@codelia/core 0.1.80 → 0.1.82

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/dist/index.js CHANGED
@@ -23,6 +23,38 @@ var buildGpt56Model = (id) => ({
23
23
  supportsFast: true
24
24
  });
25
25
  var OPENAI_MODELS = [
26
+ {
27
+ id: "gpt-6.1-sol",
28
+ provider: "openai",
29
+ contextWindow: 105e4,
30
+ maxInputTokens: 27e4,
31
+ maxOutputTokens: 128e3,
32
+ supportsFast: true
33
+ },
34
+ {
35
+ id: "gpt-6-astra",
36
+ provider: "openai",
37
+ contextWindow: 105e4,
38
+ maxInputTokens: 27e4,
39
+ maxOutputTokens: 128e3,
40
+ supportsFast: true
41
+ },
42
+ {
43
+ id: "gpt-6-sol",
44
+ provider: "openai",
45
+ contextWindow: 105e4,
46
+ maxInputTokens: 27e4,
47
+ maxOutputTokens: 128e3,
48
+ supportsFast: true
49
+ },
50
+ {
51
+ id: "gpt-6-luna",
52
+ provider: "openai",
53
+ contextWindow: 105e4,
54
+ maxInputTokens: 27e4,
55
+ maxOutputTokens: 128e3,
56
+ supportsFast: true
57
+ },
26
58
  ...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
27
59
  {
28
60
  id: "gpt-5.5",
@@ -200,7 +232,48 @@ configRegistry.registerDefaults({
200
232
  });
201
233
 
202
234
  // src/agent/agent.ts
203
- import { performance } from "perf_hooks";
235
+ import { performance as performance2 } from "perf_hooks";
236
+ import { randomUUID } from "crypto";
237
+
238
+ // src/llm/provider-status.ts
239
+ async function* withProviderStatus(operation, signal) {
240
+ const controller = new AbortController();
241
+ const abort = () => controller.abort(signal?.reason);
242
+ if (signal?.aborted) abort();
243
+ else signal?.addEventListener("abort", abort, { once: true });
244
+ const queue = [];
245
+ let wake;
246
+ let closed = false;
247
+ const iterator = operation((event) => {
248
+ if (closed || controller.signal.aborted) return;
249
+ if (queue.length < 32) queue.push(event);
250
+ wake?.();
251
+ }, controller.signal);
252
+ let pending = iterator.next();
253
+ try {
254
+ while (true) {
255
+ while (queue.length) yield queue.shift();
256
+ const changed = new Promise((resolve) => {
257
+ wake = () => resolve(void 0);
258
+ });
259
+ const result = await Promise.race([pending, changed]);
260
+ wake = void 0;
261
+ if (!result) continue;
262
+ while (queue.length) yield queue.shift();
263
+ if (result.done) return result.value;
264
+ yield result.value;
265
+ pending = iterator.next();
266
+ }
267
+ } finally {
268
+ closed = true;
269
+ controller.abort();
270
+ signal?.removeEventListener("abort", abort);
271
+ void pending.catch(() => {
272
+ });
273
+ void iterator.return(void 0).catch(() => {
274
+ });
275
+ }
276
+ }
204
277
 
205
278
  // src/content/stringify.ts
206
279
  var stringifyUnknown = (value) => {
@@ -214,6 +287,9 @@ var stringifyPart = (part, options) => {
214
287
  if (part.type === "text") {
215
288
  return part.text;
216
289
  }
290
+ if (part.type === "image_ref") {
291
+ return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
292
+ }
217
293
  if (part.type === "image_url") {
218
294
  if (options.mode === "log") {
219
295
  return `[image:${part.image_url.media_type ?? "unknown"}]`;
@@ -289,6 +365,10 @@ var MessageHistoryAdapter = class {
289
365
  }
290
366
  };
291
367
 
368
+ // src/llm/openai/history.ts
369
+ var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
370
+ };
371
+
292
372
  // src/llm/failures.ts
293
373
  var ProviderFailureError = class extends Error {
294
374
  failure;
@@ -310,8 +390,8 @@ var ProviderTimeoutError = class extends Error {
310
390
  };
311
391
  var isProviderFailureError = (error) => error instanceof ProviderFailureError;
312
392
  var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
313
- var readString = (record, key) => {
314
- const value = record?.[key];
393
+ var readString = (record3, key) => {
394
+ const value = record3?.[key];
315
395
  return typeof value === "string" && value.length > 0 ? value : void 0;
316
396
  };
317
397
  var readStatus = (error) => {
@@ -322,9 +402,9 @@ var readHeader = (headers, name) => {
322
402
  if (headers instanceof Headers) {
323
403
  return headers.get(name);
324
404
  }
325
- const record = asRecord(headers);
326
- if (!record) return null;
327
- const direct = record[name] ?? record[name.toLowerCase()];
405
+ const record3 = asRecord(headers);
406
+ if (!record3) return null;
407
+ const direct = record3[name] ?? record3[name.toLowerCase()];
328
408
  return typeof direct === "string" ? direct : null;
329
409
  };
330
410
  var parsePositiveNumber = (value) => {
@@ -380,7 +460,7 @@ var PROVIDER_LABELS = {
380
460
  xai: "xAI"
381
461
  };
382
462
  var safeProviderMessage = (provider, kind) => {
383
- const label = PROVIDER_LABELS[provider];
463
+ const label = PROVIDER_LABELS[provider] ?? provider;
384
464
  switch (kind) {
385
465
  case "hard_quota":
386
466
  return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
@@ -712,10 +792,6 @@ async function* invokeWithRetry({
712
792
  }
713
793
  }
714
794
 
715
- // src/llm/openai/history.ts
716
- var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
717
- };
718
-
719
795
  // src/models/anthropic.ts
720
796
  var ANTHROPIC_DEFAULT_MODEL = "claude-sonnet-4-5";
721
797
  var ANTHROPIC_MODELS = [
@@ -724,6 +800,28 @@ var ANTHROPIC_MODELS = [
724
800
  provider: "anthropic",
725
801
  aliases: ["default"]
726
802
  },
803
+ {
804
+ id: "claude-fable-5-1",
805
+ provider: "anthropic",
806
+ contextWindow: 1e6,
807
+ maxInputTokens: 1e6,
808
+ maxOutputTokens: 128e3
809
+ },
810
+ {
811
+ id: "claude-opus-5-5",
812
+ provider: "anthropic",
813
+ contextWindow: 1e6,
814
+ maxInputTokens: 1e6,
815
+ maxOutputTokens: 128e3,
816
+ supportsFast: true
817
+ },
818
+ {
819
+ id: "claude-sonnet-5",
820
+ provider: "anthropic",
821
+ contextWindow: 1e6,
822
+ maxInputTokens: 1e6,
823
+ maxOutputTokens: 128e3
824
+ },
727
825
  {
728
826
  id: "claude-fable-5",
729
827
  provider: "anthropic",
@@ -753,12 +851,12 @@ var ANTHROPIC_MODELS = [
753
851
  contextWindow: 1e6,
754
852
  maxInputTokens: 1e6,
755
853
  maxOutputTokens: 128e3,
756
- supportsFast: true
854
+ supportsFast: false
757
855
  },
758
856
  {
759
857
  id: "claude-opus-4-6",
760
858
  provider: "anthropic",
761
- supportsFast: true
859
+ supportsFast: false
762
860
  },
763
861
  {
764
862
  id: "claude-opus-4-5",
@@ -839,6 +937,7 @@ function createModelRegistry(specs) {
839
937
  function registerModels(registry, specs) {
840
938
  for (const spec of specs) {
841
939
  registry.modelsById[spec.id] = spec;
940
+ registry.aliasesByProvider[spec.provider] ??= {};
842
941
  const aliasBucket = registry.aliasesByProvider[spec.provider];
843
942
  for (const alias of spec.aliases ?? []) {
844
943
  aliasBucket[alias] = spec.id;
@@ -847,11 +946,11 @@ function registerModels(registry, specs) {
847
946
  }
848
947
  function resolveModel(registry, idOrAlias, provider) {
849
948
  const direct = registry.modelsById[idOrAlias];
850
- if (direct) {
949
+ if (direct && (!provider || direct.provider === provider)) {
851
950
  return direct;
852
951
  }
853
952
  if (provider) {
854
- const aliasId = registry.aliasesByProvider[provider][idOrAlias];
953
+ const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
855
954
  return aliasId ? registry.modelsById[aliasId] : void 0;
856
955
  }
857
956
  let resolved;
@@ -886,15 +985,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
886
985
  return spec?.supportsFast === true;
887
986
  }
888
987
  function cloneAliases(aliasesByProvider) {
889
- return {
890
- openai: { ...aliasesByProvider.openai },
891
- anthropic: { ...aliasesByProvider.anthropic },
892
- openrouter: { ...aliasesByProvider.openrouter },
893
- google: { ...aliasesByProvider.google },
894
- moonshot: { ...aliasesByProvider.moonshot },
895
- zai: { ...aliasesByProvider.zai },
896
- xai: { ...aliasesByProvider.xai }
897
- };
988
+ return Object.fromEntries(
989
+ Object.entries(aliasesByProvider).map(([provider, aliases]) => [
990
+ provider,
991
+ { ...aliases }
992
+ ])
993
+ );
898
994
  }
899
995
  function applyModelMetadata(registry, index) {
900
996
  const next = {
@@ -987,6 +1083,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
987
1083
  ...XAI_MODELS
988
1084
  ]);
989
1085
 
1086
+ // src/content/image-references.ts
1087
+ var REGISTRY = "[codelia.image.artifacts]";
1088
+ function isImageRegistry(message) {
1089
+ return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
1090
+ }
1091
+ function imageReferenceRegistry(messages) {
1092
+ const refs = /* @__PURE__ */ new Map();
1093
+ for (const message of messages) {
1094
+ if (!("content" in message) || !Array.isArray(message.content)) continue;
1095
+ for (const part of message.content)
1096
+ if (part.type === "image_ref") {
1097
+ refs.delete(part.image_ref.artifact_id);
1098
+ refs.set(part.image_ref.artifact_id, part);
1099
+ }
1100
+ }
1101
+ const recent = [...refs.values()].slice(-16);
1102
+ return recent.length ? {
1103
+ role: "user",
1104
+ content: [
1105
+ {
1106
+ type: "text",
1107
+ text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
1108
+ `
1109
+ },
1110
+ ...recent
1111
+ ]
1112
+ } : null;
1113
+ }
1114
+ function describeImageReferences(messages) {
1115
+ return messages.map((message) => {
1116
+ if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
1117
+ return message;
1118
+ const content = message.content.map(
1119
+ (part) => part.type === "image_ref" ? {
1120
+ type: "text",
1121
+ text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
1122
+ } : part
1123
+ );
1124
+ return { ...message, content };
1125
+ });
1126
+ }
1127
+
990
1128
  // src/services/compaction/service.ts
991
1129
  var DEFAULT_THRESHOLD_RATIO = 0.85;
992
1130
  var DEFAULT_RETAIN_LAST_TURNS = 1;
@@ -1001,14 +1139,14 @@ var CompactionService = class _CompactionService {
1001
1139
  this.config = _CompactionService.normalizeConfig(config);
1002
1140
  this.modelRegistry = deps.modelRegistry;
1003
1141
  }
1004
- async shouldCompact(llm, usage) {
1142
+ async shouldCompact(llm, usage, estimatedInputTokens) {
1005
1143
  if (!this.config.enabled) {
1006
1144
  return false;
1007
1145
  }
1008
1146
  if (!this.config.auto) {
1009
1147
  return false;
1010
1148
  }
1011
- if (!usage) {
1149
+ if (!usage && estimatedInputTokens === void 0) {
1012
1150
  return false;
1013
1151
  }
1014
1152
  let contextLimit;
@@ -1018,7 +1156,7 @@ var CompactionService = class _CompactionService {
1018
1156
  return false;
1019
1157
  }
1020
1158
  const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
1021
- return usage.total_tokens >= threshold;
1159
+ return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
1022
1160
  }
1023
1161
  async compact(llm, messages, options) {
1024
1162
  if (!this.config.enabled) {
@@ -1045,7 +1183,10 @@ var CompactionService = class _CompactionService {
1045
1183
  try {
1046
1184
  response = await llm.ainvoke(
1047
1185
  {
1048
- messages: [...preparedMessages, interruptMessage],
1186
+ messages: describeImageReferences([
1187
+ ...preparedMessages,
1188
+ interruptMessage
1189
+ ]),
1049
1190
  tools: null,
1050
1191
  toolChoice: "none",
1051
1192
  ...options?.signal ? { signal: options.signal } : {},
@@ -1155,7 +1296,7 @@ var CompactionService = class _CompactionService {
1155
1296
  );
1156
1297
  const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
1157
1298
  const conversationMessages = nonSystemMessages.filter(
1158
- (message) => !isCompactionMemoryMessage(message)
1299
+ (message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
1159
1300
  );
1160
1301
  const tail = this.normalizeRetainedTail(
1161
1302
  this.getLastTurns(conversationMessages, this.config.retainLastTurns)
@@ -1173,6 +1314,8 @@ var CompactionService = class _CompactionService {
1173
1314
  content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
1174
1315
  });
1175
1316
  }
1317
+ const imageRegistry = imageReferenceRegistry(messages);
1318
+ if (imageRegistry) compacted.push(imageRegistry);
1176
1319
  compacted.push(...tail);
1177
1320
  return compacted;
1178
1321
  }
@@ -1234,7 +1377,7 @@ var CompactionService = class _CompactionService {
1234
1377
  return messages.slice(startIndex);
1235
1378
  }
1236
1379
  async resolveContextLimit(llm, usage) {
1237
- const modelId = usage.model ?? llm.model;
1380
+ const modelId = usage?.model ?? llm.model;
1238
1381
  const modelSpec = this.resolveModelSpecWithSnapshotFallback(
1239
1382
  llm.provider,
1240
1383
  modelId
@@ -1602,6 +1745,239 @@ var TokenUsageService = class {
1602
1745
  }
1603
1746
  };
1604
1747
 
1748
+ // src/agent/image-context.ts
1749
+ import { imageSize } from "image-size";
1750
+
1751
+ // src/llm/image-policy.ts
1752
+ function estimateImageTokens(provider, model, image) {
1753
+ let name = model.toLowerCase();
1754
+ if (provider === "openrouter") {
1755
+ if (name.startsWith("openai/")) provider = "openai";
1756
+ else if (name.startsWith("anthropic/")) provider = "anthropic";
1757
+ name = name.slice(name.indexOf("/") + 1);
1758
+ }
1759
+ const width = image.width;
1760
+ const height = image.height;
1761
+ const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
1762
+ const patches = (size, edge, budget, multiplier = 1) => {
1763
+ if (!dimensionsKnown)
1764
+ return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
1765
+ const scale = Math.min(1, edge / Math.max(width, height));
1766
+ return {
1767
+ tokens: Math.ceil(
1768
+ Math.min(
1769
+ budget,
1770
+ Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
1771
+ ) * multiplier
1772
+ ),
1773
+ method: "patch"
1774
+ };
1775
+ };
1776
+ if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
1777
+ name
1778
+ )) {
1779
+ const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
1780
+ name
1781
+ );
1782
+ return patches(
1783
+ 28,
1784
+ highResolution ? 2576 : 1568,
1785
+ highResolution ? 4784 : 1568
1786
+ );
1787
+ }
1788
+ if (provider === "openai") {
1789
+ if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
1790
+ return patches(32, 512, 256, 1.2);
1791
+ if (/^gpt-6-astra(-|$)/.test(name))
1792
+ return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
1793
+ if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
1794
+ return patches(
1795
+ 32,
1796
+ image.detail === "high" ? 2048 : 65535,
1797
+ image.detail === "high" ? 2500 : 3e4,
1798
+ 1.2
1799
+ );
1800
+ if (/^gpt-5\.5(-|$)/.test(name))
1801
+ return patches(
1802
+ 32,
1803
+ image.detail === "high" ? 2048 : 6e3,
1804
+ image.detail === "high" ? 2500 : 1e4,
1805
+ 1.2
1806
+ );
1807
+ if (/^gpt-5\.4(-|$)/.test(name))
1808
+ return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
1809
+ if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
1810
+ if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
1811
+ if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
1812
+ const mini = name.startsWith("gpt-4o-mini");
1813
+ const base = mini ? 2833 : 85;
1814
+ const tile = mini ? 5667 : 170;
1815
+ if (image.detail === "low") return { tokens: base, method: "tile" };
1816
+ if (!dimensionsKnown)
1817
+ return { tokens: base + tile * 8, method: "fallback" };
1818
+ const fit = Math.min(1, 2048 / Math.max(width, height));
1819
+ const shortFit = 768 / (Math.min(width, height) * fit);
1820
+ return {
1821
+ tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
1822
+ method: "tile"
1823
+ };
1824
+ }
1825
+ }
1826
+ return { tokens: 1e4, method: "fallback" };
1827
+ }
1828
+ function imagePayloadLimit(provider) {
1829
+ if (provider === "anthropic") return 32e6;
1830
+ if (provider === "openai") return 512e6;
1831
+ return void 0;
1832
+ }
1833
+
1834
+ // src/agent/image-context.ts
1835
+ function estimateImageContext(input, llm, resolveReferences = true) {
1836
+ let imageTokens = 0;
1837
+ let imageCount = 0;
1838
+ let fallbackCount = 0;
1839
+ let imageBytes = 0;
1840
+ const account = (image) => {
1841
+ const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
1842
+ if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
1843
+ throw new Error("Invalid model image-token estimate");
1844
+ imageTokens += estimate.tokens;
1845
+ imageCount++;
1846
+ if (estimate.method === "fallback") fallbackCount++;
1847
+ };
1848
+ const messages = input.messages.map((message) => {
1849
+ if (!Array.isArray(message.content)) return message;
1850
+ const registry = isImageRegistry(message);
1851
+ return {
1852
+ ...message,
1853
+ content: message.content.map((part) => {
1854
+ if (part.type === "image_ref") {
1855
+ if (!registry && resolveReferences) {
1856
+ account({
1857
+ width: part.image_ref.width,
1858
+ height: part.image_ref.height,
1859
+ detail: part.detail
1860
+ });
1861
+ imageBytes += 4 * Math.ceil(
1862
+ (part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
1863
+ ) + 64;
1864
+ }
1865
+ return {
1866
+ type: "text",
1867
+ text: `[Image ${part.image_ref.artifact_id}]`
1868
+ };
1869
+ }
1870
+ if (part.type === "image_url") {
1871
+ let dimensions = {};
1872
+ const url = part.image_url.url;
1873
+ const comma = url.indexOf(",");
1874
+ if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
1875
+ try {
1876
+ dimensions = imageSize(
1877
+ Buffer.from(url.slice(comma + 1), "base64")
1878
+ );
1879
+ } catch {
1880
+ dimensions = {};
1881
+ }
1882
+ }
1883
+ account({ ...dimensions, detail: part.image_url.detail });
1884
+ imageBytes += Buffer.byteLength(part.image_url.url);
1885
+ return { type: "text", text: "[Image]" };
1886
+ }
1887
+ if (part.type === "document")
1888
+ return {
1889
+ type: "text",
1890
+ text: "[Document: token estimate unavailable]"
1891
+ };
1892
+ return part;
1893
+ })
1894
+ };
1895
+ });
1896
+ const textBytes = Buffer.byteLength(
1897
+ JSON.stringify({
1898
+ messages,
1899
+ tools: input.tools ?? null,
1900
+ tool_choice: input.toolChoice
1901
+ })
1902
+ );
1903
+ const textTokens = Math.ceil(textBytes / 3);
1904
+ return {
1905
+ text_tokens: textTokens,
1906
+ image_tokens: imageTokens,
1907
+ total_tokens: textTokens + imageTokens,
1908
+ image_count: imageCount,
1909
+ fallback_image_count: fallbackCount,
1910
+ encoded_image_bytes: imageBytes,
1911
+ estimated_request_bytes: textBytes + imageBytes
1912
+ };
1913
+ }
1914
+ function validateImagePayload(estimate, llm) {
1915
+ const limit = imagePayloadLimit(llm.provider);
1916
+ if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
1917
+ throw new Error(
1918
+ `Image-bearing request exceeds the ${llm.provider} transport payload budget (${limit} bytes), not the context-token budget. Use smaller attachments in a new conversation or explicitly reorganize this history. Originals are unchanged; no model request was sent.`
1919
+ );
1920
+ }
1921
+
1922
+ // src/agent/image-input.ts
1923
+ var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
1924
+ async function materializeImageReferences(messages, resolve, signal) {
1925
+ signal?.throwIfAborted();
1926
+ if (resolve) {
1927
+ for (const message of messages) {
1928
+ if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
1929
+ for (const part of message.content) {
1930
+ if (part.type !== "image_ref") continue;
1931
+ const size = part.image_ref.byte_size;
1932
+ if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
1933
+ throw new Error(
1934
+ "Invalid or oversized image reference; model request was not sent."
1935
+ );
1936
+ }
1937
+ }
1938
+ }
1939
+ const result = [];
1940
+ for (const message of messages) {
1941
+ if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
1942
+ result.push(message);
1943
+ continue;
1944
+ }
1945
+ const registry = isImageRegistry(message);
1946
+ const content = [];
1947
+ for (const part of message.content) {
1948
+ if (part.type !== "image_ref") {
1949
+ content.push(part);
1950
+ continue;
1951
+ }
1952
+ signal?.throwIfAborted();
1953
+ if (!registry && resolve) {
1954
+ try {
1955
+ const image = await resolve(part.image_ref, signal);
1956
+ content.push(
1957
+ part.detail ? {
1958
+ ...image,
1959
+ image_url: { ...image.image_url, detail: part.detail }
1960
+ } : image
1961
+ );
1962
+ signal?.throwIfAborted();
1963
+ continue;
1964
+ } catch {
1965
+ signal?.throwIfAborted();
1966
+ throw new Error(
1967
+ `Image artifact ${part.image_ref.artifact_id} or its fixed model view is unavailable or corrupt. Restore the saved bytes or compact the conversation; model request was not sent to avoid rewriting earlier image input.`
1968
+ );
1969
+ }
1970
+ }
1971
+ content.push({
1972
+ type: "text",
1973
+ text: `[Image artifact ${part.image_ref.artifact_id}: ${registry ? "compacted image registry; use image_inspect to revisit" : "image input unavailable on this connection"}. Not visually inspected.]`
1974
+ });
1975
+ }
1976
+ result.push({ ...message, content });
1977
+ }
1978
+ return result;
1979
+ }
1980
+
1605
1981
  // src/agent/model-context.ts
1606
1982
  var calculateContextLeftPercent = ({
1607
1983
  usage,
@@ -1683,16 +2059,16 @@ var collectModelOutput = (messages) => {
1683
2059
  if (message.role === "reasoning") {
1684
2060
  const raw = message.raw_item;
1685
2061
  if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
1686
- const record = raw;
1687
- const kind = record.type === "x_search_call" ? "x" : "web";
1688
- const statusRaw = record.status;
2062
+ const record3 = raw;
2063
+ const kind = record3.type === "x_search_call" ? "x" : "web";
2064
+ const statusRaw = record3.status;
1689
2065
  const status = typeof statusRaw === "string" ? statusRaw : "completed";
1690
- const action = record.action && typeof record.action === "object" ? record.action : null;
2066
+ const action = record3.action && typeof record3.action === "object" ? record3.action : null;
1691
2067
  const queries = Array.isArray(action?.queries) ? action.queries.filter(
1692
2068
  (entry) => typeof entry === "string" && entry.length > 0
1693
2069
  ) : [];
1694
2070
  const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
1695
- const explicitId = typeof record.id === "string" && record.id.length > 0 ? record.id : null;
2071
+ const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
1696
2072
  let id = explicitId;
1697
2073
  const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
1698
2074
  if (!id) {
@@ -1790,6 +2166,16 @@ var TaskComplete = class extends Error {
1790
2166
  }
1791
2167
  };
1792
2168
 
2169
+ // src/types/permissions.ts
2170
+ var ToolPermissionDenied = class extends Error {
2171
+ constructor(decision) {
2172
+ super(`Permission denied${decision.reason ? `: ${decision.reason}` : ""}`);
2173
+ this.decision = decision;
2174
+ this.name = "ToolPermissionDenied";
2175
+ }
2176
+ decision;
2177
+ };
2178
+
1793
2179
  // src/agent/tool-execution.ts
1794
2180
  var toolResultToContent = (result) => {
1795
2181
  if (result.type === "text") return result.text;
@@ -1818,6 +2204,23 @@ var createToolContext = (signal) => {
1818
2204
  now: () => /* @__PURE__ */ new Date()
1819
2205
  };
1820
2206
  };
2207
+ var permissionDeniedResult = (toolCall, decision) => {
2208
+ const toolName = toolCall.function.name;
2209
+ const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
2210
+ return {
2211
+ message: {
2212
+ role: "tool",
2213
+ tool_call_id: toolCall.id,
2214
+ tool_name: toolName,
2215
+ content: deniedContent,
2216
+ is_error: true
2217
+ },
2218
+ ...decision.stop_turn ? {
2219
+ done: true,
2220
+ finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
2221
+ } : {}
2222
+ };
2223
+ };
1821
2224
  var executeToolCall = async ({
1822
2225
  toolCall,
1823
2226
  tools,
@@ -1845,20 +2248,7 @@ var executeToolCall = async ({
1845
2248
  createToolContext(signal)
1846
2249
  );
1847
2250
  if (decision.decision === "deny") {
1848
- const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
1849
- return {
1850
- message: {
1851
- role: "tool",
1852
- tool_call_id: toolCall.id,
1853
- tool_name: toolName,
1854
- content: deniedContent,
1855
- is_error: true
1856
- },
1857
- ...decision.stop_turn ? {
1858
- done: true,
1859
- finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
1860
- } : {}
1861
- };
2251
+ return permissionDeniedResult(toolCall, decision);
1862
2252
  }
1863
2253
  } catch (error) {
1864
2254
  return {
@@ -1886,6 +2276,8 @@ var executeToolCall = async ({
1886
2276
  }
1887
2277
  };
1888
2278
  } catch (error) {
2279
+ if (error instanceof ToolPermissionDenied)
2280
+ return permissionDeniedResult(toolCall, error.decision);
1889
2281
  if (error instanceof TaskComplete) {
1890
2282
  return {
1891
2283
  message: {
@@ -1912,7 +2304,7 @@ var executeToolCall = async ({
1912
2304
 
1913
2305
  // src/agent/agent.ts
1914
2306
  var DEFAULT_MAX_ITERATIONS = 200;
1915
- var defaultMonotonicNowMs = () => performance.now();
2307
+ var defaultMonotonicNowMs = () => performance2.now();
1916
2308
  var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
1917
2309
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
1918
2310
  var createAbortError2 = () => {
@@ -1946,6 +2338,7 @@ var Agent = class {
1946
2338
  //private readonly dependencyOverrides?: DependencyOverrides;
1947
2339
  history;
1948
2340
  usageService;
2341
+ imageUsageBaseline;
1949
2342
  constructor(options) {
1950
2343
  this.llm = options.llm;
1951
2344
  this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
@@ -1998,13 +2391,15 @@ var Agent = class {
1998
2391
  }
1999
2392
  replaceHistoryMessages(messages) {
2000
2393
  this.history.replaceViewMessages(messages);
2394
+ this.imageUsageBaseline = void 0;
2001
2395
  }
2002
2396
  async *checkAndCompact(signal, options = {}) {
2003
2397
  throwIfAborted(signal);
2004
2398
  await this.trimToolOutputs();
2005
2399
  const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
2006
2400
  this.llm,
2007
- this.usageService.getLastUsage()
2401
+ this.usageService.getLastUsage(),
2402
+ options.estimatedInputTokens
2008
2403
  );
2009
2404
  if (shouldCompact && this.compactionService) {
2010
2405
  throwIfAborted(signal);
@@ -2025,6 +2420,7 @@ var Agent = class {
2025
2420
  this.usageService.updateUsageSummary(usage);
2026
2421
  if (compacted && compactedMessages) {
2027
2422
  this.history.replaceViewMessages(compactedMessages);
2423
+ this.imageUsageBaseline = void 0;
2028
2424
  }
2029
2425
  if (compacted || options.force) {
2030
2426
  await this.llm.onHistoryCompacted?.(invokeContext);
@@ -2083,9 +2479,13 @@ var Agent = class {
2083
2479
  const runId = session?.run_id?.trim();
2084
2480
  return runId && runId.length > 0 ? runId : void 0;
2085
2481
  }
2086
- buildInvokeContext(session) {
2482
+ buildInvokeContext(session, turnKey) {
2087
2483
  const sessionKey = this.resolveSessionKey(session);
2088
- return sessionKey ? { sessionKey } : void 0;
2484
+ const turn = turnKey ?? session?.run_id;
2485
+ return sessionKey || turn ? {
2486
+ ...sessionKey ? { sessionKey } : {},
2487
+ ...turn ? { turnKey: turn } : {}
2488
+ } : void 0;
2089
2489
  }
2090
2490
  recordLlmResponse(session, seq, response) {
2091
2491
  if (!session || seq === null) return;
@@ -2096,6 +2496,7 @@ var Agent = class {
2096
2496
  seq,
2097
2497
  output: {
2098
2498
  messages: response.messages,
2499
+ ...response.timing ? { timing: response.timing } : {},
2099
2500
  usage: response.usage ?? null,
2100
2501
  stop_reason: response.stop_reason ?? null,
2101
2502
  provider_meta: response.provider_meta ?? null
@@ -2103,19 +2504,43 @@ var Agent = class {
2103
2504
  });
2104
2505
  }
2105
2506
  async *invokeModelWithRetry(input, context, signal) {
2106
- return yield* invokeWithRetry({
2107
- operation: (attemptSignal) => this.llm.ainvoke(
2108
- {
2109
- ...input,
2110
- ...attemptSignal ? { signal: attemptSignal } : {}
2111
- },
2112
- context
2113
- ),
2114
- classifyFailure: this.llm.classifyFailure,
2115
- policy: this.llmRetryPolicy,
2116
- ...signal ? { signal } : {},
2117
- dependencies: this.llmRetryDependencies
2118
- });
2507
+ const estimate = estimateImageContext(
2508
+ input,
2509
+ this.llm,
2510
+ Boolean(this.services.resolveImage)
2511
+ );
2512
+ validateImagePayload(estimate, this.llm);
2513
+ const messages = await materializeImageReferences(
2514
+ input.messages,
2515
+ this.services.resolveImage,
2516
+ signal
2517
+ );
2518
+ const response = yield* withProviderStatus(
2519
+ (onProviderStatus, progressSignal) => invokeWithRetry({
2520
+ operation: (attemptSignal) => this.llm.ainvoke(
2521
+ {
2522
+ ...input,
2523
+ messages,
2524
+ ...attemptSignal ? { signal: attemptSignal } : {}
2525
+ },
2526
+ { ...context, onProviderStatus }
2527
+ ),
2528
+ classifyFailure: this.llm.classifyFailure,
2529
+ policy: resolveLlmRetryPolicy({
2530
+ ...this.llmRetryPolicy,
2531
+ ...this.llm.retryPolicy
2532
+ }),
2533
+ signal: progressSignal,
2534
+ dependencies: this.llmRetryDependencies
2535
+ }),
2536
+ signal
2537
+ );
2538
+ this.imageUsageBaseline = response.usage ? {
2539
+ messages: input.messages.slice(),
2540
+ estimated: estimate.total_tokens,
2541
+ observed: response.usage.input_tokens
2542
+ } : void 0;
2543
+ return response;
2119
2544
  }
2120
2545
  async run(message, options = {}) {
2121
2546
  let finalResponse = "";
@@ -2148,19 +2573,43 @@ var Agent = class {
2148
2573
  return;
2149
2574
  }
2150
2575
  this.history.enqueueUserMessage(message);
2576
+ const receiveMessages = async () => {
2577
+ const messages = await options.pollMessages?.() ?? [];
2578
+ for (const content of messages) this.history.enqueueUserMessage(content);
2579
+ return messages;
2580
+ };
2581
+ const turnKey = session?.run_id ?? randomUUID();
2151
2582
  let iterations = 0;
2152
2583
  const runTools = [...this.tools, ...options.tools ?? []];
2153
2584
  const runToolChoice = options.toolChoice ?? this.toolChoice;
2154
2585
  while (iterations < this.maxIterations) {
2155
2586
  iterations++;
2156
2587
  throwIfAborted(signal);
2588
+ for (const content of await receiveMessages())
2589
+ yield { type: "hidden_user_message", content };
2157
2590
  await this.trimToolOutputs();
2158
2591
  throwIfAborted(signal);
2159
- const invokeInput = this.history.prepareInvokeInput({
2592
+ let invokeInput = this.history.prepareInvokeInput({
2160
2593
  tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
2161
2594
  toolChoice: runToolChoice
2162
2595
  });
2163
- const invokeContext = this.buildInvokeContext(session);
2596
+ const imageEstimate = estimateImageContext(
2597
+ invokeInput,
2598
+ this.llm,
2599
+ Boolean(this.services.resolveImage)
2600
+ );
2601
+ if (imageEstimate.image_count > 0) {
2602
+ const baseline = this.imageUsageBaseline;
2603
+ const estimatedInputTokens = baseline && baseline.messages.every(
2604
+ (message2, index) => invokeInput.messages[index] === message2
2605
+ ) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
2606
+ yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
2607
+ invokeInput = this.history.prepareInvokeInput({
2608
+ tools: invokeInput.tools,
2609
+ toolChoice: runToolChoice
2610
+ });
2611
+ }
2612
+ const invokeContext = this.buildInvokeContext(session, turnKey);
2164
2613
  const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
2165
2614
  const response = yield* this.invokeModelWithRetry(
2166
2615
  invokeInput,
@@ -2230,6 +2679,10 @@ var Agent = class {
2230
2679
  if (!hasToolCalls) {
2231
2680
  if (!this.requireDoneTool) {
2232
2681
  yield* this.checkAndCompact(signal, { session });
2682
+ const incoming = await receiveMessages();
2683
+ for (const content of incoming)
2684
+ yield { type: "hidden_user_message", content };
2685
+ if (incoming.length) continue;
2233
2686
  const finalText = assistantTexts.join("\n").trim();
2234
2687
  const finalResponseEvent2 = {
2235
2688
  type: "final",
@@ -2380,15 +2833,21 @@ var Agent = class {
2380
2833
  }
2381
2834
  yield* this.checkAndCompact(signal, { session });
2382
2835
  }
2383
- const finalResponse = await this.generateFinalResponse(session, signal);
2836
+ if (signal?.aborted) throw createAbortError2();
2837
+ const finalResponse = await this.generateFinalResponse(
2838
+ session,
2839
+ signal,
2840
+ turnKey
2841
+ );
2384
2842
  const finalResponseEvent = {
2385
2843
  type: "final",
2844
+ termination_reason: "max_steps",
2386
2845
  content: finalResponse
2387
2846
  };
2388
2847
  yield finalResponseEvent;
2389
2848
  return;
2390
2849
  }
2391
- async generateFinalResponse(session, signal) {
2850
+ async generateFinalResponse(session, signal, turnKey) {
2392
2851
  const summaryMessage = {
2393
2852
  role: "user",
2394
2853
  content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
@@ -2401,11 +2860,24 @@ var Agent = class {
2401
2860
  // no tools are allowed at this point
2402
2861
  toolChoice: "none"
2403
2862
  };
2404
- const invokeContext = this.buildInvokeContext(session);
2863
+ const invokeContext = this.buildInvokeContext(session, turnKey);
2405
2864
  const seq = this.recordLlmRequest(session, input, invokeContext);
2865
+ validateImagePayload(
2866
+ estimateImageContext(
2867
+ input,
2868
+ this.llm,
2869
+ Boolean(this.services.resolveImage)
2870
+ ),
2871
+ this.llm
2872
+ );
2406
2873
  const summary = await this.llm.ainvoke(
2407
2874
  {
2408
2875
  ...input,
2876
+ messages: await materializeImageReferences(
2877
+ input.messages,
2878
+ this.services.resolveImage,
2879
+ signal
2880
+ ),
2409
2881
  ...signal ? { signal } : {}
2410
2882
  },
2411
2883
  invokeContext
@@ -2426,6 +2898,88 @@ ${assistantTexts.join("\n").trim()}`;
2426
2898
  }
2427
2899
  };
2428
2900
 
2901
+ // src/llm/stream-timing.ts
2902
+ var record = (value) => value !== null && typeof value === "object" ? value : void 0;
2903
+ var nonempty = (value) => typeof value === "string" && value.length > 0;
2904
+ var responseOutputDeltas = /* @__PURE__ */ new Set([
2905
+ "response.output_text.delta",
2906
+ "response.refusal.delta",
2907
+ "response.function_call_arguments.delta",
2908
+ "response.custom_tool_call_input.delta",
2909
+ "response.reasoning_text.delta",
2910
+ "response.reasoning_summary_text.delta"
2911
+ ]);
2912
+ var LlmStreamTiming = class {
2913
+ constructor(nowMs = () => performance.now()) {
2914
+ this.nowMs = nowMs;
2915
+ this.startedAt = nowMs();
2916
+ }
2917
+ nowMs;
2918
+ startedAt;
2919
+ firstOutputAt;
2920
+ reasoningStartedAt;
2921
+ completedAt;
2922
+ observeOutput() {
2923
+ if (this.completedAt === void 0 && this.firstOutputAt === void 0)
2924
+ this.firstOutputAt = this.nowMs();
2925
+ }
2926
+ complete() {
2927
+ this.completedAt ??= this.nowMs();
2928
+ }
2929
+ observeResponsesEvent(event) {
2930
+ const value = record(event);
2931
+ if (!value) return;
2932
+ if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
2933
+ this.reasoningStartedAt ??= this.nowMs();
2934
+ if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
2935
+ this.observeOutput();
2936
+ if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
2937
+ this.complete();
2938
+ }
2939
+ observeChatChunk(chunk) {
2940
+ const choices = record(chunk)?.choices;
2941
+ if (!Array.isArray(choices)) return;
2942
+ for (const choice of choices) {
2943
+ const delta = record(record(choice)?.delta);
2944
+ if (!delta) continue;
2945
+ if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
2946
+ (tool) => nonempty(record(record(tool)?.function)?.arguments)
2947
+ ))
2948
+ this.observeOutput();
2949
+ }
2950
+ }
2951
+ observeAnthropicEvent(event) {
2952
+ const value = record(event);
2953
+ if (!value) return;
2954
+ const delta = record(value.delta);
2955
+ if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
2956
+ this.observeOutput();
2957
+ if (value.type === "message_stop") this.complete();
2958
+ }
2959
+ finish() {
2960
+ this.complete();
2961
+ if (this.firstOutputAt === void 0) return void 0;
2962
+ const first = this.firstOutputAt - this.startedAt;
2963
+ const start = Math.min(
2964
+ this.firstOutputAt,
2965
+ this.reasoningStartedAt ?? this.firstOutputAt
2966
+ );
2967
+ const generation = this.completedAt - start;
2968
+ if (![first, generation, start - this.startedAt].every(
2969
+ (ms) => Number.isFinite(ms) && ms >= 0
2970
+ ))
2971
+ return void 0;
2972
+ return {
2973
+ time_to_first_token_ms: first,
2974
+ generation_duration_ms: generation,
2975
+ ...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
2976
+ generation_start_ms: start - this.startedAt,
2977
+ generation_start_source: "reasoning_item"
2978
+ } : {}
2979
+ };
2980
+ }
2981
+ };
2982
+
2429
2983
  // src/llm/anthropic/chat.ts
2430
2984
  import { createHash } from "crypto";
2431
2985
  import Anthropic from "@anthropic-ai/sdk";
@@ -2552,6 +3106,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
2552
3106
  };
2553
3107
 
2554
3108
  // src/types/llm/guards.ts
3109
+ import { isImageModelView } from "@codelia/shared-types";
2555
3110
  var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
2556
3111
  function isTextPart(value) {
2557
3112
  if (!value || typeof value !== "object") return false;
@@ -2580,7 +3135,19 @@ function isOtherPart(value) {
2580
3135
  return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
2581
3136
  }
2582
3137
  function isContentPart(value) {
2583
- return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
3138
+ return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
3139
+ }
3140
+ function isImageRefPart(value) {
3141
+ if (!value || typeof value !== "object") return false;
3142
+ const v = value;
3143
+ if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
3144
+ return false;
3145
+ const r = v.image_ref;
3146
+ return (r.model_view === void 0 || isImageModelView(r.model_view)) && typeof r.artifact_id === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(r.artifact_id) && typeof r.sha256 === "string" && /^[0-9a-f]{64}$/.test(r.sha256) && ["image/png", "image/jpeg", "image/webp", "image/gif"].includes(
3147
+ String(r.media_type)
3148
+ ) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
3149
+ (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
3150
+ ) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
2584
3151
  }
2585
3152
  function isToolResult(value) {
2586
3153
  if (!value || typeof value !== "object") return false;
@@ -2684,6 +3251,15 @@ var toContentBlocks = (content) => {
2684
3251
  }
2685
3252
  };
2686
3253
  }
3254
+ if (URL.canParse(part.image_url.url)) {
3255
+ const url = new URL(part.image_url.url);
3256
+ if (url.protocol === "https:" || url.protocol === "http:") {
3257
+ return {
3258
+ type: "image",
3259
+ source: { type: "url", url: part.image_url.url }
3260
+ };
3261
+ }
3262
+ }
2687
3263
  return toTextBlock(part.image_url.url);
2688
3264
  }
2689
3265
  case "document":
@@ -3101,20 +3677,27 @@ var ChatAnthropic = class {
3101
3677
  const debugSeq = this.nextDebugInvokeSeq();
3102
3678
  await this.debugRequestIfEnabled(request, debugSeq);
3103
3679
  const requestOptions = signal ? { signal } : void 0;
3104
- const response = this.fastMode ? await this.client.beta.messages.create(
3680
+ const timing = new LlmStreamTiming();
3681
+ const stream = this.fastMode ? this.client.beta.messages.stream(
3105
3682
  request,
3106
3683
  requestOptions
3107
- ) : await this.client.messages.create(
3684
+ ) : this.client.messages.stream(
3108
3685
  request,
3109
3686
  requestOptions
3110
3687
  );
3688
+ for await (const event of stream) timing.observeAnthropicEvent(event);
3689
+ const response = await stream.finalMessage();
3690
+ const measuredTiming = timing.finish();
3111
3691
  await this.debugResponseIfEnabled(response, debugSeq);
3112
- return toChatInvokeCompletion(response, {
3113
- reasoning_requested: this.reasoningLevelMeta.requested,
3114
- reasoning_applied: this.reasoningLevelMeta.applied,
3115
- reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
3116
- reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
3117
- });
3692
+ return {
3693
+ ...toChatInvokeCompletion(response, {
3694
+ reasoning_requested: this.reasoningLevelMeta.requested,
3695
+ reasoning_applied: this.reasoningLevelMeta.applied,
3696
+ reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
3697
+ reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
3698
+ }),
3699
+ ...measuredTiming ? { timing: measuredTiming } : {}
3700
+ };
3118
3701
  }
3119
3702
  nextDebugInvokeSeq() {
3120
3703
  const seq = this.debugInvokeSeq + 1;
@@ -3602,6 +4185,7 @@ var ChatMoonshot = class {
3602
4185
  const seq = this.nextDebugInvokeSeq();
3603
4186
  await this.debugRequestIfEnabled(request, seq);
3604
4187
  const client = new OpenAI({ apiKey: this.apiKey, ...this.clientOptions });
4188
+ const timing = new LlmStreamTiming();
3605
4189
  const accumulator = createMoonshotStreamAccumulator();
3606
4190
  try {
3607
4191
  const stream = await client.chat.completions.create(
@@ -3609,6 +4193,7 @@ var ChatMoonshot = class {
3609
4193
  { signal: input.signal }
3610
4194
  );
3611
4195
  for await (const chunk of stream) {
4196
+ timing.observeChatChunk(chunk);
3612
4197
  appendMoonshotChatCompletionChunk(
3613
4198
  accumulator,
3614
4199
  chunk
@@ -3621,11 +4206,15 @@ var ChatMoonshot = class {
3621
4206
  { cause: error }
3622
4207
  );
3623
4208
  }
4209
+ const measuredTiming = timing.finish();
3624
4210
  await this.debugResponseIfEnabled(accumulator, seq);
3625
- return toMoonshotChatInvokeCompletion(accumulator, {
3626
- reasoningRequested: this.reasoningLevelRequested,
3627
- reasoningFallback: this.reasoningLevelRequested !== "max"
3628
- });
4211
+ return {
4212
+ ...toMoonshotChatInvokeCompletion(accumulator, {
4213
+ reasoningRequested: this.reasoningLevelRequested,
4214
+ reasoningFallback: this.reasoningLevelRequested !== "max"
4215
+ }),
4216
+ ...measuredTiming ? { timing: measuredTiming } : {}
4217
+ };
3629
4218
  }
3630
4219
  nextDebugInvokeSeq() {
3631
4220
  this.debugInvokeSeq += 1;
@@ -3691,9 +4280,183 @@ var ChatMoonshot = class {
3691
4280
  };
3692
4281
 
3693
4282
  // src/llm/openai/chat.ts
3694
- import { createHash as createHash3 } from "crypto";
4283
+ import { createHash as createHash4 } from "crypto";
4284
+ import OpenAI3 from "openai";
4285
+
4286
+ // src/llm/openai/http-transport.ts
3695
4287
  import OpenAI2 from "openai";
3696
4288
 
4289
+ // src/llm/openai/codex-metadata.ts
4290
+ import { createHash as createHash3 } from "crypto";
4291
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4292
+ var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
4293
+ var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
4294
+ var headerValue = (headers, name) => {
4295
+ const entries = record2(headers);
4296
+ const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
4297
+ return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
4298
+ };
4299
+ var isCodexBackend = (baseURL) => {
4300
+ try {
4301
+ const url = new URL(baseURL);
4302
+ return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
4303
+ } catch {
4304
+ return false;
4305
+ }
4306
+ };
4307
+ var CodexTurnState = class {
4308
+ owner;
4309
+ value;
4310
+ invalidated = false;
4311
+ bindAuth(headers) {
4312
+ const authorization = headers.get("authorization") ?? "";
4313
+ let identity = authorization;
4314
+ try {
4315
+ const claims = record2(
4316
+ JSON.parse(
4317
+ Buffer.from(
4318
+ authorization.replace(/^Bearer /i, "").split(".")[1],
4319
+ "base64url"
4320
+ ).toString("utf8")
4321
+ )
4322
+ );
4323
+ if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
4324
+ const account = record2(
4325
+ claims["https://api.openai.com/auth"]
4326
+ )?.chatgpt_account_id;
4327
+ identity = JSON.stringify([
4328
+ claims.iss,
4329
+ claims.sub,
4330
+ typeof claims.client_id === "string" ? claims.client_id : null,
4331
+ typeof account === "string" ? account : null
4332
+ ]);
4333
+ }
4334
+ } catch {
4335
+ }
4336
+ const owner = createHash3("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
4337
+ const changed = this.owner !== void 0 && this.owner !== owner;
4338
+ if (changed) {
4339
+ this.value = void 0;
4340
+ this.invalidated = true;
4341
+ }
4342
+ this.owner = owner;
4343
+ return this.invalidated;
4344
+ }
4345
+ observe(value) {
4346
+ if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
4347
+ this.value = value;
4348
+ }
4349
+ requestHeaders() {
4350
+ return this.value ? { "x-codex-turn-state": this.value } : {};
4351
+ }
4352
+ };
4353
+ var CodexMetadataCollector = class {
4354
+ constructor(routing, onStatus) {
4355
+ this.routing = routing;
4356
+ this.onStatus = onStatus;
4357
+ }
4358
+ routing;
4359
+ onStatus;
4360
+ summary = {};
4361
+ outputStarted = false;
4362
+ fallbackModel;
4363
+ verificationNotified = false;
4364
+ beginAttempt() {
4365
+ this.clearBuffering();
4366
+ for (const key of Object.keys(this.summary))
4367
+ delete this.summary[key];
4368
+ this.outputStarted = false;
4369
+ this.fallbackModel = void 0;
4370
+ }
4371
+ observeHeaders(headers) {
4372
+ this.routing?.observe(headers.get("x-codex-turn-state"));
4373
+ const model = identifier(
4374
+ headers.get("openai-model") ?? headers.get("x-openai-model")
4375
+ );
4376
+ if (model) this.summary.server_model = model;
4377
+ this.fallbackModel = identifier(
4378
+ headers.get("x-codex-safety-buffering-faster-model")
4379
+ );
4380
+ }
4381
+ observeEvent(event) {
4382
+ const value = record2(event);
4383
+ if (!value) return;
4384
+ const response = record2(value.response);
4385
+ const model = identifier(
4386
+ headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
4387
+ );
4388
+ if (model) this.summary.server_model = model;
4389
+ const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
4390
+ if (value.type === "response.metadata")
4391
+ this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
4392
+ const verifications = metadata?.openai_verification_recommendation;
4393
+ if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
4394
+ this.summary.model_verifications = ["trusted_access_for_cyber"];
4395
+ if (!this.verificationNotified) {
4396
+ this.verificationNotified = true;
4397
+ this.emit({
4398
+ type: "llm.status",
4399
+ provider: "openai",
4400
+ kind: "verification",
4401
+ verification: "trusted_access_for_cyber"
4402
+ });
4403
+ }
4404
+ }
4405
+ if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
4406
+ this.summary.moderation_metadata_present = true;
4407
+ const buffering = record2(
4408
+ value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
4409
+ );
4410
+ if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
4411
+ const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
4412
+ const wasActive = this.summary.safety_buffering?.active;
4413
+ this.summary.safety_buffering = {
4414
+ active: !this.outputStarted,
4415
+ use_case_count: buffering.use_cases.length,
4416
+ reason_count: buffering.reasons.length,
4417
+ ...faster ? { faster_model: faster } : {}
4418
+ };
4419
+ if (!this.outputStarted && !wasActive)
4420
+ this.emit({
4421
+ type: "llm.status",
4422
+ provider: "openai",
4423
+ kind: "buffering",
4424
+ active: true,
4425
+ ...faster ? { faster_model: faster } : {}
4426
+ });
4427
+ }
4428
+ if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
4429
+ this.outputStarted = true;
4430
+ this.clearBuffering();
4431
+ }
4432
+ if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
4433
+ this.clearBuffering();
4434
+ }
4435
+ finish() {
4436
+ this.clearBuffering();
4437
+ }
4438
+ snapshot() {
4439
+ return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
4440
+ }
4441
+ clearBuffering() {
4442
+ if (this.summary.safety_buffering?.active) {
4443
+ this.summary.safety_buffering.active = false;
4444
+ this.emit({
4445
+ type: "llm.status",
4446
+ provider: "openai",
4447
+ kind: "buffering",
4448
+ active: false
4449
+ });
4450
+ }
4451
+ }
4452
+ emit(event) {
4453
+ try {
4454
+ this.onStatus?.(event);
4455
+ } catch {
4456
+ }
4457
+ }
4458
+ };
4459
+
3697
4460
  // src/llm/openai/response-utils.ts
3698
4461
  var isRecord2 = (value) => typeof value === "object" && value !== null;
3699
4462
  var stringifyUnknown3 = (value) => {
@@ -3735,12 +4498,12 @@ var extractOutputText = (items) => {
3735
4498
  }
3736
4499
  return texts.join("");
3737
4500
  };
3738
- var getRecordString = (record, key) => {
3739
- const value = record[key];
4501
+ var getRecordString = (record3, key) => {
4502
+ const value = record3[key];
3740
4503
  return typeof value === "string" ? value : void 0;
3741
4504
  };
3742
- var getRecordNumber = (record, key) => {
3743
- const value = record[key];
4505
+ var getRecordNumber = (record3, key) => {
4506
+ const value = record3[key];
3744
4507
  return typeof value === "number" ? value : void 0;
3745
4508
  };
3746
4509
  var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
@@ -3750,6 +4513,10 @@ var getResponseStreamEventDebugPayload = (event) => {
3750
4513
  sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
3751
4514
  };
3752
4515
  const eventRecord = event;
4516
+ const metadata = new CodexMetadataCollector();
4517
+ metadata.observeEvent(event);
4518
+ const summary = metadata.snapshot();
4519
+ if (summary) payload.metadata_summary = summary;
3753
4520
  const outputIndex = getRecordNumber(eventRecord, "output_index");
3754
4521
  if (outputIndex !== void 0) {
3755
4522
  payload.output_index = outputIndex;
@@ -3903,6 +4670,9 @@ var OpenAiResponseAccumulator = class {
3903
4670
  terminalResponse = null;
3904
4671
  outputItems = [];
3905
4672
  observeEvent(event) {
4673
+ const type = event.type;
4674
+ if (type === "response.metadata" || type === "codex.response.metadata")
4675
+ return;
3906
4676
  switch (event.type) {
3907
4677
  case "response.created":
3908
4678
  case "response.queued":
@@ -4254,22 +5024,64 @@ var OpenAiResponseAccumulator = class {
4254
5024
  };
4255
5025
 
4256
5026
  // src/llm/openai/http-transport.ts
4257
- var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
5027
+ var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
4258
5028
  const streamRequest = {
4259
5029
  ...request,
4260
5030
  stream: true
4261
5031
  };
4262
- const stream = client.responses.stream(
4263
- streamRequest,
4264
- signal || sessionIdHeader ? {
4265
- ...signal ? { signal } : {},
4266
- ...sessionIdHeader ? {
4267
- headers: {
4268
- session_id: sessionIdHeader
5032
+ const options = signal || sessionIdHeader ? {
5033
+ ...signal ? { signal } : {},
5034
+ ...sessionIdHeader ? {
5035
+ headers: {
5036
+ session_id: sessionIdHeader
5037
+ }
5038
+ } : {}
5039
+ } : void 0;
5040
+ if (isCodexBackend(client.baseURL)) {
5041
+ codex?.metadata.beginAttempt();
5042
+ const sourceFetch = client.fetch;
5043
+ let ownershipError;
5044
+ const requestClient = codex ? client.withOptions({
5045
+ fetch: async (input, init) => {
5046
+ const headers = new Headers(init?.headers);
5047
+ if (codex.routing?.bindAuth(headers)) {
5048
+ ownershipError = createProviderValidationError(
5049
+ "openai",
5050
+ "OpenAI authentication changed; start a new run"
5051
+ );
5052
+ throw ownershipError;
4269
5053
  }
4270
- } : {}
4271
- } : void 0
4272
- );
5054
+ for (const [key, value] of Object.entries(
5055
+ codex.routing?.requestHeaders() ?? {}
5056
+ ))
5057
+ headers.set(key, value);
5058
+ const response = await sourceFetch(input, { ...init, headers });
5059
+ codex.metadata.observeHeaders(response.headers);
5060
+ return response;
5061
+ }
5062
+ }) : client;
5063
+ const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
5064
+ throw ownershipError ?? error;
5065
+ });
5066
+ const accumulator = new OpenAiResponseAccumulator();
5067
+ for await (const event of stream2) {
5068
+ if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
5069
+ codex?.metadata.observeEvent(event);
5070
+ await onEvent?.(event);
5071
+ if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
5072
+ if (event.type === "response.failed") {
5073
+ throw event.response.error ?? new Error("OpenAI stream failed");
5074
+ }
5075
+ if (event.type === "error") throw event;
5076
+ accumulator.observeEvent(event);
5077
+ if (event.type === "response.completed" || event.type === "response.incomplete") {
5078
+ return accumulator.buildResponse(event.response);
5079
+ }
5080
+ }
5081
+ if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
5082
+ throw new Error("OpenAI stream ended without a terminal response");
5083
+ }
5084
+ const stream = client.responses.stream(streamRequest, options);
4273
5085
  if (typeof stream[Symbol.asyncIterator] === "function") {
4274
5086
  const accumulator = new OpenAiResponseAccumulator();
4275
5087
  for await (const event of stream) {
@@ -4320,12 +5132,12 @@ var formatOtherPart3 = (part) => {
4320
5132
  };
4321
5133
  var isOpenAIAssistantInputContent = (value) => {
4322
5134
  if (!value || typeof value !== "object") return false;
4323
- const record = value;
4324
- if (record.type === "output_text") {
4325
- return typeof record.text === "string";
5135
+ const record3 = value;
5136
+ if (record3.type === "output_text") {
5137
+ return typeof record3.text === "string";
4326
5138
  }
4327
- if (record.type === "refusal") {
4328
- return typeof record.refusal === "string";
5139
+ if (record3.type === "refusal") {
5140
+ return typeof record3.refusal === "string";
4329
5141
  }
4330
5142
  return false;
4331
5143
  };
@@ -4343,8 +5155,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
4343
5155
  if (!value || typeof value !== "object") {
4344
5156
  return false;
4345
5157
  }
4346
- const record = value;
4347
- return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
5158
+ const record3 = value;
5159
+ return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
4348
5160
  };
4349
5161
  var toReplayableFunctionCallItemId = (value) => {
4350
5162
  if (typeof value !== "string") {
@@ -4395,14 +5207,14 @@ var extractReasoningText = (item) => {
4395
5207
  };
4396
5208
  var extractWebSearchSummary = (item) => {
4397
5209
  const parts = [`WebSearch status=${item.status}`];
4398
- const record = item;
4399
- const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
5210
+ const record3 = item;
5211
+ const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
4400
5212
  (entry) => typeof entry === "string" && entry.length > 0
4401
5213
  ) : [];
4402
5214
  if (queries.length) {
4403
5215
  parts.push(`queries=${queries.join(" | ")}`);
4404
5216
  }
4405
- const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
5217
+ const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
4406
5218
  if (sources.length) {
4407
5219
  parts.push(`sources=${sources.length}`);
4408
5220
  }
@@ -4573,6 +5385,9 @@ function toChatInvokeCompletion2(response, meta) {
4573
5385
  input_tokens: response.usage.input_tokens,
4574
5386
  input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
4575
5387
  output_tokens: response.usage.output_tokens,
5388
+ ...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
5389
+ output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
5390
+ } : {},
4576
5391
  total_tokens: response.usage.total_tokens
4577
5392
  } : null;
4578
5393
  const messages = toMessageSequence(response);
@@ -4678,6 +5493,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
4678
5493
  var OPENAI_BETA_HEADER = "OpenAI-Beta";
4679
5494
  var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
4680
5495
  var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
5496
+ var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
5497
+ constructor() {
5498
+ super({
5499
+ ...buildProviderFailure("openai", "validation"),
5500
+ safeMessage: "OpenAI WebSocket message exceeded the server size limit (1009). WebSocket-only mode does not resend this request; auto mode can fall back to HTTP. Compact oversized history if needed. Saved originals are unchanged."
5501
+ });
5502
+ }
5503
+ };
4681
5504
  var resolveTimeoutMs = (value, fallbackMs) => {
4682
5505
  if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
4683
5506
  return fallbackMs;
@@ -4759,6 +5582,8 @@ var OpenAiWsTransport = class {
4759
5582
  );
4760
5583
  }
4761
5584
  async invoke(args) {
5585
+ const timing = new LlmStreamTiming();
5586
+ args.codex?.metadata.beginAttempt();
4762
5587
  await this.prepareClientForWsHandshake();
4763
5588
  const wsOptionsHeaders = {
4764
5589
  ...this.getClientDefaultHeaders(),
@@ -4767,6 +5592,19 @@ var OpenAiWsTransport = class {
4767
5592
  if (args.sessionIdHeader) {
4768
5593
  wsOptionsHeaders.session_id = args.sessionIdHeader;
4769
5594
  }
5595
+ if (args.codex?.routing) {
5596
+ const authHeaders = new Headers(wsOptionsHeaders);
5597
+ authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
5598
+ if (args.codex.routing.bindAuth(authHeaders)) {
5599
+ if (args.ws)
5600
+ this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
5601
+ throw createProviderValidationError(
5602
+ "openai",
5603
+ "OpenAI authentication changed; start a new run"
5604
+ );
5605
+ }
5606
+ Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
5607
+ }
4770
5608
  const wsOptions = { headers: wsOptionsHeaders };
4771
5609
  const ownsWs = !args.ws;
4772
5610
  const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new ResponsesWS(
@@ -4777,6 +5615,15 @@ var OpenAiWsTransport = class {
4777
5615
  ws.on("error", () => {
4778
5616
  });
4779
5617
  }
5618
+ const removeUpgrade = args.codex ? this.addNativeSocketListener(
5619
+ this.getNativeSocket(ws),
5620
+ "upgrade",
5621
+ (response) => {
5622
+ const headers = response?.headers;
5623
+ if (headers)
5624
+ args.codex?.metadata.observeHeaders(new Headers(headers));
5625
+ }
5626
+ ) : void 0;
4780
5627
  try {
4781
5628
  await this.waitForWsOpen(ws, args.signal);
4782
5629
  const closeWs = () => {
@@ -4785,11 +5632,14 @@ var OpenAiWsTransport = class {
4785
5632
  const responseWaiter = this.createResponsePromise({
4786
5633
  ws,
4787
5634
  signal: args.signal,
4788
- closeWs
5635
+ closeWs,
5636
+ timing,
5637
+ metadata: args.codex?.metadata
4789
5638
  });
4790
5639
  const responseCreateEvent = {
4791
5640
  type: "response.create",
4792
- ...args.request
5641
+ ...args.request,
5642
+ ...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
4793
5643
  };
4794
5644
  if (!responseWaiter.isSettled()) {
4795
5645
  try {
@@ -4799,12 +5649,14 @@ var OpenAiWsTransport = class {
4799
5649
  }
4800
5650
  }
4801
5651
  const response = await responseWaiter.responsePromise;
4802
- return { response, ws };
5652
+ return { response, ws, timing: timing.finish() };
4803
5653
  } catch (error) {
4804
5654
  if (ownsWs) {
4805
5655
  this.closeWithoutMaskingPrimaryError(ws, "failed", error);
4806
5656
  }
4807
5657
  throw error;
5658
+ } finally {
5659
+ removeUpgrade?.();
4808
5660
  }
4809
5661
  }
4810
5662
  createResponsePromise(args) {
@@ -4894,6 +5746,7 @@ var OpenAiWsTransport = class {
4894
5746
  rejectOnce(error);
4895
5747
  };
4896
5748
  const resolveFromTerminalEvent = (event, type) => {
5749
+ args.timing.complete();
4897
5750
  const response = event?.response;
4898
5751
  if (response && typeof response === "object") {
4899
5752
  accumulator.observeTerminalResponse(response);
@@ -4916,6 +5769,9 @@ var OpenAiWsTransport = class {
4916
5769
  );
4917
5770
  };
4918
5771
  const onEvent = (event) => {
5772
+ if (settled) return;
5773
+ args.metadata?.observeEvent(event);
5774
+ args.timing.observeResponsesEvent(event);
4919
5775
  const eventType = this.extractResponsesEventType(event);
4920
5776
  if (!eventType) {
4921
5777
  return;
@@ -4964,7 +5820,7 @@ var OpenAiWsTransport = class {
4964
5820
  const onClose = (event) => {
4965
5821
  const closeCode = this.extractWsCloseCode(event);
4966
5822
  rejectOnce(
4967
- new Error(
5823
+ closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
4968
5824
  `openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
4969
5825
  )
4970
5826
  );
@@ -5233,6 +6089,8 @@ var OpenAiWsTransport = class {
5233
6089
  return void 0;
5234
6090
  }
5235
6091
  const limited = entries.slice(0, 12).map(([key, value]) => {
6092
+ if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
6093
+ return `${key}:[redacted]`;
5236
6094
  const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
5237
6095
  return `${key}:${text}`;
5238
6096
  });
@@ -5437,7 +6295,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
5437
6295
  };
5438
6296
  var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
5439
6297
  var WS_SESSION_DISABLE_TTL_MS = 6e4;
5440
- var WS_REUSE_MAX_IDLE_MS = 3e4;
5441
6298
  var ChatOpenAI = class {
5442
6299
  provider = PROVIDER_NAME5;
5443
6300
  model;
@@ -5456,8 +6313,9 @@ var ChatOpenAI = class {
5456
6313
  wsStateBySessionKey = /* @__PURE__ */ new Map();
5457
6314
  wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
5458
6315
  wsReconnectCount = 0;
6316
+ codexTurns = /* @__PURE__ */ new Map();
5459
6317
  constructor(options = {}) {
5460
- this.client = options.client ?? new OpenAI2({
6318
+ this.client = options.client ?? new OpenAI3({
5461
6319
  ...options.clientOptions ?? {},
5462
6320
  maxRetries: options.clientOptions?.maxRetries ?? 0
5463
6321
  });
@@ -5540,17 +6398,32 @@ var ChatOpenAI = class {
5540
6398
  const debugSeq = this.nextDebugInvokeSeq();
5541
6399
  const requestMeta = {
5542
6400
  model: String(request.model ?? this.providerModel),
5543
- instructionsHash: createHash3("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
5544
- toolsHash: createHash3("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
6401
+ instructionsHash: createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
6402
+ toolsHash: createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
5545
6403
  };
5546
- const transportResult = await this.invokeWithTransport({
5547
- request,
5548
- sessionKey: context?.sessionKey,
5549
- sessionIdHeader,
5550
- signal,
5551
- debugSeq,
5552
- requestMeta
5553
- });
6404
+ const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
6405
+ let transportResult;
6406
+ try {
6407
+ transportResult = await this.invokeWithTransport({
6408
+ request,
6409
+ sessionKey: context?.sessionKey,
6410
+ sessionIdHeader,
6411
+ signal,
6412
+ debugSeq,
6413
+ requestMeta,
6414
+ ...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
6415
+ });
6416
+ } finally {
6417
+ codex?.metadata?.finish();
6418
+ }
6419
+ const codexMetadata = codex?.metadata?.snapshot();
6420
+ if (codex) {
6421
+ const { headers: _headers, ...response } = transportResult.response;
6422
+ transportResult.response = {
6423
+ ...response,
6424
+ ...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
6425
+ };
6426
+ }
5554
6427
  await this.debugResponseIfEnabled(
5555
6428
  transportResult.response,
5556
6429
  debugSeq,
@@ -5574,7 +6447,42 @@ var ChatOpenAI = class {
5574
6447
  debugSeq,
5575
6448
  transportResult.transport
5576
6449
  );
5577
- return completion;
6450
+ return {
6451
+ ...completion,
6452
+ ...codexMetadata ? {
6453
+ provider_meta: {
6454
+ ...completion.provider_meta,
6455
+ codex_metadata: codexMetadata
6456
+ }
6457
+ } : {},
6458
+ ...transportResult.timing ? { timing: transportResult.timing } : {}
6459
+ };
6460
+ }
6461
+ createCodexMetadata(context) {
6462
+ const routing = this.resolveCodexTurn(context);
6463
+ return {
6464
+ routing,
6465
+ metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
6466
+ };
6467
+ }
6468
+ resolveCodexTurn(context) {
6469
+ if (!context?.turnKey) return void 0;
6470
+ const key = context.sessionKey ?? context.turnKey;
6471
+ let state = this.codexTurns.get(key);
6472
+ if (!state || state.turnKey !== context.turnKey) {
6473
+ this.clearWsSessionState(key, "new_turn");
6474
+ state = { turnKey: context.turnKey, routing: new CodexTurnState() };
6475
+ this.codexTurns.delete(key);
6476
+ this.codexTurns.set(key, state);
6477
+ if (this.codexTurns.size > 16) {
6478
+ const oldest = this.codexTurns.keys().next().value;
6479
+ if (oldest !== void 0) {
6480
+ this.codexTurns.delete(oldest);
6481
+ this.clearWsSessionState(oldest, "turn_state_evicted");
6482
+ }
6483
+ }
6484
+ }
6485
+ return state.routing;
5578
6486
  }
5579
6487
  onHistoryCompacted(context) {
5580
6488
  const sessionKey = context?.sessionKey;
@@ -5592,6 +6500,7 @@ var ChatOpenAI = class {
5592
6500
  this.evictIdleWsSessionState();
5593
6501
  if (this.websocketMode === "off") {
5594
6502
  return this.invokeHttpTransportWithDebug({
6503
+ codex: args.codex,
5595
6504
  request: args.request,
5596
6505
  debugSeq: args.debugSeq,
5597
6506
  sessionIdHeader: args.sessionIdHeader,
@@ -5607,6 +6516,7 @@ var ChatOpenAI = class {
5607
6516
  );
5608
6517
  }
5609
6518
  return this.invokeHttpTransportWithDebug({
6519
+ codex: args.codex,
5610
6520
  request: args.request,
5611
6521
  debugSeq: args.debugSeq,
5612
6522
  sessionIdHeader: args.sessionIdHeader,
@@ -5617,6 +6527,7 @@ var ChatOpenAI = class {
5617
6527
  }
5618
6528
  if (this.isWsSessionDisabled(args.sessionKey)) {
5619
6529
  return this.invokeHttpTransportWithDebug({
6530
+ codex: args.codex,
5620
6531
  request: args.request,
5621
6532
  debugSeq: args.debugSeq,
5622
6533
  sessionIdHeader: args.sessionIdHeader,
@@ -5626,7 +6537,7 @@ var ChatOpenAI = class {
5626
6537
  });
5627
6538
  }
5628
6539
  const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
5629
- const hasReusableWs = this.isWsConnectionReusable(wsState.ws) && !this.isWsConnectionReuseExpired(wsState.lastUsedAt);
6540
+ const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
5630
6541
  const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
5631
6542
  const incrementalInput = this.getIncrementalInput(
5632
6543
  wsState.lastInput,
@@ -5674,7 +6585,8 @@ var ChatOpenAI = class {
5674
6585
  wsExecutionPlan.chainReset,
5675
6586
  wsExecutionPlan.wsInputMode
5676
6587
  );
5677
- const { response, ws } = await this.invokeViaWs({
6588
+ const { response, ws, timing } = await this.invokeViaWs({
6589
+ codex: args.codex,
5678
6590
  request: wsExecutionPlan.request,
5679
6591
  signal: args.signal,
5680
6592
  sessionIdHeader: args.sessionIdHeader,
@@ -5690,12 +6602,17 @@ var ChatOpenAI = class {
5690
6602
  return {
5691
6603
  response,
5692
6604
  transport: "ws_mode",
6605
+ ...timing ? { timing } : {},
5693
6606
  fallbackUsed: false,
5694
6607
  chainReset: wsExecutionPlan.chainReset,
5695
6608
  wsInputMode: wsExecutionPlan.wsInputMode
5696
6609
  };
5697
6610
  } catch (error) {
5698
6611
  let failure = error;
6612
+ if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
6613
+ this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
6614
+ throw failure;
6615
+ }
5699
6616
  if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
5700
6617
  const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
5701
6618
  this.closeWsWithoutMaskingPrimaryError(
@@ -5713,7 +6630,8 @@ var ChatOpenAI = class {
5713
6630
  true,
5714
6631
  retryWsInputMode
5715
6632
  );
5716
- const { response, ws } = await this.invokeViaWs({
6633
+ const { response, ws, timing } = await this.invokeViaWs({
6634
+ codex: args.codex,
5717
6635
  request: args.request,
5718
6636
  signal: args.signal,
5719
6637
  sessionIdHeader: args.sessionIdHeader,
@@ -5730,6 +6648,7 @@ var ChatOpenAI = class {
5730
6648
  return {
5731
6649
  response,
5732
6650
  transport: "ws_mode",
6651
+ ...timing ? { timing } : {},
5733
6652
  fallbackUsed: false,
5734
6653
  chainReset: true,
5735
6654
  wsInputMode: retryWsInputMode
@@ -5738,9 +6657,13 @@ var ChatOpenAI = class {
5738
6657
  failure = retryError;
5739
6658
  }
5740
6659
  }
6660
+ if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
6661
+ this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
6662
+ throw failure;
6663
+ }
5741
6664
  const wsErrorCode = this.extractWsErrorCode(failure);
5742
6665
  const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
5743
- const shouldDisableWsForSession = wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
6666
+ const shouldDisableWsForSession = failure instanceof OpenAiWsMessageTooLargeError || wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
5744
6667
  this.clearWsSessionState(args.sessionKey, "reset", failure);
5745
6668
  if (shouldDisableWsForSession && fallbackAllowed) {
5746
6669
  this.wsDisabledUntilBySessionKey.set(
@@ -5753,6 +6676,7 @@ var ChatOpenAI = class {
5753
6676
  }
5754
6677
  this.wsReconnectCount += 1;
5755
6678
  return this.invokeHttpTransportWithDebug({
6679
+ codex: args.codex,
5756
6680
  request: args.request,
5757
6681
  debugSeq: args.debugSeq,
5758
6682
  sessionIdHeader: args.sessionIdHeader,
@@ -5773,16 +6697,23 @@ var ChatOpenAI = class {
5773
6697
  args.chainReset,
5774
6698
  args.wsInputMode
5775
6699
  );
6700
+ const timing = new LlmStreamTiming();
6701
+ const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
5776
6702
  const response = await invokeOpenAiHttp(
5777
6703
  this.client,
5778
6704
  args.request,
5779
6705
  args.signal,
5780
6706
  args.sessionIdHeader,
5781
- this.getHttpStreamDebugObserver(args.debugSeq)
6707
+ (event) => {
6708
+ timing.observeResponsesEvent(event);
6709
+ return debugObserver?.(event);
6710
+ },
6711
+ args.codex
5782
6712
  );
5783
6713
  return {
5784
6714
  response,
5785
6715
  transport: "http_stream",
6716
+ timing: timing.finish(),
5786
6717
  fallbackUsed: args.fallbackUsed,
5787
6718
  chainReset: args.chainReset
5788
6719
  };
@@ -5820,12 +6751,6 @@ var ChatOpenAI = class {
5820
6751
  closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
5821
6752
  this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
5822
6753
  }
5823
- isWsConnectionReuseExpired(lastUsedAt) {
5824
- if (typeof lastUsedAt !== "number") {
5825
- return false;
5826
- }
5827
- return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
5828
- }
5829
6754
  isWsReconnectRetryableError(error) {
5830
6755
  if (!(error instanceof Error)) {
5831
6756
  return false;
@@ -5904,14 +6829,14 @@ var ChatOpenAI = class {
5904
6829
  return;
5905
6830
  }
5906
6831
  const payload = safeJsonStringify(request);
5907
- const hash = createHash3("sha256").update(payload).digest("hex").slice(0, 16);
5908
- const toolsHash = createHash3("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
5909
- const instructionsHash = createHash3("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
6832
+ const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
6833
+ const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
6834
+ const instructionsHash = createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
5910
6835
  const previous = this.lastDebugRequestPayload;
5911
6836
  const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
5912
6837
  const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
5913
6838
  if (settings.enabled) {
5914
- const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash3("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
6839
+ const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash4("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
5915
6840
  const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
5916
6841
  const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
5917
6842
  console.error(
@@ -6004,8 +6929,8 @@ var ChatOpenAI = class {
6004
6929
  };
6005
6930
 
6006
6931
  // src/llm/openrouter/chat.ts
6007
- import { createHash as createHash4 } from "crypto";
6008
- import OpenAI3 from "openai";
6932
+ import { createHash as createHash5 } from "crypto";
6933
+ import OpenAI4 from "openai";
6009
6934
 
6010
6935
  // src/llm/openrouter/response-utils.ts
6011
6936
  var isRecord4 = (value) => typeof value === "object" && value !== null;
@@ -6125,12 +7050,12 @@ var formatOtherPart5 = (part) => {
6125
7050
  };
6126
7051
  var isOpenAIAssistantInputContent2 = (value) => {
6127
7052
  if (!value || typeof value !== "object") return false;
6128
- const record = value;
6129
- if (record.type === "output_text") {
6130
- return typeof record.text === "string";
7053
+ const record3 = value;
7054
+ if (record3.type === "output_text") {
7055
+ return typeof record3.text === "string";
6131
7056
  }
6132
- if (record.type === "refusal") {
6133
- return typeof record.refusal === "string";
7057
+ if (record3.type === "refusal") {
7058
+ return typeof record3.refusal === "string";
6134
7059
  }
6135
7060
  return false;
6136
7061
  };
@@ -6138,8 +7063,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
6138
7063
  if (!value || typeof value !== "object") {
6139
7064
  return false;
6140
7065
  }
6141
- const record = value;
6142
- return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
7066
+ const record3 = value;
7067
+ return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
6143
7068
  };
6144
7069
  var toReplayableFunctionCallItemId2 = (value) => {
6145
7070
  if (typeof value !== "string") {
@@ -6190,14 +7115,14 @@ var extractReasoningText2 = (item) => {
6190
7115
  };
6191
7116
  var extractWebSearchSummary2 = (item) => {
6192
7117
  const parts = [`WebSearch status=${item.status}`];
6193
- const record = item;
6194
- const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
7118
+ const record3 = item;
7119
+ const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
6195
7120
  (entry) => typeof entry === "string" && entry.length > 0
6196
7121
  ) : [];
6197
7122
  if (queries.length) {
6198
7123
  parts.push(`queries=${queries.join(" | ")}`);
6199
7124
  }
6200
- const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
7125
+ const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
6201
7126
  if (sources.length) {
6202
7127
  parts.push(`sources=${sources.length}`);
6203
7128
  }
@@ -6364,6 +7289,9 @@ function toChatInvokeCompletion3(response, meta) {
6364
7289
  input_tokens: response.usage.input_tokens,
6365
7290
  input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
6366
7291
  output_tokens: response.usage.output_tokens,
7292
+ ...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
7293
+ output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
7294
+ } : {},
6367
7295
  total_tokens: response.usage.total_tokens
6368
7296
  } : null;
6369
7297
  const messages = toMessageSequence2(response);
@@ -6473,7 +7401,7 @@ var ChatOpenRouter = class {
6473
7401
  debugInvokeSeq = 0;
6474
7402
  lastDebugRequestPayload = null;
6475
7403
  constructor(options = {}) {
6476
- this.client = options.client ?? new OpenAI3({
7404
+ this.client = options.client ?? new OpenAI4({
6477
7405
  baseURL: OPENROUTER_BASE_URL,
6478
7406
  ...options.clientOptions ?? {},
6479
7407
  maxRetries: options.clientOptions?.maxRetries ?? 0
@@ -6545,7 +7473,8 @@ var ChatOpenRouter = class {
6545
7473
  ...request,
6546
7474
  stream: true
6547
7475
  };
6548
- const response = await this.client.responses.stream(
7476
+ const timing = new LlmStreamTiming();
7477
+ const stream = this.client.responses.stream(
6549
7478
  streamRequest,
6550
7479
  signal || sessionIdHeader ? {
6551
7480
  ...signal ? { signal } : {},
@@ -6555,13 +7484,21 @@ var ChatOpenRouter = class {
6555
7484
  }
6556
7485
  } : {}
6557
7486
  } : void 0
6558
- ).finalResponse();
7487
+ );
7488
+ if (typeof stream[Symbol.asyncIterator] === "function") {
7489
+ for await (const event of stream) timing.observeResponsesEvent(event);
7490
+ }
7491
+ const response = await stream.finalResponse();
7492
+ const measuredTiming = timing.finish();
6559
7493
  await this.debugResponseIfEnabled(response, debugSeq);
6560
- return toChatInvokeCompletion3(response, {
6561
- reasoning_requested: this.reasoningLevelMeta.requested,
6562
- reasoning_applied: this.reasoningLevelMeta.applied,
6563
- reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
6564
- });
7494
+ return {
7495
+ ...toChatInvokeCompletion3(response, {
7496
+ reasoning_requested: this.reasoningLevelMeta.requested,
7497
+ reasoning_applied: this.reasoningLevelMeta.applied,
7498
+ reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
7499
+ }),
7500
+ ...measuredTiming ? { timing: measuredTiming } : {}
7501
+ };
6565
7502
  }
6566
7503
  nextDebugInvokeSeq() {
6567
7504
  const seq = this.debugInvokeSeq + 1;
@@ -6574,14 +7511,14 @@ var ChatOpenRouter = class {
6574
7511
  return;
6575
7512
  }
6576
7513
  const payload = safeJsonStringify(request);
6577
- const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
6578
- const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
6579
- const instructionsHash = createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
7514
+ const hash = createHash5("sha256").update(payload).digest("hex").slice(0, 16);
7515
+ const toolsHash = createHash5("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
7516
+ const instructionsHash = createHash5("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
6580
7517
  const previous = this.lastDebugRequestPayload;
6581
7518
  const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
6582
7519
  const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
6583
7520
  if (settings.enabled) {
6584
- const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash4("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
7521
+ const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash5("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
6585
7522
  console.error(
6586
7523
  `[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
6587
7524
  );
@@ -6645,8 +7582,8 @@ var ChatOpenRouter = class {
6645
7582
  };
6646
7583
 
6647
7584
  // src/llm/xai/chat.ts
6648
- import { createHash as createHash5 } from "crypto";
6649
- import OpenAI4 from "openai";
7585
+ import { createHash as createHash6 } from "crypto";
7586
+ import OpenAI5 from "openai";
6650
7587
 
6651
7588
  // src/llm/xai/serializer.ts
6652
7589
  var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
@@ -6869,7 +7806,7 @@ var ChatXai = class {
6869
7806
  debugInvokeSeq = 0;
6870
7807
  lastDebugRequestPayload = null;
6871
7808
  constructor(options = {}) {
6872
- this.client = options.client ?? new OpenAI4({
7809
+ this.client = options.client ?? new OpenAI5({
6873
7810
  baseURL: XAI_BASE_URL,
6874
7811
  timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
6875
7812
  ...options.clientOptions ?? {},
@@ -6922,13 +7859,24 @@ var ChatXai = class {
6922
7859
  }
6923
7860
  const debugSeq = this.nextDebugInvokeSeq();
6924
7861
  await this.debugRequestIfEnabled(request, debugSeq);
6925
- const response = await invokeOpenAiHttp(this.client, request, signal);
7862
+ const timing = new LlmStreamTiming();
7863
+ const response = await invokeOpenAiHttp(
7864
+ this.client,
7865
+ request,
7866
+ signal,
7867
+ void 0,
7868
+ (event) => timing.observeResponsesEvent(event)
7869
+ );
7870
+ const measuredTiming = timing.finish();
6926
7871
  await this.debugResponseIfEnabled(response, debugSeq);
6927
- return toXaiChatInvokeCompletion(response, {
6928
- reasoning_requested: this.reasoningLevelMeta.requested,
6929
- reasoning_applied: this.reasoningLevelMeta.applied,
6930
- reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
6931
- });
7872
+ return {
7873
+ ...toXaiChatInvokeCompletion(response, {
7874
+ reasoning_requested: this.reasoningLevelMeta.requested,
7875
+ reasoning_applied: this.reasoningLevelMeta.applied,
7876
+ reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
7877
+ }),
7878
+ ...measuredTiming ? { timing: measuredTiming } : {}
7879
+ };
6932
7880
  }
6933
7881
  nextDebugInvokeSeq() {
6934
7882
  this.debugInvokeSeq += 1;
@@ -6938,7 +7886,7 @@ var ChatXai = class {
6938
7886
  const settings = getProviderLogSettings();
6939
7887
  if (!settings.enabled && !settings.dumpDir) return;
6940
7888
  const payload = safeJsonStringify(request);
6941
- const hash = createHash5("sha256").update(payload).digest("hex").slice(0, 16);
7889
+ const hash = createHash6("sha256").update(payload).digest("hex").slice(0, 16);
6942
7890
  const previous = this.lastDebugRequestPayload;
6943
7891
  const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
6944
7892
  const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
@@ -6995,15 +7943,15 @@ var ChatXai = class {
6995
7943
  };
6996
7944
 
6997
7945
  // src/llm/zai/chat.ts
6998
- import { createHash as createHash6 } from "crypto";
7946
+ import { createHash as createHash7 } from "crypto";
6999
7947
 
7000
7948
  // src/llm/zai/failure.ts
7001
7949
  var PROVIDER_NAME8 = "zai";
7002
7950
  var readBusinessCode = (error) => {
7003
- const record = asRecord(error);
7004
- const body = asRecord(record?.body);
7951
+ const record3 = asRecord(error);
7952
+ const body = asRecord(record3?.body);
7005
7953
  const nested = asRecord(body?.error) ?? body;
7006
- const raw = nested?.code ?? record?.code;
7954
+ const raw = nested?.code ?? record3?.code;
7007
7955
  const parsed = typeof raw === "number" ? raw : Number(raw);
7008
7956
  return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
7009
7957
  };
@@ -7307,6 +8255,7 @@ var streamZaiChatCompletion = async ({
7307
8255
  timeoutMs,
7308
8256
  captureRawChunks
7309
8257
  }) => {
8258
+ const timing = new LlmStreamTiming();
7310
8259
  const requestSignal = createZaiRequestSignal(signal, timeoutMs);
7311
8260
  try {
7312
8261
  const response = await fetchImpl(`${baseURL}/chat/completions`, {
@@ -7328,9 +8277,11 @@ var streamZaiChatCompletion = async ({
7328
8277
  response,
7329
8278
  requestSignal.signal
7330
8279
  )) {
8280
+ timing.observeChatChunk(chunk);
7331
8281
  appendZaiChatCompletionChunk(accumulated, chunk);
7332
8282
  }
7333
8283
  return {
8284
+ timing: timing.finish(),
7334
8285
  status: response.status,
7335
8286
  request_id: response.headers.get("x-request-id"),
7336
8287
  accumulated
@@ -7525,13 +8476,16 @@ var ChatZai = class {
7525
8476
  await this.debugRequestIfEnabled(request, debugSeq);
7526
8477
  const terminal = await this.streamRequest(apiKey, request, signal);
7527
8478
  await this.debugResponseIfEnabled(terminal, debugSeq);
7528
- return toZaiChatInvokeCompletion(terminal.accumulated, {
7529
- request_id: terminal.request_id ?? null,
7530
- reasoning_requested: this.reasoningLevelMeta.requested,
7531
- reasoning_applied: this.reasoningLevelMeta.applied,
7532
- reasoning_effort: request.reasoning_effort,
7533
- reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
7534
- });
8479
+ return {
8480
+ ...toZaiChatInvokeCompletion(terminal.accumulated, {
8481
+ request_id: terminal.request_id ?? null,
8482
+ reasoning_requested: this.reasoningLevelMeta.requested,
8483
+ reasoning_applied: this.reasoningLevelMeta.applied,
8484
+ reasoning_effort: request.reasoning_effort,
8485
+ reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
8486
+ }),
8487
+ ...terminal.timing ? { timing: terminal.timing } : {}
8488
+ };
7535
8489
  }
7536
8490
  async streamRequest(apiKey, request, signal) {
7537
8491
  const logSettings = getProviderLogSettings();
@@ -7556,8 +8510,8 @@ var ChatZai = class {
7556
8510
  return;
7557
8511
  }
7558
8512
  const payload = safeJsonStringify(request);
7559
- const hash = createHash6("sha256").update(payload).digest("hex").slice(0, 16);
7560
- const toolsHash = createHash6("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
8513
+ const hash = createHash7("sha256").update(payload).digest("hex").slice(0, 16);
8514
+ const toolsHash = createHash7("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
7561
8515
  const previous = this.lastDebugRequestPayload;
7562
8516
  const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
7563
8517
  const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
@@ -7688,6 +8642,159 @@ function defineTool(toolOptions) {
7688
8642
  }
7689
8643
  };
7690
8644
  }
8645
+
8646
+ // src/llm/responses/chat.ts
8647
+ import OpenAI6 from "openai";
8648
+ var ChatResponses = class {
8649
+ provider;
8650
+ model;
8651
+ retryPolicy;
8652
+ client;
8653
+ endpoint;
8654
+ reasoningEffort;
8655
+ textVerbosity;
8656
+ constructor(options) {
8657
+ this.provider = options.provider;
8658
+ this.model = options.model;
8659
+ this.endpoint = options.endpoint;
8660
+ this.reasoningEffort = options.reasoningEffort;
8661
+ this.textVerbosity = options.textVerbosity;
8662
+ const retry = options.endpoint.retry;
8663
+ this.retryPolicy = {
8664
+ maxRetries: typeof retry === "object" ? retry.max_retries : 0,
8665
+ ...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
8666
+ };
8667
+ this.client = new OpenAI6({
8668
+ apiKey: options.apiKey,
8669
+ baseURL: options.endpoint.base_url,
8670
+ organization: null,
8671
+ project: null,
8672
+ maxRetries: 0,
8673
+ timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
8674
+ ...options.fetch ? { fetch: options.fetch } : {}
8675
+ });
8676
+ }
8677
+ classifyFailure = (error) => {
8678
+ if (isProviderFailureError(error)) return error.failure;
8679
+ const failure = error instanceof OpenAI6.APIUserAbortError ? buildProviderFailure(this.provider, "cancelled") : error instanceof OpenAI6.APIConnectionTimeoutError ? buildProviderFailure(this.provider, "timeout", { retryable: true }) : error instanceof OpenAI6.APIConnectionError ? buildProviderFailure(this.provider, "network", {
8680
+ retryable: true
8681
+ }) : classifyOpenAiCompatibleFailure(this.provider, error);
8682
+ const extracted = extractProviderError(error);
8683
+ const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
8684
+ return {
8685
+ ...failure,
8686
+ ...extracted.status !== void 0 ? { status: extracted.status } : {},
8687
+ ...extracted.status === 413 ? { kind: "validation" } : {},
8688
+ retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
8689
+ ...code ? { code } : {},
8690
+ safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
8691
+ };
8692
+ };
8693
+ async ainvoke(input, context) {
8694
+ const model = input.model ?? this.model;
8695
+ const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
8696
+ const invalid = (message) => {
8697
+ throw createProviderValidationError(this.provider, message);
8698
+ };
8699
+ if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
8700
+ if (input.tools?.some((tool) => tool.type === "hosted_search"))
8701
+ invalid(
8702
+ `${this.provider} supports function tools only; hosted tools are unavailable`
8703
+ );
8704
+ if (input.tools?.length && !spec.supports_tools)
8705
+ invalid(`${this.provider}/${model} does not support tools`);
8706
+ const items = toResponsesInput(input.messages);
8707
+ if (!spec.supports_vision && Array.isArray(items) && items.some(
8708
+ (item) => "content" in item && Array.isArray(item.content) && item.content.some((part) => part.type === "input_image")
8709
+ ))
8710
+ invalid(`${this.provider}/${model} vision is disabled`);
8711
+ const text = input.options?.text;
8712
+ if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
8713
+ invalid(`${this.provider}/${model} does not support structured output`);
8714
+ const features = this.endpoint.features;
8715
+ const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
8716
+ if (effort && !spec.supports_reasoning)
8717
+ invalid(`${this.provider}/${model} reasoning is disabled`);
8718
+ const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
8719
+ if (effort && !levels.includes(effort))
8720
+ invalid(
8721
+ `Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
8722
+ );
8723
+ const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
8724
+ if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
8725
+ invalid(`Invalid max output tokens for ${this.provider}/${model}`);
8726
+ const tools = toResponsesTools(input.tools);
8727
+ const choice = toResponsesToolChoice(input.toolChoice);
8728
+ const instructions = extractInstructions(input.messages);
8729
+ const request = {
8730
+ model,
8731
+ input: items,
8732
+ store: false,
8733
+ ...instructions ? { instructions } : {},
8734
+ ...tools ? { tools } : {},
8735
+ ...choice ? { tool_choice: choice } : {},
8736
+ ...output !== void 0 ? { max_output_tokens: output } : {}
8737
+ };
8738
+ if (spec.supports_reasoning && (effort || features?.reasoning_summary))
8739
+ request.reasoning = {
8740
+ ...effort ? { effort: toSdkReasoningEffort(effort) } : {},
8741
+ ...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
8742
+ };
8743
+ if (spec.supports_reasoning && features?.encrypted_reasoning)
8744
+ request.include = ["reasoning.encrypted_content"];
8745
+ if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
8746
+ request.text = {
8747
+ ...text?.format ? { format: text.format } : {},
8748
+ ...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
8749
+ };
8750
+ if (features?.prompt_cache_key && context?.sessionKey)
8751
+ request.prompt_cache_key = context.sessionKey;
8752
+ const timing = new LlmStreamTiming();
8753
+ let streamStarted = false;
8754
+ try {
8755
+ const stream = await this.client.responses.create(
8756
+ { ...request, stream: true },
8757
+ {
8758
+ ...input.signal ? { signal: input.signal } : {},
8759
+ ...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
8760
+ }
8761
+ );
8762
+ streamStarted = true;
8763
+ const accumulator = new OpenAiResponseAccumulator();
8764
+ let terminal;
8765
+ for await (const event of stream) {
8766
+ timing.observeResponsesEvent(event);
8767
+ if (event.type === "error") throw { error: event };
8768
+ if (event.type === "response.failed")
8769
+ throw { error: event.response.error };
8770
+ accumulator.observeEvent(event);
8771
+ if (event.type === "response.completed" || event.type === "response.incomplete") {
8772
+ terminal = event.response;
8773
+ break;
8774
+ }
8775
+ }
8776
+ if (!terminal)
8777
+ throw new Error("Responses stream ended before a terminal event");
8778
+ const measuredTiming = timing.finish();
8779
+ return {
8780
+ ...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
8781
+ transport: "http_stream"
8782
+ }),
8783
+ ...measuredTiming ? { timing: measuredTiming } : {}
8784
+ };
8785
+ } catch (error) {
8786
+ if (isProviderFailureError(error)) throw error;
8787
+ const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
8788
+ throw new ProviderFailureError(
8789
+ {
8790
+ ...failure,
8791
+ ...streamStarted ? { retryable: false, delivery: "buffered" } : {}
8792
+ },
8793
+ { cause: error }
8794
+ );
8795
+ }
8796
+ }
8797
+ };
7691
8798
  export {
7692
8799
  ANTHROPIC_DEFAULT_MODEL,
7693
8800
  ANTHROPIC_MODELS,
@@ -7696,6 +8803,7 @@ export {
7696
8803
  ChatMoonshot,
7697
8804
  ChatOpenAI,
7698
8805
  ChatOpenRouter,
8806
+ ChatResponses,
7699
8807
  ChatXai,
7700
8808
  ChatZai,
7701
8809
  DEFAULT_MODEL_REGISTRY,
@@ -7708,6 +8816,7 @@ export {
7708
8816
  ProviderFailureError,
7709
8817
  TaskComplete,
7710
8818
  ToolOutputCacheService,
8819
+ ToolPermissionDenied,
7711
8820
  XAI_DEFAULT_MODEL,
7712
8821
  XAI_DEFAULT_REASONING_EFFORT,
7713
8822
  XAI_MODELS,