@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.cjs
CHANGED
|
@@ -37,11 +37,13 @@ __export(index_exports, {
|
|
|
37
37
|
ChatMoonshot: () => ChatMoonshot,
|
|
38
38
|
ChatOpenAI: () => ChatOpenAI,
|
|
39
39
|
ChatOpenRouter: () => ChatOpenRouter,
|
|
40
|
+
ChatResponses: () => ChatResponses,
|
|
40
41
|
ChatXai: () => ChatXai,
|
|
41
42
|
ChatZai: () => ChatZai,
|
|
42
43
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
43
44
|
GOOGLE_MODELS: () => GOOGLE_MODELS,
|
|
44
45
|
MOONSHOT_DEFAULT_MODEL: () => MOONSHOT_DEFAULT_MODEL,
|
|
46
|
+
MOONSHOT_K3_1_MODELS: () => MOONSHOT_K3_1_MODELS,
|
|
45
47
|
MOONSHOT_MODELS: () => MOONSHOT_MODELS,
|
|
46
48
|
OPENAI_DEFAULT_MODEL: () => OPENAI_DEFAULT_MODEL,
|
|
47
49
|
OPENAI_DEFAULT_REASONING_EFFORT: () => OPENAI_DEFAULT_REASONING_EFFORT,
|
|
@@ -97,6 +99,22 @@ var buildGpt56Model = (id) => ({
|
|
|
97
99
|
supportsFast: true
|
|
98
100
|
});
|
|
99
101
|
var OPENAI_MODELS = [
|
|
102
|
+
{
|
|
103
|
+
id: "gpt-6.1-terra",
|
|
104
|
+
provider: "openai",
|
|
105
|
+
contextWindow: 105e4,
|
|
106
|
+
maxInputTokens: 27e4,
|
|
107
|
+
maxOutputTokens: 128e3,
|
|
108
|
+
supportsFast: true
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
id: "gpt-6.1-sol",
|
|
112
|
+
provider: "openai",
|
|
113
|
+
contextWindow: 105e4,
|
|
114
|
+
maxInputTokens: 27e4,
|
|
115
|
+
maxOutputTokens: 128e3,
|
|
116
|
+
supportsFast: true
|
|
117
|
+
},
|
|
100
118
|
{
|
|
101
119
|
id: "gpt-6-astra",
|
|
102
120
|
provider: "openai",
|
|
@@ -105,6 +123,22 @@ var OPENAI_MODELS = [
|
|
|
105
123
|
maxOutputTokens: 128e3,
|
|
106
124
|
supportsFast: true
|
|
107
125
|
},
|
|
126
|
+
{
|
|
127
|
+
id: "gpt-6-sol",
|
|
128
|
+
provider: "openai",
|
|
129
|
+
contextWindow: 105e4,
|
|
130
|
+
maxInputTokens: 27e4,
|
|
131
|
+
maxOutputTokens: 128e3,
|
|
132
|
+
supportsFast: true
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
id: "gpt-6-luna",
|
|
136
|
+
provider: "openai",
|
|
137
|
+
contextWindow: 105e4,
|
|
138
|
+
maxInputTokens: 27e4,
|
|
139
|
+
maxOutputTokens: 128e3,
|
|
140
|
+
supportsFast: true
|
|
141
|
+
},
|
|
108
142
|
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
109
143
|
{
|
|
110
144
|
id: "gpt-5.5",
|
|
@@ -283,6 +317,47 @@ import_config.configRegistry.registerDefaults({
|
|
|
283
317
|
|
|
284
318
|
// src/agent/agent.ts
|
|
285
319
|
var import_node_perf_hooks = require("perf_hooks");
|
|
320
|
+
var import_node_crypto = require("crypto");
|
|
321
|
+
|
|
322
|
+
// src/llm/provider-status.ts
|
|
323
|
+
async function* withProviderStatus(operation, signal) {
|
|
324
|
+
const controller = new AbortController();
|
|
325
|
+
const abort = () => controller.abort(signal?.reason);
|
|
326
|
+
if (signal?.aborted) abort();
|
|
327
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
328
|
+
const queue = [];
|
|
329
|
+
let wake;
|
|
330
|
+
let closed = false;
|
|
331
|
+
const iterator = operation((event) => {
|
|
332
|
+
if (closed || controller.signal.aborted) return;
|
|
333
|
+
if (queue.length < 32) queue.push(event);
|
|
334
|
+
wake?.();
|
|
335
|
+
}, controller.signal);
|
|
336
|
+
let pending = iterator.next();
|
|
337
|
+
try {
|
|
338
|
+
while (true) {
|
|
339
|
+
while (queue.length) yield queue.shift();
|
|
340
|
+
const changed = new Promise((resolve) => {
|
|
341
|
+
wake = () => resolve(void 0);
|
|
342
|
+
});
|
|
343
|
+
const result = await Promise.race([pending, changed]);
|
|
344
|
+
wake = void 0;
|
|
345
|
+
if (!result) continue;
|
|
346
|
+
while (queue.length) yield queue.shift();
|
|
347
|
+
if (result.done) return result.value;
|
|
348
|
+
yield result.value;
|
|
349
|
+
pending = iterator.next();
|
|
350
|
+
}
|
|
351
|
+
} finally {
|
|
352
|
+
closed = true;
|
|
353
|
+
controller.abort();
|
|
354
|
+
signal?.removeEventListener("abort", abort);
|
|
355
|
+
void pending.catch(() => {
|
|
356
|
+
});
|
|
357
|
+
void iterator.return(void 0).catch(() => {
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
286
361
|
|
|
287
362
|
// src/content/stringify.ts
|
|
288
363
|
var stringifyUnknown = (value) => {
|
|
@@ -296,6 +371,9 @@ var stringifyPart = (part, options) => {
|
|
|
296
371
|
if (part.type === "text") {
|
|
297
372
|
return part.text;
|
|
298
373
|
}
|
|
374
|
+
if (part.type === "image_ref") {
|
|
375
|
+
return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
|
|
376
|
+
}
|
|
299
377
|
if (part.type === "image_url") {
|
|
300
378
|
if (options.mode === "log") {
|
|
301
379
|
return `[image:${part.image_url.media_type ?? "unknown"}]`;
|
|
@@ -396,8 +474,8 @@ var ProviderTimeoutError = class extends Error {
|
|
|
396
474
|
};
|
|
397
475
|
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
398
476
|
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
399
|
-
var readString = (
|
|
400
|
-
const value =
|
|
477
|
+
var readString = (record3, key) => {
|
|
478
|
+
const value = record3?.[key];
|
|
401
479
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
402
480
|
};
|
|
403
481
|
var readStatus = (error) => {
|
|
@@ -408,9 +486,9 @@ var readHeader = (headers, name) => {
|
|
|
408
486
|
if (headers instanceof Headers) {
|
|
409
487
|
return headers.get(name);
|
|
410
488
|
}
|
|
411
|
-
const
|
|
412
|
-
if (!
|
|
413
|
-
const direct =
|
|
489
|
+
const record3 = asRecord(headers);
|
|
490
|
+
if (!record3) return null;
|
|
491
|
+
const direct = record3[name] ?? record3[name.toLowerCase()];
|
|
414
492
|
return typeof direct === "string" ? direct : null;
|
|
415
493
|
};
|
|
416
494
|
var parsePositiveNumber = (value) => {
|
|
@@ -466,7 +544,7 @@ var PROVIDER_LABELS = {
|
|
|
466
544
|
xai: "xAI"
|
|
467
545
|
};
|
|
468
546
|
var safeProviderMessage = (provider, kind) => {
|
|
469
|
-
const label = PROVIDER_LABELS[provider];
|
|
547
|
+
const label = PROVIDER_LABELS[provider] ?? provider;
|
|
470
548
|
switch (kind) {
|
|
471
549
|
case "hard_quota":
|
|
472
550
|
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
@@ -806,6 +884,42 @@ var ANTHROPIC_MODELS = [
|
|
|
806
884
|
provider: "anthropic",
|
|
807
885
|
aliases: ["default"]
|
|
808
886
|
},
|
|
887
|
+
{
|
|
888
|
+
id: "claude-sonnet-5-5",
|
|
889
|
+
provider: "anthropic",
|
|
890
|
+
contextWindow: 1e6,
|
|
891
|
+
maxInputTokens: 1e6,
|
|
892
|
+
maxOutputTokens: 128e3
|
|
893
|
+
},
|
|
894
|
+
{
|
|
895
|
+
id: "claude-haiku-5-5",
|
|
896
|
+
provider: "anthropic",
|
|
897
|
+
contextWindow: 1e6,
|
|
898
|
+
maxInputTokens: 1e6,
|
|
899
|
+
maxOutputTokens: 128e3
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
id: "claude-fable-5-1",
|
|
903
|
+
provider: "anthropic",
|
|
904
|
+
contextWindow: 1e6,
|
|
905
|
+
maxInputTokens: 1e6,
|
|
906
|
+
maxOutputTokens: 128e3
|
|
907
|
+
},
|
|
908
|
+
{
|
|
909
|
+
id: "claude-opus-5-5",
|
|
910
|
+
provider: "anthropic",
|
|
911
|
+
contextWindow: 1e6,
|
|
912
|
+
maxInputTokens: 1e6,
|
|
913
|
+
maxOutputTokens: 128e3,
|
|
914
|
+
supportsFast: true
|
|
915
|
+
},
|
|
916
|
+
{
|
|
917
|
+
id: "claude-sonnet-5",
|
|
918
|
+
provider: "anthropic",
|
|
919
|
+
contextWindow: 1e6,
|
|
920
|
+
maxInputTokens: 1e6,
|
|
921
|
+
maxOutputTokens: 128e3
|
|
922
|
+
},
|
|
809
923
|
{
|
|
810
924
|
id: "claude-fable-5",
|
|
811
925
|
provider: "anthropic",
|
|
@@ -835,12 +949,12 @@ var ANTHROPIC_MODELS = [
|
|
|
835
949
|
contextWindow: 1e6,
|
|
836
950
|
maxInputTokens: 1e6,
|
|
837
951
|
maxOutputTokens: 128e3,
|
|
838
|
-
supportsFast:
|
|
952
|
+
supportsFast: false
|
|
839
953
|
},
|
|
840
954
|
{
|
|
841
955
|
id: "claude-opus-4-6",
|
|
842
956
|
provider: "anthropic",
|
|
843
|
-
supportsFast:
|
|
957
|
+
supportsFast: false
|
|
844
958
|
},
|
|
845
959
|
{
|
|
846
960
|
id: "claude-opus-4-5",
|
|
@@ -886,7 +1000,25 @@ var GOOGLE_MODELS = [
|
|
|
886
1000
|
|
|
887
1001
|
// src/models/moonshot.ts
|
|
888
1002
|
var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
|
|
1003
|
+
var MOONSHOT_K3_1_MODELS = /* @__PURE__ */ new Set([
|
|
1004
|
+
"kimi-k3.1-pro",
|
|
1005
|
+
"kimi-k3.1-pro-highspeed"
|
|
1006
|
+
]);
|
|
889
1007
|
var MOONSHOT_MODELS = [
|
|
1008
|
+
...Array.from(
|
|
1009
|
+
MOONSHOT_K3_1_MODELS,
|
|
1010
|
+
(id) => ({
|
|
1011
|
+
id,
|
|
1012
|
+
provider: "moonshot",
|
|
1013
|
+
contextWindow: 1048576,
|
|
1014
|
+
maxInputTokens: 1048576,
|
|
1015
|
+
maxOutputTokens: 1048576,
|
|
1016
|
+
supportsTools: true,
|
|
1017
|
+
supportsVision: true,
|
|
1018
|
+
supportsReasoning: true,
|
|
1019
|
+
supportsJsonSchema: true
|
|
1020
|
+
})
|
|
1021
|
+
),
|
|
890
1022
|
{
|
|
891
1023
|
id: MOONSHOT_DEFAULT_MODEL,
|
|
892
1024
|
provider: "moonshot",
|
|
@@ -921,6 +1053,7 @@ function createModelRegistry(specs) {
|
|
|
921
1053
|
function registerModels(registry, specs) {
|
|
922
1054
|
for (const spec of specs) {
|
|
923
1055
|
registry.modelsById[spec.id] = spec;
|
|
1056
|
+
registry.aliasesByProvider[spec.provider] ??= {};
|
|
924
1057
|
const aliasBucket = registry.aliasesByProvider[spec.provider];
|
|
925
1058
|
for (const alias of spec.aliases ?? []) {
|
|
926
1059
|
aliasBucket[alias] = spec.id;
|
|
@@ -929,11 +1062,11 @@ function registerModels(registry, specs) {
|
|
|
929
1062
|
}
|
|
930
1063
|
function resolveModel(registry, idOrAlias, provider) {
|
|
931
1064
|
const direct = registry.modelsById[idOrAlias];
|
|
932
|
-
if (direct) {
|
|
1065
|
+
if (direct && (!provider || direct.provider === provider)) {
|
|
933
1066
|
return direct;
|
|
934
1067
|
}
|
|
935
1068
|
if (provider) {
|
|
936
|
-
const aliasId = registry.aliasesByProvider[provider][idOrAlias];
|
|
1069
|
+
const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
|
|
937
1070
|
return aliasId ? registry.modelsById[aliasId] : void 0;
|
|
938
1071
|
}
|
|
939
1072
|
let resolved;
|
|
@@ -968,15 +1101,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
|
|
|
968
1101
|
return spec?.supportsFast === true;
|
|
969
1102
|
}
|
|
970
1103
|
function cloneAliases(aliasesByProvider) {
|
|
971
|
-
return
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
zai: { ...aliasesByProvider.zai },
|
|
978
|
-
xai: { ...aliasesByProvider.xai }
|
|
979
|
-
};
|
|
1104
|
+
return Object.fromEntries(
|
|
1105
|
+
Object.entries(aliasesByProvider).map(([provider, aliases]) => [
|
|
1106
|
+
provider,
|
|
1107
|
+
{ ...aliases }
|
|
1108
|
+
])
|
|
1109
|
+
);
|
|
980
1110
|
}
|
|
981
1111
|
function applyModelMetadata(registry, index) {
|
|
982
1112
|
const next = {
|
|
@@ -1008,6 +1138,16 @@ function applyModelMetadata(registry, index) {
|
|
|
1008
1138
|
var XAI_DEFAULT_MODEL = "grok-4.5";
|
|
1009
1139
|
var XAI_DEFAULT_REASONING_EFFORT = "high";
|
|
1010
1140
|
var XAI_MODELS = [
|
|
1141
|
+
{
|
|
1142
|
+
id: "grok-4.7",
|
|
1143
|
+
provider: "xai",
|
|
1144
|
+
contextWindow: 5e5,
|
|
1145
|
+
maxInputTokens: 2e5,
|
|
1146
|
+
supportsTools: true,
|
|
1147
|
+
supportsVision: true,
|
|
1148
|
+
supportsReasoning: true,
|
|
1149
|
+
supportsJsonSchema: true
|
|
1150
|
+
},
|
|
1011
1151
|
{
|
|
1012
1152
|
id: XAI_DEFAULT_MODEL,
|
|
1013
1153
|
provider: "xai",
|
|
@@ -1023,7 +1163,10 @@ var XAI_MODELS = [
|
|
|
1023
1163
|
|
|
1024
1164
|
// src/models/zai.ts
|
|
1025
1165
|
var ZAI_DEFAULT_MODEL = "glm-5.2";
|
|
1026
|
-
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set([
|
|
1166
|
+
var ZAI_REASONING_EFFORT_MODELS = /* @__PURE__ */ new Set([
|
|
1167
|
+
"glm-5.3",
|
|
1168
|
+
"glm-5.2"
|
|
1169
|
+
]);
|
|
1027
1170
|
var zaiModel = (id, limits) => ({
|
|
1028
1171
|
id,
|
|
1029
1172
|
provider: "zai",
|
|
@@ -1036,6 +1179,10 @@ var zaiModel = (id, limits) => ({
|
|
|
1036
1179
|
supportsJsonSchema: true
|
|
1037
1180
|
});
|
|
1038
1181
|
var ZAI_MODELS = [
|
|
1182
|
+
zaiModel("glm-5.3", {
|
|
1183
|
+
contextWindow: 1e6,
|
|
1184
|
+
maxOutputTokens: 131072
|
|
1185
|
+
}),
|
|
1039
1186
|
zaiModel(ZAI_DEFAULT_MODEL, {
|
|
1040
1187
|
aliases: ["default"],
|
|
1041
1188
|
contextWindow: 1e6,
|
|
@@ -1069,6 +1216,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
1069
1216
|
...XAI_MODELS
|
|
1070
1217
|
]);
|
|
1071
1218
|
|
|
1219
|
+
// src/content/image-references.ts
|
|
1220
|
+
var REGISTRY = "[codelia.image.artifacts]";
|
|
1221
|
+
function isImageRegistry(message) {
|
|
1222
|
+
return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
|
|
1223
|
+
}
|
|
1224
|
+
function imageReferenceRegistry(messages) {
|
|
1225
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1226
|
+
for (const message of messages) {
|
|
1227
|
+
if (!("content" in message) || !Array.isArray(message.content)) continue;
|
|
1228
|
+
for (const part of message.content)
|
|
1229
|
+
if (part.type === "image_ref") {
|
|
1230
|
+
refs.delete(part.image_ref.artifact_id);
|
|
1231
|
+
refs.set(part.image_ref.artifact_id, part);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
const recent = [...refs.values()].slice(-16);
|
|
1235
|
+
return recent.length ? {
|
|
1236
|
+
role: "user",
|
|
1237
|
+
content: [
|
|
1238
|
+
{
|
|
1239
|
+
type: "text",
|
|
1240
|
+
text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
|
|
1241
|
+
`
|
|
1242
|
+
},
|
|
1243
|
+
...recent
|
|
1244
|
+
]
|
|
1245
|
+
} : null;
|
|
1246
|
+
}
|
|
1247
|
+
function describeImageReferences(messages) {
|
|
1248
|
+
return messages.map((message) => {
|
|
1249
|
+
if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
|
|
1250
|
+
return message;
|
|
1251
|
+
const content = message.content.map(
|
|
1252
|
+
(part) => part.type === "image_ref" ? {
|
|
1253
|
+
type: "text",
|
|
1254
|
+
text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
|
|
1255
|
+
} : part
|
|
1256
|
+
);
|
|
1257
|
+
return { ...message, content };
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1072
1261
|
// src/services/compaction/service.ts
|
|
1073
1262
|
var DEFAULT_THRESHOLD_RATIO = 0.85;
|
|
1074
1263
|
var DEFAULT_RETAIN_LAST_TURNS = 1;
|
|
@@ -1083,14 +1272,14 @@ var CompactionService = class _CompactionService {
|
|
|
1083
1272
|
this.config = _CompactionService.normalizeConfig(config);
|
|
1084
1273
|
this.modelRegistry = deps.modelRegistry;
|
|
1085
1274
|
}
|
|
1086
|
-
async shouldCompact(llm, usage) {
|
|
1275
|
+
async shouldCompact(llm, usage, estimatedInputTokens) {
|
|
1087
1276
|
if (!this.config.enabled) {
|
|
1088
1277
|
return false;
|
|
1089
1278
|
}
|
|
1090
1279
|
if (!this.config.auto) {
|
|
1091
1280
|
return false;
|
|
1092
1281
|
}
|
|
1093
|
-
if (!usage) {
|
|
1282
|
+
if (!usage && estimatedInputTokens === void 0) {
|
|
1094
1283
|
return false;
|
|
1095
1284
|
}
|
|
1096
1285
|
let contextLimit;
|
|
@@ -1100,7 +1289,7 @@ var CompactionService = class _CompactionService {
|
|
|
1100
1289
|
return false;
|
|
1101
1290
|
}
|
|
1102
1291
|
const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
|
|
1103
|
-
return usage
|
|
1292
|
+
return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
|
|
1104
1293
|
}
|
|
1105
1294
|
async compact(llm, messages, options) {
|
|
1106
1295
|
if (!this.config.enabled) {
|
|
@@ -1127,7 +1316,10 @@ var CompactionService = class _CompactionService {
|
|
|
1127
1316
|
try {
|
|
1128
1317
|
response = await llm.ainvoke(
|
|
1129
1318
|
{
|
|
1130
|
-
messages: [
|
|
1319
|
+
messages: describeImageReferences([
|
|
1320
|
+
...preparedMessages,
|
|
1321
|
+
interruptMessage
|
|
1322
|
+
]),
|
|
1131
1323
|
tools: null,
|
|
1132
1324
|
toolChoice: "none",
|
|
1133
1325
|
...options?.signal ? { signal: options.signal } : {},
|
|
@@ -1237,7 +1429,7 @@ var CompactionService = class _CompactionService {
|
|
|
1237
1429
|
);
|
|
1238
1430
|
const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
|
|
1239
1431
|
const conversationMessages = nonSystemMessages.filter(
|
|
1240
|
-
(message) => !isCompactionMemoryMessage(message)
|
|
1432
|
+
(message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
|
|
1241
1433
|
);
|
|
1242
1434
|
const tail = this.normalizeRetainedTail(
|
|
1243
1435
|
this.getLastTurns(conversationMessages, this.config.retainLastTurns)
|
|
@@ -1255,6 +1447,8 @@ var CompactionService = class _CompactionService {
|
|
|
1255
1447
|
content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
|
|
1256
1448
|
});
|
|
1257
1449
|
}
|
|
1450
|
+
const imageRegistry = imageReferenceRegistry(messages);
|
|
1451
|
+
if (imageRegistry) compacted.push(imageRegistry);
|
|
1258
1452
|
compacted.push(...tail);
|
|
1259
1453
|
return compacted;
|
|
1260
1454
|
}
|
|
@@ -1316,7 +1510,7 @@ var CompactionService = class _CompactionService {
|
|
|
1316
1510
|
return messages.slice(startIndex);
|
|
1317
1511
|
}
|
|
1318
1512
|
async resolveContextLimit(llm, usage) {
|
|
1319
|
-
const modelId = usage
|
|
1513
|
+
const modelId = usage?.model ?? llm.model;
|
|
1320
1514
|
const modelSpec = this.resolveModelSpecWithSnapshotFallback(
|
|
1321
1515
|
llm.provider,
|
|
1322
1516
|
modelId
|
|
@@ -1684,6 +1878,239 @@ var TokenUsageService = class {
|
|
|
1684
1878
|
}
|
|
1685
1879
|
};
|
|
1686
1880
|
|
|
1881
|
+
// src/agent/image-context.ts
|
|
1882
|
+
var import_image_size = require("image-size");
|
|
1883
|
+
|
|
1884
|
+
// src/llm/image-policy.ts
|
|
1885
|
+
function estimateImageTokens(provider, model, image) {
|
|
1886
|
+
let name = model.toLowerCase();
|
|
1887
|
+
if (provider === "openrouter") {
|
|
1888
|
+
if (name.startsWith("openai/")) provider = "openai";
|
|
1889
|
+
else if (name.startsWith("anthropic/")) provider = "anthropic";
|
|
1890
|
+
name = name.slice(name.indexOf("/") + 1);
|
|
1891
|
+
}
|
|
1892
|
+
const width = image.width;
|
|
1893
|
+
const height = image.height;
|
|
1894
|
+
const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
|
|
1895
|
+
const patches = (size, edge, budget, multiplier = 1) => {
|
|
1896
|
+
if (!dimensionsKnown)
|
|
1897
|
+
return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
|
|
1898
|
+
const scale = Math.min(1, edge / Math.max(width, height));
|
|
1899
|
+
return {
|
|
1900
|
+
tokens: Math.ceil(
|
|
1901
|
+
Math.min(
|
|
1902
|
+
budget,
|
|
1903
|
+
Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
|
|
1904
|
+
) * multiplier
|
|
1905
|
+
),
|
|
1906
|
+
method: "patch"
|
|
1907
|
+
};
|
|
1908
|
+
};
|
|
1909
|
+
if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
|
|
1910
|
+
name
|
|
1911
|
+
)) {
|
|
1912
|
+
const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
|
|
1913
|
+
name
|
|
1914
|
+
);
|
|
1915
|
+
return patches(
|
|
1916
|
+
28,
|
|
1917
|
+
highResolution ? 2576 : 1568,
|
|
1918
|
+
highResolution ? 4784 : 1568
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
if (provider === "openai") {
|
|
1922
|
+
if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
|
|
1923
|
+
return patches(32, 512, 256, 1.2);
|
|
1924
|
+
if (/^gpt-6-astra(-|$)/.test(name))
|
|
1925
|
+
return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
|
|
1926
|
+
if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
|
|
1927
|
+
return patches(
|
|
1928
|
+
32,
|
|
1929
|
+
image.detail === "high" ? 2048 : 65535,
|
|
1930
|
+
image.detail === "high" ? 2500 : 3e4,
|
|
1931
|
+
1.2
|
|
1932
|
+
);
|
|
1933
|
+
if (/^gpt-5\.5(-|$)/.test(name))
|
|
1934
|
+
return patches(
|
|
1935
|
+
32,
|
|
1936
|
+
image.detail === "high" ? 2048 : 6e3,
|
|
1937
|
+
image.detail === "high" ? 2500 : 1e4,
|
|
1938
|
+
1.2
|
|
1939
|
+
);
|
|
1940
|
+
if (/^gpt-5\.4(-|$)/.test(name))
|
|
1941
|
+
return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
|
|
1942
|
+
if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
|
|
1943
|
+
if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
|
|
1944
|
+
if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
|
|
1945
|
+
const mini = name.startsWith("gpt-4o-mini");
|
|
1946
|
+
const base = mini ? 2833 : 85;
|
|
1947
|
+
const tile = mini ? 5667 : 170;
|
|
1948
|
+
if (image.detail === "low") return { tokens: base, method: "tile" };
|
|
1949
|
+
if (!dimensionsKnown)
|
|
1950
|
+
return { tokens: base + tile * 8, method: "fallback" };
|
|
1951
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
1952
|
+
const shortFit = 768 / (Math.min(width, height) * fit);
|
|
1953
|
+
return {
|
|
1954
|
+
tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
|
|
1955
|
+
method: "tile"
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
return { tokens: 1e4, method: "fallback" };
|
|
1960
|
+
}
|
|
1961
|
+
function imagePayloadLimit(provider) {
|
|
1962
|
+
if (provider === "anthropic") return 32e6;
|
|
1963
|
+
if (provider === "openai") return 512e6;
|
|
1964
|
+
return void 0;
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
// src/agent/image-context.ts
|
|
1968
|
+
function estimateImageContext(input, llm, resolveReferences = true) {
|
|
1969
|
+
let imageTokens = 0;
|
|
1970
|
+
let imageCount = 0;
|
|
1971
|
+
let fallbackCount = 0;
|
|
1972
|
+
let imageBytes = 0;
|
|
1973
|
+
const account = (image) => {
|
|
1974
|
+
const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
|
|
1975
|
+
if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
|
|
1976
|
+
throw new Error("Invalid model image-token estimate");
|
|
1977
|
+
imageTokens += estimate.tokens;
|
|
1978
|
+
imageCount++;
|
|
1979
|
+
if (estimate.method === "fallback") fallbackCount++;
|
|
1980
|
+
};
|
|
1981
|
+
const messages = input.messages.map((message) => {
|
|
1982
|
+
if (!Array.isArray(message.content)) return message;
|
|
1983
|
+
const registry = isImageRegistry(message);
|
|
1984
|
+
return {
|
|
1985
|
+
...message,
|
|
1986
|
+
content: message.content.map((part) => {
|
|
1987
|
+
if (part.type === "image_ref") {
|
|
1988
|
+
if (!registry && resolveReferences) {
|
|
1989
|
+
account({
|
|
1990
|
+
width: part.image_ref.width,
|
|
1991
|
+
height: part.image_ref.height,
|
|
1992
|
+
detail: part.detail
|
|
1993
|
+
});
|
|
1994
|
+
imageBytes += 4 * Math.ceil(
|
|
1995
|
+
(part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
|
|
1996
|
+
) + 64;
|
|
1997
|
+
}
|
|
1998
|
+
return {
|
|
1999
|
+
type: "text",
|
|
2000
|
+
text: `[Image ${part.image_ref.artifact_id}]`
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
if (part.type === "image_url") {
|
|
2004
|
+
let dimensions = {};
|
|
2005
|
+
const url = part.image_url.url;
|
|
2006
|
+
const comma = url.indexOf(",");
|
|
2007
|
+
if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
|
|
2008
|
+
try {
|
|
2009
|
+
dimensions = (0, import_image_size.imageSize)(
|
|
2010
|
+
Buffer.from(url.slice(comma + 1), "base64")
|
|
2011
|
+
);
|
|
2012
|
+
} catch {
|
|
2013
|
+
dimensions = {};
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
account({ ...dimensions, detail: part.image_url.detail });
|
|
2017
|
+
imageBytes += Buffer.byteLength(part.image_url.url);
|
|
2018
|
+
return { type: "text", text: "[Image]" };
|
|
2019
|
+
}
|
|
2020
|
+
if (part.type === "document")
|
|
2021
|
+
return {
|
|
2022
|
+
type: "text",
|
|
2023
|
+
text: "[Document: token estimate unavailable]"
|
|
2024
|
+
};
|
|
2025
|
+
return part;
|
|
2026
|
+
})
|
|
2027
|
+
};
|
|
2028
|
+
});
|
|
2029
|
+
const textBytes = Buffer.byteLength(
|
|
2030
|
+
JSON.stringify({
|
|
2031
|
+
messages,
|
|
2032
|
+
tools: input.tools ?? null,
|
|
2033
|
+
tool_choice: input.toolChoice
|
|
2034
|
+
})
|
|
2035
|
+
);
|
|
2036
|
+
const textTokens = Math.ceil(textBytes / 3);
|
|
2037
|
+
return {
|
|
2038
|
+
text_tokens: textTokens,
|
|
2039
|
+
image_tokens: imageTokens,
|
|
2040
|
+
total_tokens: textTokens + imageTokens,
|
|
2041
|
+
image_count: imageCount,
|
|
2042
|
+
fallback_image_count: fallbackCount,
|
|
2043
|
+
encoded_image_bytes: imageBytes,
|
|
2044
|
+
estimated_request_bytes: textBytes + imageBytes
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
function validateImagePayload(estimate, llm) {
|
|
2048
|
+
const limit = imagePayloadLimit(llm.provider);
|
|
2049
|
+
if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
|
|
2050
|
+
throw new Error(
|
|
2051
|
+
`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.`
|
|
2052
|
+
);
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
// src/agent/image-input.ts
|
|
2056
|
+
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
2057
|
+
async function materializeImageReferences(messages, resolve, signal) {
|
|
2058
|
+
signal?.throwIfAborted();
|
|
2059
|
+
if (resolve) {
|
|
2060
|
+
for (const message of messages) {
|
|
2061
|
+
if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
|
|
2062
|
+
for (const part of message.content) {
|
|
2063
|
+
if (part.type !== "image_ref") continue;
|
|
2064
|
+
const size = part.image_ref.byte_size;
|
|
2065
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
|
|
2066
|
+
throw new Error(
|
|
2067
|
+
"Invalid or oversized image reference; model request was not sent."
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
const result = [];
|
|
2073
|
+
for (const message of messages) {
|
|
2074
|
+
if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
|
|
2075
|
+
result.push(message);
|
|
2076
|
+
continue;
|
|
2077
|
+
}
|
|
2078
|
+
const registry = isImageRegistry(message);
|
|
2079
|
+
const content = [];
|
|
2080
|
+
for (const part of message.content) {
|
|
2081
|
+
if (part.type !== "image_ref") {
|
|
2082
|
+
content.push(part);
|
|
2083
|
+
continue;
|
|
2084
|
+
}
|
|
2085
|
+
signal?.throwIfAborted();
|
|
2086
|
+
if (!registry && resolve) {
|
|
2087
|
+
try {
|
|
2088
|
+
const image = await resolve(part.image_ref, signal);
|
|
2089
|
+
content.push(
|
|
2090
|
+
part.detail ? {
|
|
2091
|
+
...image,
|
|
2092
|
+
image_url: { ...image.image_url, detail: part.detail }
|
|
2093
|
+
} : image
|
|
2094
|
+
);
|
|
2095
|
+
signal?.throwIfAborted();
|
|
2096
|
+
continue;
|
|
2097
|
+
} catch {
|
|
2098
|
+
signal?.throwIfAborted();
|
|
2099
|
+
throw new Error(
|
|
2100
|
+
`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.`
|
|
2101
|
+
);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
content.push({
|
|
2105
|
+
type: "text",
|
|
2106
|
+
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.]`
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
result.push({ ...message, content });
|
|
2110
|
+
}
|
|
2111
|
+
return result;
|
|
2112
|
+
}
|
|
2113
|
+
|
|
1687
2114
|
// src/agent/model-context.ts
|
|
1688
2115
|
var calculateContextLeftPercent = ({
|
|
1689
2116
|
usage,
|
|
@@ -1765,16 +2192,16 @@ var collectModelOutput = (messages) => {
|
|
|
1765
2192
|
if (message.role === "reasoning") {
|
|
1766
2193
|
const raw = message.raw_item;
|
|
1767
2194
|
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1768
|
-
const
|
|
1769
|
-
const kind =
|
|
1770
|
-
const statusRaw =
|
|
2195
|
+
const record3 = raw;
|
|
2196
|
+
const kind = record3.type === "x_search_call" ? "x" : "web";
|
|
2197
|
+
const statusRaw = record3.status;
|
|
1771
2198
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1772
|
-
const action =
|
|
2199
|
+
const action = record3.action && typeof record3.action === "object" ? record3.action : null;
|
|
1773
2200
|
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1774
2201
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1775
2202
|
) : [];
|
|
1776
2203
|
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1777
|
-
const explicitId = typeof
|
|
2204
|
+
const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
|
|
1778
2205
|
let id = explicitId;
|
|
1779
2206
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1780
2207
|
if (!id) {
|
|
@@ -2044,6 +2471,7 @@ var Agent = class {
|
|
|
2044
2471
|
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
2045
2472
|
history;
|
|
2046
2473
|
usageService;
|
|
2474
|
+
imageUsageBaseline;
|
|
2047
2475
|
constructor(options) {
|
|
2048
2476
|
this.llm = options.llm;
|
|
2049
2477
|
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
@@ -2096,13 +2524,15 @@ var Agent = class {
|
|
|
2096
2524
|
}
|
|
2097
2525
|
replaceHistoryMessages(messages) {
|
|
2098
2526
|
this.history.replaceViewMessages(messages);
|
|
2527
|
+
this.imageUsageBaseline = void 0;
|
|
2099
2528
|
}
|
|
2100
2529
|
async *checkAndCompact(signal, options = {}) {
|
|
2101
2530
|
throwIfAborted(signal);
|
|
2102
2531
|
await this.trimToolOutputs();
|
|
2103
2532
|
const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
|
|
2104
2533
|
this.llm,
|
|
2105
|
-
this.usageService.getLastUsage()
|
|
2534
|
+
this.usageService.getLastUsage(),
|
|
2535
|
+
options.estimatedInputTokens
|
|
2106
2536
|
);
|
|
2107
2537
|
if (shouldCompact && this.compactionService) {
|
|
2108
2538
|
throwIfAborted(signal);
|
|
@@ -2123,6 +2553,7 @@ var Agent = class {
|
|
|
2123
2553
|
this.usageService.updateUsageSummary(usage);
|
|
2124
2554
|
if (compacted && compactedMessages) {
|
|
2125
2555
|
this.history.replaceViewMessages(compactedMessages);
|
|
2556
|
+
this.imageUsageBaseline = void 0;
|
|
2126
2557
|
}
|
|
2127
2558
|
if (compacted || options.force) {
|
|
2128
2559
|
await this.llm.onHistoryCompacted?.(invokeContext);
|
|
@@ -2181,9 +2612,13 @@ var Agent = class {
|
|
|
2181
2612
|
const runId = session?.run_id?.trim();
|
|
2182
2613
|
return runId && runId.length > 0 ? runId : void 0;
|
|
2183
2614
|
}
|
|
2184
|
-
buildInvokeContext(session) {
|
|
2615
|
+
buildInvokeContext(session, turnKey) {
|
|
2185
2616
|
const sessionKey = this.resolveSessionKey(session);
|
|
2186
|
-
|
|
2617
|
+
const turn = turnKey ?? session?.run_id;
|
|
2618
|
+
return sessionKey || turn ? {
|
|
2619
|
+
...sessionKey ? { sessionKey } : {},
|
|
2620
|
+
...turn ? { turnKey: turn } : {}
|
|
2621
|
+
} : void 0;
|
|
2187
2622
|
}
|
|
2188
2623
|
recordLlmResponse(session, seq, response) {
|
|
2189
2624
|
if (!session || seq === null) return;
|
|
@@ -2194,6 +2629,7 @@ var Agent = class {
|
|
|
2194
2629
|
seq,
|
|
2195
2630
|
output: {
|
|
2196
2631
|
messages: response.messages,
|
|
2632
|
+
...response.timing ? { timing: response.timing } : {},
|
|
2197
2633
|
usage: response.usage ?? null,
|
|
2198
2634
|
stop_reason: response.stop_reason ?? null,
|
|
2199
2635
|
provider_meta: response.provider_meta ?? null
|
|
@@ -2201,19 +2637,43 @@ var Agent = class {
|
|
|
2201
2637
|
});
|
|
2202
2638
|
}
|
|
2203
2639
|
async *invokeModelWithRetry(input, context, signal) {
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2640
|
+
const estimate = estimateImageContext(
|
|
2641
|
+
input,
|
|
2642
|
+
this.llm,
|
|
2643
|
+
Boolean(this.services.resolveImage)
|
|
2644
|
+
);
|
|
2645
|
+
validateImagePayload(estimate, this.llm);
|
|
2646
|
+
const messages = await materializeImageReferences(
|
|
2647
|
+
input.messages,
|
|
2648
|
+
this.services.resolveImage,
|
|
2649
|
+
signal
|
|
2650
|
+
);
|
|
2651
|
+
const response = yield* withProviderStatus(
|
|
2652
|
+
(onProviderStatus, progressSignal) => invokeWithRetry({
|
|
2653
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2654
|
+
{
|
|
2655
|
+
...input,
|
|
2656
|
+
messages,
|
|
2657
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2658
|
+
},
|
|
2659
|
+
{ ...context, onProviderStatus }
|
|
2660
|
+
),
|
|
2661
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2662
|
+
policy: resolveLlmRetryPolicy({
|
|
2663
|
+
...this.llmRetryPolicy,
|
|
2664
|
+
...this.llm.retryPolicy
|
|
2665
|
+
}),
|
|
2666
|
+
signal: progressSignal,
|
|
2667
|
+
dependencies: this.llmRetryDependencies
|
|
2668
|
+
}),
|
|
2669
|
+
signal
|
|
2670
|
+
);
|
|
2671
|
+
this.imageUsageBaseline = response.usage ? {
|
|
2672
|
+
messages: input.messages.slice(),
|
|
2673
|
+
estimated: estimate.total_tokens,
|
|
2674
|
+
observed: response.usage.input_tokens
|
|
2675
|
+
} : void 0;
|
|
2676
|
+
return response;
|
|
2217
2677
|
}
|
|
2218
2678
|
async run(message, options = {}) {
|
|
2219
2679
|
let finalResponse = "";
|
|
@@ -2251,6 +2711,7 @@ var Agent = class {
|
|
|
2251
2711
|
for (const content of messages) this.history.enqueueUserMessage(content);
|
|
2252
2712
|
return messages;
|
|
2253
2713
|
};
|
|
2714
|
+
const turnKey = session?.run_id ?? (0, import_node_crypto.randomUUID)();
|
|
2254
2715
|
let iterations = 0;
|
|
2255
2716
|
const runTools = [...this.tools, ...options.tools ?? []];
|
|
2256
2717
|
const runToolChoice = options.toolChoice ?? this.toolChoice;
|
|
@@ -2261,11 +2722,27 @@ var Agent = class {
|
|
|
2261
2722
|
yield { type: "hidden_user_message", content };
|
|
2262
2723
|
await this.trimToolOutputs();
|
|
2263
2724
|
throwIfAborted(signal);
|
|
2264
|
-
|
|
2725
|
+
let invokeInput = this.history.prepareInvokeInput({
|
|
2265
2726
|
tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
|
|
2266
2727
|
toolChoice: runToolChoice
|
|
2267
2728
|
});
|
|
2268
|
-
const
|
|
2729
|
+
const imageEstimate = estimateImageContext(
|
|
2730
|
+
invokeInput,
|
|
2731
|
+
this.llm,
|
|
2732
|
+
Boolean(this.services.resolveImage)
|
|
2733
|
+
);
|
|
2734
|
+
if (imageEstimate.image_count > 0) {
|
|
2735
|
+
const baseline = this.imageUsageBaseline;
|
|
2736
|
+
const estimatedInputTokens = baseline && baseline.messages.every(
|
|
2737
|
+
(message2, index) => invokeInput.messages[index] === message2
|
|
2738
|
+
) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
|
|
2739
|
+
yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
|
|
2740
|
+
invokeInput = this.history.prepareInvokeInput({
|
|
2741
|
+
tools: invokeInput.tools,
|
|
2742
|
+
toolChoice: runToolChoice
|
|
2743
|
+
});
|
|
2744
|
+
}
|
|
2745
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2269
2746
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
2270
2747
|
const response = yield* this.invokeModelWithRetry(
|
|
2271
2748
|
invokeInput,
|
|
@@ -2490,7 +2967,11 @@ var Agent = class {
|
|
|
2490
2967
|
yield* this.checkAndCompact(signal, { session });
|
|
2491
2968
|
}
|
|
2492
2969
|
if (signal?.aborted) throw createAbortError2();
|
|
2493
|
-
const finalResponse = await this.generateFinalResponse(
|
|
2970
|
+
const finalResponse = await this.generateFinalResponse(
|
|
2971
|
+
session,
|
|
2972
|
+
signal,
|
|
2973
|
+
turnKey
|
|
2974
|
+
);
|
|
2494
2975
|
const finalResponseEvent = {
|
|
2495
2976
|
type: "final",
|
|
2496
2977
|
termination_reason: "max_steps",
|
|
@@ -2499,7 +2980,7 @@ var Agent = class {
|
|
|
2499
2980
|
yield finalResponseEvent;
|
|
2500
2981
|
return;
|
|
2501
2982
|
}
|
|
2502
|
-
async generateFinalResponse(session, signal) {
|
|
2983
|
+
async generateFinalResponse(session, signal, turnKey) {
|
|
2503
2984
|
const summaryMessage = {
|
|
2504
2985
|
role: "user",
|
|
2505
2986
|
content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
|
|
@@ -2512,11 +2993,24 @@ var Agent = class {
|
|
|
2512
2993
|
// no tools are allowed at this point
|
|
2513
2994
|
toolChoice: "none"
|
|
2514
2995
|
};
|
|
2515
|
-
const invokeContext = this.buildInvokeContext(session);
|
|
2996
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2516
2997
|
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
2998
|
+
validateImagePayload(
|
|
2999
|
+
estimateImageContext(
|
|
3000
|
+
input,
|
|
3001
|
+
this.llm,
|
|
3002
|
+
Boolean(this.services.resolveImage)
|
|
3003
|
+
),
|
|
3004
|
+
this.llm
|
|
3005
|
+
);
|
|
2517
3006
|
const summary = await this.llm.ainvoke(
|
|
2518
3007
|
{
|
|
2519
3008
|
...input,
|
|
3009
|
+
messages: await materializeImageReferences(
|
|
3010
|
+
input.messages,
|
|
3011
|
+
this.services.resolveImage,
|
|
3012
|
+
signal
|
|
3013
|
+
),
|
|
2520
3014
|
...signal ? { signal } : {}
|
|
2521
3015
|
},
|
|
2522
3016
|
invokeContext
|
|
@@ -2537,8 +3031,90 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
2537
3031
|
}
|
|
2538
3032
|
};
|
|
2539
3033
|
|
|
3034
|
+
// src/llm/stream-timing.ts
|
|
3035
|
+
var record = (value) => value !== null && typeof value === "object" ? value : void 0;
|
|
3036
|
+
var nonempty = (value) => typeof value === "string" && value.length > 0;
|
|
3037
|
+
var responseOutputDeltas = /* @__PURE__ */ new Set([
|
|
3038
|
+
"response.output_text.delta",
|
|
3039
|
+
"response.refusal.delta",
|
|
3040
|
+
"response.function_call_arguments.delta",
|
|
3041
|
+
"response.custom_tool_call_input.delta",
|
|
3042
|
+
"response.reasoning_text.delta",
|
|
3043
|
+
"response.reasoning_summary_text.delta"
|
|
3044
|
+
]);
|
|
3045
|
+
var LlmStreamTiming = class {
|
|
3046
|
+
constructor(nowMs = () => performance.now()) {
|
|
3047
|
+
this.nowMs = nowMs;
|
|
3048
|
+
this.startedAt = nowMs();
|
|
3049
|
+
}
|
|
3050
|
+
nowMs;
|
|
3051
|
+
startedAt;
|
|
3052
|
+
firstOutputAt;
|
|
3053
|
+
reasoningStartedAt;
|
|
3054
|
+
completedAt;
|
|
3055
|
+
observeOutput() {
|
|
3056
|
+
if (this.completedAt === void 0 && this.firstOutputAt === void 0)
|
|
3057
|
+
this.firstOutputAt = this.nowMs();
|
|
3058
|
+
}
|
|
3059
|
+
complete() {
|
|
3060
|
+
this.completedAt ??= this.nowMs();
|
|
3061
|
+
}
|
|
3062
|
+
observeResponsesEvent(event) {
|
|
3063
|
+
const value = record(event);
|
|
3064
|
+
if (!value) return;
|
|
3065
|
+
if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
|
|
3066
|
+
this.reasoningStartedAt ??= this.nowMs();
|
|
3067
|
+
if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
|
|
3068
|
+
this.observeOutput();
|
|
3069
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
|
|
3070
|
+
this.complete();
|
|
3071
|
+
}
|
|
3072
|
+
observeChatChunk(chunk) {
|
|
3073
|
+
const choices = record(chunk)?.choices;
|
|
3074
|
+
if (!Array.isArray(choices)) return;
|
|
3075
|
+
for (const choice of choices) {
|
|
3076
|
+
const delta = record(record(choice)?.delta);
|
|
3077
|
+
if (!delta) continue;
|
|
3078
|
+
if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
|
|
3079
|
+
(tool) => nonempty(record(record(tool)?.function)?.arguments)
|
|
3080
|
+
))
|
|
3081
|
+
this.observeOutput();
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
observeAnthropicEvent(event) {
|
|
3085
|
+
const value = record(event);
|
|
3086
|
+
if (!value) return;
|
|
3087
|
+
const delta = record(value.delta);
|
|
3088
|
+
if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
|
|
3089
|
+
this.observeOutput();
|
|
3090
|
+
if (value.type === "message_stop") this.complete();
|
|
3091
|
+
}
|
|
3092
|
+
finish() {
|
|
3093
|
+
this.complete();
|
|
3094
|
+
if (this.firstOutputAt === void 0) return void 0;
|
|
3095
|
+
const first = this.firstOutputAt - this.startedAt;
|
|
3096
|
+
const start = Math.min(
|
|
3097
|
+
this.firstOutputAt,
|
|
3098
|
+
this.reasoningStartedAt ?? this.firstOutputAt
|
|
3099
|
+
);
|
|
3100
|
+
const generation = this.completedAt - start;
|
|
3101
|
+
if (![first, generation, start - this.startedAt].every(
|
|
3102
|
+
(ms) => Number.isFinite(ms) && ms >= 0
|
|
3103
|
+
))
|
|
3104
|
+
return void 0;
|
|
3105
|
+
return {
|
|
3106
|
+
time_to_first_token_ms: first,
|
|
3107
|
+
generation_duration_ms: generation,
|
|
3108
|
+
...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
|
|
3109
|
+
generation_start_ms: start - this.startedAt,
|
|
3110
|
+
generation_start_source: "reasoning_item"
|
|
3111
|
+
} : {}
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
};
|
|
3115
|
+
|
|
2540
3116
|
// src/llm/anthropic/chat.ts
|
|
2541
|
-
var
|
|
3117
|
+
var import_node_crypto3 = require("crypto");
|
|
2542
3118
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
2543
3119
|
|
|
2544
3120
|
// src/llm/anthropic/failure.ts
|
|
@@ -2608,6 +3184,74 @@ var classifyAnthropicFailure = (error) => {
|
|
|
2608
3184
|
return classifyTransportFailure(PROVIDER_NAME, error) ?? buildProviderFailure(PROVIDER_NAME, "provider");
|
|
2609
3185
|
};
|
|
2610
3186
|
|
|
3187
|
+
// src/llm/anthropic/thinking.ts
|
|
3188
|
+
var import_node_crypto2 = require("crypto");
|
|
3189
|
+
var PREFIX_KEY = "codelia_anthropic_prefix_sha256";
|
|
3190
|
+
var usesBoundThinking = (model) => model === "claude-sonnet-5-5" || model === "claude-haiku-5-5";
|
|
3191
|
+
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
3192
|
+
var isThinkingBlock = (value) => isRecord(value) && (value.type === "thinking" && typeof value.thinking === "string" && typeof value.signature === "string" || value.type === "redacted_thinking" && typeof value.data === "string");
|
|
3193
|
+
var canonicalJson = (value) => JSON.stringify(
|
|
3194
|
+
value,
|
|
3195
|
+
(_key, item) => isRecord(item) && !Array.isArray(item) ? Object.fromEntries(
|
|
3196
|
+
Object.keys(item).sort().map((key) => [key, item[key]])
|
|
3197
|
+
) : item
|
|
3198
|
+
);
|
|
3199
|
+
var startPrefix = (request) => (0, import_node_crypto2.createHash)("sha256").update(
|
|
3200
|
+
canonicalJson({
|
|
3201
|
+
system: request.system ?? null,
|
|
3202
|
+
tools: request.tools ?? []
|
|
3203
|
+
})
|
|
3204
|
+
).update("\n");
|
|
3205
|
+
var startMessage = (hash, role) => hash.copy().update(`${role}
|
|
3206
|
+
`);
|
|
3207
|
+
var addBlock = (hash, block) => {
|
|
3208
|
+
hash.update(canonicalJson(block)).update("\n");
|
|
3209
|
+
};
|
|
3210
|
+
var contentBlocks = (message) => typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
|
|
3211
|
+
var filterBoundThinking = (request) => {
|
|
3212
|
+
let hash = startPrefix(request);
|
|
3213
|
+
const messages = [];
|
|
3214
|
+
for (const message of request.messages) {
|
|
3215
|
+
const nextHash = startMessage(hash, message.role);
|
|
3216
|
+
const content = [];
|
|
3217
|
+
for (const block of contentBlocks(message)) {
|
|
3218
|
+
let clean = block;
|
|
3219
|
+
if (isThinkingBlock(block)) {
|
|
3220
|
+
const { [PREFIX_KEY]: prefix, ...original } = block;
|
|
3221
|
+
if (prefix !== nextHash.copy().digest("hex") || !isThinkingBlock(original))
|
|
3222
|
+
continue;
|
|
3223
|
+
clean = original;
|
|
3224
|
+
}
|
|
3225
|
+
content.push(clean);
|
|
3226
|
+
addBlock(nextHash, clean);
|
|
3227
|
+
}
|
|
3228
|
+
if (content.length === 0) continue;
|
|
3229
|
+
messages.push({ ...message, content });
|
|
3230
|
+
hash = nextHash;
|
|
3231
|
+
}
|
|
3232
|
+
return messages;
|
|
3233
|
+
};
|
|
3234
|
+
var bindResponseThinking = (request, blocks, messages) => {
|
|
3235
|
+
let hash = startPrefix(request);
|
|
3236
|
+
for (const message of request.messages) {
|
|
3237
|
+
hash = startMessage(hash, message.role);
|
|
3238
|
+
for (const block of contentBlocks(message)) addBlock(hash, block);
|
|
3239
|
+
}
|
|
3240
|
+
hash = startMessage(hash, "assistant");
|
|
3241
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
3242
|
+
for (const block of blocks) {
|
|
3243
|
+
if (isThinkingBlock(block)) prefixes.set(block, hash.copy().digest("hex"));
|
|
3244
|
+
addBlock(hash, block);
|
|
3245
|
+
}
|
|
3246
|
+
for (const message of messages) {
|
|
3247
|
+
if (message.role !== "reasoning" || !isThinkingBlock(message.raw_item))
|
|
3248
|
+
continue;
|
|
3249
|
+
const prefix = prefixes.get(message.raw_item);
|
|
3250
|
+
if (prefix)
|
|
3251
|
+
message.raw_item = { ...message.raw_item, [PREFIX_KEY]: prefix };
|
|
3252
|
+
}
|
|
3253
|
+
};
|
|
3254
|
+
|
|
2611
3255
|
// src/llm/provider-log.ts
|
|
2612
3256
|
var import_node_fs = require("fs");
|
|
2613
3257
|
var import_node_path = __toESM(require("path"), 1);
|
|
@@ -2663,6 +3307,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
|
|
|
2663
3307
|
};
|
|
2664
3308
|
|
|
2665
3309
|
// src/types/llm/guards.ts
|
|
3310
|
+
var import_shared_types = require("@codelia/shared-types");
|
|
2666
3311
|
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2667
3312
|
function isTextPart(value) {
|
|
2668
3313
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2691,7 +3336,19 @@ function isOtherPart(value) {
|
|
|
2691
3336
|
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2692
3337
|
}
|
|
2693
3338
|
function isContentPart(value) {
|
|
2694
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3339
|
+
return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3340
|
+
}
|
|
3341
|
+
function isImageRefPart(value) {
|
|
3342
|
+
if (!value || typeof value !== "object") return false;
|
|
3343
|
+
const v = value;
|
|
3344
|
+
if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
|
|
3345
|
+
return false;
|
|
3346
|
+
const r = v.image_ref;
|
|
3347
|
+
return (r.model_view === void 0 || (0, import_shared_types.isImageModelView)(r.model_view)) && typeof r.artifact_id === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(r.artifact_id) && typeof r.sha256 === "string" && /^[0-9a-f]{64}$/.test(r.sha256) && ["image/png", "image/jpeg", "image/webp", "image/gif"].includes(
|
|
3348
|
+
String(r.media_type)
|
|
3349
|
+
) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
|
|
3350
|
+
(n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
|
|
3351
|
+
) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
|
|
2695
3352
|
}
|
|
2696
3353
|
function isToolResult(value) {
|
|
2697
3354
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2713,7 +3370,7 @@ var isHostedXSearchToolDefinition = (value) => value.type === "hosted_search" &&
|
|
|
2713
3370
|
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
2714
3371
|
|
|
2715
3372
|
// src/llm/anthropic/serializer.ts
|
|
2716
|
-
var
|
|
3373
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
2717
3374
|
var stringifyUnknown2 = (value) => {
|
|
2718
3375
|
if (value == null) return "";
|
|
2719
3376
|
if (typeof value === "string") return value;
|
|
@@ -2734,14 +3391,14 @@ var parseDataUrl = (url) => {
|
|
|
2734
3391
|
};
|
|
2735
3392
|
var isSupportedImageMediaType = (value) => value === "image/png" || value === "image/jpeg" || value === "image/webp" || value === "image/gif";
|
|
2736
3393
|
var isAnthropicContentBlock = (value) => {
|
|
2737
|
-
if (!
|
|
3394
|
+
if (!isRecord2(value) || typeof value.type !== "string") return false;
|
|
2738
3395
|
switch (value.type) {
|
|
2739
3396
|
case "text":
|
|
2740
3397
|
return typeof value.text === "string";
|
|
2741
3398
|
case "image":
|
|
2742
|
-
return
|
|
3399
|
+
return isRecord2(value.source);
|
|
2743
3400
|
case "document":
|
|
2744
|
-
return
|
|
3401
|
+
return isRecord2(value.source);
|
|
2745
3402
|
case "search_result":
|
|
2746
3403
|
return true;
|
|
2747
3404
|
default:
|
|
@@ -2795,6 +3452,15 @@ var toContentBlocks = (content) => {
|
|
|
2795
3452
|
}
|
|
2796
3453
|
};
|
|
2797
3454
|
}
|
|
3455
|
+
if (URL.canParse(part.image_url.url)) {
|
|
3456
|
+
const url = new URL(part.image_url.url);
|
|
3457
|
+
if (url.protocol === "https:" || url.protocol === "http:") {
|
|
3458
|
+
return {
|
|
3459
|
+
type: "image",
|
|
3460
|
+
source: { type: "url", url: part.image_url.url }
|
|
3461
|
+
};
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
2798
3464
|
return toTextBlock(part.image_url.url);
|
|
2799
3465
|
}
|
|
2800
3466
|
case "document":
|
|
@@ -2872,8 +3538,8 @@ var mergePendingToolResults = (pendingToolResults, output) => {
|
|
|
2872
3538
|
});
|
|
2873
3539
|
pendingToolResults.length = 0;
|
|
2874
3540
|
};
|
|
2875
|
-
var isToolUseBlock = (block) =>
|
|
2876
|
-
var isToolResultBlock = (block) =>
|
|
3541
|
+
var isToolUseBlock = (block) => isRecord2(block) && block.type === "tool_use";
|
|
3542
|
+
var isToolResultBlock = (block) => isRecord2(block) && block.type === "tool_result";
|
|
2877
3543
|
var isAssistantWithToolUseBlocks = (message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => isToolUseBlock(block));
|
|
2878
3544
|
var coalesceConsecutiveAssistantToolUseMessages = (messages) => {
|
|
2879
3545
|
const normalized = [];
|
|
@@ -2956,7 +3622,7 @@ var dropOrphanToolUseBlocks = (messages) => {
|
|
|
2956
3622
|
}
|
|
2957
3623
|
return sanitized;
|
|
2958
3624
|
};
|
|
2959
|
-
var toAnthropicMessages = (messages) => {
|
|
3625
|
+
var toAnthropicMessages = (messages, options) => {
|
|
2960
3626
|
const systemParts = [];
|
|
2961
3627
|
const output = [];
|
|
2962
3628
|
const pendingToolResults = [];
|
|
@@ -2969,6 +3635,10 @@ var toAnthropicMessages = (messages) => {
|
|
|
2969
3635
|
break;
|
|
2970
3636
|
}
|
|
2971
3637
|
case "reasoning":
|
|
3638
|
+
if (options?.replayThinking && isThinkingBlock(message.raw_item)) {
|
|
3639
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
3640
|
+
output.push({ role: "assistant", content: [message.raw_item] });
|
|
3641
|
+
}
|
|
2972
3642
|
break;
|
|
2973
3643
|
case "tool": {
|
|
2974
3644
|
pendingToolResults.push(toToolResultBlock(message));
|
|
@@ -2977,9 +3647,29 @@ var toAnthropicMessages = (messages) => {
|
|
|
2977
3647
|
case "assistant": {
|
|
2978
3648
|
mergePendingToolResults(pendingToolResults, output);
|
|
2979
3649
|
const blocks = [];
|
|
2980
|
-
|
|
3650
|
+
const original = message.provider_meta;
|
|
3651
|
+
if (options?.replayThinking && isRecord2(original) && original.type === "text" && original.text === message.content) {
|
|
3652
|
+
blocks.push(original);
|
|
3653
|
+
} else {
|
|
3654
|
+
const part = Array.isArray(message.content) && message.content.length === 1 ? message.content[0] : void 0;
|
|
3655
|
+
if (options?.replayThinking && part?.type === "other" && part.provider === "anthropic" && isRecord2(part.payload) && [
|
|
3656
|
+
"server_tool_use",
|
|
3657
|
+
"web_search_tool_result",
|
|
3658
|
+
"web_fetch_tool_result"
|
|
3659
|
+
].includes(String(part.payload.type))) {
|
|
3660
|
+
blocks.push(part.payload);
|
|
3661
|
+
} else {
|
|
3662
|
+
blocks.push(...toContentBlocks(message.content));
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
2981
3665
|
if (message.tool_calls?.length) {
|
|
2982
|
-
blocks.push(
|
|
3666
|
+
blocks.push(
|
|
3667
|
+
...message.tool_calls.map((call) => {
|
|
3668
|
+
const block = toToolUseBlock(call);
|
|
3669
|
+
const original2 = call.provider_meta;
|
|
3670
|
+
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;
|
|
3671
|
+
})
|
|
3672
|
+
);
|
|
2983
3673
|
}
|
|
2984
3674
|
output.push({
|
|
2985
3675
|
role: "assistant",
|
|
@@ -3002,7 +3692,16 @@ var toAnthropicMessages = (messages) => {
|
|
|
3002
3692
|
}
|
|
3003
3693
|
mergePendingToolResults(pendingToolResults, output);
|
|
3004
3694
|
const system = systemParts.length ? systemParts.join("\n\n") : void 0;
|
|
3005
|
-
|
|
3695
|
+
const turns = [];
|
|
3696
|
+
for (const message of output) {
|
|
3697
|
+
const previous = turns.at(-1);
|
|
3698
|
+
if (options?.replayThinking && message.role === "assistant" && previous?.role === "assistant" && Array.isArray(message.content) && Array.isArray(previous.content)) {
|
|
3699
|
+
previous.content.push(...message.content);
|
|
3700
|
+
} else {
|
|
3701
|
+
turns.push(message);
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
return { system, messages: dropOrphanToolUseBlocks(turns) };
|
|
3006
3705
|
};
|
|
3007
3706
|
var extractText = (blocks) => blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
3008
3707
|
var DEFAULT_REFUSAL_MESSAGE = "This request was declined by Anthropic's safety classifier.";
|
|
@@ -3039,7 +3738,8 @@ var toChatInvokeCompletion = (response, meta) => {
|
|
|
3039
3738
|
case "text":
|
|
3040
3739
|
messages.push({
|
|
3041
3740
|
role: "assistant",
|
|
3042
|
-
content: block.text
|
|
3741
|
+
content: block.text,
|
|
3742
|
+
...meta?.preserveBlocks ? { provider_meta: block } : {}
|
|
3043
3743
|
});
|
|
3044
3744
|
break;
|
|
3045
3745
|
case "tool_use":
|
|
@@ -3052,7 +3752,7 @@ var toChatInvokeCompletion = (response, meta) => {
|
|
|
3052
3752
|
type: "function",
|
|
3053
3753
|
function: {
|
|
3054
3754
|
name: block.name,
|
|
3055
|
-
arguments:
|
|
3755
|
+
arguments: isRecord2(block.input) ? JSON.stringify(block.input) : JSON.stringify({ value: block.input })
|
|
3056
3756
|
},
|
|
3057
3757
|
provider_meta: block
|
|
3058
3758
|
}
|
|
@@ -3184,7 +3884,12 @@ var ChatAnthropic = class {
|
|
|
3184
3884
|
model,
|
|
3185
3885
|
signal
|
|
3186
3886
|
} = input;
|
|
3187
|
-
const
|
|
3887
|
+
const requestModel = model ?? this.model;
|
|
3888
|
+
const boundThinking = usesBoundThinking(requestModel);
|
|
3889
|
+
const { system, messages: anthropicMessages } = toAnthropicMessages(
|
|
3890
|
+
messages,
|
|
3891
|
+
{ replayThinking: boundThinking }
|
|
3892
|
+
);
|
|
3188
3893
|
const enableTools = toolChoice !== "none";
|
|
3189
3894
|
const tools = enableTools ? toAnthropicTools(toolDefs) : void 0;
|
|
3190
3895
|
const tool_choice = enableTools ? toAnthropicToolChoice(toolChoice) : void 0;
|
|
@@ -3194,7 +3899,7 @@ var ChatAnthropic = class {
|
|
|
3194
3899
|
};
|
|
3195
3900
|
const { max_tokens, ...rest } = resolvedOptions;
|
|
3196
3901
|
const request = {
|
|
3197
|
-
model:
|
|
3902
|
+
model: requestModel,
|
|
3198
3903
|
max_tokens: max_tokens ?? this.defaultMaxTokens,
|
|
3199
3904
|
messages: anthropicMessages,
|
|
3200
3905
|
...rest,
|
|
@@ -3202,6 +3907,54 @@ var ChatAnthropic = class {
|
|
|
3202
3907
|
...tools ? { tools } : {},
|
|
3203
3908
|
...tool_choice ? { tool_choice } : {}
|
|
3204
3909
|
};
|
|
3910
|
+
if (boundThinking) {
|
|
3911
|
+
if (this.fastMode || request.speed === "fast") {
|
|
3912
|
+
throw createProviderValidationError(
|
|
3913
|
+
PROVIDER_NAME2,
|
|
3914
|
+
"Claude Sonnet/Haiku 5.5 do not support Fast mode."
|
|
3915
|
+
);
|
|
3916
|
+
}
|
|
3917
|
+
if ([request.temperature, request.top_p, request.top_k].some(
|
|
3918
|
+
(value) => value !== void 0
|
|
3919
|
+
)) {
|
|
3920
|
+
throw createProviderValidationError(
|
|
3921
|
+
PROVIDER_NAME2,
|
|
3922
|
+
"Claude Sonnet/Haiku 5.5 require temperature, top_p and top_k to be omitted."
|
|
3923
|
+
);
|
|
3924
|
+
}
|
|
3925
|
+
if (request.thinking?.type === "enabled") {
|
|
3926
|
+
throw createProviderValidationError(
|
|
3927
|
+
PROVIDER_NAME2,
|
|
3928
|
+
"Claude Sonnet/Haiku 5.5 require adaptive thinking instead of legacy budget_tokens."
|
|
3929
|
+
);
|
|
3930
|
+
}
|
|
3931
|
+
if (requestModel === "claude-sonnet-5-5" && (tool_choice?.type === "any" || tool_choice?.type === "tool")) {
|
|
3932
|
+
throw createProviderValidationError(
|
|
3933
|
+
PROVIDER_NAME2,
|
|
3934
|
+
"Claude Sonnet 5.5 does not support required or named tool choice. Use auto tool choice."
|
|
3935
|
+
);
|
|
3936
|
+
}
|
|
3937
|
+
if (requestModel === "claude-sonnet-5-5" && request.thinking?.type === "disabled") {
|
|
3938
|
+
throw createProviderValidationError(
|
|
3939
|
+
PROVIDER_NAME2,
|
|
3940
|
+
"Claude Sonnet 5.5 requires adaptive thinking."
|
|
3941
|
+
);
|
|
3942
|
+
}
|
|
3943
|
+
if (!request.thinking || request.thinking.type === "adaptive") {
|
|
3944
|
+
request.thinking = {
|
|
3945
|
+
type: "adaptive",
|
|
3946
|
+
display: "summarized",
|
|
3947
|
+
...request.thinking
|
|
3948
|
+
};
|
|
3949
|
+
}
|
|
3950
|
+
request.messages = filterBoundThinking(request);
|
|
3951
|
+
if (request.messages.at(-1)?.role !== "user") {
|
|
3952
|
+
throw createProviderValidationError(
|
|
3953
|
+
PROVIDER_NAME2,
|
|
3954
|
+
"Claude Sonnet/Haiku 5.5 require a final user or tool-result turn; assistant prefill is unsupported."
|
|
3955
|
+
);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3205
3958
|
if (request.cache_control === void 0) {
|
|
3206
3959
|
request.cache_control = DEFAULT_PROMPT_CACHE_CONTROL;
|
|
3207
3960
|
}
|
|
@@ -3212,20 +3965,31 @@ var ChatAnthropic = class {
|
|
|
3212
3965
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
3213
3966
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
3214
3967
|
const requestOptions = signal ? { signal } : void 0;
|
|
3215
|
-
const
|
|
3968
|
+
const timing = new LlmStreamTiming();
|
|
3969
|
+
const stream = this.fastMode ? this.client.beta.messages.stream(
|
|
3216
3970
|
request,
|
|
3217
3971
|
requestOptions
|
|
3218
|
-
) :
|
|
3972
|
+
) : this.client.messages.stream(
|
|
3219
3973
|
request,
|
|
3220
3974
|
requestOptions
|
|
3221
3975
|
);
|
|
3976
|
+
for await (const event of stream) timing.observeAnthropicEvent(event);
|
|
3977
|
+
const response = await stream.finalMessage();
|
|
3978
|
+
const measuredTiming = timing.finish();
|
|
3222
3979
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3223
|
-
|
|
3980
|
+
const completion = toChatInvokeCompletion(response, {
|
|
3224
3981
|
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
3225
3982
|
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
3226
3983
|
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
|
|
3227
|
-
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
|
|
3984
|
+
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset,
|
|
3985
|
+
preserveBlocks: boundThinking
|
|
3228
3986
|
});
|
|
3987
|
+
if (boundThinking)
|
|
3988
|
+
bindResponseThinking(request, response.content, completion.messages);
|
|
3989
|
+
return {
|
|
3990
|
+
...completion,
|
|
3991
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
3992
|
+
};
|
|
3229
3993
|
}
|
|
3230
3994
|
nextDebugInvokeSeq() {
|
|
3231
3995
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -3238,9 +4002,9 @@ var ChatAnthropic = class {
|
|
|
3238
4002
|
return;
|
|
3239
4003
|
}
|
|
3240
4004
|
const payload = safeJsonStringify(request);
|
|
3241
|
-
const hash = (0,
|
|
3242
|
-
const toolsHash = (0,
|
|
3243
|
-
const systemHash = (0,
|
|
4005
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
4006
|
+
const toolsHash = (0, import_node_crypto3.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
4007
|
+
const systemHash = (0, import_node_crypto3.createHash)("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
3244
4008
|
const previous = this.lastDebugRequestPayload;
|
|
3245
4009
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3246
4010
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -3310,7 +4074,7 @@ var ChatAnthropic = class {
|
|
|
3310
4074
|
};
|
|
3311
4075
|
|
|
3312
4076
|
// src/llm/moonshot/chat.ts
|
|
3313
|
-
var
|
|
4077
|
+
var import_node_crypto4 = require("crypto");
|
|
3314
4078
|
var import_openai3 = __toESM(require("openai"), 1);
|
|
3315
4079
|
|
|
3316
4080
|
// src/llm/moonshot/failure.ts
|
|
@@ -3631,8 +4395,8 @@ function toMoonshotChatInvokeCompletion(accumulator, meta) {
|
|
|
3631
4395
|
response_id: accumulator.id,
|
|
3632
4396
|
finish_reason: accumulator.finishReason ?? null,
|
|
3633
4397
|
reasoning_requested: meta.reasoningRequested,
|
|
3634
|
-
reasoning_applied: "max",
|
|
3635
|
-
reasoning_effort: "max",
|
|
4398
|
+
reasoning_applied: meta.reasoningApplied ?? "max",
|
|
4399
|
+
reasoning_effort: meta.reasoningApplied ?? "max",
|
|
3636
4400
|
reasoning_fallback: meta.reasoningFallback
|
|
3637
4401
|
}
|
|
3638
4402
|
};
|
|
@@ -3681,12 +4445,14 @@ var ChatMoonshot = class {
|
|
|
3681
4445
|
apiKey;
|
|
3682
4446
|
clientOptions;
|
|
3683
4447
|
reasoningLevelRequested;
|
|
4448
|
+
reasoningEffort;
|
|
3684
4449
|
debugInvokeSeq = 0;
|
|
3685
4450
|
lastDebugRequestPayload = null;
|
|
3686
4451
|
constructor(options = {}) {
|
|
3687
4452
|
this.apiKey = options.apiKey;
|
|
3688
4453
|
this.model = options.model ?? MOONSHOT_DEFAULT_MODEL;
|
|
3689
4454
|
this.reasoningLevelRequested = options.reasoningLevelRequested ?? "medium";
|
|
4455
|
+
this.reasoningEffort = options.reasoningEffort ?? "max";
|
|
3690
4456
|
this.clientOptions = {
|
|
3691
4457
|
baseURL: (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
3692
4458
|
timeout: options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
@@ -3705,7 +4471,7 @@ var ChatMoonshot = class {
|
|
|
3705
4471
|
messages: toMoonshotMessages(input.messages),
|
|
3706
4472
|
stream: true,
|
|
3707
4473
|
stream_options: { include_usage: true },
|
|
3708
|
-
reasoning_effort:
|
|
4474
|
+
reasoning_effort: this.reasoningEffort,
|
|
3709
4475
|
...input.options ?? {},
|
|
3710
4476
|
...tools ? { tools } : {},
|
|
3711
4477
|
...toolChoice ? { tool_choice: toolChoice } : {}
|
|
@@ -3713,6 +4479,7 @@ var ChatMoonshot = class {
|
|
|
3713
4479
|
const seq = this.nextDebugInvokeSeq();
|
|
3714
4480
|
await this.debugRequestIfEnabled(request, seq);
|
|
3715
4481
|
const client = new import_openai3.default({ apiKey: this.apiKey, ...this.clientOptions });
|
|
4482
|
+
const timing = new LlmStreamTiming();
|
|
3716
4483
|
const accumulator = createMoonshotStreamAccumulator();
|
|
3717
4484
|
try {
|
|
3718
4485
|
const stream = await client.chat.completions.create(
|
|
@@ -3720,6 +4487,7 @@ var ChatMoonshot = class {
|
|
|
3720
4487
|
{ signal: input.signal }
|
|
3721
4488
|
);
|
|
3722
4489
|
for await (const chunk of stream) {
|
|
4490
|
+
timing.observeChatChunk(chunk);
|
|
3723
4491
|
appendMoonshotChatCompletionChunk(
|
|
3724
4492
|
accumulator,
|
|
3725
4493
|
chunk
|
|
@@ -3732,11 +4500,16 @@ var ChatMoonshot = class {
|
|
|
3732
4500
|
{ cause: error }
|
|
3733
4501
|
);
|
|
3734
4502
|
}
|
|
4503
|
+
const measuredTiming = timing.finish();
|
|
3735
4504
|
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3736
|
-
return
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
4505
|
+
return {
|
|
4506
|
+
...toMoonshotChatInvokeCompletion(accumulator, {
|
|
4507
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
4508
|
+
reasoningApplied: request.reasoning_effort,
|
|
4509
|
+
reasoningFallback: this.reasoningLevelRequested !== request.reasoning_effort
|
|
4510
|
+
}),
|
|
4511
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
4512
|
+
};
|
|
3740
4513
|
}
|
|
3741
4514
|
nextDebugInvokeSeq() {
|
|
3742
4515
|
this.debugInvokeSeq += 1;
|
|
@@ -3746,7 +4519,7 @@ var ChatMoonshot = class {
|
|
|
3746
4519
|
const settings = getProviderLogSettings();
|
|
3747
4520
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
3748
4521
|
const payload = safeJsonStringify(request);
|
|
3749
|
-
const hash = (0,
|
|
4522
|
+
const hash = (0, import_node_crypto4.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3750
4523
|
const previous = this.lastDebugRequestPayload;
|
|
3751
4524
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3752
4525
|
if (settings.enabled) {
|
|
@@ -3802,11 +4575,185 @@ var ChatMoonshot = class {
|
|
|
3802
4575
|
};
|
|
3803
4576
|
|
|
3804
4577
|
// src/llm/openai/chat.ts
|
|
3805
|
-
var
|
|
4578
|
+
var import_node_crypto6 = require("crypto");
|
|
4579
|
+
var import_openai5 = __toESM(require("openai"), 1);
|
|
4580
|
+
|
|
4581
|
+
// src/llm/openai/codex-metadata.ts
|
|
4582
|
+
var import_node_crypto5 = require("crypto");
|
|
4583
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
4584
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
|
|
4585
|
+
var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
|
|
4586
|
+
var headerValue = (headers, name) => {
|
|
4587
|
+
const entries = record2(headers);
|
|
4588
|
+
const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
4589
|
+
return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
|
|
4590
|
+
};
|
|
4591
|
+
var isCodexBackend = (baseURL) => {
|
|
4592
|
+
try {
|
|
4593
|
+
const url = new URL(baseURL);
|
|
4594
|
+
return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
|
|
4595
|
+
} catch {
|
|
4596
|
+
return false;
|
|
4597
|
+
}
|
|
4598
|
+
};
|
|
4599
|
+
var CodexTurnState = class {
|
|
4600
|
+
owner;
|
|
4601
|
+
value;
|
|
4602
|
+
invalidated = false;
|
|
4603
|
+
bindAuth(headers) {
|
|
4604
|
+
const authorization = headers.get("authorization") ?? "";
|
|
4605
|
+
let identity = authorization;
|
|
4606
|
+
try {
|
|
4607
|
+
const claims = record2(
|
|
4608
|
+
JSON.parse(
|
|
4609
|
+
Buffer.from(
|
|
4610
|
+
authorization.replace(/^Bearer /i, "").split(".")[1],
|
|
4611
|
+
"base64url"
|
|
4612
|
+
).toString("utf8")
|
|
4613
|
+
)
|
|
4614
|
+
);
|
|
4615
|
+
if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
|
|
4616
|
+
const account = record2(
|
|
4617
|
+
claims["https://api.openai.com/auth"]
|
|
4618
|
+
)?.chatgpt_account_id;
|
|
4619
|
+
identity = JSON.stringify([
|
|
4620
|
+
claims.iss,
|
|
4621
|
+
claims.sub,
|
|
4622
|
+
typeof claims.client_id === "string" ? claims.client_id : null,
|
|
4623
|
+
typeof account === "string" ? account : null
|
|
4624
|
+
]);
|
|
4625
|
+
}
|
|
4626
|
+
} catch {
|
|
4627
|
+
}
|
|
4628
|
+
const owner = (0, import_node_crypto5.createHash)("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
|
|
4629
|
+
const changed = this.owner !== void 0 && this.owner !== owner;
|
|
4630
|
+
if (changed) {
|
|
4631
|
+
this.value = void 0;
|
|
4632
|
+
this.invalidated = true;
|
|
4633
|
+
}
|
|
4634
|
+
this.owner = owner;
|
|
4635
|
+
return this.invalidated;
|
|
4636
|
+
}
|
|
4637
|
+
observe(value) {
|
|
4638
|
+
if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
|
|
4639
|
+
this.value = value;
|
|
4640
|
+
}
|
|
4641
|
+
requestHeaders() {
|
|
4642
|
+
return this.value ? { "x-codex-turn-state": this.value } : {};
|
|
4643
|
+
}
|
|
4644
|
+
};
|
|
4645
|
+
var CodexMetadataCollector = class {
|
|
4646
|
+
constructor(routing, onStatus) {
|
|
4647
|
+
this.routing = routing;
|
|
4648
|
+
this.onStatus = onStatus;
|
|
4649
|
+
}
|
|
4650
|
+
routing;
|
|
4651
|
+
onStatus;
|
|
4652
|
+
summary = {};
|
|
4653
|
+
outputStarted = false;
|
|
4654
|
+
fallbackModel;
|
|
4655
|
+
verificationNotified = false;
|
|
4656
|
+
beginAttempt() {
|
|
4657
|
+
this.clearBuffering();
|
|
4658
|
+
for (const key of Object.keys(this.summary))
|
|
4659
|
+
delete this.summary[key];
|
|
4660
|
+
this.outputStarted = false;
|
|
4661
|
+
this.fallbackModel = void 0;
|
|
4662
|
+
}
|
|
4663
|
+
observeHeaders(headers) {
|
|
4664
|
+
this.routing?.observe(headers.get("x-codex-turn-state"));
|
|
4665
|
+
const model = identifier(
|
|
4666
|
+
headers.get("openai-model") ?? headers.get("x-openai-model")
|
|
4667
|
+
);
|
|
4668
|
+
if (model) this.summary.server_model = model;
|
|
4669
|
+
this.fallbackModel = identifier(
|
|
4670
|
+
headers.get("x-codex-safety-buffering-faster-model")
|
|
4671
|
+
);
|
|
4672
|
+
}
|
|
4673
|
+
observeEvent(event) {
|
|
4674
|
+
const value = record2(event);
|
|
4675
|
+
if (!value) return;
|
|
4676
|
+
const response = record2(value.response);
|
|
4677
|
+
const model = identifier(
|
|
4678
|
+
headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
|
|
4679
|
+
);
|
|
4680
|
+
if (model) this.summary.server_model = model;
|
|
4681
|
+
const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
|
|
4682
|
+
if (value.type === "response.metadata")
|
|
4683
|
+
this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
|
|
4684
|
+
const verifications = metadata?.openai_verification_recommendation;
|
|
4685
|
+
if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
|
|
4686
|
+
this.summary.model_verifications = ["trusted_access_for_cyber"];
|
|
4687
|
+
if (!this.verificationNotified) {
|
|
4688
|
+
this.verificationNotified = true;
|
|
4689
|
+
this.emit({
|
|
4690
|
+
type: "llm.status",
|
|
4691
|
+
provider: "openai",
|
|
4692
|
+
kind: "verification",
|
|
4693
|
+
verification: "trusted_access_for_cyber"
|
|
4694
|
+
});
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
|
|
4698
|
+
this.summary.moderation_metadata_present = true;
|
|
4699
|
+
const buffering = record2(
|
|
4700
|
+
value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
|
|
4701
|
+
);
|
|
4702
|
+
if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
|
|
4703
|
+
const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
|
|
4704
|
+
const wasActive = this.summary.safety_buffering?.active;
|
|
4705
|
+
this.summary.safety_buffering = {
|
|
4706
|
+
active: !this.outputStarted,
|
|
4707
|
+
use_case_count: buffering.use_cases.length,
|
|
4708
|
+
reason_count: buffering.reasons.length,
|
|
4709
|
+
...faster ? { faster_model: faster } : {}
|
|
4710
|
+
};
|
|
4711
|
+
if (!this.outputStarted && !wasActive)
|
|
4712
|
+
this.emit({
|
|
4713
|
+
type: "llm.status",
|
|
4714
|
+
provider: "openai",
|
|
4715
|
+
kind: "buffering",
|
|
4716
|
+
active: true,
|
|
4717
|
+
...faster ? { faster_model: faster } : {}
|
|
4718
|
+
});
|
|
4719
|
+
}
|
|
4720
|
+
if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
|
|
4721
|
+
this.outputStarted = true;
|
|
4722
|
+
this.clearBuffering();
|
|
4723
|
+
}
|
|
4724
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
|
|
4725
|
+
this.clearBuffering();
|
|
4726
|
+
}
|
|
4727
|
+
finish() {
|
|
4728
|
+
this.clearBuffering();
|
|
4729
|
+
}
|
|
4730
|
+
snapshot() {
|
|
4731
|
+
return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
|
|
4732
|
+
}
|
|
4733
|
+
clearBuffering() {
|
|
4734
|
+
if (this.summary.safety_buffering?.active) {
|
|
4735
|
+
this.summary.safety_buffering.active = false;
|
|
4736
|
+
this.emit({
|
|
4737
|
+
type: "llm.status",
|
|
4738
|
+
provider: "openai",
|
|
4739
|
+
kind: "buffering",
|
|
4740
|
+
active: false
|
|
4741
|
+
});
|
|
4742
|
+
}
|
|
4743
|
+
}
|
|
4744
|
+
emit(event) {
|
|
4745
|
+
try {
|
|
4746
|
+
this.onStatus?.(event);
|
|
4747
|
+
} catch {
|
|
4748
|
+
}
|
|
4749
|
+
}
|
|
4750
|
+
};
|
|
4751
|
+
|
|
4752
|
+
// src/llm/openai/http-transport.ts
|
|
3806
4753
|
var import_openai4 = __toESM(require("openai"), 1);
|
|
3807
4754
|
|
|
3808
4755
|
// src/llm/openai/response-utils.ts
|
|
3809
|
-
var
|
|
4756
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null;
|
|
3810
4757
|
var stringifyUnknown3 = (value) => {
|
|
3811
4758
|
if (value == null) return "";
|
|
3812
4759
|
if (typeof value === "string") return value;
|
|
@@ -3821,7 +4768,7 @@ var formatOtherPart2 = (part) => {
|
|
|
3821
4768
|
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
3822
4769
|
};
|
|
3823
4770
|
var isOpenAiInputContent = (value) => {
|
|
3824
|
-
if (!
|
|
4771
|
+
if (!isRecord3(value)) return false;
|
|
3825
4772
|
const type = value.type;
|
|
3826
4773
|
if (type === "input_text") {
|
|
3827
4774
|
return typeof value.text === "string";
|
|
@@ -3846,12 +4793,12 @@ var extractOutputText = (items) => {
|
|
|
3846
4793
|
}
|
|
3847
4794
|
return texts.join("");
|
|
3848
4795
|
};
|
|
3849
|
-
var getRecordString = (
|
|
3850
|
-
const value =
|
|
4796
|
+
var getRecordString = (record3, key) => {
|
|
4797
|
+
const value = record3[key];
|
|
3851
4798
|
return typeof value === "string" ? value : void 0;
|
|
3852
4799
|
};
|
|
3853
|
-
var getRecordNumber = (
|
|
3854
|
-
const value =
|
|
4800
|
+
var getRecordNumber = (record3, key) => {
|
|
4801
|
+
const value = record3[key];
|
|
3855
4802
|
return typeof value === "number" ? value : void 0;
|
|
3856
4803
|
};
|
|
3857
4804
|
var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
|
|
@@ -3861,6 +4808,10 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3861
4808
|
sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
|
|
3862
4809
|
};
|
|
3863
4810
|
const eventRecord = event;
|
|
4811
|
+
const metadata = new CodexMetadataCollector();
|
|
4812
|
+
metadata.observeEvent(event);
|
|
4813
|
+
const summary = metadata.snapshot();
|
|
4814
|
+
if (summary) payload.metadata_summary = summary;
|
|
3864
4815
|
const outputIndex = getRecordNumber(eventRecord, "output_index");
|
|
3865
4816
|
if (outputIndex !== void 0) {
|
|
3866
4817
|
payload.output_index = outputIndex;
|
|
@@ -3881,7 +4832,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3881
4832
|
case "response.output_item.added":
|
|
3882
4833
|
case "response.output_item.done": {
|
|
3883
4834
|
const item = eventRecord.item;
|
|
3884
|
-
if (
|
|
4835
|
+
if (isRecord3(item)) {
|
|
3885
4836
|
payload.item_type = getRecordString(item, "type");
|
|
3886
4837
|
payload.item_role = getRecordString(item, "role");
|
|
3887
4838
|
}
|
|
@@ -3889,7 +4840,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3889
4840
|
}
|
|
3890
4841
|
case "response.content_part.added": {
|
|
3891
4842
|
const part = eventRecord.part;
|
|
3892
|
-
if (
|
|
4843
|
+
if (isRecord3(part)) {
|
|
3893
4844
|
payload.part_type = getRecordString(part, "type");
|
|
3894
4845
|
if (part.type === "output_text") {
|
|
3895
4846
|
const text = getRecordString(part, "text") ?? "";
|
|
@@ -3901,7 +4852,7 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3901
4852
|
}
|
|
3902
4853
|
case "response.completed": {
|
|
3903
4854
|
const response = eventRecord.response;
|
|
3904
|
-
if (
|
|
4855
|
+
if (isRecord3(response)) {
|
|
3905
4856
|
payload.response_id = getRecordString(response, "id");
|
|
3906
4857
|
const status = response.status;
|
|
3907
4858
|
payload.response_status = typeof status === "string" ? status : null;
|
|
@@ -3912,13 +4863,13 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3912
4863
|
const outputText = response.output_text;
|
|
3913
4864
|
payload.response_output_text = typeof outputText === "string" ? clipDebugText(outputText) : null;
|
|
3914
4865
|
const usage = response.usage;
|
|
3915
|
-
if (
|
|
4866
|
+
if (isRecord3(usage)) {
|
|
3916
4867
|
payload.response_output_tokens = getRecordNumber(
|
|
3917
4868
|
usage,
|
|
3918
4869
|
"output_tokens"
|
|
3919
4870
|
);
|
|
3920
4871
|
const outputDetails = usage.output_tokens_details;
|
|
3921
|
-
if (
|
|
4872
|
+
if (isRecord3(outputDetails)) {
|
|
3922
4873
|
payload.response_reasoning_tokens = getRecordNumber(
|
|
3923
4874
|
outputDetails,
|
|
3924
4875
|
"reasoning_tokens"
|
|
@@ -3989,7 +4940,7 @@ var toFunctionCallOutput = (content) => {
|
|
|
3989
4940
|
};
|
|
3990
4941
|
|
|
3991
4942
|
// src/llm/openai/response-accumulator.ts
|
|
3992
|
-
var
|
|
4943
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
3993
4944
|
var envTruthy2 = (value) => {
|
|
3994
4945
|
if (!value) return false;
|
|
3995
4946
|
const normalized = value.trim().toLowerCase();
|
|
@@ -4014,6 +4965,9 @@ var OpenAiResponseAccumulator = class {
|
|
|
4014
4965
|
terminalResponse = null;
|
|
4015
4966
|
outputItems = [];
|
|
4016
4967
|
observeEvent(event) {
|
|
4968
|
+
const type = event.type;
|
|
4969
|
+
if (type === "response.metadata" || type === "codex.response.metadata")
|
|
4970
|
+
return;
|
|
4017
4971
|
switch (event.type) {
|
|
4018
4972
|
case "response.created":
|
|
4019
4973
|
case "response.queued":
|
|
@@ -4182,7 +5136,7 @@ var OpenAiResponseAccumulator = class {
|
|
|
4182
5136
|
}
|
|
4183
5137
|
addContentPart(outputIndex, contentIndex, part) {
|
|
4184
5138
|
const output = this.getOutputItem(outputIndex);
|
|
4185
|
-
if (!output || !
|
|
5139
|
+
if (!output || !isRecord4(part)) {
|
|
4186
5140
|
return;
|
|
4187
5141
|
}
|
|
4188
5142
|
if (output.type === "message" && part.type !== "reasoning_text") {
|
|
@@ -4365,22 +5319,64 @@ var OpenAiResponseAccumulator = class {
|
|
|
4365
5319
|
};
|
|
4366
5320
|
|
|
4367
5321
|
// src/llm/openai/http-transport.ts
|
|
4368
|
-
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
|
|
5322
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
|
|
4369
5323
|
const streamRequest = {
|
|
4370
5324
|
...request,
|
|
4371
5325
|
stream: true
|
|
4372
5326
|
};
|
|
4373
|
-
const
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
5327
|
+
const options = signal || sessionIdHeader ? {
|
|
5328
|
+
...signal ? { signal } : {},
|
|
5329
|
+
...sessionIdHeader ? {
|
|
5330
|
+
headers: {
|
|
5331
|
+
session_id: sessionIdHeader
|
|
5332
|
+
}
|
|
5333
|
+
} : {}
|
|
5334
|
+
} : void 0;
|
|
5335
|
+
if (isCodexBackend(client.baseURL)) {
|
|
5336
|
+
codex?.metadata.beginAttempt();
|
|
5337
|
+
const sourceFetch = client.fetch;
|
|
5338
|
+
let ownershipError;
|
|
5339
|
+
const requestClient = codex ? client.withOptions({
|
|
5340
|
+
fetch: async (input, init) => {
|
|
5341
|
+
const headers = new Headers(init?.headers);
|
|
5342
|
+
if (codex.routing?.bindAuth(headers)) {
|
|
5343
|
+
ownershipError = createProviderValidationError(
|
|
5344
|
+
"openai",
|
|
5345
|
+
"OpenAI authentication changed; start a new run"
|
|
5346
|
+
);
|
|
5347
|
+
throw ownershipError;
|
|
4380
5348
|
}
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
5349
|
+
for (const [key, value] of Object.entries(
|
|
5350
|
+
codex.routing?.requestHeaders() ?? {}
|
|
5351
|
+
))
|
|
5352
|
+
headers.set(key, value);
|
|
5353
|
+
const response = await sourceFetch(input, { ...init, headers });
|
|
5354
|
+
codex.metadata.observeHeaders(response.headers);
|
|
5355
|
+
return response;
|
|
5356
|
+
}
|
|
5357
|
+
}) : client;
|
|
5358
|
+
const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
|
|
5359
|
+
throw ownershipError ?? error;
|
|
5360
|
+
});
|
|
5361
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
5362
|
+
for await (const event of stream2) {
|
|
5363
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5364
|
+
codex?.metadata.observeEvent(event);
|
|
5365
|
+
await onEvent?.(event);
|
|
5366
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5367
|
+
if (event.type === "response.failed") {
|
|
5368
|
+
throw event.response.error ?? new Error("OpenAI stream failed");
|
|
5369
|
+
}
|
|
5370
|
+
if (event.type === "error") throw event;
|
|
5371
|
+
accumulator.observeEvent(event);
|
|
5372
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
5373
|
+
return accumulator.buildResponse(event.response);
|
|
5374
|
+
}
|
|
5375
|
+
}
|
|
5376
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5377
|
+
throw new Error("OpenAI stream ended without a terminal response");
|
|
5378
|
+
}
|
|
5379
|
+
const stream = client.responses.stream(streamRequest, options);
|
|
4384
5380
|
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
4385
5381
|
const accumulator = new OpenAiResponseAccumulator();
|
|
4386
5382
|
for await (const event of stream) {
|
|
@@ -4431,12 +5427,12 @@ var formatOtherPart3 = (part) => {
|
|
|
4431
5427
|
};
|
|
4432
5428
|
var isOpenAIAssistantInputContent = (value) => {
|
|
4433
5429
|
if (!value || typeof value !== "object") return false;
|
|
4434
|
-
const
|
|
4435
|
-
if (
|
|
4436
|
-
return typeof
|
|
5430
|
+
const record3 = value;
|
|
5431
|
+
if (record3.type === "output_text") {
|
|
5432
|
+
return typeof record3.text === "string";
|
|
4437
5433
|
}
|
|
4438
|
-
if (
|
|
4439
|
-
return typeof
|
|
5434
|
+
if (record3.type === "refusal") {
|
|
5435
|
+
return typeof record3.refusal === "string";
|
|
4440
5436
|
}
|
|
4441
5437
|
return false;
|
|
4442
5438
|
};
|
|
@@ -4454,8 +5450,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
4454
5450
|
if (!value || typeof value !== "object") {
|
|
4455
5451
|
return false;
|
|
4456
5452
|
}
|
|
4457
|
-
const
|
|
4458
|
-
return
|
|
5453
|
+
const record3 = value;
|
|
5454
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
4459
5455
|
};
|
|
4460
5456
|
var toReplayableFunctionCallItemId = (value) => {
|
|
4461
5457
|
if (typeof value !== "string") {
|
|
@@ -4506,14 +5502,14 @@ var extractReasoningText = (item) => {
|
|
|
4506
5502
|
};
|
|
4507
5503
|
var extractWebSearchSummary = (item) => {
|
|
4508
5504
|
const parts = [`WebSearch status=${item.status}`];
|
|
4509
|
-
const
|
|
4510
|
-
const queries = Array.isArray(
|
|
5505
|
+
const record3 = item;
|
|
5506
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
4511
5507
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
4512
5508
|
) : [];
|
|
4513
5509
|
if (queries.length) {
|
|
4514
5510
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
4515
5511
|
}
|
|
4516
|
-
const sources = Array.isArray(
|
|
5512
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
4517
5513
|
if (sources.length) {
|
|
4518
5514
|
parts.push(`sources=${sources.length}`);
|
|
4519
5515
|
}
|
|
@@ -4684,6 +5680,9 @@ function toChatInvokeCompletion2(response, meta) {
|
|
|
4684
5680
|
input_tokens: response.usage.input_tokens,
|
|
4685
5681
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
4686
5682
|
output_tokens: response.usage.output_tokens,
|
|
5683
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
5684
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
5685
|
+
} : {},
|
|
4687
5686
|
total_tokens: response.usage.total_tokens
|
|
4688
5687
|
} : null;
|
|
4689
5688
|
const messages = toMessageSequence(response);
|
|
@@ -4789,6 +5788,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
|
4789
5788
|
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
4790
5789
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
4791
5790
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
5791
|
+
var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
|
|
5792
|
+
constructor() {
|
|
5793
|
+
super({
|
|
5794
|
+
...buildProviderFailure("openai", "validation"),
|
|
5795
|
+
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."
|
|
5796
|
+
});
|
|
5797
|
+
}
|
|
5798
|
+
};
|
|
4792
5799
|
var resolveTimeoutMs = (value, fallbackMs) => {
|
|
4793
5800
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
4794
5801
|
return fallbackMs;
|
|
@@ -4870,6 +5877,8 @@ var OpenAiWsTransport = class {
|
|
|
4870
5877
|
);
|
|
4871
5878
|
}
|
|
4872
5879
|
async invoke(args) {
|
|
5880
|
+
const timing = new LlmStreamTiming();
|
|
5881
|
+
args.codex?.metadata.beginAttempt();
|
|
4873
5882
|
await this.prepareClientForWsHandshake();
|
|
4874
5883
|
const wsOptionsHeaders = {
|
|
4875
5884
|
...this.getClientDefaultHeaders(),
|
|
@@ -4878,6 +5887,19 @@ var OpenAiWsTransport = class {
|
|
|
4878
5887
|
if (args.sessionIdHeader) {
|
|
4879
5888
|
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
4880
5889
|
}
|
|
5890
|
+
if (args.codex?.routing) {
|
|
5891
|
+
const authHeaders = new Headers(wsOptionsHeaders);
|
|
5892
|
+
authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
|
|
5893
|
+
if (args.codex.routing.bindAuth(authHeaders)) {
|
|
5894
|
+
if (args.ws)
|
|
5895
|
+
this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
|
|
5896
|
+
throw createProviderValidationError(
|
|
5897
|
+
"openai",
|
|
5898
|
+
"OpenAI authentication changed; start a new run"
|
|
5899
|
+
);
|
|
5900
|
+
}
|
|
5901
|
+
Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
|
|
5902
|
+
}
|
|
4881
5903
|
const wsOptions = { headers: wsOptionsHeaders };
|
|
4882
5904
|
const ownsWs = !args.ws;
|
|
4883
5905
|
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new import_ws.ResponsesWS(
|
|
@@ -4888,6 +5910,15 @@ var OpenAiWsTransport = class {
|
|
|
4888
5910
|
ws.on("error", () => {
|
|
4889
5911
|
});
|
|
4890
5912
|
}
|
|
5913
|
+
const removeUpgrade = args.codex ? this.addNativeSocketListener(
|
|
5914
|
+
this.getNativeSocket(ws),
|
|
5915
|
+
"upgrade",
|
|
5916
|
+
(response) => {
|
|
5917
|
+
const headers = response?.headers;
|
|
5918
|
+
if (headers)
|
|
5919
|
+
args.codex?.metadata.observeHeaders(new Headers(headers));
|
|
5920
|
+
}
|
|
5921
|
+
) : void 0;
|
|
4891
5922
|
try {
|
|
4892
5923
|
await this.waitForWsOpen(ws, args.signal);
|
|
4893
5924
|
const closeWs = () => {
|
|
@@ -4896,11 +5927,14 @@ var OpenAiWsTransport = class {
|
|
|
4896
5927
|
const responseWaiter = this.createResponsePromise({
|
|
4897
5928
|
ws,
|
|
4898
5929
|
signal: args.signal,
|
|
4899
|
-
closeWs
|
|
5930
|
+
closeWs,
|
|
5931
|
+
timing,
|
|
5932
|
+
metadata: args.codex?.metadata
|
|
4900
5933
|
});
|
|
4901
5934
|
const responseCreateEvent = {
|
|
4902
5935
|
type: "response.create",
|
|
4903
|
-
...args.request
|
|
5936
|
+
...args.request,
|
|
5937
|
+
...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
|
|
4904
5938
|
};
|
|
4905
5939
|
if (!responseWaiter.isSettled()) {
|
|
4906
5940
|
try {
|
|
@@ -4910,12 +5944,14 @@ var OpenAiWsTransport = class {
|
|
|
4910
5944
|
}
|
|
4911
5945
|
}
|
|
4912
5946
|
const response = await responseWaiter.responsePromise;
|
|
4913
|
-
return { response, ws };
|
|
5947
|
+
return { response, ws, timing: timing.finish() };
|
|
4914
5948
|
} catch (error) {
|
|
4915
5949
|
if (ownsWs) {
|
|
4916
5950
|
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
4917
5951
|
}
|
|
4918
5952
|
throw error;
|
|
5953
|
+
} finally {
|
|
5954
|
+
removeUpgrade?.();
|
|
4919
5955
|
}
|
|
4920
5956
|
}
|
|
4921
5957
|
createResponsePromise(args) {
|
|
@@ -5005,6 +6041,7 @@ var OpenAiWsTransport = class {
|
|
|
5005
6041
|
rejectOnce(error);
|
|
5006
6042
|
};
|
|
5007
6043
|
const resolveFromTerminalEvent = (event, type) => {
|
|
6044
|
+
args.timing.complete();
|
|
5008
6045
|
const response = event?.response;
|
|
5009
6046
|
if (response && typeof response === "object") {
|
|
5010
6047
|
accumulator.observeTerminalResponse(response);
|
|
@@ -5027,6 +6064,9 @@ var OpenAiWsTransport = class {
|
|
|
5027
6064
|
);
|
|
5028
6065
|
};
|
|
5029
6066
|
const onEvent = (event) => {
|
|
6067
|
+
if (settled) return;
|
|
6068
|
+
args.metadata?.observeEvent(event);
|
|
6069
|
+
args.timing.observeResponsesEvent(event);
|
|
5030
6070
|
const eventType = this.extractResponsesEventType(event);
|
|
5031
6071
|
if (!eventType) {
|
|
5032
6072
|
return;
|
|
@@ -5075,7 +6115,7 @@ var OpenAiWsTransport = class {
|
|
|
5075
6115
|
const onClose = (event) => {
|
|
5076
6116
|
const closeCode = this.extractWsCloseCode(event);
|
|
5077
6117
|
rejectOnce(
|
|
5078
|
-
new Error(
|
|
6118
|
+
closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
|
|
5079
6119
|
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
5080
6120
|
)
|
|
5081
6121
|
);
|
|
@@ -5344,6 +6384,8 @@ var OpenAiWsTransport = class {
|
|
|
5344
6384
|
return void 0;
|
|
5345
6385
|
}
|
|
5346
6386
|
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
6387
|
+
if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
|
|
6388
|
+
return `${key}:[redacted]`;
|
|
5347
6389
|
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
5348
6390
|
return `${key}:${text}`;
|
|
5349
6391
|
});
|
|
@@ -5548,7 +6590,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
|
5548
6590
|
};
|
|
5549
6591
|
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
5550
6592
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
5551
|
-
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
5552
6593
|
var ChatOpenAI = class {
|
|
5553
6594
|
provider = PROVIDER_NAME5;
|
|
5554
6595
|
model;
|
|
@@ -5567,8 +6608,9 @@ var ChatOpenAI = class {
|
|
|
5567
6608
|
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
5568
6609
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
5569
6610
|
wsReconnectCount = 0;
|
|
6611
|
+
codexTurns = /* @__PURE__ */ new Map();
|
|
5570
6612
|
constructor(options = {}) {
|
|
5571
|
-
this.client = options.client ?? new
|
|
6613
|
+
this.client = options.client ?? new import_openai5.default({
|
|
5572
6614
|
...options.clientOptions ?? {},
|
|
5573
6615
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5574
6616
|
});
|
|
@@ -5651,17 +6693,32 @@ var ChatOpenAI = class {
|
|
|
5651
6693
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
5652
6694
|
const requestMeta = {
|
|
5653
6695
|
model: String(request.model ?? this.providerModel),
|
|
5654
|
-
instructionsHash: (0,
|
|
5655
|
-
toolsHash: (0,
|
|
6696
|
+
instructionsHash: (0, import_node_crypto6.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
6697
|
+
toolsHash: (0, import_node_crypto6.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
5656
6698
|
};
|
|
5657
|
-
const
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
6699
|
+
const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
|
|
6700
|
+
let transportResult;
|
|
6701
|
+
try {
|
|
6702
|
+
transportResult = await this.invokeWithTransport({
|
|
6703
|
+
request,
|
|
6704
|
+
sessionKey: context?.sessionKey,
|
|
6705
|
+
sessionIdHeader,
|
|
6706
|
+
signal,
|
|
6707
|
+
debugSeq,
|
|
6708
|
+
requestMeta,
|
|
6709
|
+
...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
|
|
6710
|
+
});
|
|
6711
|
+
} finally {
|
|
6712
|
+
codex?.metadata?.finish();
|
|
6713
|
+
}
|
|
6714
|
+
const codexMetadata = codex?.metadata?.snapshot();
|
|
6715
|
+
if (codex) {
|
|
6716
|
+
const { headers: _headers, ...response } = transportResult.response;
|
|
6717
|
+
transportResult.response = {
|
|
6718
|
+
...response,
|
|
6719
|
+
...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
|
|
6720
|
+
};
|
|
6721
|
+
}
|
|
5665
6722
|
await this.debugResponseIfEnabled(
|
|
5666
6723
|
transportResult.response,
|
|
5667
6724
|
debugSeq,
|
|
@@ -5685,7 +6742,42 @@ var ChatOpenAI = class {
|
|
|
5685
6742
|
debugSeq,
|
|
5686
6743
|
transportResult.transport
|
|
5687
6744
|
);
|
|
5688
|
-
return
|
|
6745
|
+
return {
|
|
6746
|
+
...completion,
|
|
6747
|
+
...codexMetadata ? {
|
|
6748
|
+
provider_meta: {
|
|
6749
|
+
...completion.provider_meta,
|
|
6750
|
+
codex_metadata: codexMetadata
|
|
6751
|
+
}
|
|
6752
|
+
} : {},
|
|
6753
|
+
...transportResult.timing ? { timing: transportResult.timing } : {}
|
|
6754
|
+
};
|
|
6755
|
+
}
|
|
6756
|
+
createCodexMetadata(context) {
|
|
6757
|
+
const routing = this.resolveCodexTurn(context);
|
|
6758
|
+
return {
|
|
6759
|
+
routing,
|
|
6760
|
+
metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
|
|
6761
|
+
};
|
|
6762
|
+
}
|
|
6763
|
+
resolveCodexTurn(context) {
|
|
6764
|
+
if (!context?.turnKey) return void 0;
|
|
6765
|
+
const key = context.sessionKey ?? context.turnKey;
|
|
6766
|
+
let state = this.codexTurns.get(key);
|
|
6767
|
+
if (!state || state.turnKey !== context.turnKey) {
|
|
6768
|
+
this.clearWsSessionState(key, "new_turn");
|
|
6769
|
+
state = { turnKey: context.turnKey, routing: new CodexTurnState() };
|
|
6770
|
+
this.codexTurns.delete(key);
|
|
6771
|
+
this.codexTurns.set(key, state);
|
|
6772
|
+
if (this.codexTurns.size > 16) {
|
|
6773
|
+
const oldest = this.codexTurns.keys().next().value;
|
|
6774
|
+
if (oldest !== void 0) {
|
|
6775
|
+
this.codexTurns.delete(oldest);
|
|
6776
|
+
this.clearWsSessionState(oldest, "turn_state_evicted");
|
|
6777
|
+
}
|
|
6778
|
+
}
|
|
6779
|
+
}
|
|
6780
|
+
return state.routing;
|
|
5689
6781
|
}
|
|
5690
6782
|
onHistoryCompacted(context) {
|
|
5691
6783
|
const sessionKey = context?.sessionKey;
|
|
@@ -5703,6 +6795,7 @@ var ChatOpenAI = class {
|
|
|
5703
6795
|
this.evictIdleWsSessionState();
|
|
5704
6796
|
if (this.websocketMode === "off") {
|
|
5705
6797
|
return this.invokeHttpTransportWithDebug({
|
|
6798
|
+
codex: args.codex,
|
|
5706
6799
|
request: args.request,
|
|
5707
6800
|
debugSeq: args.debugSeq,
|
|
5708
6801
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5718,6 +6811,7 @@ var ChatOpenAI = class {
|
|
|
5718
6811
|
);
|
|
5719
6812
|
}
|
|
5720
6813
|
return this.invokeHttpTransportWithDebug({
|
|
6814
|
+
codex: args.codex,
|
|
5721
6815
|
request: args.request,
|
|
5722
6816
|
debugSeq: args.debugSeq,
|
|
5723
6817
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5728,6 +6822,7 @@ var ChatOpenAI = class {
|
|
|
5728
6822
|
}
|
|
5729
6823
|
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
5730
6824
|
return this.invokeHttpTransportWithDebug({
|
|
6825
|
+
codex: args.codex,
|
|
5731
6826
|
request: args.request,
|
|
5732
6827
|
debugSeq: args.debugSeq,
|
|
5733
6828
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5737,7 +6832,7 @@ var ChatOpenAI = class {
|
|
|
5737
6832
|
});
|
|
5738
6833
|
}
|
|
5739
6834
|
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
5740
|
-
const hasReusableWs = this.isWsConnectionReusable(wsState.ws)
|
|
6835
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
|
|
5741
6836
|
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
5742
6837
|
const incrementalInput = this.getIncrementalInput(
|
|
5743
6838
|
wsState.lastInput,
|
|
@@ -5785,7 +6880,8 @@ var ChatOpenAI = class {
|
|
|
5785
6880
|
wsExecutionPlan.chainReset,
|
|
5786
6881
|
wsExecutionPlan.wsInputMode
|
|
5787
6882
|
);
|
|
5788
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6883
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6884
|
+
codex: args.codex,
|
|
5789
6885
|
request: wsExecutionPlan.request,
|
|
5790
6886
|
signal: args.signal,
|
|
5791
6887
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5801,12 +6897,17 @@ var ChatOpenAI = class {
|
|
|
5801
6897
|
return {
|
|
5802
6898
|
response,
|
|
5803
6899
|
transport: "ws_mode",
|
|
6900
|
+
...timing ? { timing } : {},
|
|
5804
6901
|
fallbackUsed: false,
|
|
5805
6902
|
chainReset: wsExecutionPlan.chainReset,
|
|
5806
6903
|
wsInputMode: wsExecutionPlan.wsInputMode
|
|
5807
6904
|
};
|
|
5808
6905
|
} catch (error) {
|
|
5809
6906
|
let failure = error;
|
|
6907
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6908
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6909
|
+
throw failure;
|
|
6910
|
+
}
|
|
5810
6911
|
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
5811
6912
|
const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
|
|
5812
6913
|
this.closeWsWithoutMaskingPrimaryError(
|
|
@@ -5824,7 +6925,8 @@ var ChatOpenAI = class {
|
|
|
5824
6925
|
true,
|
|
5825
6926
|
retryWsInputMode
|
|
5826
6927
|
);
|
|
5827
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6928
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6929
|
+
codex: args.codex,
|
|
5828
6930
|
request: args.request,
|
|
5829
6931
|
signal: args.signal,
|
|
5830
6932
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5841,6 +6943,7 @@ var ChatOpenAI = class {
|
|
|
5841
6943
|
return {
|
|
5842
6944
|
response,
|
|
5843
6945
|
transport: "ws_mode",
|
|
6946
|
+
...timing ? { timing } : {},
|
|
5844
6947
|
fallbackUsed: false,
|
|
5845
6948
|
chainReset: true,
|
|
5846
6949
|
wsInputMode: retryWsInputMode
|
|
@@ -5849,9 +6952,13 @@ var ChatOpenAI = class {
|
|
|
5849
6952
|
failure = retryError;
|
|
5850
6953
|
}
|
|
5851
6954
|
}
|
|
6955
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6956
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6957
|
+
throw failure;
|
|
6958
|
+
}
|
|
5852
6959
|
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
5853
6960
|
const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
|
|
5854
|
-
const shouldDisableWsForSession = wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
6961
|
+
const shouldDisableWsForSession = failure instanceof OpenAiWsMessageTooLargeError || wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
5855
6962
|
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
5856
6963
|
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
5857
6964
|
this.wsDisabledUntilBySessionKey.set(
|
|
@@ -5864,6 +6971,7 @@ var ChatOpenAI = class {
|
|
|
5864
6971
|
}
|
|
5865
6972
|
this.wsReconnectCount += 1;
|
|
5866
6973
|
return this.invokeHttpTransportWithDebug({
|
|
6974
|
+
codex: args.codex,
|
|
5867
6975
|
request: args.request,
|
|
5868
6976
|
debugSeq: args.debugSeq,
|
|
5869
6977
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5884,16 +6992,23 @@ var ChatOpenAI = class {
|
|
|
5884
6992
|
args.chainReset,
|
|
5885
6993
|
args.wsInputMode
|
|
5886
6994
|
);
|
|
6995
|
+
const timing = new LlmStreamTiming();
|
|
6996
|
+
const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
|
|
5887
6997
|
const response = await invokeOpenAiHttp(
|
|
5888
6998
|
this.client,
|
|
5889
6999
|
args.request,
|
|
5890
7000
|
args.signal,
|
|
5891
7001
|
args.sessionIdHeader,
|
|
5892
|
-
|
|
7002
|
+
(event) => {
|
|
7003
|
+
timing.observeResponsesEvent(event);
|
|
7004
|
+
return debugObserver?.(event);
|
|
7005
|
+
},
|
|
7006
|
+
args.codex
|
|
5893
7007
|
);
|
|
5894
7008
|
return {
|
|
5895
7009
|
response,
|
|
5896
7010
|
transport: "http_stream",
|
|
7011
|
+
timing: timing.finish(),
|
|
5897
7012
|
fallbackUsed: args.fallbackUsed,
|
|
5898
7013
|
chainReset: args.chainReset
|
|
5899
7014
|
};
|
|
@@ -5931,12 +7046,6 @@ var ChatOpenAI = class {
|
|
|
5931
7046
|
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
5932
7047
|
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
5933
7048
|
}
|
|
5934
|
-
isWsConnectionReuseExpired(lastUsedAt) {
|
|
5935
|
-
if (typeof lastUsedAt !== "number") {
|
|
5936
|
-
return false;
|
|
5937
|
-
}
|
|
5938
|
-
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
5939
|
-
}
|
|
5940
7049
|
isWsReconnectRetryableError(error) {
|
|
5941
7050
|
if (!(error instanceof Error)) {
|
|
5942
7051
|
return false;
|
|
@@ -6015,14 +7124,14 @@ var ChatOpenAI = class {
|
|
|
6015
7124
|
return;
|
|
6016
7125
|
}
|
|
6017
7126
|
const payload = safeJsonStringify(request);
|
|
6018
|
-
const hash = (0,
|
|
6019
|
-
const toolsHash = (0,
|
|
6020
|
-
const instructionsHash = (0,
|
|
7127
|
+
const hash = (0, import_node_crypto6.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7128
|
+
const toolsHash = (0, import_node_crypto6.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7129
|
+
const instructionsHash = (0, import_node_crypto6.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6021
7130
|
const previous = this.lastDebugRequestPayload;
|
|
6022
7131
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6023
7132
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6024
7133
|
if (settings.enabled) {
|
|
6025
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
7134
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto6.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6026
7135
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
6027
7136
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
6028
7137
|
console.error(
|
|
@@ -6115,11 +7224,11 @@ var ChatOpenAI = class {
|
|
|
6115
7224
|
};
|
|
6116
7225
|
|
|
6117
7226
|
// src/llm/openrouter/chat.ts
|
|
6118
|
-
var
|
|
6119
|
-
var
|
|
7227
|
+
var import_node_crypto7 = require("crypto");
|
|
7228
|
+
var import_openai7 = __toESM(require("openai"), 1);
|
|
6120
7229
|
|
|
6121
7230
|
// src/llm/openrouter/response-utils.ts
|
|
6122
|
-
var
|
|
7231
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null;
|
|
6123
7232
|
var stringifyUnknown5 = (value) => {
|
|
6124
7233
|
if (value == null) return "";
|
|
6125
7234
|
if (typeof value === "string") return value;
|
|
@@ -6134,7 +7243,7 @@ var formatOtherPart4 = (part) => {
|
|
|
6134
7243
|
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
6135
7244
|
};
|
|
6136
7245
|
var isResponsesApiInputContent = (value) => {
|
|
6137
|
-
if (!
|
|
7246
|
+
if (!isRecord5(value)) return false;
|
|
6138
7247
|
const type = value.type;
|
|
6139
7248
|
if (type === "input_text") {
|
|
6140
7249
|
return typeof value.text === "string";
|
|
@@ -6236,12 +7345,12 @@ var formatOtherPart5 = (part) => {
|
|
|
6236
7345
|
};
|
|
6237
7346
|
var isOpenAIAssistantInputContent2 = (value) => {
|
|
6238
7347
|
if (!value || typeof value !== "object") return false;
|
|
6239
|
-
const
|
|
6240
|
-
if (
|
|
6241
|
-
return typeof
|
|
7348
|
+
const record3 = value;
|
|
7349
|
+
if (record3.type === "output_text") {
|
|
7350
|
+
return typeof record3.text === "string";
|
|
6242
7351
|
}
|
|
6243
|
-
if (
|
|
6244
|
-
return typeof
|
|
7352
|
+
if (record3.type === "refusal") {
|
|
7353
|
+
return typeof record3.refusal === "string";
|
|
6245
7354
|
}
|
|
6246
7355
|
return false;
|
|
6247
7356
|
};
|
|
@@ -6249,8 +7358,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
|
6249
7358
|
if (!value || typeof value !== "object") {
|
|
6250
7359
|
return false;
|
|
6251
7360
|
}
|
|
6252
|
-
const
|
|
6253
|
-
return
|
|
7361
|
+
const record3 = value;
|
|
7362
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
6254
7363
|
};
|
|
6255
7364
|
var toReplayableFunctionCallItemId2 = (value) => {
|
|
6256
7365
|
if (typeof value !== "string") {
|
|
@@ -6301,14 +7410,14 @@ var extractReasoningText2 = (item) => {
|
|
|
6301
7410
|
};
|
|
6302
7411
|
var extractWebSearchSummary2 = (item) => {
|
|
6303
7412
|
const parts = [`WebSearch status=${item.status}`];
|
|
6304
|
-
const
|
|
6305
|
-
const queries = Array.isArray(
|
|
7413
|
+
const record3 = item;
|
|
7414
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
6306
7415
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
6307
7416
|
) : [];
|
|
6308
7417
|
if (queries.length) {
|
|
6309
7418
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
6310
7419
|
}
|
|
6311
|
-
const sources = Array.isArray(
|
|
7420
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
6312
7421
|
if (sources.length) {
|
|
6313
7422
|
parts.push(`sources=${sources.length}`);
|
|
6314
7423
|
}
|
|
@@ -6475,6 +7584,9 @@ function toChatInvokeCompletion3(response, meta) {
|
|
|
6475
7584
|
input_tokens: response.usage.input_tokens,
|
|
6476
7585
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
6477
7586
|
output_tokens: response.usage.output_tokens,
|
|
7587
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
7588
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
7589
|
+
} : {},
|
|
6478
7590
|
total_tokens: response.usage.total_tokens
|
|
6479
7591
|
} : null;
|
|
6480
7592
|
const messages = toMessageSequence2(response);
|
|
@@ -6584,7 +7696,7 @@ var ChatOpenRouter = class {
|
|
|
6584
7696
|
debugInvokeSeq = 0;
|
|
6585
7697
|
lastDebugRequestPayload = null;
|
|
6586
7698
|
constructor(options = {}) {
|
|
6587
|
-
this.client = options.client ?? new
|
|
7699
|
+
this.client = options.client ?? new import_openai7.default({
|
|
6588
7700
|
baseURL: OPENROUTER_BASE_URL,
|
|
6589
7701
|
...options.clientOptions ?? {},
|
|
6590
7702
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
@@ -6656,7 +7768,8 @@ var ChatOpenRouter = class {
|
|
|
6656
7768
|
...request,
|
|
6657
7769
|
stream: true
|
|
6658
7770
|
};
|
|
6659
|
-
const
|
|
7771
|
+
const timing = new LlmStreamTiming();
|
|
7772
|
+
const stream = this.client.responses.stream(
|
|
6660
7773
|
streamRequest,
|
|
6661
7774
|
signal || sessionIdHeader ? {
|
|
6662
7775
|
...signal ? { signal } : {},
|
|
@@ -6666,13 +7779,21 @@ var ChatOpenRouter = class {
|
|
|
6666
7779
|
}
|
|
6667
7780
|
} : {}
|
|
6668
7781
|
} : void 0
|
|
6669
|
-
)
|
|
7782
|
+
);
|
|
7783
|
+
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
7784
|
+
for await (const event of stream) timing.observeResponsesEvent(event);
|
|
7785
|
+
}
|
|
7786
|
+
const response = await stream.finalResponse();
|
|
7787
|
+
const measuredTiming = timing.finish();
|
|
6670
7788
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6671
|
-
return
|
|
6672
|
-
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
7789
|
+
return {
|
|
7790
|
+
...toChatInvokeCompletion3(response, {
|
|
7791
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7792
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7793
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7794
|
+
}),
|
|
7795
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7796
|
+
};
|
|
6676
7797
|
}
|
|
6677
7798
|
nextDebugInvokeSeq() {
|
|
6678
7799
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -6685,14 +7806,14 @@ var ChatOpenRouter = class {
|
|
|
6685
7806
|
return;
|
|
6686
7807
|
}
|
|
6687
7808
|
const payload = safeJsonStringify(request);
|
|
6688
|
-
const hash = (0,
|
|
6689
|
-
const toolsHash = (0,
|
|
6690
|
-
const instructionsHash = (0,
|
|
7809
|
+
const hash = (0, import_node_crypto7.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7810
|
+
const toolsHash = (0, import_node_crypto7.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7811
|
+
const instructionsHash = (0, import_node_crypto7.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6691
7812
|
const previous = this.lastDebugRequestPayload;
|
|
6692
7813
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6693
7814
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6694
7815
|
if (settings.enabled) {
|
|
6695
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
7816
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto7.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6696
7817
|
console.error(
|
|
6697
7818
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
6698
7819
|
);
|
|
@@ -6756,8 +7877,8 @@ var ChatOpenRouter = class {
|
|
|
6756
7877
|
};
|
|
6757
7878
|
|
|
6758
7879
|
// src/llm/xai/chat.ts
|
|
6759
|
-
var
|
|
6760
|
-
var
|
|
7880
|
+
var import_node_crypto8 = require("crypto");
|
|
7881
|
+
var import_openai9 = __toESM(require("openai"), 1);
|
|
6761
7882
|
|
|
6762
7883
|
// src/llm/xai/serializer.ts
|
|
6763
7884
|
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -6980,7 +8101,7 @@ var ChatXai = class {
|
|
|
6980
8101
|
debugInvokeSeq = 0;
|
|
6981
8102
|
lastDebugRequestPayload = null;
|
|
6982
8103
|
constructor(options = {}) {
|
|
6983
|
-
this.client = options.client ?? new
|
|
8104
|
+
this.client = options.client ?? new import_openai9.default({
|
|
6984
8105
|
baseURL: XAI_BASE_URL,
|
|
6985
8106
|
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6986
8107
|
...options.clientOptions ?? {},
|
|
@@ -7033,13 +8154,24 @@ var ChatXai = class {
|
|
|
7033
8154
|
}
|
|
7034
8155
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
7035
8156
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7036
|
-
const
|
|
8157
|
+
const timing = new LlmStreamTiming();
|
|
8158
|
+
const response = await invokeOpenAiHttp(
|
|
8159
|
+
this.client,
|
|
8160
|
+
request,
|
|
8161
|
+
signal,
|
|
8162
|
+
void 0,
|
|
8163
|
+
(event) => timing.observeResponsesEvent(event)
|
|
8164
|
+
);
|
|
8165
|
+
const measuredTiming = timing.finish();
|
|
7037
8166
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
7038
|
-
return
|
|
7039
|
-
|
|
7040
|
-
|
|
7041
|
-
|
|
7042
|
-
|
|
8167
|
+
return {
|
|
8168
|
+
...toXaiChatInvokeCompletion(response, {
|
|
8169
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8170
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8171
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8172
|
+
}),
|
|
8173
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
8174
|
+
};
|
|
7043
8175
|
}
|
|
7044
8176
|
nextDebugInvokeSeq() {
|
|
7045
8177
|
this.debugInvokeSeq += 1;
|
|
@@ -7049,7 +8181,7 @@ var ChatXai = class {
|
|
|
7049
8181
|
const settings = getProviderLogSettings();
|
|
7050
8182
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
7051
8183
|
const payload = safeJsonStringify(request);
|
|
7052
|
-
const hash = (0,
|
|
8184
|
+
const hash = (0, import_node_crypto8.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7053
8185
|
const previous = this.lastDebugRequestPayload;
|
|
7054
8186
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7055
8187
|
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7106,15 +8238,15 @@ var ChatXai = class {
|
|
|
7106
8238
|
};
|
|
7107
8239
|
|
|
7108
8240
|
// src/llm/zai/chat.ts
|
|
7109
|
-
var
|
|
8241
|
+
var import_node_crypto9 = require("crypto");
|
|
7110
8242
|
|
|
7111
8243
|
// src/llm/zai/failure.ts
|
|
7112
8244
|
var PROVIDER_NAME8 = "zai";
|
|
7113
8245
|
var readBusinessCode = (error) => {
|
|
7114
|
-
const
|
|
7115
|
-
const body = asRecord(
|
|
8246
|
+
const record3 = asRecord(error);
|
|
8247
|
+
const body = asRecord(record3?.body);
|
|
7116
8248
|
const nested = asRecord(body?.error) ?? body;
|
|
7117
|
-
const raw = nested?.code ??
|
|
8249
|
+
const raw = nested?.code ?? record3?.code;
|
|
7118
8250
|
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7119
8251
|
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7120
8252
|
};
|
|
@@ -7418,6 +8550,7 @@ var streamZaiChatCompletion = async ({
|
|
|
7418
8550
|
timeoutMs,
|
|
7419
8551
|
captureRawChunks
|
|
7420
8552
|
}) => {
|
|
8553
|
+
const timing = new LlmStreamTiming();
|
|
7421
8554
|
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
7422
8555
|
try {
|
|
7423
8556
|
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
@@ -7439,9 +8572,11 @@ var streamZaiChatCompletion = async ({
|
|
|
7439
8572
|
response,
|
|
7440
8573
|
requestSignal.signal
|
|
7441
8574
|
)) {
|
|
8575
|
+
timing.observeChatChunk(chunk);
|
|
7442
8576
|
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
7443
8577
|
}
|
|
7444
8578
|
return {
|
|
8579
|
+
timing: timing.finish(),
|
|
7445
8580
|
status: response.status,
|
|
7446
8581
|
request_id: response.headers.get("x-request-id"),
|
|
7447
8582
|
accumulated
|
|
@@ -7636,13 +8771,16 @@ var ChatZai = class {
|
|
|
7636
8771
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7637
8772
|
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
7638
8773
|
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
7639
|
-
return
|
|
7640
|
-
|
|
7641
|
-
|
|
7642
|
-
|
|
7643
|
-
|
|
7644
|
-
|
|
7645
|
-
|
|
8774
|
+
return {
|
|
8775
|
+
...toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
8776
|
+
request_id: terminal.request_id ?? null,
|
|
8777
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8778
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8779
|
+
reasoning_effort: request.reasoning_effort,
|
|
8780
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8781
|
+
}),
|
|
8782
|
+
...terminal.timing ? { timing: terminal.timing } : {}
|
|
8783
|
+
};
|
|
7646
8784
|
}
|
|
7647
8785
|
async streamRequest(apiKey, request, signal) {
|
|
7648
8786
|
const logSettings = getProviderLogSettings();
|
|
@@ -7667,8 +8805,8 @@ var ChatZai = class {
|
|
|
7667
8805
|
return;
|
|
7668
8806
|
}
|
|
7669
8807
|
const payload = safeJsonStringify(request);
|
|
7670
|
-
const hash = (0,
|
|
7671
|
-
const toolsHash = (0,
|
|
8808
|
+
const hash = (0, import_node_crypto9.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
8809
|
+
const toolsHash = (0, import_node_crypto9.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7672
8810
|
const previous = this.lastDebugRequestPayload;
|
|
7673
8811
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7674
8812
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7799,6 +8937,160 @@ function defineTool(toolOptions) {
|
|
|
7799
8937
|
}
|
|
7800
8938
|
};
|
|
7801
8939
|
}
|
|
8940
|
+
|
|
8941
|
+
// src/llm/responses/chat.ts
|
|
8942
|
+
var import_openai10 = __toESM(require("openai"), 1);
|
|
8943
|
+
var ChatResponses = class {
|
|
8944
|
+
provider;
|
|
8945
|
+
model;
|
|
8946
|
+
retryPolicy;
|
|
8947
|
+
client;
|
|
8948
|
+
endpoint;
|
|
8949
|
+
reasoningEffort;
|
|
8950
|
+
textVerbosity;
|
|
8951
|
+
constructor(options) {
|
|
8952
|
+
this.provider = options.provider;
|
|
8953
|
+
this.model = options.model;
|
|
8954
|
+
this.endpoint = options.endpoint;
|
|
8955
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
8956
|
+
this.textVerbosity = options.textVerbosity;
|
|
8957
|
+
const retry = options.endpoint.retry;
|
|
8958
|
+
this.retryPolicy = {
|
|
8959
|
+
maxRetries: typeof retry === "object" ? retry.max_retries : 0,
|
|
8960
|
+
...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
|
|
8961
|
+
};
|
|
8962
|
+
this.client = new import_openai10.default({
|
|
8963
|
+
apiKey: options.apiKey,
|
|
8964
|
+
baseURL: options.endpoint.base_url,
|
|
8965
|
+
organization: null,
|
|
8966
|
+
project: null,
|
|
8967
|
+
maxRetries: 0,
|
|
8968
|
+
timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
|
|
8969
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
8970
|
+
});
|
|
8971
|
+
}
|
|
8972
|
+
classifyFailure = (error) => {
|
|
8973
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
8974
|
+
const failure = error instanceof import_openai10.default.APIUserAbortError ? buildProviderFailure(this.provider, "cancelled") : error instanceof import_openai10.default.APIConnectionTimeoutError ? buildProviderFailure(this.provider, "timeout", { retryable: true }) : error instanceof import_openai10.default.APIConnectionError ? buildProviderFailure(this.provider, "network", {
|
|
8975
|
+
retryable: true
|
|
8976
|
+
}) : classifyOpenAiCompatibleFailure(this.provider, error);
|
|
8977
|
+
const extracted = extractProviderError(error);
|
|
8978
|
+
const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
|
|
8979
|
+
return {
|
|
8980
|
+
...failure,
|
|
8981
|
+
...extracted.status !== void 0 ? { status: extracted.status } : {},
|
|
8982
|
+
...extracted.status === 413 ? { kind: "validation" } : {},
|
|
8983
|
+
retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
|
|
8984
|
+
...code ? { code } : {},
|
|
8985
|
+
safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
|
|
8986
|
+
};
|
|
8987
|
+
};
|
|
8988
|
+
async ainvoke(input, context) {
|
|
8989
|
+
const model = input.model ?? this.model;
|
|
8990
|
+
const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
|
|
8991
|
+
const invalid = (message) => {
|
|
8992
|
+
throw createProviderValidationError(this.provider, message);
|
|
8993
|
+
};
|
|
8994
|
+
if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
|
|
8995
|
+
if (input.tools?.some((tool) => tool.type === "hosted_search"))
|
|
8996
|
+
invalid(
|
|
8997
|
+
`${this.provider} supports function tools only; hosted tools are unavailable`
|
|
8998
|
+
);
|
|
8999
|
+
if (input.tools?.length && !spec.supports_tools)
|
|
9000
|
+
invalid(`${this.provider}/${model} does not support tools`);
|
|
9001
|
+
const items = toResponsesInput(input.messages);
|
|
9002
|
+
if (!spec.supports_vision && Array.isArray(items) && items.some((item) => {
|
|
9003
|
+
const parts = item.type === "function_call_output" ? item.output : "content" in item ? item.content : void 0;
|
|
9004
|
+
return Array.isArray(parts) && parts.some((part) => part.type === "input_image");
|
|
9005
|
+
}))
|
|
9006
|
+
invalid(`${this.provider}/${model} vision is disabled`);
|
|
9007
|
+
const text = input.options?.text;
|
|
9008
|
+
if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
|
|
9009
|
+
invalid(`${this.provider}/${model} does not support structured output`);
|
|
9010
|
+
const features = this.endpoint.features;
|
|
9011
|
+
const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
|
|
9012
|
+
if (effort && !spec.supports_reasoning)
|
|
9013
|
+
invalid(`${this.provider}/${model} reasoning is disabled`);
|
|
9014
|
+
const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
|
|
9015
|
+
if (effort && !levels.includes(effort))
|
|
9016
|
+
invalid(
|
|
9017
|
+
`Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
|
|
9018
|
+
);
|
|
9019
|
+
const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
|
|
9020
|
+
if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
|
|
9021
|
+
invalid(`Invalid max output tokens for ${this.provider}/${model}`);
|
|
9022
|
+
const tools = toResponsesTools(input.tools);
|
|
9023
|
+
const choice = toResponsesToolChoice(input.toolChoice);
|
|
9024
|
+
const instructions = extractInstructions(input.messages);
|
|
9025
|
+
const request = {
|
|
9026
|
+
model,
|
|
9027
|
+
input: items,
|
|
9028
|
+
store: false,
|
|
9029
|
+
...instructions ? { instructions } : {},
|
|
9030
|
+
...tools ? { tools } : {},
|
|
9031
|
+
...choice ? { tool_choice: choice } : {},
|
|
9032
|
+
...output !== void 0 ? { max_output_tokens: output } : {}
|
|
9033
|
+
};
|
|
9034
|
+
if (spec.supports_reasoning && (effort || features?.reasoning_summary))
|
|
9035
|
+
request.reasoning = {
|
|
9036
|
+
...effort ? { effort: toSdkReasoningEffort(effort) } : {},
|
|
9037
|
+
...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
|
|
9038
|
+
};
|
|
9039
|
+
if (spec.supports_reasoning && features?.encrypted_reasoning)
|
|
9040
|
+
request.include = ["reasoning.encrypted_content"];
|
|
9041
|
+
if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
|
|
9042
|
+
request.text = {
|
|
9043
|
+
...text?.format ? { format: text.format } : {},
|
|
9044
|
+
...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
|
|
9045
|
+
};
|
|
9046
|
+
if (features?.prompt_cache_key && context?.sessionKey)
|
|
9047
|
+
request.prompt_cache_key = context.sessionKey;
|
|
9048
|
+
const timing = new LlmStreamTiming();
|
|
9049
|
+
let streamStarted = false;
|
|
9050
|
+
try {
|
|
9051
|
+
const stream = await this.client.responses.create(
|
|
9052
|
+
{ ...request, stream: true },
|
|
9053
|
+
{
|
|
9054
|
+
...input.signal ? { signal: input.signal } : {},
|
|
9055
|
+
...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
|
|
9056
|
+
}
|
|
9057
|
+
);
|
|
9058
|
+
streamStarted = true;
|
|
9059
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
9060
|
+
let terminal;
|
|
9061
|
+
for await (const event of stream) {
|
|
9062
|
+
timing.observeResponsesEvent(event);
|
|
9063
|
+
if (event.type === "error") throw { error: event };
|
|
9064
|
+
if (event.type === "response.failed")
|
|
9065
|
+
throw { error: event.response.error };
|
|
9066
|
+
accumulator.observeEvent(event);
|
|
9067
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
9068
|
+
terminal = event.response;
|
|
9069
|
+
break;
|
|
9070
|
+
}
|
|
9071
|
+
}
|
|
9072
|
+
if (!terminal)
|
|
9073
|
+
throw new Error("Responses stream ended before a terminal event");
|
|
9074
|
+
const measuredTiming = timing.finish();
|
|
9075
|
+
return {
|
|
9076
|
+
...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
|
|
9077
|
+
transport: "http_stream"
|
|
9078
|
+
}),
|
|
9079
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
9080
|
+
};
|
|
9081
|
+
} catch (error) {
|
|
9082
|
+
if (isProviderFailureError(error)) throw error;
|
|
9083
|
+
const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
|
|
9084
|
+
throw new ProviderFailureError(
|
|
9085
|
+
{
|
|
9086
|
+
...failure,
|
|
9087
|
+
...streamStarted ? { retryable: false, delivery: "buffered" } : {}
|
|
9088
|
+
},
|
|
9089
|
+
{ cause: error }
|
|
9090
|
+
);
|
|
9091
|
+
}
|
|
9092
|
+
}
|
|
9093
|
+
};
|
|
7802
9094
|
// Annotate the CommonJS export names for ESM import in node:
|
|
7803
9095
|
0 && (module.exports = {
|
|
7804
9096
|
ANTHROPIC_DEFAULT_MODEL,
|
|
@@ -7808,11 +9100,13 @@ function defineTool(toolOptions) {
|
|
|
7808
9100
|
ChatMoonshot,
|
|
7809
9101
|
ChatOpenAI,
|
|
7810
9102
|
ChatOpenRouter,
|
|
9103
|
+
ChatResponses,
|
|
7811
9104
|
ChatXai,
|
|
7812
9105
|
ChatZai,
|
|
7813
9106
|
DEFAULT_MODEL_REGISTRY,
|
|
7814
9107
|
GOOGLE_MODELS,
|
|
7815
9108
|
MOONSHOT_DEFAULT_MODEL,
|
|
9109
|
+
MOONSHOT_K3_1_MODELS,
|
|
7816
9110
|
MOONSHOT_MODELS,
|
|
7817
9111
|
OPENAI_DEFAULT_MODEL,
|
|
7818
9112
|
OPENAI_DEFAULT_REASONING_EFFORT,
|