@codelia/core 0.1.13 → 0.1.15
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.js
CHANGED
|
@@ -368,13 +368,16 @@ var CompactionService = class _CompactionService {
|
|
|
368
368
|
};
|
|
369
369
|
let response;
|
|
370
370
|
try {
|
|
371
|
-
response = await llm.ainvoke(
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
371
|
+
response = await llm.ainvoke(
|
|
372
|
+
{
|
|
373
|
+
messages: [...preparedMessages, interruptMessage],
|
|
374
|
+
tools: null,
|
|
375
|
+
toolChoice: "none",
|
|
376
|
+
...options?.signal ? { signal: options.signal } : {},
|
|
377
|
+
...this.config.model ? { model: this.config.model } : {}
|
|
378
|
+
},
|
|
379
|
+
options?.invokeContext
|
|
380
|
+
);
|
|
378
381
|
} catch (error) {
|
|
379
382
|
if (error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal")) {
|
|
380
383
|
throw error;
|
|
@@ -687,7 +690,7 @@ var ToolOutputCacheService = class {
|
|
|
687
690
|
};
|
|
688
691
|
}
|
|
689
692
|
async trimMessages(llm, messages) {
|
|
690
|
-
if (this.config.enabled === false) {
|
|
693
|
+
if (this.config.enabled === false || this.config.totalBudgetTrim === false) {
|
|
691
694
|
return { messages, trimmed: false };
|
|
692
695
|
}
|
|
693
696
|
const budget = await this.resolveContextBudgetTokens(llm);
|
|
@@ -850,11 +853,73 @@ function toolResultToContent(result) {
|
|
|
850
853
|
}
|
|
851
854
|
}
|
|
852
855
|
var collectModelOutput = (messages) => {
|
|
856
|
+
const buildWebSearchSummary = (status, queries, sourcesCount) => {
|
|
857
|
+
const parts = [`WebSearch status=${status}`];
|
|
858
|
+
if (queries.length) {
|
|
859
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
860
|
+
}
|
|
861
|
+
if (typeof sourcesCount === "number") {
|
|
862
|
+
parts.push(`sources=${sourcesCount}`);
|
|
863
|
+
}
|
|
864
|
+
return parts.join(" | ");
|
|
865
|
+
};
|
|
853
866
|
const reasoningTexts = [];
|
|
854
867
|
const assistantTexts = [];
|
|
855
868
|
const toolCalls = [];
|
|
869
|
+
const hostedToolCalls = [];
|
|
870
|
+
const hostedWebSearchById = /* @__PURE__ */ new Map();
|
|
871
|
+
const hostedWebSearchOrder = [];
|
|
872
|
+
let anonymousWebSearchCounter = 0;
|
|
873
|
+
let lastAnonymousWebSearchId = null;
|
|
856
874
|
for (const message of messages) {
|
|
857
875
|
if (message.role === "reasoning") {
|
|
876
|
+
const raw = message.raw_item;
|
|
877
|
+
if (raw && typeof raw === "object" && raw.type === "web_search_call") {
|
|
878
|
+
const record = raw;
|
|
879
|
+
const statusRaw = record.status;
|
|
880
|
+
const status = typeof statusRaw === "string" ? statusRaw : "completed";
|
|
881
|
+
const action = record.action && typeof record.action === "object" ? record.action : null;
|
|
882
|
+
const queries = Array.isArray(action?.queries) ? action?.queries.filter(
|
|
883
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
884
|
+
) : [];
|
|
885
|
+
const sourcesCount = Array.isArray(action?.sources) ? action?.sources.length : void 0;
|
|
886
|
+
const explicitId = typeof record.id === "string" && record.id.length > 0 ? record.id : null;
|
|
887
|
+
let id = explicitId;
|
|
888
|
+
const hasSearchContext = queries.length > 0 || typeof sourcesCount === "number";
|
|
889
|
+
if (!id) {
|
|
890
|
+
if (hasSearchContext || status === "failed") {
|
|
891
|
+
anonymousWebSearchCounter += 1;
|
|
892
|
+
id = `web_search_${anonymousWebSearchCounter}`;
|
|
893
|
+
if (hasSearchContext) {
|
|
894
|
+
lastAnonymousWebSearchId = id;
|
|
895
|
+
}
|
|
896
|
+
} else if (lastAnonymousWebSearchId) {
|
|
897
|
+
id = lastAnonymousWebSearchId;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (!id) {
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
const existing = hostedWebSearchById.get(id);
|
|
904
|
+
if (existing) {
|
|
905
|
+
existing.status = status;
|
|
906
|
+
if (queries.length) {
|
|
907
|
+
existing.queries = queries;
|
|
908
|
+
}
|
|
909
|
+
if (typeof sourcesCount === "number") {
|
|
910
|
+
existing.sourcesCount = sourcesCount;
|
|
911
|
+
}
|
|
912
|
+
} else {
|
|
913
|
+
hostedWebSearchById.set(id, {
|
|
914
|
+
id,
|
|
915
|
+
status,
|
|
916
|
+
queries,
|
|
917
|
+
...typeof sourcesCount === "number" ? { sourcesCount } : {}
|
|
918
|
+
});
|
|
919
|
+
hostedWebSearchOrder.push(id);
|
|
920
|
+
}
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
858
923
|
const text = message.content ?? "";
|
|
859
924
|
if (text) {
|
|
860
925
|
reasoningTexts.push(text);
|
|
@@ -874,7 +939,30 @@ var collectModelOutput = (messages) => {
|
|
|
874
939
|
toolCalls.push(...message.tool_calls);
|
|
875
940
|
}
|
|
876
941
|
}
|
|
877
|
-
|
|
942
|
+
for (const id of hostedWebSearchOrder) {
|
|
943
|
+
const aggregate = hostedWebSearchById.get(id);
|
|
944
|
+
if (!aggregate) {
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
const args = {
|
|
948
|
+
status: aggregate.status,
|
|
949
|
+
...aggregate.queries.length ? { queries: aggregate.queries } : {},
|
|
950
|
+
...typeof aggregate.sourcesCount === "number" ? { sources_count: aggregate.sourcesCount } : {}
|
|
951
|
+
};
|
|
952
|
+
hostedToolCalls.push({
|
|
953
|
+
id: aggregate.id,
|
|
954
|
+
tool: "web_search",
|
|
955
|
+
displayName: "WebSearch",
|
|
956
|
+
args,
|
|
957
|
+
result: buildWebSearchSummary(
|
|
958
|
+
aggregate.status,
|
|
959
|
+
aggregate.queries,
|
|
960
|
+
aggregate.sourcesCount
|
|
961
|
+
),
|
|
962
|
+
isError: aggregate.status === "failed"
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
return { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls };
|
|
878
966
|
};
|
|
879
967
|
var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
880
968
|
var createAbortError = () => {
|
|
@@ -891,6 +979,7 @@ var throwIfAborted = (signal) => {
|
|
|
891
979
|
var Agent = class {
|
|
892
980
|
llm;
|
|
893
981
|
tools;
|
|
982
|
+
hostedTools;
|
|
894
983
|
systemPrompt;
|
|
895
984
|
maxIterations;
|
|
896
985
|
toolChoice;
|
|
@@ -907,6 +996,7 @@ var Agent = class {
|
|
|
907
996
|
this.llm = options.llm;
|
|
908
997
|
this.history = this.llm.provider === "openai" ? new OpenAIHistoryAdapter() : new MessageHistoryAdapter();
|
|
909
998
|
this.tools = options.tools;
|
|
999
|
+
this.hostedTools = options.hostedTools ?? [];
|
|
910
1000
|
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
911
1001
|
this.maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
912
1002
|
this.toolChoice = options.toolChoice ?? void 0;
|
|
@@ -972,10 +1062,14 @@ var Agent = class {
|
|
|
972
1062
|
timestamp: Date.now()
|
|
973
1063
|
};
|
|
974
1064
|
yield startEvent;
|
|
1065
|
+
const invokeContext = this.buildInvokeContext(options.session);
|
|
975
1066
|
const { compacted, compactedMessages, usage } = await this.compactionService.compact(
|
|
976
1067
|
this.llm,
|
|
977
1068
|
this.history.getViewMessages(),
|
|
978
|
-
{
|
|
1069
|
+
{
|
|
1070
|
+
...signal ? { signal } : {},
|
|
1071
|
+
...invokeContext ? { invokeContext } : {}
|
|
1072
|
+
}
|
|
979
1073
|
);
|
|
980
1074
|
this.usageService.updateUsageSummary(usage);
|
|
981
1075
|
if (compacted && compactedMessages) {
|
|
@@ -1021,7 +1115,7 @@ var Agent = class {
|
|
|
1021
1115
|
now: () => /* @__PURE__ */ new Date()
|
|
1022
1116
|
};
|
|
1023
1117
|
}
|
|
1024
|
-
recordLlmRequest(session, input) {
|
|
1118
|
+
recordLlmRequest(session, input, context) {
|
|
1025
1119
|
if (!session) return null;
|
|
1026
1120
|
const seq = (session.invoke_seq ?? 0) + 1;
|
|
1027
1121
|
session.invoke_seq = seq;
|
|
@@ -1039,11 +1133,24 @@ var Agent = class {
|
|
|
1039
1133
|
messages: input.messages,
|
|
1040
1134
|
tools: input.tools ?? null,
|
|
1041
1135
|
tool_choice: input.toolChoice ?? null,
|
|
1042
|
-
model: input.model
|
|
1136
|
+
model: input.model,
|
|
1137
|
+
...context?.sessionKey ? { session_key: context.sessionKey } : {}
|
|
1043
1138
|
}
|
|
1044
1139
|
});
|
|
1045
1140
|
return seq;
|
|
1046
1141
|
}
|
|
1142
|
+
resolveSessionKey(session) {
|
|
1143
|
+
const sessionId = session?.session_id?.trim();
|
|
1144
|
+
if (sessionId && sessionId.length > 0) {
|
|
1145
|
+
return sessionId;
|
|
1146
|
+
}
|
|
1147
|
+
const runId = session?.run_id?.trim();
|
|
1148
|
+
return runId && runId.length > 0 ? runId : void 0;
|
|
1149
|
+
}
|
|
1150
|
+
buildInvokeContext(session) {
|
|
1151
|
+
const sessionKey = this.resolveSessionKey(session);
|
|
1152
|
+
return sessionKey ? { sessionKey } : void 0;
|
|
1153
|
+
}
|
|
1047
1154
|
recordLlmResponse(session, seq, response) {
|
|
1048
1155
|
if (!session || seq === null) return;
|
|
1049
1156
|
session.append({
|
|
@@ -1081,7 +1188,7 @@ var Agent = class {
|
|
|
1081
1188
|
this.history.enqueueSystem(systemMessage);
|
|
1082
1189
|
}
|
|
1083
1190
|
if (forceCompaction) {
|
|
1084
|
-
yield* this.checkAndCompact(signal, { force: true });
|
|
1191
|
+
yield* this.checkAndCompact(signal, { force: true, session });
|
|
1085
1192
|
const finalResponseEvent2 = {
|
|
1086
1193
|
type: "final",
|
|
1087
1194
|
content: "Compaction run completed."
|
|
@@ -1097,20 +1204,30 @@ var Agent = class {
|
|
|
1097
1204
|
await this.trimToolOutputs();
|
|
1098
1205
|
throwIfAborted(signal);
|
|
1099
1206
|
const invokeInput = this.history.prepareInvokeInput({
|
|
1100
|
-
tools:
|
|
1207
|
+
tools: [
|
|
1208
|
+
...this.tools.map((t) => t.definition),
|
|
1209
|
+
...this.hostedTools
|
|
1210
|
+
],
|
|
1101
1211
|
toolChoice: this.toolChoice
|
|
1102
1212
|
});
|
|
1103
|
-
const
|
|
1104
|
-
const
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1213
|
+
const invokeContext = this.buildInvokeContext(session);
|
|
1214
|
+
const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
|
|
1215
|
+
const response = await this.llm.ainvoke(
|
|
1216
|
+
{
|
|
1217
|
+
...invokeInput,
|
|
1218
|
+
...signal ? { signal } : {}
|
|
1219
|
+
},
|
|
1220
|
+
invokeContext
|
|
1221
|
+
);
|
|
1108
1222
|
this.recordLlmResponse(session, seq, response);
|
|
1109
1223
|
this.usageService.updateUsageSummary(response.usage);
|
|
1110
1224
|
this.history.commitModelResponse(response);
|
|
1111
|
-
const {
|
|
1112
|
-
|
|
1113
|
-
|
|
1225
|
+
const {
|
|
1226
|
+
reasoningTexts,
|
|
1227
|
+
assistantTexts,
|
|
1228
|
+
toolCalls,
|
|
1229
|
+
hostedToolCalls
|
|
1230
|
+
} = collectModelOutput(response.messages);
|
|
1114
1231
|
for (const reasoningText of reasoningTexts) {
|
|
1115
1232
|
const reasoningEvent = {
|
|
1116
1233
|
type: "reasoning",
|
|
@@ -1119,6 +1236,42 @@ var Agent = class {
|
|
|
1119
1236
|
};
|
|
1120
1237
|
yield reasoningEvent;
|
|
1121
1238
|
}
|
|
1239
|
+
let stepNumber = 0;
|
|
1240
|
+
for (const hostedCall of hostedToolCalls) {
|
|
1241
|
+
stepNumber++;
|
|
1242
|
+
const stepStartEvent = {
|
|
1243
|
+
type: "step_start",
|
|
1244
|
+
step_id: hostedCall.id,
|
|
1245
|
+
title: hostedCall.displayName,
|
|
1246
|
+
step_number: stepNumber
|
|
1247
|
+
};
|
|
1248
|
+
yield stepStartEvent;
|
|
1249
|
+
const rawArgs = JSON.stringify(hostedCall.args);
|
|
1250
|
+
const toolCallEvent = {
|
|
1251
|
+
type: "tool_call",
|
|
1252
|
+
tool: hostedCall.tool,
|
|
1253
|
+
args: hostedCall.args,
|
|
1254
|
+
raw_args: rawArgs,
|
|
1255
|
+
tool_call_id: hostedCall.id,
|
|
1256
|
+
display_name: hostedCall.displayName
|
|
1257
|
+
};
|
|
1258
|
+
yield toolCallEvent;
|
|
1259
|
+
const toolResultEvent = {
|
|
1260
|
+
type: "tool_result",
|
|
1261
|
+
tool: hostedCall.tool,
|
|
1262
|
+
result: hostedCall.result,
|
|
1263
|
+
tool_call_id: hostedCall.id,
|
|
1264
|
+
...hostedCall.isError ? { is_error: true } : {}
|
|
1265
|
+
};
|
|
1266
|
+
yield toolResultEvent;
|
|
1267
|
+
const stepCompleteEvent = {
|
|
1268
|
+
type: "step_complete",
|
|
1269
|
+
step_id: hostedCall.id,
|
|
1270
|
+
status: hostedCall.isError ? "error" : "completed",
|
|
1271
|
+
duration_ms: 0
|
|
1272
|
+
};
|
|
1273
|
+
yield stepCompleteEvent;
|
|
1274
|
+
}
|
|
1122
1275
|
const hasToolCalls = toolCalls.length > 0;
|
|
1123
1276
|
const shouldEmitFinalOnly = !hasToolCalls && !this.requireDoneTool;
|
|
1124
1277
|
if (!shouldEmitFinalOnly) {
|
|
@@ -1133,7 +1286,7 @@ var Agent = class {
|
|
|
1133
1286
|
}
|
|
1134
1287
|
if (!hasToolCalls) {
|
|
1135
1288
|
if (!this.requireDoneTool) {
|
|
1136
|
-
yield* this.checkAndCompact(signal);
|
|
1289
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1137
1290
|
const finalText = assistantTexts.join("\n").trim();
|
|
1138
1291
|
const finalResponseEvent2 = {
|
|
1139
1292
|
type: "final",
|
|
@@ -1142,11 +1295,10 @@ var Agent = class {
|
|
|
1142
1295
|
yield finalResponseEvent2;
|
|
1143
1296
|
return;
|
|
1144
1297
|
} else {
|
|
1145
|
-
yield* this.checkAndCompact(signal);
|
|
1298
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1146
1299
|
}
|
|
1147
1300
|
continue;
|
|
1148
1301
|
}
|
|
1149
|
-
let stepNumber = 0;
|
|
1150
1302
|
for (const toolCall of toolCalls) {
|
|
1151
1303
|
stepNumber++;
|
|
1152
1304
|
let jsonArgs;
|
|
@@ -1272,7 +1424,7 @@ var Agent = class {
|
|
|
1272
1424
|
yield stepCompleteEvent;
|
|
1273
1425
|
}
|
|
1274
1426
|
}
|
|
1275
|
-
yield* this.checkAndCompact(signal);
|
|
1427
|
+
yield* this.checkAndCompact(signal, { session });
|
|
1276
1428
|
}
|
|
1277
1429
|
const finalResponse = await this.generateFinalResponse(session, signal);
|
|
1278
1430
|
const finalResponseEvent = {
|
|
@@ -1295,11 +1447,15 @@ var Agent = class {
|
|
|
1295
1447
|
// no tools are allowed at this point
|
|
1296
1448
|
toolChoice: "none"
|
|
1297
1449
|
};
|
|
1298
|
-
const
|
|
1299
|
-
const
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1450
|
+
const invokeContext = this.buildInvokeContext(session);
|
|
1451
|
+
const seq = this.recordLlmRequest(session, input, invokeContext);
|
|
1452
|
+
const summary = await this.llm.ainvoke(
|
|
1453
|
+
{
|
|
1454
|
+
...input,
|
|
1455
|
+
...signal ? { signal } : {}
|
|
1456
|
+
},
|
|
1457
|
+
invokeContext
|
|
1458
|
+
);
|
|
1303
1459
|
this.recordLlmResponse(session, seq, summary);
|
|
1304
1460
|
this.usageService.updateUsageSummary(summary.usage);
|
|
1305
1461
|
const { assistantTexts } = collectModelOutput(summary.messages);
|
|
@@ -1430,6 +1586,110 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1430
1586
|
|
|
1431
1587
|
// src/llm/anthropic/chat.ts
|
|
1432
1588
|
import Anthropic from "@anthropic-ai/sdk";
|
|
1589
|
+
import { createHash } from "crypto";
|
|
1590
|
+
|
|
1591
|
+
// src/llm/provider-log.ts
|
|
1592
|
+
import { promises as fs } from "fs";
|
|
1593
|
+
import path from "path";
|
|
1594
|
+
var envTruthy = (value) => {
|
|
1595
|
+
if (!value) return false;
|
|
1596
|
+
const normalized = value.trim().toLowerCase();
|
|
1597
|
+
return normalized === "1" || normalized === "true";
|
|
1598
|
+
};
|
|
1599
|
+
var getProviderLogSettings = () => {
|
|
1600
|
+
const enabled = envTruthy(process.env.CODELIA_PROVIDER_LOG);
|
|
1601
|
+
const dumpDirEnv = process.env.CODELIA_PROVIDER_LOG_DIR?.trim();
|
|
1602
|
+
const dumpDir = enabled ? dumpDirEnv && dumpDirEnv.length > 0 ? dumpDirEnv : path.resolve(process.cwd(), "tmp") : void 0;
|
|
1603
|
+
return { enabled, dumpDir };
|
|
1604
|
+
};
|
|
1605
|
+
var safeJsonStringify = (value, space) => {
|
|
1606
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
1607
|
+
return JSON.stringify(
|
|
1608
|
+
value,
|
|
1609
|
+
(_key, currentValue) => {
|
|
1610
|
+
if (typeof currentValue === "bigint") {
|
|
1611
|
+
return currentValue.toString();
|
|
1612
|
+
}
|
|
1613
|
+
if (typeof currentValue === "object" && currentValue !== null) {
|
|
1614
|
+
if (seen.has(currentValue)) {
|
|
1615
|
+
return "[Circular]";
|
|
1616
|
+
}
|
|
1617
|
+
seen.add(currentValue);
|
|
1618
|
+
}
|
|
1619
|
+
return currentValue;
|
|
1620
|
+
},
|
|
1621
|
+
space
|
|
1622
|
+
) ?? "null";
|
|
1623
|
+
};
|
|
1624
|
+
var sharedPrefixChars = (a, b) => {
|
|
1625
|
+
const min = Math.min(a.length, b.length);
|
|
1626
|
+
let index = 0;
|
|
1627
|
+
while (index < min && a.charCodeAt(index) === b.charCodeAt(index)) {
|
|
1628
|
+
index += 1;
|
|
1629
|
+
}
|
|
1630
|
+
return index;
|
|
1631
|
+
};
|
|
1632
|
+
var writeProviderLogDump = async (settings, provider, seq, direction, payload) => {
|
|
1633
|
+
if (!settings.dumpDir) {
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
await fs.mkdir(settings.dumpDir, { recursive: true });
|
|
1637
|
+
const iso = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
1638
|
+
const fileName = `${iso}_${process.pid}_${provider}_${seq}_${direction}.json`;
|
|
1639
|
+
const filePath = path.resolve(settings.dumpDir, fileName);
|
|
1640
|
+
const prettyPayload = safeJsonStringify(payload, 2);
|
|
1641
|
+
await fs.writeFile(filePath, `${prettyPayload}
|
|
1642
|
+
`, "utf8");
|
|
1643
|
+
};
|
|
1644
|
+
|
|
1645
|
+
// src/types/llm/guards.ts
|
|
1646
|
+
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
1647
|
+
function isTextPart(value) {
|
|
1648
|
+
if (!value || typeof value !== "object") return false;
|
|
1649
|
+
const v = value;
|
|
1650
|
+
return v.type === "text" && typeof v.text === "string";
|
|
1651
|
+
}
|
|
1652
|
+
function isImagePart(value) {
|
|
1653
|
+
if (!value || typeof value !== "object") return false;
|
|
1654
|
+
const v = value;
|
|
1655
|
+
if (v.type !== "image_url") return false;
|
|
1656
|
+
if (!v.image_url || typeof v.image_url !== "object") return false;
|
|
1657
|
+
const url = v.image_url.url;
|
|
1658
|
+
return typeof url === "string";
|
|
1659
|
+
}
|
|
1660
|
+
function isDocumentPart(value) {
|
|
1661
|
+
if (!value || typeof value !== "object") return false;
|
|
1662
|
+
const v = value;
|
|
1663
|
+
if (v.type !== "document") return false;
|
|
1664
|
+
if (!v.source || typeof v.source !== "object") return false;
|
|
1665
|
+
const source = v.source;
|
|
1666
|
+
return typeof source.data === "string" && source.media_type === "application/pdf";
|
|
1667
|
+
}
|
|
1668
|
+
function isOtherPart(value) {
|
|
1669
|
+
if (!value || typeof value !== "object") return false;
|
|
1670
|
+
const v = value;
|
|
1671
|
+
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
1672
|
+
}
|
|
1673
|
+
function isContentPart(value) {
|
|
1674
|
+
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
1675
|
+
}
|
|
1676
|
+
function isToolResult(value) {
|
|
1677
|
+
if (!value || typeof value !== "object") return false;
|
|
1678
|
+
const v = value;
|
|
1679
|
+
if (!TOOL_RESULT_TYPES.has(String(v.type))) return false;
|
|
1680
|
+
if (v.type === "text")
|
|
1681
|
+
return typeof value.text === "string";
|
|
1682
|
+
if (v.type === "json") return "value" in value;
|
|
1683
|
+
if (v.type === "parts") {
|
|
1684
|
+
const parts = value.parts;
|
|
1685
|
+
return Array.isArray(parts) && parts.every(isContentPart);
|
|
1686
|
+
}
|
|
1687
|
+
return false;
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
// src/types/llm/tools.ts
|
|
1691
|
+
var isHostedSearchToolDefinition = (value) => value.type === "hosted_search";
|
|
1692
|
+
var isFunctionToolDefinition = (value) => value.type !== "hosted_search";
|
|
1433
1693
|
|
|
1434
1694
|
// src/llm/anthropic/serializer.ts
|
|
1435
1695
|
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
@@ -1557,11 +1817,24 @@ var toToolResultBlock = (message) => {
|
|
|
1557
1817
|
};
|
|
1558
1818
|
var toAnthropicTools = (tools) => {
|
|
1559
1819
|
if (!tools || tools.length === 0) return void 0;
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1820
|
+
const mapped = [];
|
|
1821
|
+
for (const tool of tools) {
|
|
1822
|
+
if (isFunctionToolDefinition(tool)) {
|
|
1823
|
+
mapped.push({
|
|
1824
|
+
name: tool.name,
|
|
1825
|
+
description: tool.description,
|
|
1826
|
+
input_schema: tool.parameters
|
|
1827
|
+
});
|
|
1828
|
+
continue;
|
|
1829
|
+
}
|
|
1830
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
1831
|
+
const hosted = toAnthropicHostedSearchTool(tool);
|
|
1832
|
+
if (hosted) {
|
|
1833
|
+
mapped.push(hosted);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
return mapped.length ? mapped : void 0;
|
|
1565
1838
|
};
|
|
1566
1839
|
var toAnthropicToolChoice = (choice) => {
|
|
1567
1840
|
if (!choice) return void 0;
|
|
@@ -1704,6 +1977,26 @@ var toChatInvokeCompletion = (response) => {
|
|
|
1704
1977
|
}
|
|
1705
1978
|
};
|
|
1706
1979
|
};
|
|
1980
|
+
var toAnthropicHostedSearchTool = (tool) => {
|
|
1981
|
+
if (tool.provider && tool.provider !== "anthropic") {
|
|
1982
|
+
return null;
|
|
1983
|
+
}
|
|
1984
|
+
const userLocation = tool.user_location ? {
|
|
1985
|
+
type: "approximate",
|
|
1986
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
1987
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
1988
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
1989
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
1990
|
+
} : void 0;
|
|
1991
|
+
return {
|
|
1992
|
+
type: "web_search_20250305",
|
|
1993
|
+
name: "web_search",
|
|
1994
|
+
...tool.allowed_domains?.length ? { allowed_domains: tool.allowed_domains } : {},
|
|
1995
|
+
...tool.blocked_domains?.length ? { blocked_domains: tool.blocked_domains } : {},
|
|
1996
|
+
...typeof tool.max_uses === "number" ? { max_uses: tool.max_uses } : {},
|
|
1997
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
1998
|
+
};
|
|
1999
|
+
};
|
|
1707
2000
|
|
|
1708
2001
|
// src/llm/anthropic/chat.ts
|
|
1709
2002
|
var PROVIDER_NAME = "anthropic";
|
|
@@ -1714,12 +2007,14 @@ var ChatAnthropic = class {
|
|
|
1714
2007
|
model;
|
|
1715
2008
|
client;
|
|
1716
2009
|
defaultMaxTokens;
|
|
2010
|
+
debugInvokeSeq = 0;
|
|
2011
|
+
lastDebugRequestPayload = null;
|
|
1717
2012
|
constructor(options = {}) {
|
|
1718
2013
|
this.client = options.client ?? new Anthropic(options.clientOptions);
|
|
1719
2014
|
this.model = options.model ?? DEFAULT_MODEL;
|
|
1720
2015
|
this.defaultMaxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
1721
2016
|
}
|
|
1722
|
-
async ainvoke(input,
|
|
2017
|
+
async ainvoke(input, _context) {
|
|
1723
2018
|
const {
|
|
1724
2019
|
messages,
|
|
1725
2020
|
tools: toolDefs,
|
|
@@ -1742,24 +2037,102 @@ var ChatAnthropic = class {
|
|
|
1742
2037
|
...tools ? { tools } : {},
|
|
1743
2038
|
...tool_choice ? { tool_choice } : {}
|
|
1744
2039
|
};
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
}
|
|
2040
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
2041
|
+
await this.debugRequestIfEnabled(request, debugSeq);
|
|
1748
2042
|
const response = await this.client.messages.create(
|
|
1749
2043
|
request,
|
|
1750
2044
|
signal ? {
|
|
1751
2045
|
signal
|
|
1752
2046
|
} : void 0
|
|
1753
2047
|
);
|
|
1754
|
-
|
|
1755
|
-
console.debug(response);
|
|
1756
|
-
}
|
|
2048
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
1757
2049
|
return toChatInvokeCompletion(response);
|
|
1758
2050
|
}
|
|
2051
|
+
nextDebugInvokeSeq() {
|
|
2052
|
+
const seq = this.debugInvokeSeq + 1;
|
|
2053
|
+
this.debugInvokeSeq = seq;
|
|
2054
|
+
return seq;
|
|
2055
|
+
}
|
|
2056
|
+
async debugRequestIfEnabled(request, seq) {
|
|
2057
|
+
const settings = getProviderLogSettings();
|
|
2058
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2059
|
+
return;
|
|
2060
|
+
}
|
|
2061
|
+
const payload = safeJsonStringify(request);
|
|
2062
|
+
const hash = createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2063
|
+
const toolsHash = createHash("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
2064
|
+
const systemHash = createHash("sha256").update(safeJsonStringify(request.system ?? "")).digest("hex").slice(0, 12);
|
|
2065
|
+
const previous = this.lastDebugRequestPayload;
|
|
2066
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2067
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
2068
|
+
if (settings.enabled) {
|
|
2069
|
+
console.error(
|
|
2070
|
+
`[anthropic.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} system_sha=${systemHash}`
|
|
2071
|
+
);
|
|
2072
|
+
}
|
|
2073
|
+
if (settings.dumpDir) {
|
|
2074
|
+
try {
|
|
2075
|
+
await writeProviderLogDump(
|
|
2076
|
+
settings,
|
|
2077
|
+
PROVIDER_NAME,
|
|
2078
|
+
seq,
|
|
2079
|
+
"request",
|
|
2080
|
+
request
|
|
2081
|
+
);
|
|
2082
|
+
} catch (error) {
|
|
2083
|
+
if (settings.enabled) {
|
|
2084
|
+
console.error(
|
|
2085
|
+
`[anthropic.request] dump_failed seq=${seq} error=${String(error)}`
|
|
2086
|
+
);
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
this.lastDebugRequestPayload = payload;
|
|
2091
|
+
}
|
|
2092
|
+
async debugResponseIfEnabled(response, seq) {
|
|
2093
|
+
const settings = getProviderLogSettings();
|
|
2094
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
2097
|
+
if (settings.enabled) {
|
|
2098
|
+
const usage = response.usage;
|
|
2099
|
+
const inputTokens = usage?.input_tokens ?? 0;
|
|
2100
|
+
const outputTokens = usage?.output_tokens ?? 0;
|
|
2101
|
+
const cachedRead = usage?.cache_read_input_tokens ?? 0;
|
|
2102
|
+
const cachedCreate = usage?.cache_creation_input_tokens ?? 0;
|
|
2103
|
+
const blocks = Array.isArray(response.content) ? response.content : [];
|
|
2104
|
+
const blockKinds = /* @__PURE__ */ new Set();
|
|
2105
|
+
for (const block of blocks) {
|
|
2106
|
+
const kind = block && typeof block === "object" && "type" in block ? String(block.type ?? "unknown") : "unknown";
|
|
2107
|
+
blockKinds.add(kind);
|
|
2108
|
+
}
|
|
2109
|
+
console.error(
|
|
2110
|
+
`[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}`
|
|
2111
|
+
);
|
|
2112
|
+
}
|
|
2113
|
+
if (settings.dumpDir) {
|
|
2114
|
+
try {
|
|
2115
|
+
await writeProviderLogDump(
|
|
2116
|
+
settings,
|
|
2117
|
+
PROVIDER_NAME,
|
|
2118
|
+
seq,
|
|
2119
|
+
"response",
|
|
2120
|
+
response
|
|
2121
|
+
);
|
|
2122
|
+
} catch (error) {
|
|
2123
|
+
if (settings.enabled) {
|
|
2124
|
+
console.error(
|
|
2125
|
+
`[anthropic.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2126
|
+
);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
1759
2131
|
};
|
|
1760
2132
|
|
|
1761
2133
|
// src/llm/openai/chat.ts
|
|
1762
2134
|
import OpenAI from "openai";
|
|
2135
|
+
import { createHash as createHash2 } from "crypto";
|
|
1763
2136
|
|
|
1764
2137
|
// src/llm/openai/response-utils.ts
|
|
1765
2138
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -1887,6 +2260,23 @@ var isOpenAIAssistantInputContent = (value) => {
|
|
|
1887
2260
|
}
|
|
1888
2261
|
return false;
|
|
1889
2262
|
};
|
|
2263
|
+
var isReplayableOpenAIHistoryItem = (value) => {
|
|
2264
|
+
if (!value || typeof value !== "object") {
|
|
2265
|
+
return false;
|
|
2266
|
+
}
|
|
2267
|
+
const type = value.type;
|
|
2268
|
+
if (type === "reasoning") {
|
|
2269
|
+
return typeof value.id === "string";
|
|
2270
|
+
}
|
|
2271
|
+
return type === "web_search_call";
|
|
2272
|
+
};
|
|
2273
|
+
var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
2274
|
+
if (!value || typeof value !== "object") {
|
|
2275
|
+
return false;
|
|
2276
|
+
}
|
|
2277
|
+
const record = value;
|
|
2278
|
+
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
2279
|
+
};
|
|
1890
2280
|
var toAssistantInputContent = (part) => {
|
|
1891
2281
|
switch (part.type) {
|
|
1892
2282
|
case "text":
|
|
@@ -1928,6 +2318,21 @@ var extractReasoningText = (item) => {
|
|
|
1928
2318
|
).filter((text) => text.length > 0).join("\n");
|
|
1929
2319
|
return contentText;
|
|
1930
2320
|
};
|
|
2321
|
+
var extractWebSearchSummary = (item) => {
|
|
2322
|
+
const parts = [`WebSearch status=${item.status}`];
|
|
2323
|
+
const record = item;
|
|
2324
|
+
const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
|
|
2325
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
2326
|
+
) : [];
|
|
2327
|
+
if (queries.length) {
|
|
2328
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
2329
|
+
}
|
|
2330
|
+
const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
|
|
2331
|
+
if (sources.length) {
|
|
2332
|
+
parts.push(`sources=${sources.length}`);
|
|
2333
|
+
}
|
|
2334
|
+
return parts.join(" | ");
|
|
2335
|
+
};
|
|
1931
2336
|
var toMessageSequence = (response) => {
|
|
1932
2337
|
const messages = [];
|
|
1933
2338
|
for (const item of response.output) {
|
|
@@ -1961,6 +2366,14 @@ var toMessageSequence = (response) => {
|
|
|
1961
2366
|
});
|
|
1962
2367
|
break;
|
|
1963
2368
|
}
|
|
2369
|
+
case "web_search_call": {
|
|
2370
|
+
messages.push({
|
|
2371
|
+
role: "reasoning",
|
|
2372
|
+
content: extractWebSearchSummary(item),
|
|
2373
|
+
raw_item: item
|
|
2374
|
+
});
|
|
2375
|
+
break;
|
|
2376
|
+
}
|
|
1964
2377
|
default: {
|
|
1965
2378
|
messages.push({
|
|
1966
2379
|
role: "assistant",
|
|
@@ -2024,6 +2437,9 @@ function toResponsesInput(messages) {
|
|
|
2024
2437
|
continue;
|
|
2025
2438
|
}
|
|
2026
2439
|
if (message.role === "reasoning") {
|
|
2440
|
+
if (isReplayableOpenAIHistoryItem(message.raw_item)) {
|
|
2441
|
+
items.push(message.raw_item);
|
|
2442
|
+
}
|
|
2027
2443
|
continue;
|
|
2028
2444
|
}
|
|
2029
2445
|
if (message.role === "assistant") {
|
|
@@ -2045,13 +2461,26 @@ function toResponsesTools(tools) {
|
|
|
2045
2461
|
if (!tools || tools.length === 0) {
|
|
2046
2462
|
return void 0;
|
|
2047
2463
|
}
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2464
|
+
const mapped = [];
|
|
2465
|
+
for (const tool of tools) {
|
|
2466
|
+
if (isFunctionToolDefinition(tool)) {
|
|
2467
|
+
mapped.push({
|
|
2468
|
+
type: "function",
|
|
2469
|
+
name: tool.name,
|
|
2470
|
+
description: tool.description,
|
|
2471
|
+
parameters: tool.parameters,
|
|
2472
|
+
strict: tool.strict ?? false
|
|
2473
|
+
});
|
|
2474
|
+
continue;
|
|
2475
|
+
}
|
|
2476
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
2477
|
+
const hosted = toOpenAiHostedSearchTool(tool);
|
|
2478
|
+
if (hosted) {
|
|
2479
|
+
mapped.push(hosted);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
return mapped.length ? mapped : void 0;
|
|
2055
2484
|
}
|
|
2056
2485
|
function toResponsesToolChoice(choice) {
|
|
2057
2486
|
if (!choice) {
|
|
@@ -2104,6 +2533,10 @@ function toAssistantMessageItem(message) {
|
|
|
2104
2533
|
};
|
|
2105
2534
|
}
|
|
2106
2535
|
function toFunctionCallItem(call) {
|
|
2536
|
+
if (isReplayableOpenAIFunctionCallItem(call.provider_meta)) {
|
|
2537
|
+
const { parsed_arguments: _parsed, ...rest } = call.provider_meta;
|
|
2538
|
+
return rest;
|
|
2539
|
+
}
|
|
2107
2540
|
return {
|
|
2108
2541
|
type: "function_call",
|
|
2109
2542
|
call_id: call.id,
|
|
@@ -2118,25 +2551,52 @@ function toFunctionCallOutputItem(message) {
|
|
|
2118
2551
|
output: toFunctionCallOutput(message.content)
|
|
2119
2552
|
};
|
|
2120
2553
|
}
|
|
2554
|
+
function toOpenAiHostedSearchTool(tool) {
|
|
2555
|
+
if (tool.provider && tool.provider !== "openai" && tool.provider !== "openrouter") {
|
|
2556
|
+
return null;
|
|
2557
|
+
}
|
|
2558
|
+
const userLocation = tool.user_location ? {
|
|
2559
|
+
type: "approximate",
|
|
2560
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
2561
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
2562
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
2563
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
2564
|
+
} : void 0;
|
|
2565
|
+
return {
|
|
2566
|
+
type: "web_search",
|
|
2567
|
+
...tool.search_context_size ? { search_context_size: tool.search_context_size } : {},
|
|
2568
|
+
...tool.allowed_domains?.length ? {
|
|
2569
|
+
filters: {
|
|
2570
|
+
allowed_domains: tool.allowed_domains
|
|
2571
|
+
}
|
|
2572
|
+
} : {},
|
|
2573
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
2574
|
+
};
|
|
2575
|
+
}
|
|
2121
2576
|
|
|
2122
2577
|
// src/llm/openai/chat.ts
|
|
2123
2578
|
var PROVIDER_NAME2 = "openai";
|
|
2124
2579
|
var DEFAULT_MODEL2 = OPENAI_DEFAULT_MODEL;
|
|
2125
2580
|
var DEFAULT_REASONING_EFFORT = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
2126
2581
|
var DEFAULT_REASONING_SUMMARY = "auto";
|
|
2582
|
+
var getSessionIdHeaderValue = (promptCacheKey) => {
|
|
2583
|
+
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
2584
|
+
};
|
|
2127
2585
|
var ChatOpenAI = class {
|
|
2128
2586
|
provider = PROVIDER_NAME2;
|
|
2129
2587
|
model;
|
|
2130
2588
|
client;
|
|
2131
2589
|
defaultReasoningEffort;
|
|
2132
2590
|
defaultTextVerbosity;
|
|
2591
|
+
debugInvokeSeq = 0;
|
|
2592
|
+
lastDebugRequestPayload = null;
|
|
2133
2593
|
constructor(options = {}) {
|
|
2134
2594
|
this.client = options.client ?? new OpenAI(options.clientOptions);
|
|
2135
2595
|
this.model = options.model ?? DEFAULT_MODEL2;
|
|
2136
2596
|
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT;
|
|
2137
2597
|
this.defaultTextVerbosity = options.textVerbosity;
|
|
2138
2598
|
}
|
|
2139
|
-
async ainvoke(input,
|
|
2599
|
+
async ainvoke(input, context) {
|
|
2140
2600
|
const {
|
|
2141
2601
|
messages,
|
|
2142
2602
|
tools: toolDefs,
|
|
@@ -2163,7 +2623,16 @@ var ChatOpenAI = class {
|
|
|
2163
2623
|
if (instructions) {
|
|
2164
2624
|
request.instructions = instructions;
|
|
2165
2625
|
}
|
|
2166
|
-
|
|
2626
|
+
const hasWebSearchTool = tools?.some(
|
|
2627
|
+
(tool) => tool.type === "web_search" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11"
|
|
2628
|
+
);
|
|
2629
|
+
const includeSet = new Set(request.include ?? []);
|
|
2630
|
+
includeSet.add("reasoning.encrypted_content");
|
|
2631
|
+
if (hasWebSearchTool) {
|
|
2632
|
+
includeSet.add("web_search_call.action.sources");
|
|
2633
|
+
includeSet.add("web_search_call.results");
|
|
2634
|
+
}
|
|
2635
|
+
request.include = Array.from(includeSet);
|
|
2167
2636
|
const effort = reasoningEffort ?? this.defaultReasoningEffort;
|
|
2168
2637
|
request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY };
|
|
2169
2638
|
const verbosity = textVerbosity ?? this.defaultTextVerbosity;
|
|
@@ -2173,90 +2642,128 @@ var ChatOpenAI = class {
|
|
|
2173
2642
|
verbosity
|
|
2174
2643
|
};
|
|
2175
2644
|
}
|
|
2176
|
-
if (
|
|
2177
|
-
|
|
2645
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
2646
|
+
request.prompt_cache_key = context.sessionKey;
|
|
2178
2647
|
}
|
|
2648
|
+
const sessionIdHeader = getSessionIdHeaderValue(request.prompt_cache_key);
|
|
2649
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
2650
|
+
await this.debugRequestIfEnabled(request, debugSeq, sessionIdHeader);
|
|
2179
2651
|
const streamRequest = {
|
|
2180
2652
|
...request,
|
|
2181
2653
|
stream: true
|
|
2182
2654
|
};
|
|
2183
2655
|
const response = await this.client.responses.stream(
|
|
2184
2656
|
streamRequest,
|
|
2185
|
-
signal ? {
|
|
2186
|
-
signal
|
|
2657
|
+
signal || sessionIdHeader ? {
|
|
2658
|
+
...signal ? { signal } : {},
|
|
2659
|
+
...sessionIdHeader ? {
|
|
2660
|
+
headers: {
|
|
2661
|
+
session_id: sessionIdHeader
|
|
2662
|
+
}
|
|
2663
|
+
} : {}
|
|
2187
2664
|
} : void 0
|
|
2188
2665
|
).finalResponse();
|
|
2189
|
-
|
|
2190
|
-
console.debug(response);
|
|
2191
|
-
}
|
|
2666
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
2192
2667
|
return toChatInvokeCompletion2(response);
|
|
2193
2668
|
}
|
|
2669
|
+
nextDebugInvokeSeq() {
|
|
2670
|
+
const seq = this.debugInvokeSeq + 1;
|
|
2671
|
+
this.debugInvokeSeq = seq;
|
|
2672
|
+
return seq;
|
|
2673
|
+
}
|
|
2674
|
+
async debugRequestIfEnabled(request, seq, sessionIdHeader) {
|
|
2675
|
+
const settings = getProviderLogSettings();
|
|
2676
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2677
|
+
return;
|
|
2678
|
+
}
|
|
2679
|
+
const payload = safeJsonStringify(request);
|
|
2680
|
+
const hash = createHash2("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2681
|
+
const toolsHash = createHash2("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
2682
|
+
const instructionsHash = createHash2("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
2683
|
+
const previous = this.lastDebugRequestPayload;
|
|
2684
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
2685
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
2686
|
+
if (settings.enabled) {
|
|
2687
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash2("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
2688
|
+
console.error(
|
|
2689
|
+
`[openai.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
2690
|
+
);
|
|
2691
|
+
}
|
|
2692
|
+
if (settings.dumpDir) {
|
|
2693
|
+
try {
|
|
2694
|
+
await writeProviderLogDump(
|
|
2695
|
+
settings,
|
|
2696
|
+
PROVIDER_NAME2,
|
|
2697
|
+
seq,
|
|
2698
|
+
"request",
|
|
2699
|
+
request
|
|
2700
|
+
);
|
|
2701
|
+
} catch (error) {
|
|
2702
|
+
if (settings.enabled) {
|
|
2703
|
+
console.error(
|
|
2704
|
+
`[openai.request] dump_failed seq=${seq} error=${String(error)}`
|
|
2705
|
+
);
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
this.lastDebugRequestPayload = payload;
|
|
2710
|
+
}
|
|
2711
|
+
async debugResponseIfEnabled(response, seq) {
|
|
2712
|
+
const settings = getProviderLogSettings();
|
|
2713
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
2716
|
+
if (settings.enabled) {
|
|
2717
|
+
const usage = response.usage;
|
|
2718
|
+
const cachedInputTokens = usage?.input_tokens_details?.cached_tokens ?? 0;
|
|
2719
|
+
const outputItems = Array.isArray(response.output) ? response.output : [];
|
|
2720
|
+
const outputKinds = /* @__PURE__ */ new Set();
|
|
2721
|
+
for (const item of outputItems) {
|
|
2722
|
+
const kind = item && typeof item === "object" && "type" in item ? String(item.type ?? "unknown") : "unknown";
|
|
2723
|
+
outputKinds.add(kind);
|
|
2724
|
+
}
|
|
2725
|
+
const usageIn = usage?.input_tokens ?? 0;
|
|
2726
|
+
console.error(
|
|
2727
|
+
`[openai.response] seq=${seq} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
2728
|
+
);
|
|
2729
|
+
}
|
|
2730
|
+
if (settings.dumpDir) {
|
|
2731
|
+
try {
|
|
2732
|
+
await writeProviderLogDump(
|
|
2733
|
+
settings,
|
|
2734
|
+
PROVIDER_NAME2,
|
|
2735
|
+
seq,
|
|
2736
|
+
"response",
|
|
2737
|
+
response
|
|
2738
|
+
);
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
if (settings.enabled) {
|
|
2741
|
+
console.error(
|
|
2742
|
+
`[openai.response] dump_failed seq=${seq} error=${String(error)}`
|
|
2743
|
+
);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2194
2748
|
};
|
|
2195
2749
|
|
|
2196
2750
|
// src/prompts.ts
|
|
2197
|
-
import
|
|
2751
|
+
import path2 from "path";
|
|
2198
2752
|
import { fileURLToPath } from "url";
|
|
2199
2753
|
var resolvePromptPath = () => {
|
|
2200
2754
|
if (typeof __filename === "string") {
|
|
2201
|
-
return
|
|
2755
|
+
return path2.resolve(path2.dirname(__filename), "../prompts/system.md");
|
|
2202
2756
|
}
|
|
2203
2757
|
if (typeof import.meta !== "undefined" && import.meta.url) {
|
|
2204
2758
|
return fileURLToPath(new URL("../prompts/system.md", import.meta.url));
|
|
2205
2759
|
}
|
|
2206
|
-
return
|
|
2760
|
+
return path2.resolve("prompts/system.md");
|
|
2207
2761
|
};
|
|
2208
2762
|
var promptPath = resolvePromptPath();
|
|
2209
2763
|
var getDefaultSystemPromptPath = () => promptPath;
|
|
2210
2764
|
|
|
2211
2765
|
// src/tools/define.ts
|
|
2212
2766
|
import { toJSONSchema } from "zod";
|
|
2213
|
-
|
|
2214
|
-
// src/types/llm/guards.ts
|
|
2215
|
-
var TOOL_RESULT_TYPES = /* @__PURE__ */ new Set(["text", "parts", "json"]);
|
|
2216
|
-
function isTextPart(value) {
|
|
2217
|
-
if (!value || typeof value !== "object") return false;
|
|
2218
|
-
const v = value;
|
|
2219
|
-
return v.type === "text" && typeof v.text === "string";
|
|
2220
|
-
}
|
|
2221
|
-
function isImagePart(value) {
|
|
2222
|
-
if (!value || typeof value !== "object") return false;
|
|
2223
|
-
const v = value;
|
|
2224
|
-
if (v.type !== "image_url") return false;
|
|
2225
|
-
if (!v.image_url || typeof v.image_url !== "object") return false;
|
|
2226
|
-
const url = v.image_url.url;
|
|
2227
|
-
return typeof url === "string";
|
|
2228
|
-
}
|
|
2229
|
-
function isDocumentPart(value) {
|
|
2230
|
-
if (!value || typeof value !== "object") return false;
|
|
2231
|
-
const v = value;
|
|
2232
|
-
if (v.type !== "document") return false;
|
|
2233
|
-
if (!v.source || typeof v.source !== "object") return false;
|
|
2234
|
-
const source = v.source;
|
|
2235
|
-
return typeof source.data === "string" && source.media_type === "application/pdf";
|
|
2236
|
-
}
|
|
2237
|
-
function isOtherPart(value) {
|
|
2238
|
-
if (!value || typeof value !== "object") return false;
|
|
2239
|
-
const v = value;
|
|
2240
|
-
return v.type === "other" && typeof v.provider === "string" && typeof v.kind === "string";
|
|
2241
|
-
}
|
|
2242
|
-
function isContentPart(value) {
|
|
2243
|
-
return isTextPart(value) || isImagePart(value) || isDocumentPart(value) || isOtherPart(value);
|
|
2244
|
-
}
|
|
2245
|
-
function isToolResult(value) {
|
|
2246
|
-
if (!value || typeof value !== "object") return false;
|
|
2247
|
-
const v = value;
|
|
2248
|
-
if (!TOOL_RESULT_TYPES.has(String(v.type))) return false;
|
|
2249
|
-
if (v.type === "text")
|
|
2250
|
-
return typeof value.text === "string";
|
|
2251
|
-
if (v.type === "json") return "value" in value;
|
|
2252
|
-
if (v.type === "parts") {
|
|
2253
|
-
const parts = value.parts;
|
|
2254
|
-
return Array.isArray(parts) && parts.every(isContentPart);
|
|
2255
|
-
}
|
|
2256
|
-
return false;
|
|
2257
|
-
}
|
|
2258
|
-
|
|
2259
|
-
// src/tools/define.ts
|
|
2260
2767
|
var mapSchema = (schema, transform) => {
|
|
2261
2768
|
if (!schema || typeof schema !== "object") return schema;
|
|
2262
2769
|
const next = transform({ ...schema });
|