@codelia/core 0.1.81 → 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.cjs +1247 -175
- package/dist/index.d.ts +80 -17
- package/dist/index.js +1242 -171
- package/package.json +4 -3
- package/prompts/system.md +2 -2
package/dist/index.cjs
CHANGED
|
@@ -37,6 +37,7 @@ __export(index_exports, {
|
|
|
37
37
|
ChatMoonshot: () => ChatMoonshot,
|
|
38
38
|
ChatOpenAI: () => ChatOpenAI,
|
|
39
39
|
ChatOpenRouter: () => ChatOpenRouter,
|
|
40
|
+
ChatResponses: () => ChatResponses,
|
|
40
41
|
ChatXai: () => ChatXai,
|
|
41
42
|
ChatZai: () => ChatZai,
|
|
42
43
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
@@ -97,6 +98,14 @@ var buildGpt56Model = (id) => ({
|
|
|
97
98
|
supportsFast: true
|
|
98
99
|
});
|
|
99
100
|
var OPENAI_MODELS = [
|
|
101
|
+
{
|
|
102
|
+
id: "gpt-6.1-sol",
|
|
103
|
+
provider: "openai",
|
|
104
|
+
contextWindow: 105e4,
|
|
105
|
+
maxInputTokens: 27e4,
|
|
106
|
+
maxOutputTokens: 128e3,
|
|
107
|
+
supportsFast: true
|
|
108
|
+
},
|
|
100
109
|
{
|
|
101
110
|
id: "gpt-6-astra",
|
|
102
111
|
provider: "openai",
|
|
@@ -105,6 +114,22 @@ var OPENAI_MODELS = [
|
|
|
105
114
|
maxOutputTokens: 128e3,
|
|
106
115
|
supportsFast: true
|
|
107
116
|
},
|
|
117
|
+
{
|
|
118
|
+
id: "gpt-6-sol",
|
|
119
|
+
provider: "openai",
|
|
120
|
+
contextWindow: 105e4,
|
|
121
|
+
maxInputTokens: 27e4,
|
|
122
|
+
maxOutputTokens: 128e3,
|
|
123
|
+
supportsFast: true
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
id: "gpt-6-luna",
|
|
127
|
+
provider: "openai",
|
|
128
|
+
contextWindow: 105e4,
|
|
129
|
+
maxInputTokens: 27e4,
|
|
130
|
+
maxOutputTokens: 128e3,
|
|
131
|
+
supportsFast: true
|
|
132
|
+
},
|
|
108
133
|
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
109
134
|
{
|
|
110
135
|
id: "gpt-5.5",
|
|
@@ -283,6 +308,47 @@ import_config.configRegistry.registerDefaults({
|
|
|
283
308
|
|
|
284
309
|
// src/agent/agent.ts
|
|
285
310
|
var import_node_perf_hooks = require("perf_hooks");
|
|
311
|
+
var import_node_crypto = require("crypto");
|
|
312
|
+
|
|
313
|
+
// src/llm/provider-status.ts
|
|
314
|
+
async function* withProviderStatus(operation, signal) {
|
|
315
|
+
const controller = new AbortController();
|
|
316
|
+
const abort = () => controller.abort(signal?.reason);
|
|
317
|
+
if (signal?.aborted) abort();
|
|
318
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
319
|
+
const queue = [];
|
|
320
|
+
let wake;
|
|
321
|
+
let closed = false;
|
|
322
|
+
const iterator = operation((event) => {
|
|
323
|
+
if (closed || controller.signal.aborted) return;
|
|
324
|
+
if (queue.length < 32) queue.push(event);
|
|
325
|
+
wake?.();
|
|
326
|
+
}, controller.signal);
|
|
327
|
+
let pending = iterator.next();
|
|
328
|
+
try {
|
|
329
|
+
while (true) {
|
|
330
|
+
while (queue.length) yield queue.shift();
|
|
331
|
+
const changed = new Promise((resolve) => {
|
|
332
|
+
wake = () => resolve(void 0);
|
|
333
|
+
});
|
|
334
|
+
const result = await Promise.race([pending, changed]);
|
|
335
|
+
wake = void 0;
|
|
336
|
+
if (!result) continue;
|
|
337
|
+
while (queue.length) yield queue.shift();
|
|
338
|
+
if (result.done) return result.value;
|
|
339
|
+
yield result.value;
|
|
340
|
+
pending = iterator.next();
|
|
341
|
+
}
|
|
342
|
+
} finally {
|
|
343
|
+
closed = true;
|
|
344
|
+
controller.abort();
|
|
345
|
+
signal?.removeEventListener("abort", abort);
|
|
346
|
+
void pending.catch(() => {
|
|
347
|
+
});
|
|
348
|
+
void iterator.return(void 0).catch(() => {
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
}
|
|
286
352
|
|
|
287
353
|
// src/content/stringify.ts
|
|
288
354
|
var stringifyUnknown = (value) => {
|
|
@@ -296,6 +362,9 @@ var stringifyPart = (part, options) => {
|
|
|
296
362
|
if (part.type === "text") {
|
|
297
363
|
return part.text;
|
|
298
364
|
}
|
|
365
|
+
if (part.type === "image_ref") {
|
|
366
|
+
return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
|
|
367
|
+
}
|
|
299
368
|
if (part.type === "image_url") {
|
|
300
369
|
if (options.mode === "log") {
|
|
301
370
|
return `[image:${part.image_url.media_type ?? "unknown"}]`;
|
|
@@ -396,8 +465,8 @@ var ProviderTimeoutError = class extends Error {
|
|
|
396
465
|
};
|
|
397
466
|
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
398
467
|
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
399
|
-
var readString = (
|
|
400
|
-
const value =
|
|
468
|
+
var readString = (record3, key) => {
|
|
469
|
+
const value = record3?.[key];
|
|
401
470
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
402
471
|
};
|
|
403
472
|
var readStatus = (error) => {
|
|
@@ -408,9 +477,9 @@ var readHeader = (headers, name) => {
|
|
|
408
477
|
if (headers instanceof Headers) {
|
|
409
478
|
return headers.get(name);
|
|
410
479
|
}
|
|
411
|
-
const
|
|
412
|
-
if (!
|
|
413
|
-
const direct =
|
|
480
|
+
const record3 = asRecord(headers);
|
|
481
|
+
if (!record3) return null;
|
|
482
|
+
const direct = record3[name] ?? record3[name.toLowerCase()];
|
|
414
483
|
return typeof direct === "string" ? direct : null;
|
|
415
484
|
};
|
|
416
485
|
var parsePositiveNumber = (value) => {
|
|
@@ -466,7 +535,7 @@ var PROVIDER_LABELS = {
|
|
|
466
535
|
xai: "xAI"
|
|
467
536
|
};
|
|
468
537
|
var safeProviderMessage = (provider, kind) => {
|
|
469
|
-
const label = PROVIDER_LABELS[provider];
|
|
538
|
+
const label = PROVIDER_LABELS[provider] ?? provider;
|
|
470
539
|
switch (kind) {
|
|
471
540
|
case "hard_quota":
|
|
472
541
|
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
@@ -806,6 +875,28 @@ var ANTHROPIC_MODELS = [
|
|
|
806
875
|
provider: "anthropic",
|
|
807
876
|
aliases: ["default"]
|
|
808
877
|
},
|
|
878
|
+
{
|
|
879
|
+
id: "claude-fable-5-1",
|
|
880
|
+
provider: "anthropic",
|
|
881
|
+
contextWindow: 1e6,
|
|
882
|
+
maxInputTokens: 1e6,
|
|
883
|
+
maxOutputTokens: 128e3
|
|
884
|
+
},
|
|
885
|
+
{
|
|
886
|
+
id: "claude-opus-5-5",
|
|
887
|
+
provider: "anthropic",
|
|
888
|
+
contextWindow: 1e6,
|
|
889
|
+
maxInputTokens: 1e6,
|
|
890
|
+
maxOutputTokens: 128e3,
|
|
891
|
+
supportsFast: true
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
id: "claude-sonnet-5",
|
|
895
|
+
provider: "anthropic",
|
|
896
|
+
contextWindow: 1e6,
|
|
897
|
+
maxInputTokens: 1e6,
|
|
898
|
+
maxOutputTokens: 128e3
|
|
899
|
+
},
|
|
809
900
|
{
|
|
810
901
|
id: "claude-fable-5",
|
|
811
902
|
provider: "anthropic",
|
|
@@ -835,12 +926,12 @@ var ANTHROPIC_MODELS = [
|
|
|
835
926
|
contextWindow: 1e6,
|
|
836
927
|
maxInputTokens: 1e6,
|
|
837
928
|
maxOutputTokens: 128e3,
|
|
838
|
-
supportsFast:
|
|
929
|
+
supportsFast: false
|
|
839
930
|
},
|
|
840
931
|
{
|
|
841
932
|
id: "claude-opus-4-6",
|
|
842
933
|
provider: "anthropic",
|
|
843
|
-
supportsFast:
|
|
934
|
+
supportsFast: false
|
|
844
935
|
},
|
|
845
936
|
{
|
|
846
937
|
id: "claude-opus-4-5",
|
|
@@ -921,6 +1012,7 @@ function createModelRegistry(specs) {
|
|
|
921
1012
|
function registerModels(registry, specs) {
|
|
922
1013
|
for (const spec of specs) {
|
|
923
1014
|
registry.modelsById[spec.id] = spec;
|
|
1015
|
+
registry.aliasesByProvider[spec.provider] ??= {};
|
|
924
1016
|
const aliasBucket = registry.aliasesByProvider[spec.provider];
|
|
925
1017
|
for (const alias of spec.aliases ?? []) {
|
|
926
1018
|
aliasBucket[alias] = spec.id;
|
|
@@ -929,11 +1021,11 @@ function registerModels(registry, specs) {
|
|
|
929
1021
|
}
|
|
930
1022
|
function resolveModel(registry, idOrAlias, provider) {
|
|
931
1023
|
const direct = registry.modelsById[idOrAlias];
|
|
932
|
-
if (direct) {
|
|
1024
|
+
if (direct && (!provider || direct.provider === provider)) {
|
|
933
1025
|
return direct;
|
|
934
1026
|
}
|
|
935
1027
|
if (provider) {
|
|
936
|
-
const aliasId = registry.aliasesByProvider[provider][idOrAlias];
|
|
1028
|
+
const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
|
|
937
1029
|
return aliasId ? registry.modelsById[aliasId] : void 0;
|
|
938
1030
|
}
|
|
939
1031
|
let resolved;
|
|
@@ -968,15 +1060,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
|
|
|
968
1060
|
return spec?.supportsFast === true;
|
|
969
1061
|
}
|
|
970
1062
|
function cloneAliases(aliasesByProvider) {
|
|
971
|
-
return
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
zai: { ...aliasesByProvider.zai },
|
|
978
|
-
xai: { ...aliasesByProvider.xai }
|
|
979
|
-
};
|
|
1063
|
+
return Object.fromEntries(
|
|
1064
|
+
Object.entries(aliasesByProvider).map(([provider, aliases]) => [
|
|
1065
|
+
provider,
|
|
1066
|
+
{ ...aliases }
|
|
1067
|
+
])
|
|
1068
|
+
);
|
|
980
1069
|
}
|
|
981
1070
|
function applyModelMetadata(registry, index) {
|
|
982
1071
|
const next = {
|
|
@@ -1069,6 +1158,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
1069
1158
|
...XAI_MODELS
|
|
1070
1159
|
]);
|
|
1071
1160
|
|
|
1161
|
+
// src/content/image-references.ts
|
|
1162
|
+
var REGISTRY = "[codelia.image.artifacts]";
|
|
1163
|
+
function isImageRegistry(message) {
|
|
1164
|
+
return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
|
|
1165
|
+
}
|
|
1166
|
+
function imageReferenceRegistry(messages) {
|
|
1167
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1168
|
+
for (const message of messages) {
|
|
1169
|
+
if (!("content" in message) || !Array.isArray(message.content)) continue;
|
|
1170
|
+
for (const part of message.content)
|
|
1171
|
+
if (part.type === "image_ref") {
|
|
1172
|
+
refs.delete(part.image_ref.artifact_id);
|
|
1173
|
+
refs.set(part.image_ref.artifact_id, part);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
const recent = [...refs.values()].slice(-16);
|
|
1177
|
+
return recent.length ? {
|
|
1178
|
+
role: "user",
|
|
1179
|
+
content: [
|
|
1180
|
+
{
|
|
1181
|
+
type: "text",
|
|
1182
|
+
text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
|
|
1183
|
+
`
|
|
1184
|
+
},
|
|
1185
|
+
...recent
|
|
1186
|
+
]
|
|
1187
|
+
} : null;
|
|
1188
|
+
}
|
|
1189
|
+
function describeImageReferences(messages) {
|
|
1190
|
+
return messages.map((message) => {
|
|
1191
|
+
if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
|
|
1192
|
+
return message;
|
|
1193
|
+
const content = message.content.map(
|
|
1194
|
+
(part) => part.type === "image_ref" ? {
|
|
1195
|
+
type: "text",
|
|
1196
|
+
text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
|
|
1197
|
+
} : part
|
|
1198
|
+
);
|
|
1199
|
+
return { ...message, content };
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1072
1203
|
// src/services/compaction/service.ts
|
|
1073
1204
|
var DEFAULT_THRESHOLD_RATIO = 0.85;
|
|
1074
1205
|
var DEFAULT_RETAIN_LAST_TURNS = 1;
|
|
@@ -1083,14 +1214,14 @@ var CompactionService = class _CompactionService {
|
|
|
1083
1214
|
this.config = _CompactionService.normalizeConfig(config);
|
|
1084
1215
|
this.modelRegistry = deps.modelRegistry;
|
|
1085
1216
|
}
|
|
1086
|
-
async shouldCompact(llm, usage) {
|
|
1217
|
+
async shouldCompact(llm, usage, estimatedInputTokens) {
|
|
1087
1218
|
if (!this.config.enabled) {
|
|
1088
1219
|
return false;
|
|
1089
1220
|
}
|
|
1090
1221
|
if (!this.config.auto) {
|
|
1091
1222
|
return false;
|
|
1092
1223
|
}
|
|
1093
|
-
if (!usage) {
|
|
1224
|
+
if (!usage && estimatedInputTokens === void 0) {
|
|
1094
1225
|
return false;
|
|
1095
1226
|
}
|
|
1096
1227
|
let contextLimit;
|
|
@@ -1100,7 +1231,7 @@ var CompactionService = class _CompactionService {
|
|
|
1100
1231
|
return false;
|
|
1101
1232
|
}
|
|
1102
1233
|
const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
|
|
1103
|
-
return usage
|
|
1234
|
+
return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
|
|
1104
1235
|
}
|
|
1105
1236
|
async compact(llm, messages, options) {
|
|
1106
1237
|
if (!this.config.enabled) {
|
|
@@ -1127,7 +1258,10 @@ var CompactionService = class _CompactionService {
|
|
|
1127
1258
|
try {
|
|
1128
1259
|
response = await llm.ainvoke(
|
|
1129
1260
|
{
|
|
1130
|
-
messages: [
|
|
1261
|
+
messages: describeImageReferences([
|
|
1262
|
+
...preparedMessages,
|
|
1263
|
+
interruptMessage
|
|
1264
|
+
]),
|
|
1131
1265
|
tools: null,
|
|
1132
1266
|
toolChoice: "none",
|
|
1133
1267
|
...options?.signal ? { signal: options.signal } : {},
|
|
@@ -1237,7 +1371,7 @@ var CompactionService = class _CompactionService {
|
|
|
1237
1371
|
);
|
|
1238
1372
|
const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
|
|
1239
1373
|
const conversationMessages = nonSystemMessages.filter(
|
|
1240
|
-
(message) => !isCompactionMemoryMessage(message)
|
|
1374
|
+
(message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
|
|
1241
1375
|
);
|
|
1242
1376
|
const tail = this.normalizeRetainedTail(
|
|
1243
1377
|
this.getLastTurns(conversationMessages, this.config.retainLastTurns)
|
|
@@ -1255,6 +1389,8 @@ var CompactionService = class _CompactionService {
|
|
|
1255
1389
|
content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
|
|
1256
1390
|
});
|
|
1257
1391
|
}
|
|
1392
|
+
const imageRegistry = imageReferenceRegistry(messages);
|
|
1393
|
+
if (imageRegistry) compacted.push(imageRegistry);
|
|
1258
1394
|
compacted.push(...tail);
|
|
1259
1395
|
return compacted;
|
|
1260
1396
|
}
|
|
@@ -1316,7 +1452,7 @@ var CompactionService = class _CompactionService {
|
|
|
1316
1452
|
return messages.slice(startIndex);
|
|
1317
1453
|
}
|
|
1318
1454
|
async resolveContextLimit(llm, usage) {
|
|
1319
|
-
const modelId = usage
|
|
1455
|
+
const modelId = usage?.model ?? llm.model;
|
|
1320
1456
|
const modelSpec = this.resolveModelSpecWithSnapshotFallback(
|
|
1321
1457
|
llm.provider,
|
|
1322
1458
|
modelId
|
|
@@ -1684,6 +1820,239 @@ var TokenUsageService = class {
|
|
|
1684
1820
|
}
|
|
1685
1821
|
};
|
|
1686
1822
|
|
|
1823
|
+
// src/agent/image-context.ts
|
|
1824
|
+
var import_image_size = require("image-size");
|
|
1825
|
+
|
|
1826
|
+
// src/llm/image-policy.ts
|
|
1827
|
+
function estimateImageTokens(provider, model, image) {
|
|
1828
|
+
let name = model.toLowerCase();
|
|
1829
|
+
if (provider === "openrouter") {
|
|
1830
|
+
if (name.startsWith("openai/")) provider = "openai";
|
|
1831
|
+
else if (name.startsWith("anthropic/")) provider = "anthropic";
|
|
1832
|
+
name = name.slice(name.indexOf("/") + 1);
|
|
1833
|
+
}
|
|
1834
|
+
const width = image.width;
|
|
1835
|
+
const height = image.height;
|
|
1836
|
+
const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
|
|
1837
|
+
const patches = (size, edge, budget, multiplier = 1) => {
|
|
1838
|
+
if (!dimensionsKnown)
|
|
1839
|
+
return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
|
|
1840
|
+
const scale = Math.min(1, edge / Math.max(width, height));
|
|
1841
|
+
return {
|
|
1842
|
+
tokens: Math.ceil(
|
|
1843
|
+
Math.min(
|
|
1844
|
+
budget,
|
|
1845
|
+
Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
|
|
1846
|
+
) * multiplier
|
|
1847
|
+
),
|
|
1848
|
+
method: "patch"
|
|
1849
|
+
};
|
|
1850
|
+
};
|
|
1851
|
+
if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
|
|
1852
|
+
name
|
|
1853
|
+
)) {
|
|
1854
|
+
const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
|
|
1855
|
+
name
|
|
1856
|
+
);
|
|
1857
|
+
return patches(
|
|
1858
|
+
28,
|
|
1859
|
+
highResolution ? 2576 : 1568,
|
|
1860
|
+
highResolution ? 4784 : 1568
|
|
1861
|
+
);
|
|
1862
|
+
}
|
|
1863
|
+
if (provider === "openai") {
|
|
1864
|
+
if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
|
|
1865
|
+
return patches(32, 512, 256, 1.2);
|
|
1866
|
+
if (/^gpt-6-astra(-|$)/.test(name))
|
|
1867
|
+
return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
|
|
1868
|
+
if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
|
|
1869
|
+
return patches(
|
|
1870
|
+
32,
|
|
1871
|
+
image.detail === "high" ? 2048 : 65535,
|
|
1872
|
+
image.detail === "high" ? 2500 : 3e4,
|
|
1873
|
+
1.2
|
|
1874
|
+
);
|
|
1875
|
+
if (/^gpt-5\.5(-|$)/.test(name))
|
|
1876
|
+
return patches(
|
|
1877
|
+
32,
|
|
1878
|
+
image.detail === "high" ? 2048 : 6e3,
|
|
1879
|
+
image.detail === "high" ? 2500 : 1e4,
|
|
1880
|
+
1.2
|
|
1881
|
+
);
|
|
1882
|
+
if (/^gpt-5\.4(-|$)/.test(name))
|
|
1883
|
+
return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
|
|
1884
|
+
if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
|
|
1885
|
+
if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
|
|
1886
|
+
if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
|
|
1887
|
+
const mini = name.startsWith("gpt-4o-mini");
|
|
1888
|
+
const base = mini ? 2833 : 85;
|
|
1889
|
+
const tile = mini ? 5667 : 170;
|
|
1890
|
+
if (image.detail === "low") return { tokens: base, method: "tile" };
|
|
1891
|
+
if (!dimensionsKnown)
|
|
1892
|
+
return { tokens: base + tile * 8, method: "fallback" };
|
|
1893
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
1894
|
+
const shortFit = 768 / (Math.min(width, height) * fit);
|
|
1895
|
+
return {
|
|
1896
|
+
tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
|
|
1897
|
+
method: "tile"
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
return { tokens: 1e4, method: "fallback" };
|
|
1902
|
+
}
|
|
1903
|
+
function imagePayloadLimit(provider) {
|
|
1904
|
+
if (provider === "anthropic") return 32e6;
|
|
1905
|
+
if (provider === "openai") return 512e6;
|
|
1906
|
+
return void 0;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// src/agent/image-context.ts
|
|
1910
|
+
function estimateImageContext(input, llm, resolveReferences = true) {
|
|
1911
|
+
let imageTokens = 0;
|
|
1912
|
+
let imageCount = 0;
|
|
1913
|
+
let fallbackCount = 0;
|
|
1914
|
+
let imageBytes = 0;
|
|
1915
|
+
const account = (image) => {
|
|
1916
|
+
const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
|
|
1917
|
+
if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
|
|
1918
|
+
throw new Error("Invalid model image-token estimate");
|
|
1919
|
+
imageTokens += estimate.tokens;
|
|
1920
|
+
imageCount++;
|
|
1921
|
+
if (estimate.method === "fallback") fallbackCount++;
|
|
1922
|
+
};
|
|
1923
|
+
const messages = input.messages.map((message) => {
|
|
1924
|
+
if (!Array.isArray(message.content)) return message;
|
|
1925
|
+
const registry = isImageRegistry(message);
|
|
1926
|
+
return {
|
|
1927
|
+
...message,
|
|
1928
|
+
content: message.content.map((part) => {
|
|
1929
|
+
if (part.type === "image_ref") {
|
|
1930
|
+
if (!registry && resolveReferences) {
|
|
1931
|
+
account({
|
|
1932
|
+
width: part.image_ref.width,
|
|
1933
|
+
height: part.image_ref.height,
|
|
1934
|
+
detail: part.detail
|
|
1935
|
+
});
|
|
1936
|
+
imageBytes += 4 * Math.ceil(
|
|
1937
|
+
(part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
|
|
1938
|
+
) + 64;
|
|
1939
|
+
}
|
|
1940
|
+
return {
|
|
1941
|
+
type: "text",
|
|
1942
|
+
text: `[Image ${part.image_ref.artifact_id}]`
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
if (part.type === "image_url") {
|
|
1946
|
+
let dimensions = {};
|
|
1947
|
+
const url = part.image_url.url;
|
|
1948
|
+
const comma = url.indexOf(",");
|
|
1949
|
+
if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
|
|
1950
|
+
try {
|
|
1951
|
+
dimensions = (0, import_image_size.imageSize)(
|
|
1952
|
+
Buffer.from(url.slice(comma + 1), "base64")
|
|
1953
|
+
);
|
|
1954
|
+
} catch {
|
|
1955
|
+
dimensions = {};
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
account({ ...dimensions, detail: part.image_url.detail });
|
|
1959
|
+
imageBytes += Buffer.byteLength(part.image_url.url);
|
|
1960
|
+
return { type: "text", text: "[Image]" };
|
|
1961
|
+
}
|
|
1962
|
+
if (part.type === "document")
|
|
1963
|
+
return {
|
|
1964
|
+
type: "text",
|
|
1965
|
+
text: "[Document: token estimate unavailable]"
|
|
1966
|
+
};
|
|
1967
|
+
return part;
|
|
1968
|
+
})
|
|
1969
|
+
};
|
|
1970
|
+
});
|
|
1971
|
+
const textBytes = Buffer.byteLength(
|
|
1972
|
+
JSON.stringify({
|
|
1973
|
+
messages,
|
|
1974
|
+
tools: input.tools ?? null,
|
|
1975
|
+
tool_choice: input.toolChoice
|
|
1976
|
+
})
|
|
1977
|
+
);
|
|
1978
|
+
const textTokens = Math.ceil(textBytes / 3);
|
|
1979
|
+
return {
|
|
1980
|
+
text_tokens: textTokens,
|
|
1981
|
+
image_tokens: imageTokens,
|
|
1982
|
+
total_tokens: textTokens + imageTokens,
|
|
1983
|
+
image_count: imageCount,
|
|
1984
|
+
fallback_image_count: fallbackCount,
|
|
1985
|
+
encoded_image_bytes: imageBytes,
|
|
1986
|
+
estimated_request_bytes: textBytes + imageBytes
|
|
1987
|
+
};
|
|
1988
|
+
}
|
|
1989
|
+
function validateImagePayload(estimate, llm) {
|
|
1990
|
+
const limit = imagePayloadLimit(llm.provider);
|
|
1991
|
+
if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
|
|
1992
|
+
throw new Error(
|
|
1993
|
+
`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.`
|
|
1994
|
+
);
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
// src/agent/image-input.ts
|
|
1998
|
+
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
1999
|
+
async function materializeImageReferences(messages, resolve, signal) {
|
|
2000
|
+
signal?.throwIfAborted();
|
|
2001
|
+
if (resolve) {
|
|
2002
|
+
for (const message of messages) {
|
|
2003
|
+
if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
|
|
2004
|
+
for (const part of message.content) {
|
|
2005
|
+
if (part.type !== "image_ref") continue;
|
|
2006
|
+
const size = part.image_ref.byte_size;
|
|
2007
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
|
|
2008
|
+
throw new Error(
|
|
2009
|
+
"Invalid or oversized image reference; model request was not sent."
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
const result = [];
|
|
2015
|
+
for (const message of messages) {
|
|
2016
|
+
if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
|
|
2017
|
+
result.push(message);
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
const registry = isImageRegistry(message);
|
|
2021
|
+
const content = [];
|
|
2022
|
+
for (const part of message.content) {
|
|
2023
|
+
if (part.type !== "image_ref") {
|
|
2024
|
+
content.push(part);
|
|
2025
|
+
continue;
|
|
2026
|
+
}
|
|
2027
|
+
signal?.throwIfAborted();
|
|
2028
|
+
if (!registry && resolve) {
|
|
2029
|
+
try {
|
|
2030
|
+
const image = await resolve(part.image_ref, signal);
|
|
2031
|
+
content.push(
|
|
2032
|
+
part.detail ? {
|
|
2033
|
+
...image,
|
|
2034
|
+
image_url: { ...image.image_url, detail: part.detail }
|
|
2035
|
+
} : image
|
|
2036
|
+
);
|
|
2037
|
+
signal?.throwIfAborted();
|
|
2038
|
+
continue;
|
|
2039
|
+
} catch {
|
|
2040
|
+
signal?.throwIfAborted();
|
|
2041
|
+
throw new Error(
|
|
2042
|
+
`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.`
|
|
2043
|
+
);
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
content.push({
|
|
2047
|
+
type: "text",
|
|
2048
|
+
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.]`
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
result.push({ ...message, content });
|
|
2052
|
+
}
|
|
2053
|
+
return result;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
1687
2056
|
// src/agent/model-context.ts
|
|
1688
2057
|
var calculateContextLeftPercent = ({
|
|
1689
2058
|
usage,
|
|
@@ -1765,16 +2134,16 @@ var collectModelOutput = (messages) => {
|
|
|
1765
2134
|
if (message.role === "reasoning") {
|
|
1766
2135
|
const raw = message.raw_item;
|
|
1767
2136
|
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1768
|
-
const
|
|
1769
|
-
const kind =
|
|
1770
|
-
const statusRaw =
|
|
2137
|
+
const record3 = raw;
|
|
2138
|
+
const kind = record3.type === "x_search_call" ? "x" : "web";
|
|
2139
|
+
const statusRaw = record3.status;
|
|
1771
2140
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1772
|
-
const action =
|
|
2141
|
+
const action = record3.action && typeof record3.action === "object" ? record3.action : null;
|
|
1773
2142
|
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1774
2143
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1775
2144
|
) : [];
|
|
1776
2145
|
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1777
|
-
const explicitId = typeof
|
|
2146
|
+
const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
|
|
1778
2147
|
let id = explicitId;
|
|
1779
2148
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1780
2149
|
if (!id) {
|
|
@@ -2044,6 +2413,7 @@ var Agent = class {
|
|
|
2044
2413
|
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
2045
2414
|
history;
|
|
2046
2415
|
usageService;
|
|
2416
|
+
imageUsageBaseline;
|
|
2047
2417
|
constructor(options) {
|
|
2048
2418
|
this.llm = options.llm;
|
|
2049
2419
|
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
@@ -2096,13 +2466,15 @@ var Agent = class {
|
|
|
2096
2466
|
}
|
|
2097
2467
|
replaceHistoryMessages(messages) {
|
|
2098
2468
|
this.history.replaceViewMessages(messages);
|
|
2469
|
+
this.imageUsageBaseline = void 0;
|
|
2099
2470
|
}
|
|
2100
2471
|
async *checkAndCompact(signal, options = {}) {
|
|
2101
2472
|
throwIfAborted(signal);
|
|
2102
2473
|
await this.trimToolOutputs();
|
|
2103
2474
|
const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
|
|
2104
2475
|
this.llm,
|
|
2105
|
-
this.usageService.getLastUsage()
|
|
2476
|
+
this.usageService.getLastUsage(),
|
|
2477
|
+
options.estimatedInputTokens
|
|
2106
2478
|
);
|
|
2107
2479
|
if (shouldCompact && this.compactionService) {
|
|
2108
2480
|
throwIfAborted(signal);
|
|
@@ -2123,6 +2495,7 @@ var Agent = class {
|
|
|
2123
2495
|
this.usageService.updateUsageSummary(usage);
|
|
2124
2496
|
if (compacted && compactedMessages) {
|
|
2125
2497
|
this.history.replaceViewMessages(compactedMessages);
|
|
2498
|
+
this.imageUsageBaseline = void 0;
|
|
2126
2499
|
}
|
|
2127
2500
|
if (compacted || options.force) {
|
|
2128
2501
|
await this.llm.onHistoryCompacted?.(invokeContext);
|
|
@@ -2181,9 +2554,13 @@ var Agent = class {
|
|
|
2181
2554
|
const runId = session?.run_id?.trim();
|
|
2182
2555
|
return runId && runId.length > 0 ? runId : void 0;
|
|
2183
2556
|
}
|
|
2184
|
-
buildInvokeContext(session) {
|
|
2557
|
+
buildInvokeContext(session, turnKey) {
|
|
2185
2558
|
const sessionKey = this.resolveSessionKey(session);
|
|
2186
|
-
|
|
2559
|
+
const turn = turnKey ?? session?.run_id;
|
|
2560
|
+
return sessionKey || turn ? {
|
|
2561
|
+
...sessionKey ? { sessionKey } : {},
|
|
2562
|
+
...turn ? { turnKey: turn } : {}
|
|
2563
|
+
} : void 0;
|
|
2187
2564
|
}
|
|
2188
2565
|
recordLlmResponse(session, seq, response) {
|
|
2189
2566
|
if (!session || seq === null) return;
|
|
@@ -2194,6 +2571,7 @@ var Agent = class {
|
|
|
2194
2571
|
seq,
|
|
2195
2572
|
output: {
|
|
2196
2573
|
messages: response.messages,
|
|
2574
|
+
...response.timing ? { timing: response.timing } : {},
|
|
2197
2575
|
usage: response.usage ?? null,
|
|
2198
2576
|
stop_reason: response.stop_reason ?? null,
|
|
2199
2577
|
provider_meta: response.provider_meta ?? null
|
|
@@ -2201,19 +2579,43 @@ var Agent = class {
|
|
|
2201
2579
|
});
|
|
2202
2580
|
}
|
|
2203
2581
|
async *invokeModelWithRetry(input, context, signal) {
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2582
|
+
const estimate = estimateImageContext(
|
|
2583
|
+
input,
|
|
2584
|
+
this.llm,
|
|
2585
|
+
Boolean(this.services.resolveImage)
|
|
2586
|
+
);
|
|
2587
|
+
validateImagePayload(estimate, this.llm);
|
|
2588
|
+
const messages = await materializeImageReferences(
|
|
2589
|
+
input.messages,
|
|
2590
|
+
this.services.resolveImage,
|
|
2591
|
+
signal
|
|
2592
|
+
);
|
|
2593
|
+
const response = yield* withProviderStatus(
|
|
2594
|
+
(onProviderStatus, progressSignal) => invokeWithRetry({
|
|
2595
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2596
|
+
{
|
|
2597
|
+
...input,
|
|
2598
|
+
messages,
|
|
2599
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2600
|
+
},
|
|
2601
|
+
{ ...context, onProviderStatus }
|
|
2602
|
+
),
|
|
2603
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2604
|
+
policy: resolveLlmRetryPolicy({
|
|
2605
|
+
...this.llmRetryPolicy,
|
|
2606
|
+
...this.llm.retryPolicy
|
|
2607
|
+
}),
|
|
2608
|
+
signal: progressSignal,
|
|
2609
|
+
dependencies: this.llmRetryDependencies
|
|
2610
|
+
}),
|
|
2611
|
+
signal
|
|
2612
|
+
);
|
|
2613
|
+
this.imageUsageBaseline = response.usage ? {
|
|
2614
|
+
messages: input.messages.slice(),
|
|
2615
|
+
estimated: estimate.total_tokens,
|
|
2616
|
+
observed: response.usage.input_tokens
|
|
2617
|
+
} : void 0;
|
|
2618
|
+
return response;
|
|
2217
2619
|
}
|
|
2218
2620
|
async run(message, options = {}) {
|
|
2219
2621
|
let finalResponse = "";
|
|
@@ -2251,6 +2653,7 @@ var Agent = class {
|
|
|
2251
2653
|
for (const content of messages) this.history.enqueueUserMessage(content);
|
|
2252
2654
|
return messages;
|
|
2253
2655
|
};
|
|
2656
|
+
const turnKey = session?.run_id ?? (0, import_node_crypto.randomUUID)();
|
|
2254
2657
|
let iterations = 0;
|
|
2255
2658
|
const runTools = [...this.tools, ...options.tools ?? []];
|
|
2256
2659
|
const runToolChoice = options.toolChoice ?? this.toolChoice;
|
|
@@ -2261,11 +2664,27 @@ var Agent = class {
|
|
|
2261
2664
|
yield { type: "hidden_user_message", content };
|
|
2262
2665
|
await this.trimToolOutputs();
|
|
2263
2666
|
throwIfAborted(signal);
|
|
2264
|
-
|
|
2667
|
+
let invokeInput = this.history.prepareInvokeInput({
|
|
2265
2668
|
tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
|
|
2266
2669
|
toolChoice: runToolChoice
|
|
2267
2670
|
});
|
|
2268
|
-
const
|
|
2671
|
+
const imageEstimate = estimateImageContext(
|
|
2672
|
+
invokeInput,
|
|
2673
|
+
this.llm,
|
|
2674
|
+
Boolean(this.services.resolveImage)
|
|
2675
|
+
);
|
|
2676
|
+
if (imageEstimate.image_count > 0) {
|
|
2677
|
+
const baseline = this.imageUsageBaseline;
|
|
2678
|
+
const estimatedInputTokens = baseline && baseline.messages.every(
|
|
2679
|
+
(message2, index) => invokeInput.messages[index] === message2
|
|
2680
|
+
) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
|
|
2681
|
+
yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
|
|
2682
|
+
invokeInput = this.history.prepareInvokeInput({
|
|
2683
|
+
tools: invokeInput.tools,
|
|
2684
|
+
toolChoice: runToolChoice
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2269
2688
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
2270
2689
|
const response = yield* this.invokeModelWithRetry(
|
|
2271
2690
|
invokeInput,
|
|
@@ -2490,7 +2909,11 @@ var Agent = class {
|
|
|
2490
2909
|
yield* this.checkAndCompact(signal, { session });
|
|
2491
2910
|
}
|
|
2492
2911
|
if (signal?.aborted) throw createAbortError2();
|
|
2493
|
-
const finalResponse = await this.generateFinalResponse(
|
|
2912
|
+
const finalResponse = await this.generateFinalResponse(
|
|
2913
|
+
session,
|
|
2914
|
+
signal,
|
|
2915
|
+
turnKey
|
|
2916
|
+
);
|
|
2494
2917
|
const finalResponseEvent = {
|
|
2495
2918
|
type: "final",
|
|
2496
2919
|
termination_reason: "max_steps",
|
|
@@ -2499,7 +2922,7 @@ var Agent = class {
|
|
|
2499
2922
|
yield finalResponseEvent;
|
|
2500
2923
|
return;
|
|
2501
2924
|
}
|
|
2502
|
-
async generateFinalResponse(session, signal) {
|
|
2925
|
+
async generateFinalResponse(session, signal, turnKey) {
|
|
2503
2926
|
const summaryMessage = {
|
|
2504
2927
|
role: "user",
|
|
2505
2928
|
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.`
|
|
@@ -2512,11 +2935,24 @@ var Agent = class {
|
|
|
2512
2935
|
// no tools are allowed at this point
|
|
2513
2936
|
toolChoice: "none"
|
|
2514
2937
|
};
|
|
2515
|
-
const invokeContext = this.buildInvokeContext(session);
|
|
2938
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2516
2939
|
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
2940
|
+
validateImagePayload(
|
|
2941
|
+
estimateImageContext(
|
|
2942
|
+
input,
|
|
2943
|
+
this.llm,
|
|
2944
|
+
Boolean(this.services.resolveImage)
|
|
2945
|
+
),
|
|
2946
|
+
this.llm
|
|
2947
|
+
);
|
|
2517
2948
|
const summary = await this.llm.ainvoke(
|
|
2518
2949
|
{
|
|
2519
2950
|
...input,
|
|
2951
|
+
messages: await materializeImageReferences(
|
|
2952
|
+
input.messages,
|
|
2953
|
+
this.services.resolveImage,
|
|
2954
|
+
signal
|
|
2955
|
+
),
|
|
2520
2956
|
...signal ? { signal } : {}
|
|
2521
2957
|
},
|
|
2522
2958
|
invokeContext
|
|
@@ -2537,8 +2973,90 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
2537
2973
|
}
|
|
2538
2974
|
};
|
|
2539
2975
|
|
|
2976
|
+
// src/llm/stream-timing.ts
|
|
2977
|
+
var record = (value) => value !== null && typeof value === "object" ? value : void 0;
|
|
2978
|
+
var nonempty = (value) => typeof value === "string" && value.length > 0;
|
|
2979
|
+
var responseOutputDeltas = /* @__PURE__ */ new Set([
|
|
2980
|
+
"response.output_text.delta",
|
|
2981
|
+
"response.refusal.delta",
|
|
2982
|
+
"response.function_call_arguments.delta",
|
|
2983
|
+
"response.custom_tool_call_input.delta",
|
|
2984
|
+
"response.reasoning_text.delta",
|
|
2985
|
+
"response.reasoning_summary_text.delta"
|
|
2986
|
+
]);
|
|
2987
|
+
var LlmStreamTiming = class {
|
|
2988
|
+
constructor(nowMs = () => performance.now()) {
|
|
2989
|
+
this.nowMs = nowMs;
|
|
2990
|
+
this.startedAt = nowMs();
|
|
2991
|
+
}
|
|
2992
|
+
nowMs;
|
|
2993
|
+
startedAt;
|
|
2994
|
+
firstOutputAt;
|
|
2995
|
+
reasoningStartedAt;
|
|
2996
|
+
completedAt;
|
|
2997
|
+
observeOutput() {
|
|
2998
|
+
if (this.completedAt === void 0 && this.firstOutputAt === void 0)
|
|
2999
|
+
this.firstOutputAt = this.nowMs();
|
|
3000
|
+
}
|
|
3001
|
+
complete() {
|
|
3002
|
+
this.completedAt ??= this.nowMs();
|
|
3003
|
+
}
|
|
3004
|
+
observeResponsesEvent(event) {
|
|
3005
|
+
const value = record(event);
|
|
3006
|
+
if (!value) return;
|
|
3007
|
+
if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
|
|
3008
|
+
this.reasoningStartedAt ??= this.nowMs();
|
|
3009
|
+
if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
|
|
3010
|
+
this.observeOutput();
|
|
3011
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
|
|
3012
|
+
this.complete();
|
|
3013
|
+
}
|
|
3014
|
+
observeChatChunk(chunk) {
|
|
3015
|
+
const choices = record(chunk)?.choices;
|
|
3016
|
+
if (!Array.isArray(choices)) return;
|
|
3017
|
+
for (const choice of choices) {
|
|
3018
|
+
const delta = record(record(choice)?.delta);
|
|
3019
|
+
if (!delta) continue;
|
|
3020
|
+
if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
|
|
3021
|
+
(tool) => nonempty(record(record(tool)?.function)?.arguments)
|
|
3022
|
+
))
|
|
3023
|
+
this.observeOutput();
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
observeAnthropicEvent(event) {
|
|
3027
|
+
const value = record(event);
|
|
3028
|
+
if (!value) return;
|
|
3029
|
+
const delta = record(value.delta);
|
|
3030
|
+
if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
|
|
3031
|
+
this.observeOutput();
|
|
3032
|
+
if (value.type === "message_stop") this.complete();
|
|
3033
|
+
}
|
|
3034
|
+
finish() {
|
|
3035
|
+
this.complete();
|
|
3036
|
+
if (this.firstOutputAt === void 0) return void 0;
|
|
3037
|
+
const first = this.firstOutputAt - this.startedAt;
|
|
3038
|
+
const start = Math.min(
|
|
3039
|
+
this.firstOutputAt,
|
|
3040
|
+
this.reasoningStartedAt ?? this.firstOutputAt
|
|
3041
|
+
);
|
|
3042
|
+
const generation = this.completedAt - start;
|
|
3043
|
+
if (![first, generation, start - this.startedAt].every(
|
|
3044
|
+
(ms) => Number.isFinite(ms) && ms >= 0
|
|
3045
|
+
))
|
|
3046
|
+
return void 0;
|
|
3047
|
+
return {
|
|
3048
|
+
time_to_first_token_ms: first,
|
|
3049
|
+
generation_duration_ms: generation,
|
|
3050
|
+
...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
|
|
3051
|
+
generation_start_ms: start - this.startedAt,
|
|
3052
|
+
generation_start_source: "reasoning_item"
|
|
3053
|
+
} : {}
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
};
|
|
3057
|
+
|
|
2540
3058
|
// src/llm/anthropic/chat.ts
|
|
2541
|
-
var
|
|
3059
|
+
var import_node_crypto2 = require("crypto");
|
|
2542
3060
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
2543
3061
|
|
|
2544
3062
|
// src/llm/anthropic/failure.ts
|
|
@@ -2663,6 +3181,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
|
|
|
2663
3181
|
};
|
|
2664
3182
|
|
|
2665
3183
|
// src/types/llm/guards.ts
|
|
3184
|
+
var import_shared_types = require("@codelia/shared-types");
|
|
2666
3185
|
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2667
3186
|
function isTextPart(value) {
|
|
2668
3187
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2691,7 +3210,19 @@ function isOtherPart(value) {
|
|
|
2691
3210
|
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2692
3211
|
}
|
|
2693
3212
|
function isContentPart(value) {
|
|
2694
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3213
|
+
return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3214
|
+
}
|
|
3215
|
+
function isImageRefPart(value) {
|
|
3216
|
+
if (!value || typeof value !== "object") return false;
|
|
3217
|
+
const v = value;
|
|
3218
|
+
if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
|
|
3219
|
+
return false;
|
|
3220
|
+
const r = v.image_ref;
|
|
3221
|
+
return (r.model_view === void 0 || (0, import_shared_types.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(
|
|
3222
|
+
String(r.media_type)
|
|
3223
|
+
) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
|
|
3224
|
+
(n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
|
|
3225
|
+
) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
|
|
2695
3226
|
}
|
|
2696
3227
|
function isToolResult(value) {
|
|
2697
3228
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2795,6 +3326,15 @@ var toContentBlocks = (content) => {
|
|
|
2795
3326
|
}
|
|
2796
3327
|
};
|
|
2797
3328
|
}
|
|
3329
|
+
if (URL.canParse(part.image_url.url)) {
|
|
3330
|
+
const url = new URL(part.image_url.url);
|
|
3331
|
+
if (url.protocol === "https:" || url.protocol === "http:") {
|
|
3332
|
+
return {
|
|
3333
|
+
type: "image",
|
|
3334
|
+
source: { type: "url", url: part.image_url.url }
|
|
3335
|
+
};
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
2798
3338
|
return toTextBlock(part.image_url.url);
|
|
2799
3339
|
}
|
|
2800
3340
|
case "document":
|
|
@@ -3212,20 +3752,27 @@ var ChatAnthropic = class {
|
|
|
3212
3752
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
3213
3753
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
3214
3754
|
const requestOptions = signal ? { signal } : void 0;
|
|
3215
|
-
const
|
|
3755
|
+
const timing = new LlmStreamTiming();
|
|
3756
|
+
const stream = this.fastMode ? this.client.beta.messages.stream(
|
|
3216
3757
|
request,
|
|
3217
3758
|
requestOptions
|
|
3218
|
-
) :
|
|
3759
|
+
) : this.client.messages.stream(
|
|
3219
3760
|
request,
|
|
3220
3761
|
requestOptions
|
|
3221
3762
|
);
|
|
3763
|
+
for await (const event of stream) timing.observeAnthropicEvent(event);
|
|
3764
|
+
const response = await stream.finalMessage();
|
|
3765
|
+
const measuredTiming = timing.finish();
|
|
3222
3766
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3223
|
-
return
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3767
|
+
return {
|
|
3768
|
+
...toChatInvokeCompletion(response, {
|
|
3769
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
3770
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
3771
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
|
|
3772
|
+
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
|
|
3773
|
+
}),
|
|
3774
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
3775
|
+
};
|
|
3229
3776
|
}
|
|
3230
3777
|
nextDebugInvokeSeq() {
|
|
3231
3778
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -3238,9 +3785,9 @@ var ChatAnthropic = class {
|
|
|
3238
3785
|
return;
|
|
3239
3786
|
}
|
|
3240
3787
|
const payload = safeJsonStringify(request);
|
|
3241
|
-
const hash = (0,
|
|
3242
|
-
const toolsHash = (0,
|
|
3243
|
-
const systemHash = (0,
|
|
3788
|
+
const hash = (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3789
|
+
const toolsHash = (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
3790
|
+
const systemHash = (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
3244
3791
|
const previous = this.lastDebugRequestPayload;
|
|
3245
3792
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3246
3793
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -3310,7 +3857,7 @@ var ChatAnthropic = class {
|
|
|
3310
3857
|
};
|
|
3311
3858
|
|
|
3312
3859
|
// src/llm/moonshot/chat.ts
|
|
3313
|
-
var
|
|
3860
|
+
var import_node_crypto3 = require("crypto");
|
|
3314
3861
|
var import_openai3 = __toESM(require("openai"), 1);
|
|
3315
3862
|
|
|
3316
3863
|
// src/llm/moonshot/failure.ts
|
|
@@ -3713,6 +4260,7 @@ var ChatMoonshot = class {
|
|
|
3713
4260
|
const seq = this.nextDebugInvokeSeq();
|
|
3714
4261
|
await this.debugRequestIfEnabled(request, seq);
|
|
3715
4262
|
const client = new import_openai3.default({ apiKey: this.apiKey, ...this.clientOptions });
|
|
4263
|
+
const timing = new LlmStreamTiming();
|
|
3716
4264
|
const accumulator = createMoonshotStreamAccumulator();
|
|
3717
4265
|
try {
|
|
3718
4266
|
const stream = await client.chat.completions.create(
|
|
@@ -3720,6 +4268,7 @@ var ChatMoonshot = class {
|
|
|
3720
4268
|
{ signal: input.signal }
|
|
3721
4269
|
);
|
|
3722
4270
|
for await (const chunk of stream) {
|
|
4271
|
+
timing.observeChatChunk(chunk);
|
|
3723
4272
|
appendMoonshotChatCompletionChunk(
|
|
3724
4273
|
accumulator,
|
|
3725
4274
|
chunk
|
|
@@ -3732,11 +4281,15 @@ var ChatMoonshot = class {
|
|
|
3732
4281
|
{ cause: error }
|
|
3733
4282
|
);
|
|
3734
4283
|
}
|
|
4284
|
+
const measuredTiming = timing.finish();
|
|
3735
4285
|
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3736
|
-
return
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
4286
|
+
return {
|
|
4287
|
+
...toMoonshotChatInvokeCompletion(accumulator, {
|
|
4288
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
4289
|
+
reasoningFallback: this.reasoningLevelRequested !== "max"
|
|
4290
|
+
}),
|
|
4291
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
4292
|
+
};
|
|
3740
4293
|
}
|
|
3741
4294
|
nextDebugInvokeSeq() {
|
|
3742
4295
|
this.debugInvokeSeq += 1;
|
|
@@ -3746,7 +4299,7 @@ var ChatMoonshot = class {
|
|
|
3746
4299
|
const settings = getProviderLogSettings();
|
|
3747
4300
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
3748
4301
|
const payload = safeJsonStringify(request);
|
|
3749
|
-
const hash = (0,
|
|
4302
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3750
4303
|
const previous = this.lastDebugRequestPayload;
|
|
3751
4304
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3752
4305
|
if (settings.enabled) {
|
|
@@ -3802,9 +4355,183 @@ var ChatMoonshot = class {
|
|
|
3802
4355
|
};
|
|
3803
4356
|
|
|
3804
4357
|
// src/llm/openai/chat.ts
|
|
3805
|
-
var
|
|
4358
|
+
var import_node_crypto5 = require("crypto");
|
|
4359
|
+
var import_openai5 = __toESM(require("openai"), 1);
|
|
4360
|
+
|
|
4361
|
+
// src/llm/openai/http-transport.ts
|
|
3806
4362
|
var import_openai4 = __toESM(require("openai"), 1);
|
|
3807
4363
|
|
|
4364
|
+
// src/llm/openai/codex-metadata.ts
|
|
4365
|
+
var import_node_crypto4 = require("crypto");
|
|
4366
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
4367
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
|
|
4368
|
+
var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
|
|
4369
|
+
var headerValue = (headers, name) => {
|
|
4370
|
+
const entries = record2(headers);
|
|
4371
|
+
const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
4372
|
+
return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
|
|
4373
|
+
};
|
|
4374
|
+
var isCodexBackend = (baseURL) => {
|
|
4375
|
+
try {
|
|
4376
|
+
const url = new URL(baseURL);
|
|
4377
|
+
return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
|
|
4378
|
+
} catch {
|
|
4379
|
+
return false;
|
|
4380
|
+
}
|
|
4381
|
+
};
|
|
4382
|
+
var CodexTurnState = class {
|
|
4383
|
+
owner;
|
|
4384
|
+
value;
|
|
4385
|
+
invalidated = false;
|
|
4386
|
+
bindAuth(headers) {
|
|
4387
|
+
const authorization = headers.get("authorization") ?? "";
|
|
4388
|
+
let identity = authorization;
|
|
4389
|
+
try {
|
|
4390
|
+
const claims = record2(
|
|
4391
|
+
JSON.parse(
|
|
4392
|
+
Buffer.from(
|
|
4393
|
+
authorization.replace(/^Bearer /i, "").split(".")[1],
|
|
4394
|
+
"base64url"
|
|
4395
|
+
).toString("utf8")
|
|
4396
|
+
)
|
|
4397
|
+
);
|
|
4398
|
+
if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
|
|
4399
|
+
const account = record2(
|
|
4400
|
+
claims["https://api.openai.com/auth"]
|
|
4401
|
+
)?.chatgpt_account_id;
|
|
4402
|
+
identity = JSON.stringify([
|
|
4403
|
+
claims.iss,
|
|
4404
|
+
claims.sub,
|
|
4405
|
+
typeof claims.client_id === "string" ? claims.client_id : null,
|
|
4406
|
+
typeof account === "string" ? account : null
|
|
4407
|
+
]);
|
|
4408
|
+
}
|
|
4409
|
+
} catch {
|
|
4410
|
+
}
|
|
4411
|
+
const owner = (0, import_node_crypto4.createHash)("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
|
|
4412
|
+
const changed = this.owner !== void 0 && this.owner !== owner;
|
|
4413
|
+
if (changed) {
|
|
4414
|
+
this.value = void 0;
|
|
4415
|
+
this.invalidated = true;
|
|
4416
|
+
}
|
|
4417
|
+
this.owner = owner;
|
|
4418
|
+
return this.invalidated;
|
|
4419
|
+
}
|
|
4420
|
+
observe(value) {
|
|
4421
|
+
if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
|
|
4422
|
+
this.value = value;
|
|
4423
|
+
}
|
|
4424
|
+
requestHeaders() {
|
|
4425
|
+
return this.value ? { "x-codex-turn-state": this.value } : {};
|
|
4426
|
+
}
|
|
4427
|
+
};
|
|
4428
|
+
var CodexMetadataCollector = class {
|
|
4429
|
+
constructor(routing, onStatus) {
|
|
4430
|
+
this.routing = routing;
|
|
4431
|
+
this.onStatus = onStatus;
|
|
4432
|
+
}
|
|
4433
|
+
routing;
|
|
4434
|
+
onStatus;
|
|
4435
|
+
summary = {};
|
|
4436
|
+
outputStarted = false;
|
|
4437
|
+
fallbackModel;
|
|
4438
|
+
verificationNotified = false;
|
|
4439
|
+
beginAttempt() {
|
|
4440
|
+
this.clearBuffering();
|
|
4441
|
+
for (const key of Object.keys(this.summary))
|
|
4442
|
+
delete this.summary[key];
|
|
4443
|
+
this.outputStarted = false;
|
|
4444
|
+
this.fallbackModel = void 0;
|
|
4445
|
+
}
|
|
4446
|
+
observeHeaders(headers) {
|
|
4447
|
+
this.routing?.observe(headers.get("x-codex-turn-state"));
|
|
4448
|
+
const model = identifier(
|
|
4449
|
+
headers.get("openai-model") ?? headers.get("x-openai-model")
|
|
4450
|
+
);
|
|
4451
|
+
if (model) this.summary.server_model = model;
|
|
4452
|
+
this.fallbackModel = identifier(
|
|
4453
|
+
headers.get("x-codex-safety-buffering-faster-model")
|
|
4454
|
+
);
|
|
4455
|
+
}
|
|
4456
|
+
observeEvent(event) {
|
|
4457
|
+
const value = record2(event);
|
|
4458
|
+
if (!value) return;
|
|
4459
|
+
const response = record2(value.response);
|
|
4460
|
+
const model = identifier(
|
|
4461
|
+
headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
|
|
4462
|
+
);
|
|
4463
|
+
if (model) this.summary.server_model = model;
|
|
4464
|
+
const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
|
|
4465
|
+
if (value.type === "response.metadata")
|
|
4466
|
+
this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
|
|
4467
|
+
const verifications = metadata?.openai_verification_recommendation;
|
|
4468
|
+
if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
|
|
4469
|
+
this.summary.model_verifications = ["trusted_access_for_cyber"];
|
|
4470
|
+
if (!this.verificationNotified) {
|
|
4471
|
+
this.verificationNotified = true;
|
|
4472
|
+
this.emit({
|
|
4473
|
+
type: "llm.status",
|
|
4474
|
+
provider: "openai",
|
|
4475
|
+
kind: "verification",
|
|
4476
|
+
verification: "trusted_access_for_cyber"
|
|
4477
|
+
});
|
|
4478
|
+
}
|
|
4479
|
+
}
|
|
4480
|
+
if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
|
|
4481
|
+
this.summary.moderation_metadata_present = true;
|
|
4482
|
+
const buffering = record2(
|
|
4483
|
+
value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
|
|
4484
|
+
);
|
|
4485
|
+
if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
|
|
4486
|
+
const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
|
|
4487
|
+
const wasActive = this.summary.safety_buffering?.active;
|
|
4488
|
+
this.summary.safety_buffering = {
|
|
4489
|
+
active: !this.outputStarted,
|
|
4490
|
+
use_case_count: buffering.use_cases.length,
|
|
4491
|
+
reason_count: buffering.reasons.length,
|
|
4492
|
+
...faster ? { faster_model: faster } : {}
|
|
4493
|
+
};
|
|
4494
|
+
if (!this.outputStarted && !wasActive)
|
|
4495
|
+
this.emit({
|
|
4496
|
+
type: "llm.status",
|
|
4497
|
+
provider: "openai",
|
|
4498
|
+
kind: "buffering",
|
|
4499
|
+
active: true,
|
|
4500
|
+
...faster ? { faster_model: faster } : {}
|
|
4501
|
+
});
|
|
4502
|
+
}
|
|
4503
|
+
if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
|
|
4504
|
+
this.outputStarted = true;
|
|
4505
|
+
this.clearBuffering();
|
|
4506
|
+
}
|
|
4507
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
|
|
4508
|
+
this.clearBuffering();
|
|
4509
|
+
}
|
|
4510
|
+
finish() {
|
|
4511
|
+
this.clearBuffering();
|
|
4512
|
+
}
|
|
4513
|
+
snapshot() {
|
|
4514
|
+
return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
|
|
4515
|
+
}
|
|
4516
|
+
clearBuffering() {
|
|
4517
|
+
if (this.summary.safety_buffering?.active) {
|
|
4518
|
+
this.summary.safety_buffering.active = false;
|
|
4519
|
+
this.emit({
|
|
4520
|
+
type: "llm.status",
|
|
4521
|
+
provider: "openai",
|
|
4522
|
+
kind: "buffering",
|
|
4523
|
+
active: false
|
|
4524
|
+
});
|
|
4525
|
+
}
|
|
4526
|
+
}
|
|
4527
|
+
emit(event) {
|
|
4528
|
+
try {
|
|
4529
|
+
this.onStatus?.(event);
|
|
4530
|
+
} catch {
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
};
|
|
4534
|
+
|
|
3808
4535
|
// src/llm/openai/response-utils.ts
|
|
3809
4536
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
3810
4537
|
var stringifyUnknown3 = (value) => {
|
|
@@ -3846,12 +4573,12 @@ var extractOutputText = (items) => {
|
|
|
3846
4573
|
}
|
|
3847
4574
|
return texts.join("");
|
|
3848
4575
|
};
|
|
3849
|
-
var getRecordString = (
|
|
3850
|
-
const value =
|
|
4576
|
+
var getRecordString = (record3, key) => {
|
|
4577
|
+
const value = record3[key];
|
|
3851
4578
|
return typeof value === "string" ? value : void 0;
|
|
3852
4579
|
};
|
|
3853
|
-
var getRecordNumber = (
|
|
3854
|
-
const value =
|
|
4580
|
+
var getRecordNumber = (record3, key) => {
|
|
4581
|
+
const value = record3[key];
|
|
3855
4582
|
return typeof value === "number" ? value : void 0;
|
|
3856
4583
|
};
|
|
3857
4584
|
var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
|
|
@@ -3861,6 +4588,10 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3861
4588
|
sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
|
|
3862
4589
|
};
|
|
3863
4590
|
const eventRecord = event;
|
|
4591
|
+
const metadata = new CodexMetadataCollector();
|
|
4592
|
+
metadata.observeEvent(event);
|
|
4593
|
+
const summary = metadata.snapshot();
|
|
4594
|
+
if (summary) payload.metadata_summary = summary;
|
|
3864
4595
|
const outputIndex = getRecordNumber(eventRecord, "output_index");
|
|
3865
4596
|
if (outputIndex !== void 0) {
|
|
3866
4597
|
payload.output_index = outputIndex;
|
|
@@ -4014,6 +4745,9 @@ var OpenAiResponseAccumulator = class {
|
|
|
4014
4745
|
terminalResponse = null;
|
|
4015
4746
|
outputItems = [];
|
|
4016
4747
|
observeEvent(event) {
|
|
4748
|
+
const type = event.type;
|
|
4749
|
+
if (type === "response.metadata" || type === "codex.response.metadata")
|
|
4750
|
+
return;
|
|
4017
4751
|
switch (event.type) {
|
|
4018
4752
|
case "response.created":
|
|
4019
4753
|
case "response.queued":
|
|
@@ -4365,22 +5099,64 @@ var OpenAiResponseAccumulator = class {
|
|
|
4365
5099
|
};
|
|
4366
5100
|
|
|
4367
5101
|
// src/llm/openai/http-transport.ts
|
|
4368
|
-
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
|
|
5102
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
|
|
4369
5103
|
const streamRequest = {
|
|
4370
5104
|
...request,
|
|
4371
5105
|
stream: true
|
|
4372
5106
|
};
|
|
4373
|
-
const
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
5107
|
+
const options = signal || sessionIdHeader ? {
|
|
5108
|
+
...signal ? { signal } : {},
|
|
5109
|
+
...sessionIdHeader ? {
|
|
5110
|
+
headers: {
|
|
5111
|
+
session_id: sessionIdHeader
|
|
5112
|
+
}
|
|
5113
|
+
} : {}
|
|
5114
|
+
} : void 0;
|
|
5115
|
+
if (isCodexBackend(client.baseURL)) {
|
|
5116
|
+
codex?.metadata.beginAttempt();
|
|
5117
|
+
const sourceFetch = client.fetch;
|
|
5118
|
+
let ownershipError;
|
|
5119
|
+
const requestClient = codex ? client.withOptions({
|
|
5120
|
+
fetch: async (input, init) => {
|
|
5121
|
+
const headers = new Headers(init?.headers);
|
|
5122
|
+
if (codex.routing?.bindAuth(headers)) {
|
|
5123
|
+
ownershipError = createProviderValidationError(
|
|
5124
|
+
"openai",
|
|
5125
|
+
"OpenAI authentication changed; start a new run"
|
|
5126
|
+
);
|
|
5127
|
+
throw ownershipError;
|
|
4380
5128
|
}
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
5129
|
+
for (const [key, value] of Object.entries(
|
|
5130
|
+
codex.routing?.requestHeaders() ?? {}
|
|
5131
|
+
))
|
|
5132
|
+
headers.set(key, value);
|
|
5133
|
+
const response = await sourceFetch(input, { ...init, headers });
|
|
5134
|
+
codex.metadata.observeHeaders(response.headers);
|
|
5135
|
+
return response;
|
|
5136
|
+
}
|
|
5137
|
+
}) : client;
|
|
5138
|
+
const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
|
|
5139
|
+
throw ownershipError ?? error;
|
|
5140
|
+
});
|
|
5141
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
5142
|
+
for await (const event of stream2) {
|
|
5143
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5144
|
+
codex?.metadata.observeEvent(event);
|
|
5145
|
+
await onEvent?.(event);
|
|
5146
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5147
|
+
if (event.type === "response.failed") {
|
|
5148
|
+
throw event.response.error ?? new Error("OpenAI stream failed");
|
|
5149
|
+
}
|
|
5150
|
+
if (event.type === "error") throw event;
|
|
5151
|
+
accumulator.observeEvent(event);
|
|
5152
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
5153
|
+
return accumulator.buildResponse(event.response);
|
|
5154
|
+
}
|
|
5155
|
+
}
|
|
5156
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5157
|
+
throw new Error("OpenAI stream ended without a terminal response");
|
|
5158
|
+
}
|
|
5159
|
+
const stream = client.responses.stream(streamRequest, options);
|
|
4384
5160
|
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
4385
5161
|
const accumulator = new OpenAiResponseAccumulator();
|
|
4386
5162
|
for await (const event of stream) {
|
|
@@ -4431,12 +5207,12 @@ var formatOtherPart3 = (part) => {
|
|
|
4431
5207
|
};
|
|
4432
5208
|
var isOpenAIAssistantInputContent = (value) => {
|
|
4433
5209
|
if (!value || typeof value !== "object") return false;
|
|
4434
|
-
const
|
|
4435
|
-
if (
|
|
4436
|
-
return typeof
|
|
5210
|
+
const record3 = value;
|
|
5211
|
+
if (record3.type === "output_text") {
|
|
5212
|
+
return typeof record3.text === "string";
|
|
4437
5213
|
}
|
|
4438
|
-
if (
|
|
4439
|
-
return typeof
|
|
5214
|
+
if (record3.type === "refusal") {
|
|
5215
|
+
return typeof record3.refusal === "string";
|
|
4440
5216
|
}
|
|
4441
5217
|
return false;
|
|
4442
5218
|
};
|
|
@@ -4454,8 +5230,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
4454
5230
|
if (!value || typeof value !== "object") {
|
|
4455
5231
|
return false;
|
|
4456
5232
|
}
|
|
4457
|
-
const
|
|
4458
|
-
return
|
|
5233
|
+
const record3 = value;
|
|
5234
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
4459
5235
|
};
|
|
4460
5236
|
var toReplayableFunctionCallItemId = (value) => {
|
|
4461
5237
|
if (typeof value !== "string") {
|
|
@@ -4506,14 +5282,14 @@ var extractReasoningText = (item) => {
|
|
|
4506
5282
|
};
|
|
4507
5283
|
var extractWebSearchSummary = (item) => {
|
|
4508
5284
|
const parts = [`WebSearch status=${item.status}`];
|
|
4509
|
-
const
|
|
4510
|
-
const queries = Array.isArray(
|
|
5285
|
+
const record3 = item;
|
|
5286
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
4511
5287
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
4512
5288
|
) : [];
|
|
4513
5289
|
if (queries.length) {
|
|
4514
5290
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
4515
5291
|
}
|
|
4516
|
-
const sources = Array.isArray(
|
|
5292
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
4517
5293
|
if (sources.length) {
|
|
4518
5294
|
parts.push(`sources=${sources.length}`);
|
|
4519
5295
|
}
|
|
@@ -4684,6 +5460,9 @@ function toChatInvokeCompletion2(response, meta) {
|
|
|
4684
5460
|
input_tokens: response.usage.input_tokens,
|
|
4685
5461
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
4686
5462
|
output_tokens: response.usage.output_tokens,
|
|
5463
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
5464
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
5465
|
+
} : {},
|
|
4687
5466
|
total_tokens: response.usage.total_tokens
|
|
4688
5467
|
} : null;
|
|
4689
5468
|
const messages = toMessageSequence(response);
|
|
@@ -4789,6 +5568,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
|
4789
5568
|
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
4790
5569
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
4791
5570
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
5571
|
+
var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
|
|
5572
|
+
constructor() {
|
|
5573
|
+
super({
|
|
5574
|
+
...buildProviderFailure("openai", "validation"),
|
|
5575
|
+
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."
|
|
5576
|
+
});
|
|
5577
|
+
}
|
|
5578
|
+
};
|
|
4792
5579
|
var resolveTimeoutMs = (value, fallbackMs) => {
|
|
4793
5580
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
4794
5581
|
return fallbackMs;
|
|
@@ -4870,6 +5657,8 @@ var OpenAiWsTransport = class {
|
|
|
4870
5657
|
);
|
|
4871
5658
|
}
|
|
4872
5659
|
async invoke(args) {
|
|
5660
|
+
const timing = new LlmStreamTiming();
|
|
5661
|
+
args.codex?.metadata.beginAttempt();
|
|
4873
5662
|
await this.prepareClientForWsHandshake();
|
|
4874
5663
|
const wsOptionsHeaders = {
|
|
4875
5664
|
...this.getClientDefaultHeaders(),
|
|
@@ -4878,6 +5667,19 @@ var OpenAiWsTransport = class {
|
|
|
4878
5667
|
if (args.sessionIdHeader) {
|
|
4879
5668
|
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
4880
5669
|
}
|
|
5670
|
+
if (args.codex?.routing) {
|
|
5671
|
+
const authHeaders = new Headers(wsOptionsHeaders);
|
|
5672
|
+
authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
|
|
5673
|
+
if (args.codex.routing.bindAuth(authHeaders)) {
|
|
5674
|
+
if (args.ws)
|
|
5675
|
+
this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
|
|
5676
|
+
throw createProviderValidationError(
|
|
5677
|
+
"openai",
|
|
5678
|
+
"OpenAI authentication changed; start a new run"
|
|
5679
|
+
);
|
|
5680
|
+
}
|
|
5681
|
+
Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
|
|
5682
|
+
}
|
|
4881
5683
|
const wsOptions = { headers: wsOptionsHeaders };
|
|
4882
5684
|
const ownsWs = !args.ws;
|
|
4883
5685
|
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new import_ws.ResponsesWS(
|
|
@@ -4888,6 +5690,15 @@ var OpenAiWsTransport = class {
|
|
|
4888
5690
|
ws.on("error", () => {
|
|
4889
5691
|
});
|
|
4890
5692
|
}
|
|
5693
|
+
const removeUpgrade = args.codex ? this.addNativeSocketListener(
|
|
5694
|
+
this.getNativeSocket(ws),
|
|
5695
|
+
"upgrade",
|
|
5696
|
+
(response) => {
|
|
5697
|
+
const headers = response?.headers;
|
|
5698
|
+
if (headers)
|
|
5699
|
+
args.codex?.metadata.observeHeaders(new Headers(headers));
|
|
5700
|
+
}
|
|
5701
|
+
) : void 0;
|
|
4891
5702
|
try {
|
|
4892
5703
|
await this.waitForWsOpen(ws, args.signal);
|
|
4893
5704
|
const closeWs = () => {
|
|
@@ -4896,11 +5707,14 @@ var OpenAiWsTransport = class {
|
|
|
4896
5707
|
const responseWaiter = this.createResponsePromise({
|
|
4897
5708
|
ws,
|
|
4898
5709
|
signal: args.signal,
|
|
4899
|
-
closeWs
|
|
5710
|
+
closeWs,
|
|
5711
|
+
timing,
|
|
5712
|
+
metadata: args.codex?.metadata
|
|
4900
5713
|
});
|
|
4901
5714
|
const responseCreateEvent = {
|
|
4902
5715
|
type: "response.create",
|
|
4903
|
-
...args.request
|
|
5716
|
+
...args.request,
|
|
5717
|
+
...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
|
|
4904
5718
|
};
|
|
4905
5719
|
if (!responseWaiter.isSettled()) {
|
|
4906
5720
|
try {
|
|
@@ -4910,12 +5724,14 @@ var OpenAiWsTransport = class {
|
|
|
4910
5724
|
}
|
|
4911
5725
|
}
|
|
4912
5726
|
const response = await responseWaiter.responsePromise;
|
|
4913
|
-
return { response, ws };
|
|
5727
|
+
return { response, ws, timing: timing.finish() };
|
|
4914
5728
|
} catch (error) {
|
|
4915
5729
|
if (ownsWs) {
|
|
4916
5730
|
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
4917
5731
|
}
|
|
4918
5732
|
throw error;
|
|
5733
|
+
} finally {
|
|
5734
|
+
removeUpgrade?.();
|
|
4919
5735
|
}
|
|
4920
5736
|
}
|
|
4921
5737
|
createResponsePromise(args) {
|
|
@@ -5005,6 +5821,7 @@ var OpenAiWsTransport = class {
|
|
|
5005
5821
|
rejectOnce(error);
|
|
5006
5822
|
};
|
|
5007
5823
|
const resolveFromTerminalEvent = (event, type) => {
|
|
5824
|
+
args.timing.complete();
|
|
5008
5825
|
const response = event?.response;
|
|
5009
5826
|
if (response && typeof response === "object") {
|
|
5010
5827
|
accumulator.observeTerminalResponse(response);
|
|
@@ -5027,6 +5844,9 @@ var OpenAiWsTransport = class {
|
|
|
5027
5844
|
);
|
|
5028
5845
|
};
|
|
5029
5846
|
const onEvent = (event) => {
|
|
5847
|
+
if (settled) return;
|
|
5848
|
+
args.metadata?.observeEvent(event);
|
|
5849
|
+
args.timing.observeResponsesEvent(event);
|
|
5030
5850
|
const eventType = this.extractResponsesEventType(event);
|
|
5031
5851
|
if (!eventType) {
|
|
5032
5852
|
return;
|
|
@@ -5075,7 +5895,7 @@ var OpenAiWsTransport = class {
|
|
|
5075
5895
|
const onClose = (event) => {
|
|
5076
5896
|
const closeCode = this.extractWsCloseCode(event);
|
|
5077
5897
|
rejectOnce(
|
|
5078
|
-
new Error(
|
|
5898
|
+
closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
|
|
5079
5899
|
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
5080
5900
|
)
|
|
5081
5901
|
);
|
|
@@ -5344,6 +6164,8 @@ var OpenAiWsTransport = class {
|
|
|
5344
6164
|
return void 0;
|
|
5345
6165
|
}
|
|
5346
6166
|
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
6167
|
+
if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
|
|
6168
|
+
return `${key}:[redacted]`;
|
|
5347
6169
|
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
5348
6170
|
return `${key}:${text}`;
|
|
5349
6171
|
});
|
|
@@ -5548,7 +6370,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
|
5548
6370
|
};
|
|
5549
6371
|
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
5550
6372
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
5551
|
-
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
5552
6373
|
var ChatOpenAI = class {
|
|
5553
6374
|
provider = PROVIDER_NAME5;
|
|
5554
6375
|
model;
|
|
@@ -5567,8 +6388,9 @@ var ChatOpenAI = class {
|
|
|
5567
6388
|
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
5568
6389
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
5569
6390
|
wsReconnectCount = 0;
|
|
6391
|
+
codexTurns = /* @__PURE__ */ new Map();
|
|
5570
6392
|
constructor(options = {}) {
|
|
5571
|
-
this.client = options.client ?? new
|
|
6393
|
+
this.client = options.client ?? new import_openai5.default({
|
|
5572
6394
|
...options.clientOptions ?? {},
|
|
5573
6395
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5574
6396
|
});
|
|
@@ -5651,17 +6473,32 @@ var ChatOpenAI = class {
|
|
|
5651
6473
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
5652
6474
|
const requestMeta = {
|
|
5653
6475
|
model: String(request.model ?? this.providerModel),
|
|
5654
|
-
instructionsHash: (0,
|
|
5655
|
-
toolsHash: (0,
|
|
6476
|
+
instructionsHash: (0, import_node_crypto5.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
6477
|
+
toolsHash: (0, import_node_crypto5.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
5656
6478
|
};
|
|
5657
|
-
const
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
6479
|
+
const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
|
|
6480
|
+
let transportResult;
|
|
6481
|
+
try {
|
|
6482
|
+
transportResult = await this.invokeWithTransport({
|
|
6483
|
+
request,
|
|
6484
|
+
sessionKey: context?.sessionKey,
|
|
6485
|
+
sessionIdHeader,
|
|
6486
|
+
signal,
|
|
6487
|
+
debugSeq,
|
|
6488
|
+
requestMeta,
|
|
6489
|
+
...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
|
|
6490
|
+
});
|
|
6491
|
+
} finally {
|
|
6492
|
+
codex?.metadata?.finish();
|
|
6493
|
+
}
|
|
6494
|
+
const codexMetadata = codex?.metadata?.snapshot();
|
|
6495
|
+
if (codex) {
|
|
6496
|
+
const { headers: _headers, ...response } = transportResult.response;
|
|
6497
|
+
transportResult.response = {
|
|
6498
|
+
...response,
|
|
6499
|
+
...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
|
|
6500
|
+
};
|
|
6501
|
+
}
|
|
5665
6502
|
await this.debugResponseIfEnabled(
|
|
5666
6503
|
transportResult.response,
|
|
5667
6504
|
debugSeq,
|
|
@@ -5685,7 +6522,42 @@ var ChatOpenAI = class {
|
|
|
5685
6522
|
debugSeq,
|
|
5686
6523
|
transportResult.transport
|
|
5687
6524
|
);
|
|
5688
|
-
return
|
|
6525
|
+
return {
|
|
6526
|
+
...completion,
|
|
6527
|
+
...codexMetadata ? {
|
|
6528
|
+
provider_meta: {
|
|
6529
|
+
...completion.provider_meta,
|
|
6530
|
+
codex_metadata: codexMetadata
|
|
6531
|
+
}
|
|
6532
|
+
} : {},
|
|
6533
|
+
...transportResult.timing ? { timing: transportResult.timing } : {}
|
|
6534
|
+
};
|
|
6535
|
+
}
|
|
6536
|
+
createCodexMetadata(context) {
|
|
6537
|
+
const routing = this.resolveCodexTurn(context);
|
|
6538
|
+
return {
|
|
6539
|
+
routing,
|
|
6540
|
+
metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
|
|
6541
|
+
};
|
|
6542
|
+
}
|
|
6543
|
+
resolveCodexTurn(context) {
|
|
6544
|
+
if (!context?.turnKey) return void 0;
|
|
6545
|
+
const key = context.sessionKey ?? context.turnKey;
|
|
6546
|
+
let state = this.codexTurns.get(key);
|
|
6547
|
+
if (!state || state.turnKey !== context.turnKey) {
|
|
6548
|
+
this.clearWsSessionState(key, "new_turn");
|
|
6549
|
+
state = { turnKey: context.turnKey, routing: new CodexTurnState() };
|
|
6550
|
+
this.codexTurns.delete(key);
|
|
6551
|
+
this.codexTurns.set(key, state);
|
|
6552
|
+
if (this.codexTurns.size > 16) {
|
|
6553
|
+
const oldest = this.codexTurns.keys().next().value;
|
|
6554
|
+
if (oldest !== void 0) {
|
|
6555
|
+
this.codexTurns.delete(oldest);
|
|
6556
|
+
this.clearWsSessionState(oldest, "turn_state_evicted");
|
|
6557
|
+
}
|
|
6558
|
+
}
|
|
6559
|
+
}
|
|
6560
|
+
return state.routing;
|
|
5689
6561
|
}
|
|
5690
6562
|
onHistoryCompacted(context) {
|
|
5691
6563
|
const sessionKey = context?.sessionKey;
|
|
@@ -5703,6 +6575,7 @@ var ChatOpenAI = class {
|
|
|
5703
6575
|
this.evictIdleWsSessionState();
|
|
5704
6576
|
if (this.websocketMode === "off") {
|
|
5705
6577
|
return this.invokeHttpTransportWithDebug({
|
|
6578
|
+
codex: args.codex,
|
|
5706
6579
|
request: args.request,
|
|
5707
6580
|
debugSeq: args.debugSeq,
|
|
5708
6581
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5718,6 +6591,7 @@ var ChatOpenAI = class {
|
|
|
5718
6591
|
);
|
|
5719
6592
|
}
|
|
5720
6593
|
return this.invokeHttpTransportWithDebug({
|
|
6594
|
+
codex: args.codex,
|
|
5721
6595
|
request: args.request,
|
|
5722
6596
|
debugSeq: args.debugSeq,
|
|
5723
6597
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5728,6 +6602,7 @@ var ChatOpenAI = class {
|
|
|
5728
6602
|
}
|
|
5729
6603
|
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
5730
6604
|
return this.invokeHttpTransportWithDebug({
|
|
6605
|
+
codex: args.codex,
|
|
5731
6606
|
request: args.request,
|
|
5732
6607
|
debugSeq: args.debugSeq,
|
|
5733
6608
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5737,7 +6612,7 @@ var ChatOpenAI = class {
|
|
|
5737
6612
|
});
|
|
5738
6613
|
}
|
|
5739
6614
|
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
5740
|
-
const hasReusableWs = this.isWsConnectionReusable(wsState.ws)
|
|
6615
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
|
|
5741
6616
|
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
5742
6617
|
const incrementalInput = this.getIncrementalInput(
|
|
5743
6618
|
wsState.lastInput,
|
|
@@ -5785,7 +6660,8 @@ var ChatOpenAI = class {
|
|
|
5785
6660
|
wsExecutionPlan.chainReset,
|
|
5786
6661
|
wsExecutionPlan.wsInputMode
|
|
5787
6662
|
);
|
|
5788
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6663
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6664
|
+
codex: args.codex,
|
|
5789
6665
|
request: wsExecutionPlan.request,
|
|
5790
6666
|
signal: args.signal,
|
|
5791
6667
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5801,12 +6677,17 @@ var ChatOpenAI = class {
|
|
|
5801
6677
|
return {
|
|
5802
6678
|
response,
|
|
5803
6679
|
transport: "ws_mode",
|
|
6680
|
+
...timing ? { timing } : {},
|
|
5804
6681
|
fallbackUsed: false,
|
|
5805
6682
|
chainReset: wsExecutionPlan.chainReset,
|
|
5806
6683
|
wsInputMode: wsExecutionPlan.wsInputMode
|
|
5807
6684
|
};
|
|
5808
6685
|
} catch (error) {
|
|
5809
6686
|
let failure = error;
|
|
6687
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6688
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6689
|
+
throw failure;
|
|
6690
|
+
}
|
|
5810
6691
|
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
5811
6692
|
const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
|
|
5812
6693
|
this.closeWsWithoutMaskingPrimaryError(
|
|
@@ -5824,7 +6705,8 @@ var ChatOpenAI = class {
|
|
|
5824
6705
|
true,
|
|
5825
6706
|
retryWsInputMode
|
|
5826
6707
|
);
|
|
5827
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6708
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6709
|
+
codex: args.codex,
|
|
5828
6710
|
request: args.request,
|
|
5829
6711
|
signal: args.signal,
|
|
5830
6712
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5841,6 +6723,7 @@ var ChatOpenAI = class {
|
|
|
5841
6723
|
return {
|
|
5842
6724
|
response,
|
|
5843
6725
|
transport: "ws_mode",
|
|
6726
|
+
...timing ? { timing } : {},
|
|
5844
6727
|
fallbackUsed: false,
|
|
5845
6728
|
chainReset: true,
|
|
5846
6729
|
wsInputMode: retryWsInputMode
|
|
@@ -5849,9 +6732,13 @@ var ChatOpenAI = class {
|
|
|
5849
6732
|
failure = retryError;
|
|
5850
6733
|
}
|
|
5851
6734
|
}
|
|
6735
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6736
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6737
|
+
throw failure;
|
|
6738
|
+
}
|
|
5852
6739
|
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
5853
6740
|
const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
|
|
5854
|
-
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");
|
|
6741
|
+
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");
|
|
5855
6742
|
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
5856
6743
|
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
5857
6744
|
this.wsDisabledUntilBySessionKey.set(
|
|
@@ -5864,6 +6751,7 @@ var ChatOpenAI = class {
|
|
|
5864
6751
|
}
|
|
5865
6752
|
this.wsReconnectCount += 1;
|
|
5866
6753
|
return this.invokeHttpTransportWithDebug({
|
|
6754
|
+
codex: args.codex,
|
|
5867
6755
|
request: args.request,
|
|
5868
6756
|
debugSeq: args.debugSeq,
|
|
5869
6757
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5884,16 +6772,23 @@ var ChatOpenAI = class {
|
|
|
5884
6772
|
args.chainReset,
|
|
5885
6773
|
args.wsInputMode
|
|
5886
6774
|
);
|
|
6775
|
+
const timing = new LlmStreamTiming();
|
|
6776
|
+
const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
|
|
5887
6777
|
const response = await invokeOpenAiHttp(
|
|
5888
6778
|
this.client,
|
|
5889
6779
|
args.request,
|
|
5890
6780
|
args.signal,
|
|
5891
6781
|
args.sessionIdHeader,
|
|
5892
|
-
|
|
6782
|
+
(event) => {
|
|
6783
|
+
timing.observeResponsesEvent(event);
|
|
6784
|
+
return debugObserver?.(event);
|
|
6785
|
+
},
|
|
6786
|
+
args.codex
|
|
5893
6787
|
);
|
|
5894
6788
|
return {
|
|
5895
6789
|
response,
|
|
5896
6790
|
transport: "http_stream",
|
|
6791
|
+
timing: timing.finish(),
|
|
5897
6792
|
fallbackUsed: args.fallbackUsed,
|
|
5898
6793
|
chainReset: args.chainReset
|
|
5899
6794
|
};
|
|
@@ -5931,12 +6826,6 @@ var ChatOpenAI = class {
|
|
|
5931
6826
|
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
5932
6827
|
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
5933
6828
|
}
|
|
5934
|
-
isWsConnectionReuseExpired(lastUsedAt) {
|
|
5935
|
-
if (typeof lastUsedAt !== "number") {
|
|
5936
|
-
return false;
|
|
5937
|
-
}
|
|
5938
|
-
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
5939
|
-
}
|
|
5940
6829
|
isWsReconnectRetryableError(error) {
|
|
5941
6830
|
if (!(error instanceof Error)) {
|
|
5942
6831
|
return false;
|
|
@@ -6015,14 +6904,14 @@ var ChatOpenAI = class {
|
|
|
6015
6904
|
return;
|
|
6016
6905
|
}
|
|
6017
6906
|
const payload = safeJsonStringify(request);
|
|
6018
|
-
const hash = (0,
|
|
6019
|
-
const toolsHash = (0,
|
|
6020
|
-
const instructionsHash = (0,
|
|
6907
|
+
const hash = (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6908
|
+
const toolsHash = (0, import_node_crypto5.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6909
|
+
const instructionsHash = (0, import_node_crypto5.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6021
6910
|
const previous = this.lastDebugRequestPayload;
|
|
6022
6911
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6023
6912
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6024
6913
|
if (settings.enabled) {
|
|
6025
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
6914
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto5.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6026
6915
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
6027
6916
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
6028
6917
|
console.error(
|
|
@@ -6115,8 +7004,8 @@ var ChatOpenAI = class {
|
|
|
6115
7004
|
};
|
|
6116
7005
|
|
|
6117
7006
|
// src/llm/openrouter/chat.ts
|
|
6118
|
-
var
|
|
6119
|
-
var
|
|
7007
|
+
var import_node_crypto6 = require("crypto");
|
|
7008
|
+
var import_openai7 = __toESM(require("openai"), 1);
|
|
6120
7009
|
|
|
6121
7010
|
// src/llm/openrouter/response-utils.ts
|
|
6122
7011
|
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
@@ -6236,12 +7125,12 @@ var formatOtherPart5 = (part) => {
|
|
|
6236
7125
|
};
|
|
6237
7126
|
var isOpenAIAssistantInputContent2 = (value) => {
|
|
6238
7127
|
if (!value || typeof value !== "object") return false;
|
|
6239
|
-
const
|
|
6240
|
-
if (
|
|
6241
|
-
return typeof
|
|
7128
|
+
const record3 = value;
|
|
7129
|
+
if (record3.type === "output_text") {
|
|
7130
|
+
return typeof record3.text === "string";
|
|
6242
7131
|
}
|
|
6243
|
-
if (
|
|
6244
|
-
return typeof
|
|
7132
|
+
if (record3.type === "refusal") {
|
|
7133
|
+
return typeof record3.refusal === "string";
|
|
6245
7134
|
}
|
|
6246
7135
|
return false;
|
|
6247
7136
|
};
|
|
@@ -6249,8 +7138,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
|
6249
7138
|
if (!value || typeof value !== "object") {
|
|
6250
7139
|
return false;
|
|
6251
7140
|
}
|
|
6252
|
-
const
|
|
6253
|
-
return
|
|
7141
|
+
const record3 = value;
|
|
7142
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
6254
7143
|
};
|
|
6255
7144
|
var toReplayableFunctionCallItemId2 = (value) => {
|
|
6256
7145
|
if (typeof value !== "string") {
|
|
@@ -6301,14 +7190,14 @@ var extractReasoningText2 = (item) => {
|
|
|
6301
7190
|
};
|
|
6302
7191
|
var extractWebSearchSummary2 = (item) => {
|
|
6303
7192
|
const parts = [`WebSearch status=${item.status}`];
|
|
6304
|
-
const
|
|
6305
|
-
const queries = Array.isArray(
|
|
7193
|
+
const record3 = item;
|
|
7194
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
6306
7195
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
6307
7196
|
) : [];
|
|
6308
7197
|
if (queries.length) {
|
|
6309
7198
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
6310
7199
|
}
|
|
6311
|
-
const sources = Array.isArray(
|
|
7200
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
6312
7201
|
if (sources.length) {
|
|
6313
7202
|
parts.push(`sources=${sources.length}`);
|
|
6314
7203
|
}
|
|
@@ -6475,6 +7364,9 @@ function toChatInvokeCompletion3(response, meta) {
|
|
|
6475
7364
|
input_tokens: response.usage.input_tokens,
|
|
6476
7365
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
6477
7366
|
output_tokens: response.usage.output_tokens,
|
|
7367
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
7368
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
7369
|
+
} : {},
|
|
6478
7370
|
total_tokens: response.usage.total_tokens
|
|
6479
7371
|
} : null;
|
|
6480
7372
|
const messages = toMessageSequence2(response);
|
|
@@ -6584,7 +7476,7 @@ var ChatOpenRouter = class {
|
|
|
6584
7476
|
debugInvokeSeq = 0;
|
|
6585
7477
|
lastDebugRequestPayload = null;
|
|
6586
7478
|
constructor(options = {}) {
|
|
6587
|
-
this.client = options.client ?? new
|
|
7479
|
+
this.client = options.client ?? new import_openai7.default({
|
|
6588
7480
|
baseURL: OPENROUTER_BASE_URL,
|
|
6589
7481
|
...options.clientOptions ?? {},
|
|
6590
7482
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
@@ -6656,7 +7548,8 @@ var ChatOpenRouter = class {
|
|
|
6656
7548
|
...request,
|
|
6657
7549
|
stream: true
|
|
6658
7550
|
};
|
|
6659
|
-
const
|
|
7551
|
+
const timing = new LlmStreamTiming();
|
|
7552
|
+
const stream = this.client.responses.stream(
|
|
6660
7553
|
streamRequest,
|
|
6661
7554
|
signal || sessionIdHeader ? {
|
|
6662
7555
|
...signal ? { signal } : {},
|
|
@@ -6666,13 +7559,21 @@ var ChatOpenRouter = class {
|
|
|
6666
7559
|
}
|
|
6667
7560
|
} : {}
|
|
6668
7561
|
} : void 0
|
|
6669
|
-
)
|
|
7562
|
+
);
|
|
7563
|
+
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
7564
|
+
for await (const event of stream) timing.observeResponsesEvent(event);
|
|
7565
|
+
}
|
|
7566
|
+
const response = await stream.finalResponse();
|
|
7567
|
+
const measuredTiming = timing.finish();
|
|
6670
7568
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6671
|
-
return
|
|
6672
|
-
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
7569
|
+
return {
|
|
7570
|
+
...toChatInvokeCompletion3(response, {
|
|
7571
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7572
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7573
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7574
|
+
}),
|
|
7575
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7576
|
+
};
|
|
6676
7577
|
}
|
|
6677
7578
|
nextDebugInvokeSeq() {
|
|
6678
7579
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -6685,14 +7586,14 @@ var ChatOpenRouter = class {
|
|
|
6685
7586
|
return;
|
|
6686
7587
|
}
|
|
6687
7588
|
const payload = safeJsonStringify(request);
|
|
6688
|
-
const hash = (0,
|
|
6689
|
-
const toolsHash = (0,
|
|
6690
|
-
const instructionsHash = (0,
|
|
7589
|
+
const hash = (0, import_node_crypto6.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7590
|
+
const toolsHash = (0, import_node_crypto6.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7591
|
+
const instructionsHash = (0, import_node_crypto6.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6691
7592
|
const previous = this.lastDebugRequestPayload;
|
|
6692
7593
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6693
7594
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6694
7595
|
if (settings.enabled) {
|
|
6695
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
7596
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto6.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6696
7597
|
console.error(
|
|
6697
7598
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
6698
7599
|
);
|
|
@@ -6756,8 +7657,8 @@ var ChatOpenRouter = class {
|
|
|
6756
7657
|
};
|
|
6757
7658
|
|
|
6758
7659
|
// src/llm/xai/chat.ts
|
|
6759
|
-
var
|
|
6760
|
-
var
|
|
7660
|
+
var import_node_crypto7 = require("crypto");
|
|
7661
|
+
var import_openai9 = __toESM(require("openai"), 1);
|
|
6761
7662
|
|
|
6762
7663
|
// src/llm/xai/serializer.ts
|
|
6763
7664
|
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -6980,7 +7881,7 @@ var ChatXai = class {
|
|
|
6980
7881
|
debugInvokeSeq = 0;
|
|
6981
7882
|
lastDebugRequestPayload = null;
|
|
6982
7883
|
constructor(options = {}) {
|
|
6983
|
-
this.client = options.client ?? new
|
|
7884
|
+
this.client = options.client ?? new import_openai9.default({
|
|
6984
7885
|
baseURL: XAI_BASE_URL,
|
|
6985
7886
|
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6986
7887
|
...options.clientOptions ?? {},
|
|
@@ -7033,13 +7934,24 @@ var ChatXai = class {
|
|
|
7033
7934
|
}
|
|
7034
7935
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
7035
7936
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7036
|
-
const
|
|
7937
|
+
const timing = new LlmStreamTiming();
|
|
7938
|
+
const response = await invokeOpenAiHttp(
|
|
7939
|
+
this.client,
|
|
7940
|
+
request,
|
|
7941
|
+
signal,
|
|
7942
|
+
void 0,
|
|
7943
|
+
(event) => timing.observeResponsesEvent(event)
|
|
7944
|
+
);
|
|
7945
|
+
const measuredTiming = timing.finish();
|
|
7037
7946
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
7038
|
-
return
|
|
7039
|
-
|
|
7040
|
-
|
|
7041
|
-
|
|
7042
|
-
|
|
7947
|
+
return {
|
|
7948
|
+
...toXaiChatInvokeCompletion(response, {
|
|
7949
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7950
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7951
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7952
|
+
}),
|
|
7953
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7954
|
+
};
|
|
7043
7955
|
}
|
|
7044
7956
|
nextDebugInvokeSeq() {
|
|
7045
7957
|
this.debugInvokeSeq += 1;
|
|
@@ -7049,7 +7961,7 @@ var ChatXai = class {
|
|
|
7049
7961
|
const settings = getProviderLogSettings();
|
|
7050
7962
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
7051
7963
|
const payload = safeJsonStringify(request);
|
|
7052
|
-
const hash = (0,
|
|
7964
|
+
const hash = (0, import_node_crypto7.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7053
7965
|
const previous = this.lastDebugRequestPayload;
|
|
7054
7966
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7055
7967
|
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7106,15 +8018,15 @@ var ChatXai = class {
|
|
|
7106
8018
|
};
|
|
7107
8019
|
|
|
7108
8020
|
// src/llm/zai/chat.ts
|
|
7109
|
-
var
|
|
8021
|
+
var import_node_crypto8 = require("crypto");
|
|
7110
8022
|
|
|
7111
8023
|
// src/llm/zai/failure.ts
|
|
7112
8024
|
var PROVIDER_NAME8 = "zai";
|
|
7113
8025
|
var readBusinessCode = (error) => {
|
|
7114
|
-
const
|
|
7115
|
-
const body = asRecord(
|
|
8026
|
+
const record3 = asRecord(error);
|
|
8027
|
+
const body = asRecord(record3?.body);
|
|
7116
8028
|
const nested = asRecord(body?.error) ?? body;
|
|
7117
|
-
const raw = nested?.code ??
|
|
8029
|
+
const raw = nested?.code ?? record3?.code;
|
|
7118
8030
|
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7119
8031
|
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7120
8032
|
};
|
|
@@ -7418,6 +8330,7 @@ var streamZaiChatCompletion = async ({
|
|
|
7418
8330
|
timeoutMs,
|
|
7419
8331
|
captureRawChunks
|
|
7420
8332
|
}) => {
|
|
8333
|
+
const timing = new LlmStreamTiming();
|
|
7421
8334
|
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
7422
8335
|
try {
|
|
7423
8336
|
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
@@ -7439,9 +8352,11 @@ var streamZaiChatCompletion = async ({
|
|
|
7439
8352
|
response,
|
|
7440
8353
|
requestSignal.signal
|
|
7441
8354
|
)) {
|
|
8355
|
+
timing.observeChatChunk(chunk);
|
|
7442
8356
|
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
7443
8357
|
}
|
|
7444
8358
|
return {
|
|
8359
|
+
timing: timing.finish(),
|
|
7445
8360
|
status: response.status,
|
|
7446
8361
|
request_id: response.headers.get("x-request-id"),
|
|
7447
8362
|
accumulated
|
|
@@ -7636,13 +8551,16 @@ var ChatZai = class {
|
|
|
7636
8551
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7637
8552
|
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
7638
8553
|
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
7639
|
-
return
|
|
7640
|
-
|
|
7641
|
-
|
|
7642
|
-
|
|
7643
|
-
|
|
7644
|
-
|
|
7645
|
-
|
|
8554
|
+
return {
|
|
8555
|
+
...toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
8556
|
+
request_id: terminal.request_id ?? null,
|
|
8557
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8558
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8559
|
+
reasoning_effort: request.reasoning_effort,
|
|
8560
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8561
|
+
}),
|
|
8562
|
+
...terminal.timing ? { timing: terminal.timing } : {}
|
|
8563
|
+
};
|
|
7646
8564
|
}
|
|
7647
8565
|
async streamRequest(apiKey, request, signal) {
|
|
7648
8566
|
const logSettings = getProviderLogSettings();
|
|
@@ -7667,8 +8585,8 @@ var ChatZai = class {
|
|
|
7667
8585
|
return;
|
|
7668
8586
|
}
|
|
7669
8587
|
const payload = safeJsonStringify(request);
|
|
7670
|
-
const hash = (0,
|
|
7671
|
-
const toolsHash = (0,
|
|
8588
|
+
const hash = (0, import_node_crypto8.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
8589
|
+
const toolsHash = (0, import_node_crypto8.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7672
8590
|
const previous = this.lastDebugRequestPayload;
|
|
7673
8591
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7674
8592
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7799,6 +8717,159 @@ function defineTool(toolOptions) {
|
|
|
7799
8717
|
}
|
|
7800
8718
|
};
|
|
7801
8719
|
}
|
|
8720
|
+
|
|
8721
|
+
// src/llm/responses/chat.ts
|
|
8722
|
+
var import_openai10 = __toESM(require("openai"), 1);
|
|
8723
|
+
var ChatResponses = class {
|
|
8724
|
+
provider;
|
|
8725
|
+
model;
|
|
8726
|
+
retryPolicy;
|
|
8727
|
+
client;
|
|
8728
|
+
endpoint;
|
|
8729
|
+
reasoningEffort;
|
|
8730
|
+
textVerbosity;
|
|
8731
|
+
constructor(options) {
|
|
8732
|
+
this.provider = options.provider;
|
|
8733
|
+
this.model = options.model;
|
|
8734
|
+
this.endpoint = options.endpoint;
|
|
8735
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
8736
|
+
this.textVerbosity = options.textVerbosity;
|
|
8737
|
+
const retry = options.endpoint.retry;
|
|
8738
|
+
this.retryPolicy = {
|
|
8739
|
+
maxRetries: typeof retry === "object" ? retry.max_retries : 0,
|
|
8740
|
+
...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
|
|
8741
|
+
};
|
|
8742
|
+
this.client = new import_openai10.default({
|
|
8743
|
+
apiKey: options.apiKey,
|
|
8744
|
+
baseURL: options.endpoint.base_url,
|
|
8745
|
+
organization: null,
|
|
8746
|
+
project: null,
|
|
8747
|
+
maxRetries: 0,
|
|
8748
|
+
timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
|
|
8749
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
8750
|
+
});
|
|
8751
|
+
}
|
|
8752
|
+
classifyFailure = (error) => {
|
|
8753
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
8754
|
+
const failure = error instanceof import_openai10.default.APIUserAbortError ? buildProviderFailure(this.provider, "cancelled") : error instanceof import_openai10.default.APIConnectionTimeoutError ? buildProviderFailure(this.provider, "timeout", { retryable: true }) : error instanceof import_openai10.default.APIConnectionError ? buildProviderFailure(this.provider, "network", {
|
|
8755
|
+
retryable: true
|
|
8756
|
+
}) : classifyOpenAiCompatibleFailure(this.provider, error);
|
|
8757
|
+
const extracted = extractProviderError(error);
|
|
8758
|
+
const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
|
|
8759
|
+
return {
|
|
8760
|
+
...failure,
|
|
8761
|
+
...extracted.status !== void 0 ? { status: extracted.status } : {},
|
|
8762
|
+
...extracted.status === 413 ? { kind: "validation" } : {},
|
|
8763
|
+
retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
|
|
8764
|
+
...code ? { code } : {},
|
|
8765
|
+
safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
|
|
8766
|
+
};
|
|
8767
|
+
};
|
|
8768
|
+
async ainvoke(input, context) {
|
|
8769
|
+
const model = input.model ?? this.model;
|
|
8770
|
+
const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
|
|
8771
|
+
const invalid = (message) => {
|
|
8772
|
+
throw createProviderValidationError(this.provider, message);
|
|
8773
|
+
};
|
|
8774
|
+
if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
|
|
8775
|
+
if (input.tools?.some((tool) => tool.type === "hosted_search"))
|
|
8776
|
+
invalid(
|
|
8777
|
+
`${this.provider} supports function tools only; hosted tools are unavailable`
|
|
8778
|
+
);
|
|
8779
|
+
if (input.tools?.length && !spec.supports_tools)
|
|
8780
|
+
invalid(`${this.provider}/${model} does not support tools`);
|
|
8781
|
+
const items = toResponsesInput(input.messages);
|
|
8782
|
+
if (!spec.supports_vision && Array.isArray(items) && items.some(
|
|
8783
|
+
(item) => "content" in item && Array.isArray(item.content) && item.content.some((part) => part.type === "input_image")
|
|
8784
|
+
))
|
|
8785
|
+
invalid(`${this.provider}/${model} vision is disabled`);
|
|
8786
|
+
const text = input.options?.text;
|
|
8787
|
+
if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
|
|
8788
|
+
invalid(`${this.provider}/${model} does not support structured output`);
|
|
8789
|
+
const features = this.endpoint.features;
|
|
8790
|
+
const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
|
|
8791
|
+
if (effort && !spec.supports_reasoning)
|
|
8792
|
+
invalid(`${this.provider}/${model} reasoning is disabled`);
|
|
8793
|
+
const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
|
|
8794
|
+
if (effort && !levels.includes(effort))
|
|
8795
|
+
invalid(
|
|
8796
|
+
`Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
|
|
8797
|
+
);
|
|
8798
|
+
const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
|
|
8799
|
+
if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
|
|
8800
|
+
invalid(`Invalid max output tokens for ${this.provider}/${model}`);
|
|
8801
|
+
const tools = toResponsesTools(input.tools);
|
|
8802
|
+
const choice = toResponsesToolChoice(input.toolChoice);
|
|
8803
|
+
const instructions = extractInstructions(input.messages);
|
|
8804
|
+
const request = {
|
|
8805
|
+
model,
|
|
8806
|
+
input: items,
|
|
8807
|
+
store: false,
|
|
8808
|
+
...instructions ? { instructions } : {},
|
|
8809
|
+
...tools ? { tools } : {},
|
|
8810
|
+
...choice ? { tool_choice: choice } : {},
|
|
8811
|
+
...output !== void 0 ? { max_output_tokens: output } : {}
|
|
8812
|
+
};
|
|
8813
|
+
if (spec.supports_reasoning && (effort || features?.reasoning_summary))
|
|
8814
|
+
request.reasoning = {
|
|
8815
|
+
...effort ? { effort: toSdkReasoningEffort(effort) } : {},
|
|
8816
|
+
...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
|
|
8817
|
+
};
|
|
8818
|
+
if (spec.supports_reasoning && features?.encrypted_reasoning)
|
|
8819
|
+
request.include = ["reasoning.encrypted_content"];
|
|
8820
|
+
if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
|
|
8821
|
+
request.text = {
|
|
8822
|
+
...text?.format ? { format: text.format } : {},
|
|
8823
|
+
...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
|
|
8824
|
+
};
|
|
8825
|
+
if (features?.prompt_cache_key && context?.sessionKey)
|
|
8826
|
+
request.prompt_cache_key = context.sessionKey;
|
|
8827
|
+
const timing = new LlmStreamTiming();
|
|
8828
|
+
let streamStarted = false;
|
|
8829
|
+
try {
|
|
8830
|
+
const stream = await this.client.responses.create(
|
|
8831
|
+
{ ...request, stream: true },
|
|
8832
|
+
{
|
|
8833
|
+
...input.signal ? { signal: input.signal } : {},
|
|
8834
|
+
...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
|
|
8835
|
+
}
|
|
8836
|
+
);
|
|
8837
|
+
streamStarted = true;
|
|
8838
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
8839
|
+
let terminal;
|
|
8840
|
+
for await (const event of stream) {
|
|
8841
|
+
timing.observeResponsesEvent(event);
|
|
8842
|
+
if (event.type === "error") throw { error: event };
|
|
8843
|
+
if (event.type === "response.failed")
|
|
8844
|
+
throw { error: event.response.error };
|
|
8845
|
+
accumulator.observeEvent(event);
|
|
8846
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
8847
|
+
terminal = event.response;
|
|
8848
|
+
break;
|
|
8849
|
+
}
|
|
8850
|
+
}
|
|
8851
|
+
if (!terminal)
|
|
8852
|
+
throw new Error("Responses stream ended before a terminal event");
|
|
8853
|
+
const measuredTiming = timing.finish();
|
|
8854
|
+
return {
|
|
8855
|
+
...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
|
|
8856
|
+
transport: "http_stream"
|
|
8857
|
+
}),
|
|
8858
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
8859
|
+
};
|
|
8860
|
+
} catch (error) {
|
|
8861
|
+
if (isProviderFailureError(error)) throw error;
|
|
8862
|
+
const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
|
|
8863
|
+
throw new ProviderFailureError(
|
|
8864
|
+
{
|
|
8865
|
+
...failure,
|
|
8866
|
+
...streamStarted ? { retryable: false, delivery: "buffered" } : {}
|
|
8867
|
+
},
|
|
8868
|
+
{ cause: error }
|
|
8869
|
+
);
|
|
8870
|
+
}
|
|
8871
|
+
}
|
|
8872
|
+
};
|
|
7802
8873
|
// Annotate the CommonJS export names for ESM import in node:
|
|
7803
8874
|
0 && (module.exports = {
|
|
7804
8875
|
ANTHROPIC_DEFAULT_MODEL,
|
|
@@ -7808,6 +8879,7 @@ function defineTool(toolOptions) {
|
|
|
7808
8879
|
ChatMoonshot,
|
|
7809
8880
|
ChatOpenAI,
|
|
7810
8881
|
ChatOpenRouter,
|
|
8882
|
+
ChatResponses,
|
|
7811
8883
|
ChatXai,
|
|
7812
8884
|
ChatZai,
|
|
7813
8885
|
DEFAULT_MODEL_REGISTRY,
|