@codelia/core 0.1.13 → 0.1.16
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 +616 -109
- package/dist/index.d.cts +42 -5
- package/dist/index.d.ts +42 -5
- package/dist/index.js +616 -109
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -424,13 +424,16 @@ var CompactionService = class _CompactionService {
|
|
|
424
424
|
};
|
|
425
425
|
let response;
|
|
426
426
|
try {
|
|
427
|
-
response = await llm.ainvoke(
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
427
|
+
response = await llm.ainvoke(
|
|
428
|
+
{
|
|
429
|
+
messages: [...preparedMessages, interruptMessage],
|
|
430
|
+
tools: null,
|
|
431
|
+
toolChoice: "none",
|
|
432
|
+
...options?.signal ? { signal: options.signal } : {},
|
|
433
|
+
...this.config.model ? { model: this.config.model } : {}
|
|
434
|
+
},
|
|
435
|
+
options?.invokeContext
|
|
436
|
+
);
|
|
434
437
|
} catch (error) {
|
|
435
438
|
if (error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal")) {
|
|
436
439
|
throw error;
|
|
@@ -743,7 +746,7 @@ var ToolOutputCacheService = class {
|
|
|
743
746
|
};
|
|
744
747
|
}
|
|
745
748
|
async trimMessages(llm, messages) {
|
|
746
|
-
if (this.config.enabled === false) {
|
|
749
|
+
if (this.config.enabled === false || this.config.totalBudgetTrim === false) {
|
|
747
750
|
return { messages, trimmed: false };
|
|
748
751
|
}
|
|
749
752
|
const budget = await this.resolveContextBudgetTokens(llm);
|
|
@@ -906,11 +909,73 @@ function toolResultToContent(result) {
|
|
|
906
909
|
}
|
|
907
910
|
}
|
|
908
911
|
var collectModelOutput = (messages) => {
|
|
912
|
+
const buildWebSearchSummary = (status, queries, sourcesCount) => {
|
|
913
|
+
const parts = [`WebSearch status=${status}`];
|
|
914
|
+
if (queries.length) {
|
|
915
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
916
|
+
}
|
|
917
|
+
if (typeof sourcesCount === "number") {
|
|
918
|
+
parts.push(`sources=${sourcesCount}`);
|
|
919
|
+
}
|
|
920
|
+
return parts.join(" | ");
|
|
921
|
+
};
|
|
909
922
|
const reasoningTexts = [];
|
|
910
923
|
const assistantTexts = [];
|
|
911
924
|
const toolCalls = [];
|
|
925
|
+
const hostedToolCalls = [];
|
|
926
|
+
const hostedWebSearchById = /* @__PURE__ */ new Map();
|
|
927
|
+
const hostedWebSearchOrder = [];
|
|
928
|
+
let anonymousWebSearchCounter = 0;
|
|
929
|
+
let lastAnonymousWebSearchId = null;
|
|
912
930
|
for (const message of messages) {
|
|
913
931
|
if (message.role === "reasoning") {
|
|
932
|
+
const raw = message.raw_item;
|
|
933
|
+
if (raw && typeof raw === "object" && raw.type === "web_search_call") {
|
|
934
|
+
const record = raw;
|
|
935
|
+
const statusRaw = record.status;
|
|
936
|
+
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
937
|
+
const action = record.action && typeof record.action === "object" ? record.action : null;
|
|
938
|
+
const queries = Array.isArray(action?.queries) ? action?.queries.filter(
|
|
939
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
940
|
+
) : [];
|
|
941
|
+
const sourcesCount = Array.isArray(action?.sources) ? action?.sources.length : void 0;
|
|
942
|
+
const explicitId = typeof record.id === "string" && record.id.length > 0 ? record.id : null;
|
|
943
|
+
let id = explicitId;
|
|
944
|
+
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
945
|
+
if (!id) {
|
|
946
|
+
if (hasSearchContext || status === "failed") {
|
|
947
|
+
anonymousWebSearchCounter += 1;
|
|
948
|
+
id = `web_search_${anonymousWebSearchCounter}`;
|
|
949
|
+
if (hasSearchContext) {
|
|
950
|
+
lastAnonymousWebSearchId = id;
|
|
951
|
+
}
|
|
952
|
+
} else if (lastAnonymousWebSearchId) {
|
|
953
|
+
id = lastAnonymousWebSearchId;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (!id) {
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
const existing = hostedWebSearchById.get(id);
|
|
960
|
+
if (existing) {
|
|
961
|
+
existing.status = status;
|
|
962
|
+
if (queries.length) {
|
|
963
|
+
existing.queries = queries;
|
|
964
|
+
}
|
|
965
|
+
if (typeof sourcesCount === "number") {
|
|
966
|
+
existing.sourcesCount = sourcesCount;
|
|
967
|
+
}
|
|
968
|
+
} else {
|
|
969
|
+
hostedWebSearchById.set(id, {
|
|
970
|
+
id,
|
|
971
|
+
status,
|
|
972
|
+
queries,
|
|
973
|
+
...typeof sourcesCount === "number" ? { sourcesCount } : {}
|
|
974
|
+
});
|
|
975
|
+
hostedWebSearchOrder.push(id);
|
|
976
|
+
}
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
914
979
|
const text = message.content ?? "";
|
|
915
980
|
if (text) {
|
|
916
981
|
reasoningTexts.push(text);
|
|
@@ -930,7 +995,30 @@ var collectModelOutput = (messages) => {
|
|
|
930
995
|
toolCalls.push(...message.tool_calls);
|
|
931
996
|
}
|
|
932
997
|
}
|
|
933
|
-
|
|
998
|
+
for (const id of hostedWebSearchOrder) {
|
|
999
|
+
const aggregate = hostedWebSearchById.get(id);
|
|
1000
|
+
if (!aggregate) {
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
const args = {
|
|
1004
|
+
status: aggregate.status,
|
|
1005
|
+
...aggregate.queries.length ? { queries: aggregate.queries } : {},
|
|
1006
|
+
...typeof aggregate.sourcesCount === "number" ? { sources_count: aggregate.sourcesCount } : {}
|
|
1007
|
+
};
|
|
1008
|
+
hostedToolCalls.push({
|
|
1009
|
+
id: aggregate.id,
|
|
1010
|
+
tool: "web_search",
|
|
1011
|
+
displayName: "WebSearch",
|
|
1012
|
+
args,
|
|
1013
|
+
result: buildWebSearchSummary(
|
|
1014
|
+
aggregate.status,
|
|
1015
|
+
aggregate.queries,
|
|
1016
|
+
aggregate.sourcesCount
|
|
1017
|
+
),
|
|
1018
|
+
isError: aggregate.status === "failed"
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
return { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls };
|
|
934
1022
|
};
|
|
935
1023
|
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
936
1024
|
var createAbortError = () => {
|
|
@@ -947,6 +1035,7 @@ var throwIfAborted = (signal) => {
|
|
|
947
1035
|
var Agent = class {
|
|
948
1036
|
llm;
|
|
949
1037
|
tools;
|
|
1038
|
+
hostedTools;
|
|
950
1039
|
systemPrompt;
|
|
951
1040
|
maxIterations;
|
|
952
1041
|
toolChoice;
|
|
@@ -963,6 +1052,7 @@ var Agent = class {
|
|
|
963
1052
|
this.llm = options.llm;
|
|
964
1053
|
this.history = this.llm.provider === "openai" ? new OpenAIHistoryAdapter() : new MessageHistoryAdapter();
|
|
965
1054
|
this.tools = options.tools;
|
|
1055
|
+
this.hostedTools = options.hostedTools ?? [];
|
|
966
1056
|
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
967
1057
|
this.maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
968
1058
|
this.toolChoice = options.toolChoice ?? void 0;
|
|
@@ -1028,10 +1118,14 @@ var Agent = class {
|
|
|
1028
1118
|
timestamp: Date.now()
|
|
1029
1119
|
};
|
|
1030
1120
|
yield startEvent;
|
|
1121
|
+
const invokeContext = this.buildInvokeContext(options.session);
|
|
1031
1122
|
const { compacted, compactedMessages, usage } = await this.compactionService.compact(
|
|
1032
1123
|
this.llm,
|
|
1033
1124
|
this.history.getViewMessages(),
|
|
1034
|
-
{
|
|
1125
|
+
{
|
|
1126
|
+
...signal ? { signal } : {},
|
|
1127
|
+
...invokeContext ? { invokeContext } : {}
|
|
1128
|
+
}
|
|
1035
1129
|
);
|
|
1036
1130
|
this.usageService.updateUsageSummary(usage);
|
|
1037
1131
|
if (compacted && compactedMessages) {
|
|
@@ -1077,7 +1171,7 @@ var Agent = class {
|
|
|
1077
1171
|
now: () => /* @__PURE__ */ new Date()
|
|
1078
1172
|
};
|
|
1079
1173
|
}
|
|
1080
|
-
recordLlmRequest(session, input) {
|
|
1174
|
+
recordLlmRequest(session, input, context) {
|
|
1081
1175
|
if (!session) return null;
|
|
1082
1176
|
const seq = (session.invoke_seq ?? 0) + 1;
|
|
1083
1177
|
session.invoke_seq = seq;
|
|
@@ -1095,11 +1189,24 @@ var Agent = class {
|
|
|
1095
1189
|
messages: input.messages,
|
|
1096
1190
|
tools: input.tools ?? null,
|
|
1097
1191
|
tool_choice: input.toolChoice ?? null,
|
|
1098
|
-
model: input.model
|
|
1192
|
+
model: input.model,
|
|
1193
|
+
...context?.sessionKey ? { session_key: context.sessionKey } : {}
|
|
1099
1194
|
}
|
|
1100
1195
|
});
|
|
1101
1196
|
return seq;
|
|
1102
1197
|
}
|
|
1198
|
+
resolveSessionKey(session) {
|
|
1199
|
+
const sessionId = session?.session_id?.trim();
|
|
1200
|
+
if (sessionId && sessionId.length > 0) {
|
|
1201
|
+
return sessionId;
|
|
1202
|
+
}
|
|
1203
|
+
const runId = session?.run_id?.trim();
|
|
1204
|
+
return runId && runId.length > 0 ? runId : void 0;
|
|
1205
|
+
}
|
|
1206
|
+
buildInvokeContext(session) {
|
|
1207
|
+
const sessionKey = this.resolveSessionKey(session);
|
|
1208
|
+
return sessionKey ? { sessionKey } : void 0;
|
|
1209
|
+
}
|
|
1103
1210
|
recordLlmResponse(session, seq, response) {
|
|
1104
1211
|
if (!session || seq === null) return;
|
|
1105
1212
|
session.append({
|
|
@@ -1137,7 +1244,7 @@ var Agent = class {
|
|
|
1137
1244
|
this.history.enqueueSystem(systemMessage);
|
|
1138
1245
|
}
|
|
1139
1246
|
if (forceCompaction) {
|
|
1140
|
-
yield* this.checkAndCompact(signal, { force: true });
|
|
1247
|
+
yield* this.checkAndCompact(signal, { force: true, session });
|
|
1141
1248
|
const finalResponseEvent2 = {
|
|
1142
1249
|
type: "final",
|
|
1143
1250
|
content: "Compaction run completed."
|
|
@@ -1153,20 +1260,30 @@ var Agent = class {
|
|
|
1153
1260
|
await this.trimToolOutputs();
|
|
1154
1261
|
throwIfAborted(signal);
|
|
1155
1262
|
const invokeInput = this.history.prepareInvokeInput({
|
|
1156
|
-
tools:
|
|
1263
|
+
tools: [
|
|
1264
|
+
...this.tools.map((t) => t.definition),
|
|
1265
|
+
...this.hostedTools
|
|
1266
|
+
],
|
|
1157
1267
|
toolChoice: this.toolChoice
|
|
1158
1268
|
});
|
|
1159
|
-
const
|
|
1160
|
-
const
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1269
|
+
const invokeContext = this.buildInvokeContext(session);
|
|
1270
|
+
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
1271
|
+
const response = await this.llm.ainvoke(
|
|
1272
|
+
{
|
|
1273
|
+
...invokeInput,
|
|
1274
|
+
...signal ? { signal } : {}
|
|
1275
|
+
},
|
|
1276
|
+
invokeContext
|
|
1277
|
+
);
|
|
1164
1278
|
this.recordLlmResponse(session, seq, response);
|
|
1165
1279
|
this.usageService.updateUsageSummary(response.usage);
|
|
1166
1280
|
this.history.commitModelResponse(response);
|
|
1167
|
-
const {
|
|
1168
|
-
|
|
1169
|
-
|
|
1281
|
+
const {
|
|
1282
|
+
reasoningTexts,
|
|
1283
|
+
assistantTexts,
|
|
1284
|
+
toolCalls,
|
|
1285
|
+
hostedToolCalls
|
|
1286
|
+
} = collectModelOutput(response.messages);
|
|
1170
1287
|
for (const reasoningText of reasoningTexts) {
|
|
1171
1288
|
const reasoningEvent = {
|
|
1172
1289
|
type: "reasoning",
|
|
@@ -1175,6 +1292,42 @@ var Agent = class {
|
|
|
1175
1292
|
};
|
|
1176
1293
|
yield reasoningEvent;
|
|
1177
1294
|
}
|
|
1295
|
+
let stepNumber = 0;
|
|
1296
|
+
for (const hostedCall of hostedToolCalls) {
|
|
1297
|
+
stepNumber++;
|
|
1298
|
+
const stepStartEvent = {
|
|
1299
|
+
type: "step_start",
|
|
1300
|
+
step_id: hostedCall.id,
|
|
1301
|
+
title: hostedCall.displayName,
|
|
1302
|
+
step_number: stepNumber
|
|
1303
|
+
};
|
|
1304
|
+
yield stepStartEvent;
|
|
1305
|
+
const rawArgs = JSON.stringify(hostedCall.args);
|
|
1306
|
+
const toolCallEvent = {
|
|
1307
|
+
type: "tool_call",
|
|
1308
|
+
tool: hostedCall.tool,
|
|
1309
|
+
args: hostedCall.args,
|
|
1310
|
+
raw_args: rawArgs,
|
|
1311
|
+
tool_call_id: hostedCall.id,
|
|
1312
|
+
display_name: hostedCall.displayName
|
|
1313
|
+
};
|
|
1314
|
+
yield toolCallEvent;
|
|
1315
|
+
const toolResultEvent = {
|
|
1316
|
+
type: "tool_result",
|
|
1317
|
+
tool: hostedCall.tool,
|
|
1318
|
+
result: hostedCall.result,
|
|
1319
|
+
tool_call_id: hostedCall.id,
|
|
1320
|
+
...hostedCall.isError ? { is_error: true } : {}
|
|
1321
|
+
};
|
|
1322
|
+
yield toolResultEvent;
|
|
1323
|
+
const stepCompleteEvent = {
|
|
1324
|
+
type: "step_complete",
|
|
1325
|
+
step_id: hostedCall.id,
|
|
1326
|
+
status: hostedCall.isError ? "error" : "completed",
|
|
1327
|
+
duration_ms: 0
|
|
1328
|
+
};
|
|
1329
|
+
yield stepCompleteEvent;
|
|
1330
|
+
}
|
|
1178
1331
|
const hasToolCalls = toolCalls.length > 0;
|
|
1179
1332
|
const shouldEmitFinalOnly = !hasToolCalls && !this.requireDoneTool;
|
|
1180
1333
|
if (!shouldEmitFinalOnly) {
|
|
@@ -1189,7 +1342,7 @@ var Agent = class {
|
|
|
1189
1342
|
}
|
|
1190
1343
|
if (!hasToolCalls) {
|
|
1191
1344
|
if (!this.requireDoneTool) {
|
|
1192
|
-
yield* this.checkAndCompact(signal);
|
|
1345
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1193
1346
|
const finalText = assistantTexts.join("\n").trim();
|
|
1194
1347
|
const finalResponseEvent2 = {
|
|
1195
1348
|
type: "final",
|
|
@@ -1198,11 +1351,10 @@ var Agent = class {
|
|
|
1198
1351
|
yield finalResponseEvent2;
|
|
1199
1352
|
return;
|
|
1200
1353
|
} else {
|
|
1201
|
-
yield* this.checkAndCompact(signal);
|
|
1354
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1202
1355
|
}
|
|
1203
1356
|
continue;
|
|
1204
1357
|
}
|
|
1205
|
-
let stepNumber = 0;
|
|
1206
1358
|
for (const toolCall of toolCalls) {
|
|
1207
1359
|
stepNumber++;
|
|
1208
1360
|
let jsonArgs;
|
|
@@ -1328,7 +1480,7 @@ var Agent = class {
|
|
|
1328
1480
|
yield stepCompleteEvent;
|
|
1329
1481
|
}
|
|
1330
1482
|
}
|
|
1331
|
-
yield* this.checkAndCompact(signal);
|
|
1483
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1332
1484
|
}
|
|
1333
1485
|
const finalResponse = await this.generateFinalResponse(session, signal);
|
|
1334
1486
|
const finalResponseEvent = {
|
|
@@ -1351,11 +1503,15 @@ var Agent = class {
|
|
|
1351
1503
|
// no tools are allowed at this point
|
|
1352
1504
|
toolChoice: "none"
|
|
1353
1505
|
};
|
|
1354
|
-
const
|
|
1355
|
-
const
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1506
|
+
const invokeContext = this.buildInvokeContext(session);
|
|
1507
|
+
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
1508
|
+
const summary = await this.llm.ainvoke(
|
|
1509
|
+
{
|
|
1510
|
+
...input,
|
|
1511
|
+
...signal ? { signal } : {}
|
|
1512
|
+
},
|
|
1513
|
+
invokeContext
|
|
1514
|
+
);
|
|
1359
1515
|
this.recordLlmResponse(session, seq, summary);
|
|
1360
1516
|
this.usageService.updateUsageSummary(summary.usage);
|
|
1361
1517
|
const { assistantTexts } = collectModelOutput(summary.messages);
|
|
@@ -1486,6 +1642,110 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1486
1642
|
|
|
1487
1643
|
// src/llm/anthropic/chat.ts
|
|
1488
1644
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
1645
|
+
var import_node_crypto = require("crypto");
|
|
1646
|
+
|
|
1647
|
+
// src/llm/provider-log.ts
|
|
1648
|
+
var import_node_fs = require("fs");
|
|
1649
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
1650
|
+
var envTruthy = (value) => {
|
|
1651
|
+
if (!value) return false;
|
|
1652
|
+
const normalized = value.trim().toLowerCase();
|
|
1653
|
+
return normalized === "1" || normalized === "true";
|
|
1654
|
+
};
|
|
1655
|
+
var getProviderLogSettings = () => {
|
|
1656
|
+
const enabled = envTruthy(process.env.CODELIA_PROVIDER_LOG);
|
|
1657
|
+
const dumpDirEnv = process.env.CODELIA_PROVIDER_LOG_DIR?.trim();
|
|
1658
|
+
const dumpDir = enabled ? dumpDirEnv && dumpDirEnv.length > 0 ? dumpDirEnv : import_node_path.default.resolve(process.cwd(), "tmp") : void 0;
|
|
1659
|
+
return { enabled, dumpDir };
|
|
1660
|
+
};
|
|
1661
|
+
var safeJsonStringify = (value, space) => {
|
|
1662
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
1663
|
+
return JSON.stringify(
|
|
1664
|
+
value,
|
|
1665
|
+
(_key, currentValue) => {
|
|
1666
|
+
if (typeof currentValue === "bigint") {
|
|
1667
|
+
return currentValue.toString();
|
|
1668
|
+
}
|
|
1669
|
+
if (typeof currentValue === "object" && currentValue !== null) {
|
|
1670
|
+
if (seen.has(currentValue)) {
|
|
1671
|
+
return "[Circular]";
|
|
1672
|
+
}
|
|
1673
|
+
seen.add(currentValue);
|
|
1674
|
+
}
|
|
1675
|
+
return currentValue;
|
|
1676
|
+
},
|
|
1677
|
+
space
|
|
1678
|
+
) ?? "null";
|
|
1679
|
+
};
|
|
1680
|
+
var sharedPrefixChars = (a, b) => {
|
|
1681
|
+
const min = Math.min(a.length, b.length);
|
|
1682
|
+
let index = 0;
|
|
1683
|
+
while (index < min && a.charCodeAt(index) === b.charCodeAt(index)) {
|
|
1684
|
+
index += 1;
|
|
1685
|
+
}
|
|
1686
|
+
return index;
|
|
1687
|
+
};
|
|
1688
|
+
var writeProviderLogDump = async (settings, provider, seq, direction, payload) => {
|
|
1689
|
+
if (!settings.dumpDir) {
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
await import_node_fs.promises.mkdir(settings.dumpDir, { recursive: true });
|
|
1693
|
+
const iso = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1694
|
+
const fileName = `${iso}_${process.pid}_${provider}_${seq}_${direction}.json`;
|
|
1695
|
+
const filePath = import_node_path.default.resolve(settings.dumpDir, fileName);
|
|
1696
|
+
const prettyPayload = safeJsonStringify(payload, 2);
|
|
1697
|
+
await import_node_fs.promises.writeFile(filePath, `${prettyPayload}
|
|
1698
|
+
`, "utf8");
|
|
1699
|
+
};
|
|
1700
|
+
|
|
1701
|
+
// src/types/llm/guards.ts
|
|
1702
|
+
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
1703
|
+
function isTextPart(value) {
|
|
1704
|
+
if (!value || typeof value !== "object") return false;
|
|
1705
|
+
const v = value;
|
|
1706
|
+
return v.type === "text" && typeof v.text === "string";
|
|
1707
|
+
}
|
|
1708
|
+
function isImagePart(value) {
|
|
1709
|
+
if (!value || typeof value !== "object") return false;
|
|
1710
|
+
const v = value;
|
|
1711
|
+
if (v.type !== "image_url") return false;
|
|
1712
|
+
if (!v.image_url || typeof v.image_url !== "object") return false;
|
|
1713
|
+
const url = v.image_url.url;
|
|
1714
|
+
return typeof url === "string";
|
|
1715
|
+
}
|
|
1716
|
+
function isDocumentPart(value) {
|
|
1717
|
+
if (!value || typeof value !== "object") return false;
|
|
1718
|
+
const v = value;
|
|
1719
|
+
if (v.type !== "document") return false;
|
|
1720
|
+
if (!v.source || typeof v.source !== "object") return false;
|
|
1721
|
+
const source = v.source;
|
|
1722
|
+
return typeof source.data === "string" && source.media_type === "application/pdf";
|
|
1723
|
+
}
|
|
1724
|
+
function isOtherPart(value) {
|
|
1725
|
+
if (!value || typeof value !== "object") return false;
|
|
1726
|
+
const v = value;
|
|
1727
|
+
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
1728
|
+
}
|
|
1729
|
+
function isContentPart(value) {
|
|
1730
|
+
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
1731
|
+
}
|
|
1732
|
+
function isToolResult(value) {
|
|
1733
|
+
if (!value || typeof value !== "object") return false;
|
|
1734
|
+
const v = value;
|
|
1735
|
+
if (!TOOL_RESULT_TYPES.has(String(v.type))) return false;
|
|
1736
|
+
if (v.type === "text")
|
|
1737
|
+
return typeof value.text === "string";
|
|
1738
|
+
if (v.type === "json") return "value" in value;
|
|
1739
|
+
if (v.type === "parts") {
|
|
1740
|
+
const parts = value.parts;
|
|
1741
|
+
return Array.isArray(parts) && parts.every(isContentPart);
|
|
1742
|
+
}
|
|
1743
|
+
return false;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
// src/types/llm/tools.ts
|
|
1747
|
+
var isHostedSearchToolDefinition = (value) => value.type === "hosted_search";
|
|
1748
|
+
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
1489
1749
|
|
|
1490
1750
|
// src/llm/anthropic/serializer.ts
|
|
1491
1751
|
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
@@ -1613,11 +1873,24 @@ var toToolResultBlock = (message) => {
|
|
|
1613
1873
|
};
|
|
1614
1874
|
var toAnthropicTools = (tools) => {
|
|
1615
1875
|
if (!tools || tools.length === 0) return void 0;
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1876
|
+
const mapped = [];
|
|
1877
|
+
for (const tool of tools) {
|
|
1878
|
+
if (isFunctionToolDefinition(tool)) {
|
|
1879
|
+
mapped.push({
|
|
1880
|
+
name: tool.name,
|
|
1881
|
+
description: tool.description,
|
|
1882
|
+
input_schema: tool.parameters
|
|
1883
|
+
});
|
|
1884
|
+
continue;
|
|
1885
|
+
}
|
|
1886
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
1887
|
+
const hosted = toAnthropicHostedSearchTool(tool);
|
|
1888
|
+
if (hosted) {
|
|
1889
|
+
mapped.push(hosted);
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
return mapped.length ? mapped : void 0;
|
|
1621
1894
|
};
|
|
1622
1895
|
var toAnthropicToolChoice = (choice) => {
|
|
1623
1896
|
if (!choice) return void 0;
|
|
@@ -1760,6 +2033,26 @@ var toChatInvokeCompletion = (response) => {
|
|
|
1760
2033
|
}
|
|
1761
2034
|
};
|
|
1762
2035
|
};
|
|
2036
|
+
var toAnthropicHostedSearchTool = (tool) => {
|
|
2037
|
+
if (tool.provider && tool.provider !== "anthropic") {
|
|
2038
|
+
return null;
|
|
2039
|
+
}
|
|
2040
|
+
const userLocation = tool.user_location ? {
|
|
2041
|
+
type: "approximate",
|
|
2042
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
2043
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
2044
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
2045
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
2046
|
+
} : void 0;
|
|
2047
|
+
return {
|
|
2048
|
+
type: "web_search_20250305",
|
|
2049
|
+
name: "web_search",
|
|
2050
|
+
...tool.allowed_domains?.length ? { allowed_domains: tool.allowed_domains } : {},
|
|
2051
|
+
...tool.blocked_domains?.length ? { blocked_domains: tool.blocked_domains } : {},
|
|
2052
|
+
...typeof tool.max_uses === "number" ? { max_uses: tool.max_uses } : {},
|
|
2053
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
2054
|
+
};
|
|
2055
|
+
};
|
|
1763
2056
|
|
|
1764
2057
|
// src/llm/anthropic/chat.ts
|
|
1765
2058
|
var PROVIDER_NAME = "anthropic";
|
|
@@ -1770,12 +2063,14 @@ var ChatAnthropic = class {
|
|
|
1770
2063
|
model;
|
|
1771
2064
|
client;
|
|
1772
2065
|
defaultMaxTokens;
|
|
2066
|
+
debugInvokeSeq = 0;
|
|
2067
|
+
lastDebugRequestPayload = null;
|
|
1773
2068
|
constructor(options = {}) {
|
|
1774
2069
|
this.client = options.client ?? new import_sdk.default(options.clientOptions);
|
|
1775
2070
|
this.model = options.model ?? DEFAULT_MODEL;
|
|
1776
2071
|
this.defaultMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
1777
2072
|
}
|
|
1778
|
-
async ainvoke(input,
|
|
2073
|
+
async ainvoke(input, _context) {
|
|
1779
2074
|
const {
|
|
1780
2075
|
messages,
|
|
1781
2076
|
tools: toolDefs,
|
|
@@ -1798,24 +2093,102 @@ var ChatAnthropic = class {
|
|
|
1798
2093
|
...tools ? { tools } : {},
|
|
1799
2094
|
...tool_choice ? { tool_choice } : {}
|
|
1800
2095
|
};
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
}
|
|
2096
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
2097
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
1804
2098
|
const response = await this.client.messages.create(
|
|
1805
2099
|
request,
|
|
1806
2100
|
signal ? {
|
|
1807
2101
|
signal
|
|
1808
2102
|
} : void 0
|
|
1809
2103
|
);
|
|
1810
|
-
|
|
1811
|
-
console.debug(response);
|
|
1812
|
-
}
|
|
2104
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
1813
2105
|
return toChatInvokeCompletion(response);
|
|
1814
2106
|
}
|
|
2107
|
+
nextDebugInvokeSeq() {
|
|
2108
|
+
const seq = this.debugInvokeSeq + 1;
|
|
2109
|
+
this.debugInvokeSeq = seq;
|
|
2110
|
+
return seq;
|
|
2111
|
+
}
|
|
2112
|
+
async debugRequestIfEnabled(request, seq) {
|
|
2113
|
+
const settings = getProviderLogSettings();
|
|
2114
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
const payload = safeJsonStringify(request);
|
|
2118
|
+
const hash = (0, import_node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2119
|
+
const toolsHash = (0, import_node_crypto.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
2120
|
+
const systemHash = (0, import_node_crypto.createHash)("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
2121
|
+
const previous = this.lastDebugRequestPayload;
|
|
2122
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2123
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
2124
|
+
if (settings.enabled) {
|
|
2125
|
+
console.error(
|
|
2126
|
+
`[anthropic.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} system_sha=${systemHash}`
|
|
2127
|
+
);
|
|
2128
|
+
}
|
|
2129
|
+
if (settings.dumpDir) {
|
|
2130
|
+
try {
|
|
2131
|
+
await writeProviderLogDump(
|
|
2132
|
+
settings,
|
|
2133
|
+
PROVIDER_NAME,
|
|
2134
|
+
seq,
|
|
2135
|
+
"request",
|
|
2136
|
+
request
|
|
2137
|
+
);
|
|
2138
|
+
} catch (error) {
|
|
2139
|
+
if (settings.enabled) {
|
|
2140
|
+
console.error(
|
|
2141
|
+
`[anthropic.request] dump_failed seq=${seq} error=${String(error)}`
|
|
2142
|
+
);
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
this.lastDebugRequestPayload = payload;
|
|
2147
|
+
}
|
|
2148
|
+
async debugResponseIfEnabled(response, seq) {
|
|
2149
|
+
const settings = getProviderLogSettings();
|
|
2150
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
if (settings.enabled) {
|
|
2154
|
+
const usage = response.usage;
|
|
2155
|
+
const inputTokens = usage?.input_tokens ?? 0;
|
|
2156
|
+
const outputTokens = usage?.output_tokens ?? 0;
|
|
2157
|
+
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
2158
|
+
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
2159
|
+
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
2160
|
+
const blockKinds = /* @__PURE__ */ new Set();
|
|
2161
|
+
for (const block of blocks) {
|
|
2162
|
+
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
2163
|
+
blockKinds.add(kind);
|
|
2164
|
+
}
|
|
2165
|
+
console.error(
|
|
2166
|
+
`[anthropic.response] seq=${seq} id=${response.id} stop=${String(response.stop_reason ?? "unknown")} blocks=${blocks.length} kinds=${Array.from(blockKinds).join(",")} tok_in=${inputTokens} tok_out=${outputTokens} cache_read=${cachedRead} cache_create=${cachedCreate}`
|
|
2167
|
+
);
|
|
2168
|
+
}
|
|
2169
|
+
if (settings.dumpDir) {
|
|
2170
|
+
try {
|
|
2171
|
+
await writeProviderLogDump(
|
|
2172
|
+
settings,
|
|
2173
|
+
PROVIDER_NAME,
|
|
2174
|
+
seq,
|
|
2175
|
+
"response",
|
|
2176
|
+
response
|
|
2177
|
+
);
|
|
2178
|
+
} catch (error) {
|
|
2179
|
+
if (settings.enabled) {
|
|
2180
|
+
console.error(
|
|
2181
|
+
`[anthropic.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2182
|
+
);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
1815
2187
|
};
|
|
1816
2188
|
|
|
1817
2189
|
// src/llm/openai/chat.ts
|
|
1818
2190
|
var import_openai3 = __toESM(require("openai"), 1);
|
|
2191
|
+
var import_node_crypto2 = require("crypto");
|
|
1819
2192
|
|
|
1820
2193
|
// src/llm/openai/response-utils.ts
|
|
1821
2194
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -1943,6 +2316,23 @@ var isOpenAIAssistantInputContent = (value) => {
|
|
|
1943
2316
|
}
|
|
1944
2317
|
return false;
|
|
1945
2318
|
};
|
|
2319
|
+
var isReplayableOpenAIHistoryItem = (value) => {
|
|
2320
|
+
if (!value || typeof value !== "object") {
|
|
2321
|
+
return false;
|
|
2322
|
+
}
|
|
2323
|
+
const type = value.type;
|
|
2324
|
+
if (type === "reasoning") {
|
|
2325
|
+
return typeof value.id === "string";
|
|
2326
|
+
}
|
|
2327
|
+
return type === "web_search_call";
|
|
2328
|
+
};
|
|
2329
|
+
var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
2330
|
+
if (!value || typeof value !== "object") {
|
|
2331
|
+
return false;
|
|
2332
|
+
}
|
|
2333
|
+
const record = value;
|
|
2334
|
+
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
2335
|
+
};
|
|
1946
2336
|
var toAssistantInputContent = (part) => {
|
|
1947
2337
|
switch (part.type) {
|
|
1948
2338
|
case "text":
|
|
@@ -1984,6 +2374,21 @@ var extractReasoningText = (item) => {
|
|
|
1984
2374
|
).filter((text) => text.length > 0).join("\n");
|
|
1985
2375
|
return contentText;
|
|
1986
2376
|
};
|
|
2377
|
+
var extractWebSearchSummary = (item) => {
|
|
2378
|
+
const parts = [`WebSearch status=${item.status}`];
|
|
2379
|
+
const record = item;
|
|
2380
|
+
const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
|
|
2381
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
2382
|
+
) : [];
|
|
2383
|
+
if (queries.length) {
|
|
2384
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
2385
|
+
}
|
|
2386
|
+
const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
|
|
2387
|
+
if (sources.length) {
|
|
2388
|
+
parts.push(`sources=${sources.length}`);
|
|
2389
|
+
}
|
|
2390
|
+
return parts.join(" | ");
|
|
2391
|
+
};
|
|
1987
2392
|
var toMessageSequence = (response) => {
|
|
1988
2393
|
const messages = [];
|
|
1989
2394
|
for (const item of response.output) {
|
|
@@ -2017,6 +2422,14 @@ var toMessageSequence = (response) => {
|
|
|
2017
2422
|
});
|
|
2018
2423
|
break;
|
|
2019
2424
|
}
|
|
2425
|
+
case "web_search_call": {
|
|
2426
|
+
messages.push({
|
|
2427
|
+
role: "reasoning",
|
|
2428
|
+
content: extractWebSearchSummary(item),
|
|
2429
|
+
raw_item: item
|
|
2430
|
+
});
|
|
2431
|
+
break;
|
|
2432
|
+
}
|
|
2020
2433
|
default: {
|
|
2021
2434
|
messages.push({
|
|
2022
2435
|
role: "assistant",
|
|
@@ -2080,6 +2493,9 @@ function toResponsesInput(messages) {
|
|
|
2080
2493
|
continue;
|
|
2081
2494
|
}
|
|
2082
2495
|
if (message.role === "reasoning") {
|
|
2496
|
+
if (isReplayableOpenAIHistoryItem(message.raw_item)) {
|
|
2497
|
+
items.push(message.raw_item);
|
|
2498
|
+
}
|
|
2083
2499
|
continue;
|
|
2084
2500
|
}
|
|
2085
2501
|
if (message.role === "assistant") {
|
|
@@ -2101,13 +2517,26 @@ function toResponsesTools(tools) {
|
|
|
2101
2517
|
if (!tools || tools.length === 0) {
|
|
2102
2518
|
return void 0;
|
|
2103
2519
|
}
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2520
|
+
const mapped = [];
|
|
2521
|
+
for (const tool of tools) {
|
|
2522
|
+
if (isFunctionToolDefinition(tool)) {
|
|
2523
|
+
mapped.push({
|
|
2524
|
+
type: "function",
|
|
2525
|
+
name: tool.name,
|
|
2526
|
+
description: tool.description,
|
|
2527
|
+
parameters: tool.parameters,
|
|
2528
|
+
strict: tool.strict ?? false
|
|
2529
|
+
});
|
|
2530
|
+
continue;
|
|
2531
|
+
}
|
|
2532
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
2533
|
+
const hosted = toOpenAiHostedSearchTool(tool);
|
|
2534
|
+
if (hosted) {
|
|
2535
|
+
mapped.push(hosted);
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
return mapped.length ? mapped : void 0;
|
|
2111
2540
|
}
|
|
2112
2541
|
function toResponsesToolChoice(choice) {
|
|
2113
2542
|
if (!choice) {
|
|
@@ -2160,6 +2589,10 @@ function toAssistantMessageItem(message) {
|
|
|
2160
2589
|
};
|
|
2161
2590
|
}
|
|
2162
2591
|
function toFunctionCallItem(call) {
|
|
2592
|
+
if (isReplayableOpenAIFunctionCallItem(call.provider_meta)) {
|
|
2593
|
+
const { parsed_arguments: _parsed, ...rest } = call.provider_meta;
|
|
2594
|
+
return rest;
|
|
2595
|
+
}
|
|
2163
2596
|
return {
|
|
2164
2597
|
type: "function_call",
|
|
2165
2598
|
call_id: call.id,
|
|
@@ -2174,25 +2607,52 @@ function toFunctionCallOutputItem(message) {
|
|
|
2174
2607
|
output: toFunctionCallOutput(message.content)
|
|
2175
2608
|
};
|
|
2176
2609
|
}
|
|
2610
|
+
function toOpenAiHostedSearchTool(tool) {
|
|
2611
|
+
if (tool.provider && tool.provider !== "openai" && tool.provider !== "openrouter") {
|
|
2612
|
+
return null;
|
|
2613
|
+
}
|
|
2614
|
+
const userLocation = tool.user_location ? {
|
|
2615
|
+
type: "approximate",
|
|
2616
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
2617
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
2618
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
2619
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
2620
|
+
} : void 0;
|
|
2621
|
+
return {
|
|
2622
|
+
type: "web_search",
|
|
2623
|
+
...tool.search_context_size ? { search_context_size: tool.search_context_size } : {},
|
|
2624
|
+
...tool.allowed_domains?.length ? {
|
|
2625
|
+
filters: {
|
|
2626
|
+
allowed_domains: tool.allowed_domains
|
|
2627
|
+
}
|
|
2628
|
+
} : {},
|
|
2629
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
2630
|
+
};
|
|
2631
|
+
}
|
|
2177
2632
|
|
|
2178
2633
|
// src/llm/openai/chat.ts
|
|
2179
2634
|
var PROVIDER_NAME2 = "openai";
|
|
2180
2635
|
var DEFAULT_MODEL2 = OPENAI_DEFAULT_MODEL;
|
|
2181
2636
|
var DEFAULT_REASONING_EFFORT = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
2182
2637
|
var DEFAULT_REASONING_SUMMARY = "auto";
|
|
2638
|
+
var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
2639
|
+
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
2640
|
+
};
|
|
2183
2641
|
var ChatOpenAI = class {
|
|
2184
2642
|
provider = PROVIDER_NAME2;
|
|
2185
2643
|
model;
|
|
2186
2644
|
client;
|
|
2187
2645
|
defaultReasoningEffort;
|
|
2188
2646
|
defaultTextVerbosity;
|
|
2647
|
+
debugInvokeSeq = 0;
|
|
2648
|
+
lastDebugRequestPayload = null;
|
|
2189
2649
|
constructor(options = {}) {
|
|
2190
2650
|
this.client = options.client ?? new import_openai3.default(options.clientOptions);
|
|
2191
2651
|
this.model = options.model ?? DEFAULT_MODEL2;
|
|
2192
2652
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT;
|
|
2193
2653
|
this.defaultTextVerbosity = options.textVerbosity;
|
|
2194
2654
|
}
|
|
2195
|
-
async ainvoke(input,
|
|
2655
|
+
async ainvoke(input, context) {
|
|
2196
2656
|
const {
|
|
2197
2657
|
messages,
|
|
2198
2658
|
tools: toolDefs,
|
|
@@ -2219,7 +2679,16 @@ var ChatOpenAI = class {
|
|
|
2219
2679
|
if (instructions) {
|
|
2220
2680
|
request.instructions = instructions;
|
|
2221
2681
|
}
|
|
2222
|
-
|
|
2682
|
+
const hasWebSearchTool = tools?.some(
|
|
2683
|
+
(tool) => tool.type === "web_search" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11"
|
|
2684
|
+
);
|
|
2685
|
+
const includeSet = new Set(request.include ?? []);
|
|
2686
|
+
includeSet.add("reasoning.encrypted_content");
|
|
2687
|
+
if (hasWebSearchTool) {
|
|
2688
|
+
includeSet.add("web_search_call.action.sources");
|
|
2689
|
+
includeSet.add("web_search_call.results");
|
|
2690
|
+
}
|
|
2691
|
+
request.include = Array.from(includeSet);
|
|
2223
2692
|
const effort = reasoningEffort ?? this.defaultReasoningEffort;
|
|
2224
2693
|
request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY };
|
|
2225
2694
|
const verbosity = textVerbosity ?? this.defaultTextVerbosity;
|
|
@@ -2229,91 +2698,129 @@ var ChatOpenAI = class {
|
|
|
2229
2698
|
verbosity
|
|
2230
2699
|
};
|
|
2231
2700
|
}
|
|
2232
|
-
if (
|
|
2233
|
-
|
|
2701
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
2702
|
+
request.prompt_cache_key = context.sessionKey;
|
|
2234
2703
|
}
|
|
2704
|
+
const sessionIdHeader = getSessionIdHeaderValue(request.prompt_cache_key);
|
|
2705
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
2706
|
+
await this.debugRequestIfEnabled(request, debugSeq, sessionIdHeader);
|
|
2235
2707
|
const streamRequest = {
|
|
2236
2708
|
...request,
|
|
2237
2709
|
stream: true
|
|
2238
2710
|
};
|
|
2239
2711
|
const response = await this.client.responses.stream(
|
|
2240
2712
|
streamRequest,
|
|
2241
|
-
signal ? {
|
|
2242
|
-
signal
|
|
2713
|
+
signal || sessionIdHeader ? {
|
|
2714
|
+
...signal ? { signal } : {},
|
|
2715
|
+
...sessionIdHeader ? {
|
|
2716
|
+
headers: {
|
|
2717
|
+
session_id: sessionIdHeader
|
|
2718
|
+
}
|
|
2719
|
+
} : {}
|
|
2243
2720
|
} : void 0
|
|
2244
2721
|
).finalResponse();
|
|
2245
|
-
|
|
2246
|
-
console.debug(response);
|
|
2247
|
-
}
|
|
2722
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
2248
2723
|
return toChatInvokeCompletion2(response);
|
|
2249
2724
|
}
|
|
2725
|
+
nextDebugInvokeSeq() {
|
|
2726
|
+
const seq = this.debugInvokeSeq + 1;
|
|
2727
|
+
this.debugInvokeSeq = seq;
|
|
2728
|
+
return seq;
|
|
2729
|
+
}
|
|
2730
|
+
async debugRequestIfEnabled(request, seq, sessionIdHeader) {
|
|
2731
|
+
const settings = getProviderLogSettings();
|
|
2732
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2733
|
+
return;
|
|
2734
|
+
}
|
|
2735
|
+
const payload = safeJsonStringify(request);
|
|
2736
|
+
const hash = (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2737
|
+
const toolsHash = (0, import_node_crypto2.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
2738
|
+
const instructionsHash = (0, import_node_crypto2.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
2739
|
+
const previous = this.lastDebugRequestPayload;
|
|
2740
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2741
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
2742
|
+
if (settings.enabled) {
|
|
2743
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto2.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
2744
|
+
console.error(
|
|
2745
|
+
`[openai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
2746
|
+
);
|
|
2747
|
+
}
|
|
2748
|
+
if (settings.dumpDir) {
|
|
2749
|
+
try {
|
|
2750
|
+
await writeProviderLogDump(
|
|
2751
|
+
settings,
|
|
2752
|
+
PROVIDER_NAME2,
|
|
2753
|
+
seq,
|
|
2754
|
+
"request",
|
|
2755
|
+
request
|
|
2756
|
+
);
|
|
2757
|
+
} catch (error) {
|
|
2758
|
+
if (settings.enabled) {
|
|
2759
|
+
console.error(
|
|
2760
|
+
`[openai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
2761
|
+
);
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
this.lastDebugRequestPayload = payload;
|
|
2766
|
+
}
|
|
2767
|
+
async debugResponseIfEnabled(response, seq) {
|
|
2768
|
+
const settings = getProviderLogSettings();
|
|
2769
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2770
|
+
return;
|
|
2771
|
+
}
|
|
2772
|
+
if (settings.enabled) {
|
|
2773
|
+
const usage = response.usage;
|
|
2774
|
+
const cachedInputTokens = usage?.input_tokens_details?.cached_tokens ?? 0;
|
|
2775
|
+
const outputItems = Array.isArray(response.output) ? response.output : [];
|
|
2776
|
+
const outputKinds = /* @__PURE__ */ new Set();
|
|
2777
|
+
for (const item of outputItems) {
|
|
2778
|
+
const kind = item && typeof item === "object" && "type" in item ? String(item.type ?? "unknown") : "unknown";
|
|
2779
|
+
outputKinds.add(kind);
|
|
2780
|
+
}
|
|
2781
|
+
const usageIn = usage?.input_tokens ?? 0;
|
|
2782
|
+
console.error(
|
|
2783
|
+
`[openai.response] seq=${seq} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
2784
|
+
);
|
|
2785
|
+
}
|
|
2786
|
+
if (settings.dumpDir) {
|
|
2787
|
+
try {
|
|
2788
|
+
await writeProviderLogDump(
|
|
2789
|
+
settings,
|
|
2790
|
+
PROVIDER_NAME2,
|
|
2791
|
+
seq,
|
|
2792
|
+
"response",
|
|
2793
|
+
response
|
|
2794
|
+
);
|
|
2795
|
+
} catch (error) {
|
|
2796
|
+
if (settings.enabled) {
|
|
2797
|
+
console.error(
|
|
2798
|
+
`[openai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2799
|
+
);
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2250
2804
|
};
|
|
2251
2805
|
|
|
2252
2806
|
// src/prompts.ts
|
|
2253
|
-
var
|
|
2807
|
+
var import_node_path2 = __toESM(require("path"), 1);
|
|
2254
2808
|
var import_node_url = require("url");
|
|
2255
2809
|
var import_meta = {};
|
|
2256
2810
|
var resolvePromptPath = () => {
|
|
2257
2811
|
if (typeof __filename === "string") {
|
|
2258
|
-
return
|
|
2812
|
+
return import_node_path2.default.resolve(import_node_path2.default.dirname(__filename), "../prompts/system.md");
|
|
2259
2813
|
}
|
|
2260
2814
|
if (typeof import_meta !== "undefined" && import_meta.url) {
|
|
2261
2815
|
return (0, import_node_url.fileURLToPath)(new URL("../prompts/system.md", import_meta.url));
|
|
2262
2816
|
}
|
|
2263
|
-
return
|
|
2817
|
+
return import_node_path2.default.resolve("prompts/system.md");
|
|
2264
2818
|
};
|
|
2265
2819
|
var promptPath = resolvePromptPath();
|
|
2266
2820
|
var getDefaultSystemPromptPath = () => promptPath;
|
|
2267
2821
|
|
|
2268
2822
|
// src/tools/define.ts
|
|
2269
2823
|
var import_zod = require("zod");
|
|
2270
|
-
|
|
2271
|
-
// src/types/llm/guards.ts
|
|
2272
|
-
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2273
|
-
function isTextPart(value) {
|
|
2274
|
-
if (!value || typeof value !== "object") return false;
|
|
2275
|
-
const v = value;
|
|
2276
|
-
return v.type === "text" && typeof v.text === "string";
|
|
2277
|
-
}
|
|
2278
|
-
function isImagePart(value) {
|
|
2279
|
-
if (!value || typeof value !== "object") return false;
|
|
2280
|
-
const v = value;
|
|
2281
|
-
if (v.type !== "image_url") return false;
|
|
2282
|
-
if (!v.image_url || typeof v.image_url !== "object") return false;
|
|
2283
|
-
const url = v.image_url.url;
|
|
2284
|
-
return typeof url === "string";
|
|
2285
|
-
}
|
|
2286
|
-
function isDocumentPart(value) {
|
|
2287
|
-
if (!value || typeof value !== "object") return false;
|
|
2288
|
-
const v = value;
|
|
2289
|
-
if (v.type !== "document") return false;
|
|
2290
|
-
if (!v.source || typeof v.source !== "object") return false;
|
|
2291
|
-
const source = v.source;
|
|
2292
|
-
return typeof source.data === "string" && source.media_type === "application/pdf";
|
|
2293
|
-
}
|
|
2294
|
-
function isOtherPart(value) {
|
|
2295
|
-
if (!value || typeof value !== "object") return false;
|
|
2296
|
-
const v = value;
|
|
2297
|
-
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2298
|
-
}
|
|
2299
|
-
function isContentPart(value) {
|
|
2300
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
2301
|
-
}
|
|
2302
|
-
function isToolResult(value) {
|
|
2303
|
-
if (!value || typeof value !== "object") return false;
|
|
2304
|
-
const v = value;
|
|
2305
|
-
if (!TOOL_RESULT_TYPES.has(String(v.type))) return false;
|
|
2306
|
-
if (v.type === "text")
|
|
2307
|
-
return typeof value.text === "string";
|
|
2308
|
-
if (v.type === "json") return "value" in value;
|
|
2309
|
-
if (v.type === "parts") {
|
|
2310
|
-
const parts = value.parts;
|
|
2311
|
-
return Array.isArray(parts) && parts.every(isContentPart);
|
|
2312
|
-
}
|
|
2313
|
-
return false;
|
|
2314
|
-
}
|
|
2315
|
-
|
|
2316
|
-
// src/tools/define.ts
|
|
2317
2824
|
var mapSchema = (schema, transform) => {
|
|
2318
2825
|
if (!schema || typeof schema !== "object") return schema;
|
|
2319
2826
|
const next = transform({ ...schema });
|