@codelia/core 0.1.80 → 0.1.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1304 -193
- package/dist/index.d.ts +87 -17
- package/dist/index.js +1298 -189
- package/package.json +4 -3
- package/prompts/AGENTS.md +1 -0
- package/prompts/system.md +12 -2
package/dist/index.cjs
CHANGED
|
@@ -37,6 +37,7 @@ __export(index_exports, {
|
|
|
37
37
|
ChatMoonshot: () => ChatMoonshot,
|
|
38
38
|
ChatOpenAI: () => ChatOpenAI,
|
|
39
39
|
ChatOpenRouter: () => ChatOpenRouter,
|
|
40
|
+
ChatResponses: () => ChatResponses,
|
|
40
41
|
ChatXai: () => ChatXai,
|
|
41
42
|
ChatZai: () => ChatZai,
|
|
42
43
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
@@ -49,6 +50,7 @@ __export(index_exports, {
|
|
|
49
50
|
ProviderFailureError: () => ProviderFailureError,
|
|
50
51
|
TaskComplete: () => TaskComplete,
|
|
51
52
|
ToolOutputCacheService: () => ToolOutputCacheService,
|
|
53
|
+
ToolPermissionDenied: () => ToolPermissionDenied,
|
|
52
54
|
XAI_DEFAULT_MODEL: () => XAI_DEFAULT_MODEL,
|
|
53
55
|
XAI_DEFAULT_REASONING_EFFORT: () => XAI_DEFAULT_REASONING_EFFORT,
|
|
54
56
|
XAI_MODELS: () => XAI_MODELS,
|
|
@@ -96,6 +98,38 @@ var buildGpt56Model = (id) => ({
|
|
|
96
98
|
supportsFast: true
|
|
97
99
|
});
|
|
98
100
|
var OPENAI_MODELS = [
|
|
101
|
+
{
|
|
102
|
+
id: "gpt-6.1-sol",
|
|
103
|
+
provider: "openai",
|
|
104
|
+
contextWindow: 105e4,
|
|
105
|
+
maxInputTokens: 27e4,
|
|
106
|
+
maxOutputTokens: 128e3,
|
|
107
|
+
supportsFast: true
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
id: "gpt-6-astra",
|
|
111
|
+
provider: "openai",
|
|
112
|
+
contextWindow: 105e4,
|
|
113
|
+
maxInputTokens: 27e4,
|
|
114
|
+
maxOutputTokens: 128e3,
|
|
115
|
+
supportsFast: true
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
id: "gpt-6-sol",
|
|
119
|
+
provider: "openai",
|
|
120
|
+
contextWindow: 105e4,
|
|
121
|
+
maxInputTokens: 27e4,
|
|
122
|
+
maxOutputTokens: 128e3,
|
|
123
|
+
supportsFast: true
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
id: "gpt-6-luna",
|
|
127
|
+
provider: "openai",
|
|
128
|
+
contextWindow: 105e4,
|
|
129
|
+
maxInputTokens: 27e4,
|
|
130
|
+
maxOutputTokens: 128e3,
|
|
131
|
+
supportsFast: true
|
|
132
|
+
},
|
|
99
133
|
...GPT_5_6_PROVIDER_MODELS.map(buildGpt56Model),
|
|
100
134
|
{
|
|
101
135
|
id: "gpt-5.5",
|
|
@@ -274,6 +308,47 @@ import_config.configRegistry.registerDefaults({
|
|
|
274
308
|
|
|
275
309
|
// src/agent/agent.ts
|
|
276
310
|
var import_node_perf_hooks = require("perf_hooks");
|
|
311
|
+
var import_node_crypto = require("crypto");
|
|
312
|
+
|
|
313
|
+
// src/llm/provider-status.ts
|
|
314
|
+
async function* withProviderStatus(operation, signal) {
|
|
315
|
+
const controller = new AbortController();
|
|
316
|
+
const abort = () => controller.abort(signal?.reason);
|
|
317
|
+
if (signal?.aborted) abort();
|
|
318
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
319
|
+
const queue = [];
|
|
320
|
+
let wake;
|
|
321
|
+
let closed = false;
|
|
322
|
+
const iterator = operation((event) => {
|
|
323
|
+
if (closed || controller.signal.aborted) return;
|
|
324
|
+
if (queue.length < 32) queue.push(event);
|
|
325
|
+
wake?.();
|
|
326
|
+
}, controller.signal);
|
|
327
|
+
let pending = iterator.next();
|
|
328
|
+
try {
|
|
329
|
+
while (true) {
|
|
330
|
+
while (queue.length) yield queue.shift();
|
|
331
|
+
const changed = new Promise((resolve) => {
|
|
332
|
+
wake = () => resolve(void 0);
|
|
333
|
+
});
|
|
334
|
+
const result = await Promise.race([pending, changed]);
|
|
335
|
+
wake = void 0;
|
|
336
|
+
if (!result) continue;
|
|
337
|
+
while (queue.length) yield queue.shift();
|
|
338
|
+
if (result.done) return result.value;
|
|
339
|
+
yield result.value;
|
|
340
|
+
pending = iterator.next();
|
|
341
|
+
}
|
|
342
|
+
} finally {
|
|
343
|
+
closed = true;
|
|
344
|
+
controller.abort();
|
|
345
|
+
signal?.removeEventListener("abort", abort);
|
|
346
|
+
void pending.catch(() => {
|
|
347
|
+
});
|
|
348
|
+
void iterator.return(void 0).catch(() => {
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
}
|
|
277
352
|
|
|
278
353
|
// src/content/stringify.ts
|
|
279
354
|
var stringifyUnknown = (value) => {
|
|
@@ -287,6 +362,9 @@ var stringifyPart = (part, options) => {
|
|
|
287
362
|
if (part.type === "text") {
|
|
288
363
|
return part.text;
|
|
289
364
|
}
|
|
365
|
+
if (part.type === "image_ref") {
|
|
366
|
+
return `[image artifact:${part.image_ref.artifact_id} ${part.image_ref.width}x${part.image_ref.height}]`;
|
|
367
|
+
}
|
|
290
368
|
if (part.type === "image_url") {
|
|
291
369
|
if (options.mode === "log") {
|
|
292
370
|
return `[image:${part.image_url.media_type ?? "unknown"}]`;
|
|
@@ -362,6 +440,10 @@ var MessageHistoryAdapter = class {
|
|
|
362
440
|
}
|
|
363
441
|
};
|
|
364
442
|
|
|
443
|
+
// src/llm/openai/history.ts
|
|
444
|
+
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
445
|
+
};
|
|
446
|
+
|
|
365
447
|
// src/llm/failures.ts
|
|
366
448
|
var ProviderFailureError = class extends Error {
|
|
367
449
|
failure;
|
|
@@ -383,8 +465,8 @@ var ProviderTimeoutError = class extends Error {
|
|
|
383
465
|
};
|
|
384
466
|
var isProviderFailureError = (error) => error instanceof ProviderFailureError;
|
|
385
467
|
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
386
|
-
var readString = (
|
|
387
|
-
const value =
|
|
468
|
+
var readString = (record3, key) => {
|
|
469
|
+
const value = record3?.[key];
|
|
388
470
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
389
471
|
};
|
|
390
472
|
var readStatus = (error) => {
|
|
@@ -395,9 +477,9 @@ var readHeader = (headers, name) => {
|
|
|
395
477
|
if (headers instanceof Headers) {
|
|
396
478
|
return headers.get(name);
|
|
397
479
|
}
|
|
398
|
-
const
|
|
399
|
-
if (!
|
|
400
|
-
const direct =
|
|
480
|
+
const record3 = asRecord(headers);
|
|
481
|
+
if (!record3) return null;
|
|
482
|
+
const direct = record3[name] ?? record3[name.toLowerCase()];
|
|
401
483
|
return typeof direct === "string" ? direct : null;
|
|
402
484
|
};
|
|
403
485
|
var parsePositiveNumber = (value) => {
|
|
@@ -453,7 +535,7 @@ var PROVIDER_LABELS = {
|
|
|
453
535
|
xai: "xAI"
|
|
454
536
|
};
|
|
455
537
|
var safeProviderMessage = (provider, kind) => {
|
|
456
|
-
const label = PROVIDER_LABELS[provider];
|
|
538
|
+
const label = PROVIDER_LABELS[provider] ?? provider;
|
|
457
539
|
switch (kind) {
|
|
458
540
|
case "hard_quota":
|
|
459
541
|
return `${label} quota is exhausted for the interactive retry window. Wait for reset, review billing, or switch provider.`;
|
|
@@ -785,10 +867,6 @@ async function* invokeWithRetry({
|
|
|
785
867
|
}
|
|
786
868
|
}
|
|
787
869
|
|
|
788
|
-
// src/llm/openai/history.ts
|
|
789
|
-
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
790
|
-
};
|
|
791
|
-
|
|
792
870
|
// src/models/anthropic.ts
|
|
793
871
|
var ANTHROPIC_DEFAULT_MODEL = "claude-sonnet-4-5";
|
|
794
872
|
var ANTHROPIC_MODELS = [
|
|
@@ -797,6 +875,28 @@ var ANTHROPIC_MODELS = [
|
|
|
797
875
|
provider: "anthropic",
|
|
798
876
|
aliases: ["default"]
|
|
799
877
|
},
|
|
878
|
+
{
|
|
879
|
+
id: "claude-fable-5-1",
|
|
880
|
+
provider: "anthropic",
|
|
881
|
+
contextWindow: 1e6,
|
|
882
|
+
maxInputTokens: 1e6,
|
|
883
|
+
maxOutputTokens: 128e3
|
|
884
|
+
},
|
|
885
|
+
{
|
|
886
|
+
id: "claude-opus-5-5",
|
|
887
|
+
provider: "anthropic",
|
|
888
|
+
contextWindow: 1e6,
|
|
889
|
+
maxInputTokens: 1e6,
|
|
890
|
+
maxOutputTokens: 128e3,
|
|
891
|
+
supportsFast: true
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
id: "claude-sonnet-5",
|
|
895
|
+
provider: "anthropic",
|
|
896
|
+
contextWindow: 1e6,
|
|
897
|
+
maxInputTokens: 1e6,
|
|
898
|
+
maxOutputTokens: 128e3
|
|
899
|
+
},
|
|
800
900
|
{
|
|
801
901
|
id: "claude-fable-5",
|
|
802
902
|
provider: "anthropic",
|
|
@@ -826,12 +926,12 @@ var ANTHROPIC_MODELS = [
|
|
|
826
926
|
contextWindow: 1e6,
|
|
827
927
|
maxInputTokens: 1e6,
|
|
828
928
|
maxOutputTokens: 128e3,
|
|
829
|
-
supportsFast:
|
|
929
|
+
supportsFast: false
|
|
830
930
|
},
|
|
831
931
|
{
|
|
832
932
|
id: "claude-opus-4-6",
|
|
833
933
|
provider: "anthropic",
|
|
834
|
-
supportsFast:
|
|
934
|
+
supportsFast: false
|
|
835
935
|
},
|
|
836
936
|
{
|
|
837
937
|
id: "claude-opus-4-5",
|
|
@@ -912,6 +1012,7 @@ function createModelRegistry(specs) {
|
|
|
912
1012
|
function registerModels(registry, specs) {
|
|
913
1013
|
for (const spec of specs) {
|
|
914
1014
|
registry.modelsById[spec.id] = spec;
|
|
1015
|
+
registry.aliasesByProvider[spec.provider] ??= {};
|
|
915
1016
|
const aliasBucket = registry.aliasesByProvider[spec.provider];
|
|
916
1017
|
for (const alias of spec.aliases ?? []) {
|
|
917
1018
|
aliasBucket[alias] = spec.id;
|
|
@@ -920,11 +1021,11 @@ function registerModels(registry, specs) {
|
|
|
920
1021
|
}
|
|
921
1022
|
function resolveModel(registry, idOrAlias, provider) {
|
|
922
1023
|
const direct = registry.modelsById[idOrAlias];
|
|
923
|
-
if (direct) {
|
|
1024
|
+
if (direct && (!provider || direct.provider === provider)) {
|
|
924
1025
|
return direct;
|
|
925
1026
|
}
|
|
926
1027
|
if (provider) {
|
|
927
|
-
const aliasId = registry.aliasesByProvider[provider][idOrAlias];
|
|
1028
|
+
const aliasId = registry.aliasesByProvider[provider]?.[idOrAlias];
|
|
928
1029
|
return aliasId ? registry.modelsById[aliasId] : void 0;
|
|
929
1030
|
}
|
|
930
1031
|
let resolved;
|
|
@@ -959,15 +1060,12 @@ function supportsFastMode(registry, idOrAlias, provider) {
|
|
|
959
1060
|
return spec?.supportsFast === true;
|
|
960
1061
|
}
|
|
961
1062
|
function cloneAliases(aliasesByProvider) {
|
|
962
|
-
return
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
zai: { ...aliasesByProvider.zai },
|
|
969
|
-
xai: { ...aliasesByProvider.xai }
|
|
970
|
-
};
|
|
1063
|
+
return Object.fromEntries(
|
|
1064
|
+
Object.entries(aliasesByProvider).map(([provider, aliases]) => [
|
|
1065
|
+
provider,
|
|
1066
|
+
{ ...aliases }
|
|
1067
|
+
])
|
|
1068
|
+
);
|
|
971
1069
|
}
|
|
972
1070
|
function applyModelMetadata(registry, index) {
|
|
973
1071
|
const next = {
|
|
@@ -1060,6 +1158,48 @@ var DEFAULT_MODEL_REGISTRY = createModelRegistry([
|
|
|
1060
1158
|
...XAI_MODELS
|
|
1061
1159
|
]);
|
|
1062
1160
|
|
|
1161
|
+
// src/content/image-references.ts
|
|
1162
|
+
var REGISTRY = "[codelia.image.artifacts]";
|
|
1163
|
+
function isImageRegistry(message) {
|
|
1164
|
+
return message.role === "user" && Array.isArray(message.content) && message.content[0]?.type === "text" && message.content[0].text.startsWith(REGISTRY);
|
|
1165
|
+
}
|
|
1166
|
+
function imageReferenceRegistry(messages) {
|
|
1167
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1168
|
+
for (const message of messages) {
|
|
1169
|
+
if (!("content" in message) || !Array.isArray(message.content)) continue;
|
|
1170
|
+
for (const part of message.content)
|
|
1171
|
+
if (part.type === "image_ref") {
|
|
1172
|
+
refs.delete(part.image_ref.artifact_id);
|
|
1173
|
+
refs.set(part.image_ref.artifact_id, part);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
const recent = [...refs.values()].slice(-16);
|
|
1177
|
+
return recent.length ? {
|
|
1178
|
+
role: "user",
|
|
1179
|
+
content: [
|
|
1180
|
+
{
|
|
1181
|
+
type: "text",
|
|
1182
|
+
text: `${REGISTRY} Saved image references (not a new user request). Use image_inspect to revisit originals; this registry does not claim visual inspection.
|
|
1183
|
+
`
|
|
1184
|
+
},
|
|
1185
|
+
...recent
|
|
1186
|
+
]
|
|
1187
|
+
} : null;
|
|
1188
|
+
}
|
|
1189
|
+
function describeImageReferences(messages) {
|
|
1190
|
+
return messages.map((message) => {
|
|
1191
|
+
if (message.role === "system" || message.role === "reasoning" || !Array.isArray(message.content))
|
|
1192
|
+
return message;
|
|
1193
|
+
const content = message.content.map(
|
|
1194
|
+
(part) => part.type === "image_ref" ? {
|
|
1195
|
+
type: "text",
|
|
1196
|
+
text: `[Image artifact ${part.image_ref.artifact_id}, ${part.image_ref.width}x${part.image_ref.height}; use image_inspect to view]`
|
|
1197
|
+
} : part
|
|
1198
|
+
);
|
|
1199
|
+
return { ...message, content };
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1063
1203
|
// src/services/compaction/service.ts
|
|
1064
1204
|
var DEFAULT_THRESHOLD_RATIO = 0.85;
|
|
1065
1205
|
var DEFAULT_RETAIN_LAST_TURNS = 1;
|
|
@@ -1074,14 +1214,14 @@ var CompactionService = class _CompactionService {
|
|
|
1074
1214
|
this.config = _CompactionService.normalizeConfig(config);
|
|
1075
1215
|
this.modelRegistry = deps.modelRegistry;
|
|
1076
1216
|
}
|
|
1077
|
-
async shouldCompact(llm, usage) {
|
|
1217
|
+
async shouldCompact(llm, usage, estimatedInputTokens) {
|
|
1078
1218
|
if (!this.config.enabled) {
|
|
1079
1219
|
return false;
|
|
1080
1220
|
}
|
|
1081
1221
|
if (!this.config.auto) {
|
|
1082
1222
|
return false;
|
|
1083
1223
|
}
|
|
1084
|
-
if (!usage) {
|
|
1224
|
+
if (!usage && estimatedInputTokens === void 0) {
|
|
1085
1225
|
return false;
|
|
1086
1226
|
}
|
|
1087
1227
|
let contextLimit;
|
|
@@ -1091,7 +1231,7 @@ var CompactionService = class _CompactionService {
|
|
|
1091
1231
|
return false;
|
|
1092
1232
|
}
|
|
1093
1233
|
const threshold = Math.floor(contextLimit * this.config.thresholdRatio);
|
|
1094
|
-
return usage
|
|
1234
|
+
return Math.max(usage?.total_tokens ?? 0, estimatedInputTokens ?? 0) >= threshold;
|
|
1095
1235
|
}
|
|
1096
1236
|
async compact(llm, messages, options) {
|
|
1097
1237
|
if (!this.config.enabled) {
|
|
@@ -1118,7 +1258,10 @@ var CompactionService = class _CompactionService {
|
|
|
1118
1258
|
try {
|
|
1119
1259
|
response = await llm.ainvoke(
|
|
1120
1260
|
{
|
|
1121
|
-
messages: [
|
|
1261
|
+
messages: describeImageReferences([
|
|
1262
|
+
...preparedMessages,
|
|
1263
|
+
interruptMessage
|
|
1264
|
+
]),
|
|
1122
1265
|
tools: null,
|
|
1123
1266
|
toolChoice: "none",
|
|
1124
1267
|
...options?.signal ? { signal: options.signal } : {},
|
|
@@ -1228,7 +1371,7 @@ var CompactionService = class _CompactionService {
|
|
|
1228
1371
|
);
|
|
1229
1372
|
const mergedSummary = summary.trim() || existingMemory.summaryEntries[existingMemory.summaryEntries.length - 1] || "";
|
|
1230
1373
|
const conversationMessages = nonSystemMessages.filter(
|
|
1231
|
-
(message) => !isCompactionMemoryMessage(message)
|
|
1374
|
+
(message) => !isCompactionMemoryMessage(message) && !isImageRegistry(message)
|
|
1232
1375
|
);
|
|
1233
1376
|
const tail = this.normalizeRetainedTail(
|
|
1234
1377
|
this.getLastTurns(conversationMessages, this.config.retainLastTurns)
|
|
@@ -1246,6 +1389,8 @@ var CompactionService = class _CompactionService {
|
|
|
1246
1389
|
content: `${COMPACTION_SUMMARY_PREFIX}${mergedSummary}`
|
|
1247
1390
|
});
|
|
1248
1391
|
}
|
|
1392
|
+
const imageRegistry = imageReferenceRegistry(messages);
|
|
1393
|
+
if (imageRegistry) compacted.push(imageRegistry);
|
|
1249
1394
|
compacted.push(...tail);
|
|
1250
1395
|
return compacted;
|
|
1251
1396
|
}
|
|
@@ -1307,7 +1452,7 @@ var CompactionService = class _CompactionService {
|
|
|
1307
1452
|
return messages.slice(startIndex);
|
|
1308
1453
|
}
|
|
1309
1454
|
async resolveContextLimit(llm, usage) {
|
|
1310
|
-
const modelId = usage
|
|
1455
|
+
const modelId = usage?.model ?? llm.model;
|
|
1311
1456
|
const modelSpec = this.resolveModelSpecWithSnapshotFallback(
|
|
1312
1457
|
llm.provider,
|
|
1313
1458
|
modelId
|
|
@@ -1675,6 +1820,239 @@ var TokenUsageService = class {
|
|
|
1675
1820
|
}
|
|
1676
1821
|
};
|
|
1677
1822
|
|
|
1823
|
+
// src/agent/image-context.ts
|
|
1824
|
+
var import_image_size = require("image-size");
|
|
1825
|
+
|
|
1826
|
+
// src/llm/image-policy.ts
|
|
1827
|
+
function estimateImageTokens(provider, model, image) {
|
|
1828
|
+
let name = model.toLowerCase();
|
|
1829
|
+
if (provider === "openrouter") {
|
|
1830
|
+
if (name.startsWith("openai/")) provider = "openai";
|
|
1831
|
+
else if (name.startsWith("anthropic/")) provider = "anthropic";
|
|
1832
|
+
name = name.slice(name.indexOf("/") + 1);
|
|
1833
|
+
}
|
|
1834
|
+
const width = image.width;
|
|
1835
|
+
const height = image.height;
|
|
1836
|
+
const dimensionsKnown = width !== void 0 && height !== void 0 && Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
|
|
1837
|
+
const patches = (size, edge, budget, multiplier = 1) => {
|
|
1838
|
+
if (!dimensionsKnown)
|
|
1839
|
+
return { tokens: Math.ceil(budget * multiplier), method: "fallback" };
|
|
1840
|
+
const scale = Math.min(1, edge / Math.max(width, height));
|
|
1841
|
+
return {
|
|
1842
|
+
tokens: Math.ceil(
|
|
1843
|
+
Math.min(
|
|
1844
|
+
budget,
|
|
1845
|
+
Math.ceil(width * scale / size) * Math.ceil(height * scale / size)
|
|
1846
|
+
) * multiplier
|
|
1847
|
+
),
|
|
1848
|
+
method: "patch"
|
|
1849
|
+
};
|
|
1850
|
+
};
|
|
1851
|
+
if (provider === "anthropic" && /^claude-((opus|sonnet|haiku)-(4(-[0-8])?|5)(-|$)|3(-[57])?-(opus|sonnet|haiku)(-|$))/.test(
|
|
1852
|
+
name
|
|
1853
|
+
)) {
|
|
1854
|
+
const highResolution = /^claude-(opus|sonnet|haiku)-(4-[78]|5)(-|$)/.test(
|
|
1855
|
+
name
|
|
1856
|
+
);
|
|
1857
|
+
return patches(
|
|
1858
|
+
28,
|
|
1859
|
+
highResolution ? 2576 : 1568,
|
|
1860
|
+
highResolution ? 4784 : 1568
|
|
1861
|
+
);
|
|
1862
|
+
}
|
|
1863
|
+
if (provider === "openai") {
|
|
1864
|
+
if (image.detail === "low" && /^gpt-(6-astra|5\.6-(sol|terra|luna)|5\.5)(-|$)/.test(name))
|
|
1865
|
+
return patches(32, 512, 256, 1.2);
|
|
1866
|
+
if (/^gpt-6-astra(-|$)/.test(name))
|
|
1867
|
+
return patches(32, 65535, image.detail === "high" ? 2500 : 3e4, 1.2);
|
|
1868
|
+
if (/^gpt-5\.6-(sol|terra|luna)(-|$)/.test(name))
|
|
1869
|
+
return patches(
|
|
1870
|
+
32,
|
|
1871
|
+
image.detail === "high" ? 2048 : 65535,
|
|
1872
|
+
image.detail === "high" ? 2500 : 3e4,
|
|
1873
|
+
1.2
|
|
1874
|
+
);
|
|
1875
|
+
if (/^gpt-5\.5(-|$)/.test(name))
|
|
1876
|
+
return patches(
|
|
1877
|
+
32,
|
|
1878
|
+
image.detail === "high" ? 2048 : 6e3,
|
|
1879
|
+
image.detail === "high" ? 2500 : 1e4,
|
|
1880
|
+
1.2
|
|
1881
|
+
);
|
|
1882
|
+
if (/^gpt-5\.4(-|$)/.test(name))
|
|
1883
|
+
return patches(32, 2048, image.detail === "low" ? 6144 : 2500, 1.2);
|
|
1884
|
+
if (/^gpt-5\.2(-|$)/.test(name)) return patches(32, 2048, 6144, 1.2);
|
|
1885
|
+
if (/^gpt-4\.1-mini(-|$)/.test(name)) return patches(32, 2048, 6144, 1.62);
|
|
1886
|
+
if (/^(gpt-4o(-mini)?|gpt-4\.1|gpt-5\.1)(-\d{4}-\d{2}-\d{2})?$/.test(name)) {
|
|
1887
|
+
const mini = name.startsWith("gpt-4o-mini");
|
|
1888
|
+
const base = mini ? 2833 : 85;
|
|
1889
|
+
const tile = mini ? 5667 : 170;
|
|
1890
|
+
if (image.detail === "low") return { tokens: base, method: "tile" };
|
|
1891
|
+
if (!dimensionsKnown)
|
|
1892
|
+
return { tokens: base + tile * 8, method: "fallback" };
|
|
1893
|
+
const fit = Math.min(1, 2048 / Math.max(width, height));
|
|
1894
|
+
const shortFit = 768 / (Math.min(width, height) * fit);
|
|
1895
|
+
return {
|
|
1896
|
+
tokens: base + tile * Math.ceil(width * fit * shortFit / 512) * Math.ceil(height * fit * shortFit / 512),
|
|
1897
|
+
method: "tile"
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
return { tokens: 1e4, method: "fallback" };
|
|
1902
|
+
}
|
|
1903
|
+
function imagePayloadLimit(provider) {
|
|
1904
|
+
if (provider === "anthropic") return 32e6;
|
|
1905
|
+
if (provider === "openai") return 512e6;
|
|
1906
|
+
return void 0;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// src/agent/image-context.ts
|
|
1910
|
+
function estimateImageContext(input, llm, resolveReferences = true) {
|
|
1911
|
+
let imageTokens = 0;
|
|
1912
|
+
let imageCount = 0;
|
|
1913
|
+
let fallbackCount = 0;
|
|
1914
|
+
let imageBytes = 0;
|
|
1915
|
+
const account = (image) => {
|
|
1916
|
+
const estimate = llm.estimateImageTokens?.(image) ?? estimateImageTokens(llm.provider, input.model ?? llm.model, image);
|
|
1917
|
+
if (!Number.isSafeInteger(estimate.tokens) || estimate.tokens < 0)
|
|
1918
|
+
throw new Error("Invalid model image-token estimate");
|
|
1919
|
+
imageTokens += estimate.tokens;
|
|
1920
|
+
imageCount++;
|
|
1921
|
+
if (estimate.method === "fallback") fallbackCount++;
|
|
1922
|
+
};
|
|
1923
|
+
const messages = input.messages.map((message) => {
|
|
1924
|
+
if (!Array.isArray(message.content)) return message;
|
|
1925
|
+
const registry = isImageRegistry(message);
|
|
1926
|
+
return {
|
|
1927
|
+
...message,
|
|
1928
|
+
content: message.content.map((part) => {
|
|
1929
|
+
if (part.type === "image_ref") {
|
|
1930
|
+
if (!registry && resolveReferences) {
|
|
1931
|
+
account({
|
|
1932
|
+
width: part.image_ref.width,
|
|
1933
|
+
height: part.image_ref.height,
|
|
1934
|
+
detail: part.detail
|
|
1935
|
+
});
|
|
1936
|
+
imageBytes += 4 * Math.ceil(
|
|
1937
|
+
(part.image_ref.model_view?.byte_size ?? part.image_ref.byte_size) / 3
|
|
1938
|
+
) + 64;
|
|
1939
|
+
}
|
|
1940
|
+
return {
|
|
1941
|
+
type: "text",
|
|
1942
|
+
text: `[Image ${part.image_ref.artifact_id}]`
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
if (part.type === "image_url") {
|
|
1946
|
+
let dimensions = {};
|
|
1947
|
+
const url = part.image_url.url;
|
|
1948
|
+
const comma = url.indexOf(",");
|
|
1949
|
+
if (url.startsWith("data:image/") && url.slice(0, comma).endsWith(";base64") && url.length <= 12 * 1024 * 1024) {
|
|
1950
|
+
try {
|
|
1951
|
+
dimensions = (0, import_image_size.imageSize)(
|
|
1952
|
+
Buffer.from(url.slice(comma + 1), "base64")
|
|
1953
|
+
);
|
|
1954
|
+
} catch {
|
|
1955
|
+
dimensions = {};
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
account({ ...dimensions, detail: part.image_url.detail });
|
|
1959
|
+
imageBytes += Buffer.byteLength(part.image_url.url);
|
|
1960
|
+
return { type: "text", text: "[Image]" };
|
|
1961
|
+
}
|
|
1962
|
+
if (part.type === "document")
|
|
1963
|
+
return {
|
|
1964
|
+
type: "text",
|
|
1965
|
+
text: "[Document: token estimate unavailable]"
|
|
1966
|
+
};
|
|
1967
|
+
return part;
|
|
1968
|
+
})
|
|
1969
|
+
};
|
|
1970
|
+
});
|
|
1971
|
+
const textBytes = Buffer.byteLength(
|
|
1972
|
+
JSON.stringify({
|
|
1973
|
+
messages,
|
|
1974
|
+
tools: input.tools ?? null,
|
|
1975
|
+
tool_choice: input.toolChoice
|
|
1976
|
+
})
|
|
1977
|
+
);
|
|
1978
|
+
const textTokens = Math.ceil(textBytes / 3);
|
|
1979
|
+
return {
|
|
1980
|
+
text_tokens: textTokens,
|
|
1981
|
+
image_tokens: imageTokens,
|
|
1982
|
+
total_tokens: textTokens + imageTokens,
|
|
1983
|
+
image_count: imageCount,
|
|
1984
|
+
fallback_image_count: fallbackCount,
|
|
1985
|
+
encoded_image_bytes: imageBytes,
|
|
1986
|
+
estimated_request_bytes: textBytes + imageBytes
|
|
1987
|
+
};
|
|
1988
|
+
}
|
|
1989
|
+
function validateImagePayload(estimate, llm) {
|
|
1990
|
+
const limit = imagePayloadLimit(llm.provider);
|
|
1991
|
+
if (estimate.image_count && limit && estimate.estimated_request_bytes > limit)
|
|
1992
|
+
throw new Error(
|
|
1993
|
+
`Image-bearing request exceeds the ${llm.provider} transport payload budget (${limit} bytes), not the context-token budget. Use smaller attachments in a new conversation or explicitly reorganize this history. Originals are unchanged; no model request was sent.`
|
|
1994
|
+
);
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
// src/agent/image-input.ts
|
|
1998
|
+
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
1999
|
+
async function materializeImageReferences(messages, resolve, signal) {
|
|
2000
|
+
signal?.throwIfAborted();
|
|
2001
|
+
if (resolve) {
|
|
2002
|
+
for (const message of messages) {
|
|
2003
|
+
if (isImageRegistry(message) || !Array.isArray(message.content)) continue;
|
|
2004
|
+
for (const part of message.content) {
|
|
2005
|
+
if (part.type !== "image_ref") continue;
|
|
2006
|
+
const size = part.image_ref.byte_size;
|
|
2007
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_BYTES)
|
|
2008
|
+
throw new Error(
|
|
2009
|
+
"Invalid or oversized image reference; model request was not sent."
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
const result = [];
|
|
2015
|
+
for (const message of messages) {
|
|
2016
|
+
if (!Array.isArray(message.content) || message.role === "system" || message.role === "reasoning") {
|
|
2017
|
+
result.push(message);
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
const registry = isImageRegistry(message);
|
|
2021
|
+
const content = [];
|
|
2022
|
+
for (const part of message.content) {
|
|
2023
|
+
if (part.type !== "image_ref") {
|
|
2024
|
+
content.push(part);
|
|
2025
|
+
continue;
|
|
2026
|
+
}
|
|
2027
|
+
signal?.throwIfAborted();
|
|
2028
|
+
if (!registry && resolve) {
|
|
2029
|
+
try {
|
|
2030
|
+
const image = await resolve(part.image_ref, signal);
|
|
2031
|
+
content.push(
|
|
2032
|
+
part.detail ? {
|
|
2033
|
+
...image,
|
|
2034
|
+
image_url: { ...image.image_url, detail: part.detail }
|
|
2035
|
+
} : image
|
|
2036
|
+
);
|
|
2037
|
+
signal?.throwIfAborted();
|
|
2038
|
+
continue;
|
|
2039
|
+
} catch {
|
|
2040
|
+
signal?.throwIfAborted();
|
|
2041
|
+
throw new Error(
|
|
2042
|
+
`Image artifact ${part.image_ref.artifact_id} or its fixed model view is unavailable or corrupt. Restore the saved bytes or compact the conversation; model request was not sent to avoid rewriting earlier image input.`
|
|
2043
|
+
);
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
content.push({
|
|
2047
|
+
type: "text",
|
|
2048
|
+
text: `[Image artifact ${part.image_ref.artifact_id}: ${registry ? "compacted image registry; use image_inspect to revisit" : "image input unavailable on this connection"}. Not visually inspected.]`
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
result.push({ ...message, content });
|
|
2052
|
+
}
|
|
2053
|
+
return result;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
1678
2056
|
// src/agent/model-context.ts
|
|
1679
2057
|
var calculateContextLeftPercent = ({
|
|
1680
2058
|
usage,
|
|
@@ -1756,16 +2134,16 @@ var collectModelOutput = (messages) => {
|
|
|
1756
2134
|
if (message.role === "reasoning") {
|
|
1757
2135
|
const raw = message.raw_item;
|
|
1758
2136
|
if (raw && typeof raw === "object" && (raw.type === "web_search_call" || raw.type === "x_search_call")) {
|
|
1759
|
-
const
|
|
1760
|
-
const kind =
|
|
1761
|
-
const statusRaw =
|
|
2137
|
+
const record3 = raw;
|
|
2138
|
+
const kind = record3.type === "x_search_call" ? "x" : "web";
|
|
2139
|
+
const statusRaw = record3.status;
|
|
1762
2140
|
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
1763
|
-
const action =
|
|
2141
|
+
const action = record3.action && typeof record3.action === "object" ? record3.action : null;
|
|
1764
2142
|
const queries = Array.isArray(action?.queries) ? action.queries.filter(
|
|
1765
2143
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
1766
2144
|
) : [];
|
|
1767
2145
|
const sourcesCount = Array.isArray(action?.sources) ? action.sources.length : void 0;
|
|
1768
|
-
const explicitId = typeof
|
|
2146
|
+
const explicitId = typeof record3.id === "string" && record3.id.length > 0 ? record3.id : null;
|
|
1769
2147
|
let id = explicitId;
|
|
1770
2148
|
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
1771
2149
|
if (!id) {
|
|
@@ -1863,6 +2241,16 @@ var TaskComplete = class extends Error {
|
|
|
1863
2241
|
}
|
|
1864
2242
|
};
|
|
1865
2243
|
|
|
2244
|
+
// src/types/permissions.ts
|
|
2245
|
+
var ToolPermissionDenied = class extends Error {
|
|
2246
|
+
constructor(decision) {
|
|
2247
|
+
super(`Permission denied${decision.reason ? `: ${decision.reason}` : ""}`);
|
|
2248
|
+
this.decision = decision;
|
|
2249
|
+
this.name = "ToolPermissionDenied";
|
|
2250
|
+
}
|
|
2251
|
+
decision;
|
|
2252
|
+
};
|
|
2253
|
+
|
|
1866
2254
|
// src/agent/tool-execution.ts
|
|
1867
2255
|
var toolResultToContent = (result) => {
|
|
1868
2256
|
if (result.type === "text") return result.text;
|
|
@@ -1891,6 +2279,23 @@ var createToolContext = (signal) => {
|
|
|
1891
2279
|
now: () => /* @__PURE__ */ new Date()
|
|
1892
2280
|
};
|
|
1893
2281
|
};
|
|
2282
|
+
var permissionDeniedResult = (toolCall, decision) => {
|
|
2283
|
+
const toolName = toolCall.function.name;
|
|
2284
|
+
const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
|
|
2285
|
+
return {
|
|
2286
|
+
message: {
|
|
2287
|
+
role: "tool",
|
|
2288
|
+
tool_call_id: toolCall.id,
|
|
2289
|
+
tool_name: toolName,
|
|
2290
|
+
content: deniedContent,
|
|
2291
|
+
is_error: true
|
|
2292
|
+
},
|
|
2293
|
+
...decision.stop_turn ? {
|
|
2294
|
+
done: true,
|
|
2295
|
+
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
2296
|
+
} : {}
|
|
2297
|
+
};
|
|
2298
|
+
};
|
|
1894
2299
|
var executeToolCall = async ({
|
|
1895
2300
|
toolCall,
|
|
1896
2301
|
tools,
|
|
@@ -1918,20 +2323,7 @@ var executeToolCall = async ({
|
|
|
1918
2323
|
createToolContext(signal)
|
|
1919
2324
|
);
|
|
1920
2325
|
if (decision.decision === "deny") {
|
|
1921
|
-
|
|
1922
|
-
return {
|
|
1923
|
-
message: {
|
|
1924
|
-
role: "tool",
|
|
1925
|
-
tool_call_id: toolCall.id,
|
|
1926
|
-
tool_name: toolName,
|
|
1927
|
-
content: deniedContent,
|
|
1928
|
-
is_error: true
|
|
1929
|
-
},
|
|
1930
|
-
...decision.stop_turn ? {
|
|
1931
|
-
done: true,
|
|
1932
|
-
finalMessage: "Permission request was denied. Turn stopped. Please send your next input to continue."
|
|
1933
|
-
} : {}
|
|
1934
|
-
};
|
|
2326
|
+
return permissionDeniedResult(toolCall, decision);
|
|
1935
2327
|
}
|
|
1936
2328
|
} catch (error) {
|
|
1937
2329
|
return {
|
|
@@ -1959,6 +2351,8 @@ var executeToolCall = async ({
|
|
|
1959
2351
|
}
|
|
1960
2352
|
};
|
|
1961
2353
|
} catch (error) {
|
|
2354
|
+
if (error instanceof ToolPermissionDenied)
|
|
2355
|
+
return permissionDeniedResult(toolCall, error.decision);
|
|
1962
2356
|
if (error instanceof TaskComplete) {
|
|
1963
2357
|
return {
|
|
1964
2358
|
message: {
|
|
@@ -2019,6 +2413,7 @@ var Agent = class {
|
|
|
2019
2413
|
//private readonly dependencyOverrides?: DependencyOverrides;
|
|
2020
2414
|
history;
|
|
2021
2415
|
usageService;
|
|
2416
|
+
imageUsageBaseline;
|
|
2022
2417
|
constructor(options) {
|
|
2023
2418
|
this.llm = options.llm;
|
|
2024
2419
|
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
@@ -2071,13 +2466,15 @@ var Agent = class {
|
|
|
2071
2466
|
}
|
|
2072
2467
|
replaceHistoryMessages(messages) {
|
|
2073
2468
|
this.history.replaceViewMessages(messages);
|
|
2469
|
+
this.imageUsageBaseline = void 0;
|
|
2074
2470
|
}
|
|
2075
2471
|
async *checkAndCompact(signal, options = {}) {
|
|
2076
2472
|
throwIfAborted(signal);
|
|
2077
2473
|
await this.trimToolOutputs();
|
|
2078
2474
|
const shouldCompact = options.force ? true : await this.compactionService?.shouldCompact(
|
|
2079
2475
|
this.llm,
|
|
2080
|
-
this.usageService.getLastUsage()
|
|
2476
|
+
this.usageService.getLastUsage(),
|
|
2477
|
+
options.estimatedInputTokens
|
|
2081
2478
|
);
|
|
2082
2479
|
if (shouldCompact && this.compactionService) {
|
|
2083
2480
|
throwIfAborted(signal);
|
|
@@ -2098,6 +2495,7 @@ var Agent = class {
|
|
|
2098
2495
|
this.usageService.updateUsageSummary(usage);
|
|
2099
2496
|
if (compacted && compactedMessages) {
|
|
2100
2497
|
this.history.replaceViewMessages(compactedMessages);
|
|
2498
|
+
this.imageUsageBaseline = void 0;
|
|
2101
2499
|
}
|
|
2102
2500
|
if (compacted || options.force) {
|
|
2103
2501
|
await this.llm.onHistoryCompacted?.(invokeContext);
|
|
@@ -2156,9 +2554,13 @@ var Agent = class {
|
|
|
2156
2554
|
const runId = session?.run_id?.trim();
|
|
2157
2555
|
return runId && runId.length > 0 ? runId : void 0;
|
|
2158
2556
|
}
|
|
2159
|
-
buildInvokeContext(session) {
|
|
2557
|
+
buildInvokeContext(session, turnKey) {
|
|
2160
2558
|
const sessionKey = this.resolveSessionKey(session);
|
|
2161
|
-
|
|
2559
|
+
const turn = turnKey ?? session?.run_id;
|
|
2560
|
+
return sessionKey || turn ? {
|
|
2561
|
+
...sessionKey ? { sessionKey } : {},
|
|
2562
|
+
...turn ? { turnKey: turn } : {}
|
|
2563
|
+
} : void 0;
|
|
2162
2564
|
}
|
|
2163
2565
|
recordLlmResponse(session, seq, response) {
|
|
2164
2566
|
if (!session || seq === null) return;
|
|
@@ -2169,6 +2571,7 @@ var Agent = class {
|
|
|
2169
2571
|
seq,
|
|
2170
2572
|
output: {
|
|
2171
2573
|
messages: response.messages,
|
|
2574
|
+
...response.timing ? { timing: response.timing } : {},
|
|
2172
2575
|
usage: response.usage ?? null,
|
|
2173
2576
|
stop_reason: response.stop_reason ?? null,
|
|
2174
2577
|
provider_meta: response.provider_meta ?? null
|
|
@@ -2176,19 +2579,43 @@ var Agent = class {
|
|
|
2176
2579
|
});
|
|
2177
2580
|
}
|
|
2178
2581
|
async *invokeModelWithRetry(input, context, signal) {
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2582
|
+
const estimate = estimateImageContext(
|
|
2583
|
+
input,
|
|
2584
|
+
this.llm,
|
|
2585
|
+
Boolean(this.services.resolveImage)
|
|
2586
|
+
);
|
|
2587
|
+
validateImagePayload(estimate, this.llm);
|
|
2588
|
+
const messages = await materializeImageReferences(
|
|
2589
|
+
input.messages,
|
|
2590
|
+
this.services.resolveImage,
|
|
2591
|
+
signal
|
|
2592
|
+
);
|
|
2593
|
+
const response = yield* withProviderStatus(
|
|
2594
|
+
(onProviderStatus, progressSignal) => invokeWithRetry({
|
|
2595
|
+
operation: (attemptSignal) => this.llm.ainvoke(
|
|
2596
|
+
{
|
|
2597
|
+
...input,
|
|
2598
|
+
messages,
|
|
2599
|
+
...attemptSignal ? { signal: attemptSignal } : {}
|
|
2600
|
+
},
|
|
2601
|
+
{ ...context, onProviderStatus }
|
|
2602
|
+
),
|
|
2603
|
+
classifyFailure: this.llm.classifyFailure,
|
|
2604
|
+
policy: resolveLlmRetryPolicy({
|
|
2605
|
+
...this.llmRetryPolicy,
|
|
2606
|
+
...this.llm.retryPolicy
|
|
2607
|
+
}),
|
|
2608
|
+
signal: progressSignal,
|
|
2609
|
+
dependencies: this.llmRetryDependencies
|
|
2610
|
+
}),
|
|
2611
|
+
signal
|
|
2612
|
+
);
|
|
2613
|
+
this.imageUsageBaseline = response.usage ? {
|
|
2614
|
+
messages: input.messages.slice(),
|
|
2615
|
+
estimated: estimate.total_tokens,
|
|
2616
|
+
observed: response.usage.input_tokens
|
|
2617
|
+
} : void 0;
|
|
2618
|
+
return response;
|
|
2192
2619
|
}
|
|
2193
2620
|
async run(message, options = {}) {
|
|
2194
2621
|
let finalResponse = "";
|
|
@@ -2221,19 +2648,43 @@ var Agent = class {
|
|
|
2221
2648
|
return;
|
|
2222
2649
|
}
|
|
2223
2650
|
this.history.enqueueUserMessage(message);
|
|
2651
|
+
const receiveMessages = async () => {
|
|
2652
|
+
const messages = await options.pollMessages?.() ?? [];
|
|
2653
|
+
for (const content of messages) this.history.enqueueUserMessage(content);
|
|
2654
|
+
return messages;
|
|
2655
|
+
};
|
|
2656
|
+
const turnKey = session?.run_id ?? (0, import_node_crypto.randomUUID)();
|
|
2224
2657
|
let iterations = 0;
|
|
2225
2658
|
const runTools = [...this.tools, ...options.tools ?? []];
|
|
2226
2659
|
const runToolChoice = options.toolChoice ?? this.toolChoice;
|
|
2227
2660
|
while (iterations < this.maxIterations) {
|
|
2228
2661
|
iterations++;
|
|
2229
2662
|
throwIfAborted(signal);
|
|
2663
|
+
for (const content of await receiveMessages())
|
|
2664
|
+
yield { type: "hidden_user_message", content };
|
|
2230
2665
|
await this.trimToolOutputs();
|
|
2231
2666
|
throwIfAborted(signal);
|
|
2232
|
-
|
|
2667
|
+
let invokeInput = this.history.prepareInvokeInput({
|
|
2233
2668
|
tools: [...runTools.map((t) => t.definition), ...this.hostedTools],
|
|
2234
2669
|
toolChoice: runToolChoice
|
|
2235
2670
|
});
|
|
2236
|
-
const
|
|
2671
|
+
const imageEstimate = estimateImageContext(
|
|
2672
|
+
invokeInput,
|
|
2673
|
+
this.llm,
|
|
2674
|
+
Boolean(this.services.resolveImage)
|
|
2675
|
+
);
|
|
2676
|
+
if (imageEstimate.image_count > 0) {
|
|
2677
|
+
const baseline = this.imageUsageBaseline;
|
|
2678
|
+
const estimatedInputTokens = baseline && baseline.messages.every(
|
|
2679
|
+
(message2, index) => invokeInput.messages[index] === message2
|
|
2680
|
+
) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
|
|
2681
|
+
yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
|
|
2682
|
+
invokeInput = this.history.prepareInvokeInput({
|
|
2683
|
+
tools: invokeInput.tools,
|
|
2684
|
+
toolChoice: runToolChoice
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2237
2688
|
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
2238
2689
|
const response = yield* this.invokeModelWithRetry(
|
|
2239
2690
|
invokeInput,
|
|
@@ -2303,6 +2754,10 @@ var Agent = class {
|
|
|
2303
2754
|
if (!hasToolCalls) {
|
|
2304
2755
|
if (!this.requireDoneTool) {
|
|
2305
2756
|
yield* this.checkAndCompact(signal, { session });
|
|
2757
|
+
const incoming = await receiveMessages();
|
|
2758
|
+
for (const content of incoming)
|
|
2759
|
+
yield { type: "hidden_user_message", content };
|
|
2760
|
+
if (incoming.length) continue;
|
|
2306
2761
|
const finalText = assistantTexts.join("\n").trim();
|
|
2307
2762
|
const finalResponseEvent2 = {
|
|
2308
2763
|
type: "final",
|
|
@@ -2453,15 +2908,21 @@ var Agent = class {
|
|
|
2453
2908
|
}
|
|
2454
2909
|
yield* this.checkAndCompact(signal, { session });
|
|
2455
2910
|
}
|
|
2456
|
-
|
|
2911
|
+
if (signal?.aborted) throw createAbortError2();
|
|
2912
|
+
const finalResponse = await this.generateFinalResponse(
|
|
2913
|
+
session,
|
|
2914
|
+
signal,
|
|
2915
|
+
turnKey
|
|
2916
|
+
);
|
|
2457
2917
|
const finalResponseEvent = {
|
|
2458
2918
|
type: "final",
|
|
2919
|
+
termination_reason: "max_steps",
|
|
2459
2920
|
content: finalResponse
|
|
2460
2921
|
};
|
|
2461
2922
|
yield finalResponseEvent;
|
|
2462
2923
|
return;
|
|
2463
2924
|
}
|
|
2464
|
-
async generateFinalResponse(session, signal) {
|
|
2925
|
+
async generateFinalResponse(session, signal, turnKey) {
|
|
2465
2926
|
const summaryMessage = {
|
|
2466
2927
|
role: "user",
|
|
2467
2928
|
content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
|
|
@@ -2474,11 +2935,24 @@ var Agent = class {
|
|
|
2474
2935
|
// no tools are allowed at this point
|
|
2475
2936
|
toolChoice: "none"
|
|
2476
2937
|
};
|
|
2477
|
-
const invokeContext = this.buildInvokeContext(session);
|
|
2938
|
+
const invokeContext = this.buildInvokeContext(session, turnKey);
|
|
2478
2939
|
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
2940
|
+
validateImagePayload(
|
|
2941
|
+
estimateImageContext(
|
|
2942
|
+
input,
|
|
2943
|
+
this.llm,
|
|
2944
|
+
Boolean(this.services.resolveImage)
|
|
2945
|
+
),
|
|
2946
|
+
this.llm
|
|
2947
|
+
);
|
|
2479
2948
|
const summary = await this.llm.ainvoke(
|
|
2480
2949
|
{
|
|
2481
2950
|
...input,
|
|
2951
|
+
messages: await materializeImageReferences(
|
|
2952
|
+
input.messages,
|
|
2953
|
+
this.services.resolveImage,
|
|
2954
|
+
signal
|
|
2955
|
+
),
|
|
2482
2956
|
...signal ? { signal } : {}
|
|
2483
2957
|
},
|
|
2484
2958
|
invokeContext
|
|
@@ -2499,8 +2973,90 @@ ${assistantTexts.join("\n").trim()}`;
|
|
|
2499
2973
|
}
|
|
2500
2974
|
};
|
|
2501
2975
|
|
|
2976
|
+
// src/llm/stream-timing.ts
|
|
2977
|
+
var record = (value) => value !== null && typeof value === "object" ? value : void 0;
|
|
2978
|
+
var nonempty = (value) => typeof value === "string" && value.length > 0;
|
|
2979
|
+
var responseOutputDeltas = /* @__PURE__ */ new Set([
|
|
2980
|
+
"response.output_text.delta",
|
|
2981
|
+
"response.refusal.delta",
|
|
2982
|
+
"response.function_call_arguments.delta",
|
|
2983
|
+
"response.custom_tool_call_input.delta",
|
|
2984
|
+
"response.reasoning_text.delta",
|
|
2985
|
+
"response.reasoning_summary_text.delta"
|
|
2986
|
+
]);
|
|
2987
|
+
var LlmStreamTiming = class {
|
|
2988
|
+
constructor(nowMs = () => performance.now()) {
|
|
2989
|
+
this.nowMs = nowMs;
|
|
2990
|
+
this.startedAt = nowMs();
|
|
2991
|
+
}
|
|
2992
|
+
nowMs;
|
|
2993
|
+
startedAt;
|
|
2994
|
+
firstOutputAt;
|
|
2995
|
+
reasoningStartedAt;
|
|
2996
|
+
completedAt;
|
|
2997
|
+
observeOutput() {
|
|
2998
|
+
if (this.completedAt === void 0 && this.firstOutputAt === void 0)
|
|
2999
|
+
this.firstOutputAt = this.nowMs();
|
|
3000
|
+
}
|
|
3001
|
+
complete() {
|
|
3002
|
+
this.completedAt ??= this.nowMs();
|
|
3003
|
+
}
|
|
3004
|
+
observeResponsesEvent(event) {
|
|
3005
|
+
const value = record(event);
|
|
3006
|
+
if (!value) return;
|
|
3007
|
+
if (value.type === "response.output_item.added" && record(value.item)?.type === "reasoning" && this.completedAt === void 0)
|
|
3008
|
+
this.reasoningStartedAt ??= this.nowMs();
|
|
3009
|
+
if (responseOutputDeltas.has(String(value.type)) && nonempty(value.delta))
|
|
3010
|
+
this.observeOutput();
|
|
3011
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done")
|
|
3012
|
+
this.complete();
|
|
3013
|
+
}
|
|
3014
|
+
observeChatChunk(chunk) {
|
|
3015
|
+
const choices = record(chunk)?.choices;
|
|
3016
|
+
if (!Array.isArray(choices)) return;
|
|
3017
|
+
for (const choice of choices) {
|
|
3018
|
+
const delta = record(record(choice)?.delta);
|
|
3019
|
+
if (!delta) continue;
|
|
3020
|
+
if (nonempty(delta.content) || nonempty(delta.reasoning_content) || nonempty(delta.reasoning) || Array.isArray(delta.tool_calls) && delta.tool_calls.some(
|
|
3021
|
+
(tool) => nonempty(record(record(tool)?.function)?.arguments)
|
|
3022
|
+
))
|
|
3023
|
+
this.observeOutput();
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
observeAnthropicEvent(event) {
|
|
3027
|
+
const value = record(event);
|
|
3028
|
+
if (!value) return;
|
|
3029
|
+
const delta = record(value.delta);
|
|
3030
|
+
if (value.type === "content_block_delta" && (nonempty(delta?.text) || nonempty(delta?.thinking) || nonempty(delta?.partial_json)))
|
|
3031
|
+
this.observeOutput();
|
|
3032
|
+
if (value.type === "message_stop") this.complete();
|
|
3033
|
+
}
|
|
3034
|
+
finish() {
|
|
3035
|
+
this.complete();
|
|
3036
|
+
if (this.firstOutputAt === void 0) return void 0;
|
|
3037
|
+
const first = this.firstOutputAt - this.startedAt;
|
|
3038
|
+
const start = Math.min(
|
|
3039
|
+
this.firstOutputAt,
|
|
3040
|
+
this.reasoningStartedAt ?? this.firstOutputAt
|
|
3041
|
+
);
|
|
3042
|
+
const generation = this.completedAt - start;
|
|
3043
|
+
if (![first, generation, start - this.startedAt].every(
|
|
3044
|
+
(ms) => Number.isFinite(ms) && ms >= 0
|
|
3045
|
+
))
|
|
3046
|
+
return void 0;
|
|
3047
|
+
return {
|
|
3048
|
+
time_to_first_token_ms: first,
|
|
3049
|
+
generation_duration_ms: generation,
|
|
3050
|
+
...this.reasoningStartedAt !== void 0 && start === this.reasoningStartedAt ? {
|
|
3051
|
+
generation_start_ms: start - this.startedAt,
|
|
3052
|
+
generation_start_source: "reasoning_item"
|
|
3053
|
+
} : {}
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
};
|
|
3057
|
+
|
|
2502
3058
|
// src/llm/anthropic/chat.ts
|
|
2503
|
-
var
|
|
3059
|
+
var import_node_crypto2 = require("crypto");
|
|
2504
3060
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
2505
3061
|
|
|
2506
3062
|
// src/llm/anthropic/failure.ts
|
|
@@ -2625,6 +3181,7 @@ var writeProviderLogDump = async (settings, provider, seq, direction, payload) =
|
|
|
2625
3181
|
};
|
|
2626
3182
|
|
|
2627
3183
|
// src/types/llm/guards.ts
|
|
3184
|
+
var import_shared_types = require("@codelia/shared-types");
|
|
2628
3185
|
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2629
3186
|
function isTextPart(value) {
|
|
2630
3187
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2653,7 +3210,19 @@ function isOtherPart(value) {
|
|
|
2653
3210
|
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2654
3211
|
}
|
|
2655
3212
|
function isContentPart(value) {
|
|
2656
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3213
|
+
return isTextPart(value) || isImagePart(value) || isImageRefPart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
3214
|
+
}
|
|
3215
|
+
function isImageRefPart(value) {
|
|
3216
|
+
if (!value || typeof value !== "object") return false;
|
|
3217
|
+
const v = value;
|
|
3218
|
+
if (v.type !== "image_ref" || !v.image_ref || typeof v.image_ref !== "object")
|
|
3219
|
+
return false;
|
|
3220
|
+
const r = v.image_ref;
|
|
3221
|
+
return (r.model_view === void 0 || (0, import_shared_types.isImageModelView)(r.model_view)) && typeof r.artifact_id === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(r.artifact_id) && typeof r.sha256 === "string" && /^[0-9a-f]{64}$/.test(r.sha256) && ["image/png", "image/jpeg", "image/webp", "image/gif"].includes(
|
|
3222
|
+
String(r.media_type)
|
|
3223
|
+
) && (v.detail === void 0 || ["auto", "low", "high"].includes(String(v.detail))) && [r.byte_size, r.width, r.height].every(
|
|
3224
|
+
(n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0
|
|
3225
|
+
) && Number(r.byte_size) <= 8 * 1024 * 1024 && Number(r.width) <= 4096 && Number(r.height) <= 4096 && Number(r.width) * Number(r.height) <= 16e6;
|
|
2657
3226
|
}
|
|
2658
3227
|
function isToolResult(value) {
|
|
2659
3228
|
if (!value || typeof value !== "object") return false;
|
|
@@ -2757,6 +3326,15 @@ var toContentBlocks = (content) => {
|
|
|
2757
3326
|
}
|
|
2758
3327
|
};
|
|
2759
3328
|
}
|
|
3329
|
+
if (URL.canParse(part.image_url.url)) {
|
|
3330
|
+
const url = new URL(part.image_url.url);
|
|
3331
|
+
if (url.protocol === "https:" || url.protocol === "http:") {
|
|
3332
|
+
return {
|
|
3333
|
+
type: "image",
|
|
3334
|
+
source: { type: "url", url: part.image_url.url }
|
|
3335
|
+
};
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
2760
3338
|
return toTextBlock(part.image_url.url);
|
|
2761
3339
|
}
|
|
2762
3340
|
case "document":
|
|
@@ -3174,20 +3752,27 @@ var ChatAnthropic = class {
|
|
|
3174
3752
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
3175
3753
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
3176
3754
|
const requestOptions = signal ? { signal } : void 0;
|
|
3177
|
-
const
|
|
3755
|
+
const timing = new LlmStreamTiming();
|
|
3756
|
+
const stream = this.fastMode ? this.client.beta.messages.stream(
|
|
3178
3757
|
request,
|
|
3179
3758
|
requestOptions
|
|
3180
|
-
) :
|
|
3759
|
+
) : this.client.messages.stream(
|
|
3181
3760
|
request,
|
|
3182
3761
|
requestOptions
|
|
3183
3762
|
);
|
|
3763
|
+
for await (const event of stream) timing.observeAnthropicEvent(event);
|
|
3764
|
+
const response = await stream.finalMessage();
|
|
3765
|
+
const measuredTiming = timing.finish();
|
|
3184
3766
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3185
|
-
return
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3767
|
+
return {
|
|
3768
|
+
...toChatInvokeCompletion(response, {
|
|
3769
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
3770
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
3771
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied,
|
|
3772
|
+
reasoning_budget_preset: this.reasoningLevelMeta.budgetPreset
|
|
3773
|
+
}),
|
|
3774
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
3775
|
+
};
|
|
3191
3776
|
}
|
|
3192
3777
|
nextDebugInvokeSeq() {
|
|
3193
3778
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -3200,9 +3785,9 @@ var ChatAnthropic = class {
|
|
|
3200
3785
|
return;
|
|
3201
3786
|
}
|
|
3202
3787
|
const payload = safeJsonStringify(request);
|
|
3203
|
-
const hash = (0,
|
|
3204
|
-
const toolsHash = (0,
|
|
3205
|
-
const systemHash = (0,
|
|
3788
|
+
const hash = (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3789
|
+
const toolsHash = (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
3790
|
+
const systemHash = (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
3206
3791
|
const previous = this.lastDebugRequestPayload;
|
|
3207
3792
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3208
3793
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -3272,7 +3857,7 @@ var ChatAnthropic = class {
|
|
|
3272
3857
|
};
|
|
3273
3858
|
|
|
3274
3859
|
// src/llm/moonshot/chat.ts
|
|
3275
|
-
var
|
|
3860
|
+
var import_node_crypto3 = require("crypto");
|
|
3276
3861
|
var import_openai3 = __toESM(require("openai"), 1);
|
|
3277
3862
|
|
|
3278
3863
|
// src/llm/moonshot/failure.ts
|
|
@@ -3675,6 +4260,7 @@ var ChatMoonshot = class {
|
|
|
3675
4260
|
const seq = this.nextDebugInvokeSeq();
|
|
3676
4261
|
await this.debugRequestIfEnabled(request, seq);
|
|
3677
4262
|
const client = new import_openai3.default({ apiKey: this.apiKey, ...this.clientOptions });
|
|
4263
|
+
const timing = new LlmStreamTiming();
|
|
3678
4264
|
const accumulator = createMoonshotStreamAccumulator();
|
|
3679
4265
|
try {
|
|
3680
4266
|
const stream = await client.chat.completions.create(
|
|
@@ -3682,6 +4268,7 @@ var ChatMoonshot = class {
|
|
|
3682
4268
|
{ signal: input.signal }
|
|
3683
4269
|
);
|
|
3684
4270
|
for await (const chunk of stream) {
|
|
4271
|
+
timing.observeChatChunk(chunk);
|
|
3685
4272
|
appendMoonshotChatCompletionChunk(
|
|
3686
4273
|
accumulator,
|
|
3687
4274
|
chunk
|
|
@@ -3694,11 +4281,15 @@ var ChatMoonshot = class {
|
|
|
3694
4281
|
{ cause: error }
|
|
3695
4282
|
);
|
|
3696
4283
|
}
|
|
4284
|
+
const measuredTiming = timing.finish();
|
|
3697
4285
|
await this.debugResponseIfEnabled(accumulator, seq);
|
|
3698
|
-
return
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
4286
|
+
return {
|
|
4287
|
+
...toMoonshotChatInvokeCompletion(accumulator, {
|
|
4288
|
+
reasoningRequested: this.reasoningLevelRequested,
|
|
4289
|
+
reasoningFallback: this.reasoningLevelRequested !== "max"
|
|
4290
|
+
}),
|
|
4291
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
4292
|
+
};
|
|
3702
4293
|
}
|
|
3703
4294
|
nextDebugInvokeSeq() {
|
|
3704
4295
|
this.debugInvokeSeq += 1;
|
|
@@ -3708,7 +4299,7 @@ var ChatMoonshot = class {
|
|
|
3708
4299
|
const settings = getProviderLogSettings();
|
|
3709
4300
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
3710
4301
|
const payload = safeJsonStringify(request);
|
|
3711
|
-
const hash = (0,
|
|
4302
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3712
4303
|
const previous = this.lastDebugRequestPayload;
|
|
3713
4304
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3714
4305
|
if (settings.enabled) {
|
|
@@ -3764,9 +4355,183 @@ var ChatMoonshot = class {
|
|
|
3764
4355
|
};
|
|
3765
4356
|
|
|
3766
4357
|
// src/llm/openai/chat.ts
|
|
3767
|
-
var
|
|
4358
|
+
var import_node_crypto5 = require("crypto");
|
|
4359
|
+
var import_openai5 = __toESM(require("openai"), 1);
|
|
4360
|
+
|
|
4361
|
+
// src/llm/openai/http-transport.ts
|
|
3768
4362
|
var import_openai4 = __toESM(require("openai"), 1);
|
|
3769
4363
|
|
|
4364
|
+
// src/llm/openai/codex-metadata.ts
|
|
4365
|
+
var import_node_crypto4 = require("crypto");
|
|
4366
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
4367
|
+
var identifier = (value) => typeof value === "string" && /^[a-zA-Z0-9._/-]{1,128}$/.test(value) ? value : void 0;
|
|
4368
|
+
var stringList = (value) => Array.isArray(value) && value.length <= 64 && value.every((item) => typeof item === "string");
|
|
4369
|
+
var headerValue = (headers, name) => {
|
|
4370
|
+
const entries = record2(headers);
|
|
4371
|
+
const value = entries && Object.entries(entries).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
4372
|
+
return typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : void 0;
|
|
4373
|
+
};
|
|
4374
|
+
var isCodexBackend = (baseURL) => {
|
|
4375
|
+
try {
|
|
4376
|
+
const url = new URL(baseURL);
|
|
4377
|
+
return url.origin === "https://chatgpt.com" && url.pathname.replace(/\/$/, "") === "/backend-api/codex";
|
|
4378
|
+
} catch {
|
|
4379
|
+
return false;
|
|
4380
|
+
}
|
|
4381
|
+
};
|
|
4382
|
+
var CodexTurnState = class {
|
|
4383
|
+
owner;
|
|
4384
|
+
value;
|
|
4385
|
+
invalidated = false;
|
|
4386
|
+
bindAuth(headers) {
|
|
4387
|
+
const authorization = headers.get("authorization") ?? "";
|
|
4388
|
+
let identity = authorization;
|
|
4389
|
+
try {
|
|
4390
|
+
const claims = record2(
|
|
4391
|
+
JSON.parse(
|
|
4392
|
+
Buffer.from(
|
|
4393
|
+
authorization.replace(/^Bearer /i, "").split(".")[1],
|
|
4394
|
+
"base64url"
|
|
4395
|
+
).toString("utf8")
|
|
4396
|
+
)
|
|
4397
|
+
);
|
|
4398
|
+
if (typeof claims?.sub === "string" && typeof claims.iss === "string") {
|
|
4399
|
+
const account = record2(
|
|
4400
|
+
claims["https://api.openai.com/auth"]
|
|
4401
|
+
)?.chatgpt_account_id;
|
|
4402
|
+
identity = JSON.stringify([
|
|
4403
|
+
claims.iss,
|
|
4404
|
+
claims.sub,
|
|
4405
|
+
typeof claims.client_id === "string" ? claims.client_id : null,
|
|
4406
|
+
typeof account === "string" ? account : null
|
|
4407
|
+
]);
|
|
4408
|
+
}
|
|
4409
|
+
} catch {
|
|
4410
|
+
}
|
|
4411
|
+
const owner = (0, import_node_crypto4.createHash)("sha256").update(identity).update("\0").update(headers.get("chatgpt-account-id") ?? "").digest("hex");
|
|
4412
|
+
const changed = this.owner !== void 0 && this.owner !== owner;
|
|
4413
|
+
if (changed) {
|
|
4414
|
+
this.value = void 0;
|
|
4415
|
+
this.invalidated = true;
|
|
4416
|
+
}
|
|
4417
|
+
this.owner = owner;
|
|
4418
|
+
return this.invalidated;
|
|
4419
|
+
}
|
|
4420
|
+
observe(value) {
|
|
4421
|
+
if (this.value === void 0 && typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[!-~]+$/.test(value))
|
|
4422
|
+
this.value = value;
|
|
4423
|
+
}
|
|
4424
|
+
requestHeaders() {
|
|
4425
|
+
return this.value ? { "x-codex-turn-state": this.value } : {};
|
|
4426
|
+
}
|
|
4427
|
+
};
|
|
4428
|
+
var CodexMetadataCollector = class {
|
|
4429
|
+
constructor(routing, onStatus) {
|
|
4430
|
+
this.routing = routing;
|
|
4431
|
+
this.onStatus = onStatus;
|
|
4432
|
+
}
|
|
4433
|
+
routing;
|
|
4434
|
+
onStatus;
|
|
4435
|
+
summary = {};
|
|
4436
|
+
outputStarted = false;
|
|
4437
|
+
fallbackModel;
|
|
4438
|
+
verificationNotified = false;
|
|
4439
|
+
beginAttempt() {
|
|
4440
|
+
this.clearBuffering();
|
|
4441
|
+
for (const key of Object.keys(this.summary))
|
|
4442
|
+
delete this.summary[key];
|
|
4443
|
+
this.outputStarted = false;
|
|
4444
|
+
this.fallbackModel = void 0;
|
|
4445
|
+
}
|
|
4446
|
+
observeHeaders(headers) {
|
|
4447
|
+
this.routing?.observe(headers.get("x-codex-turn-state"));
|
|
4448
|
+
const model = identifier(
|
|
4449
|
+
headers.get("openai-model") ?? headers.get("x-openai-model")
|
|
4450
|
+
);
|
|
4451
|
+
if (model) this.summary.server_model = model;
|
|
4452
|
+
this.fallbackModel = identifier(
|
|
4453
|
+
headers.get("x-codex-safety-buffering-faster-model")
|
|
4454
|
+
);
|
|
4455
|
+
}
|
|
4456
|
+
observeEvent(event) {
|
|
4457
|
+
const value = record2(event);
|
|
4458
|
+
if (!value) return;
|
|
4459
|
+
const response = record2(value.response);
|
|
4460
|
+
const model = identifier(
|
|
4461
|
+
headerValue(response?.headers, "openai-model") ?? headerValue(response?.headers, "x-openai-model") ?? headerValue(value.headers, "openai-model") ?? headerValue(value.headers, "x-openai-model")
|
|
4462
|
+
);
|
|
4463
|
+
if (model) this.summary.server_model = model;
|
|
4464
|
+
const metadata = value.type === "response.metadata" ? record2(value.metadata) : void 0;
|
|
4465
|
+
if (value.type === "response.metadata")
|
|
4466
|
+
this.routing?.observe(headerValue(value.headers, "x-codex-turn-state"));
|
|
4467
|
+
const verifications = metadata?.openai_verification_recommendation;
|
|
4468
|
+
if (Array.isArray(verifications) && verifications.includes("trusted_access_for_cyber") && !this.summary.model_verifications) {
|
|
4469
|
+
this.summary.model_verifications = ["trusted_access_for_cyber"];
|
|
4470
|
+
if (!this.verificationNotified) {
|
|
4471
|
+
this.verificationNotified = true;
|
|
4472
|
+
this.emit({
|
|
4473
|
+
type: "llm.status",
|
|
4474
|
+
provider: "openai",
|
|
4475
|
+
kind: "verification",
|
|
4476
|
+
verification: "trusted_access_for_cyber"
|
|
4477
|
+
});
|
|
4478
|
+
}
|
|
4479
|
+
}
|
|
4480
|
+
if (metadata && Object.hasOwn(metadata, "openai_chatgpt_moderation_metadata"))
|
|
4481
|
+
this.summary.moderation_metadata_present = true;
|
|
4482
|
+
const buffering = record2(
|
|
4483
|
+
value.safety_buffering ?? (metadata?.type === "safety_buffering" ? metadata : void 0)
|
|
4484
|
+
);
|
|
4485
|
+
if (buffering && stringList(buffering.use_cases) && stringList(buffering.reasons)) {
|
|
4486
|
+
const faster = Object.hasOwn(buffering, "retry_model") ? identifier(buffering.retry_model) : this.fallbackModel;
|
|
4487
|
+
const wasActive = this.summary.safety_buffering?.active;
|
|
4488
|
+
this.summary.safety_buffering = {
|
|
4489
|
+
active: !this.outputStarted,
|
|
4490
|
+
use_case_count: buffering.use_cases.length,
|
|
4491
|
+
reason_count: buffering.reasons.length,
|
|
4492
|
+
...faster ? { faster_model: faster } : {}
|
|
4493
|
+
};
|
|
4494
|
+
if (!this.outputStarted && !wasActive)
|
|
4495
|
+
this.emit({
|
|
4496
|
+
type: "llm.status",
|
|
4497
|
+
provider: "openai",
|
|
4498
|
+
kind: "buffering",
|
|
4499
|
+
active: true,
|
|
4500
|
+
...faster ? { faster_model: faster } : {}
|
|
4501
|
+
});
|
|
4502
|
+
}
|
|
4503
|
+
if ((value.type === "response.output_text.delta" || value.type === "response.refusal.delta") && typeof value.delta === "string" && value.delta.length > 0) {
|
|
4504
|
+
this.outputStarted = true;
|
|
4505
|
+
this.clearBuffering();
|
|
4506
|
+
}
|
|
4507
|
+
if (value.type === "response.completed" || value.type === "response.incomplete" || value.type === "response.done" || value.type === "response.failed" || value.type === "error")
|
|
4508
|
+
this.clearBuffering();
|
|
4509
|
+
}
|
|
4510
|
+
finish() {
|
|
4511
|
+
this.clearBuffering();
|
|
4512
|
+
}
|
|
4513
|
+
snapshot() {
|
|
4514
|
+
return Object.keys(this.summary).length ? structuredClone(this.summary) : void 0;
|
|
4515
|
+
}
|
|
4516
|
+
clearBuffering() {
|
|
4517
|
+
if (this.summary.safety_buffering?.active) {
|
|
4518
|
+
this.summary.safety_buffering.active = false;
|
|
4519
|
+
this.emit({
|
|
4520
|
+
type: "llm.status",
|
|
4521
|
+
provider: "openai",
|
|
4522
|
+
kind: "buffering",
|
|
4523
|
+
active: false
|
|
4524
|
+
});
|
|
4525
|
+
}
|
|
4526
|
+
}
|
|
4527
|
+
emit(event) {
|
|
4528
|
+
try {
|
|
4529
|
+
this.onStatus?.(event);
|
|
4530
|
+
} catch {
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
};
|
|
4534
|
+
|
|
3770
4535
|
// src/llm/openai/response-utils.ts
|
|
3771
4536
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
3772
4537
|
var stringifyUnknown3 = (value) => {
|
|
@@ -3808,12 +4573,12 @@ var extractOutputText = (items) => {
|
|
|
3808
4573
|
}
|
|
3809
4574
|
return texts.join("");
|
|
3810
4575
|
};
|
|
3811
|
-
var getRecordString = (
|
|
3812
|
-
const value =
|
|
4576
|
+
var getRecordString = (record3, key) => {
|
|
4577
|
+
const value = record3[key];
|
|
3813
4578
|
return typeof value === "string" ? value : void 0;
|
|
3814
4579
|
};
|
|
3815
|
-
var getRecordNumber = (
|
|
3816
|
-
const value =
|
|
4580
|
+
var getRecordNumber = (record3, key) => {
|
|
4581
|
+
const value = record3[key];
|
|
3817
4582
|
return typeof value === "number" ? value : void 0;
|
|
3818
4583
|
};
|
|
3819
4584
|
var clipDebugText = (value, maxChars = 80) => value.length <= maxChars ? value : `${value.slice(0, maxChars)}...`;
|
|
@@ -3823,6 +4588,10 @@ var getResponseStreamEventDebugPayload = (event) => {
|
|
|
3823
4588
|
sequence_number: typeof event.sequence_number === "number" ? event.sequence_number : null
|
|
3824
4589
|
};
|
|
3825
4590
|
const eventRecord = event;
|
|
4591
|
+
const metadata = new CodexMetadataCollector();
|
|
4592
|
+
metadata.observeEvent(event);
|
|
4593
|
+
const summary = metadata.snapshot();
|
|
4594
|
+
if (summary) payload.metadata_summary = summary;
|
|
3826
4595
|
const outputIndex = getRecordNumber(eventRecord, "output_index");
|
|
3827
4596
|
if (outputIndex !== void 0) {
|
|
3828
4597
|
payload.output_index = outputIndex;
|
|
@@ -3976,6 +4745,9 @@ var OpenAiResponseAccumulator = class {
|
|
|
3976
4745
|
terminalResponse = null;
|
|
3977
4746
|
outputItems = [];
|
|
3978
4747
|
observeEvent(event) {
|
|
4748
|
+
const type = event.type;
|
|
4749
|
+
if (type === "response.metadata" || type === "codex.response.metadata")
|
|
4750
|
+
return;
|
|
3979
4751
|
switch (event.type) {
|
|
3980
4752
|
case "response.created":
|
|
3981
4753
|
case "response.queued":
|
|
@@ -4327,22 +5099,64 @@ var OpenAiResponseAccumulator = class {
|
|
|
4327
5099
|
};
|
|
4328
5100
|
|
|
4329
5101
|
// src/llm/openai/http-transport.ts
|
|
4330
|
-
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent) => {
|
|
5102
|
+
var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent, codex) => {
|
|
4331
5103
|
const streamRequest = {
|
|
4332
5104
|
...request,
|
|
4333
5105
|
stream: true
|
|
4334
5106
|
};
|
|
4335
|
-
const
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
5107
|
+
const options = signal || sessionIdHeader ? {
|
|
5108
|
+
...signal ? { signal } : {},
|
|
5109
|
+
...sessionIdHeader ? {
|
|
5110
|
+
headers: {
|
|
5111
|
+
session_id: sessionIdHeader
|
|
5112
|
+
}
|
|
5113
|
+
} : {}
|
|
5114
|
+
} : void 0;
|
|
5115
|
+
if (isCodexBackend(client.baseURL)) {
|
|
5116
|
+
codex?.metadata.beginAttempt();
|
|
5117
|
+
const sourceFetch = client.fetch;
|
|
5118
|
+
let ownershipError;
|
|
5119
|
+
const requestClient = codex ? client.withOptions({
|
|
5120
|
+
fetch: async (input, init) => {
|
|
5121
|
+
const headers = new Headers(init?.headers);
|
|
5122
|
+
if (codex.routing?.bindAuth(headers)) {
|
|
5123
|
+
ownershipError = createProviderValidationError(
|
|
5124
|
+
"openai",
|
|
5125
|
+
"OpenAI authentication changed; start a new run"
|
|
5126
|
+
);
|
|
5127
|
+
throw ownershipError;
|
|
4342
5128
|
}
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
5129
|
+
for (const [key, value] of Object.entries(
|
|
5130
|
+
codex.routing?.requestHeaders() ?? {}
|
|
5131
|
+
))
|
|
5132
|
+
headers.set(key, value);
|
|
5133
|
+
const response = await sourceFetch(input, { ...init, headers });
|
|
5134
|
+
codex.metadata.observeHeaders(response.headers);
|
|
5135
|
+
return response;
|
|
5136
|
+
}
|
|
5137
|
+
}) : client;
|
|
5138
|
+
const stream2 = await requestClient.responses.create(streamRequest, options).catch((error) => {
|
|
5139
|
+
throw ownershipError ?? error;
|
|
5140
|
+
});
|
|
5141
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
5142
|
+
for await (const event of stream2) {
|
|
5143
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5144
|
+
codex?.metadata.observeEvent(event);
|
|
5145
|
+
await onEvent?.(event);
|
|
5146
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5147
|
+
if (event.type === "response.failed") {
|
|
5148
|
+
throw event.response.error ?? new Error("OpenAI stream failed");
|
|
5149
|
+
}
|
|
5150
|
+
if (event.type === "error") throw event;
|
|
5151
|
+
accumulator.observeEvent(event);
|
|
5152
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
5153
|
+
return accumulator.buildResponse(event.response);
|
|
5154
|
+
}
|
|
5155
|
+
}
|
|
5156
|
+
if (signal?.aborted) throw new import_openai4.default.APIUserAbortError();
|
|
5157
|
+
throw new Error("OpenAI stream ended without a terminal response");
|
|
5158
|
+
}
|
|
5159
|
+
const stream = client.responses.stream(streamRequest, options);
|
|
4346
5160
|
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
4347
5161
|
const accumulator = new OpenAiResponseAccumulator();
|
|
4348
5162
|
for await (const event of stream) {
|
|
@@ -4393,12 +5207,12 @@ var formatOtherPart3 = (part) => {
|
|
|
4393
5207
|
};
|
|
4394
5208
|
var isOpenAIAssistantInputContent = (value) => {
|
|
4395
5209
|
if (!value || typeof value !== "object") return false;
|
|
4396
|
-
const
|
|
4397
|
-
if (
|
|
4398
|
-
return typeof
|
|
5210
|
+
const record3 = value;
|
|
5211
|
+
if (record3.type === "output_text") {
|
|
5212
|
+
return typeof record3.text === "string";
|
|
4399
5213
|
}
|
|
4400
|
-
if (
|
|
4401
|
-
return typeof
|
|
5214
|
+
if (record3.type === "refusal") {
|
|
5215
|
+
return typeof record3.refusal === "string";
|
|
4402
5216
|
}
|
|
4403
5217
|
return false;
|
|
4404
5218
|
};
|
|
@@ -4416,8 +5230,8 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
4416
5230
|
if (!value || typeof value !== "object") {
|
|
4417
5231
|
return false;
|
|
4418
5232
|
}
|
|
4419
|
-
const
|
|
4420
|
-
return
|
|
5233
|
+
const record3 = value;
|
|
5234
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
4421
5235
|
};
|
|
4422
5236
|
var toReplayableFunctionCallItemId = (value) => {
|
|
4423
5237
|
if (typeof value !== "string") {
|
|
@@ -4468,14 +5282,14 @@ var extractReasoningText = (item) => {
|
|
|
4468
5282
|
};
|
|
4469
5283
|
var extractWebSearchSummary = (item) => {
|
|
4470
5284
|
const parts = [`WebSearch status=${item.status}`];
|
|
4471
|
-
const
|
|
4472
|
-
const queries = Array.isArray(
|
|
5285
|
+
const record3 = item;
|
|
5286
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
4473
5287
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
4474
5288
|
) : [];
|
|
4475
5289
|
if (queries.length) {
|
|
4476
5290
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
4477
5291
|
}
|
|
4478
|
-
const sources = Array.isArray(
|
|
5292
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
4479
5293
|
if (sources.length) {
|
|
4480
5294
|
parts.push(`sources=${sources.length}`);
|
|
4481
5295
|
}
|
|
@@ -4646,6 +5460,9 @@ function toChatInvokeCompletion2(response, meta) {
|
|
|
4646
5460
|
input_tokens: response.usage.input_tokens,
|
|
4647
5461
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
4648
5462
|
output_tokens: response.usage.output_tokens,
|
|
5463
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
5464
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
5465
|
+
} : {},
|
|
4649
5466
|
total_tokens: response.usage.total_tokens
|
|
4650
5467
|
} : null;
|
|
4651
5468
|
const messages = toMessageSequence(response);
|
|
@@ -4751,6 +5568,14 @@ var WS_UNEXPECTED_RESPONSE_BODY_MAX_CHARS = 2e3;
|
|
|
4751
5568
|
var OPENAI_BETA_HEADER = "OpenAI-Beta";
|
|
4752
5569
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V1 = "responses_websockets=2026-02-04";
|
|
4753
5570
|
var OPENAI_BETA_RESPONSES_WEBSOCKETS_V2 = "responses_websockets=2026-02-06";
|
|
5571
|
+
var OpenAiWsMessageTooLargeError = class extends ProviderFailureError {
|
|
5572
|
+
constructor() {
|
|
5573
|
+
super({
|
|
5574
|
+
...buildProviderFailure("openai", "validation"),
|
|
5575
|
+
safeMessage: "OpenAI WebSocket message exceeded the server size limit (1009). WebSocket-only mode does not resend this request; auto mode can fall back to HTTP. Compact oversized history if needed. Saved originals are unchanged."
|
|
5576
|
+
});
|
|
5577
|
+
}
|
|
5578
|
+
};
|
|
4754
5579
|
var resolveTimeoutMs = (value, fallbackMs) => {
|
|
4755
5580
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
4756
5581
|
return fallbackMs;
|
|
@@ -4832,6 +5657,8 @@ var OpenAiWsTransport = class {
|
|
|
4832
5657
|
);
|
|
4833
5658
|
}
|
|
4834
5659
|
async invoke(args) {
|
|
5660
|
+
const timing = new LlmStreamTiming();
|
|
5661
|
+
args.codex?.metadata.beginAttempt();
|
|
4835
5662
|
await this.prepareClientForWsHandshake();
|
|
4836
5663
|
const wsOptionsHeaders = {
|
|
4837
5664
|
...this.getClientDefaultHeaders(),
|
|
@@ -4840,6 +5667,19 @@ var OpenAiWsTransport = class {
|
|
|
4840
5667
|
if (args.sessionIdHeader) {
|
|
4841
5668
|
wsOptionsHeaders.session_id = args.sessionIdHeader;
|
|
4842
5669
|
}
|
|
5670
|
+
if (args.codex?.routing) {
|
|
5671
|
+
const authHeaders = new Headers(wsOptionsHeaders);
|
|
5672
|
+
authHeaders.set("authorization", `Bearer ${this.client.apiKey ?? ""}`);
|
|
5673
|
+
if (args.codex.routing.bindAuth(authHeaders)) {
|
|
5674
|
+
if (args.ws)
|
|
5675
|
+
this.closeWithoutMaskingPrimaryError(args.ws, "auth_changed");
|
|
5676
|
+
throw createProviderValidationError(
|
|
5677
|
+
"openai",
|
|
5678
|
+
"OpenAI authentication changed; start a new run"
|
|
5679
|
+
);
|
|
5680
|
+
}
|
|
5681
|
+
Object.assign(wsOptionsHeaders, args.codex.routing.requestHeaders());
|
|
5682
|
+
}
|
|
4843
5683
|
const wsOptions = { headers: wsOptionsHeaders };
|
|
4844
5684
|
const ownsWs = !args.ws;
|
|
4845
5685
|
const ws = args.ws ?? (this.createResponsesWs ? this.createResponsesWs(this.client, wsOptions) : new import_ws.ResponsesWS(
|
|
@@ -4850,6 +5690,15 @@ var OpenAiWsTransport = class {
|
|
|
4850
5690
|
ws.on("error", () => {
|
|
4851
5691
|
});
|
|
4852
5692
|
}
|
|
5693
|
+
const removeUpgrade = args.codex ? this.addNativeSocketListener(
|
|
5694
|
+
this.getNativeSocket(ws),
|
|
5695
|
+
"upgrade",
|
|
5696
|
+
(response) => {
|
|
5697
|
+
const headers = response?.headers;
|
|
5698
|
+
if (headers)
|
|
5699
|
+
args.codex?.metadata.observeHeaders(new Headers(headers));
|
|
5700
|
+
}
|
|
5701
|
+
) : void 0;
|
|
4853
5702
|
try {
|
|
4854
5703
|
await this.waitForWsOpen(ws, args.signal);
|
|
4855
5704
|
const closeWs = () => {
|
|
@@ -4858,11 +5707,14 @@ var OpenAiWsTransport = class {
|
|
|
4858
5707
|
const responseWaiter = this.createResponsePromise({
|
|
4859
5708
|
ws,
|
|
4860
5709
|
signal: args.signal,
|
|
4861
|
-
closeWs
|
|
5710
|
+
closeWs,
|
|
5711
|
+
timing,
|
|
5712
|
+
metadata: args.codex?.metadata
|
|
4862
5713
|
});
|
|
4863
5714
|
const responseCreateEvent = {
|
|
4864
5715
|
type: "response.create",
|
|
4865
|
-
...args.request
|
|
5716
|
+
...args.request,
|
|
5717
|
+
...args.codex?.routing && Object.keys(args.codex.routing.requestHeaders()).length ? { client_metadata: args.codex.routing.requestHeaders() } : {}
|
|
4866
5718
|
};
|
|
4867
5719
|
if (!responseWaiter.isSettled()) {
|
|
4868
5720
|
try {
|
|
@@ -4872,12 +5724,14 @@ var OpenAiWsTransport = class {
|
|
|
4872
5724
|
}
|
|
4873
5725
|
}
|
|
4874
5726
|
const response = await responseWaiter.responsePromise;
|
|
4875
|
-
return { response, ws };
|
|
5727
|
+
return { response, ws, timing: timing.finish() };
|
|
4876
5728
|
} catch (error) {
|
|
4877
5729
|
if (ownsWs) {
|
|
4878
5730
|
this.closeWithoutMaskingPrimaryError(ws, "failed", error);
|
|
4879
5731
|
}
|
|
4880
5732
|
throw error;
|
|
5733
|
+
} finally {
|
|
5734
|
+
removeUpgrade?.();
|
|
4881
5735
|
}
|
|
4882
5736
|
}
|
|
4883
5737
|
createResponsePromise(args) {
|
|
@@ -4967,6 +5821,7 @@ var OpenAiWsTransport = class {
|
|
|
4967
5821
|
rejectOnce(error);
|
|
4968
5822
|
};
|
|
4969
5823
|
const resolveFromTerminalEvent = (event, type) => {
|
|
5824
|
+
args.timing.complete();
|
|
4970
5825
|
const response = event?.response;
|
|
4971
5826
|
if (response && typeof response === "object") {
|
|
4972
5827
|
accumulator.observeTerminalResponse(response);
|
|
@@ -4989,6 +5844,9 @@ var OpenAiWsTransport = class {
|
|
|
4989
5844
|
);
|
|
4990
5845
|
};
|
|
4991
5846
|
const onEvent = (event) => {
|
|
5847
|
+
if (settled) return;
|
|
5848
|
+
args.metadata?.observeEvent(event);
|
|
5849
|
+
args.timing.observeResponsesEvent(event);
|
|
4992
5850
|
const eventType = this.extractResponsesEventType(event);
|
|
4993
5851
|
if (!eventType) {
|
|
4994
5852
|
return;
|
|
@@ -5037,7 +5895,7 @@ var OpenAiWsTransport = class {
|
|
|
5037
5895
|
const onClose = (event) => {
|
|
5038
5896
|
const closeCode = this.extractWsCloseCode(event);
|
|
5039
5897
|
rejectOnce(
|
|
5040
|
-
new Error(
|
|
5898
|
+
closeCode === 1009 ? new OpenAiWsMessageTooLargeError() : new Error(
|
|
5041
5899
|
`openai websocket closed before response${closeCode ? ` code=${closeCode}` : ""}`
|
|
5042
5900
|
)
|
|
5043
5901
|
);
|
|
@@ -5306,6 +6164,8 @@ var OpenAiWsTransport = class {
|
|
|
5306
6164
|
return void 0;
|
|
5307
6165
|
}
|
|
5308
6166
|
const limited = entries.slice(0, 12).map(([key, value]) => {
|
|
6167
|
+
if (/^(x-codex-turn-state|authorization|cookie|set-cookie)$/i.test(key))
|
|
6168
|
+
return `${key}:[redacted]`;
|
|
5309
6169
|
const text = Array.isArray(value) ? value.map((entry) => String(entry)).join("|") : String(value);
|
|
5310
6170
|
return `${key}:${text}`;
|
|
5311
6171
|
});
|
|
@@ -5510,7 +6370,6 @@ var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
|
5510
6370
|
};
|
|
5511
6371
|
var WS_SESSION_IDLE_TTL_MS = 10 * 6e4;
|
|
5512
6372
|
var WS_SESSION_DISABLE_TTL_MS = 6e4;
|
|
5513
|
-
var WS_REUSE_MAX_IDLE_MS = 3e4;
|
|
5514
6373
|
var ChatOpenAI = class {
|
|
5515
6374
|
provider = PROVIDER_NAME5;
|
|
5516
6375
|
model;
|
|
@@ -5529,8 +6388,9 @@ var ChatOpenAI = class {
|
|
|
5529
6388
|
wsStateBySessionKey = /* @__PURE__ */ new Map();
|
|
5530
6389
|
wsDisabledUntilBySessionKey = /* @__PURE__ */ new Map();
|
|
5531
6390
|
wsReconnectCount = 0;
|
|
6391
|
+
codexTurns = /* @__PURE__ */ new Map();
|
|
5532
6392
|
constructor(options = {}) {
|
|
5533
|
-
this.client = options.client ?? new
|
|
6393
|
+
this.client = options.client ?? new import_openai5.default({
|
|
5534
6394
|
...options.clientOptions ?? {},
|
|
5535
6395
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
5536
6396
|
});
|
|
@@ -5613,17 +6473,32 @@ var ChatOpenAI = class {
|
|
|
5613
6473
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
5614
6474
|
const requestMeta = {
|
|
5615
6475
|
model: String(request.model ?? this.providerModel),
|
|
5616
|
-
instructionsHash: (0,
|
|
5617
|
-
toolsHash: (0,
|
|
6476
|
+
instructionsHash: (0, import_node_crypto5.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12),
|
|
6477
|
+
toolsHash: (0, import_node_crypto5.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12)
|
|
5618
6478
|
};
|
|
5619
|
-
const
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
6479
|
+
const codex = isCodexBackend(this.client.baseURL) ? this.createCodexMetadata(context) : void 0;
|
|
6480
|
+
let transportResult;
|
|
6481
|
+
try {
|
|
6482
|
+
transportResult = await this.invokeWithTransport({
|
|
6483
|
+
request,
|
|
6484
|
+
sessionKey: context?.sessionKey,
|
|
6485
|
+
sessionIdHeader,
|
|
6486
|
+
signal,
|
|
6487
|
+
debugSeq,
|
|
6488
|
+
requestMeta,
|
|
6489
|
+
...codex?.metadata ? { codex: { routing: codex.routing, metadata: codex.metadata } } : {}
|
|
6490
|
+
});
|
|
6491
|
+
} finally {
|
|
6492
|
+
codex?.metadata?.finish();
|
|
6493
|
+
}
|
|
6494
|
+
const codexMetadata = codex?.metadata?.snapshot();
|
|
6495
|
+
if (codex) {
|
|
6496
|
+
const { headers: _headers, ...response } = transportResult.response;
|
|
6497
|
+
transportResult.response = {
|
|
6498
|
+
...response,
|
|
6499
|
+
...codexMetadata?.server_model ? { model: codexMetadata.server_model } : {}
|
|
6500
|
+
};
|
|
6501
|
+
}
|
|
5627
6502
|
await this.debugResponseIfEnabled(
|
|
5628
6503
|
transportResult.response,
|
|
5629
6504
|
debugSeq,
|
|
@@ -5647,7 +6522,42 @@ var ChatOpenAI = class {
|
|
|
5647
6522
|
debugSeq,
|
|
5648
6523
|
transportResult.transport
|
|
5649
6524
|
);
|
|
5650
|
-
return
|
|
6525
|
+
return {
|
|
6526
|
+
...completion,
|
|
6527
|
+
...codexMetadata ? {
|
|
6528
|
+
provider_meta: {
|
|
6529
|
+
...completion.provider_meta,
|
|
6530
|
+
codex_metadata: codexMetadata
|
|
6531
|
+
}
|
|
6532
|
+
} : {},
|
|
6533
|
+
...transportResult.timing ? { timing: transportResult.timing } : {}
|
|
6534
|
+
};
|
|
6535
|
+
}
|
|
6536
|
+
createCodexMetadata(context) {
|
|
6537
|
+
const routing = this.resolveCodexTurn(context);
|
|
6538
|
+
return {
|
|
6539
|
+
routing,
|
|
6540
|
+
metadata: new CodexMetadataCollector(routing, context?.onProviderStatus)
|
|
6541
|
+
};
|
|
6542
|
+
}
|
|
6543
|
+
resolveCodexTurn(context) {
|
|
6544
|
+
if (!context?.turnKey) return void 0;
|
|
6545
|
+
const key = context.sessionKey ?? context.turnKey;
|
|
6546
|
+
let state = this.codexTurns.get(key);
|
|
6547
|
+
if (!state || state.turnKey !== context.turnKey) {
|
|
6548
|
+
this.clearWsSessionState(key, "new_turn");
|
|
6549
|
+
state = { turnKey: context.turnKey, routing: new CodexTurnState() };
|
|
6550
|
+
this.codexTurns.delete(key);
|
|
6551
|
+
this.codexTurns.set(key, state);
|
|
6552
|
+
if (this.codexTurns.size > 16) {
|
|
6553
|
+
const oldest = this.codexTurns.keys().next().value;
|
|
6554
|
+
if (oldest !== void 0) {
|
|
6555
|
+
this.codexTurns.delete(oldest);
|
|
6556
|
+
this.clearWsSessionState(oldest, "turn_state_evicted");
|
|
6557
|
+
}
|
|
6558
|
+
}
|
|
6559
|
+
}
|
|
6560
|
+
return state.routing;
|
|
5651
6561
|
}
|
|
5652
6562
|
onHistoryCompacted(context) {
|
|
5653
6563
|
const sessionKey = context?.sessionKey;
|
|
@@ -5665,6 +6575,7 @@ var ChatOpenAI = class {
|
|
|
5665
6575
|
this.evictIdleWsSessionState();
|
|
5666
6576
|
if (this.websocketMode === "off") {
|
|
5667
6577
|
return this.invokeHttpTransportWithDebug({
|
|
6578
|
+
codex: args.codex,
|
|
5668
6579
|
request: args.request,
|
|
5669
6580
|
debugSeq: args.debugSeq,
|
|
5670
6581
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5680,6 +6591,7 @@ var ChatOpenAI = class {
|
|
|
5680
6591
|
);
|
|
5681
6592
|
}
|
|
5682
6593
|
return this.invokeHttpTransportWithDebug({
|
|
6594
|
+
codex: args.codex,
|
|
5683
6595
|
request: args.request,
|
|
5684
6596
|
debugSeq: args.debugSeq,
|
|
5685
6597
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5690,6 +6602,7 @@ var ChatOpenAI = class {
|
|
|
5690
6602
|
}
|
|
5691
6603
|
if (this.isWsSessionDisabled(args.sessionKey)) {
|
|
5692
6604
|
return this.invokeHttpTransportWithDebug({
|
|
6605
|
+
codex: args.codex,
|
|
5693
6606
|
request: args.request,
|
|
5694
6607
|
debugSeq: args.debugSeq,
|
|
5695
6608
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5699,7 +6612,7 @@ var ChatOpenAI = class {
|
|
|
5699
6612
|
});
|
|
5700
6613
|
}
|
|
5701
6614
|
const wsState = this.wsStateBySessionKey.get(args.sessionKey) ?? {};
|
|
5702
|
-
const hasReusableWs = this.isWsConnectionReusable(wsState.ws)
|
|
6615
|
+
const hasReusableWs = this.isWsConnectionReusable(wsState.ws);
|
|
5703
6616
|
const shouldResetChain = wsState.model !== args.requestMeta.model || wsState.instructionsHash !== args.requestMeta.instructionsHash || wsState.toolsHash !== args.requestMeta.toolsHash || Boolean(wsState.ws) && !hasReusableWs;
|
|
5704
6617
|
const incrementalInput = this.getIncrementalInput(
|
|
5705
6618
|
wsState.lastInput,
|
|
@@ -5747,7 +6660,8 @@ var ChatOpenAI = class {
|
|
|
5747
6660
|
wsExecutionPlan.chainReset,
|
|
5748
6661
|
wsExecutionPlan.wsInputMode
|
|
5749
6662
|
);
|
|
5750
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6663
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6664
|
+
codex: args.codex,
|
|
5751
6665
|
request: wsExecutionPlan.request,
|
|
5752
6666
|
signal: args.signal,
|
|
5753
6667
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5763,12 +6677,17 @@ var ChatOpenAI = class {
|
|
|
5763
6677
|
return {
|
|
5764
6678
|
response,
|
|
5765
6679
|
transport: "ws_mode",
|
|
6680
|
+
...timing ? { timing } : {},
|
|
5766
6681
|
fallbackUsed: false,
|
|
5767
6682
|
chainReset: wsExecutionPlan.chainReset,
|
|
5768
6683
|
wsInputMode: wsExecutionPlan.wsInputMode
|
|
5769
6684
|
};
|
|
5770
6685
|
} catch (error) {
|
|
5771
6686
|
let failure = error;
|
|
6687
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6688
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6689
|
+
throw failure;
|
|
6690
|
+
}
|
|
5772
6691
|
if (this.websocketMode === "on" && this.isWsReconnectRetryableError(failure)) {
|
|
5773
6692
|
const retryWsInputMode = wsState.previousResponseId ? "full_regenerated" : "full_no_previous";
|
|
5774
6693
|
this.closeWsWithoutMaskingPrimaryError(
|
|
@@ -5786,7 +6705,8 @@ var ChatOpenAI = class {
|
|
|
5786
6705
|
true,
|
|
5787
6706
|
retryWsInputMode
|
|
5788
6707
|
);
|
|
5789
|
-
const { response, ws } = await this.invokeViaWs({
|
|
6708
|
+
const { response, ws, timing } = await this.invokeViaWs({
|
|
6709
|
+
codex: args.codex,
|
|
5790
6710
|
request: args.request,
|
|
5791
6711
|
signal: args.signal,
|
|
5792
6712
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5803,6 +6723,7 @@ var ChatOpenAI = class {
|
|
|
5803
6723
|
return {
|
|
5804
6724
|
response,
|
|
5805
6725
|
transport: "ws_mode",
|
|
6726
|
+
...timing ? { timing } : {},
|
|
5806
6727
|
fallbackUsed: false,
|
|
5807
6728
|
chainReset: true,
|
|
5808
6729
|
wsInputMode: retryWsInputMode
|
|
@@ -5811,9 +6732,13 @@ var ChatOpenAI = class {
|
|
|
5811
6732
|
failure = retryError;
|
|
5812
6733
|
}
|
|
5813
6734
|
}
|
|
6735
|
+
if (isProviderFailureError(failure) && !(fallbackAllowed && failure instanceof OpenAiWsMessageTooLargeError)) {
|
|
6736
|
+
this.clearWsSessionState(args.sessionKey, "terminal_failure", failure);
|
|
6737
|
+
throw failure;
|
|
6738
|
+
}
|
|
5814
6739
|
const wsErrorCode = this.extractWsErrorCode(failure);
|
|
5815
6740
|
const wsErrorMessage = failure instanceof Error ? failure.message.toLowerCase() : "";
|
|
5816
|
-
const shouldDisableWsForSession = wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
6741
|
+
const shouldDisableWsForSession = failure instanceof OpenAiWsMessageTooLargeError || wsErrorCode === "previous_response_not_found" || wsErrorMessage.includes("previous_response_not_found") || wsErrorMessage.includes("could not send data") || wsErrorMessage.includes("unexpected server response") || wsErrorMessage.includes("response timeout") || wsErrorMessage.includes("closed before response") || wsErrorMessage.includes("closed before open");
|
|
5817
6742
|
this.clearWsSessionState(args.sessionKey, "reset", failure);
|
|
5818
6743
|
if (shouldDisableWsForSession && fallbackAllowed) {
|
|
5819
6744
|
this.wsDisabledUntilBySessionKey.set(
|
|
@@ -5826,6 +6751,7 @@ var ChatOpenAI = class {
|
|
|
5826
6751
|
}
|
|
5827
6752
|
this.wsReconnectCount += 1;
|
|
5828
6753
|
return this.invokeHttpTransportWithDebug({
|
|
6754
|
+
codex: args.codex,
|
|
5829
6755
|
request: args.request,
|
|
5830
6756
|
debugSeq: args.debugSeq,
|
|
5831
6757
|
sessionIdHeader: args.sessionIdHeader,
|
|
@@ -5846,16 +6772,23 @@ var ChatOpenAI = class {
|
|
|
5846
6772
|
args.chainReset,
|
|
5847
6773
|
args.wsInputMode
|
|
5848
6774
|
);
|
|
6775
|
+
const timing = new LlmStreamTiming();
|
|
6776
|
+
const debugObserver = this.getHttpStreamDebugObserver(args.debugSeq);
|
|
5849
6777
|
const response = await invokeOpenAiHttp(
|
|
5850
6778
|
this.client,
|
|
5851
6779
|
args.request,
|
|
5852
6780
|
args.signal,
|
|
5853
6781
|
args.sessionIdHeader,
|
|
5854
|
-
|
|
6782
|
+
(event) => {
|
|
6783
|
+
timing.observeResponsesEvent(event);
|
|
6784
|
+
return debugObserver?.(event);
|
|
6785
|
+
},
|
|
6786
|
+
args.codex
|
|
5855
6787
|
);
|
|
5856
6788
|
return {
|
|
5857
6789
|
response,
|
|
5858
6790
|
transport: "http_stream",
|
|
6791
|
+
timing: timing.finish(),
|
|
5859
6792
|
fallbackUsed: args.fallbackUsed,
|
|
5860
6793
|
chainReset: args.chainReset
|
|
5861
6794
|
};
|
|
@@ -5893,12 +6826,6 @@ var ChatOpenAI = class {
|
|
|
5893
6826
|
closeWsWithoutMaskingPrimaryError(ws, reason, primaryError) {
|
|
5894
6827
|
this.wsTransport.closeWithoutMaskingPrimaryError(ws, reason, primaryError);
|
|
5895
6828
|
}
|
|
5896
|
-
isWsConnectionReuseExpired(lastUsedAt) {
|
|
5897
|
-
if (typeof lastUsedAt !== "number") {
|
|
5898
|
-
return false;
|
|
5899
|
-
}
|
|
5900
|
-
return Date.now() - lastUsedAt > WS_REUSE_MAX_IDLE_MS;
|
|
5901
|
-
}
|
|
5902
6829
|
isWsReconnectRetryableError(error) {
|
|
5903
6830
|
if (!(error instanceof Error)) {
|
|
5904
6831
|
return false;
|
|
@@ -5977,14 +6904,14 @@ var ChatOpenAI = class {
|
|
|
5977
6904
|
return;
|
|
5978
6905
|
}
|
|
5979
6906
|
const payload = safeJsonStringify(request);
|
|
5980
|
-
const hash = (0,
|
|
5981
|
-
const toolsHash = (0,
|
|
5982
|
-
const instructionsHash = (0,
|
|
6907
|
+
const hash = (0, import_node_crypto5.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
6908
|
+
const toolsHash = (0, import_node_crypto5.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
6909
|
+
const instructionsHash = (0, import_node_crypto5.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
5983
6910
|
const previous = this.lastDebugRequestPayload;
|
|
5984
6911
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
5985
6912
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
5986
6913
|
if (settings.enabled) {
|
|
5987
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
6914
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto5.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
5988
6915
|
const chainResetSuffix = typeof chainReset === "boolean" ? ` chain_reset=${chainReset ? "true" : "false"}` : "";
|
|
5989
6916
|
const wsInputModeSuffix = wsInputMode ? ` ws_input_mode=${wsInputMode}` : "";
|
|
5990
6917
|
console.error(
|
|
@@ -6077,8 +7004,8 @@ var ChatOpenAI = class {
|
|
|
6077
7004
|
};
|
|
6078
7005
|
|
|
6079
7006
|
// src/llm/openrouter/chat.ts
|
|
6080
|
-
var
|
|
6081
|
-
var
|
|
7007
|
+
var import_node_crypto6 = require("crypto");
|
|
7008
|
+
var import_openai7 = __toESM(require("openai"), 1);
|
|
6082
7009
|
|
|
6083
7010
|
// src/llm/openrouter/response-utils.ts
|
|
6084
7011
|
var isRecord4 = (value) => typeof value === "object" && value !== null;
|
|
@@ -6198,12 +7125,12 @@ var formatOtherPart5 = (part) => {
|
|
|
6198
7125
|
};
|
|
6199
7126
|
var isOpenAIAssistantInputContent2 = (value) => {
|
|
6200
7127
|
if (!value || typeof value !== "object") return false;
|
|
6201
|
-
const
|
|
6202
|
-
if (
|
|
6203
|
-
return typeof
|
|
7128
|
+
const record3 = value;
|
|
7129
|
+
if (record3.type === "output_text") {
|
|
7130
|
+
return typeof record3.text === "string";
|
|
6204
7131
|
}
|
|
6205
|
-
if (
|
|
6206
|
-
return typeof
|
|
7132
|
+
if (record3.type === "refusal") {
|
|
7133
|
+
return typeof record3.refusal === "string";
|
|
6207
7134
|
}
|
|
6208
7135
|
return false;
|
|
6209
7136
|
};
|
|
@@ -6211,8 +7138,8 @@ var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
|
6211
7138
|
if (!value || typeof value !== "object") {
|
|
6212
7139
|
return false;
|
|
6213
7140
|
}
|
|
6214
|
-
const
|
|
6215
|
-
return
|
|
7141
|
+
const record3 = value;
|
|
7142
|
+
return record3.type === "function_call" && typeof record3.call_id === "string" && typeof record3.name === "string" && typeof record3.arguments === "string";
|
|
6216
7143
|
};
|
|
6217
7144
|
var toReplayableFunctionCallItemId2 = (value) => {
|
|
6218
7145
|
if (typeof value !== "string") {
|
|
@@ -6263,14 +7190,14 @@ var extractReasoningText2 = (item) => {
|
|
|
6263
7190
|
};
|
|
6264
7191
|
var extractWebSearchSummary2 = (item) => {
|
|
6265
7192
|
const parts = [`WebSearch status=${item.status}`];
|
|
6266
|
-
const
|
|
6267
|
-
const queries = Array.isArray(
|
|
7193
|
+
const record3 = item;
|
|
7194
|
+
const queries = Array.isArray(record3.action?.queries) ? record3.action?.queries.filter(
|
|
6268
7195
|
(entry) => typeof entry === "string" && entry.length > 0
|
|
6269
7196
|
) : [];
|
|
6270
7197
|
if (queries.length) {
|
|
6271
7198
|
parts.push(`queries=${queries.join(" | ")}`);
|
|
6272
7199
|
}
|
|
6273
|
-
const sources = Array.isArray(
|
|
7200
|
+
const sources = Array.isArray(record3.action?.sources) ? record3.action?.sources : [];
|
|
6274
7201
|
if (sources.length) {
|
|
6275
7202
|
parts.push(`sources=${sources.length}`);
|
|
6276
7203
|
}
|
|
@@ -6437,6 +7364,9 @@ function toChatInvokeCompletion3(response, meta) {
|
|
|
6437
7364
|
input_tokens: response.usage.input_tokens,
|
|
6438
7365
|
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
6439
7366
|
output_tokens: response.usage.output_tokens,
|
|
7367
|
+
...typeof response.usage.output_tokens_details?.reasoning_tokens === "number" ? {
|
|
7368
|
+
output_reasoning_tokens: response.usage.output_tokens_details.reasoning_tokens
|
|
7369
|
+
} : {},
|
|
6440
7370
|
total_tokens: response.usage.total_tokens
|
|
6441
7371
|
} : null;
|
|
6442
7372
|
const messages = toMessageSequence2(response);
|
|
@@ -6546,7 +7476,7 @@ var ChatOpenRouter = class {
|
|
|
6546
7476
|
debugInvokeSeq = 0;
|
|
6547
7477
|
lastDebugRequestPayload = null;
|
|
6548
7478
|
constructor(options = {}) {
|
|
6549
|
-
this.client = options.client ?? new
|
|
7479
|
+
this.client = options.client ?? new import_openai7.default({
|
|
6550
7480
|
baseURL: OPENROUTER_BASE_URL,
|
|
6551
7481
|
...options.clientOptions ?? {},
|
|
6552
7482
|
maxRetries: options.clientOptions?.maxRetries ?? 0
|
|
@@ -6618,7 +7548,8 @@ var ChatOpenRouter = class {
|
|
|
6618
7548
|
...request,
|
|
6619
7549
|
stream: true
|
|
6620
7550
|
};
|
|
6621
|
-
const
|
|
7551
|
+
const timing = new LlmStreamTiming();
|
|
7552
|
+
const stream = this.client.responses.stream(
|
|
6622
7553
|
streamRequest,
|
|
6623
7554
|
signal || sessionIdHeader ? {
|
|
6624
7555
|
...signal ? { signal } : {},
|
|
@@ -6628,13 +7559,21 @@ var ChatOpenRouter = class {
|
|
|
6628
7559
|
}
|
|
6629
7560
|
} : {}
|
|
6630
7561
|
} : void 0
|
|
6631
|
-
)
|
|
7562
|
+
);
|
|
7563
|
+
if (typeof stream[Symbol.asyncIterator] === "function") {
|
|
7564
|
+
for await (const event of stream) timing.observeResponsesEvent(event);
|
|
7565
|
+
}
|
|
7566
|
+
const response = await stream.finalResponse();
|
|
7567
|
+
const measuredTiming = timing.finish();
|
|
6632
7568
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
6633
|
-
return
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
|
|
7569
|
+
return {
|
|
7570
|
+
...toChatInvokeCompletion3(response, {
|
|
7571
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7572
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7573
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7574
|
+
}),
|
|
7575
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7576
|
+
};
|
|
6638
7577
|
}
|
|
6639
7578
|
nextDebugInvokeSeq() {
|
|
6640
7579
|
const seq = this.debugInvokeSeq + 1;
|
|
@@ -6647,14 +7586,14 @@ var ChatOpenRouter = class {
|
|
|
6647
7586
|
return;
|
|
6648
7587
|
}
|
|
6649
7588
|
const payload = safeJsonStringify(request);
|
|
6650
|
-
const hash = (0,
|
|
6651
|
-
const toolsHash = (0,
|
|
6652
|
-
const instructionsHash = (0,
|
|
7589
|
+
const hash = (0, import_node_crypto6.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7590
|
+
const toolsHash = (0, import_node_crypto6.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7591
|
+
const instructionsHash = (0, import_node_crypto6.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
6653
7592
|
const previous = this.lastDebugRequestPayload;
|
|
6654
7593
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
6655
7594
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
6656
7595
|
if (settings.enabled) {
|
|
6657
|
-
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0,
|
|
7596
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto6.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
6658
7597
|
console.error(
|
|
6659
7598
|
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
6660
7599
|
);
|
|
@@ -6718,8 +7657,8 @@ var ChatOpenRouter = class {
|
|
|
6718
7657
|
};
|
|
6719
7658
|
|
|
6720
7659
|
// src/llm/xai/chat.ts
|
|
6721
|
-
var
|
|
6722
|
-
var
|
|
7660
|
+
var import_node_crypto7 = require("crypto");
|
|
7661
|
+
var import_openai9 = __toESM(require("openai"), 1);
|
|
6723
7662
|
|
|
6724
7663
|
// src/llm/xai/serializer.ts
|
|
6725
7664
|
var XAI_SUPPORTED_INLINE_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -6942,7 +7881,7 @@ var ChatXai = class {
|
|
|
6942
7881
|
debugInvokeSeq = 0;
|
|
6943
7882
|
lastDebugRequestPayload = null;
|
|
6944
7883
|
constructor(options = {}) {
|
|
6945
|
-
this.client = options.client ?? new
|
|
7884
|
+
this.client = options.client ?? new import_openai9.default({
|
|
6946
7885
|
baseURL: XAI_BASE_URL,
|
|
6947
7886
|
timeout: DEFAULT_REQUEST_TIMEOUT_MS2,
|
|
6948
7887
|
...options.clientOptions ?? {},
|
|
@@ -6995,13 +7934,24 @@ var ChatXai = class {
|
|
|
6995
7934
|
}
|
|
6996
7935
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
6997
7936
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
6998
|
-
const
|
|
7937
|
+
const timing = new LlmStreamTiming();
|
|
7938
|
+
const response = await invokeOpenAiHttp(
|
|
7939
|
+
this.client,
|
|
7940
|
+
request,
|
|
7941
|
+
signal,
|
|
7942
|
+
void 0,
|
|
7943
|
+
(event) => timing.observeResponsesEvent(event)
|
|
7944
|
+
);
|
|
7945
|
+
const measuredTiming = timing.finish();
|
|
6999
7946
|
await this.debugResponseIfEnabled(response, debugSeq);
|
|
7000
|
-
return
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
7947
|
+
return {
|
|
7948
|
+
...toXaiChatInvokeCompletion(response, {
|
|
7949
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
7950
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
7951
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
7952
|
+
}),
|
|
7953
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
7954
|
+
};
|
|
7005
7955
|
}
|
|
7006
7956
|
nextDebugInvokeSeq() {
|
|
7007
7957
|
this.debugInvokeSeq += 1;
|
|
@@ -7011,7 +7961,7 @@ var ChatXai = class {
|
|
|
7011
7961
|
const settings = getProviderLogSettings();
|
|
7012
7962
|
if (!settings.enabled && !settings.dumpDir) return;
|
|
7013
7963
|
const payload = safeJsonStringify(request);
|
|
7014
|
-
const hash = (0,
|
|
7964
|
+
const hash = (0, import_node_crypto7.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
7015
7965
|
const previous = this.lastDebugRequestPayload;
|
|
7016
7966
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7017
7967
|
const ratio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7068,15 +8018,15 @@ var ChatXai = class {
|
|
|
7068
8018
|
};
|
|
7069
8019
|
|
|
7070
8020
|
// src/llm/zai/chat.ts
|
|
7071
|
-
var
|
|
8021
|
+
var import_node_crypto8 = require("crypto");
|
|
7072
8022
|
|
|
7073
8023
|
// src/llm/zai/failure.ts
|
|
7074
8024
|
var PROVIDER_NAME8 = "zai";
|
|
7075
8025
|
var readBusinessCode = (error) => {
|
|
7076
|
-
const
|
|
7077
|
-
const body = asRecord(
|
|
8026
|
+
const record3 = asRecord(error);
|
|
8027
|
+
const body = asRecord(record3?.body);
|
|
7078
8028
|
const nested = asRecord(body?.error) ?? body;
|
|
7079
|
-
const raw = nested?.code ??
|
|
8029
|
+
const raw = nested?.code ?? record3?.code;
|
|
7080
8030
|
const parsed = typeof raw === "number" ? raw : Number(raw);
|
|
7081
8031
|
return Number.isFinite(parsed) ? Math.trunc(parsed) : void 0;
|
|
7082
8032
|
};
|
|
@@ -7380,6 +8330,7 @@ var streamZaiChatCompletion = async ({
|
|
|
7380
8330
|
timeoutMs,
|
|
7381
8331
|
captureRawChunks
|
|
7382
8332
|
}) => {
|
|
8333
|
+
const timing = new LlmStreamTiming();
|
|
7383
8334
|
const requestSignal = createZaiRequestSignal(signal, timeoutMs);
|
|
7384
8335
|
try {
|
|
7385
8336
|
const response = await fetchImpl(`${baseURL}/chat/completions`, {
|
|
@@ -7401,9 +8352,11 @@ var streamZaiChatCompletion = async ({
|
|
|
7401
8352
|
response,
|
|
7402
8353
|
requestSignal.signal
|
|
7403
8354
|
)) {
|
|
8355
|
+
timing.observeChatChunk(chunk);
|
|
7404
8356
|
appendZaiChatCompletionChunk(accumulated, chunk);
|
|
7405
8357
|
}
|
|
7406
8358
|
return {
|
|
8359
|
+
timing: timing.finish(),
|
|
7407
8360
|
status: response.status,
|
|
7408
8361
|
request_id: response.headers.get("x-request-id"),
|
|
7409
8362
|
accumulated
|
|
@@ -7598,13 +8551,16 @@ var ChatZai = class {
|
|
|
7598
8551
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
7599
8552
|
const terminal = await this.streamRequest(apiKey, request, signal);
|
|
7600
8553
|
await this.debugResponseIfEnabled(terminal, debugSeq);
|
|
7601
|
-
return
|
|
7602
|
-
|
|
7603
|
-
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
|
|
7607
|
-
|
|
8554
|
+
return {
|
|
8555
|
+
...toZaiChatInvokeCompletion(terminal.accumulated, {
|
|
8556
|
+
request_id: terminal.request_id ?? null,
|
|
8557
|
+
reasoning_requested: this.reasoningLevelMeta.requested,
|
|
8558
|
+
reasoning_applied: this.reasoningLevelMeta.applied,
|
|
8559
|
+
reasoning_effort: request.reasoning_effort,
|
|
8560
|
+
reasoning_fallback: this.reasoningLevelMeta.fallbackApplied
|
|
8561
|
+
}),
|
|
8562
|
+
...terminal.timing ? { timing: terminal.timing } : {}
|
|
8563
|
+
};
|
|
7608
8564
|
}
|
|
7609
8565
|
async streamRequest(apiKey, request, signal) {
|
|
7610
8566
|
const logSettings = getProviderLogSettings();
|
|
@@ -7629,8 +8585,8 @@ var ChatZai = class {
|
|
|
7629
8585
|
return;
|
|
7630
8586
|
}
|
|
7631
8587
|
const payload = safeJsonStringify(request);
|
|
7632
|
-
const hash = (0,
|
|
7633
|
-
const toolsHash = (0,
|
|
8588
|
+
const hash = (0, import_node_crypto8.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
8589
|
+
const toolsHash = (0, import_node_crypto8.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
7634
8590
|
const previous = this.lastDebugRequestPayload;
|
|
7635
8591
|
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
7636
8592
|
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
@@ -7761,6 +8717,159 @@ function defineTool(toolOptions) {
|
|
|
7761
8717
|
}
|
|
7762
8718
|
};
|
|
7763
8719
|
}
|
|
8720
|
+
|
|
8721
|
+
// src/llm/responses/chat.ts
|
|
8722
|
+
var import_openai10 = __toESM(require("openai"), 1);
|
|
8723
|
+
var ChatResponses = class {
|
|
8724
|
+
provider;
|
|
8725
|
+
model;
|
|
8726
|
+
retryPolicy;
|
|
8727
|
+
client;
|
|
8728
|
+
endpoint;
|
|
8729
|
+
reasoningEffort;
|
|
8730
|
+
textVerbosity;
|
|
8731
|
+
constructor(options) {
|
|
8732
|
+
this.provider = options.provider;
|
|
8733
|
+
this.model = options.model;
|
|
8734
|
+
this.endpoint = options.endpoint;
|
|
8735
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
8736
|
+
this.textVerbosity = options.textVerbosity;
|
|
8737
|
+
const retry = options.endpoint.retry;
|
|
8738
|
+
this.retryPolicy = {
|
|
8739
|
+
maxRetries: typeof retry === "object" ? retry.max_retries : 0,
|
|
8740
|
+
...typeof retry === "object" && retry.base_delay_ms !== void 0 ? { baseDelayMs: retry.base_delay_ms } : {}
|
|
8741
|
+
};
|
|
8742
|
+
this.client = new import_openai10.default({
|
|
8743
|
+
apiKey: options.apiKey,
|
|
8744
|
+
baseURL: options.endpoint.base_url,
|
|
8745
|
+
organization: null,
|
|
8746
|
+
project: null,
|
|
8747
|
+
maxRetries: 0,
|
|
8748
|
+
timeout: options.endpoint.timeout_ms ?? 60 * 60 * 1e3,
|
|
8749
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
8750
|
+
});
|
|
8751
|
+
}
|
|
8752
|
+
classifyFailure = (error) => {
|
|
8753
|
+
if (isProviderFailureError(error)) return error.failure;
|
|
8754
|
+
const failure = error instanceof import_openai10.default.APIUserAbortError ? buildProviderFailure(this.provider, "cancelled") : error instanceof import_openai10.default.APIConnectionTimeoutError ? buildProviderFailure(this.provider, "timeout", { retryable: true }) : error instanceof import_openai10.default.APIConnectionError ? buildProviderFailure(this.provider, "network", {
|
|
8755
|
+
retryable: true
|
|
8756
|
+
}) : classifyOpenAiCompatibleFailure(this.provider, error);
|
|
8757
|
+
const extracted = extractProviderError(error);
|
|
8758
|
+
const code = typeof extracted.code === "string" && /^[a-zA-Z0-9_.-]{1,80}$/.test(extracted.code) ? extracted.code : void 0;
|
|
8759
|
+
return {
|
|
8760
|
+
...failure,
|
|
8761
|
+
...extracted.status !== void 0 ? { status: extracted.status } : {},
|
|
8762
|
+
...extracted.status === 413 ? { kind: "validation" } : {},
|
|
8763
|
+
retryable: this.retryPolicy.maxRetries > 0 && failure.retryable,
|
|
8764
|
+
...code ? { code } : {},
|
|
8765
|
+
safeMessage: `${failure.safeMessage}${extracted.status !== void 0 ? ` HTTP ${extracted.status}.` : ""}${code ? ` code=${code}.` : ""}`
|
|
8766
|
+
};
|
|
8767
|
+
};
|
|
8768
|
+
async ainvoke(input, context) {
|
|
8769
|
+
const model = input.model ?? this.model;
|
|
8770
|
+
const spec = Object.hasOwn(this.endpoint.models, model) ? this.endpoint.models[model] : void 0;
|
|
8771
|
+
const invalid = (message) => {
|
|
8772
|
+
throw createProviderValidationError(this.provider, message);
|
|
8773
|
+
};
|
|
8774
|
+
if (!spec) return invalid(`Unknown model for ${this.provider}: ${model}`);
|
|
8775
|
+
if (input.tools?.some((tool) => tool.type === "hosted_search"))
|
|
8776
|
+
invalid(
|
|
8777
|
+
`${this.provider} supports function tools only; hosted tools are unavailable`
|
|
8778
|
+
);
|
|
8779
|
+
if (input.tools?.length && !spec.supports_tools)
|
|
8780
|
+
invalid(`${this.provider}/${model} does not support tools`);
|
|
8781
|
+
const items = toResponsesInput(input.messages);
|
|
8782
|
+
if (!spec.supports_vision && Array.isArray(items) && items.some(
|
|
8783
|
+
(item) => "content" in item && Array.isArray(item.content) && item.content.some((part) => part.type === "input_image")
|
|
8784
|
+
))
|
|
8785
|
+
invalid(`${this.provider}/${model} vision is disabled`);
|
|
8786
|
+
const text = input.options?.text;
|
|
8787
|
+
if (text?.format && text.format.type !== "text" && !spec.supports_json_schema)
|
|
8788
|
+
invalid(`${this.provider}/${model} does not support structured output`);
|
|
8789
|
+
const features = this.endpoint.features;
|
|
8790
|
+
const effort = input.options?.reasoningEffort ?? this.reasoningEffort;
|
|
8791
|
+
if (effort && !spec.supports_reasoning)
|
|
8792
|
+
invalid(`${this.provider}/${model} reasoning is disabled`);
|
|
8793
|
+
const levels = spec.reasoning_levels ?? ["low", "medium", "high"];
|
|
8794
|
+
if (effort && !levels.includes(effort))
|
|
8795
|
+
invalid(
|
|
8796
|
+
`Unsupported reasoning effort for ${this.provider}/${model}: ${effort}`
|
|
8797
|
+
);
|
|
8798
|
+
const output = input.options?.maxOutputTokens ?? spec.max_output_tokens;
|
|
8799
|
+
if (output !== void 0 && (!Number.isSafeInteger(output) || output < 1 || output > (spec.max_output_tokens ?? spec.context_window)))
|
|
8800
|
+
invalid(`Invalid max output tokens for ${this.provider}/${model}`);
|
|
8801
|
+
const tools = toResponsesTools(input.tools);
|
|
8802
|
+
const choice = toResponsesToolChoice(input.toolChoice);
|
|
8803
|
+
const instructions = extractInstructions(input.messages);
|
|
8804
|
+
const request = {
|
|
8805
|
+
model,
|
|
8806
|
+
input: items,
|
|
8807
|
+
store: false,
|
|
8808
|
+
...instructions ? { instructions } : {},
|
|
8809
|
+
...tools ? { tools } : {},
|
|
8810
|
+
...choice ? { tool_choice: choice } : {},
|
|
8811
|
+
...output !== void 0 ? { max_output_tokens: output } : {}
|
|
8812
|
+
};
|
|
8813
|
+
if (spec.supports_reasoning && (effort || features?.reasoning_summary))
|
|
8814
|
+
request.reasoning = {
|
|
8815
|
+
...effort ? { effort: toSdkReasoningEffort(effort) } : {},
|
|
8816
|
+
...features?.reasoning_summary ? { summary: features.reasoning_summary } : {}
|
|
8817
|
+
};
|
|
8818
|
+
if (spec.supports_reasoning && features?.encrypted_reasoning)
|
|
8819
|
+
request.include = ["reasoning.encrypted_content"];
|
|
8820
|
+
if (text?.format || features?.text_verbosity && (text?.verbosity || this.textVerbosity))
|
|
8821
|
+
request.text = {
|
|
8822
|
+
...text?.format ? { format: text.format } : {},
|
|
8823
|
+
...features?.text_verbosity && (text?.verbosity || this.textVerbosity) ? { verbosity: text?.verbosity ?? this.textVerbosity } : {}
|
|
8824
|
+
};
|
|
8825
|
+
if (features?.prompt_cache_key && context?.sessionKey)
|
|
8826
|
+
request.prompt_cache_key = context.sessionKey;
|
|
8827
|
+
const timing = new LlmStreamTiming();
|
|
8828
|
+
let streamStarted = false;
|
|
8829
|
+
try {
|
|
8830
|
+
const stream = await this.client.responses.create(
|
|
8831
|
+
{ ...request, stream: true },
|
|
8832
|
+
{
|
|
8833
|
+
...input.signal ? { signal: input.signal } : {},
|
|
8834
|
+
...features?.session_id_header && context?.sessionKey ? { headers: { session_id: context.sessionKey } } : {}
|
|
8835
|
+
}
|
|
8836
|
+
);
|
|
8837
|
+
streamStarted = true;
|
|
8838
|
+
const accumulator = new OpenAiResponseAccumulator();
|
|
8839
|
+
let terminal;
|
|
8840
|
+
for await (const event of stream) {
|
|
8841
|
+
timing.observeResponsesEvent(event);
|
|
8842
|
+
if (event.type === "error") throw { error: event };
|
|
8843
|
+
if (event.type === "response.failed")
|
|
8844
|
+
throw { error: event.response.error };
|
|
8845
|
+
accumulator.observeEvent(event);
|
|
8846
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
8847
|
+
terminal = event.response;
|
|
8848
|
+
break;
|
|
8849
|
+
}
|
|
8850
|
+
}
|
|
8851
|
+
if (!terminal)
|
|
8852
|
+
throw new Error("Responses stream ended before a terminal event");
|
|
8853
|
+
const measuredTiming = timing.finish();
|
|
8854
|
+
return {
|
|
8855
|
+
...toChatInvokeCompletion2(accumulator.buildResponse(terminal), {
|
|
8856
|
+
transport: "http_stream"
|
|
8857
|
+
}),
|
|
8858
|
+
...measuredTiming ? { timing: measuredTiming } : {}
|
|
8859
|
+
};
|
|
8860
|
+
} catch (error) {
|
|
8861
|
+
if (isProviderFailureError(error)) throw error;
|
|
8862
|
+
const failure = input.signal?.aborted ? buildProviderFailure(this.provider, "cancelled") : this.classifyFailure(error);
|
|
8863
|
+
throw new ProviderFailureError(
|
|
8864
|
+
{
|
|
8865
|
+
...failure,
|
|
8866
|
+
...streamStarted ? { retryable: false, delivery: "buffered" } : {}
|
|
8867
|
+
},
|
|
8868
|
+
{ cause: error }
|
|
8869
|
+
);
|
|
8870
|
+
}
|
|
8871
|
+
}
|
|
8872
|
+
};
|
|
7764
8873
|
// Annotate the CommonJS export names for ESM import in node:
|
|
7765
8874
|
0 && (module.exports = {
|
|
7766
8875
|
ANTHROPIC_DEFAULT_MODEL,
|
|
@@ -7770,6 +8879,7 @@ function defineTool(toolOptions) {
|
|
|
7770
8879
|
ChatMoonshot,
|
|
7771
8880
|
ChatOpenAI,
|
|
7772
8881
|
ChatOpenRouter,
|
|
8882
|
+
ChatResponses,
|
|
7773
8883
|
ChatXai,
|
|
7774
8884
|
ChatZai,
|
|
7775
8885
|
DEFAULT_MODEL_REGISTRY,
|
|
@@ -7782,6 +8892,7 @@ function defineTool(toolOptions) {
|
|
|
7782
8892
|
ProviderFailureError,
|
|
7783
8893
|
TaskComplete,
|
|
7784
8894
|
ToolOutputCacheService,
|
|
8895
|
+
ToolPermissionDenied,
|
|
7785
8896
|
XAI_DEFAULT_MODEL,
|
|
7786
8897
|
XAI_DEFAULT_REASONING_EFFORT,
|
|
7787
8898
|
XAI_MODELS,
|