@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.js
CHANGED
|
@@ -23,6 +23,14 @@ var buildGpt56Model = (id) => ({
|
|
|
23
23
|
supportsFast: true
|
|
24
24
|
});
|
|
25
25
|
var OPENAI_MODELS = [
|
|
26
|
+
{
|
|
27
|
+
id: "gpt-6.1-sol",
|
|
28
|
+
provider: "openai",
|
|
29
|
+
contextWindow: 105e4,
|
|
30
|
+
maxInputTokens: 27e4,
|
|
31
|
+
maxOutputTokens: 128e3,
|
|
32
|
+
supportsFast: true
|
|
33
|
+
},
|
|
26
34
|
{
|
|
27
35
|
id: "gpt-6-astra",
|
|
28
36
|
provider: "openai",
|
|
@@ -31,6 +39,22 @@ var OPENAI_MODELS = [
|
|
|
31
39
|
maxOutputTokens: 128e3,
|
|
32
40
|
supportsFast: true
|
|
33
41
|
},
|
|
42
|
+
{
|
|
43
|
+
id: "gpt-6-sol",
|
|
44
|
+
provider: "openai",
|
|
45
|
+
contextWindow: 105e4,
|
|
46
|
+
maxInputTokens: 27e4,
|
|
47
|
+
maxOutputTokens: 128e3,
|
|
48
|
+
supportsFast: true
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: "gpt-6-luna",
|
|
52
|
+
provider: "openai",
|
|
53
|
+
contextWindow: 105e4,
|
|
54
|
+
maxInputTokens: 27e4,
|
|
55
|
+
maxOutputTokens: 128e3,
|
|
56
|
+
supportsFast: true
|
|
57
|
+
},
|
|
34
58
|
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
35
59
|
{
|
|
36
60
|
id: "gpt-5.5",
|
|
@@ -208,7 +232,48 @@ configRegistry.registerDefaults({
|
|
|
208
232
|
});
|
|
209
233
|
|
|
210
234
|
// src/agent/agent.ts
|
|
211
|
-
import { performance } from "perf_hooks";
|
|
235
|
+
import { performance as performance2 } from "perf_hooks";
|
|
236
|
+
import { randomUUID } from "crypto";
|
|
237
|
+
|
|
238
|
+
// src/llm/provider-status.ts
|
|
239
|
+
async function* withProviderStatus(operation, signal) {
|
|
240
|
+
const controller = new AbortController();
|
|
241
|
+
const abort = () => controller.abort(signal?.reason);
|
|
242
|
+
if (signal?.aborted) abort();
|
|
243
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
244
|
+
const queue = [];
|
|
245
|
+
let wake;
|
|
246
|
+
let closed = false;
|
|
247
|
+
const iterator = operation((event) => {
|
|
248
|
+
if (closed || controller.signal.aborted) return;
|
|
249
|
+
if (queue.length < 32) queue.push(event);
|
|
250
|
+
wake?.();
|
|
251
|
+
}, controller.signal);
|
|
252
|
+
let pending = iterator.next();
|
|
253
|
+
try {
|
|
254
|
+
while (true) {
|
|
255
|
+
while (queue.length) yield queue.shift();
|
|
256
|
+
const changed = new Promise((resolve) => {
|
|
257
|
+
wake = () => resolve(void 0);
|
|
258
|
+
});
|
|
259
|
+
const result = await Promise.race([pending, changed]);
|
|
260
|
+
wake = void 0;
|
|
261
|
+
if (!result) continue;
|
|
262
|
+
while (queue.length) yield queue.shift();
|
|
263
|
+
if (result.done) return result.value;
|
|
264
|
+
yield result.value;
|
|
265
|
+
pending = iterator.next();
|
|
266
|
+
}
|
|
267
|
+
} finally {
|
|
268
|
+
closed = true;
|
|
269
|
+
controller.abort();
|
|
270
|
+
signal?.removeEventListener("abort", abort);
|
|
271
|
+
void pending.catch(() => {
|
|
272
|
+
});
|
|
273
|
+
void iterator.return(void 0).catch(() => {
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
212
277
|
|
|
213
278
|
// src/content/stringify.ts
|
|
214
279
|
var stringifyUnknown = (value) => {
|
|
@@ -222,6 +287,9 @@ var stringifyPart = (part, options) => {
|
|
|
222
287
|
if (part.type === "text") {
|
|
223
288
|
return part.text;
|
|
224
289
|
}
|
|
290
|
+
if (part.type === "image_ref") {
|
|
291
|
+
return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
|
|
292
|
+
}
|
|
225
293
|
if (part.type === "image_url") {
|
|
226
294
|
if (options.mode === "log") {
|
|
227
295
|
return `[image:${part.image_url.media_type ?? "unknown"}]`;
|
|
@@ -322,8 +390,8 @@ var ProviderTimeoutError = class extends Error {
|
|
|
322
390
|
};
|
|
323
391
|
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
324
392
|
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
325
|
-
var readString = (
|
|
326
|
-
const value =
|
|
393
|
+
var readString = (record3, key) => {
|
|
394
|
+
const value = record3?.[key];
|
|
327
395
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
328
396
|
};
|
|
329
397
|
var readStatus = (error) => {
|
|
@@ -334,9 +402,9 @@ var readHeader = (headers, name) => {
|
|
|
334
402
|
if (headers instanceof Headers) {
|
|
335
403
|
return headers.get(name);
|
|
336
404
|
}
|
|
337
|
-
const
|
|
338
|
-
if (!
|
|
339
|
-
const direct =
|
|
405
|
+
const record3 = asRecord(headers);
|
|
406
|
+
if (!record3) return null;
|
|
407
|
+
const direct = record3[name] ?? record3[name.toLowerCase()];
|
|
340
408
|
return typeof direct === "string" ? direct : null;
|
|
341
409
|
};
|
|
342
410
|
var parsePositiveNumber = (value) => {
|
|
@@ -392,7 +460,7 @@ var PROVIDER_LABELS = {
|
|
|
392
460
|
xai: "xAI"
|
|
393
461
|
};
|
|
394
462
|
var safeProviderMessage = (provider, kind) => {
|
|
395
|
-
const label = PROVIDER_LABELS[provider];
|
|
463
|
+
const label = PROVIDER_LABELS[provider] ?? provider;
|
|
396
464
|
switch (kind) {
|
|
397
465
|
case "hard_quota":
|
|
398
466
|
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
@@ -732,6 +800,28 @@ var ANTHROPIC_MODELS = [
|
|
|
732
800
|
provider: "anthropic",
|
|
733
801
|
aliases: ["default"]
|
|
734
802
|
},
|
|
803
|
+
{
|
|
804
|
+
id: "claude-fable-5-1",
|
|
805
|
+
provider: "anthropic",
|
|
806
|
+
contextWindow: 1e6,
|
|
807
|
+
maxInputTokens: 1e6,
|
|
808
|
+
maxOutputTokens: 128e3
|
|
809
|
+
},
|
|
810
|
+
{
|
|
811
|
+
id: "claude-opus-5-5",
|
|
812
|
+
provider: "anthropic",
|
|
813
|
+
contextWindow: 1e6,
|
|
814
|
+
maxInputTokens: 1e6,
|
|
815
|
+
maxOutputTokens: 128e3,
|
|
816
|
+
supportsFast: true
|
|
817
|
+
},
|
|
818
|
+
{
|
|
819
|
+
id: "claude-sonnet-5",
|
|
820
|
+
provider: "anthropic",
|
|
821
|
+
contextWindow: 1e6,
|
|
822
|
+
maxInputTokens: 1e6,
|
|
823
|
+
maxOutputTokens: 128e3
|
|
824
|
+
},
|
|
735
825
|
{
|
|
736
826
|
id: "claude-fable-5",
|
|
737
827
|
provider: "anthropic",
|
|
@@ -761,12 +851,12 @@ var ANTHROPIC_MODELS = [
|
|
|
761
851
|
contextWindow: 1e6,
|
|
762
852
|
maxInputTokens: 1e6,
|
|
763
853
|
maxOutputTokens: 128e3,
|
|
764
|
-
supportsFast:
|
|
854
|
+
supportsFast: false
|
|
765
855
|
},
|
|
766
856
|
{
|
|
767
857
|
id: "claude-opus-4-6",
|
|
768
858
|
provider: "anthropic",
|
|
769
|
-
supportsFast:
|
|
859
|
+
supportsFast: false
|
|
770
860
|
},
|
|
771
861
|
{
|
|
772
862
|
id: "claude-opus-4-5",
|
|
@@ -847,6 +937,7 @@ function createModelRegistry(specs) {
|
|
|
847
937
|
function registerModels(registry, specs) {
|
|
848
938
|
for (const spec of specs) {
|
|
849
939
|
registry.modelsById[spec.id] = spec;
|
|
940
|
+
registry.aliasesByProvider[spec.provider] ??= {};
|
|
850
941
|
const aliasBucket = registry.aliasesByProvider[spec.provider];
|
|
851
942
|
for (const alias of spec.aliases ?? []) {
|
|
852
943
|
aliasBucket[alias] = spec.id;
|
|
@@ -855,11 +946,11 @@ function registerModels(registry, specs) {
|
|
|
855
946
|
}
|
|
856
947
|
function resolveModel(registry, idOrAlias, provider) {
|
|
857
948
|
const direct = registry.modelsById[idOrAlias];
|
|
858
|
-
if (direct) {
|
|
949
|
+
if (direct && (!provider || direct.provider === provider)) {
|
|
859
950
|
return direct;
|
|
860
951
|
}
|
|
861
952
|
if (provider) {
|
|
862
|
-
const aliasId = registry.aliasesByProvider[provider][idOrAlias];
|
|
953
|
+
const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
|
|
863
954
|
return aliasId ? registry.modelsById[aliasId] : void 0;
|
|
864
955
|
}
|
|
865
956
|
let resolved;
|
|
@@ -894,15 +985,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
|
|
|
894
985
|
return spec?.supportsFast === true;
|
|
895
986
|
}
|
|
896
987
|
function cloneAliases(aliasesByProvider) {
|
|
897
|
-
return
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
zai: { ...aliasesByProvider.zai },
|
|
904
|
-
xai: { ...aliasesByProvider.xai }
|
|
905
|
-
};
|
|
988
|
+
return Object.fromEntries(
|
|
989
|
+
Object.entries(aliasesByProvider).map(([provider, aliases]) => [
|
|
990
|
+
provider,
|
|
991
|
+
{ ...aliases }
|
|
992
|
+
])
|
|
993
|
+
);
|
|
906
994
|
}
|
|
907
995
|
function applyModelMetadata(registry, index) {
|
|
908
996
|
const next = {
|
|
@@ -995,6 +1083,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
995
1083
|
...XAI_MODELS
|
|
996
1084
|
]);
|
|
997
1085
|
|
|
1086
|
+
// src/content/image-references.ts
|
|
1087
|
+
var REGISTRY = "[codelia.image.artifacts]";
|
|
1088
|
+
function isImageRegistry(message) {
|
|
1089
|
+
return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
|
|
1090
|
+
}
|
|
1091
|
+
function imageReferenceRegistry(messages) {
|
|
1092
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1093
|
+
for (const message of messages) {
|
|
1094
|
+
if (!("content" in message) || !Array.isArray(message.content)) continue;
|
|
1095
|
+
for (const part of message.content)
|
|
1096
|
+
if (part.type === "image_ref") {
|
|
1097
|
+
refs.delete(part.image_ref.artifact_id);
|
|
1098
|
+
refs.set(part.image_ref.artifact_id, part);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
const recent = [...refs.values()].slice(-16);
|
|
1102
|
+
return recent.length ? {
|
|
1103
|
+
role: "user",
|
|
1104
|
+
content: [
|
|
1105
|
+
{
|
|
1106
|
+
type: "text",
|
|
1107
|
+
text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
|
|
1108
|
+
`
|
|
1109
|
+
},
|
|
1110
|
+
...recent
|
|
1111
|
+
]
|
|
1112
|
+
} : null;
|
|
1113
|
+
}
|
|
1114
|
+
function describeImageReferences(messages) {
|
|
1115
|
+
return messages.map((message) => {
|
|
1116
|
+
if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
|
|
1117
|
+
return message;
|
|
1118
|
+
const content = message.content.map(
|
|
1119
|
+
(part) => part.type === "image_ref" ? {
|
|
1120
|
+
type: "text",
|
|
1121
|
+
text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
|
|
1122
|
+
} : part
|
|
1123
|
+
);
|
|
1124
|
+
return { ...message, content };
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
|
|
998
1128
|
// src/services/compaction/service.ts
|
|
999
1129
|
var DEFAULT_THRESHOLD_RATIO = 0.85;
|
|
1000
1130
|
var DEFAULT_RETAIN_LAST_TURNS = 1;
|
|
@@ -1009,14 +1139,14 @@ var CompactionService = class _CompactionService {
|
|
|
1009
1139
|
this.config = _CompactionService.normalizeConfig(config);
|
|
1010
1140
|
this.modelRegistry = deps.modelRegistry;
|
|
1011
1141
|
}
|
|
1012
|
-
async shouldCompact(llm, usage) {
|
|
1142
|
+
async shouldCompact(llm, usage, estimatedInputTokens) {
|
|
1013
1143
|
if (!this.config.enabled) {
|
|
1014
1144
|
return false;
|
|
1015
1145
|
}
|
|
1016
1146
|
if (!this.config.auto) {
|
|
1017
1147
|
return false;
|
|
1018
1148
|
}
|
|
1019
|
-
if (!usage) {
|
|
1149
|
+
if (!usage && estimatedInputTokens === void 0) {
|
|
1020
1150
|
return false;
|
|
1021
1151
|
}
|
|
1022
1152
|
let contextLimit;
|
|
@@ -1026,7 +1156,7 @@ var CompactionService = class _CompactionService {
|
|
|
1026
1156
|
return false;
|
|
1027
1157
|
}
|
|
1028
1158
|
const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
|
|
1029
|
-
return usage
|
|
1159
|
+
return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
|
|
1030
1160
|
}
|
|
1031
1161
|
async compact(llm, messages, options) {
|
|
1032
1162
|
if (!this.config.enabled) {
|
|
@@ -1053,7 +1183,10 @@ var CompactionService = class _CompactionService {
|
|
|
1053
1183
|
try {
|
|
1054
1184
|
response = await llm.ainvoke(
|
|
1055
1185
|
{
|
|
1056
|
-
messages: [
|
|
1186
|
+
messages: describeImageReferences([
|
|
1187
|
+
...preparedMessages,
|
|
1188
|
+
interruptMessage
|
|
1189
|
+
]),
|
|
1057
1190
|
tools: null,
|
|
1058
1191
|
toolChoice: "none",
|
|
1059
1192
|
...options?.signal ? { signal: options.signal } : {},
|
|
@@ -1163,7 +1296,7 @@ var CompactionService = class _CompactionService {
|
|
|
1163
1296
|
);
|
|
1164
1297
|
const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
|
|
1165
1298
|
const conversationMessages = nonSystemMessages.filter(
|
|
1166
|
-
(message) => !isCompactionMemoryMessage(message)
|
|
1299
|
+
(message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
|
|
1167
1300
|
);
|
|
1168
1301
|
const tail = this.normalizeRetainedTail(
|
|
1169
1302
|
this.getLastTurns(conversationMessages, this.config.retainLastTurns)
|
|
@@ -1181,6 +1314,8 @@ var CompactionService = class _CompactionService {
|
|
|
1181
1314
|
content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
|
|
1182
1315
|
});
|
|
1183
1316
|
}
|
|
1317
|
+
const imageRegistry = imageReferenceRegistry(messages);
|
|
1318
|
+
if (imageRegistry) compacted.push(imageRegistry);
|
|
1184
1319
|
compacted.push(...tail);
|
|
1185
1320
|
return compacted;
|
|
1186
1321
|
}
|
|
@@ -1242,7 +1377,7 @@ var CompactionService = class _CompactionService {
|
|
|
1242
1377
|
return messages.slice(startIndex);
|
|
1243
1378
|
}
|
|
1244
1379
|
async resolveContextLimit(llm, usage) {
|
|
1245
|
-
const modelId = usage
|
|
1380
|
+
const modelId = usage?.model ?? llm.model;
|
|
1246
1381
|
const modelSpec = this.resolveModelSpecWithSnapshotFallback(
|
|
1247
1382
|
llm.provider,
|
|
1248
1383
|
modelId
|
|
@@ -1610,6 +1745,239 @@ var TokenUsageService = class {
|
|
|
1610
1745
|
}
|
|
1611
1746
|
};
|
|
1612
1747
|
|
|
1748
|
+
// src/agent/image-context.ts
|
|
1749
|
+
import { imageSize } from "image-size";
|
|
1750
|
+
|
|
1751
|
+
// src/llm/image-policy.ts
|
|
1752
|
+
function estimateImageTokens(provider, model, image) {
|
|
1753
|
+
let name = model.toLowerCase();
|
|
1754
|
+
if (provider === "openrouter") {
|
|
1755
|
+
if (name.startsWith("openai/")) provider = "openai";
|
|
1756
|
+
else if (name.startsWith("anthropic/")) provider = "anthropic";
|
|
1757
|
+
name = name.slice(name.indexOf("/") + 1);
|
|
1758
|
+
}
|
|
1759
|
+
const width = image.width;
|
|
1760
|
+
const height = image.height;
|
|
1761
|
+
const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
|
|
1762
|
+
const patches = (size, edge, budget, multiplier = 1) => {
|
|
1763
|
+
if (!dimensionsKnown)
|
|
1764
|
+
return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
|
|
1765
|
+
const scale = Math.min(1, edge / Math.max(width, height));
|
|
1766
|
+
return {
|
|
1767
|
+
tokens: Math.ceil(
|
|
1768
|
+
Math.min(
|
|
1769
|
+
budget,
|
|
1770
|
+
Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
|
|
1771
|
+
) * multiplier
|
|
1772
|
+
),
|
|
1773
|
+
method: "patch"
|
|
1774
|
+
};
|
|
1775
|
+
};
|
|
1776
|
+
if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
|
|
1777
|
+
name
|
|
1778
|
+
)) {
|
|
1779
|
+
const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
|
|
1780
|
+
name
|
|
1781
|
+
);
|
|
1782
|
+
return patches(
|
|
1783
|
+
28,
|
|
1784
|
+
highResolution ? 2576 : 1568,
|
|
1785
|
+
highResolution ? 4784 : 1568
|
|
1786
|
+
);
|
|
1787
|
+
}
|
|
1788
|
+
if (provider === "openai") {
|
|
1789
|
+
if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
|
|
1790
|
+
return patches(32, 512, 256, 1.2);
|
|
1791
|
+
if (/^gpt-6-astra(-|$)/.test(name))
|
|
1792
|
+
return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
|
|
1793
|
+
if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
|
|
1794
|
+
return patches(
|
|
1795
|
+
32,
|
|
1796
|
+
image.detail === "high" ? 2048 : 65535,
|
|
1797
|
+
image.detail === "high" ? 2500 : 3e4,
|
|
1798
|
+
1.2
|
|
1799
|
+
);
|
|
1800
|
+
if (/^gpt-5\.5(-|$)/.test(name))
|
|
1801
|
+
return patches(
|
|
1802
|
+
32,
|
|
1803
|
+
image.detail === "high" ? 2048 : 6e3,
|
|
1804
|
+
image.detail === "high" ? 2500 : 1e4,
|
|
1805
|
+
1.2
|
|
1806
|
+
);
|
|
1807
|
+
if (/^gpt-5\.4(-|$)/.test(name))
|
|
1808
|
+
return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
|
|
1809
|
+
if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
|
|
1810
|
+
if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
|
|
1811
|
+
if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
|
|
1812
|
+
const mini = name.startsWith("gpt-4o-mini");
|
|
1813
|
+
const base = mini ? 2833 : 85;
|
|
1814
|
+
const tile = mini ? 5667 : 170;
|
|
1815
|
+
if (image.detail === "low") return { tokens: base, method: "tile" };
|
|
1816
|
+
if (!dimensionsKnown)
|
|
1817
|
+
return { tokens: base + tile * 8, method: "fallback" };
|
|
1818
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
1819
|
+
const shortFit = 768 / (Math.min(width, height) * fit);
|
|
1820
|
+
return {
|
|
1821
|
+
tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
|
|
1822
|
+
method: "tile"
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
return { tokens: 1e4, method: "fallback" };
|
|
1827
|
+
}
|
|
1828
|
+
function imagePayloadLimit(provider) {
|
|
1829
|
+
if (provider === "anthropic") return 32e6;
|
|
1830
|
+
if (provider === "openai") return 512e6;
|
|
1831
|
+
return void 0;
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
// src/agent/image-context.ts
|
|
1835
|
+
function estimateImageContext(input, llm, resolveReferences = true) {
|
|
1836
|
+
let imageTokens = 0;
|
|
1837
|
+
let imageCount = 0;
|
|
1838
|
+
let fallbackCount = 0;
|
|
1839
|
+
let imageBytes = 0;
|
|
1840
|
+
const account = (image) => {
|
|
1841
|
+
const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
|
|
1842
|
+
if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
|
|
1843
|
+
throw new Error("Invalid model image-token estimate");
|
|
1844
|
+
imageTokens += estimate.tokens;
|
|
1845
|
+
imageCount++;
|
|
1846
|
+
if (estimate.method === "fallback") fallbackCount++;
|
|
1847
|
+
};
|
|
1848
|
+
const messages = input.messages.map((message) => {
|
|
1849
|
+
if (!Array.isArray(message.content)) return message;
|
|
1850
|
+
const registry = isImageRegistry(message);
|
|
1851
|
+
return {
|
|
1852
|
+
...message,
|
|
1853
|
+
content: message.content.map((part) => {
|
|
1854
|
+
if (part.type === "image_ref") {
|
|
1855
|
+
if (!registry && resolveReferences) {
|
|
1856
|
+
account({
|
|
1857
|
+
width: part.image_ref.width,
|
|
1858
|
+
height: part.image_ref.height,
|
|
1859
|
+
detail: part.detail
|
|
1860
|
+
});
|
|
1861
|
+
imageBytes += 4 * Math.ceil(
|
|
1862
|
+
(part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
|
|
1863
|
+
) + 64;
|
|
1864
|
+
}
|
|
1865
|
+
return {
|
|
1866
|
+
type: "text",
|
|
1867
|
+
text: `[Image ${part.image_ref.artifact_id}]`
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
if (part.type === "image_url") {
|
|
1871
|
+
let dimensions = {};
|
|
1872
|
+
const url = part.image_url.url;
|
|
1873
|
+
const comma = url.indexOf(",");
|
|
1874
|
+
if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
|
|
1875
|
+
try {
|
|
1876
|
+
dimensions = imageSize(
|
|
1877
|
+
Buffer.from(url.slice(comma + 1), "base64")
|
|
1878
|
+
);
|
|
1879
|
+
} catch {
|
|
1880
|
+
dimensions = {};
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
account({ ...dimensions, detail: part.image_url.detail });
|
|
1884
|
+
imageBytes += Buffer.byteLength(part.image_url.url);
|
|
1885
|
+
return { type: "text", text: "[Image]" };
|
|
1886
|
+
}
|
|
1887
|
+
if (part.type === "document")
|
|
1888
|
+
return {
|
|
1889
|
+
type: "text",
|
|
1890
|
+
text: "[Document: token estimate unavailable]"
|
|
1891
|
+
};
|
|
1892
|
+
return part;
|
|
1893
|
+
})
|
|
1894
|
+
};
|
|
1895
|
+
});
|
|
1896
|
+
const textBytes = Buffer.byteLength(
|
|
1897
|
+
JSON.stringify({
|
|
1898
|
+
messages,
|
|
1899
|
+
tools: input.tools ?? null,
|
|
1900
|
+
tool_choice: input.toolChoice
|
|
1901
|
+
})
|
|
1902
|
+
);
|
|
1903
|
+
const textTokens = Math.ceil(textBytes / 3);
|
|
1904
|
+
return {
|
|
1905
|
+
text_tokens: textTokens,
|
|
1906
|
+
image_tokens: imageTokens,
|
|
1907
|
+
total_tokens: textTokens + imageTokens,
|
|
1908
|
+
image_count: imageCount,
|
|
1909
|
+
fallback_image_count: fallbackCount,
|
|
1910
|
+
encoded_image_bytes: imageBytes,
|
|
1911
|
+
estimated_request_bytes: textBytes + imageBytes
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1914
|
+
function validateImagePayload(estimate, llm) {
|
|
1915
|
+
const limit = imagePayloadLimit(llm.provider);
|
|
1916
|
+
if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
|
|
1917
|
+
throw new Error(
|
|
1918
|
+
`Image-bearing request exceeds the ${llm.provider} transport payload budget (${limit} bytes), not the context-token budget. Use smaller attachments in a new conversation or explicitly reorganize this history. Originals are unchanged; no model request was sent.`
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// src/agent/image-input.ts
|
|
1923
|
+
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
1924
|
+
async function materializeImageReferences(messages, resolve, signal) {
|
|
1925
|
+
signal?.throwIfAborted();
|
|
1926
|
+
if (resolve) {
|
|
1927
|
+
for (const message of messages) {
|
|
1928
|
+
if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
|
|
1929
|
+
for (const part of message.content) {
|
|
1930
|
+
if (part.type !== "image_ref") continue;
|
|
1931
|
+
const size = part.image_ref.byte_size;
|
|
1932
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
|
|
1933
|
+
throw new Error(
|
|
1934
|
+
"Invalid or oversized image reference; model request was not sent."
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
const result = [];
|
|
1940
|
+
for (const message of messages) {
|
|
1941
|
+
if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
|
|
1942
|
+
result.push(message);
|
|
1943
|
+
continue;
|
|
1944
|
+
}
|
|
1945
|
+
const registry = isImageRegistry(message);
|
|
1946
|
+
const content = [];
|
|
1947
|
+
for (const part of message.content) {
|
|
1948
|
+
if (part.type !== "image_ref") {
|
|
1949
|
+
content.push(part);
|
|
1950
|
+
continue;
|
|
1951
|
+
}
|
|
1952
|
+
signal?.throwIfAborted();
|
|
1953
|
+
if (!registry && resolve) {
|
|
1954
|
+
try {
|
|
1955
|
+
const image = await resolve(part.image_ref, signal);
|
|
1956
|
+
content.push(
|
|
1957
|
+
part.detail ? {
|
|
1958
|
+
...image,
|
|
1959
|
+
image_url: { ...image.image_url, detail: part.detail }
|
|
1960
|
+
} : image
|
|
1961
|
+
);
|
|
1962
|
+
signal?.throwIfAborted();
|
|
1963
|
+
continue;
|
|
1964
|
+
} catch {
|
|
1965
|
+
signal?.throwIfAborted();
|
|
1966
|
+
throw new Error(
|
|
1967
|
+
`Image artifact ${part.image_ref.artifact_id} or its fixed model view is unavailable or corrupt. Restore the saved bytes or compact the conversation; model request was not sent to avoid rewriting earlier image input.`
|
|
1968
|
+
);
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
content.push({
|
|
1972
|
+
type: "text",
|
|
1973
|
+
text: `[Image artifact ${part.image_ref.artifact_id}: ${registry ? "compacted image registry; use image_inspect to revisit" : "image input unavailable on this connection"}. Not visually inspected.]`
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
result.push({ ...message, content });
|
|
1977
|
+
}
|
|
1978
|
+
return result;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1613
1981
|
// src/agent/model-context.ts
|
|
1614
1982
|
var calculateContextLeftPercent = ({
|
|
1615
1983
|
usage,
|
|
@@ -1691,16 +2059,16 @@ var collectModelOutput = (messages) => {
|
|
|
1691
2059
|
if (message.role === "reasoning") {
|
|
1692
2060
|
const raw = message.raw_item;
|
|
1693
2061
|
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1694
|
-
const
|
|
1695
|
-
const kind =
|
|
1696
|
-
const statusRaw =
|
|
2062
|
+
const record3 = raw;
|
|
2063
|
+
const kind = record3.type === "x_search_call" ? "x" : "web";
|
|
2064
|
+
const statusRaw = record3.status;
|
|
1697
2065
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1698
|
-
const action =
|
|
2066
|
+
const action = record3.action && typeof record3.action === "object" ? record3.action : null;
|
|
1699
2067
|
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1700
2068
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1701
2069
|
) : [];
|
|
1702
2070
|
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1703
|
-
const explicitId = typeof
|
|
2071
|
+
const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
|
|
1704
2072
|
let id = explicitId;
|
|
1705
2073
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1706
2074
|
if (!id) {
|
|
@@ -1936,7 +2304,7 @@ var executeToolCall = async ({
|
|
|
1936
2304
|
|
|
1937
2305
|
// src/agent/agent.ts
|
|
1938
2306
|
var DEFAULT_MAX_ITERATIONS = 200;
|
|
1939
|
-
var defaultMonotonicNowMs = () =>
|
|
2307
|
+
var defaultMonotonicNowMs = () => performance2.now();
|
|
1940
2308
|
var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
|
|
1941
2309
|
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
1942
2310
|
var createAbortError2 = () => {
|
|
@@ -1970,6 +2338,7 @@ var Agent = class {
|
|
|
1970
2338
|
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
1971
2339
|
history;
|
|
1972
2340
|
usageService;
|
|
2341
|
+
imageUsageBaseline;
|
|
1973
2342
|
constructor(options) {
|
|
1974
2343
|
this.llm = options.llm;
|
|
1975
2344
|
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
@@ -2022,13 +2391,15 @@ var Agent = class {
|
|
|
2022
2391
|
}
|
|
2023
2392
|
replaceHistoryMessages(messages) {
|
|
2024
2393
|
this.history.replaceViewMessages(messages);
|
|
2394
|
+
this.imageUsageBaseline = void 0;
|
|
2025
2395
|
}
|
|
2026
2396
|
async *checkAndCompact(signal, options = {}) {
|
|
2027
2397
|
throwIfAborted(signal);
|
|
2028
2398
|
await this.trimToolOutputs();
|
|
2029
2399
|
const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
|
|
2030
2400
|
this.llm,
|
|
2031
|
-
this.usageService.getLastUsage()
|
|
2401
|
+
this.usageService.getLastUsage(),
|
|
2402
|
+
options.estimatedInputTokens
|
|
2032
2403
|
);
|
|
2033
2404
|
if (shouldCompact && this.compactionService) {
|
|
2034
2405
|
throwIfAborted(signal);
|
|
@@ -2049,6 +2420,7 @@ var Agent = class {
|
|
|
2049
2420
|
this.usageService.updateUsageSummary(usage);
|
|
2050
2421
|
if (compacted && compactedMessages) {
|
|
2051
2422
|
this.history.replaceViewMessages(compactedMessages);
|
|
2423
|
+
this.imageUsageBaseline = void 0;
|
|
2052
2424
|
}
|
|
2053
2425
|
if (compacted || options.force) {
|
|
2054
2426
|
await this.llm.onHistoryCompacted?.(invokeContext);
|
|
@@ -2107,9 +2479,13 @@ var Agent = class {
|
|
|
2107
2479
|
const runId = session?.run_id?.trim();
|
|
2108
2480
|
return runId && runId.length > 0 ? runId : void 0;
|
|
2109
2481
|
}
|
|
2110
|
-
buildInvokeContext(session) {
|
|
2482
|
+
buildInvokeContext(session, turnKey) {
|
|
2111
2483
|
const sessionKey = this.resolveSessionKey(session);
|
|
2112
|
-
|
|
2484
|
+
const turn = turnKey ?? session?.run_id;
|
|
2485
|
+
return sessionKey || turn ? {
|
|
2486
|
+
...sessionKey ? { sessionKey } : {},
|
|
2487
|
+
...turn ? { turnKey: turn } : {}
|
|
2488
|
+
} : void 0;
|
|
2113
2489
|
}
|
|
2114
2490
|
recordLlmResponse(session, seq, response) {
|
|
2115
2491
|
if (!session || seq === null) return;
|
|
@@ -2120,6 +2496,7 @@ var Agent = class {
|
|
|
2120
2496
|
seq,
|
|
2121
2497
|
output: {
|
|
2122
2498
|
messages: response.messages,
|
|
2499
|
+
...response.timing ? { timing: response.timing } : {},
|
|
2123
2500
|
usage: response.usage ?? null,
|
|
2124
2501
|
stop_reason: response.stop_reason ?? null,
|
|
2125
2502
|
provider_meta: response.provider_meta ?? null
|
|
@@ -2127,19 +2504,43 @@ var Agent = class {
|
|
|
2127
2504
|
});
|
|
2128
2505
|
}
|
|
2129
2506
|
async *invokeModelWithRetry(input, context, signal) {
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2507
|
+
const estimate = estimateImageContext(
|
|
2508
|
+
input,
|
|
2509
|
+
this.llm,
|
|
2510
|
+
Boolean(this.services.resolveImage)
|
|
2511
|
+
);
|
|
2512
|
+
validateImagePayload(estimate, this.llm);
|
|
2513
|
+
const messages = await materializeImageReferences(
|
|
2514
|
+
input.messages,
|
|
2515
|
+
this.services.resolveImage,
|
|
2516
|
+
signal
|
|
2517
|
+
);
|
|
2518
|
+
const response = yield* withProviderStatus(
|
|
2519
|
+
(onProviderStatus, progressSignal) => invokeWithRetry({
|
|
2520
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2521
|
+
{
|
|
2522
|
+
...input,
|
|
2523
|
+
messages,
|
|
2524
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2525
|
+
},
|
|
2526
|
+
{ ...context, onProviderStatus }
|
|
2527
|
+
),
|
|
2528
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2529
|
+
policy: resolveLlmRetryPolicy({
|
|
2530
|
+
...this.llmRetryPolicy,
|
|
2531
|
+
...this.llm.retryPolicy
|
|
2532
|
+
}),
|
|
2533
|
+
signal: progressSignal,
|
|
2534
|
+
dependencies: this.llmRetryDependencies
|
|
2535
|
+
}),
|
|
2536
|
+
signal
|
|
2537
|
+
);
|
|
2538
|
+
this.imageUsageBaseline = response.usage ? {
|
|
2539
|
+
messages: input.messages.slice(),
|
|
2540
|
+
estimated: estimate.total_tokens,
|
|
2541
|
+
observed: response.usage.input_tokens
|
|
2542
|
+
} : void 0;
|
|
2543
|
+
return response;
|
|
2143
2544
|
}
|
|
2144
2545
|
async run(message, options = {}) {
|
|
2145
2546
|
let finalResponse = "";
|
|
@@ -2177,6 +2578,7 @@ var Agent = class {
|
|
|
2177
2578
|
for (const content of messages) this.history.enqueueUserMessage(content);
|
|
2178
2579
|
return messages;
|
|
2179
2580
|
};
|
|
2581
|
+
const turnKey = session?.run_id ?? randomUUID();
|
|
2180
2582
|
let iterations = 0;
|
|
2181
2583
|
const runTools = [...this.tools, ...options.tools ?? []];
|
|
2182
2584
|
const runToolChoice = options.toolChoice ?? this.toolChoice;
|
|
@@ -2187,11 +2589,27 @@ var Agent = class {
|
|
|
2187
2589
|
yield { type: "hidden_user_message", content };
|
|
2188
2590
|
await this.trimToolOutputs();
|
|
2189
2591
|
throwIfAborted(signal);
|
|
2190
|
-
|
|
2592
|
+
let invokeInput = this.history.prepareInvokeInput({
|
|
2191
2593
|
tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
|
|
2192
2594
|
toolChoice: runToolChoice
|
|
2193
2595
|
});
|
|
2194
|
-
const
|
|
2596
|
+
const imageEstimate = estimateImageContext(
|
|
2597
|
+
invokeInput,
|
|
2598
|
+
this.llm,
|
|
2599
|
+
Boolean(this.services.resolveImage)
|
|
2600
|
+
);
|
|
2601
|
+
if (imageEstimate.image_count > 0) {
|
|
2602
|
+
const baseline = this.imageUsageBaseline;
|
|
2603
|
+
const estimatedInputTokens = baseline && baseline.messages.every(
|
|
2604
|
+
(message2, index) => invokeInput.messages[index] === message2
|
|
2605
|
+
) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
|
|
2606
|
+
yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
|
|
2607
|
+
invokeInput = this.history.prepareInvokeInput({
|
|
2608
|
+
tools: invokeInput.tools,
|
|
2609
|
+
toolChoice: runToolChoice
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2195
2613
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
2196
2614
|
const response = yield* this.invokeModelWithRetry(
|
|
2197
2615
|
invokeInput,
|
|
@@ -2416,7 +2834,11 @@ var Agent = class {
|
|
|
2416
2834
|
yield* this.checkAndCompact(signal, { session });
|
|
2417
2835
|
}
|
|
2418
2836
|
if (signal?.aborted) throw createAbortError2();
|
|
2419
|
-
const finalResponse = await this.generateFinalResponse(
|
|
2837
|
+
const finalResponse = await this.generateFinalResponse(
|
|
2838
|
+
session,
|
|
2839
|
+
signal,
|
|
2840
|
+
turnKey
|
|
2841
|
+
);
|
|
2420
2842
|
const finalResponseEvent = {
|
|
2421
2843
|
type: "final",
|
|
2422
2844
|
termination_reason: "max_steps",
|
|
@@ -2425,7 +2847,7 @@ var Agent = class {
|
|
|
2425
2847
|
yield finalResponseEvent;
|
|
2426
2848
|
return;
|
|
2427
2849
|
}
|
|
2428
|
-
async generateFinalResponse(session, signal) {
|
|
2850
|
+
async generateFinalResponse(session, signal, turnKey) {
|
|
2429
2851
|
const summaryMessage = {
|
|
2430
2852
|
role: "user",
|
|
2431
2853
|
content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
|
|
@@ -2438,11 +2860,24 @@ var Agent = class {
|
|
|
2438
2860
|
// no tools are allowed at this point
|
|
2439
2861
|
toolChoice: "none"
|
|
2440
2862
|
};
|
|
2441
|
-
const invokeContext = this.buildInvokeContext(session);
|
|
2863
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2442
2864
|
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
2865
|
+
validateImagePayload(
|
|
2866
|
+
estimateImageContext(
|
|
2867
|
+
input,
|
|
2868
|
+
this.llm,
|
|
2869
|
+
Boolean(this.services.resolveImage)
|
|
2870
|
+
),
|
|
2871
|
+
this.llm
|
|
2872
|
+
);
|
|
2443
2873
|
const summary = await this.llm.ainvoke(
|
|
2444
2874
|
{
|
|
2445
2875
|
...input,
|
|
2876
|
+
messages: await materializeImageReferences(
|
|
2877
|
+
input.messages,
|
|
2878
|
+
this.services.resolveImage,
|
|
2879
|
+
signal
|
|
2880
|
+
),
|
|
2446
2881
|
...signal ? { signal } : {}
|
|
2447
2882
|
},
|
|
2448
2883
|
invokeContext
|
|
@@ -2463,6 +2898,88 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
2463
2898
|
}
|
|
2464
2899
|
};
|
|
2465
2900
|
|
|
2901
|
+
// src/llm/stream-timing.ts
|
|
2902
|
+
var record = (value) => value !== null && typeof value === "object" ? value : void 0;
|
|
2903
|
+
var nonempty = (value) => typeof value === "string" && value.length > 0;
|
|
2904
|
+
var responseOutputDeltas = /* @__PURE__ */ new Set([
|
|
2905
|
+
"response.output_text.delta",
|
|
2906
|
+
"response.refusal.delta",
|
|
2907
|
+
"response.function_call_arguments.delta",
|
|
2908
|
+
"response.custom_tool_call_input.delta",
|
|
2909
|
+
"response.reasoning_text.delta",
|
|
2910
|
+
"response.reasoning_summary_text.delta"
|
|
2911
|
+
]);
|
|
2912
|
+
var LlmStreamTiming = class {
|
|
2913
|
+
constructor(nowMs = () => performance.now()) {
|
|
2914
|
+
this.nowMs = nowMs;
|
|
2915
|
+
this.startedAt = nowMs();
|
|
2916
|
+
}
|
|
2917
|
+
nowMs;
|
|
2918
|
+
startedAt;
|
|
2919
|
+
firstOutputAt;
|
|
2920
|
+
reasoningStartedAt;
|
|
2921
|
+
completedAt;
|
|
2922
|
+
observeOutput() {
|
|
2923
|
+
if (this.completedAt === void 0 && this.firstOutputAt === void 0)
|
|
2924
|
+
this.firstOutputAt = this.nowMs();
|
|
2925
|
+
}
|
|
2926
|
+
complete() {
|
|
2927
|
+
this.completedAt ??= this.nowMs();
|
|
2928
|
+
}
|
|
2929
|
+
observeResponsesEvent(event) {
|
|
2930
|
+
const value = record(event);
|
|
2931
|
+
if (!value) return;
|
|
2932
|
+
if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
|
|
2933
|
+
this.reasoningStartedAt ??= this.nowMs();
|
|
2934
|
+
if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
|
|
2935
|
+
this.observeOutput();
|
|
2936
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
|
|
2937
|
+
this.complete();
|
|
2938
|
+
}
|
|
2939
|
+
observeChatChunk(chunk) {
|
|
2940
|
+
const choices = record(chunk)?.choices;
|
|
2941
|
+
if (!Array.isArray(choices)) return;
|
|
2942
|
+
for (const choice of choices) {
|
|
2943
|
+
const delta = record(record(choice)?.delta);
|
|
2944
|
+
if (!delta) continue;
|
|
2945
|
+
if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
|
|
2946
|
+
(tool) => nonempty(record(record(tool)?.function)?.arguments)
|
|
2947
|
+
))
|
|
2948
|
+
this.observeOutput();
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
observeAnthropicEvent(event) {
|
|
2952
|
+
const value = record(event);
|
|
2953
|
+
if (!value) return;
|
|
2954
|
+
const delta = record(value.delta);
|
|
2955
|
+
if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
|
|
2956
|
+
this.observeOutput();
|
|
2957
|
+
if (value.type === "message_stop") this.complete();
|
|
2958
|
+
}
|
|
2959
|
+
finish() {
|
|
2960
|
+
this.complete();
|
|
2961
|
+
if (this.firstOutputAt === void 0) return void 0;
|
|
2962
|
+
const first = this.firstOutputAt - this.startedAt;
|
|
2963
|
+
const start = Math.min(
|
|
2964
|
+
this.firstOutputAt,
|
|
2965
|
+
this.reasoningStartedAt ?? this.firstOutputAt
|
|
2966
|
+
);
|
|
2967
|
+
const generation = this.completedAt - start;
|
|
2968
|
+
if (![first, generation, start - this.startedAt].every(
|
|
2969
|
+
(ms) => Number.isFinite(ms) && ms >= 0
|
|
2970
|
+
))
|
|
2971
|
+
return void 0;
|
|
2972
|
+
return {
|
|
2973
|
+
time_to_first_token_ms: first,
|
|
2974
|
+
generation_duration_ms: generation,
|
|
2975
|
+
...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
|
|
2976
|
+
generation_start_ms: start - this.startedAt,
|
|
2977
|
+
generation_start_source: "reasoning_item"
|
|
2978
|
+
} : {}
|
|
2979
|
+
};
|
|
2980
|
+
}
|
|
2981
|
+
};
|
|
2982
|
+
|
|
2466
2983
|
// src/llm/anthropic/chat.ts
|
|
2467
2984
|
import { createHash } from "crypto";
|
|
2468
2985
|
import Anthropic from "@anthropic-ai/sdk";
|
|
@@ -2589,6 +3106,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
|
|
|
2589
3106
|
};
|
|
2590
3107
|
|
|
2591
3108
|
// src/types/llm/guards.ts
|
|
3109
|
+
import { isImageModelView } from "@codelia/shared-types";
|
|
2592
3110
|
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2593
3111
|
function isTextPart(value) {
|
|
2594
3112
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2617,7 +3135,19 @@ function isOtherPart(value) {
|
|
|
2617
3135
|
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2618
3136
|
}
|
|
2619
3137
|
function isContentPart(value) {
|
|
2620
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3138
|
+
return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3139
|
+
}
|
|
3140
|
+
function isImageRefPart(value) {
|
|
3141
|
+
if (!value || typeof value !== "object") return false;
|
|
3142
|
+
const v = value;
|
|
3143
|
+
if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
|
|
3144
|
+
return false;
|
|
3145
|
+
const r = v.image_ref;
|
|
3146
|
+
return (r.model_view === void 0 || isImageModelView(r.model_view)) && typeof r.artifact_id === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(r.artifact_id) && typeof r.sha256 === "string" && /^[0-9a-f]{64}$/.test(r.sha256) && ["image/png", "image/jpeg", "image/webp", "image/gif"].includes(
|
|
3147
|
+
String(r.media_type)
|
|
3148
|
+
) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
|
|
3149
|
+
(n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
|
|
3150
|
+
) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
|
|
2621
3151
|
}
|
|
2622
3152
|
function isToolResult(value) {
|
|
2623
3153
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2721,6 +3251,15 @@ var toContentBlocks = (content) => {
|
|
|
2721
3251
|
}
|
|
2722
3252
|
};
|
|
2723
3253
|
}
|
|
3254
|
+
if (URL.canParse(part.image_url.url)) {
|
|
3255
|
+
const url = new URL(part.image_url.url);
|
|
3256
|
+
if (url.protocol === "https:" || url.protocol === "http:") {
|
|
3257
|
+
return {
|
|
3258
|
+
type: "image",
|
|
3259
|
+
source: { type: "url", url: part.image_url.url }
|
|
3260
|
+
};
|
|
3261
|
+
}
|
|
3262
|
+
}
|
|
2724
3263
|
return toTextBlock(part.image_url.url);
|
|
2725
3264
|
}
|
|
2726
3265
|
case "document":
|
|
@@ -3138,20 +3677,27 @@ var ChatAnthropic = class {
|
|
|
3138
3677
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
3139
3678
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
3140
3679
|
const requestOptions = signal ? { signal } : void 0;
|
|
3141
|
-
const
|
|
3680
|
+
const timing = new LlmStreamTiming();
|
|
3681
|
+
const stream = this.fastMode ? this.client.beta.messages.stream(
|
|
3142
3682
|
request,
|
|
3143
3683
|
requestOptions
|
|
3144
|
-
) :
|
|
3684
|
+
) : this.client.messages.stream(
|
|
3145
3685
|
request,
|
|
3146
3686
|
requestOptions
|
|
3147
3687
|
);
|
|
3688
|
+
for await (const event of stream) timing.observeAnthropicEvent(event);
|
|
3689
|
+
const response = await stream.finalMessage();
|
|
3690
|
+
const measuredTiming = timing.finish();
|
|
3148
3691
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3149
|
-
return
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3692
|
+
return {
|
|
3693
|
+
...toChatInvokeCompletion(response, {
|
|
3694
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
3695
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
3696
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
|
|
3697
|
+
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
|
|
3698
|
+
}),
|
|
3699
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
3700
|
+
};
|
|
3155
3701
|
}
|
|
3156
3702
|
nextDebugInvokeSeq() {
|
|
3157
3703
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -3639,6 +4185,7 @@ var ChatMoonshot = class {
|
|
|
3639
4185
|
const seq = this.nextDebugInvokeSeq();
|
|
3640
4186
|
await this.debugRequestIfEnabled(request, seq);
|
|
3641
4187
|
const client = new OpenAI({ apiKey: this.apiKey, ...this.clientOptions });
|
|
4188
|
+
const timing = new LlmStreamTiming();
|
|
3642
4189
|
const accumulator = createMoonshotStreamAccumulator();
|
|
3643
4190
|
try {
|
|
3644
4191
|
const stream = await client.chat.completions.create(
|
|
@@ -3646,6 +4193,7 @@ var ChatMoonshot = class {
|
|
|
3646
4193
|
{ signal: input.signal }
|
|
3647
4194
|
);
|
|
3648
4195
|
for await (const chunk of stream) {
|
|
4196
|
+
timing.observeChatChunk(chunk);
|
|
3649
4197
|
appendMoonshotChatCompletionChunk(
|
|
3650
4198
|
accumulator,
|
|
3651
4199
|
chunk
|
|
@@ -3658,11 +4206,15 @@ var ChatMoonshot = class {
|
|
|
3658
4206
|
{ cause: error }
|
|
3659
4207
|
);
|
|
3660
4208
|
}
|
|
4209
|
+
const measuredTiming = timing.finish();
|
|
3661
4210
|
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3662
|
-
return
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
4211
|
+
return {
|
|
4212
|
+
...toMoonshotChatInvokeCompletion(accumulator, {
|
|
4213
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
4214
|
+
reasoningFallback: this.reasoningLevelRequested !== "max"
|
|
4215
|
+
}),
|
|
4216
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
4217
|
+
};
|
|
3666
4218
|
}
|
|
3667
4219
|
nextDebugInvokeSeq() {
|
|
3668
4220
|
this.debugInvokeSeq += 1;
|
|
@@ -3728,9 +4280,183 @@ var ChatMoonshot = class {
|
|
|
3728
4280
|
};
|
|
3729
4281
|
|
|
3730
4282
|
// src/llm/openai/chat.ts
|
|
3731
|
-
import { createHash as
|
|
4283
|
+
import { createHash as createHash4 } from "crypto";
|
|
4284
|
+
import OpenAI3 from "openai";
|
|
4285
|
+
|
|
4286
|
+
// src/llm/openai/http-transport.ts
|
|
3732
4287
|
import OpenAI2 from "openai";
|
|
3733
4288
|
|
|
4289
|
+
// src/llm/openai/codex-metadata.ts
|
|
4290
|
+
import { createHash as createHash3 } from "crypto";
|
|
4291
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
4292
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
|
|
4293
|
+
var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
|
|
4294
|
+
var headerValue = (headers, name) => {
|
|
4295
|
+
const entries = record2(headers);
|
|
4296
|
+
const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
4297
|
+
return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
|
|
4298
|
+
};
|
|
4299
|
+
var isCodexBackend = (baseURL) => {
|
|
4300
|
+
try {
|
|
4301
|
+
const url = new URL(baseURL);
|
|
4302
|
+
return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
|
|
4303
|
+
} catch {
|
|
4304
|
+
return false;
|
|
4305
|
+
}
|
|
4306
|
+
};
|
|
4307
|
+
var CodexTurnState = class {
|
|
4308
|
+
owner;
|
|
4309
|
+
value;
|
|
4310
|
+
invalidated = false;
|
|
4311
|
+
bindAuth(headers) {
|
|
4312
|
+
const authorization = headers.get("authorization") ?? "";
|
|
4313
|
+
let identity = authorization;
|
|
4314
|
+
try {
|
|
4315
|
+
const claims = record2(
|
|
4316
|
+
JSON.parse(
|
|
4317
|
+
Buffer.from(
|
|
4318
|
+
authorization.replace(/^Bearer /i, "").split(".")[1],
|
|
4319
|
+
"base64url"
|
|
4320
|
+
).toString("utf8")
|
|
4321
|
+
)
|
|
4322
|
+
);
|
|
4323
|
+
if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
|
|
4324
|
+
const account = record2(
|
|
4325
|
+
claims["https://api.openai.com/auth"]
|
|
4326
|
+
)?.chatgpt_account_id;
|
|
4327
|
+
identity = JSON.stringify([
|
|
4328
|
+
claims.iss,
|
|
4329
|
+
claims.sub,
|
|
4330
|
+
typeof claims.client_id === "string" ? claims.client_id : null,
|
|
4331
|
+
typeof account === "string" ? account : null
|
|
4332
|
+
]);
|
|
4333
|
+
}
|
|
4334
|
+
} catch {
|
|
4335
|
+
}
|
|
4336
|
+
const owner = createHash3("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
|
|
4337
|
+
const changed = this.owner !== void 0 && this.owner !== owner;
|
|
4338
|
+
if (changed) {
|
|
4339
|
+
this.value = void 0;
|
|
4340
|
+
this.invalidated = true;
|
|
4341
|
+
}
|
|
4342
|
+
this.owner = owner;
|
|
4343
|
+
return this.invalidated;
|
|
4344
|
+
}
|
|
4345
|
+
observe(value) {
|
|
4346
|
+
if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
|
|
4347
|
+
this.value = value;
|
|
4348
|
+
}
|
|
4349
|
+
requestHeaders() {
|
|
4350
|
+
return this.value ? { "x-codex-turn-state": this.value } : {};
|
|
4351
|
+
}
|
|
4352
|
+
};
|
|
4353
|
+
var CodexMetadataCollector = class {
|
|
4354
|
+
constructor(routing, onStatus) {
|
|
4355
|
+
this.routing = routing;
|
|
4356
|
+
this.onStatus = onStatus;
|
|
4357
|
+
}
|
|
4358
|
+
routing;
|
|
4359
|
+
onStatus;
|
|
4360
|
+
summary = {};
|
|
4361
|
+
outputStarted = false;
|
|
4362
|
+
fallbackModel;
|
|
4363
|
+
verificationNotified = false;
|
|
4364
|
+
beginAttempt() {
|
|
4365
|
+
this.clearBuffering();
|
|
4366
|
+
for (const key of Object.keys(this.summary))
|
|
4367
|
+
delete this.summary[key];
|
|
4368
|
+
this.outputStarted = false;
|
|
4369
|
+
this.fallbackModel = void 0;
|
|
4370
|
+
}
|
|
4371
|
+
observeHeaders(headers) {
|
|
4372
|
+
this.routing?.observe(headers.get("x-codex-turn-state"));
|
|
4373
|
+
const model = identifier(
|
|
4374
|
+
headers.get("openai-model") ?? headers.get("x-openai-model")
|
|
4375
|
+
);
|
|
4376
|
+
if (model) this.summary.server_model = model;
|
|
4377
|
+
this.fallbackModel = identifier(
|
|
4378
|
+
headers.get("x-codex-safety-buffering-faster-model")
|
|
4379
|
+
);
|
|
4380
|
+
}
|
|
4381
|
+
observeEvent(event) {
|
|
4382
|
+
const value = record2(event);
|
|
4383
|
+
if (!value) return;
|
|
4384
|
+
const response = record2(value.response);
|
|
4385
|
+
const model = identifier(
|
|
4386
|
+
headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
|
|
4387
|
+
);
|
|
4388
|
+
if (model) this.summary.server_model = model;
|
|
4389
|
+
const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
|
|
4390
|
+
if (value.type === "response.metadata")
|
|
4391
|
+
this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
|
|
4392
|
+
const verifications = metadata?.openai_verification_recommendation;
|
|
4393
|
+
if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
|
|
4394
|
+
this.summary.model_verifications = ["trusted_access_for_cyber"];
|
|
4395
|
+
if (!this.verificationNotified) {
|
|
4396
|
+
this.verificationNotified = true;
|
|
4397
|
+
this.emit({
|
|
4398
|
+
type: "llm.status",
|
|
4399
|
+
provider: "openai",
|
|
4400
|
+
kind: "verification",
|
|
4401
|
+
verification: "trusted_access_for_cyber"
|
|
4402
|
+
});
|
|
4403
|
+
}
|
|
4404
|
+
}
|
|
4405
|
+
if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
|
|
4406
|
+
this.summary.moderation_metadata_present = true;
|
|
4407
|
+
const buffering = record2(
|
|
4408
|
+
value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
|
|
4409
|
+
);
|
|
4410
|
+
if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
|
|
4411
|
+
const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
|
|
4412
|
+
const wasActive = this.summary.safety_buffering?.active;
|
|
4413
|
+
this.summary.safety_buffering = {
|
|
4414
|
+
active: !this.outputStarted,
|
|
4415
|
+
use_case_count: buffering.use_cases.length,
|
|
4416
|
+
reason_count: buffering.reasons.length,
|
|
4417
|
+
...faster ? { faster_model: faster } : {}
|
|
4418
|
+
};
|
|
4419
|
+
if (!this.outputStarted && !wasActive)
|
|
4420
|
+
this.emit({
|
|
4421
|
+
type: "llm.status",
|
|
4422
|
+
provider: "openai",
|
|
4423
|
+
kind: "buffering",
|
|
4424
|
+
active: true,
|
|
4425
|
+
...faster ? { faster_model: faster } : {}
|
|
4426
|
+
});
|
|
4427
|
+
}
|
|
4428
|
+
if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
|
|
4429
|
+
this.outputStarted = true;
|
|
4430
|
+
this.clearBuffering();
|
|
4431
|
+
}
|
|
4432
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
|
|
4433
|
+
this.clearBuffering();
|
|
4434
|
+
}
|
|
4435
|
+
finish() {
|
|
4436
|
+
this.clearBuffering();
|
|
4437
|
+
}
|
|
4438
|
+
snapshot() {
|
|
4439
|
+
return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
|
|
4440
|
+
}
|
|
4441
|
+
clearBuffering() {
|
|
4442
|
+
if (this.summary.safety_buffering?.active) {
|
|
4443
|
+
this.summary.safety_buffering.active = false;
|
|
4444
|
+
this.emit({
|
|
4445
|
+
type: "llm.status",
|
|
4446
|
+
provider: "openai",
|
|
4447
|
+
kind: "buffering",
|
|
4448
|
+
active: false
|
|
4449
|
+
});
|
|
4450
|
+
}
|
|
4451
|
+
}
|
|
4452
|
+
emit(event) {
|
|
4453
|
+
try {
|
|
4454
|
+
this.onStatus?.(event);
|
|
4455
|
+
} catch {
|
|
4456
|
+
}
|
|
4457
|
+
}
|
|
4458
|
+
};
|
|
4459
|
+
|
|
3734
4460
|
// src/llm/openai/response-utils.ts
|
|
3735
4461
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
3736
4462
|
var stringifyUnknown3 = (value) => {
|
|
@@ -3772,12 +4498,12 @@ var extractOutputText = (items) => {
|
|
|
3772
4498
|
}
|
|
3773
4499
|
return texts.join("");
|
|
3774
4500
|
};
|
|
3775
|
-
var getRecordString = (
|
|
3776
|
-
const value =
|
|
4501
|
+
var getRecordString = (record3, key) => {
|
|
4502
|
+
const value = record3[key];
|
|
3777
4503
|
return typeof value === "string" ? value : void 0;
|
|
3778
4504
|
};
|
|
3779
|
-
var getRecordNumber = (
|
|
3780
|
-
const value =
|
|
4505
|
+
var getRecordNumber = (record3, key) => {
|
|
4506
|
+
const value = record3[key];
|
|
3781
4507
|
return typeof value === "number" ? value : void 0;
|
|
3782
4508
|
};
|
|
3783
4509
|
var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
|
|
@@ -3787,6 +4513,10 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3787
4513
|
sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
|
|
3788
4514
|
};
|
|
3789
4515
|
const eventRecord = event;
|
|
4516
|
+
const metadata = new CodexMetadataCollector();
|
|
4517
|
+
metadata.observeEvent(event);
|
|
4518
|
+
const summary = metadata.snapshot();
|
|
4519
|
+
if (summary) payload.metadata_summary = summary;
|
|
3790
4520
|
const outputIndex = getRecordNumber(eventRecord, "output_index");
|
|
3791
4521
|
if (outputIndex !== void 0) {
|
|
3792
4522
|
payload.output_index = outputIndex;
|
|
@@ -3940,6 +4670,9 @@ var OpenAiResponseAccumulator = class {
|
|
|
3940
4670
|
terminalResponse = null;
|
|
3941
4671
|
outputItems = [];
|
|
3942
4672
|
observeEvent(event) {
|
|
4673
|
+
const type = event.type;
|
|
4674
|
+
if (type === "response.metadata" || type === "codex.response.metadata")
|
|
4675
|
+
return;
|
|
3943
4676
|
switch (event.type) {
|
|
3944
4677
|
case "response.created":
|
|
3945
4678
|
case "response.queued":
|
|
@@ -4291,22 +5024,64 @@ var OpenAiResponseAccumulator = class {
|
|
|
4291
5024
|
};
|
|
4292
5025
|
|
|
4293
5026
|
// src/llm/openai/http-transport.ts
|
|
4294
|
-
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
|
|
5027
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
|
|
4295
5028
|
const streamRequest = {
|
|
4296
5029
|
...request,
|
|
4297
5030
|
stream: true
|
|
4298
5031
|
};
|
|
4299
|
-
const
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
5032
|
+
const options = signal || sessionIdHeader ? {
|
|
5033
|
+
...signal ? { signal } : {},
|
|
5034
|
+
...sessionIdHeader ? {
|
|
5035
|
+
headers: {
|
|
5036
|
+
session_id: sessionIdHeader
|
|
5037
|
+
}
|
|
5038
|
+
} : {}
|
|
5039
|
+
} : void 0;
|
|
5040
|
+
if (isCodexBackend(client.baseURL)) {
|
|
5041
|
+
codex?.metadata.beginAttempt();
|
|
5042
|
+
const sourceFetch = client.fetch;
|
|
5043
|
+
let ownershipError;
|
|
5044
|
+
const requestClient = codex ? client.withOptions({
|
|
5045
|
+
fetch: async (input, init) => {
|
|
5046
|
+
const headers = new Headers(init?.headers);
|
|
5047
|
+
if (codex.routing?.bindAuth(headers)) {
|
|
5048
|
+
ownershipError = createProviderValidationError(
|
|
5049
|
+
"openai",
|
|
5050
|
+
"OpenAI authentication changed; start a new run"
|
|
5051
|
+
);
|
|
5052
|
+
throw ownershipError;
|
|
4306
5053
|
}
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
5054
|
+
for (const [key, value] of Object.entries(
|
|
5055
|
+
codex.routing?.requestHeaders() ?? {}
|
|
5056
|
+
))
|
|
5057
|
+
headers.set(key, value);
|
|
5058
|
+
const response = await sourceFetch(input, { ...init, headers });
|
|
5059
|
+
codex.metadata.observeHeaders(response.headers);
|
|
5060
|
+
return response;
|
|
5061
|
+
}
|
|
5062
|
+
}) : client;
|
|
5063
|
+
const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
|
|
5064
|
+
throw ownershipError ?? error;
|
|
5065
|
+
});
|
|
5066
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
5067
|
+
for await (const event of stream2) {
|
|
5068
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5069
|
+
codex?.metadata.observeEvent(event);
|
|
5070
|
+
await onEvent?.(event);
|
|
5071
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5072
|
+
if (event.type === "response.failed") {
|
|
5073
|
+
throw event.response.error ?? new Error("OpenAI stream failed");
|
|
5074
|
+
}
|
|
5075
|
+
if (event.type === "error") throw event;
|
|
5076
|
+
accumulator.observeEvent(event);
|
|
5077
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
5078
|
+
return accumulator.buildResponse(event.response);
|
|
5079
|
+
}
|
|
5080
|
+
}
|
|
5081
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5082
|
+
throw new Error("OpenAI stream ended without a terminal response");
|
|
5083
|
+
}
|
|
5084
|
+
const stream = client.responses.stream(streamRequest, options);
|
|
4310
5085
|
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
4311
5086
|
const accumulator = new OpenAiResponseAccumulator();
|
|
4312
5087
|
for await (const event of stream) {
|
|
@@ -4357,12 +5132,12 @@ var formatOtherPart3 = (part) => {
|
|
|
4357
5132
|
};
|
|
4358
5133
|
var isOpenAIAssistantInputContent = (value) => {
|
|
4359
5134
|
if (!value || typeof value !== "object") return false;
|
|
4360
|
-
const
|
|
4361
|
-
if (
|
|
4362
|
-
return typeof
|
|
5135
|
+
const record3 = value;
|
|
5136
|
+
if (record3.type === "output_text") {
|
|
5137
|
+
return typeof record3.text === "string";
|
|
4363
5138
|
}
|
|
4364
|
-
if (
|
|
4365
|
-
return typeof
|
|
5139
|
+
if (record3.type === "refusal") {
|
|
5140
|
+
return typeof record3.refusal === "string";
|
|
4366
5141
|
}
|
|
4367
5142
|
return false;
|
|
4368
5143
|
};
|
|
@@ -4380,8 +5155,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
4380
5155
|
if (!value || typeof value !== "object") {
|
|
4381
5156
|
return false;
|
|
4382
5157
|
}
|
|
4383
|
-
const
|
|
4384
|
-
return
|
|
5158
|
+
const record3 = value;
|
|
5159
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
4385
5160
|
};
|
|
4386
5161
|
var toReplayableFunctionCallItemId = (value) => {
|
|
4387
5162
|
if (typeof value !== "string") {
|
|
@@ -4432,14 +5207,14 @@ var extractReasoningText = (item) => {
|
|
|
4432
5207
|
};
|
|
4433
5208
|
var extractWebSearchSummary = (item) => {
|
|
4434
5209
|
const parts = [`WebSearch status=${item.status}`];
|
|
4435
|
-
const
|
|
4436
|
-
const queries = Array.isArray(
|
|
5210
|
+
const record3 = item;
|
|
5211
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
4437
5212
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
4438
5213
|
) : [];
|
|
4439
5214
|
if (queries.length) {
|
|
4440
5215
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
4441
5216
|
}
|
|
4442
|
-
const sources = Array.isArray(
|
|
5217
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
4443
5218
|
if (sources.length) {
|
|
4444
5219
|
parts.push(`sources=${sources.length}`);
|
|
4445
5220
|
}
|
|
@@ -4610,6 +5385,9 @@ function toChatInvokeCompletion2(response, meta) {
|
|
|
4610
5385
|
input_tokens: response.usage.input_tokens,
|
|
4611
5386
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
4612
5387
|
output_tokens: response.usage.output_tokens,
|
|
5388
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
5389
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
5390
|
+
} : {},
|
|
4613
5391
|
total_tokens: response.usage.total_tokens
|
|
4614
5392
|
} : null;
|
|
4615
5393
|
const messages = toMessageSequence(response);
|
|
@@ -4715,6 +5493,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
|
4715
5493
|
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
4716
5494
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
4717
5495
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
5496
|
+
var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
|
|
5497
|
+
constructor() {
|
|
5498
|
+
super({
|
|
5499
|
+
...buildProviderFailure("openai", "validation"),
|
|
5500
|
+
safeMessage: "OpenAI WebSocket message exceeded the server size limit (1009). WebSocket-only mode does not resend this request; auto mode can fall back to HTTP. Compact oversized history if needed. Saved originals are unchanged."
|
|
5501
|
+
});
|
|
5502
|
+
}
|
|
5503
|
+
};
|
|
4718
5504
|
var resolveTimeoutMs = (value, fallbackMs) => {
|
|
4719
5505
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
4720
5506
|
return fallbackMs;
|
|
@@ -4796,6 +5582,8 @@ var OpenAiWsTransport = class {
|
|
|
4796
5582
|
);
|
|
4797
5583
|
}
|
|
4798
5584
|
async invoke(args) {
|
|
5585
|
+
const timing = new LlmStreamTiming();
|
|
5586
|
+
args.codex?.metadata.beginAttempt();
|
|
4799
5587
|
await this.prepareClientForWsHandshake();
|
|
4800
5588
|
const wsOptionsHeaders = {
|
|
4801
5589
|
...this.getClientDefaultHeaders(),
|
|
@@ -4804,6 +5592,19 @@ var OpenAiWsTransport = class {
|
|
|
4804
5592
|
if (args.sessionIdHeader) {
|
|
4805
5593
|
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
4806
5594
|
}
|
|
5595
|
+
if (args.codex?.routing) {
|
|
5596
|
+
const authHeaders = new Headers(wsOptionsHeaders);
|
|
5597
|
+
authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
|
|
5598
|
+
if (args.codex.routing.bindAuth(authHeaders)) {
|
|
5599
|
+
if (args.ws)
|
|
5600
|
+
this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
|
|
5601
|
+
throw createProviderValidationError(
|
|
5602
|
+
"openai",
|
|
5603
|
+
"OpenAI authentication changed; start a new run"
|
|
5604
|
+
);
|
|
5605
|
+
}
|
|
5606
|
+
Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
|
|
5607
|
+
}
|
|
4807
5608
|
const wsOptions = { headers: wsOptionsHeaders };
|
|
4808
5609
|
const ownsWs = !args.ws;
|
|
4809
5610
|
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new ResponsesWS(
|
|
@@ -4814,6 +5615,15 @@ var OpenAiWsTransport = class {
|
|
|
4814
5615
|
ws.on("error", () => {
|
|
4815
5616
|
});
|
|
4816
5617
|
}
|
|
5618
|
+
const removeUpgrade = args.codex ? this.addNativeSocketListener(
|
|
5619
|
+
this.getNativeSocket(ws),
|
|
5620
|
+
"upgrade",
|
|
5621
|
+
(response) => {
|
|
5622
|
+
const headers = response?.headers;
|
|
5623
|
+
if (headers)
|
|
5624
|
+
args.codex?.metadata.observeHeaders(new Headers(headers));
|
|
5625
|
+
}
|
|
5626
|
+
) : void 0;
|
|
4817
5627
|
try {
|
|
4818
5628
|
await this.waitForWsOpen(ws, args.signal);
|
|
4819
5629
|
const closeWs = () => {
|
|
@@ -4822,11 +5632,14 @@ var OpenAiWsTransport = class {
|
|
|
4822
5632
|
const responseWaiter = this.createResponsePromise({
|
|
4823
5633
|
ws,
|
|
4824
5634
|
signal: args.signal,
|
|
4825
|
-
closeWs
|
|
5635
|
+
closeWs,
|
|
5636
|
+
timing,
|
|
5637
|
+
metadata: args.codex?.metadata
|
|
4826
5638
|
});
|
|
4827
5639
|
const responseCreateEvent = {
|
|
4828
5640
|
type: "response.create",
|
|
4829
|
-
...args.request
|
|
5641
|
+
...args.request,
|
|
5642
|
+
...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
|
|
4830
5643
|
};
|
|
4831
5644
|
if (!responseWaiter.isSettled()) {
|
|
4832
5645
|
try {
|
|
@@ -4836,12 +5649,14 @@ var OpenAiWsTransport = class {
|
|
|
4836
5649
|
}
|
|
4837
5650
|
}
|
|
4838
5651
|
const response = await responseWaiter.responsePromise;
|
|
4839
|
-
return { response, ws };
|
|
5652
|
+
return { response, ws, timing: timing.finish() };
|
|
4840
5653
|
} catch (error) {
|
|
4841
5654
|
if (ownsWs) {
|
|
4842
5655
|
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
4843
5656
|
}
|
|
4844
5657
|
throw error;
|
|
5658
|
+
} finally {
|
|
5659
|
+
removeUpgrade?.();
|
|
4845
5660
|
}
|
|
4846
5661
|
}
|
|
4847
5662
|
createResponsePromise(args) {
|
|
@@ -4931,6 +5746,7 @@ var OpenAiWsTransport = class {
|
|
|
4931
5746
|
rejectOnce(error);
|
|
4932
5747
|
};
|
|
4933
5748
|
const resolveFromTerminalEvent = (event, type) => {
|
|
5749
|
+
args.timing.complete();
|
|
4934
5750
|
const response = event?.response;
|
|
4935
5751
|
if (response && typeof response === "object") {
|
|
4936
5752
|
accumulator.observeTerminalResponse(response);
|
|
@@ -4953,6 +5769,9 @@ var OpenAiWsTransport = class {
|
|
|
4953
5769
|
);
|
|
4954
5770
|
};
|
|
4955
5771
|
const onEvent = (event) => {
|
|
5772
|
+
if (settled) return;
|
|
5773
|
+
args.metadata?.observeEvent(event);
|
|
5774
|
+
args.timing.observeResponsesEvent(event);
|
|
4956
5775
|
const eventType = this.extractResponsesEventType(event);
|
|
4957
5776
|
if (!eventType) {
|
|
4958
5777
|
return;
|
|
@@ -5001,7 +5820,7 @@ var OpenAiWsTransport = class {
|
|
|
5001
5820
|
const onClose = (event) => {
|
|
5002
5821
|
const closeCode = this.extractWsCloseCode(event);
|
|
5003
5822
|
rejectOnce(
|
|
5004
|
-
new Error(
|
|
5823
|
+
closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
|
|
5005
5824
|
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
5006
5825
|
)
|
|
5007
5826
|
);
|
|
@@ -5270,6 +6089,8 @@ var OpenAiWsTransport = class {
|
|
|
5270
6089
|
return void 0;
|
|
5271
6090
|
}
|
|
5272
6091
|
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
6092
|
+
if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
|
|
6093
|
+
return `${key}:[redacted]`;
|
|
5273
6094
|
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
5274
6095
|
return `${key}:${text}`;
|
|
5275
6096
|
});
|
|
@@ -5474,7 +6295,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
|
5474
6295
|
};
|
|
5475
6296
|
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
5476
6297
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
5477
|
-
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
5478
6298
|
var ChatOpenAI = class {
|
|
5479
6299
|
provider = PROVIDER_NAME5;
|
|
5480
6300
|
model;
|
|
@@ -5493,8 +6313,9 @@ var ChatOpenAI = class {
|
|
|
5493
6313
|
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
5494
6314
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
5495
6315
|
wsReconnectCount = 0;
|
|
6316
|
+
codexTurns = /* @__PURE__ */ new Map();
|
|
5496
6317
|
constructor(options = {}) {
|
|
5497
|
-
this.client = options.client ?? new
|
|
6318
|
+
this.client = options.client ?? new OpenAI3({
|
|
5498
6319
|
...options.clientOptions ?? {},
|
|
5499
6320
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5500
6321
|
});
|
|
@@ -5577,17 +6398,32 @@ var ChatOpenAI = class {
|
|
|
5577
6398
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
5578
6399
|
const requestMeta = {
|
|
5579
6400
|
model: String(request.model ?? this.providerModel),
|
|
5580
|
-
instructionsHash:
|
|
5581
|
-
toolsHash:
|
|
6401
|
+
instructionsHash: createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
6402
|
+
toolsHash: createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
5582
6403
|
};
|
|
5583
|
-
const
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
|
|
6404
|
+
const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
|
|
6405
|
+
let transportResult;
|
|
6406
|
+
try {
|
|
6407
|
+
transportResult = await this.invokeWithTransport({
|
|
6408
|
+
request,
|
|
6409
|
+
sessionKey: context?.sessionKey,
|
|
6410
|
+
sessionIdHeader,
|
|
6411
|
+
signal,
|
|
6412
|
+
debugSeq,
|
|
6413
|
+
requestMeta,
|
|
6414
|
+
...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
|
|
6415
|
+
});
|
|
6416
|
+
} finally {
|
|
6417
|
+
codex?.metadata?.finish();
|
|
6418
|
+
}
|
|
6419
|
+
const codexMetadata = codex?.metadata?.snapshot();
|
|
6420
|
+
if (codex) {
|
|
6421
|
+
const { headers: _headers, ...response } = transportResult.response;
|
|
6422
|
+
transportResult.response = {
|
|
6423
|
+
...response,
|
|
6424
|
+
...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
|
|
6425
|
+
};
|
|
6426
|
+
}
|
|
5591
6427
|
await this.debugResponseIfEnabled(
|
|
5592
6428
|
transportResult.response,
|
|
5593
6429
|
debugSeq,
|
|
@@ -5611,7 +6447,42 @@ var ChatOpenAI = class {
|
|
|
5611
6447
|
debugSeq,
|
|
5612
6448
|
transportResult.transport
|
|
5613
6449
|
);
|
|
5614
|
-
return
|
|
6450
|
+
return {
|
|
6451
|
+
...completion,
|
|
6452
|
+
...codexMetadata ? {
|
|
6453
|
+
provider_meta: {
|
|
6454
|
+
...completion.provider_meta,
|
|
6455
|
+
codex_metadata: codexMetadata
|
|
6456
|
+
}
|
|
6457
|
+
} : {},
|
|
6458
|
+
...transportResult.timing ? { timing: transportResult.timing } : {}
|
|
6459
|
+
};
|
|
6460
|
+
}
|
|
6461
|
+
createCodexMetadata(context) {
|
|
6462
|
+
const routing = this.resolveCodexTurn(context);
|
|
6463
|
+
return {
|
|
6464
|
+
routing,
|
|
6465
|
+
metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
|
|
6466
|
+
};
|
|
6467
|
+
}
|
|
6468
|
+
resolveCodexTurn(context) {
|
|
6469
|
+
if (!context?.turnKey) return void 0;
|
|
6470
|
+
const key = context.sessionKey ?? context.turnKey;
|
|
6471
|
+
let state = this.codexTurns.get(key);
|
|
6472
|
+
if (!state || state.turnKey !== context.turnKey) {
|
|
6473
|
+
this.clearWsSessionState(key, "new_turn");
|
|
6474
|
+
state = { turnKey: context.turnKey, routing: new CodexTurnState() };
|
|
6475
|
+
this.codexTurns.delete(key);
|
|
6476
|
+
this.codexTurns.set(key, state);
|
|
6477
|
+
if (this.codexTurns.size > 16) {
|
|
6478
|
+
const oldest = this.codexTurns.keys().next().value;
|
|
6479
|
+
if (oldest !== void 0) {
|
|
6480
|
+
this.codexTurns.delete(oldest);
|
|
6481
|
+
this.clearWsSessionState(oldest, "turn_state_evicted");
|
|
6482
|
+
}
|
|
6483
|
+
}
|
|
6484
|
+
}
|
|
6485
|
+
return state.routing;
|
|
5615
6486
|
}
|
|
5616
6487
|
onHistoryCompacted(context) {
|
|
5617
6488
|
const sessionKey = context?.sessionKey;
|
|
@@ -5629,6 +6500,7 @@ var ChatOpenAI = class {
|
|
|
5629
6500
|
this.evictIdleWsSessionState();
|
|
5630
6501
|
if (this.websocketMode === "off") {
|
|
5631
6502
|
return this.invokeHttpTransportWithDebug({
|
|
6503
|
+
codex: args.codex,
|
|
5632
6504
|
request: args.request,
|
|
5633
6505
|
debugSeq: args.debugSeq,
|
|
5634
6506
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5644,6 +6516,7 @@ var ChatOpenAI = class {
|
|
|
5644
6516
|
);
|
|
5645
6517
|
}
|
|
5646
6518
|
return this.invokeHttpTransportWithDebug({
|
|
6519
|
+
codex: args.codex,
|
|
5647
6520
|
request: args.request,
|
|
5648
6521
|
debugSeq: args.debugSeq,
|
|
5649
6522
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5654,6 +6527,7 @@ var ChatOpenAI = class {
|
|
|
5654
6527
|
}
|
|
5655
6528
|
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
5656
6529
|
return this.invokeHttpTransportWithDebug({
|
|
6530
|
+
codex: args.codex,
|
|
5657
6531
|
request: args.request,
|
|
5658
6532
|
debugSeq: args.debugSeq,
|
|
5659
6533
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5663,7 +6537,7 @@ var ChatOpenAI = class {
|
|
|
5663
6537
|
});
|
|
5664
6538
|
}
|
|
5665
6539
|
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
5666
|
-
const hasReusableWs = this.isWsConnectionReusable(wsState.ws)
|
|
6540
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
|
|
5667
6541
|
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
5668
6542
|
const incrementalInput = this.getIncrementalInput(
|
|
5669
6543
|
wsState.lastInput,
|
|
@@ -5711,7 +6585,8 @@ var ChatOpenAI = class {
|
|
|
5711
6585
|
wsExecutionPlan.chainReset,
|
|
5712
6586
|
wsExecutionPlan.wsInputMode
|
|
5713
6587
|
);
|
|
5714
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6588
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6589
|
+
codex: args.codex,
|
|
5715
6590
|
request: wsExecutionPlan.request,
|
|
5716
6591
|
signal: args.signal,
|
|
5717
6592
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5727,12 +6602,17 @@ var ChatOpenAI = class {
|
|
|
5727
6602
|
return {
|
|
5728
6603
|
response,
|
|
5729
6604
|
transport: "ws_mode",
|
|
6605
|
+
...timing ? { timing } : {},
|
|
5730
6606
|
fallbackUsed: false,
|
|
5731
6607
|
chainReset: wsExecutionPlan.chainReset,
|
|
5732
6608
|
wsInputMode: wsExecutionPlan.wsInputMode
|
|
5733
6609
|
};
|
|
5734
6610
|
} catch (error) {
|
|
5735
6611
|
let failure = error;
|
|
6612
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6613
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6614
|
+
throw failure;
|
|
6615
|
+
}
|
|
5736
6616
|
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
5737
6617
|
const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
|
|
5738
6618
|
this.closeWsWithoutMaskingPrimaryError(
|
|
@@ -5750,7 +6630,8 @@ var ChatOpenAI = class {
|
|
|
5750
6630
|
true,
|
|
5751
6631
|
retryWsInputMode
|
|
5752
6632
|
);
|
|
5753
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6633
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6634
|
+
codex: args.codex,
|
|
5754
6635
|
request: args.request,
|
|
5755
6636
|
signal: args.signal,
|
|
5756
6637
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5767,6 +6648,7 @@ var ChatOpenAI = class {
|
|
|
5767
6648
|
return {
|
|
5768
6649
|
response,
|
|
5769
6650
|
transport: "ws_mode",
|
|
6651
|
+
...timing ? { timing } : {},
|
|
5770
6652
|
fallbackUsed: false,
|
|
5771
6653
|
chainReset: true,
|
|
5772
6654
|
wsInputMode: retryWsInputMode
|
|
@@ -5775,9 +6657,13 @@ var ChatOpenAI = class {
|
|
|
5775
6657
|
failure = retryError;
|
|
5776
6658
|
}
|
|
5777
6659
|
}
|
|
6660
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6661
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6662
|
+
throw failure;
|
|
6663
|
+
}
|
|
5778
6664
|
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
5779
6665
|
const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
|
|
5780
|
-
const shouldDisableWsForSession = wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
6666
|
+
const shouldDisableWsForSession = failure instanceof OpenAiWsMessageTooLargeError || wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
5781
6667
|
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
5782
6668
|
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
5783
6669
|
this.wsDisabledUntilBySessionKey.set(
|
|
@@ -5790,6 +6676,7 @@ var ChatOpenAI = class {
|
|
|
5790
6676
|
}
|
|
5791
6677
|
this.wsReconnectCount += 1;
|
|
5792
6678
|
return this.invokeHttpTransportWithDebug({
|
|
6679
|
+
codex: args.codex,
|
|
5793
6680
|
request: args.request,
|
|
5794
6681
|
debugSeq: args.debugSeq,
|
|
5795
6682
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5810,16 +6697,23 @@ var ChatOpenAI = class {
|
|
|
5810
6697
|
args.chainReset,
|
|
5811
6698
|
args.wsInputMode
|
|
5812
6699
|
);
|
|
6700
|
+
const timing = new LlmStreamTiming();
|
|
6701
|
+
const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
|
|
5813
6702
|
const response = await invokeOpenAiHttp(
|
|
5814
6703
|
this.client,
|
|
5815
6704
|
args.request,
|
|
5816
6705
|
args.signal,
|
|
5817
6706
|
args.sessionIdHeader,
|
|
5818
|
-
|
|
6707
|
+
(event) => {
|
|
6708
|
+
timing.observeResponsesEvent(event);
|
|
6709
|
+
return debugObserver?.(event);
|
|
6710
|
+
},
|
|
6711
|
+
args.codex
|
|
5819
6712
|
);
|
|
5820
6713
|
return {
|
|
5821
6714
|
response,
|
|
5822
6715
|
transport: "http_stream",
|
|
6716
|
+
timing: timing.finish(),
|
|
5823
6717
|
fallbackUsed: args.fallbackUsed,
|
|
5824
6718
|
chainReset: args.chainReset
|
|
5825
6719
|
};
|
|
@@ -5857,12 +6751,6 @@ var ChatOpenAI = class {
|
|
|
5857
6751
|
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
5858
6752
|
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
5859
6753
|
}
|
|
5860
|
-
isWsConnectionReuseExpired(lastUsedAt) {
|
|
5861
|
-
if (typeof lastUsedAt !== "number") {
|
|
5862
|
-
return false;
|
|
5863
|
-
}
|
|
5864
|
-
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
5865
|
-
}
|
|
5866
6754
|
isWsReconnectRetryableError(error) {
|
|
5867
6755
|
if (!(error instanceof Error)) {
|
|
5868
6756
|
return false;
|
|
@@ -5941,14 +6829,14 @@ var ChatOpenAI = class {
|
|
|
5941
6829
|
return;
|
|
5942
6830
|
}
|
|
5943
6831
|
const payload = safeJsonStringify(request);
|
|
5944
|
-
const hash =
|
|
5945
|
-
const toolsHash =
|
|
5946
|
-
const instructionsHash =
|
|
6832
|
+
const hash = createHash4("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6833
|
+
const toolsHash = createHash4("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6834
|
+
const instructionsHash = createHash4("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
5947
6835
|
const previous = this.lastDebugRequestPayload;
|
|
5948
6836
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5949
6837
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5950
6838
|
if (settings.enabled) {
|
|
5951
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
6839
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash4("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
5952
6840
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
5953
6841
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
5954
6842
|
console.error(
|
|
@@ -6041,8 +6929,8 @@ var ChatOpenAI = class {
|
|
|
6041
6929
|
};
|
|
6042
6930
|
|
|
6043
6931
|
// src/llm/openrouter/chat.ts
|
|
6044
|
-
import { createHash as
|
|
6045
|
-
import
|
|
6932
|
+
import { createHash as createHash5 } from "crypto";
|
|
6933
|
+
import OpenAI4 from "openai";
|
|
6046
6934
|
|
|
6047
6935
|
// src/llm/openrouter/response-utils.ts
|
|
6048
6936
|
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
@@ -6162,12 +7050,12 @@ var formatOtherPart5 = (part) => {
|
|
|
6162
7050
|
};
|
|
6163
7051
|
var isOpenAIAssistantInputContent2 = (value) => {
|
|
6164
7052
|
if (!value || typeof value !== "object") return false;
|
|
6165
|
-
const
|
|
6166
|
-
if (
|
|
6167
|
-
return typeof
|
|
7053
|
+
const record3 = value;
|
|
7054
|
+
if (record3.type === "output_text") {
|
|
7055
|
+
return typeof record3.text === "string";
|
|
6168
7056
|
}
|
|
6169
|
-
if (
|
|
6170
|
-
return typeof
|
|
7057
|
+
if (record3.type === "refusal") {
|
|
7058
|
+
return typeof record3.refusal === "string";
|
|
6171
7059
|
}
|
|
6172
7060
|
return false;
|
|
6173
7061
|
};
|
|
@@ -6175,8 +7063,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
|
6175
7063
|
if (!value || typeof value !== "object") {
|
|
6176
7064
|
return false;
|
|
6177
7065
|
}
|
|
6178
|
-
const
|
|
6179
|
-
return
|
|
7066
|
+
const record3 = value;
|
|
7067
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
6180
7068
|
};
|
|
6181
7069
|
var toReplayableFunctionCallItemId2 = (value) => {
|
|
6182
7070
|
if (typeof value !== "string") {
|
|
@@ -6227,14 +7115,14 @@ var extractReasoningText2 = (item) => {
|
|
|
6227
7115
|
};
|
|
6228
7116
|
var extractWebSearchSummary2 = (item) => {
|
|
6229
7117
|
const parts = [`WebSearch status=${item.status}`];
|
|
6230
|
-
const
|
|
6231
|
-
const queries = Array.isArray(
|
|
7118
|
+
const record3 = item;
|
|
7119
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
6232
7120
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
6233
7121
|
) : [];
|
|
6234
7122
|
if (queries.length) {
|
|
6235
7123
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
6236
7124
|
}
|
|
6237
|
-
const sources = Array.isArray(
|
|
7125
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
6238
7126
|
if (sources.length) {
|
|
6239
7127
|
parts.push(`sources=${sources.length}`);
|
|
6240
7128
|
}
|
|
@@ -6401,6 +7289,9 @@ function toChatInvokeCompletion3(response, meta) {
|
|
|
6401
7289
|
input_tokens: response.usage.input_tokens,
|
|
6402
7290
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
6403
7291
|
output_tokens: response.usage.output_tokens,
|
|
7292
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
7293
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
7294
|
+
} : {},
|
|
6404
7295
|
total_tokens: response.usage.total_tokens
|
|
6405
7296
|
} : null;
|
|
6406
7297
|
const messages = toMessageSequence2(response);
|
|
@@ -6510,7 +7401,7 @@ var ChatOpenRouter = class {
|
|
|
6510
7401
|
debugInvokeSeq = 0;
|
|
6511
7402
|
lastDebugRequestPayload = null;
|
|
6512
7403
|
constructor(options = {}) {
|
|
6513
|
-
this.client = options.client ?? new
|
|
7404
|
+
this.client = options.client ?? new OpenAI4({
|
|
6514
7405
|
baseURL: OPENROUTER_BASE_URL,
|
|
6515
7406
|
...options.clientOptions ?? {},
|
|
6516
7407
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
@@ -6582,7 +7473,8 @@ var ChatOpenRouter = class {
|
|
|
6582
7473
|
...request,
|
|
6583
7474
|
stream: true
|
|
6584
7475
|
};
|
|
6585
|
-
const
|
|
7476
|
+
const timing = new LlmStreamTiming();
|
|
7477
|
+
const stream = this.client.responses.stream(
|
|
6586
7478
|
streamRequest,
|
|
6587
7479
|
signal || sessionIdHeader ? {
|
|
6588
7480
|
...signal ? { signal } : {},
|
|
@@ -6592,13 +7484,21 @@ var ChatOpenRouter = class {
|
|
|
6592
7484
|
}
|
|
6593
7485
|
} : {}
|
|
6594
7486
|
} : void 0
|
|
6595
|
-
)
|
|
7487
|
+
);
|
|
7488
|
+
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
7489
|
+
for await (const event of stream) timing.observeResponsesEvent(event);
|
|
7490
|
+
}
|
|
7491
|
+
const response = await stream.finalResponse();
|
|
7492
|
+
const measuredTiming = timing.finish();
|
|
6596
7493
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6597
|
-
return
|
|
6598
|
-
|
|
6599
|
-
|
|
6600
|
-
|
|
6601
|
-
|
|
7494
|
+
return {
|
|
7495
|
+
...toChatInvokeCompletion3(response, {
|
|
7496
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7497
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7498
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7499
|
+
}),
|
|
7500
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7501
|
+
};
|
|
6602
7502
|
}
|
|
6603
7503
|
nextDebugInvokeSeq() {
|
|
6604
7504
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -6611,14 +7511,14 @@ var ChatOpenRouter = class {
|
|
|
6611
7511
|
return;
|
|
6612
7512
|
}
|
|
6613
7513
|
const payload = safeJsonStringify(request);
|
|
6614
|
-
const hash =
|
|
6615
|
-
const toolsHash =
|
|
6616
|
-
const instructionsHash =
|
|
7514
|
+
const hash = createHash5("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7515
|
+
const toolsHash = createHash5("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7516
|
+
const instructionsHash = createHash5("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6617
7517
|
const previous = this.lastDebugRequestPayload;
|
|
6618
7518
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6619
7519
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6620
7520
|
if (settings.enabled) {
|
|
6621
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
7521
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash5("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6622
7522
|
console.error(
|
|
6623
7523
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
6624
7524
|
);
|
|
@@ -6682,8 +7582,8 @@ var ChatOpenRouter = class {
|
|
|
6682
7582
|
};
|
|
6683
7583
|
|
|
6684
7584
|
// src/llm/xai/chat.ts
|
|
6685
|
-
import { createHash as
|
|
6686
|
-
import
|
|
7585
|
+
import { createHash as createHash6 } from "crypto";
|
|
7586
|
+
import OpenAI5 from "openai";
|
|
6687
7587
|
|
|
6688
7588
|
// src/llm/xai/serializer.ts
|
|
6689
7589
|
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -6906,7 +7806,7 @@ var ChatXai = class {
|
|
|
6906
7806
|
debugInvokeSeq = 0;
|
|
6907
7807
|
lastDebugRequestPayload = null;
|
|
6908
7808
|
constructor(options = {}) {
|
|
6909
|
-
this.client = options.client ?? new
|
|
7809
|
+
this.client = options.client ?? new OpenAI5({
|
|
6910
7810
|
baseURL: XAI_BASE_URL,
|
|
6911
7811
|
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6912
7812
|
...options.clientOptions ?? {},
|
|
@@ -6959,13 +7859,24 @@ var ChatXai = class {
|
|
|
6959
7859
|
}
|
|
6960
7860
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
6961
7861
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6962
|
-
const
|
|
7862
|
+
const timing = new LlmStreamTiming();
|
|
7863
|
+
const response = await invokeOpenAiHttp(
|
|
7864
|
+
this.client,
|
|
7865
|
+
request,
|
|
7866
|
+
signal,
|
|
7867
|
+
void 0,
|
|
7868
|
+
(event) => timing.observeResponsesEvent(event)
|
|
7869
|
+
);
|
|
7870
|
+
const measuredTiming = timing.finish();
|
|
6963
7871
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6964
|
-
return
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
6968
|
-
|
|
7872
|
+
return {
|
|
7873
|
+
...toXaiChatInvokeCompletion(response, {
|
|
7874
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7875
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7876
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7877
|
+
}),
|
|
7878
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7879
|
+
};
|
|
6969
7880
|
}
|
|
6970
7881
|
nextDebugInvokeSeq() {
|
|
6971
7882
|
this.debugInvokeSeq += 1;
|
|
@@ -6975,7 +7886,7 @@ var ChatXai = class {
|
|
|
6975
7886
|
const settings = getProviderLogSettings();
|
|
6976
7887
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
6977
7888
|
const payload = safeJsonStringify(request);
|
|
6978
|
-
const hash =
|
|
7889
|
+
const hash = createHash6("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6979
7890
|
const previous = this.lastDebugRequestPayload;
|
|
6980
7891
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6981
7892
|
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7032,15 +7943,15 @@ var ChatXai = class {
|
|
|
7032
7943
|
};
|
|
7033
7944
|
|
|
7034
7945
|
// src/llm/zai/chat.ts
|
|
7035
|
-
import { createHash as
|
|
7946
|
+
import { createHash as createHash7 } from "crypto";
|
|
7036
7947
|
|
|
7037
7948
|
// src/llm/zai/failure.ts
|
|
7038
7949
|
var PROVIDER_NAME8 = "zai";
|
|
7039
7950
|
var readBusinessCode = (error) => {
|
|
7040
|
-
const
|
|
7041
|
-
const body = asRecord(
|
|
7951
|
+
const record3 = asRecord(error);
|
|
7952
|
+
const body = asRecord(record3?.body);
|
|
7042
7953
|
const nested = asRecord(body?.error) ?? body;
|
|
7043
|
-
const raw = nested?.code ??
|
|
7954
|
+
const raw = nested?.code ?? record3?.code;
|
|
7044
7955
|
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7045
7956
|
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7046
7957
|
};
|
|
@@ -7344,6 +8255,7 @@ var streamZaiChatCompletion = async ({
|
|
|
7344
8255
|
timeoutMs,
|
|
7345
8256
|
captureRawChunks
|
|
7346
8257
|
}) => {
|
|
8258
|
+
const timing = new LlmStreamTiming();
|
|
7347
8259
|
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
7348
8260
|
try {
|
|
7349
8261
|
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
@@ -7365,9 +8277,11 @@ var streamZaiChatCompletion = async ({
|
|
|
7365
8277
|
response,
|
|
7366
8278
|
requestSignal.signal
|
|
7367
8279
|
)) {
|
|
8280
|
+
timing.observeChatChunk(chunk);
|
|
7368
8281
|
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
7369
8282
|
}
|
|
7370
8283
|
return {
|
|
8284
|
+
timing: timing.finish(),
|
|
7371
8285
|
status: response.status,
|
|
7372
8286
|
request_id: response.headers.get("x-request-id"),
|
|
7373
8287
|
accumulated
|
|
@@ -7562,13 +8476,16 @@ var ChatZai = class {
|
|
|
7562
8476
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7563
8477
|
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
7564
8478
|
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
7565
|
-
return
|
|
7566
|
-
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7570
|
-
|
|
7571
|
-
|
|
8479
|
+
return {
|
|
8480
|
+
...toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
8481
|
+
request_id: terminal.request_id ?? null,
|
|
8482
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8483
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8484
|
+
reasoning_effort: request.reasoning_effort,
|
|
8485
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8486
|
+
}),
|
|
8487
|
+
...terminal.timing ? { timing: terminal.timing } : {}
|
|
8488
|
+
};
|
|
7572
8489
|
}
|
|
7573
8490
|
async streamRequest(apiKey, request, signal) {
|
|
7574
8491
|
const logSettings = getProviderLogSettings();
|
|
@@ -7593,8 +8510,8 @@ var ChatZai = class {
|
|
|
7593
8510
|
return;
|
|
7594
8511
|
}
|
|
7595
8512
|
const payload = safeJsonStringify(request);
|
|
7596
|
-
const hash =
|
|
7597
|
-
const toolsHash =
|
|
8513
|
+
const hash = createHash7("sha256").update(payload).digest("hex").slice(0, 16);
|
|
8514
|
+
const toolsHash = createHash7("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7598
8515
|
const previous = this.lastDebugRequestPayload;
|
|
7599
8516
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7600
8517
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7725,6 +8642,159 @@ function defineTool(toolOptions) {
|
|
|
7725
8642
|
}
|
|
7726
8643
|
};
|
|
7727
8644
|
}
|
|
8645
|
+
|
|
8646
|
+
// src/llm/responses/chat.ts
|
|
8647
|
+
import OpenAI6 from "openai";
|
|
8648
|
+
var ChatResponses = class {
|
|
8649
|
+
provider;
|
|
8650
|
+
model;
|
|
8651
|
+
retryPolicy;
|
|
8652
|
+
client;
|
|
8653
|
+
endpoint;
|
|
8654
|
+
reasoningEffort;
|
|
8655
|
+
textVerbosity;
|
|
8656
|
+
constructor(options) {
|
|
8657
|
+
this.provider = options.provider;
|
|
8658
|
+
this.model = options.model;
|
|
8659
|
+
this.endpoint = options.endpoint;
|
|
8660
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
8661
|
+
this.textVerbosity = options.textVerbosity;
|
|
8662
|
+
const retry = options.endpoint.retry;
|
|
8663
|
+
this.retryPolicy = {
|
|
8664
|
+
maxRetries: typeof retry === "object" ? retry.max_retries : 0,
|
|
8665
|
+
...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
|
|
8666
|
+
};
|
|
8667
|
+
this.client = new OpenAI6({
|
|
8668
|
+
apiKey: options.apiKey,
|
|
8669
|
+
baseURL: options.endpoint.base_url,
|
|
8670
|
+
organization: null,
|
|
8671
|
+
project: null,
|
|
8672
|
+
maxRetries: 0,
|
|
8673
|
+
timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
|
|
8674
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
8675
|
+
});
|
|
8676
|
+
}
|
|
8677
|
+
classifyFailure = (error) => {
|
|
8678
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
8679
|
+
const failure = error instanceof OpenAI6.APIUserAbortError ? buildProviderFailure(this.provider, "cancelled") : error instanceof OpenAI6.APIConnectionTimeoutError ? buildProviderFailure(this.provider, "timeout", { retryable: true }) : error instanceof OpenAI6.APIConnectionError ? buildProviderFailure(this.provider, "network", {
|
|
8680
|
+
retryable: true
|
|
8681
|
+
}) : classifyOpenAiCompatibleFailure(this.provider, error);
|
|
8682
|
+
const extracted = extractProviderError(error);
|
|
8683
|
+
const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
|
|
8684
|
+
return {
|
|
8685
|
+
...failure,
|
|
8686
|
+
...extracted.status !== void 0 ? { status: extracted.status } : {},
|
|
8687
|
+
...extracted.status === 413 ? { kind: "validation" } : {},
|
|
8688
|
+
retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
|
|
8689
|
+
...code ? { code } : {},
|
|
8690
|
+
safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
|
|
8691
|
+
};
|
|
8692
|
+
};
|
|
8693
|
+
async ainvoke(input, context) {
|
|
8694
|
+
const model = input.model ?? this.model;
|
|
8695
|
+
const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
|
|
8696
|
+
const invalid = (message) => {
|
|
8697
|
+
throw createProviderValidationError(this.provider, message);
|
|
8698
|
+
};
|
|
8699
|
+
if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
|
|
8700
|
+
if (input.tools?.some((tool) => tool.type === "hosted_search"))
|
|
8701
|
+
invalid(
|
|
8702
|
+
`${this.provider} supports function tools only; hosted tools are unavailable`
|
|
8703
|
+
);
|
|
8704
|
+
if (input.tools?.length && !spec.supports_tools)
|
|
8705
|
+
invalid(`${this.provider}/${model} does not support tools`);
|
|
8706
|
+
const items = toResponsesInput(input.messages);
|
|
8707
|
+
if (!spec.supports_vision && Array.isArray(items) && items.some(
|
|
8708
|
+
(item) => "content" in item && Array.isArray(item.content) && item.content.some((part) => part.type === "input_image")
|
|
8709
|
+
))
|
|
8710
|
+
invalid(`${this.provider}/${model} vision is disabled`);
|
|
8711
|
+
const text = input.options?.text;
|
|
8712
|
+
if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
|
|
8713
|
+
invalid(`${this.provider}/${model} does not support structured output`);
|
|
8714
|
+
const features = this.endpoint.features;
|
|
8715
|
+
const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
|
|
8716
|
+
if (effort && !spec.supports_reasoning)
|
|
8717
|
+
invalid(`${this.provider}/${model} reasoning is disabled`);
|
|
8718
|
+
const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
|
|
8719
|
+
if (effort && !levels.includes(effort))
|
|
8720
|
+
invalid(
|
|
8721
|
+
`Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
|
|
8722
|
+
);
|
|
8723
|
+
const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
|
|
8724
|
+
if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
|
|
8725
|
+
invalid(`Invalid max output tokens for ${this.provider}/${model}`);
|
|
8726
|
+
const tools = toResponsesTools(input.tools);
|
|
8727
|
+
const choice = toResponsesToolChoice(input.toolChoice);
|
|
8728
|
+
const instructions = extractInstructions(input.messages);
|
|
8729
|
+
const request = {
|
|
8730
|
+
model,
|
|
8731
|
+
input: items,
|
|
8732
|
+
store: false,
|
|
8733
|
+
...instructions ? { instructions } : {},
|
|
8734
|
+
...tools ? { tools } : {},
|
|
8735
|
+
...choice ? { tool_choice: choice } : {},
|
|
8736
|
+
...output !== void 0 ? { max_output_tokens: output } : {}
|
|
8737
|
+
};
|
|
8738
|
+
if (spec.supports_reasoning && (effort || features?.reasoning_summary))
|
|
8739
|
+
request.reasoning = {
|
|
8740
|
+
...effort ? { effort: toSdkReasoningEffort(effort) } : {},
|
|
8741
|
+
...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
|
|
8742
|
+
};
|
|
8743
|
+
if (spec.supports_reasoning && features?.encrypted_reasoning)
|
|
8744
|
+
request.include = ["reasoning.encrypted_content"];
|
|
8745
|
+
if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
|
|
8746
|
+
request.text = {
|
|
8747
|
+
...text?.format ? { format: text.format } : {},
|
|
8748
|
+
...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
|
|
8749
|
+
};
|
|
8750
|
+
if (features?.prompt_cache_key && context?.sessionKey)
|
|
8751
|
+
request.prompt_cache_key = context.sessionKey;
|
|
8752
|
+
const timing = new LlmStreamTiming();
|
|
8753
|
+
let streamStarted = false;
|
|
8754
|
+
try {
|
|
8755
|
+
const stream = await this.client.responses.create(
|
|
8756
|
+
{ ...request, stream: true },
|
|
8757
|
+
{
|
|
8758
|
+
...input.signal ? { signal: input.signal } : {},
|
|
8759
|
+
...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
|
|
8760
|
+
}
|
|
8761
|
+
);
|
|
8762
|
+
streamStarted = true;
|
|
8763
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
8764
|
+
let terminal;
|
|
8765
|
+
for await (const event of stream) {
|
|
8766
|
+
timing.observeResponsesEvent(event);
|
|
8767
|
+
if (event.type === "error") throw { error: event };
|
|
8768
|
+
if (event.type === "response.failed")
|
|
8769
|
+
throw { error: event.response.error };
|
|
8770
|
+
accumulator.observeEvent(event);
|
|
8771
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
8772
|
+
terminal = event.response;
|
|
8773
|
+
break;
|
|
8774
|
+
}
|
|
8775
|
+
}
|
|
8776
|
+
if (!terminal)
|
|
8777
|
+
throw new Error("Responses stream ended before a terminal event");
|
|
8778
|
+
const measuredTiming = timing.finish();
|
|
8779
|
+
return {
|
|
8780
|
+
...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
|
|
8781
|
+
transport: "http_stream"
|
|
8782
|
+
}),
|
|
8783
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
8784
|
+
};
|
|
8785
|
+
} catch (error) {
|
|
8786
|
+
if (isProviderFailureError(error)) throw error;
|
|
8787
|
+
const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
|
|
8788
|
+
throw new ProviderFailureError(
|
|
8789
|
+
{
|
|
8790
|
+
...failure,
|
|
8791
|
+
...streamStarted ? { retryable: false, delivery: "buffered" } : {}
|
|
8792
|
+
},
|
|
8793
|
+
{ cause: error }
|
|
8794
|
+
);
|
|
8795
|
+
}
|
|
8796
|
+
}
|
|
8797
|
+
};
|
|
7728
8798
|
export {
|
|
7729
8799
|
ANTHROPIC_DEFAULT_MODEL,
|
|
7730
8800
|
ANTHROPIC_MODELS,
|
|
@@ -7733,6 +8803,7 @@ export {
|
|
|
7733
8803
|
ChatMoonshot,
|
|
7734
8804
|
ChatOpenAI,
|
|
7735
8805
|
ChatOpenRouter,
|
|
8806
|
+
ChatResponses,
|
|
7736
8807
|
ChatXai,
|
|
7737
8808
|
ChatZai,
|
|
7738
8809
|
DEFAULT_MODEL_REGISTRY,
|