@codelia/core 0.1.81 → 0.1.83
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 +1494 -200
- package/dist/index.d.ts +95 -24
- package/dist/index.js +1494 -202
- package/package.json +4 -3
- package/prompts/system.md +2 -2
package/dist/index.js
CHANGED
|
@@ -23,6 +23,22 @@ var buildGpt56Model = (id) => ({
|
|
|
23
23
|
supportsFast: true
|
|
24
24
|
});
|
|
25
25
|
var OPENAI_MODELS = [
|
|
26
|
+
{
|
|
27
|
+
id: "gpt-6.1-terra",
|
|
28
|
+
provider: "openai",
|
|
29
|
+
contextWindow: 105e4,
|
|
30
|
+
maxInputTokens: 27e4,
|
|
31
|
+
maxOutputTokens: 128e3,
|
|
32
|
+
supportsFast: true
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: "gpt-6.1-sol",
|
|
36
|
+
provider: "openai",
|
|
37
|
+
contextWindow: 105e4,
|
|
38
|
+
maxInputTokens: 27e4,
|
|
39
|
+
maxOutputTokens: 128e3,
|
|
40
|
+
supportsFast: true
|
|
41
|
+
},
|
|
26
42
|
{
|
|
27
43
|
id: "gpt-6-astra",
|
|
28
44
|
provider: "openai",
|
|
@@ -31,6 +47,22 @@ var OPENAI_MODELS = [
|
|
|
31
47
|
maxOutputTokens: 128e3,
|
|
32
48
|
supportsFast: true
|
|
33
49
|
},
|
|
50
|
+
{
|
|
51
|
+
id: "gpt-6-sol",
|
|
52
|
+
provider: "openai",
|
|
53
|
+
contextWindow: 105e4,
|
|
54
|
+
maxInputTokens: 27e4,
|
|
55
|
+
maxOutputTokens: 128e3,
|
|
56
|
+
supportsFast: true
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: "gpt-6-luna",
|
|
60
|
+
provider: "openai",
|
|
61
|
+
contextWindow: 105e4,
|
|
62
|
+
maxInputTokens: 27e4,
|
|
63
|
+
maxOutputTokens: 128e3,
|
|
64
|
+
supportsFast: true
|
|
65
|
+
},
|
|
34
66
|
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
35
67
|
{
|
|
36
68
|
id: "gpt-5.5",
|
|
@@ -208,7 +240,48 @@ configRegistry.registerDefaults({
|
|
|
208
240
|
});
|
|
209
241
|
|
|
210
242
|
// src/agent/agent.ts
|
|
211
|
-
import { performance } from "perf_hooks";
|
|
243
|
+
import { performance as performance2 } from "perf_hooks";
|
|
244
|
+
import { randomUUID } from "crypto";
|
|
245
|
+
|
|
246
|
+
// src/llm/provider-status.ts
|
|
247
|
+
async function* withProviderStatus(operation, signal) {
|
|
248
|
+
const controller = new AbortController();
|
|
249
|
+
const abort = () => controller.abort(signal?.reason);
|
|
250
|
+
if (signal?.aborted) abort();
|
|
251
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
252
|
+
const queue = [];
|
|
253
|
+
let wake;
|
|
254
|
+
let closed = false;
|
|
255
|
+
const iterator = operation((event) => {
|
|
256
|
+
if (closed || controller.signal.aborted) return;
|
|
257
|
+
if (queue.length < 32) queue.push(event);
|
|
258
|
+
wake?.();
|
|
259
|
+
}, controller.signal);
|
|
260
|
+
let pending = iterator.next();
|
|
261
|
+
try {
|
|
262
|
+
while (true) {
|
|
263
|
+
while (queue.length) yield queue.shift();
|
|
264
|
+
const changed = new Promise((resolve) => {
|
|
265
|
+
wake = () => resolve(void 0);
|
|
266
|
+
});
|
|
267
|
+
const result = await Promise.race([pending, changed]);
|
|
268
|
+
wake = void 0;
|
|
269
|
+
if (!result) continue;
|
|
270
|
+
while (queue.length) yield queue.shift();
|
|
271
|
+
if (result.done) return result.value;
|
|
272
|
+
yield result.value;
|
|
273
|
+
pending = iterator.next();
|
|
274
|
+
}
|
|
275
|
+
} finally {
|
|
276
|
+
closed = true;
|
|
277
|
+
controller.abort();
|
|
278
|
+
signal?.removeEventListener("abort", abort);
|
|
279
|
+
void pending.catch(() => {
|
|
280
|
+
});
|
|
281
|
+
void iterator.return(void 0).catch(() => {
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
212
285
|
|
|
213
286
|
// src/content/stringify.ts
|
|
214
287
|
var stringifyUnknown = (value) => {
|
|
@@ -222,6 +295,9 @@ var stringifyPart = (part, options) => {
|
|
|
222
295
|
if (part.type === "text") {
|
|
223
296
|
return part.text;
|
|
224
297
|
}
|
|
298
|
+
if (part.type === "image_ref") {
|
|
299
|
+
return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
|
|
300
|
+
}
|
|
225
301
|
if (part.type === "image_url") {
|
|
226
302
|
if (options.mode === "log") {
|
|
227
303
|
return `[image:${part.image_url.media_type ?? "unknown"}]`;
|
|
@@ -322,8 +398,8 @@ var ProviderTimeoutError = class extends Error {
|
|
|
322
398
|
};
|
|
323
399
|
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
324
400
|
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
325
|
-
var readString = (
|
|
326
|
-
const value =
|
|
401
|
+
var readString = (record3, key) => {
|
|
402
|
+
const value = record3?.[key];
|
|
327
403
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
328
404
|
};
|
|
329
405
|
var readStatus = (error) => {
|
|
@@ -334,9 +410,9 @@ var readHeader = (headers, name) => {
|
|
|
334
410
|
if (headers instanceof Headers) {
|
|
335
411
|
return headers.get(name);
|
|
336
412
|
}
|
|
337
|
-
const
|
|
338
|
-
if (!
|
|
339
|
-
const direct =
|
|
413
|
+
const record3 = asRecord(headers);
|
|
414
|
+
if (!record3) return null;
|
|
415
|
+
const direct = record3[name] ?? record3[name.toLowerCase()];
|
|
340
416
|
return typeof direct === "string" ? direct : null;
|
|
341
417
|
};
|
|
342
418
|
var parsePositiveNumber = (value) => {
|
|
@@ -392,7 +468,7 @@ var PROVIDER_LABELS = {
|
|
|
392
468
|
xai: "xAI"
|
|
393
469
|
};
|
|
394
470
|
var safeProviderMessage = (provider, kind) => {
|
|
395
|
-
const label = PROVIDER_LABELS[provider];
|
|
471
|
+
const label = PROVIDER_LABELS[provider] ?? provider;
|
|
396
472
|
switch (kind) {
|
|
397
473
|
case "hard_quota":
|
|
398
474
|
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
@@ -732,6 +808,42 @@ var ANTHROPIC_MODELS = [
|
|
|
732
808
|
provider: "anthropic",
|
|
733
809
|
aliases: ["default"]
|
|
734
810
|
},
|
|
811
|
+
{
|
|
812
|
+
id: "claude-sonnet-5-5",
|
|
813
|
+
provider: "anthropic",
|
|
814
|
+
contextWindow: 1e6,
|
|
815
|
+
maxInputTokens: 1e6,
|
|
816
|
+
maxOutputTokens: 128e3
|
|
817
|
+
},
|
|
818
|
+
{
|
|
819
|
+
id: "claude-haiku-5-5",
|
|
820
|
+
provider: "anthropic",
|
|
821
|
+
contextWindow: 1e6,
|
|
822
|
+
maxInputTokens: 1e6,
|
|
823
|
+
maxOutputTokens: 128e3
|
|
824
|
+
},
|
|
825
|
+
{
|
|
826
|
+
id: "claude-fable-5-1",
|
|
827
|
+
provider: "anthropic",
|
|
828
|
+
contextWindow: 1e6,
|
|
829
|
+
maxInputTokens: 1e6,
|
|
830
|
+
maxOutputTokens: 128e3
|
|
831
|
+
},
|
|
832
|
+
{
|
|
833
|
+
id: "claude-opus-5-5",
|
|
834
|
+
provider: "anthropic",
|
|
835
|
+
contextWindow: 1e6,
|
|
836
|
+
maxInputTokens: 1e6,
|
|
837
|
+
maxOutputTokens: 128e3,
|
|
838
|
+
supportsFast: true
|
|
839
|
+
},
|
|
840
|
+
{
|
|
841
|
+
id: "claude-sonnet-5",
|
|
842
|
+
provider: "anthropic",
|
|
843
|
+
contextWindow: 1e6,
|
|
844
|
+
maxInputTokens: 1e6,
|
|
845
|
+
maxOutputTokens: 128e3
|
|
846
|
+
},
|
|
735
847
|
{
|
|
736
848
|
id: "claude-fable-5",
|
|
737
849
|
provider: "anthropic",
|
|
@@ -761,12 +873,12 @@ var ANTHROPIC_MODELS = [
|
|
|
761
873
|
contextWindow: 1e6,
|
|
762
874
|
maxInputTokens: 1e6,
|
|
763
875
|
maxOutputTokens: 128e3,
|
|
764
|
-
supportsFast:
|
|
876
|
+
supportsFast: false
|
|
765
877
|
},
|
|
766
878
|
{
|
|
767
879
|
id: "claude-opus-4-6",
|
|
768
880
|
provider: "anthropic",
|
|
769
|
-
supportsFast:
|
|
881
|
+
supportsFast: false
|
|
770
882
|
},
|
|
771
883
|
{
|
|
772
884
|
id: "claude-opus-4-5",
|
|
@@ -812,7 +924,25 @@ var GOOGLE_MODELS = [
|
|
|
812
924
|
|
|
813
925
|
// src/models/moonshot.ts
|
|
814
926
|
var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
|
|
927
|
+
var MOONSHOT_K3_1_MODELS = /* @__PURE__ */ new Set([
|
|
928
|
+
"kimi-k3.1-pro",
|
|
929
|
+
"kimi-k3.1-pro-highspeed"
|
|
930
|
+
]);
|
|
815
931
|
var MOONSHOT_MODELS = [
|
|
932
|
+
...Array.from(
|
|
933
|
+
MOONSHOT_K3_1_MODELS,
|
|
934
|
+
(id) => ({
|
|
935
|
+
id,
|
|
936
|
+
provider: "moonshot",
|
|
937
|
+
contextWindow: 1048576,
|
|
938
|
+
maxInputTokens: 1048576,
|
|
939
|
+
maxOutputTokens: 1048576,
|
|
940
|
+
supportsTools: true,
|
|
941
|
+
supportsVision: true,
|
|
942
|
+
supportsReasoning: true,
|
|
943
|
+
supportsJsonSchema: true
|
|
944
|
+
})
|
|
945
|
+
),
|
|
816
946
|
{
|
|
817
947
|
id: MOONSHOT_DEFAULT_MODEL,
|
|
818
948
|
provider: "moonshot",
|
|
@@ -847,6 +977,7 @@ function createModelRegistry(specs) {
|
|
|
847
977
|
function registerModels(registry, specs) {
|
|
848
978
|
for (const spec of specs) {
|
|
849
979
|
registry.modelsById[spec.id] = spec;
|
|
980
|
+
registry.aliasesByProvider[spec.provider] ??= {};
|
|
850
981
|
const aliasBucket = registry.aliasesByProvider[spec.provider];
|
|
851
982
|
for (const alias of spec.aliases ?? []) {
|
|
852
983
|
aliasBucket[alias] = spec.id;
|
|
@@ -855,11 +986,11 @@ function registerModels(registry, specs) {
|
|
|
855
986
|
}
|
|
856
987
|
function resolveModel(registry, idOrAlias, provider) {
|
|
857
988
|
const direct = registry.modelsById[idOrAlias];
|
|
858
|
-
if (direct) {
|
|
989
|
+
if (direct && (!provider || direct.provider === provider)) {
|
|
859
990
|
return direct;
|
|
860
991
|
}
|
|
861
992
|
if (provider) {
|
|
862
|
-
const aliasId = registry.aliasesByProvider[provider][idOrAlias];
|
|
993
|
+
const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
|
|
863
994
|
return aliasId ? registry.modelsById[aliasId] : void 0;
|
|
864
995
|
}
|
|
865
996
|
let resolved;
|
|
@@ -894,15 +1025,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
|
|
|
894
1025
|
return spec?.supportsFast === true;
|
|
895
1026
|
}
|
|
896
1027
|
function cloneAliases(aliasesByProvider) {
|
|
897
|
-
return
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
zai: { ...aliasesByProvider.zai },
|
|
904
|
-
xai: { ...aliasesByProvider.xai }
|
|
905
|
-
};
|
|
1028
|
+
return Object.fromEntries(
|
|
1029
|
+
Object.entries(aliasesByProvider).map(([provider, aliases]) => [
|
|
1030
|
+
provider,
|
|
1031
|
+
{ ...aliases }
|
|
1032
|
+
])
|
|
1033
|
+
);
|
|
906
1034
|
}
|
|
907
1035
|
function applyModelMetadata(registry, index) {
|
|
908
1036
|
const next = {
|
|
@@ -934,6 +1062,16 @@ function applyModelMetadata(registry, index) {
|
|
|
934
1062
|
var XAI_DEFAULT_MODEL = "grok-4.5";
|
|
935
1063
|
var XAI_DEFAULT_REASONING_EFFORT = "high";
|
|
936
1064
|
var XAI_MODELS = [
|
|
1065
|
+
{
|
|
1066
|
+
id: "grok-4.7",
|
|
1067
|
+
provider: "xai",
|
|
1068
|
+
contextWindow: 5e5,
|
|
1069
|
+
maxInputTokens: 2e5,
|
|
1070
|
+
supportsTools: true,
|
|
1071
|
+
supportsVision: true,
|
|
1072
|
+
supportsReasoning: true,
|
|
1073
|
+
supportsJsonSchema: true
|
|
1074
|
+
},
|
|
937
1075
|
{
|
|
938
1076
|
id: XAI_DEFAULT_MODEL,
|
|
939
1077
|
provider: "xai",
|
|
@@ -949,7 +1087,10 @@ var XAI_MODELS = [
|
|
|
949
1087
|
|
|
950
1088
|
// src/models/zai.ts
|
|
951
1089
|
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
952
|
-
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set([
|
|
1090
|
+
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set([
|
|
1091
|
+
"glm-5.3",
|
|
1092
|
+
"glm-5.2"
|
|
1093
|
+
]);
|
|
953
1094
|
var zaiModel = (id, limits) => ({
|
|
954
1095
|
id,
|
|
955
1096
|
provider: "zai",
|
|
@@ -962,6 +1103,10 @@ var zaiModel = (id, limits) => ({
|
|
|
962
1103
|
supportsJsonSchema: true
|
|
963
1104
|
});
|
|
964
1105
|
var ZAI_MODELS = [
|
|
1106
|
+
zaiModel("glm-5.3", {
|
|
1107
|
+
contextWindow: 1e6,
|
|
1108
|
+
maxOutputTokens: 131072
|
|
1109
|
+
}),
|
|
965
1110
|
zaiModel(ZAI_DEFAULT_MODEL, {
|
|
966
1111
|
aliases: ["default"],
|
|
967
1112
|
contextWindow: 1e6,
|
|
@@ -995,6 +1140,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
995
1140
|
...XAI_MODELS
|
|
996
1141
|
]);
|
|
997
1142
|
|
|
1143
|
+
// src/content/image-references.ts
|
|
1144
|
+
var REGISTRY = "[codelia.image.artifacts]";
|
|
1145
|
+
function isImageRegistry(message) {
|
|
1146
|
+
return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
|
|
1147
|
+
}
|
|
1148
|
+
function imageReferenceRegistry(messages) {
|
|
1149
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1150
|
+
for (const message of messages) {
|
|
1151
|
+
if (!("content" in message) || !Array.isArray(message.content)) continue;
|
|
1152
|
+
for (const part of message.content)
|
|
1153
|
+
if (part.type === "image_ref") {
|
|
1154
|
+
refs.delete(part.image_ref.artifact_id);
|
|
1155
|
+
refs.set(part.image_ref.artifact_id, part);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
const recent = [...refs.values()].slice(-16);
|
|
1159
|
+
return recent.length ? {
|
|
1160
|
+
role: "user",
|
|
1161
|
+
content: [
|
|
1162
|
+
{
|
|
1163
|
+
type: "text",
|
|
1164
|
+
text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
|
|
1165
|
+
`
|
|
1166
|
+
},
|
|
1167
|
+
...recent
|
|
1168
|
+
]
|
|
1169
|
+
} : null;
|
|
1170
|
+
}
|
|
1171
|
+
function describeImageReferences(messages) {
|
|
1172
|
+
return messages.map((message) => {
|
|
1173
|
+
if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
|
|
1174
|
+
return message;
|
|
1175
|
+
const content = message.content.map(
|
|
1176
|
+
(part) => part.type === "image_ref" ? {
|
|
1177
|
+
type: "text",
|
|
1178
|
+
text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
|
|
1179
|
+
} : part
|
|
1180
|
+
);
|
|
1181
|
+
return { ...message, content };
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
|
|
998
1185
|
// src/services/compaction/service.ts
|
|
999
1186
|
var DEFAULT_THRESHOLD_RATIO = 0.85;
|
|
1000
1187
|
var DEFAULT_RETAIN_LAST_TURNS = 1;
|
|
@@ -1009,14 +1196,14 @@ var CompactionService = class _CompactionService {
|
|
|
1009
1196
|
this.config = _CompactionService.normalizeConfig(config);
|
|
1010
1197
|
this.modelRegistry = deps.modelRegistry;
|
|
1011
1198
|
}
|
|
1012
|
-
async shouldCompact(llm, usage) {
|
|
1199
|
+
async shouldCompact(llm, usage, estimatedInputTokens) {
|
|
1013
1200
|
if (!this.config.enabled) {
|
|
1014
1201
|
return false;
|
|
1015
1202
|
}
|
|
1016
1203
|
if (!this.config.auto) {
|
|
1017
1204
|
return false;
|
|
1018
1205
|
}
|
|
1019
|
-
if (!usage) {
|
|
1206
|
+
if (!usage && estimatedInputTokens === void 0) {
|
|
1020
1207
|
return false;
|
|
1021
1208
|
}
|
|
1022
1209
|
let contextLimit;
|
|
@@ -1026,7 +1213,7 @@ var CompactionService = class _CompactionService {
|
|
|
1026
1213
|
return false;
|
|
1027
1214
|
}
|
|
1028
1215
|
const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
|
|
1029
|
-
return usage
|
|
1216
|
+
return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
|
|
1030
1217
|
}
|
|
1031
1218
|
async compact(llm, messages, options) {
|
|
1032
1219
|
if (!this.config.enabled) {
|
|
@@ -1053,7 +1240,10 @@ var CompactionService = class _CompactionService {
|
|
|
1053
1240
|
try {
|
|
1054
1241
|
response = await llm.ainvoke(
|
|
1055
1242
|
{
|
|
1056
|
-
messages: [
|
|
1243
|
+
messages: describeImageReferences([
|
|
1244
|
+
...preparedMessages,
|
|
1245
|
+
interruptMessage
|
|
1246
|
+
]),
|
|
1057
1247
|
tools: null,
|
|
1058
1248
|
toolChoice: "none",
|
|
1059
1249
|
...options?.signal ? { signal: options.signal } : {},
|
|
@@ -1163,7 +1353,7 @@ var CompactionService = class _CompactionService {
|
|
|
1163
1353
|
);
|
|
1164
1354
|
const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
|
|
1165
1355
|
const conversationMessages = nonSystemMessages.filter(
|
|
1166
|
-
(message) => !isCompactionMemoryMessage(message)
|
|
1356
|
+
(message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
|
|
1167
1357
|
);
|
|
1168
1358
|
const tail = this.normalizeRetainedTail(
|
|
1169
1359
|
this.getLastTurns(conversationMessages, this.config.retainLastTurns)
|
|
@@ -1181,6 +1371,8 @@ var CompactionService = class _CompactionService {
|
|
|
1181
1371
|
content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
|
|
1182
1372
|
});
|
|
1183
1373
|
}
|
|
1374
|
+
const imageRegistry = imageReferenceRegistry(messages);
|
|
1375
|
+
if (imageRegistry) compacted.push(imageRegistry);
|
|
1184
1376
|
compacted.push(...tail);
|
|
1185
1377
|
return compacted;
|
|
1186
1378
|
}
|
|
@@ -1242,7 +1434,7 @@ var CompactionService = class _CompactionService {
|
|
|
1242
1434
|
return messages.slice(startIndex);
|
|
1243
1435
|
}
|
|
1244
1436
|
async resolveContextLimit(llm, usage) {
|
|
1245
|
-
const modelId = usage
|
|
1437
|
+
const modelId = usage?.model ?? llm.model;
|
|
1246
1438
|
const modelSpec = this.resolveModelSpecWithSnapshotFallback(
|
|
1247
1439
|
llm.provider,
|
|
1248
1440
|
modelId
|
|
@@ -1610,6 +1802,239 @@ var TokenUsageService = class {
|
|
|
1610
1802
|
}
|
|
1611
1803
|
};
|
|
1612
1804
|
|
|
1805
|
+
// src/agent/image-context.ts
|
|
1806
|
+
import { imageSize } from "image-size";
|
|
1807
|
+
|
|
1808
|
+
// src/llm/image-policy.ts
|
|
1809
|
+
function estimateImageTokens(provider, model, image) {
|
|
1810
|
+
let name = model.toLowerCase();
|
|
1811
|
+
if (provider === "openrouter") {
|
|
1812
|
+
if (name.startsWith("openai/")) provider = "openai";
|
|
1813
|
+
else if (name.startsWith("anthropic/")) provider = "anthropic";
|
|
1814
|
+
name = name.slice(name.indexOf("/") + 1);
|
|
1815
|
+
}
|
|
1816
|
+
const width = image.width;
|
|
1817
|
+
const height = image.height;
|
|
1818
|
+
const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
|
|
1819
|
+
const patches = (size, edge, budget, multiplier = 1) => {
|
|
1820
|
+
if (!dimensionsKnown)
|
|
1821
|
+
return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
|
|
1822
|
+
const scale = Math.min(1, edge / Math.max(width, height));
|
|
1823
|
+
return {
|
|
1824
|
+
tokens: Math.ceil(
|
|
1825
|
+
Math.min(
|
|
1826
|
+
budget,
|
|
1827
|
+
Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
|
|
1828
|
+
) * multiplier
|
|
1829
|
+
),
|
|
1830
|
+
method: "patch"
|
|
1831
|
+
};
|
|
1832
|
+
};
|
|
1833
|
+
if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
|
|
1834
|
+
name
|
|
1835
|
+
)) {
|
|
1836
|
+
const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
|
|
1837
|
+
name
|
|
1838
|
+
);
|
|
1839
|
+
return patches(
|
|
1840
|
+
28,
|
|
1841
|
+
highResolution ? 2576 : 1568,
|
|
1842
|
+
highResolution ? 4784 : 1568
|
|
1843
|
+
);
|
|
1844
|
+
}
|
|
1845
|
+
if (provider === "openai") {
|
|
1846
|
+
if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
|
|
1847
|
+
return patches(32, 512, 256, 1.2);
|
|
1848
|
+
if (/^gpt-6-astra(-|$)/.test(name))
|
|
1849
|
+
return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
|
|
1850
|
+
if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
|
|
1851
|
+
return patches(
|
|
1852
|
+
32,
|
|
1853
|
+
image.detail === "high" ? 2048 : 65535,
|
|
1854
|
+
image.detail === "high" ? 2500 : 3e4,
|
|
1855
|
+
1.2
|
|
1856
|
+
);
|
|
1857
|
+
if (/^gpt-5\.5(-|$)/.test(name))
|
|
1858
|
+
return patches(
|
|
1859
|
+
32,
|
|
1860
|
+
image.detail === "high" ? 2048 : 6e3,
|
|
1861
|
+
image.detail === "high" ? 2500 : 1e4,
|
|
1862
|
+
1.2
|
|
1863
|
+
);
|
|
1864
|
+
if (/^gpt-5\.4(-|$)/.test(name))
|
|
1865
|
+
return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
|
|
1866
|
+
if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
|
|
1867
|
+
if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
|
|
1868
|
+
if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
|
|
1869
|
+
const mini = name.startsWith("gpt-4o-mini");
|
|
1870
|
+
const base = mini ? 2833 : 85;
|
|
1871
|
+
const tile = mini ? 5667 : 170;
|
|
1872
|
+
if (image.detail === "low") return { tokens: base, method: "tile" };
|
|
1873
|
+
if (!dimensionsKnown)
|
|
1874
|
+
return { tokens: base + tile * 8, method: "fallback" };
|
|
1875
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
1876
|
+
const shortFit = 768 / (Math.min(width, height) * fit);
|
|
1877
|
+
return {
|
|
1878
|
+
tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
|
|
1879
|
+
method: "tile"
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
return { tokens: 1e4, method: "fallback" };
|
|
1884
|
+
}
|
|
1885
|
+
function imagePayloadLimit(provider) {
|
|
1886
|
+
if (provider === "anthropic") return 32e6;
|
|
1887
|
+
if (provider === "openai") return 512e6;
|
|
1888
|
+
return void 0;
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
// src/agent/image-context.ts
|
|
1892
|
+
function estimateImageContext(input, llm, resolveReferences = true) {
|
|
1893
|
+
let imageTokens = 0;
|
|
1894
|
+
let imageCount = 0;
|
|
1895
|
+
let fallbackCount = 0;
|
|
1896
|
+
let imageBytes = 0;
|
|
1897
|
+
const account = (image) => {
|
|
1898
|
+
const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
|
|
1899
|
+
if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
|
|
1900
|
+
throw new Error("Invalid model image-token estimate");
|
|
1901
|
+
imageTokens += estimate.tokens;
|
|
1902
|
+
imageCount++;
|
|
1903
|
+
if (estimate.method === "fallback") fallbackCount++;
|
|
1904
|
+
};
|
|
1905
|
+
const messages = input.messages.map((message) => {
|
|
1906
|
+
if (!Array.isArray(message.content)) return message;
|
|
1907
|
+
const registry = isImageRegistry(message);
|
|
1908
|
+
return {
|
|
1909
|
+
...message,
|
|
1910
|
+
content: message.content.map((part) => {
|
|
1911
|
+
if (part.type === "image_ref") {
|
|
1912
|
+
if (!registry && resolveReferences) {
|
|
1913
|
+
account({
|
|
1914
|
+
width: part.image_ref.width,
|
|
1915
|
+
height: part.image_ref.height,
|
|
1916
|
+
detail: part.detail
|
|
1917
|
+
});
|
|
1918
|
+
imageBytes += 4 * Math.ceil(
|
|
1919
|
+
(part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
|
|
1920
|
+
) + 64;
|
|
1921
|
+
}
|
|
1922
|
+
return {
|
|
1923
|
+
type: "text",
|
|
1924
|
+
text: `[Image ${part.image_ref.artifact_id}]`
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
if (part.type === "image_url") {
|
|
1928
|
+
let dimensions = {};
|
|
1929
|
+
const url = part.image_url.url;
|
|
1930
|
+
const comma = url.indexOf(",");
|
|
1931
|
+
if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
|
|
1932
|
+
try {
|
|
1933
|
+
dimensions = imageSize(
|
|
1934
|
+
Buffer.from(url.slice(comma + 1), "base64")
|
|
1935
|
+
);
|
|
1936
|
+
} catch {
|
|
1937
|
+
dimensions = {};
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
account({ ...dimensions, detail: part.image_url.detail });
|
|
1941
|
+
imageBytes += Buffer.byteLength(part.image_url.url);
|
|
1942
|
+
return { type: "text", text: "[Image]" };
|
|
1943
|
+
}
|
|
1944
|
+
if (part.type === "document")
|
|
1945
|
+
return {
|
|
1946
|
+
type: "text",
|
|
1947
|
+
text: "[Document: token estimate unavailable]"
|
|
1948
|
+
};
|
|
1949
|
+
return part;
|
|
1950
|
+
})
|
|
1951
|
+
};
|
|
1952
|
+
});
|
|
1953
|
+
const textBytes = Buffer.byteLength(
|
|
1954
|
+
JSON.stringify({
|
|
1955
|
+
messages,
|
|
1956
|
+
tools: input.tools ?? null,
|
|
1957
|
+
tool_choice: input.toolChoice
|
|
1958
|
+
})
|
|
1959
|
+
);
|
|
1960
|
+
const textTokens = Math.ceil(textBytes / 3);
|
|
1961
|
+
return {
|
|
1962
|
+
text_tokens: textTokens,
|
|
1963
|
+
image_tokens: imageTokens,
|
|
1964
|
+
total_tokens: textTokens + imageTokens,
|
|
1965
|
+
image_count: imageCount,
|
|
1966
|
+
fallback_image_count: fallbackCount,
|
|
1967
|
+
encoded_image_bytes: imageBytes,
|
|
1968
|
+
estimated_request_bytes: textBytes + imageBytes
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1971
|
+
function validateImagePayload(estimate, llm) {
|
|
1972
|
+
const limit = imagePayloadLimit(llm.provider);
|
|
1973
|
+
if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
|
|
1974
|
+
throw new Error(
|
|
1975
|
+
`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.`
|
|
1976
|
+
);
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
// src/agent/image-input.ts
|
|
1980
|
+
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
1981
|
+
async function materializeImageReferences(messages, resolve, signal) {
|
|
1982
|
+
signal?.throwIfAborted();
|
|
1983
|
+
if (resolve) {
|
|
1984
|
+
for (const message of messages) {
|
|
1985
|
+
if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
|
|
1986
|
+
for (const part of message.content) {
|
|
1987
|
+
if (part.type !== "image_ref") continue;
|
|
1988
|
+
const size = part.image_ref.byte_size;
|
|
1989
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
|
|
1990
|
+
throw new Error(
|
|
1991
|
+
"Invalid or oversized image reference; model request was not sent."
|
|
1992
|
+
);
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
const result = [];
|
|
1997
|
+
for (const message of messages) {
|
|
1998
|
+
if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
|
|
1999
|
+
result.push(message);
|
|
2000
|
+
continue;
|
|
2001
|
+
}
|
|
2002
|
+
const registry = isImageRegistry(message);
|
|
2003
|
+
const content = [];
|
|
2004
|
+
for (const part of message.content) {
|
|
2005
|
+
if (part.type !== "image_ref") {
|
|
2006
|
+
content.push(part);
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
signal?.throwIfAborted();
|
|
2010
|
+
if (!registry && resolve) {
|
|
2011
|
+
try {
|
|
2012
|
+
const image = await resolve(part.image_ref, signal);
|
|
2013
|
+
content.push(
|
|
2014
|
+
part.detail ? {
|
|
2015
|
+
...image,
|
|
2016
|
+
image_url: { ...image.image_url, detail: part.detail }
|
|
2017
|
+
} : image
|
|
2018
|
+
);
|
|
2019
|
+
signal?.throwIfAborted();
|
|
2020
|
+
continue;
|
|
2021
|
+
} catch {
|
|
2022
|
+
signal?.throwIfAborted();
|
|
2023
|
+
throw new Error(
|
|
2024
|
+
`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.`
|
|
2025
|
+
);
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
content.push({
|
|
2029
|
+
type: "text",
|
|
2030
|
+
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.]`
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
result.push({ ...message, content });
|
|
2034
|
+
}
|
|
2035
|
+
return result;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
1613
2038
|
// src/agent/model-context.ts
|
|
1614
2039
|
var calculateContextLeftPercent = ({
|
|
1615
2040
|
usage,
|
|
@@ -1691,16 +2116,16 @@ var collectModelOutput = (messages) => {
|
|
|
1691
2116
|
if (message.role === "reasoning") {
|
|
1692
2117
|
const raw = message.raw_item;
|
|
1693
2118
|
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1694
|
-
const
|
|
1695
|
-
const kind =
|
|
1696
|
-
const statusRaw =
|
|
2119
|
+
const record3 = raw;
|
|
2120
|
+
const kind = record3.type === "x_search_call" ? "x" : "web";
|
|
2121
|
+
const statusRaw = record3.status;
|
|
1697
2122
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1698
|
-
const action =
|
|
2123
|
+
const action = record3.action && typeof record3.action === "object" ? record3.action : null;
|
|
1699
2124
|
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1700
2125
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1701
2126
|
) : [];
|
|
1702
2127
|
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1703
|
-
const explicitId = typeof
|
|
2128
|
+
const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
|
|
1704
2129
|
let id = explicitId;
|
|
1705
2130
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1706
2131
|
if (!id) {
|
|
@@ -1936,7 +2361,7 @@ var executeToolCall = async ({
|
|
|
1936
2361
|
|
|
1937
2362
|
// src/agent/agent.ts
|
|
1938
2363
|
var DEFAULT_MAX_ITERATIONS = 200;
|
|
1939
|
-
var defaultMonotonicNowMs = () =>
|
|
2364
|
+
var defaultMonotonicNowMs = () => performance2.now();
|
|
1940
2365
|
var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
|
|
1941
2366
|
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
1942
2367
|
var createAbortError2 = () => {
|
|
@@ -1970,6 +2395,7 @@ var Agent = class {
|
|
|
1970
2395
|
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
1971
2396
|
history;
|
|
1972
2397
|
usageService;
|
|
2398
|
+
imageUsageBaseline;
|
|
1973
2399
|
constructor(options) {
|
|
1974
2400
|
this.llm = options.llm;
|
|
1975
2401
|
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
@@ -2022,13 +2448,15 @@ var Agent = class {
|
|
|
2022
2448
|
}
|
|
2023
2449
|
replaceHistoryMessages(messages) {
|
|
2024
2450
|
this.history.replaceViewMessages(messages);
|
|
2451
|
+
this.imageUsageBaseline = void 0;
|
|
2025
2452
|
}
|
|
2026
2453
|
async *checkAndCompact(signal, options = {}) {
|
|
2027
2454
|
throwIfAborted(signal);
|
|
2028
2455
|
await this.trimToolOutputs();
|
|
2029
2456
|
const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
|
|
2030
2457
|
this.llm,
|
|
2031
|
-
this.usageService.getLastUsage()
|
|
2458
|
+
this.usageService.getLastUsage(),
|
|
2459
|
+
options.estimatedInputTokens
|
|
2032
2460
|
);
|
|
2033
2461
|
if (shouldCompact && this.compactionService) {
|
|
2034
2462
|
throwIfAborted(signal);
|
|
@@ -2049,6 +2477,7 @@ var Agent = class {
|
|
|
2049
2477
|
this.usageService.updateUsageSummary(usage);
|
|
2050
2478
|
if (compacted && compactedMessages) {
|
|
2051
2479
|
this.history.replaceViewMessages(compactedMessages);
|
|
2480
|
+
this.imageUsageBaseline = void 0;
|
|
2052
2481
|
}
|
|
2053
2482
|
if (compacted || options.force) {
|
|
2054
2483
|
await this.llm.onHistoryCompacted?.(invokeContext);
|
|
@@ -2107,9 +2536,13 @@ var Agent = class {
|
|
|
2107
2536
|
const runId = session?.run_id?.trim();
|
|
2108
2537
|
return runId && runId.length > 0 ? runId : void 0;
|
|
2109
2538
|
}
|
|
2110
|
-
buildInvokeContext(session) {
|
|
2539
|
+
buildInvokeContext(session, turnKey) {
|
|
2111
2540
|
const sessionKey = this.resolveSessionKey(session);
|
|
2112
|
-
|
|
2541
|
+
const turn = turnKey ?? session?.run_id;
|
|
2542
|
+
return sessionKey || turn ? {
|
|
2543
|
+
...sessionKey ? { sessionKey } : {},
|
|
2544
|
+
...turn ? { turnKey: turn } : {}
|
|
2545
|
+
} : void 0;
|
|
2113
2546
|
}
|
|
2114
2547
|
recordLlmResponse(session, seq, response) {
|
|
2115
2548
|
if (!session || seq === null) return;
|
|
@@ -2120,6 +2553,7 @@ var Agent = class {
|
|
|
2120
2553
|
seq,
|
|
2121
2554
|
output: {
|
|
2122
2555
|
messages: response.messages,
|
|
2556
|
+
...response.timing ? { timing: response.timing } : {},
|
|
2123
2557
|
usage: response.usage ?? null,
|
|
2124
2558
|
stop_reason: response.stop_reason ?? null,
|
|
2125
2559
|
provider_meta: response.provider_meta ?? null
|
|
@@ -2127,19 +2561,43 @@ var Agent = class {
|
|
|
2127
2561
|
});
|
|
2128
2562
|
}
|
|
2129
2563
|
async *invokeModelWithRetry(input, context, signal) {
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2564
|
+
const estimate = estimateImageContext(
|
|
2565
|
+
input,
|
|
2566
|
+
this.llm,
|
|
2567
|
+
Boolean(this.services.resolveImage)
|
|
2568
|
+
);
|
|
2569
|
+
validateImagePayload(estimate, this.llm);
|
|
2570
|
+
const messages = await materializeImageReferences(
|
|
2571
|
+
input.messages,
|
|
2572
|
+
this.services.resolveImage,
|
|
2573
|
+
signal
|
|
2574
|
+
);
|
|
2575
|
+
const response = yield* withProviderStatus(
|
|
2576
|
+
(onProviderStatus, progressSignal) => invokeWithRetry({
|
|
2577
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2578
|
+
{
|
|
2579
|
+
...input,
|
|
2580
|
+
messages,
|
|
2581
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2582
|
+
},
|
|
2583
|
+
{ ...context, onProviderStatus }
|
|
2584
|
+
),
|
|
2585
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2586
|
+
policy: resolveLlmRetryPolicy({
|
|
2587
|
+
...this.llmRetryPolicy,
|
|
2588
|
+
...this.llm.retryPolicy
|
|
2589
|
+
}),
|
|
2590
|
+
signal: progressSignal,
|
|
2591
|
+
dependencies: this.llmRetryDependencies
|
|
2592
|
+
}),
|
|
2593
|
+
signal
|
|
2594
|
+
);
|
|
2595
|
+
this.imageUsageBaseline = response.usage ? {
|
|
2596
|
+
messages: input.messages.slice(),
|
|
2597
|
+
estimated: estimate.total_tokens,
|
|
2598
|
+
observed: response.usage.input_tokens
|
|
2599
|
+
} : void 0;
|
|
2600
|
+
return response;
|
|
2143
2601
|
}
|
|
2144
2602
|
async run(message, options = {}) {
|
|
2145
2603
|
let finalResponse = "";
|
|
@@ -2177,6 +2635,7 @@ var Agent = class {
|
|
|
2177
2635
|
for (const content of messages) this.history.enqueueUserMessage(content);
|
|
2178
2636
|
return messages;
|
|
2179
2637
|
};
|
|
2638
|
+
const turnKey = session?.run_id ?? randomUUID();
|
|
2180
2639
|
let iterations = 0;
|
|
2181
2640
|
const runTools = [...this.tools, ...options.tools ?? []];
|
|
2182
2641
|
const runToolChoice = options.toolChoice ?? this.toolChoice;
|
|
@@ -2187,11 +2646,27 @@ var Agent = class {
|
|
|
2187
2646
|
yield { type: "hidden_user_message", content };
|
|
2188
2647
|
await this.trimToolOutputs();
|
|
2189
2648
|
throwIfAborted(signal);
|
|
2190
|
-
|
|
2649
|
+
let invokeInput = this.history.prepareInvokeInput({
|
|
2191
2650
|
tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
|
|
2192
2651
|
toolChoice: runToolChoice
|
|
2193
2652
|
});
|
|
2194
|
-
const
|
|
2653
|
+
const imageEstimate = estimateImageContext(
|
|
2654
|
+
invokeInput,
|
|
2655
|
+
this.llm,
|
|
2656
|
+
Boolean(this.services.resolveImage)
|
|
2657
|
+
);
|
|
2658
|
+
if (imageEstimate.image_count > 0) {
|
|
2659
|
+
const baseline = this.imageUsageBaseline;
|
|
2660
|
+
const estimatedInputTokens = baseline && baseline.messages.every(
|
|
2661
|
+
(message2, index) => invokeInput.messages[index] === message2
|
|
2662
|
+
) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
|
|
2663
|
+
yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
|
|
2664
|
+
invokeInput = this.history.prepareInvokeInput({
|
|
2665
|
+
tools: invokeInput.tools,
|
|
2666
|
+
toolChoice: runToolChoice
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2195
2670
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
2196
2671
|
const response = yield* this.invokeModelWithRetry(
|
|
2197
2672
|
invokeInput,
|
|
@@ -2416,7 +2891,11 @@ var Agent = class {
|
|
|
2416
2891
|
yield* this.checkAndCompact(signal, { session });
|
|
2417
2892
|
}
|
|
2418
2893
|
if (signal?.aborted) throw createAbortError2();
|
|
2419
|
-
const finalResponse = await this.generateFinalResponse(
|
|
2894
|
+
const finalResponse = await this.generateFinalResponse(
|
|
2895
|
+
session,
|
|
2896
|
+
signal,
|
|
2897
|
+
turnKey
|
|
2898
|
+
);
|
|
2420
2899
|
const finalResponseEvent = {
|
|
2421
2900
|
type: "final",
|
|
2422
2901
|
termination_reason: "max_steps",
|
|
@@ -2425,7 +2904,7 @@ var Agent = class {
|
|
|
2425
2904
|
yield finalResponseEvent;
|
|
2426
2905
|
return;
|
|
2427
2906
|
}
|
|
2428
|
-
async generateFinalResponse(session, signal) {
|
|
2907
|
+
async generateFinalResponse(session, signal, turnKey) {
|
|
2429
2908
|
const summaryMessage = {
|
|
2430
2909
|
role: "user",
|
|
2431
2910
|
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 +2917,24 @@ var Agent = class {
|
|
|
2438
2917
|
// no tools are allowed at this point
|
|
2439
2918
|
toolChoice: "none"
|
|
2440
2919
|
};
|
|
2441
|
-
const invokeContext = this.buildInvokeContext(session);
|
|
2920
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2442
2921
|
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
2922
|
+
validateImagePayload(
|
|
2923
|
+
estimateImageContext(
|
|
2924
|
+
input,
|
|
2925
|
+
this.llm,
|
|
2926
|
+
Boolean(this.services.resolveImage)
|
|
2927
|
+
),
|
|
2928
|
+
this.llm
|
|
2929
|
+
);
|
|
2443
2930
|
const summary = await this.llm.ainvoke(
|
|
2444
2931
|
{
|
|
2445
2932
|
...input,
|
|
2933
|
+
messages: await materializeImageReferences(
|
|
2934
|
+
input.messages,
|
|
2935
|
+
this.services.resolveImage,
|
|
2936
|
+
signal
|
|
2937
|
+
),
|
|
2446
2938
|
...signal ? { signal } : {}
|
|
2447
2939
|
},
|
|
2448
2940
|
invokeContext
|
|
@@ -2463,8 +2955,90 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
2463
2955
|
}
|
|
2464
2956
|
};
|
|
2465
2957
|
|
|
2958
|
+
// src/llm/stream-timing.ts
|
|
2959
|
+
var record = (value) => value !== null && typeof value === "object" ? value : void 0;
|
|
2960
|
+
var nonempty = (value) => typeof value === "string" && value.length > 0;
|
|
2961
|
+
var responseOutputDeltas = /* @__PURE__ */ new Set([
|
|
2962
|
+
"response.output_text.delta",
|
|
2963
|
+
"response.refusal.delta",
|
|
2964
|
+
"response.function_call_arguments.delta",
|
|
2965
|
+
"response.custom_tool_call_input.delta",
|
|
2966
|
+
"response.reasoning_text.delta",
|
|
2967
|
+
"response.reasoning_summary_text.delta"
|
|
2968
|
+
]);
|
|
2969
|
+
var LlmStreamTiming = class {
|
|
2970
|
+
constructor(nowMs = () => performance.now()) {
|
|
2971
|
+
this.nowMs = nowMs;
|
|
2972
|
+
this.startedAt = nowMs();
|
|
2973
|
+
}
|
|
2974
|
+
nowMs;
|
|
2975
|
+
startedAt;
|
|
2976
|
+
firstOutputAt;
|
|
2977
|
+
reasoningStartedAt;
|
|
2978
|
+
completedAt;
|
|
2979
|
+
observeOutput() {
|
|
2980
|
+
if (this.completedAt === void 0 && this.firstOutputAt === void 0)
|
|
2981
|
+
this.firstOutputAt = this.nowMs();
|
|
2982
|
+
}
|
|
2983
|
+
complete() {
|
|
2984
|
+
this.completedAt ??= this.nowMs();
|
|
2985
|
+
}
|
|
2986
|
+
observeResponsesEvent(event) {
|
|
2987
|
+
const value = record(event);
|
|
2988
|
+
if (!value) return;
|
|
2989
|
+
if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
|
|
2990
|
+
this.reasoningStartedAt ??= this.nowMs();
|
|
2991
|
+
if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
|
|
2992
|
+
this.observeOutput();
|
|
2993
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
|
|
2994
|
+
this.complete();
|
|
2995
|
+
}
|
|
2996
|
+
observeChatChunk(chunk) {
|
|
2997
|
+
const choices = record(chunk)?.choices;
|
|
2998
|
+
if (!Array.isArray(choices)) return;
|
|
2999
|
+
for (const choice of choices) {
|
|
3000
|
+
const delta = record(record(choice)?.delta);
|
|
3001
|
+
if (!delta) continue;
|
|
3002
|
+
if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
|
|
3003
|
+
(tool) => nonempty(record(record(tool)?.function)?.arguments)
|
|
3004
|
+
))
|
|
3005
|
+
this.observeOutput();
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
observeAnthropicEvent(event) {
|
|
3009
|
+
const value = record(event);
|
|
3010
|
+
if (!value) return;
|
|
3011
|
+
const delta = record(value.delta);
|
|
3012
|
+
if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
|
|
3013
|
+
this.observeOutput();
|
|
3014
|
+
if (value.type === "message_stop") this.complete();
|
|
3015
|
+
}
|
|
3016
|
+
finish() {
|
|
3017
|
+
this.complete();
|
|
3018
|
+
if (this.firstOutputAt === void 0) return void 0;
|
|
3019
|
+
const first = this.firstOutputAt - this.startedAt;
|
|
3020
|
+
const start = Math.min(
|
|
3021
|
+
this.firstOutputAt,
|
|
3022
|
+
this.reasoningStartedAt ?? this.firstOutputAt
|
|
3023
|
+
);
|
|
3024
|
+
const generation = this.completedAt - start;
|
|
3025
|
+
if (![first, generation, start - this.startedAt].every(
|
|
3026
|
+
(ms) => Number.isFinite(ms) && ms >= 0
|
|
3027
|
+
))
|
|
3028
|
+
return void 0;
|
|
3029
|
+
return {
|
|
3030
|
+
time_to_first_token_ms: first,
|
|
3031
|
+
generation_duration_ms: generation,
|
|
3032
|
+
...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
|
|
3033
|
+
generation_start_ms: start - this.startedAt,
|
|
3034
|
+
generation_start_source: "reasoning_item"
|
|
3035
|
+
} : {}
|
|
3036
|
+
};
|
|
3037
|
+
}
|
|
3038
|
+
};
|
|
3039
|
+
|
|
2466
3040
|
// src/llm/anthropic/chat.ts
|
|
2467
|
-
import { createHash } from "crypto";
|
|
3041
|
+
import { createHash as createHash2 } from "crypto";
|
|
2468
3042
|
import Anthropic from "@anthropic-ai/sdk";
|
|
2469
3043
|
|
|
2470
3044
|
// src/llm/anthropic/failure.ts
|
|
@@ -2534,6 +3108,74 @@ var classifyAnthropicFailure = (error) => {
|
|
|
2534
3108
|
return classifyTransportFailure(PROVIDER_NAME, error) ?? buildProviderFailure(PROVIDER_NAME, "provider");
|
|
2535
3109
|
};
|
|
2536
3110
|
|
|
3111
|
+
// src/llm/anthropic/thinking.ts
|
|
3112
|
+
import { createHash } from "crypto";
|
|
3113
|
+
var PREFIX_KEY = "codelia_anthropic_prefix_sha256";
|
|
3114
|
+
var usesBoundThinking = (model) => model === "claude-sonnet-5-5" || model === "claude-haiku-5-5";
|
|
3115
|
+
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
3116
|
+
var isThinkingBlock = (value) => isRecord(value) && (value.type === "thinking" && typeof value.thinking === "string" && typeof value.signature === "string" || value.type === "redacted_thinking" && typeof value.data === "string");
|
|
3117
|
+
var canonicalJson = (value) => JSON.stringify(
|
|
3118
|
+
value,
|
|
3119
|
+
(_key, item) => isRecord(item) && !Array.isArray(item) ? Object.fromEntries(
|
|
3120
|
+
Object.keys(item).sort().map((key) => [key, item[key]])
|
|
3121
|
+
) : item
|
|
3122
|
+
);
|
|
3123
|
+
var startPrefix = (request) => createHash("sha256").update(
|
|
3124
|
+
canonicalJson({
|
|
3125
|
+
system: request.system ?? null,
|
|
3126
|
+
tools: request.tools ?? []
|
|
3127
|
+
})
|
|
3128
|
+
).update("\n");
|
|
3129
|
+
var startMessage = (hash, role) => hash.copy().update(`${role}
|
|
3130
|
+
`);
|
|
3131
|
+
var addBlock = (hash, block) => {
|
|
3132
|
+
hash.update(canonicalJson(block)).update("\n");
|
|
3133
|
+
};
|
|
3134
|
+
var contentBlocks = (message) => typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
|
|
3135
|
+
var filterBoundThinking = (request) => {
|
|
3136
|
+
let hash = startPrefix(request);
|
|
3137
|
+
const messages = [];
|
|
3138
|
+
for (const message of request.messages) {
|
|
3139
|
+
const nextHash = startMessage(hash, message.role);
|
|
3140
|
+
const content = [];
|
|
3141
|
+
for (const block of contentBlocks(message)) {
|
|
3142
|
+
let clean = block;
|
|
3143
|
+
if (isThinkingBlock(block)) {
|
|
3144
|
+
const { [PREFIX_KEY]: prefix, ...original } = block;
|
|
3145
|
+
if (prefix !== nextHash.copy().digest("hex") || !isThinkingBlock(original))
|
|
3146
|
+
continue;
|
|
3147
|
+
clean = original;
|
|
3148
|
+
}
|
|
3149
|
+
content.push(clean);
|
|
3150
|
+
addBlock(nextHash, clean);
|
|
3151
|
+
}
|
|
3152
|
+
if (content.length === 0) continue;
|
|
3153
|
+
messages.push({ ...message, content });
|
|
3154
|
+
hash = nextHash;
|
|
3155
|
+
}
|
|
3156
|
+
return messages;
|
|
3157
|
+
};
|
|
3158
|
+
var bindResponseThinking = (request, blocks, messages) => {
|
|
3159
|
+
let hash = startPrefix(request);
|
|
3160
|
+
for (const message of request.messages) {
|
|
3161
|
+
hash = startMessage(hash, message.role);
|
|
3162
|
+
for (const block of contentBlocks(message)) addBlock(hash, block);
|
|
3163
|
+
}
|
|
3164
|
+
hash = startMessage(hash, "assistant");
|
|
3165
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
3166
|
+
for (const block of blocks) {
|
|
3167
|
+
if (isThinkingBlock(block)) prefixes.set(block, hash.copy().digest("hex"));
|
|
3168
|
+
addBlock(hash, block);
|
|
3169
|
+
}
|
|
3170
|
+
for (const message of messages) {
|
|
3171
|
+
if (message.role !== "reasoning" || !isThinkingBlock(message.raw_item))
|
|
3172
|
+
continue;
|
|
3173
|
+
const prefix = prefixes.get(message.raw_item);
|
|
3174
|
+
if (prefix)
|
|
3175
|
+
message.raw_item = { ...message.raw_item, [PREFIX_KEY]: prefix };
|
|
3176
|
+
}
|
|
3177
|
+
};
|
|
3178
|
+
|
|
2537
3179
|
// src/llm/provider-log.ts
|
|
2538
3180
|
import { promises as fs } from "fs";
|
|
2539
3181
|
import path from "path";
|
|
@@ -2589,6 +3231,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
|
|
|
2589
3231
|
};
|
|
2590
3232
|
|
|
2591
3233
|
// src/types/llm/guards.ts
|
|
3234
|
+
import { isImageModelView } from "@codelia/shared-types";
|
|
2592
3235
|
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2593
3236
|
function isTextPart(value) {
|
|
2594
3237
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2617,7 +3260,19 @@ function isOtherPart(value) {
|
|
|
2617
3260
|
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2618
3261
|
}
|
|
2619
3262
|
function isContentPart(value) {
|
|
2620
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3263
|
+
return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3264
|
+
}
|
|
3265
|
+
function isImageRefPart(value) {
|
|
3266
|
+
if (!value || typeof value !== "object") return false;
|
|
3267
|
+
const v = value;
|
|
3268
|
+
if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
|
|
3269
|
+
return false;
|
|
3270
|
+
const r = v.image_ref;
|
|
3271
|
+
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(
|
|
3272
|
+
String(r.media_type)
|
|
3273
|
+
) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
|
|
3274
|
+
(n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
|
|
3275
|
+
) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
|
|
2621
3276
|
}
|
|
2622
3277
|
function isToolResult(value) {
|
|
2623
3278
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2639,7 +3294,7 @@ var isHostedXSearchToolDefinition = (value) => value.type === "hosted_search" &&
|
|
|
2639
3294
|
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
2640
3295
|
|
|
2641
3296
|
// src/llm/anthropic/serializer.ts
|
|
2642
|
-
var
|
|
3297
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
2643
3298
|
var stringifyUnknown2 = (value) => {
|
|
2644
3299
|
if (value == null) return "";
|
|
2645
3300
|
if (typeof value === "string") return value;
|
|
@@ -2660,14 +3315,14 @@ var parseDataUrl = (url) => {
|
|
|
2660
3315
|
};
|
|
2661
3316
|
var isSupportedImageMediaType = (value) => value === "image/png" || value === "image/jpeg" || value === "image/webp" || value === "image/gif";
|
|
2662
3317
|
var isAnthropicContentBlock = (value) => {
|
|
2663
|
-
if (!
|
|
3318
|
+
if (!isRecord2(value) || typeof value.type !== "string") return false;
|
|
2664
3319
|
switch (value.type) {
|
|
2665
3320
|
case "text":
|
|
2666
3321
|
return typeof value.text === "string";
|
|
2667
3322
|
case "image":
|
|
2668
|
-
return
|
|
3323
|
+
return isRecord2(value.source);
|
|
2669
3324
|
case "document":
|
|
2670
|
-
return
|
|
3325
|
+
return isRecord2(value.source);
|
|
2671
3326
|
case "search_result":
|
|
2672
3327
|
return true;
|
|
2673
3328
|
default:
|
|
@@ -2721,6 +3376,15 @@ var toContentBlocks = (content) => {
|
|
|
2721
3376
|
}
|
|
2722
3377
|
};
|
|
2723
3378
|
}
|
|
3379
|
+
if (URL.canParse(part.image_url.url)) {
|
|
3380
|
+
const url = new URL(part.image_url.url);
|
|
3381
|
+
if (url.protocol === "https:" || url.protocol === "http:") {
|
|
3382
|
+
return {
|
|
3383
|
+
type: "image",
|
|
3384
|
+
source: { type: "url", url: part.image_url.url }
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
}
|
|
2724
3388
|
return toTextBlock(part.image_url.url);
|
|
2725
3389
|
}
|
|
2726
3390
|
case "document":
|
|
@@ -2798,8 +3462,8 @@ var mergePendingToolResults = (pendingToolResults, output) => {
|
|
|
2798
3462
|
});
|
|
2799
3463
|
pendingToolResults.length = 0;
|
|
2800
3464
|
};
|
|
2801
|
-
var isToolUseBlock = (block) =>
|
|
2802
|
-
var isToolResultBlock = (block) =>
|
|
3465
|
+
var isToolUseBlock = (block) => isRecord2(block) && block.type === "tool_use";
|
|
3466
|
+
var isToolResultBlock = (block) => isRecord2(block) && block.type === "tool_result";
|
|
2803
3467
|
var isAssistantWithToolUseBlocks = (message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => isToolUseBlock(block));
|
|
2804
3468
|
var coalesceConsecutiveAssistantToolUseMessages = (messages) => {
|
|
2805
3469
|
const normalized = [];
|
|
@@ -2882,7 +3546,7 @@ var dropOrphanToolUseBlocks = (messages) => {
|
|
|
2882
3546
|
}
|
|
2883
3547
|
return sanitized;
|
|
2884
3548
|
};
|
|
2885
|
-
var toAnthropicMessages = (messages) => {
|
|
3549
|
+
var toAnthropicMessages = (messages, options) => {
|
|
2886
3550
|
const systemParts = [];
|
|
2887
3551
|
const output = [];
|
|
2888
3552
|
const pendingToolResults = [];
|
|
@@ -2895,6 +3559,10 @@ var toAnthropicMessages = (messages) => {
|
|
|
2895
3559
|
break;
|
|
2896
3560
|
}
|
|
2897
3561
|
case "reasoning":
|
|
3562
|
+
if (options?.replayThinking && isThinkingBlock(message.raw_item)) {
|
|
3563
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
3564
|
+
output.push({ role: "assistant", content: [message.raw_item] });
|
|
3565
|
+
}
|
|
2898
3566
|
break;
|
|
2899
3567
|
case "tool": {
|
|
2900
3568
|
pendingToolResults.push(toToolResultBlock(message));
|
|
@@ -2903,9 +3571,29 @@ var toAnthropicMessages = (messages) => {
|
|
|
2903
3571
|
case "assistant": {
|
|
2904
3572
|
mergePendingToolResults(pendingToolResults, output);
|
|
2905
3573
|
const blocks = [];
|
|
2906
|
-
|
|
3574
|
+
const original = message.provider_meta;
|
|
3575
|
+
if (options?.replayThinking && isRecord2(original) && original.type === "text" && original.text === message.content) {
|
|
3576
|
+
blocks.push(original);
|
|
3577
|
+
} else {
|
|
3578
|
+
const part = Array.isArray(message.content) && message.content.length === 1 ? message.content[0] : void 0;
|
|
3579
|
+
if (options?.replayThinking && part?.type === "other" && part.provider === "anthropic" && isRecord2(part.payload) && [
|
|
3580
|
+
"server_tool_use",
|
|
3581
|
+
"web_search_tool_result",
|
|
3582
|
+
"web_fetch_tool_result"
|
|
3583
|
+
].includes(String(part.payload.type))) {
|
|
3584
|
+
blocks.push(part.payload);
|
|
3585
|
+
} else {
|
|
3586
|
+
blocks.push(...toContentBlocks(message.content));
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
2907
3589
|
if (message.tool_calls?.length) {
|
|
2908
|
-
blocks.push(
|
|
3590
|
+
blocks.push(
|
|
3591
|
+
...message.tool_calls.map((call) => {
|
|
3592
|
+
const block = toToolUseBlock(call);
|
|
3593
|
+
const original2 = call.provider_meta;
|
|
3594
|
+
return options?.replayThinking && isRecord2(original2) && original2.type === "tool_use" && original2.id === block.id && original2.name === block.name && JSON.stringify(original2.input) === JSON.stringify(block.input) ? original2 : block;
|
|
3595
|
+
})
|
|
3596
|
+
);
|
|
2909
3597
|
}
|
|
2910
3598
|
output.push({
|
|
2911
3599
|
role: "assistant",
|
|
@@ -2928,7 +3616,16 @@ var toAnthropicMessages = (messages) => {
|
|
|
2928
3616
|
}
|
|
2929
3617
|
mergePendingToolResults(pendingToolResults, output);
|
|
2930
3618
|
const system = systemParts.length ? systemParts.join("\n\n") : void 0;
|
|
2931
|
-
|
|
3619
|
+
const turns = [];
|
|
3620
|
+
for (const message of output) {
|
|
3621
|
+
const previous = turns.at(-1);
|
|
3622
|
+
if (options?.replayThinking && message.role === "assistant" && previous?.role === "assistant" && Array.isArray(message.content) && Array.isArray(previous.content)) {
|
|
3623
|
+
previous.content.push(...message.content);
|
|
3624
|
+
} else {
|
|
3625
|
+
turns.push(message);
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
return { system, messages: dropOrphanToolUseBlocks(turns) };
|
|
2932
3629
|
};
|
|
2933
3630
|
var extractText = (blocks) => blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
2934
3631
|
var DEFAULT_REFUSAL_MESSAGE = "This request was declined by Anthropic's safety classifier.";
|
|
@@ -2965,7 +3662,8 @@ var toChatInvokeCompletion = (response, meta) => {
|
|
|
2965
3662
|
case "text":
|
|
2966
3663
|
messages.push({
|
|
2967
3664
|
role: "assistant",
|
|
2968
|
-
content: block.text
|
|
3665
|
+
content: block.text,
|
|
3666
|
+
...meta?.preserveBlocks ? { provider_meta: block } : {}
|
|
2969
3667
|
});
|
|
2970
3668
|
break;
|
|
2971
3669
|
case "tool_use":
|
|
@@ -2978,7 +3676,7 @@ var toChatInvokeCompletion = (response, meta) => {
|
|
|
2978
3676
|
type: "function",
|
|
2979
3677
|
function: {
|
|
2980
3678
|
name: block.name,
|
|
2981
|
-
arguments:
|
|
3679
|
+
arguments: isRecord2(block.input) ? JSON.stringify(block.input) : JSON.stringify({ value: block.input })
|
|
2982
3680
|
},
|
|
2983
3681
|
provider_meta: block
|
|
2984
3682
|
}
|
|
@@ -3110,7 +3808,12 @@ var ChatAnthropic = class {
|
|
|
3110
3808
|
model,
|
|
3111
3809
|
signal
|
|
3112
3810
|
} = input;
|
|
3113
|
-
const
|
|
3811
|
+
const requestModel = model ?? this.model;
|
|
3812
|
+
const boundThinking = usesBoundThinking(requestModel);
|
|
3813
|
+
const { system, messages: anthropicMessages } = toAnthropicMessages(
|
|
3814
|
+
messages,
|
|
3815
|
+
{ replayThinking: boundThinking }
|
|
3816
|
+
);
|
|
3114
3817
|
const enableTools = toolChoice !== "none";
|
|
3115
3818
|
const tools = enableTools ? toAnthropicTools(toolDefs) : void 0;
|
|
3116
3819
|
const tool_choice = enableTools ? toAnthropicToolChoice(toolChoice) : void 0;
|
|
@@ -3120,7 +3823,7 @@ var ChatAnthropic = class {
|
|
|
3120
3823
|
};
|
|
3121
3824
|
const { max_tokens, ...rest } = resolvedOptions;
|
|
3122
3825
|
const request = {
|
|
3123
|
-
model:
|
|
3826
|
+
model: requestModel,
|
|
3124
3827
|
max_tokens: max_tokens ?? this.defaultMaxTokens,
|
|
3125
3828
|
messages: anthropicMessages,
|
|
3126
3829
|
...rest,
|
|
@@ -3128,6 +3831,54 @@ var ChatAnthropic = class {
|
|
|
3128
3831
|
...tools ? { tools } : {},
|
|
3129
3832
|
...tool_choice ? { tool_choice } : {}
|
|
3130
3833
|
};
|
|
3834
|
+
if (boundThinking) {
|
|
3835
|
+
if (this.fastMode || request.speed === "fast") {
|
|
3836
|
+
throw createProviderValidationError(
|
|
3837
|
+
PROVIDER_NAME2,
|
|
3838
|
+
"Claude Sonnet/Haiku 5.5 do not support Fast mode."
|
|
3839
|
+
);
|
|
3840
|
+
}
|
|
3841
|
+
if ([request.temperature, request.top_p, request.top_k].some(
|
|
3842
|
+
(value) => value !== void 0
|
|
3843
|
+
)) {
|
|
3844
|
+
throw createProviderValidationError(
|
|
3845
|
+
PROVIDER_NAME2,
|
|
3846
|
+
"Claude Sonnet/Haiku 5.5 require temperature, top_p and top_k to be omitted."
|
|
3847
|
+
);
|
|
3848
|
+
}
|
|
3849
|
+
if (request.thinking?.type === "enabled") {
|
|
3850
|
+
throw createProviderValidationError(
|
|
3851
|
+
PROVIDER_NAME2,
|
|
3852
|
+
"Claude Sonnet/Haiku 5.5 require adaptive thinking instead of legacy budget_tokens."
|
|
3853
|
+
);
|
|
3854
|
+
}
|
|
3855
|
+
if (requestModel === "claude-sonnet-5-5" && (tool_choice?.type === "any" || tool_choice?.type === "tool")) {
|
|
3856
|
+
throw createProviderValidationError(
|
|
3857
|
+
PROVIDER_NAME2,
|
|
3858
|
+
"Claude Sonnet 5.5 does not support required or named tool choice. Use auto tool choice."
|
|
3859
|
+
);
|
|
3860
|
+
}
|
|
3861
|
+
if (requestModel === "claude-sonnet-5-5" && request.thinking?.type === "disabled") {
|
|
3862
|
+
throw createProviderValidationError(
|
|
3863
|
+
PROVIDER_NAME2,
|
|
3864
|
+
"Claude Sonnet 5.5 requires adaptive thinking."
|
|
3865
|
+
);
|
|
3866
|
+
}
|
|
3867
|
+
if (!request.thinking || request.thinking.type === "adaptive") {
|
|
3868
|
+
request.thinking = {
|
|
3869
|
+
type: "adaptive",
|
|
3870
|
+
display: "summarized",
|
|
3871
|
+
...request.thinking
|
|
3872
|
+
};
|
|
3873
|
+
}
|
|
3874
|
+
request.messages = filterBoundThinking(request);
|
|
3875
|
+
if (request.messages.at(-1)?.role !== "user") {
|
|
3876
|
+
throw createProviderValidationError(
|
|
3877
|
+
PROVIDER_NAME2,
|
|
3878
|
+
"Claude Sonnet/Haiku 5.5 require a final user or tool-result turn; assistant prefill is unsupported."
|
|
3879
|
+
);
|
|
3880
|
+
}
|
|
3881
|
+
}
|
|
3131
3882
|
if (request.cache_control === void 0) {
|
|
3132
3883
|
request.cache_control = DEFAULT_PROMPT_CACHE_CONTROL;
|
|
3133
3884
|
}
|
|
@@ -3138,20 +3889,31 @@ var ChatAnthropic = class {
|
|
|
3138
3889
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
3139
3890
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
3140
3891
|
const requestOptions = signal ? { signal } : void 0;
|
|
3141
|
-
const
|
|
3892
|
+
const timing = new LlmStreamTiming();
|
|
3893
|
+
const stream = this.fastMode ? this.client.beta.messages.stream(
|
|
3142
3894
|
request,
|
|
3143
3895
|
requestOptions
|
|
3144
|
-
) :
|
|
3896
|
+
) : this.client.messages.stream(
|
|
3145
3897
|
request,
|
|
3146
3898
|
requestOptions
|
|
3147
3899
|
);
|
|
3900
|
+
for await (const event of stream) timing.observeAnthropicEvent(event);
|
|
3901
|
+
const response = await stream.finalMessage();
|
|
3902
|
+
const measuredTiming = timing.finish();
|
|
3148
3903
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3149
|
-
|
|
3904
|
+
const completion = toChatInvokeCompletion(response, {
|
|
3150
3905
|
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
3151
3906
|
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
3152
3907
|
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
|
|
3153
|
-
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
|
|
3908
|
+
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset,
|
|
3909
|
+
preserveBlocks: boundThinking
|
|
3154
3910
|
});
|
|
3911
|
+
if (boundThinking)
|
|
3912
|
+
bindResponseThinking(request, response.content, completion.messages);
|
|
3913
|
+
return {
|
|
3914
|
+
...completion,
|
|
3915
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
3916
|
+
};
|
|
3155
3917
|
}
|
|
3156
3918
|
nextDebugInvokeSeq() {
|
|
3157
3919
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -3164,9 +3926,9 @@ var ChatAnthropic = class {
|
|
|
3164
3926
|
return;
|
|
3165
3927
|
}
|
|
3166
3928
|
const payload = safeJsonStringify(request);
|
|
3167
|
-
const hash =
|
|
3168
|
-
const toolsHash =
|
|
3169
|
-
const systemHash =
|
|
3929
|
+
const hash = createHash2("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3930
|
+
const toolsHash = createHash2("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
3931
|
+
const systemHash = createHash2("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
3170
3932
|
const previous = this.lastDebugRequestPayload;
|
|
3171
3933
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3172
3934
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -3236,7 +3998,7 @@ var ChatAnthropic = class {
|
|
|
3236
3998
|
};
|
|
3237
3999
|
|
|
3238
4000
|
// src/llm/moonshot/chat.ts
|
|
3239
|
-
import { createHash as
|
|
4001
|
+
import { createHash as createHash3 } from "crypto";
|
|
3240
4002
|
import OpenAI from "openai";
|
|
3241
4003
|
|
|
3242
4004
|
// src/llm/moonshot/failure.ts
|
|
@@ -3557,8 +4319,8 @@ function toMoonshotChatInvokeCompletion(accumulator, meta) {
|
|
|
3557
4319
|
response_id: accumulator.id,
|
|
3558
4320
|
finish_reason: accumulator.finishReason ?? null,
|
|
3559
4321
|
reasoning_requested: meta.reasoningRequested,
|
|
3560
|
-
reasoning_applied: "max",
|
|
3561
|
-
reasoning_effort: "max",
|
|
4322
|
+
reasoning_applied: meta.reasoningApplied ?? "max",
|
|
4323
|
+
reasoning_effort: meta.reasoningApplied ?? "max",
|
|
3562
4324
|
reasoning_fallback: meta.reasoningFallback
|
|
3563
4325
|
}
|
|
3564
4326
|
};
|
|
@@ -3607,12 +4369,14 @@ var ChatMoonshot = class {
|
|
|
3607
4369
|
apiKey;
|
|
3608
4370
|
clientOptions;
|
|
3609
4371
|
reasoningLevelRequested;
|
|
4372
|
+
reasoningEffort;
|
|
3610
4373
|
debugInvokeSeq = 0;
|
|
3611
4374
|
lastDebugRequestPayload = null;
|
|
3612
4375
|
constructor(options = {}) {
|
|
3613
4376
|
this.apiKey = options.apiKey;
|
|
3614
4377
|
this.model = options.model ?? MOONSHOT_DEFAULT_MODEL;
|
|
3615
4378
|
this.reasoningLevelRequested = options.reasoningLevelRequested ?? "medium";
|
|
4379
|
+
this.reasoningEffort = options.reasoningEffort ?? "max";
|
|
3616
4380
|
this.clientOptions = {
|
|
3617
4381
|
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
3618
4382
|
timeout: options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
@@ -3631,7 +4395,7 @@ var ChatMoonshot = class {
|
|
|
3631
4395
|
messages: toMoonshotMessages(input.messages),
|
|
3632
4396
|
stream: true,
|
|
3633
4397
|
stream_options: { include_usage: true },
|
|
3634
|
-
reasoning_effort:
|
|
4398
|
+
reasoning_effort: this.reasoningEffort,
|
|
3635
4399
|
...input.options ?? {},
|
|
3636
4400
|
...tools ? { tools } : {},
|
|
3637
4401
|
...toolChoice ? { tool_choice: toolChoice } : {}
|
|
@@ -3639,6 +4403,7 @@ var ChatMoonshot = class {
|
|
|
3639
4403
|
const seq = this.nextDebugInvokeSeq();
|
|
3640
4404
|
await this.debugRequestIfEnabled(request, seq);
|
|
3641
4405
|
const client = new OpenAI({ apiKey: this.apiKey, ...this.clientOptions });
|
|
4406
|
+
const timing = new LlmStreamTiming();
|
|
3642
4407
|
const accumulator = createMoonshotStreamAccumulator();
|
|
3643
4408
|
try {
|
|
3644
4409
|
const stream = await client.chat.completions.create(
|
|
@@ -3646,6 +4411,7 @@ var ChatMoonshot = class {
|
|
|
3646
4411
|
{ signal: input.signal }
|
|
3647
4412
|
);
|
|
3648
4413
|
for await (const chunk of stream) {
|
|
4414
|
+
timing.observeChatChunk(chunk);
|
|
3649
4415
|
appendMoonshotChatCompletionChunk(
|
|
3650
4416
|
accumulator,
|
|
3651
4417
|
chunk
|
|
@@ -3658,11 +4424,16 @@ var ChatMoonshot = class {
|
|
|
3658
4424
|
{ cause: error }
|
|
3659
4425
|
);
|
|
3660
4426
|
}
|
|
4427
|
+
const measuredTiming = timing.finish();
|
|
3661
4428
|
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3662
|
-
return
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
4429
|
+
return {
|
|
4430
|
+
...toMoonshotChatInvokeCompletion(accumulator, {
|
|
4431
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
4432
|
+
reasoningApplied: request.reasoning_effort,
|
|
4433
|
+
reasoningFallback: this.reasoningLevelRequested !== request.reasoning_effort
|
|
4434
|
+
}),
|
|
4435
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
4436
|
+
};
|
|
3666
4437
|
}
|
|
3667
4438
|
nextDebugInvokeSeq() {
|
|
3668
4439
|
this.debugInvokeSeq += 1;
|
|
@@ -3672,7 +4443,7 @@ var ChatMoonshot = class {
|
|
|
3672
4443
|
const settings = getProviderLogSettings();
|
|
3673
4444
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
3674
4445
|
const payload = safeJsonStringify(request);
|
|
3675
|
-
const hash =
|
|
4446
|
+
const hash = createHash3("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3676
4447
|
const previous = this.lastDebugRequestPayload;
|
|
3677
4448
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3678
4449
|
if (settings.enabled) {
|
|
@@ -3728,11 +4499,185 @@ var ChatMoonshot = class {
|
|
|
3728
4499
|
};
|
|
3729
4500
|
|
|
3730
4501
|
// src/llm/openai/chat.ts
|
|
3731
|
-
import { createHash as
|
|
4502
|
+
import { createHash as createHash5 } from "crypto";
|
|
4503
|
+
import OpenAI3 from "openai";
|
|
4504
|
+
|
|
4505
|
+
// src/llm/openai/codex-metadata.ts
|
|
4506
|
+
import { createHash as createHash4 } from "crypto";
|
|
4507
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
4508
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
|
|
4509
|
+
var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
|
|
4510
|
+
var headerValue = (headers, name) => {
|
|
4511
|
+
const entries = record2(headers);
|
|
4512
|
+
const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
4513
|
+
return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
|
|
4514
|
+
};
|
|
4515
|
+
var isCodexBackend = (baseURL) => {
|
|
4516
|
+
try {
|
|
4517
|
+
const url = new URL(baseURL);
|
|
4518
|
+
return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
|
|
4519
|
+
} catch {
|
|
4520
|
+
return false;
|
|
4521
|
+
}
|
|
4522
|
+
};
|
|
4523
|
+
var CodexTurnState = class {
|
|
4524
|
+
owner;
|
|
4525
|
+
value;
|
|
4526
|
+
invalidated = false;
|
|
4527
|
+
bindAuth(headers) {
|
|
4528
|
+
const authorization = headers.get("authorization") ?? "";
|
|
4529
|
+
let identity = authorization;
|
|
4530
|
+
try {
|
|
4531
|
+
const claims = record2(
|
|
4532
|
+
JSON.parse(
|
|
4533
|
+
Buffer.from(
|
|
4534
|
+
authorization.replace(/^Bearer /i, "").split(".")[1],
|
|
4535
|
+
"base64url"
|
|
4536
|
+
).toString("utf8")
|
|
4537
|
+
)
|
|
4538
|
+
);
|
|
4539
|
+
if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
|
|
4540
|
+
const account = record2(
|
|
4541
|
+
claims["https://api.openai.com/auth"]
|
|
4542
|
+
)?.chatgpt_account_id;
|
|
4543
|
+
identity = JSON.stringify([
|
|
4544
|
+
claims.iss,
|
|
4545
|
+
claims.sub,
|
|
4546
|
+
typeof claims.client_id === "string" ? claims.client_id : null,
|
|
4547
|
+
typeof account === "string" ? account : null
|
|
4548
|
+
]);
|
|
4549
|
+
}
|
|
4550
|
+
} catch {
|
|
4551
|
+
}
|
|
4552
|
+
const owner = createHash4("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
|
|
4553
|
+
const changed = this.owner !== void 0 && this.owner !== owner;
|
|
4554
|
+
if (changed) {
|
|
4555
|
+
this.value = void 0;
|
|
4556
|
+
this.invalidated = true;
|
|
4557
|
+
}
|
|
4558
|
+
this.owner = owner;
|
|
4559
|
+
return this.invalidated;
|
|
4560
|
+
}
|
|
4561
|
+
observe(value) {
|
|
4562
|
+
if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
|
|
4563
|
+
this.value = value;
|
|
4564
|
+
}
|
|
4565
|
+
requestHeaders() {
|
|
4566
|
+
return this.value ? { "x-codex-turn-state": this.value } : {};
|
|
4567
|
+
}
|
|
4568
|
+
};
|
|
4569
|
+
var CodexMetadataCollector = class {
|
|
4570
|
+
constructor(routing, onStatus) {
|
|
4571
|
+
this.routing = routing;
|
|
4572
|
+
this.onStatus = onStatus;
|
|
4573
|
+
}
|
|
4574
|
+
routing;
|
|
4575
|
+
onStatus;
|
|
4576
|
+
summary = {};
|
|
4577
|
+
outputStarted = false;
|
|
4578
|
+
fallbackModel;
|
|
4579
|
+
verificationNotified = false;
|
|
4580
|
+
beginAttempt() {
|
|
4581
|
+
this.clearBuffering();
|
|
4582
|
+
for (const key of Object.keys(this.summary))
|
|
4583
|
+
delete this.summary[key];
|
|
4584
|
+
this.outputStarted = false;
|
|
4585
|
+
this.fallbackModel = void 0;
|
|
4586
|
+
}
|
|
4587
|
+
observeHeaders(headers) {
|
|
4588
|
+
this.routing?.observe(headers.get("x-codex-turn-state"));
|
|
4589
|
+
const model = identifier(
|
|
4590
|
+
headers.get("openai-model") ?? headers.get("x-openai-model")
|
|
4591
|
+
);
|
|
4592
|
+
if (model) this.summary.server_model = model;
|
|
4593
|
+
this.fallbackModel = identifier(
|
|
4594
|
+
headers.get("x-codex-safety-buffering-faster-model")
|
|
4595
|
+
);
|
|
4596
|
+
}
|
|
4597
|
+
observeEvent(event) {
|
|
4598
|
+
const value = record2(event);
|
|
4599
|
+
if (!value) return;
|
|
4600
|
+
const response = record2(value.response);
|
|
4601
|
+
const model = identifier(
|
|
4602
|
+
headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
|
|
4603
|
+
);
|
|
4604
|
+
if (model) this.summary.server_model = model;
|
|
4605
|
+
const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
|
|
4606
|
+
if (value.type === "response.metadata")
|
|
4607
|
+
this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
|
|
4608
|
+
const verifications = metadata?.openai_verification_recommendation;
|
|
4609
|
+
if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
|
|
4610
|
+
this.summary.model_verifications = ["trusted_access_for_cyber"];
|
|
4611
|
+
if (!this.verificationNotified) {
|
|
4612
|
+
this.verificationNotified = true;
|
|
4613
|
+
this.emit({
|
|
4614
|
+
type: "llm.status",
|
|
4615
|
+
provider: "openai",
|
|
4616
|
+
kind: "verification",
|
|
4617
|
+
verification: "trusted_access_for_cyber"
|
|
4618
|
+
});
|
|
4619
|
+
}
|
|
4620
|
+
}
|
|
4621
|
+
if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
|
|
4622
|
+
this.summary.moderation_metadata_present = true;
|
|
4623
|
+
const buffering = record2(
|
|
4624
|
+
value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
|
|
4625
|
+
);
|
|
4626
|
+
if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
|
|
4627
|
+
const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
|
|
4628
|
+
const wasActive = this.summary.safety_buffering?.active;
|
|
4629
|
+
this.summary.safety_buffering = {
|
|
4630
|
+
active: !this.outputStarted,
|
|
4631
|
+
use_case_count: buffering.use_cases.length,
|
|
4632
|
+
reason_count: buffering.reasons.length,
|
|
4633
|
+
...faster ? { faster_model: faster } : {}
|
|
4634
|
+
};
|
|
4635
|
+
if (!this.outputStarted && !wasActive)
|
|
4636
|
+
this.emit({
|
|
4637
|
+
type: "llm.status",
|
|
4638
|
+
provider: "openai",
|
|
4639
|
+
kind: "buffering",
|
|
4640
|
+
active: true,
|
|
4641
|
+
...faster ? { faster_model: faster } : {}
|
|
4642
|
+
});
|
|
4643
|
+
}
|
|
4644
|
+
if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
|
|
4645
|
+
this.outputStarted = true;
|
|
4646
|
+
this.clearBuffering();
|
|
4647
|
+
}
|
|
4648
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
|
|
4649
|
+
this.clearBuffering();
|
|
4650
|
+
}
|
|
4651
|
+
finish() {
|
|
4652
|
+
this.clearBuffering();
|
|
4653
|
+
}
|
|
4654
|
+
snapshot() {
|
|
4655
|
+
return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
|
|
4656
|
+
}
|
|
4657
|
+
clearBuffering() {
|
|
4658
|
+
if (this.summary.safety_buffering?.active) {
|
|
4659
|
+
this.summary.safety_buffering.active = false;
|
|
4660
|
+
this.emit({
|
|
4661
|
+
type: "llm.status",
|
|
4662
|
+
provider: "openai",
|
|
4663
|
+
kind: "buffering",
|
|
4664
|
+
active: false
|
|
4665
|
+
});
|
|
4666
|
+
}
|
|
4667
|
+
}
|
|
4668
|
+
emit(event) {
|
|
4669
|
+
try {
|
|
4670
|
+
this.onStatus?.(event);
|
|
4671
|
+
} catch {
|
|
4672
|
+
}
|
|
4673
|
+
}
|
|
4674
|
+
};
|
|
4675
|
+
|
|
4676
|
+
// src/llm/openai/http-transport.ts
|
|
3732
4677
|
import OpenAI2 from "openai";
|
|
3733
4678
|
|
|
3734
4679
|
// src/llm/openai/response-utils.ts
|
|
3735
|
-
var
|
|
4680
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null;
|
|
3736
4681
|
var stringifyUnknown3 = (value) => {
|
|
3737
4682
|
if (value == null) return "";
|
|
3738
4683
|
if (typeof value === "string") return value;
|
|
@@ -3747,7 +4692,7 @@ var formatOtherPart2 = (part) => {
|
|
|
3747
4692
|
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
3748
4693
|
};
|
|
3749
4694
|
var isOpenAiInputContent = (value) => {
|
|
3750
|
-
if (!
|
|
4695
|
+
if (!isRecord3(value)) return false;
|
|
3751
4696
|
const type = value.type;
|
|
3752
4697
|
if (type === "input_text") {
|
|
3753
4698
|
return typeof value.text === "string";
|
|
@@ -3772,12 +4717,12 @@ var extractOutputText = (items) => {
|
|
|
3772
4717
|
}
|
|
3773
4718
|
return texts.join("");
|
|
3774
4719
|
};
|
|
3775
|
-
var getRecordString = (
|
|
3776
|
-
const value =
|
|
4720
|
+
var getRecordString = (record3, key) => {
|
|
4721
|
+
const value = record3[key];
|
|
3777
4722
|
return typeof value === "string" ? value : void 0;
|
|
3778
4723
|
};
|
|
3779
|
-
var getRecordNumber = (
|
|
3780
|
-
const value =
|
|
4724
|
+
var getRecordNumber = (record3, key) => {
|
|
4725
|
+
const value = record3[key];
|
|
3781
4726
|
return typeof value === "number" ? value : void 0;
|
|
3782
4727
|
};
|
|
3783
4728
|
var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
|
|
@@ -3787,6 +4732,10 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3787
4732
|
sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
|
|
3788
4733
|
};
|
|
3789
4734
|
const eventRecord = event;
|
|
4735
|
+
const metadata = new CodexMetadataCollector();
|
|
4736
|
+
metadata.observeEvent(event);
|
|
4737
|
+
const summary = metadata.snapshot();
|
|
4738
|
+
if (summary) payload.metadata_summary = summary;
|
|
3790
4739
|
const outputIndex = getRecordNumber(eventRecord, "output_index");
|
|
3791
4740
|
if (outputIndex !== void 0) {
|
|
3792
4741
|
payload.output_index = outputIndex;
|
|
@@ -3807,7 +4756,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3807
4756
|
case "response.output_item.added":
|
|
3808
4757
|
case "response.output_item.done": {
|
|
3809
4758
|
const item = eventRecord.item;
|
|
3810
|
-
if (
|
|
4759
|
+
if (isRecord3(item)) {
|
|
3811
4760
|
payload.item_type = getRecordString(item, "type");
|
|
3812
4761
|
payload.item_role = getRecordString(item, "role");
|
|
3813
4762
|
}
|
|
@@ -3815,7 +4764,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3815
4764
|
}
|
|
3816
4765
|
case "response.content_part.added": {
|
|
3817
4766
|
const part = eventRecord.part;
|
|
3818
|
-
if (
|
|
4767
|
+
if (isRecord3(part)) {
|
|
3819
4768
|
payload.part_type = getRecordString(part, "type");
|
|
3820
4769
|
if (part.type === "output_text") {
|
|
3821
4770
|
const text = getRecordString(part, "text") ?? "";
|
|
@@ -3827,7 +4776,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3827
4776
|
}
|
|
3828
4777
|
case "response.completed": {
|
|
3829
4778
|
const response = eventRecord.response;
|
|
3830
|
-
if (
|
|
4779
|
+
if (isRecord3(response)) {
|
|
3831
4780
|
payload.response_id = getRecordString(response, "id");
|
|
3832
4781
|
const status = response.status;
|
|
3833
4782
|
payload.response_status = typeof status === "string" ? status : null;
|
|
@@ -3838,13 +4787,13 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3838
4787
|
const outputText = response.output_text;
|
|
3839
4788
|
payload.response_output_text = typeof outputText === "string" ? clipDebugText(outputText) : null;
|
|
3840
4789
|
const usage = response.usage;
|
|
3841
|
-
if (
|
|
4790
|
+
if (isRecord3(usage)) {
|
|
3842
4791
|
payload.response_output_tokens = getRecordNumber(
|
|
3843
4792
|
usage,
|
|
3844
4793
|
"output_tokens"
|
|
3845
4794
|
);
|
|
3846
4795
|
const outputDetails = usage.output_tokens_details;
|
|
3847
|
-
if (
|
|
4796
|
+
if (isRecord3(outputDetails)) {
|
|
3848
4797
|
payload.response_reasoning_tokens = getRecordNumber(
|
|
3849
4798
|
outputDetails,
|
|
3850
4799
|
"reasoning_tokens"
|
|
@@ -3915,7 +4864,7 @@ var toFunctionCallOutput = (content) => {
|
|
|
3915
4864
|
};
|
|
3916
4865
|
|
|
3917
4866
|
// src/llm/openai/response-accumulator.ts
|
|
3918
|
-
var
|
|
4867
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
3919
4868
|
var envTruthy2 = (value) => {
|
|
3920
4869
|
if (!value) return false;
|
|
3921
4870
|
const normalized = value.trim().toLowerCase();
|
|
@@ -3940,6 +4889,9 @@ var OpenAiResponseAccumulator = class {
|
|
|
3940
4889
|
terminalResponse = null;
|
|
3941
4890
|
outputItems = [];
|
|
3942
4891
|
observeEvent(event) {
|
|
4892
|
+
const type = event.type;
|
|
4893
|
+
if (type === "response.metadata" || type === "codex.response.metadata")
|
|
4894
|
+
return;
|
|
3943
4895
|
switch (event.type) {
|
|
3944
4896
|
case "response.created":
|
|
3945
4897
|
case "response.queued":
|
|
@@ -4108,7 +5060,7 @@ var OpenAiResponseAccumulator = class {
|
|
|
4108
5060
|
}
|
|
4109
5061
|
addContentPart(outputIndex, contentIndex, part) {
|
|
4110
5062
|
const output = this.getOutputItem(outputIndex);
|
|
4111
|
-
if (!output || !
|
|
5063
|
+
if (!output || !isRecord4(part)) {
|
|
4112
5064
|
return;
|
|
4113
5065
|
}
|
|
4114
5066
|
if (output.type === "message" && part.type !== "reasoning_text") {
|
|
@@ -4291,22 +5243,64 @@ var OpenAiResponseAccumulator = class {
|
|
|
4291
5243
|
};
|
|
4292
5244
|
|
|
4293
5245
|
// src/llm/openai/http-transport.ts
|
|
4294
|
-
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
|
|
5246
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
|
|
4295
5247
|
const streamRequest = {
|
|
4296
5248
|
...request,
|
|
4297
5249
|
stream: true
|
|
4298
5250
|
};
|
|
4299
|
-
const
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
5251
|
+
const options = signal || sessionIdHeader ? {
|
|
5252
|
+
...signal ? { signal } : {},
|
|
5253
|
+
...sessionIdHeader ? {
|
|
5254
|
+
headers: {
|
|
5255
|
+
session_id: sessionIdHeader
|
|
5256
|
+
}
|
|
5257
|
+
} : {}
|
|
5258
|
+
} : void 0;
|
|
5259
|
+
if (isCodexBackend(client.baseURL)) {
|
|
5260
|
+
codex?.metadata.beginAttempt();
|
|
5261
|
+
const sourceFetch = client.fetch;
|
|
5262
|
+
let ownershipError;
|
|
5263
|
+
const requestClient = codex ? client.withOptions({
|
|
5264
|
+
fetch: async (input, init) => {
|
|
5265
|
+
const headers = new Headers(init?.headers);
|
|
5266
|
+
if (codex.routing?.bindAuth(headers)) {
|
|
5267
|
+
ownershipError = createProviderValidationError(
|
|
5268
|
+
"openai",
|
|
5269
|
+
"OpenAI authentication changed; start a new run"
|
|
5270
|
+
);
|
|
5271
|
+
throw ownershipError;
|
|
4306
5272
|
}
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
5273
|
+
for (const [key, value] of Object.entries(
|
|
5274
|
+
codex.routing?.requestHeaders() ?? {}
|
|
5275
|
+
))
|
|
5276
|
+
headers.set(key, value);
|
|
5277
|
+
const response = await sourceFetch(input, { ...init, headers });
|
|
5278
|
+
codex.metadata.observeHeaders(response.headers);
|
|
5279
|
+
return response;
|
|
5280
|
+
}
|
|
5281
|
+
}) : client;
|
|
5282
|
+
const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
|
|
5283
|
+
throw ownershipError ?? error;
|
|
5284
|
+
});
|
|
5285
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
5286
|
+
for await (const event of stream2) {
|
|
5287
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5288
|
+
codex?.metadata.observeEvent(event);
|
|
5289
|
+
await onEvent?.(event);
|
|
5290
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5291
|
+
if (event.type === "response.failed") {
|
|
5292
|
+
throw event.response.error ?? new Error("OpenAI stream failed");
|
|
5293
|
+
}
|
|
5294
|
+
if (event.type === "error") throw event;
|
|
5295
|
+
accumulator.observeEvent(event);
|
|
5296
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
5297
|
+
return accumulator.buildResponse(event.response);
|
|
5298
|
+
}
|
|
5299
|
+
}
|
|
5300
|
+
if (signal?.aborted) throw new OpenAI2.APIUserAbortError();
|
|
5301
|
+
throw new Error("OpenAI stream ended without a terminal response");
|
|
5302
|
+
}
|
|
5303
|
+
const stream = client.responses.stream(streamRequest, options);
|
|
4310
5304
|
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
4311
5305
|
const accumulator = new OpenAiResponseAccumulator();
|
|
4312
5306
|
for await (const event of stream) {
|
|
@@ -4357,12 +5351,12 @@ var formatOtherPart3 = (part) => {
|
|
|
4357
5351
|
};
|
|
4358
5352
|
var isOpenAIAssistantInputContent = (value) => {
|
|
4359
5353
|
if (!value || typeof value !== "object") return false;
|
|
4360
|
-
const
|
|
4361
|
-
if (
|
|
4362
|
-
return typeof
|
|
5354
|
+
const record3 = value;
|
|
5355
|
+
if (record3.type === "output_text") {
|
|
5356
|
+
return typeof record3.text === "string";
|
|
4363
5357
|
}
|
|
4364
|
-
if (
|
|
4365
|
-
return typeof
|
|
5358
|
+
if (record3.type === "refusal") {
|
|
5359
|
+
return typeof record3.refusal === "string";
|
|
4366
5360
|
}
|
|
4367
5361
|
return false;
|
|
4368
5362
|
};
|
|
@@ -4380,8 +5374,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
4380
5374
|
if (!value || typeof value !== "object") {
|
|
4381
5375
|
return false;
|
|
4382
5376
|
}
|
|
4383
|
-
const
|
|
4384
|
-
return
|
|
5377
|
+
const record3 = value;
|
|
5378
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
4385
5379
|
};
|
|
4386
5380
|
var toReplayableFunctionCallItemId = (value) => {
|
|
4387
5381
|
if (typeof value !== "string") {
|
|
@@ -4432,14 +5426,14 @@ var extractReasoningText = (item) => {
|
|
|
4432
5426
|
};
|
|
4433
5427
|
var extractWebSearchSummary = (item) => {
|
|
4434
5428
|
const parts = [`WebSearch status=${item.status}`];
|
|
4435
|
-
const
|
|
4436
|
-
const queries = Array.isArray(
|
|
5429
|
+
const record3 = item;
|
|
5430
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
4437
5431
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
4438
5432
|
) : [];
|
|
4439
5433
|
if (queries.length) {
|
|
4440
5434
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
4441
5435
|
}
|
|
4442
|
-
const sources = Array.isArray(
|
|
5436
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
4443
5437
|
if (sources.length) {
|
|
4444
5438
|
parts.push(`sources=${sources.length}`);
|
|
4445
5439
|
}
|
|
@@ -4610,6 +5604,9 @@ function toChatInvokeCompletion2(response, meta) {
|
|
|
4610
5604
|
input_tokens: response.usage.input_tokens,
|
|
4611
5605
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
4612
5606
|
output_tokens: response.usage.output_tokens,
|
|
5607
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
5608
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
5609
|
+
} : {},
|
|
4613
5610
|
total_tokens: response.usage.total_tokens
|
|
4614
5611
|
} : null;
|
|
4615
5612
|
const messages = toMessageSequence(response);
|
|
@@ -4715,6 +5712,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
|
4715
5712
|
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
4716
5713
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
4717
5714
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
5715
|
+
var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
|
|
5716
|
+
constructor() {
|
|
5717
|
+
super({
|
|
5718
|
+
...buildProviderFailure("openai", "validation"),
|
|
5719
|
+
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."
|
|
5720
|
+
});
|
|
5721
|
+
}
|
|
5722
|
+
};
|
|
4718
5723
|
var resolveTimeoutMs = (value, fallbackMs) => {
|
|
4719
5724
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
4720
5725
|
return fallbackMs;
|
|
@@ -4796,6 +5801,8 @@ var OpenAiWsTransport = class {
|
|
|
4796
5801
|
);
|
|
4797
5802
|
}
|
|
4798
5803
|
async invoke(args) {
|
|
5804
|
+
const timing = new LlmStreamTiming();
|
|
5805
|
+
args.codex?.metadata.beginAttempt();
|
|
4799
5806
|
await this.prepareClientForWsHandshake();
|
|
4800
5807
|
const wsOptionsHeaders = {
|
|
4801
5808
|
...this.getClientDefaultHeaders(),
|
|
@@ -4804,6 +5811,19 @@ var OpenAiWsTransport = class {
|
|
|
4804
5811
|
if (args.sessionIdHeader) {
|
|
4805
5812
|
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
4806
5813
|
}
|
|
5814
|
+
if (args.codex?.routing) {
|
|
5815
|
+
const authHeaders = new Headers(wsOptionsHeaders);
|
|
5816
|
+
authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
|
|
5817
|
+
if (args.codex.routing.bindAuth(authHeaders)) {
|
|
5818
|
+
if (args.ws)
|
|
5819
|
+
this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
|
|
5820
|
+
throw createProviderValidationError(
|
|
5821
|
+
"openai",
|
|
5822
|
+
"OpenAI authentication changed; start a new run"
|
|
5823
|
+
);
|
|
5824
|
+
}
|
|
5825
|
+
Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
|
|
5826
|
+
}
|
|
4807
5827
|
const wsOptions = { headers: wsOptionsHeaders };
|
|
4808
5828
|
const ownsWs = !args.ws;
|
|
4809
5829
|
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new ResponsesWS(
|
|
@@ -4814,6 +5834,15 @@ var OpenAiWsTransport = class {
|
|
|
4814
5834
|
ws.on("error", () => {
|
|
4815
5835
|
});
|
|
4816
5836
|
}
|
|
5837
|
+
const removeUpgrade = args.codex ? this.addNativeSocketListener(
|
|
5838
|
+
this.getNativeSocket(ws),
|
|
5839
|
+
"upgrade",
|
|
5840
|
+
(response) => {
|
|
5841
|
+
const headers = response?.headers;
|
|
5842
|
+
if (headers)
|
|
5843
|
+
args.codex?.metadata.observeHeaders(new Headers(headers));
|
|
5844
|
+
}
|
|
5845
|
+
) : void 0;
|
|
4817
5846
|
try {
|
|
4818
5847
|
await this.waitForWsOpen(ws, args.signal);
|
|
4819
5848
|
const closeWs = () => {
|
|
@@ -4822,11 +5851,14 @@ var OpenAiWsTransport = class {
|
|
|
4822
5851
|
const responseWaiter = this.createResponsePromise({
|
|
4823
5852
|
ws,
|
|
4824
5853
|
signal: args.signal,
|
|
4825
|
-
closeWs
|
|
5854
|
+
closeWs,
|
|
5855
|
+
timing,
|
|
5856
|
+
metadata: args.codex?.metadata
|
|
4826
5857
|
});
|
|
4827
5858
|
const responseCreateEvent = {
|
|
4828
5859
|
type: "response.create",
|
|
4829
|
-
...args.request
|
|
5860
|
+
...args.request,
|
|
5861
|
+
...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
|
|
4830
5862
|
};
|
|
4831
5863
|
if (!responseWaiter.isSettled()) {
|
|
4832
5864
|
try {
|
|
@@ -4836,12 +5868,14 @@ var OpenAiWsTransport = class {
|
|
|
4836
5868
|
}
|
|
4837
5869
|
}
|
|
4838
5870
|
const response = await responseWaiter.responsePromise;
|
|
4839
|
-
return { response, ws };
|
|
5871
|
+
return { response, ws, timing: timing.finish() };
|
|
4840
5872
|
} catch (error) {
|
|
4841
5873
|
if (ownsWs) {
|
|
4842
5874
|
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
4843
5875
|
}
|
|
4844
5876
|
throw error;
|
|
5877
|
+
} finally {
|
|
5878
|
+
removeUpgrade?.();
|
|
4845
5879
|
}
|
|
4846
5880
|
}
|
|
4847
5881
|
createResponsePromise(args) {
|
|
@@ -4931,6 +5965,7 @@ var OpenAiWsTransport = class {
|
|
|
4931
5965
|
rejectOnce(error);
|
|
4932
5966
|
};
|
|
4933
5967
|
const resolveFromTerminalEvent = (event, type) => {
|
|
5968
|
+
args.timing.complete();
|
|
4934
5969
|
const response = event?.response;
|
|
4935
5970
|
if (response && typeof response === "object") {
|
|
4936
5971
|
accumulator.observeTerminalResponse(response);
|
|
@@ -4953,6 +5988,9 @@ var OpenAiWsTransport = class {
|
|
|
4953
5988
|
);
|
|
4954
5989
|
};
|
|
4955
5990
|
const onEvent = (event) => {
|
|
5991
|
+
if (settled) return;
|
|
5992
|
+
args.metadata?.observeEvent(event);
|
|
5993
|
+
args.timing.observeResponsesEvent(event);
|
|
4956
5994
|
const eventType = this.extractResponsesEventType(event);
|
|
4957
5995
|
if (!eventType) {
|
|
4958
5996
|
return;
|
|
@@ -5001,7 +6039,7 @@ var OpenAiWsTransport = class {
|
|
|
5001
6039
|
const onClose = (event) => {
|
|
5002
6040
|
const closeCode = this.extractWsCloseCode(event);
|
|
5003
6041
|
rejectOnce(
|
|
5004
|
-
new Error(
|
|
6042
|
+
closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
|
|
5005
6043
|
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
5006
6044
|
)
|
|
5007
6045
|
);
|
|
@@ -5270,6 +6308,8 @@ var OpenAiWsTransport = class {
|
|
|
5270
6308
|
return void 0;
|
|
5271
6309
|
}
|
|
5272
6310
|
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
6311
|
+
if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
|
|
6312
|
+
return `${key}:[redacted]`;
|
|
5273
6313
|
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
5274
6314
|
return `${key}:${text}`;
|
|
5275
6315
|
});
|
|
@@ -5474,7 +6514,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
|
5474
6514
|
};
|
|
5475
6515
|
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
5476
6516
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
5477
|
-
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
5478
6517
|
var ChatOpenAI = class {
|
|
5479
6518
|
provider = PROVIDER_NAME5;
|
|
5480
6519
|
model;
|
|
@@ -5493,8 +6532,9 @@ var ChatOpenAI = class {
|
|
|
5493
6532
|
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
5494
6533
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
5495
6534
|
wsReconnectCount = 0;
|
|
6535
|
+
codexTurns = /* @__PURE__ */ new Map();
|
|
5496
6536
|
constructor(options = {}) {
|
|
5497
|
-
this.client = options.client ?? new
|
|
6537
|
+
this.client = options.client ?? new OpenAI3({
|
|
5498
6538
|
...options.clientOptions ?? {},
|
|
5499
6539
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5500
6540
|
});
|
|
@@ -5577,17 +6617,32 @@ var ChatOpenAI = class {
|
|
|
5577
6617
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
5578
6618
|
const requestMeta = {
|
|
5579
6619
|
model: String(request.model ?? this.providerModel),
|
|
5580
|
-
instructionsHash:
|
|
5581
|
-
toolsHash:
|
|
6620
|
+
instructionsHash: createHash5("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
6621
|
+
toolsHash: createHash5("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
5582
6622
|
};
|
|
5583
|
-
const
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
|
|
6623
|
+
const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
|
|
6624
|
+
let transportResult;
|
|
6625
|
+
try {
|
|
6626
|
+
transportResult = await this.invokeWithTransport({
|
|
6627
|
+
request,
|
|
6628
|
+
sessionKey: context?.sessionKey,
|
|
6629
|
+
sessionIdHeader,
|
|
6630
|
+
signal,
|
|
6631
|
+
debugSeq,
|
|
6632
|
+
requestMeta,
|
|
6633
|
+
...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
|
|
6634
|
+
});
|
|
6635
|
+
} finally {
|
|
6636
|
+
codex?.metadata?.finish();
|
|
6637
|
+
}
|
|
6638
|
+
const codexMetadata = codex?.metadata?.snapshot();
|
|
6639
|
+
if (codex) {
|
|
6640
|
+
const { headers: _headers, ...response } = transportResult.response;
|
|
6641
|
+
transportResult.response = {
|
|
6642
|
+
...response,
|
|
6643
|
+
...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
|
|
6644
|
+
};
|
|
6645
|
+
}
|
|
5591
6646
|
await this.debugResponseIfEnabled(
|
|
5592
6647
|
transportResult.response,
|
|
5593
6648
|
debugSeq,
|
|
@@ -5611,7 +6666,42 @@ var ChatOpenAI = class {
|
|
|
5611
6666
|
debugSeq,
|
|
5612
6667
|
transportResult.transport
|
|
5613
6668
|
);
|
|
5614
|
-
return
|
|
6669
|
+
return {
|
|
6670
|
+
...completion,
|
|
6671
|
+
...codexMetadata ? {
|
|
6672
|
+
provider_meta: {
|
|
6673
|
+
...completion.provider_meta,
|
|
6674
|
+
codex_metadata: codexMetadata
|
|
6675
|
+
}
|
|
6676
|
+
} : {},
|
|
6677
|
+
...transportResult.timing ? { timing: transportResult.timing } : {}
|
|
6678
|
+
};
|
|
6679
|
+
}
|
|
6680
|
+
createCodexMetadata(context) {
|
|
6681
|
+
const routing = this.resolveCodexTurn(context);
|
|
6682
|
+
return {
|
|
6683
|
+
routing,
|
|
6684
|
+
metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
|
|
6685
|
+
};
|
|
6686
|
+
}
|
|
6687
|
+
resolveCodexTurn(context) {
|
|
6688
|
+
if (!context?.turnKey) return void 0;
|
|
6689
|
+
const key = context.sessionKey ?? context.turnKey;
|
|
6690
|
+
let state = this.codexTurns.get(key);
|
|
6691
|
+
if (!state || state.turnKey !== context.turnKey) {
|
|
6692
|
+
this.clearWsSessionState(key, "new_turn");
|
|
6693
|
+
state = { turnKey: context.turnKey, routing: new CodexTurnState() };
|
|
6694
|
+
this.codexTurns.delete(key);
|
|
6695
|
+
this.codexTurns.set(key, state);
|
|
6696
|
+
if (this.codexTurns.size > 16) {
|
|
6697
|
+
const oldest = this.codexTurns.keys().next().value;
|
|
6698
|
+
if (oldest !== void 0) {
|
|
6699
|
+
this.codexTurns.delete(oldest);
|
|
6700
|
+
this.clearWsSessionState(oldest, "turn_state_evicted");
|
|
6701
|
+
}
|
|
6702
|
+
}
|
|
6703
|
+
}
|
|
6704
|
+
return state.routing;
|
|
5615
6705
|
}
|
|
5616
6706
|
onHistoryCompacted(context) {
|
|
5617
6707
|
const sessionKey = context?.sessionKey;
|
|
@@ -5629,6 +6719,7 @@ var ChatOpenAI = class {
|
|
|
5629
6719
|
this.evictIdleWsSessionState();
|
|
5630
6720
|
if (this.websocketMode === "off") {
|
|
5631
6721
|
return this.invokeHttpTransportWithDebug({
|
|
6722
|
+
codex: args.codex,
|
|
5632
6723
|
request: args.request,
|
|
5633
6724
|
debugSeq: args.debugSeq,
|
|
5634
6725
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5644,6 +6735,7 @@ var ChatOpenAI = class {
|
|
|
5644
6735
|
);
|
|
5645
6736
|
}
|
|
5646
6737
|
return this.invokeHttpTransportWithDebug({
|
|
6738
|
+
codex: args.codex,
|
|
5647
6739
|
request: args.request,
|
|
5648
6740
|
debugSeq: args.debugSeq,
|
|
5649
6741
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5654,6 +6746,7 @@ var ChatOpenAI = class {
|
|
|
5654
6746
|
}
|
|
5655
6747
|
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
5656
6748
|
return this.invokeHttpTransportWithDebug({
|
|
6749
|
+
codex: args.codex,
|
|
5657
6750
|
request: args.request,
|
|
5658
6751
|
debugSeq: args.debugSeq,
|
|
5659
6752
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5663,7 +6756,7 @@ var ChatOpenAI = class {
|
|
|
5663
6756
|
});
|
|
5664
6757
|
}
|
|
5665
6758
|
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
5666
|
-
const hasReusableWs = this.isWsConnectionReusable(wsState.ws)
|
|
6759
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
|
|
5667
6760
|
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
5668
6761
|
const incrementalInput = this.getIncrementalInput(
|
|
5669
6762
|
wsState.lastInput,
|
|
@@ -5711,7 +6804,8 @@ var ChatOpenAI = class {
|
|
|
5711
6804
|
wsExecutionPlan.chainReset,
|
|
5712
6805
|
wsExecutionPlan.wsInputMode
|
|
5713
6806
|
);
|
|
5714
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6807
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6808
|
+
codex: args.codex,
|
|
5715
6809
|
request: wsExecutionPlan.request,
|
|
5716
6810
|
signal: args.signal,
|
|
5717
6811
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5727,12 +6821,17 @@ var ChatOpenAI = class {
|
|
|
5727
6821
|
return {
|
|
5728
6822
|
response,
|
|
5729
6823
|
transport: "ws_mode",
|
|
6824
|
+
...timing ? { timing } : {},
|
|
5730
6825
|
fallbackUsed: false,
|
|
5731
6826
|
chainReset: wsExecutionPlan.chainReset,
|
|
5732
6827
|
wsInputMode: wsExecutionPlan.wsInputMode
|
|
5733
6828
|
};
|
|
5734
6829
|
} catch (error) {
|
|
5735
6830
|
let failure = error;
|
|
6831
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6832
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6833
|
+
throw failure;
|
|
6834
|
+
}
|
|
5736
6835
|
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
5737
6836
|
const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
|
|
5738
6837
|
this.closeWsWithoutMaskingPrimaryError(
|
|
@@ -5750,7 +6849,8 @@ var ChatOpenAI = class {
|
|
|
5750
6849
|
true,
|
|
5751
6850
|
retryWsInputMode
|
|
5752
6851
|
);
|
|
5753
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6852
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6853
|
+
codex: args.codex,
|
|
5754
6854
|
request: args.request,
|
|
5755
6855
|
signal: args.signal,
|
|
5756
6856
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5767,6 +6867,7 @@ var ChatOpenAI = class {
|
|
|
5767
6867
|
return {
|
|
5768
6868
|
response,
|
|
5769
6869
|
transport: "ws_mode",
|
|
6870
|
+
...timing ? { timing } : {},
|
|
5770
6871
|
fallbackUsed: false,
|
|
5771
6872
|
chainReset: true,
|
|
5772
6873
|
wsInputMode: retryWsInputMode
|
|
@@ -5775,9 +6876,13 @@ var ChatOpenAI = class {
|
|
|
5775
6876
|
failure = retryError;
|
|
5776
6877
|
}
|
|
5777
6878
|
}
|
|
6879
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6880
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6881
|
+
throw failure;
|
|
6882
|
+
}
|
|
5778
6883
|
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
5779
6884
|
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");
|
|
6885
|
+
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
6886
|
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
5782
6887
|
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
5783
6888
|
this.wsDisabledUntilBySessionKey.set(
|
|
@@ -5790,6 +6895,7 @@ var ChatOpenAI = class {
|
|
|
5790
6895
|
}
|
|
5791
6896
|
this.wsReconnectCount += 1;
|
|
5792
6897
|
return this.invokeHttpTransportWithDebug({
|
|
6898
|
+
codex: args.codex,
|
|
5793
6899
|
request: args.request,
|
|
5794
6900
|
debugSeq: args.debugSeq,
|
|
5795
6901
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5810,16 +6916,23 @@ var ChatOpenAI = class {
|
|
|
5810
6916
|
args.chainReset,
|
|
5811
6917
|
args.wsInputMode
|
|
5812
6918
|
);
|
|
6919
|
+
const timing = new LlmStreamTiming();
|
|
6920
|
+
const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
|
|
5813
6921
|
const response = await invokeOpenAiHttp(
|
|
5814
6922
|
this.client,
|
|
5815
6923
|
args.request,
|
|
5816
6924
|
args.signal,
|
|
5817
6925
|
args.sessionIdHeader,
|
|
5818
|
-
|
|
6926
|
+
(event) => {
|
|
6927
|
+
timing.observeResponsesEvent(event);
|
|
6928
|
+
return debugObserver?.(event);
|
|
6929
|
+
},
|
|
6930
|
+
args.codex
|
|
5819
6931
|
);
|
|
5820
6932
|
return {
|
|
5821
6933
|
response,
|
|
5822
6934
|
transport: "http_stream",
|
|
6935
|
+
timing: timing.finish(),
|
|
5823
6936
|
fallbackUsed: args.fallbackUsed,
|
|
5824
6937
|
chainReset: args.chainReset
|
|
5825
6938
|
};
|
|
@@ -5857,12 +6970,6 @@ var ChatOpenAI = class {
|
|
|
5857
6970
|
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
5858
6971
|
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
5859
6972
|
}
|
|
5860
|
-
isWsConnectionReuseExpired(lastUsedAt) {
|
|
5861
|
-
if (typeof lastUsedAt !== "number") {
|
|
5862
|
-
return false;
|
|
5863
|
-
}
|
|
5864
|
-
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
5865
|
-
}
|
|
5866
6973
|
isWsReconnectRetryableError(error) {
|
|
5867
6974
|
if (!(error instanceof Error)) {
|
|
5868
6975
|
return false;
|
|
@@ -5941,14 +7048,14 @@ var ChatOpenAI = class {
|
|
|
5941
7048
|
return;
|
|
5942
7049
|
}
|
|
5943
7050
|
const payload = safeJsonStringify(request);
|
|
5944
|
-
const hash =
|
|
5945
|
-
const toolsHash =
|
|
5946
|
-
const instructionsHash =
|
|
7051
|
+
const hash = createHash5("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7052
|
+
const toolsHash = createHash5("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7053
|
+
const instructionsHash = createHash5("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
5947
7054
|
const previous = this.lastDebugRequestPayload;
|
|
5948
7055
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5949
7056
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5950
7057
|
if (settings.enabled) {
|
|
5951
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
7058
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash5("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
5952
7059
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
5953
7060
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
5954
7061
|
console.error(
|
|
@@ -6041,11 +7148,11 @@ var ChatOpenAI = class {
|
|
|
6041
7148
|
};
|
|
6042
7149
|
|
|
6043
7150
|
// src/llm/openrouter/chat.ts
|
|
6044
|
-
import { createHash as
|
|
6045
|
-
import
|
|
7151
|
+
import { createHash as createHash6 } from "crypto";
|
|
7152
|
+
import OpenAI4 from "openai";
|
|
6046
7153
|
|
|
6047
7154
|
// src/llm/openrouter/response-utils.ts
|
|
6048
|
-
var
|
|
7155
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null;
|
|
6049
7156
|
var stringifyUnknown5 = (value) => {
|
|
6050
7157
|
if (value == null) return "";
|
|
6051
7158
|
if (typeof value === "string") return value;
|
|
@@ -6060,7 +7167,7 @@ var formatOtherPart4 = (part) => {
|
|
|
6060
7167
|
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
6061
7168
|
};
|
|
6062
7169
|
var isResponsesApiInputContent = (value) => {
|
|
6063
|
-
if (!
|
|
7170
|
+
if (!isRecord5(value)) return false;
|
|
6064
7171
|
const type = value.type;
|
|
6065
7172
|
if (type === "input_text") {
|
|
6066
7173
|
return typeof value.text === "string";
|
|
@@ -6162,12 +7269,12 @@ var formatOtherPart5 = (part) => {
|
|
|
6162
7269
|
};
|
|
6163
7270
|
var isOpenAIAssistantInputContent2 = (value) => {
|
|
6164
7271
|
if (!value || typeof value !== "object") return false;
|
|
6165
|
-
const
|
|
6166
|
-
if (
|
|
6167
|
-
return typeof
|
|
7272
|
+
const record3 = value;
|
|
7273
|
+
if (record3.type === "output_text") {
|
|
7274
|
+
return typeof record3.text === "string";
|
|
6168
7275
|
}
|
|
6169
|
-
if (
|
|
6170
|
-
return typeof
|
|
7276
|
+
if (record3.type === "refusal") {
|
|
7277
|
+
return typeof record3.refusal === "string";
|
|
6171
7278
|
}
|
|
6172
7279
|
return false;
|
|
6173
7280
|
};
|
|
@@ -6175,8 +7282,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
|
6175
7282
|
if (!value || typeof value !== "object") {
|
|
6176
7283
|
return false;
|
|
6177
7284
|
}
|
|
6178
|
-
const
|
|
6179
|
-
return
|
|
7285
|
+
const record3 = value;
|
|
7286
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
6180
7287
|
};
|
|
6181
7288
|
var toReplayableFunctionCallItemId2 = (value) => {
|
|
6182
7289
|
if (typeof value !== "string") {
|
|
@@ -6227,14 +7334,14 @@ var extractReasoningText2 = (item) => {
|
|
|
6227
7334
|
};
|
|
6228
7335
|
var extractWebSearchSummary2 = (item) => {
|
|
6229
7336
|
const parts = [`WebSearch status=${item.status}`];
|
|
6230
|
-
const
|
|
6231
|
-
const queries = Array.isArray(
|
|
7337
|
+
const record3 = item;
|
|
7338
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
6232
7339
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
6233
7340
|
) : [];
|
|
6234
7341
|
if (queries.length) {
|
|
6235
7342
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
6236
7343
|
}
|
|
6237
|
-
const sources = Array.isArray(
|
|
7344
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
6238
7345
|
if (sources.length) {
|
|
6239
7346
|
parts.push(`sources=${sources.length}`);
|
|
6240
7347
|
}
|
|
@@ -6401,6 +7508,9 @@ function toChatInvokeCompletion3(response, meta) {
|
|
|
6401
7508
|
input_tokens: response.usage.input_tokens,
|
|
6402
7509
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
6403
7510
|
output_tokens: response.usage.output_tokens,
|
|
7511
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
7512
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
7513
|
+
} : {},
|
|
6404
7514
|
total_tokens: response.usage.total_tokens
|
|
6405
7515
|
} : null;
|
|
6406
7516
|
const messages = toMessageSequence2(response);
|
|
@@ -6510,7 +7620,7 @@ var ChatOpenRouter = class {
|
|
|
6510
7620
|
debugInvokeSeq = 0;
|
|
6511
7621
|
lastDebugRequestPayload = null;
|
|
6512
7622
|
constructor(options = {}) {
|
|
6513
|
-
this.client = options.client ?? new
|
|
7623
|
+
this.client = options.client ?? new OpenAI4({
|
|
6514
7624
|
baseURL: OPENROUTER_BASE_URL,
|
|
6515
7625
|
...options.clientOptions ?? {},
|
|
6516
7626
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
@@ -6582,7 +7692,8 @@ var ChatOpenRouter = class {
|
|
|
6582
7692
|
...request,
|
|
6583
7693
|
stream: true
|
|
6584
7694
|
};
|
|
6585
|
-
const
|
|
7695
|
+
const timing = new LlmStreamTiming();
|
|
7696
|
+
const stream = this.client.responses.stream(
|
|
6586
7697
|
streamRequest,
|
|
6587
7698
|
signal || sessionIdHeader ? {
|
|
6588
7699
|
...signal ? { signal } : {},
|
|
@@ -6592,13 +7703,21 @@ var ChatOpenRouter = class {
|
|
|
6592
7703
|
}
|
|
6593
7704
|
} : {}
|
|
6594
7705
|
} : void 0
|
|
6595
|
-
)
|
|
7706
|
+
);
|
|
7707
|
+
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
7708
|
+
for await (const event of stream) timing.observeResponsesEvent(event);
|
|
7709
|
+
}
|
|
7710
|
+
const response = await stream.finalResponse();
|
|
7711
|
+
const measuredTiming = timing.finish();
|
|
6596
7712
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6597
|
-
return
|
|
6598
|
-
|
|
6599
|
-
|
|
6600
|
-
|
|
6601
|
-
|
|
7713
|
+
return {
|
|
7714
|
+
...toChatInvokeCompletion3(response, {
|
|
7715
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7716
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7717
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7718
|
+
}),
|
|
7719
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7720
|
+
};
|
|
6602
7721
|
}
|
|
6603
7722
|
nextDebugInvokeSeq() {
|
|
6604
7723
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -6611,14 +7730,14 @@ var ChatOpenRouter = class {
|
|
|
6611
7730
|
return;
|
|
6612
7731
|
}
|
|
6613
7732
|
const payload = safeJsonStringify(request);
|
|
6614
|
-
const hash =
|
|
6615
|
-
const toolsHash =
|
|
6616
|
-
const instructionsHash =
|
|
7733
|
+
const hash = createHash6("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7734
|
+
const toolsHash = createHash6("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7735
|
+
const instructionsHash = createHash6("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6617
7736
|
const previous = this.lastDebugRequestPayload;
|
|
6618
7737
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6619
7738
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6620
7739
|
if (settings.enabled) {
|
|
6621
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${
|
|
7740
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash6("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6622
7741
|
console.error(
|
|
6623
7742
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
6624
7743
|
);
|
|
@@ -6682,8 +7801,8 @@ var ChatOpenRouter = class {
|
|
|
6682
7801
|
};
|
|
6683
7802
|
|
|
6684
7803
|
// src/llm/xai/chat.ts
|
|
6685
|
-
import { createHash as
|
|
6686
|
-
import
|
|
7804
|
+
import { createHash as createHash7 } from "crypto";
|
|
7805
|
+
import OpenAI5 from "openai";
|
|
6687
7806
|
|
|
6688
7807
|
// src/llm/xai/serializer.ts
|
|
6689
7808
|
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -6906,7 +8025,7 @@ var ChatXai = class {
|
|
|
6906
8025
|
debugInvokeSeq = 0;
|
|
6907
8026
|
lastDebugRequestPayload = null;
|
|
6908
8027
|
constructor(options = {}) {
|
|
6909
|
-
this.client = options.client ?? new
|
|
8028
|
+
this.client = options.client ?? new OpenAI5({
|
|
6910
8029
|
baseURL: XAI_BASE_URL,
|
|
6911
8030
|
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6912
8031
|
...options.clientOptions ?? {},
|
|
@@ -6959,13 +8078,24 @@ var ChatXai = class {
|
|
|
6959
8078
|
}
|
|
6960
8079
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
6961
8080
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6962
|
-
const
|
|
8081
|
+
const timing = new LlmStreamTiming();
|
|
8082
|
+
const response = await invokeOpenAiHttp(
|
|
8083
|
+
this.client,
|
|
8084
|
+
request,
|
|
8085
|
+
signal,
|
|
8086
|
+
void 0,
|
|
8087
|
+
(event) => timing.observeResponsesEvent(event)
|
|
8088
|
+
);
|
|
8089
|
+
const measuredTiming = timing.finish();
|
|
6963
8090
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6964
|
-
return
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
6968
|
-
|
|
8091
|
+
return {
|
|
8092
|
+
...toXaiChatInvokeCompletion(response, {
|
|
8093
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8094
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8095
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8096
|
+
}),
|
|
8097
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
8098
|
+
};
|
|
6969
8099
|
}
|
|
6970
8100
|
nextDebugInvokeSeq() {
|
|
6971
8101
|
this.debugInvokeSeq += 1;
|
|
@@ -6975,7 +8105,7 @@ var ChatXai = class {
|
|
|
6975
8105
|
const settings = getProviderLogSettings();
|
|
6976
8106
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
6977
8107
|
const payload = safeJsonStringify(request);
|
|
6978
|
-
const hash =
|
|
8108
|
+
const hash = createHash7("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6979
8109
|
const previous = this.lastDebugRequestPayload;
|
|
6980
8110
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6981
8111
|
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7032,15 +8162,15 @@ var ChatXai = class {
|
|
|
7032
8162
|
};
|
|
7033
8163
|
|
|
7034
8164
|
// src/llm/zai/chat.ts
|
|
7035
|
-
import { createHash as
|
|
8165
|
+
import { createHash as createHash8 } from "crypto";
|
|
7036
8166
|
|
|
7037
8167
|
// src/llm/zai/failure.ts
|
|
7038
8168
|
var PROVIDER_NAME8 = "zai";
|
|
7039
8169
|
var readBusinessCode = (error) => {
|
|
7040
|
-
const
|
|
7041
|
-
const body = asRecord(
|
|
8170
|
+
const record3 = asRecord(error);
|
|
8171
|
+
const body = asRecord(record3?.body);
|
|
7042
8172
|
const nested = asRecord(body?.error) ?? body;
|
|
7043
|
-
const raw = nested?.code ??
|
|
8173
|
+
const raw = nested?.code ?? record3?.code;
|
|
7044
8174
|
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7045
8175
|
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7046
8176
|
};
|
|
@@ -7344,6 +8474,7 @@ var streamZaiChatCompletion = async ({
|
|
|
7344
8474
|
timeoutMs,
|
|
7345
8475
|
captureRawChunks
|
|
7346
8476
|
}) => {
|
|
8477
|
+
const timing = new LlmStreamTiming();
|
|
7347
8478
|
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
7348
8479
|
try {
|
|
7349
8480
|
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
@@ -7365,9 +8496,11 @@ var streamZaiChatCompletion = async ({
|
|
|
7365
8496
|
response,
|
|
7366
8497
|
requestSignal.signal
|
|
7367
8498
|
)) {
|
|
8499
|
+
timing.observeChatChunk(chunk);
|
|
7368
8500
|
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
7369
8501
|
}
|
|
7370
8502
|
return {
|
|
8503
|
+
timing: timing.finish(),
|
|
7371
8504
|
status: response.status,
|
|
7372
8505
|
request_id: response.headers.get("x-request-id"),
|
|
7373
8506
|
accumulated
|
|
@@ -7562,13 +8695,16 @@ var ChatZai = class {
|
|
|
7562
8695
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7563
8696
|
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
7564
8697
|
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
7565
|
-
return
|
|
7566
|
-
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7570
|
-
|
|
7571
|
-
|
|
8698
|
+
return {
|
|
8699
|
+
...toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
8700
|
+
request_id: terminal.request_id ?? null,
|
|
8701
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8702
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8703
|
+
reasoning_effort: request.reasoning_effort,
|
|
8704
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8705
|
+
}),
|
|
8706
|
+
...terminal.timing ? { timing: terminal.timing } : {}
|
|
8707
|
+
};
|
|
7572
8708
|
}
|
|
7573
8709
|
async streamRequest(apiKey, request, signal) {
|
|
7574
8710
|
const logSettings = getProviderLogSettings();
|
|
@@ -7593,8 +8729,8 @@ var ChatZai = class {
|
|
|
7593
8729
|
return;
|
|
7594
8730
|
}
|
|
7595
8731
|
const payload = safeJsonStringify(request);
|
|
7596
|
-
const hash =
|
|
7597
|
-
const toolsHash =
|
|
8732
|
+
const hash = createHash8("sha256").update(payload).digest("hex").slice(0, 16);
|
|
8733
|
+
const toolsHash = createHash8("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7598
8734
|
const previous = this.lastDebugRequestPayload;
|
|
7599
8735
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7600
8736
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7725,6 +8861,160 @@ function defineTool(toolOptions) {
|
|
|
7725
8861
|
}
|
|
7726
8862
|
};
|
|
7727
8863
|
}
|
|
8864
|
+
|
|
8865
|
+
// src/llm/responses/chat.ts
|
|
8866
|
+
import OpenAI6 from "openai";
|
|
8867
|
+
var ChatResponses = class {
|
|
8868
|
+
provider;
|
|
8869
|
+
model;
|
|
8870
|
+
retryPolicy;
|
|
8871
|
+
client;
|
|
8872
|
+
endpoint;
|
|
8873
|
+
reasoningEffort;
|
|
8874
|
+
textVerbosity;
|
|
8875
|
+
constructor(options) {
|
|
8876
|
+
this.provider = options.provider;
|
|
8877
|
+
this.model = options.model;
|
|
8878
|
+
this.endpoint = options.endpoint;
|
|
8879
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
8880
|
+
this.textVerbosity = options.textVerbosity;
|
|
8881
|
+
const retry = options.endpoint.retry;
|
|
8882
|
+
this.retryPolicy = {
|
|
8883
|
+
maxRetries: typeof retry === "object" ? retry.max_retries : 0,
|
|
8884
|
+
...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
|
|
8885
|
+
};
|
|
8886
|
+
this.client = new OpenAI6({
|
|
8887
|
+
apiKey: options.apiKey,
|
|
8888
|
+
baseURL: options.endpoint.base_url,
|
|
8889
|
+
organization: null,
|
|
8890
|
+
project: null,
|
|
8891
|
+
maxRetries: 0,
|
|
8892
|
+
timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
|
|
8893
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
8894
|
+
});
|
|
8895
|
+
}
|
|
8896
|
+
classifyFailure = (error) => {
|
|
8897
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
8898
|
+
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", {
|
|
8899
|
+
retryable: true
|
|
8900
|
+
}) : classifyOpenAiCompatibleFailure(this.provider, error);
|
|
8901
|
+
const extracted = extractProviderError(error);
|
|
8902
|
+
const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
|
|
8903
|
+
return {
|
|
8904
|
+
...failure,
|
|
8905
|
+
...extracted.status !== void 0 ? { status: extracted.status } : {},
|
|
8906
|
+
...extracted.status === 413 ? { kind: "validation" } : {},
|
|
8907
|
+
retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
|
|
8908
|
+
...code ? { code } : {},
|
|
8909
|
+
safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
|
|
8910
|
+
};
|
|
8911
|
+
};
|
|
8912
|
+
async ainvoke(input, context) {
|
|
8913
|
+
const model = input.model ?? this.model;
|
|
8914
|
+
const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
|
|
8915
|
+
const invalid = (message) => {
|
|
8916
|
+
throw createProviderValidationError(this.provider, message);
|
|
8917
|
+
};
|
|
8918
|
+
if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
|
|
8919
|
+
if (input.tools?.some((tool) => tool.type === "hosted_search"))
|
|
8920
|
+
invalid(
|
|
8921
|
+
`${this.provider} supports function tools only; hosted tools are unavailable`
|
|
8922
|
+
);
|
|
8923
|
+
if (input.tools?.length && !spec.supports_tools)
|
|
8924
|
+
invalid(`${this.provider}/${model} does not support tools`);
|
|
8925
|
+
const items = toResponsesInput(input.messages);
|
|
8926
|
+
if (!spec.supports_vision && Array.isArray(items) && items.some((item) => {
|
|
8927
|
+
const parts = item.type === "function_call_output" ? item.output : "content" in item ? item.content : void 0;
|
|
8928
|
+
return Array.isArray(parts) && parts.some((part) => part.type === "input_image");
|
|
8929
|
+
}))
|
|
8930
|
+
invalid(`${this.provider}/${model} vision is disabled`);
|
|
8931
|
+
const text = input.options?.text;
|
|
8932
|
+
if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
|
|
8933
|
+
invalid(`${this.provider}/${model} does not support structured output`);
|
|
8934
|
+
const features = this.endpoint.features;
|
|
8935
|
+
const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
|
|
8936
|
+
if (effort && !spec.supports_reasoning)
|
|
8937
|
+
invalid(`${this.provider}/${model} reasoning is disabled`);
|
|
8938
|
+
const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
|
|
8939
|
+
if (effort && !levels.includes(effort))
|
|
8940
|
+
invalid(
|
|
8941
|
+
`Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
|
|
8942
|
+
);
|
|
8943
|
+
const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
|
|
8944
|
+
if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
|
|
8945
|
+
invalid(`Invalid max output tokens for ${this.provider}/${model}`);
|
|
8946
|
+
const tools = toResponsesTools(input.tools);
|
|
8947
|
+
const choice = toResponsesToolChoice(input.toolChoice);
|
|
8948
|
+
const instructions = extractInstructions(input.messages);
|
|
8949
|
+
const request = {
|
|
8950
|
+
model,
|
|
8951
|
+
input: items,
|
|
8952
|
+
store: false,
|
|
8953
|
+
...instructions ? { instructions } : {},
|
|
8954
|
+
...tools ? { tools } : {},
|
|
8955
|
+
...choice ? { tool_choice: choice } : {},
|
|
8956
|
+
...output !== void 0 ? { max_output_tokens: output } : {}
|
|
8957
|
+
};
|
|
8958
|
+
if (spec.supports_reasoning && (effort || features?.reasoning_summary))
|
|
8959
|
+
request.reasoning = {
|
|
8960
|
+
...effort ? { effort: toSdkReasoningEffort(effort) } : {},
|
|
8961
|
+
...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
|
|
8962
|
+
};
|
|
8963
|
+
if (spec.supports_reasoning && features?.encrypted_reasoning)
|
|
8964
|
+
request.include = ["reasoning.encrypted_content"];
|
|
8965
|
+
if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
|
|
8966
|
+
request.text = {
|
|
8967
|
+
...text?.format ? { format: text.format } : {},
|
|
8968
|
+
...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
|
|
8969
|
+
};
|
|
8970
|
+
if (features?.prompt_cache_key && context?.sessionKey)
|
|
8971
|
+
request.prompt_cache_key = context.sessionKey;
|
|
8972
|
+
const timing = new LlmStreamTiming();
|
|
8973
|
+
let streamStarted = false;
|
|
8974
|
+
try {
|
|
8975
|
+
const stream = await this.client.responses.create(
|
|
8976
|
+
{ ...request, stream: true },
|
|
8977
|
+
{
|
|
8978
|
+
...input.signal ? { signal: input.signal } : {},
|
|
8979
|
+
...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
|
|
8980
|
+
}
|
|
8981
|
+
);
|
|
8982
|
+
streamStarted = true;
|
|
8983
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
8984
|
+
let terminal;
|
|
8985
|
+
for await (const event of stream) {
|
|
8986
|
+
timing.observeResponsesEvent(event);
|
|
8987
|
+
if (event.type === "error") throw { error: event };
|
|
8988
|
+
if (event.type === "response.failed")
|
|
8989
|
+
throw { error: event.response.error };
|
|
8990
|
+
accumulator.observeEvent(event);
|
|
8991
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
8992
|
+
terminal = event.response;
|
|
8993
|
+
break;
|
|
8994
|
+
}
|
|
8995
|
+
}
|
|
8996
|
+
if (!terminal)
|
|
8997
|
+
throw new Error("Responses stream ended before a terminal event");
|
|
8998
|
+
const measuredTiming = timing.finish();
|
|
8999
|
+
return {
|
|
9000
|
+
...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
|
|
9001
|
+
transport: "http_stream"
|
|
9002
|
+
}),
|
|
9003
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
9004
|
+
};
|
|
9005
|
+
} catch (error) {
|
|
9006
|
+
if (isProviderFailureError(error)) throw error;
|
|
9007
|
+
const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
|
|
9008
|
+
throw new ProviderFailureError(
|
|
9009
|
+
{
|
|
9010
|
+
...failure,
|
|
9011
|
+
...streamStarted ? { retryable: false, delivery: "buffered" } : {}
|
|
9012
|
+
},
|
|
9013
|
+
{ cause: error }
|
|
9014
|
+
);
|
|
9015
|
+
}
|
|
9016
|
+
}
|
|
9017
|
+
};
|
|
7728
9018
|
export {
|
|
7729
9019
|
ANTHROPIC_DEFAULT_MODEL,
|
|
7730
9020
|
ANTHROPIC_MODELS,
|
|
@@ -7733,11 +9023,13 @@ export {
|
|
|
7733
9023
|
ChatMoonshot,
|
|
7734
9024
|
ChatOpenAI,
|
|
7735
9025
|
ChatOpenRouter,
|
|
9026
|
+
ChatResponses,
|
|
7736
9027
|
ChatXai,
|
|
7737
9028
|
ChatZai,
|
|
7738
9029
|
DEFAULT_MODEL_REGISTRY,
|
|
7739
9030
|
GOOGLE_MODELS,
|
|
7740
9031
|
MOONSHOT_DEFAULT_MODEL,
|
|
9032
|
+
MOONSHOT_K3_1_MODELS,
|
|
7741
9033
|
MOONSHOT_MODELS,
|
|
7742
9034
|
OPENAI_DEFAULT_MODEL,
|
|
7743
9035
|
OPENAI_DEFAULT_REASONING_EFFORT,
|