@codelia/core 0.1.17 → 0.1.19
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 +773 -43
- package/dist/index.d.cts +39 -9
- package/dist/index.d.ts +39 -9
- package/dist/index.js +772 -43
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -35,6 +35,7 @@ __export(index_exports, {
|
|
|
35
35
|
Agent: () => Agent,
|
|
36
36
|
ChatAnthropic: () => ChatAnthropic,
|
|
37
37
|
ChatOpenAI: () => ChatOpenAI,
|
|
38
|
+
ChatOpenRouter: () => ChatOpenRouter,
|
|
38
39
|
DEFAULT_MODEL_REGISTRY: () => DEFAULT_MODEL_REGISTRY,
|
|
39
40
|
GOOGLE_MODELS: () => GOOGLE_MODELS,
|
|
40
41
|
OPENAI_DEFAULT_MODEL: () => OPENAI_DEFAULT_MODEL,
|
|
@@ -233,7 +234,7 @@ var MessageHistoryAdapter = class {
|
|
|
233
234
|
};
|
|
234
235
|
|
|
235
236
|
// src/llm/openai/history.ts
|
|
236
|
-
var
|
|
237
|
+
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
237
238
|
};
|
|
238
239
|
|
|
239
240
|
// src/models/anthropic.ts
|
|
@@ -293,6 +294,7 @@ function createModelRegistry(specs) {
|
|
|
293
294
|
aliasesByProvider: {
|
|
294
295
|
openai: {},
|
|
295
296
|
anthropic: {},
|
|
297
|
+
openrouter: {},
|
|
296
298
|
google: {}
|
|
297
299
|
}
|
|
298
300
|
};
|
|
@@ -340,6 +342,7 @@ function cloneAliases(aliasesByProvider) {
|
|
|
340
342
|
return {
|
|
341
343
|
openai: { ...aliasesByProvider.openai },
|
|
342
344
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
345
|
+
openrouter: { ...aliasesByProvider.openrouter },
|
|
343
346
|
google: { ...aliasesByProvider.google }
|
|
344
347
|
};
|
|
345
348
|
}
|
|
@@ -349,7 +352,7 @@ function applyModelMetadata(registry, index) {
|
|
|
349
352
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
350
353
|
};
|
|
351
354
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
352
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "google") {
|
|
355
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
|
|
353
356
|
continue;
|
|
354
357
|
}
|
|
355
358
|
const provider = providerId;
|
|
@@ -590,7 +593,11 @@ var CompactionService = class _CompactionService {
|
|
|
590
593
|
}
|
|
591
594
|
const qualified = parseQualifiedModelId(modelId);
|
|
592
595
|
if (qualified) {
|
|
593
|
-
const qualifiedDirect = resolveModel(
|
|
596
|
+
const qualifiedDirect = resolveModel(
|
|
597
|
+
this.modelRegistry,
|
|
598
|
+
qualified.modelId,
|
|
599
|
+
qualified.provider
|
|
600
|
+
) ?? resolveModel(
|
|
594
601
|
this.modelRegistry,
|
|
595
602
|
`${qualified.provider}/${qualified.modelId}`,
|
|
596
603
|
qualified.provider
|
|
@@ -643,7 +650,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
643
650
|
if (!rest) {
|
|
644
651
|
return null;
|
|
645
652
|
}
|
|
646
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
653
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
647
654
|
return null;
|
|
648
655
|
}
|
|
649
656
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -826,7 +833,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
826
833
|
if (!rest) {
|
|
827
834
|
return null;
|
|
828
835
|
}
|
|
829
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
836
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
830
837
|
return null;
|
|
831
838
|
}
|
|
832
839
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -1032,6 +1039,7 @@ var throwIfAborted = (signal) => {
|
|
|
1032
1039
|
throw createAbortError();
|
|
1033
1040
|
}
|
|
1034
1041
|
};
|
|
1042
|
+
var isResponsesHistoryProvider = (provider) => provider === "openai" || provider === "openrouter";
|
|
1035
1043
|
var Agent = class {
|
|
1036
1044
|
llm;
|
|
1037
1045
|
tools;
|
|
@@ -1050,7 +1058,7 @@ var Agent = class {
|
|
|
1050
1058
|
usageService;
|
|
1051
1059
|
constructor(options) {
|
|
1052
1060
|
this.llm = options.llm;
|
|
1053
|
-
this.history = this.llm.provider
|
|
1061
|
+
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
1054
1062
|
this.tools = options.tools;
|
|
1055
1063
|
this.hostedTools = options.hostedTools ?? [];
|
|
1056
1064
|
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
@@ -1260,10 +1268,7 @@ var Agent = class {
|
|
|
1260
1268
|
await this.trimToolOutputs();
|
|
1261
1269
|
throwIfAborted(signal);
|
|
1262
1270
|
const invokeInput = this.history.prepareInvokeInput({
|
|
1263
|
-
tools: [
|
|
1264
|
-
...this.tools.map((t) => t.definition),
|
|
1265
|
-
...this.hostedTools
|
|
1266
|
-
],
|
|
1271
|
+
tools: [...this.tools.map((t) => t.definition), ...this.hostedTools],
|
|
1267
1272
|
toolChoice: this.toolChoice
|
|
1268
1273
|
});
|
|
1269
1274
|
const invokeContext = this.buildInvokeContext(session);
|
|
@@ -1278,12 +1283,7 @@ var Agent = class {
|
|
|
1278
1283
|
this.recordLlmResponse(session, seq, response);
|
|
1279
1284
|
this.usageService.updateUsageSummary(response.usage);
|
|
1280
1285
|
this.history.commitModelResponse(response);
|
|
1281
|
-
const {
|
|
1282
|
-
reasoningTexts,
|
|
1283
|
-
assistantTexts,
|
|
1284
|
-
toolCalls,
|
|
1285
|
-
hostedToolCalls
|
|
1286
|
-
} = collectModelOutput(response.messages);
|
|
1286
|
+
const { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls } = collectModelOutput(response.messages);
|
|
1287
1287
|
for (const reasoningText of reasoningTexts) {
|
|
1288
1288
|
const reasoningEvent = {
|
|
1289
1289
|
type: "reasoning",
|
|
@@ -1634,15 +1634,15 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1634
1634
|
if (!rest) {
|
|
1635
1635
|
return null;
|
|
1636
1636
|
}
|
|
1637
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
1637
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1638
1638
|
return null;
|
|
1639
1639
|
}
|
|
1640
1640
|
return { provider: providerRaw, modelId: rest };
|
|
1641
1641
|
};
|
|
1642
1642
|
|
|
1643
1643
|
// src/llm/anthropic/chat.ts
|
|
1644
|
-
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
1645
1644
|
var import_node_crypto = require("crypto");
|
|
1645
|
+
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
1646
1646
|
|
|
1647
1647
|
// src/llm/provider-log.ts
|
|
1648
1648
|
var import_node_fs = require("fs");
|
|
@@ -1899,12 +1899,106 @@ var toAnthropicToolChoice = (choice) => {
|
|
|
1899
1899
|
if (choice === "none") return void 0;
|
|
1900
1900
|
return { type: "tool", name: choice };
|
|
1901
1901
|
};
|
|
1902
|
+
var mergePendingToolResults = (pendingToolResults, output) => {
|
|
1903
|
+
if (pendingToolResults.length === 0) return;
|
|
1904
|
+
output.push({
|
|
1905
|
+
role: "user",
|
|
1906
|
+
content: [...pendingToolResults]
|
|
1907
|
+
});
|
|
1908
|
+
pendingToolResults.length = 0;
|
|
1909
|
+
};
|
|
1910
|
+
var isToolUseBlock = (block) => isRecord(block) && block.type === "tool_use";
|
|
1911
|
+
var isToolResultBlock = (block) => isRecord(block) && block.type === "tool_result";
|
|
1912
|
+
var isAssistantWithToolUseBlocks = (message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => isToolUseBlock(block));
|
|
1913
|
+
var coalesceConsecutiveAssistantToolUseMessages = (messages) => {
|
|
1914
|
+
const normalized = [];
|
|
1915
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
1916
|
+
const current = messages[index];
|
|
1917
|
+
if (!isAssistantWithToolUseBlocks(current)) {
|
|
1918
|
+
normalized.push(current);
|
|
1919
|
+
continue;
|
|
1920
|
+
}
|
|
1921
|
+
const mergedBlocks = [...current.content];
|
|
1922
|
+
let nextIndex = index + 1;
|
|
1923
|
+
while (nextIndex < messages.length) {
|
|
1924
|
+
const candidate = messages[nextIndex];
|
|
1925
|
+
if (!isAssistantWithToolUseBlocks(candidate)) break;
|
|
1926
|
+
mergedBlocks.push(...candidate.content);
|
|
1927
|
+
nextIndex += 1;
|
|
1928
|
+
}
|
|
1929
|
+
normalized.push({
|
|
1930
|
+
role: "assistant",
|
|
1931
|
+
content: ensureMessageBlocks(mergedBlocks)
|
|
1932
|
+
});
|
|
1933
|
+
index = nextIndex - 1;
|
|
1934
|
+
}
|
|
1935
|
+
return normalized;
|
|
1936
|
+
};
|
|
1937
|
+
var dropOrphanToolUseBlocks = (messages) => {
|
|
1938
|
+
const normalizedMessages = coalesceConsecutiveAssistantToolUseMessages(messages);
|
|
1939
|
+
const sanitized = [];
|
|
1940
|
+
for (let index = 0; index < normalizedMessages.length; index += 1) {
|
|
1941
|
+
const current = normalizedMessages[index];
|
|
1942
|
+
if (!Array.isArray(current.content) || current.role !== "assistant") {
|
|
1943
|
+
sanitized.push(current);
|
|
1944
|
+
continue;
|
|
1945
|
+
}
|
|
1946
|
+
const toolUseIds = /* @__PURE__ */ new Set();
|
|
1947
|
+
for (const block of current.content) {
|
|
1948
|
+
if (isToolUseBlock(block)) {
|
|
1949
|
+
toolUseIds.add(block.id);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
if (toolUseIds.size === 0) {
|
|
1953
|
+
sanitized.push(current);
|
|
1954
|
+
continue;
|
|
1955
|
+
}
|
|
1956
|
+
const next = normalizedMessages[index + 1];
|
|
1957
|
+
if (!next || next.role !== "user" || !Array.isArray(next.content)) {
|
|
1958
|
+
const filtered = current.content.filter(
|
|
1959
|
+
(block) => !isToolUseBlock(block)
|
|
1960
|
+
);
|
|
1961
|
+
if (filtered.length > 0) {
|
|
1962
|
+
sanitized.push({ ...current, content: filtered });
|
|
1963
|
+
}
|
|
1964
|
+
continue;
|
|
1965
|
+
}
|
|
1966
|
+
const toolResultIds = /* @__PURE__ */ new Set();
|
|
1967
|
+
for (const block of next.content) {
|
|
1968
|
+
if (isToolResultBlock(block)) {
|
|
1969
|
+
toolResultIds.add(block.tool_use_id);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
const allowedIds = /* @__PURE__ */ new Set();
|
|
1973
|
+
for (const id of toolUseIds) {
|
|
1974
|
+
if (toolResultIds.has(id)) {
|
|
1975
|
+
allowedIds.add(id);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
const filteredCurrent = current.content.filter(
|
|
1979
|
+
(block) => !isToolUseBlock(block) || allowedIds.has(block.id)
|
|
1980
|
+
);
|
|
1981
|
+
if (filteredCurrent.length > 0) {
|
|
1982
|
+
sanitized.push({ ...current, content: filteredCurrent });
|
|
1983
|
+
}
|
|
1984
|
+
const filteredNext = next.content.filter(
|
|
1985
|
+
(block) => !isToolResultBlock(block) || allowedIds.has(block.tool_use_id)
|
|
1986
|
+
);
|
|
1987
|
+
if (filteredNext.length > 0) {
|
|
1988
|
+
sanitized.push({ ...next, content: filteredNext });
|
|
1989
|
+
}
|
|
1990
|
+
index += 1;
|
|
1991
|
+
}
|
|
1992
|
+
return sanitized;
|
|
1993
|
+
};
|
|
1902
1994
|
var toAnthropicMessages = (messages) => {
|
|
1903
1995
|
const systemParts = [];
|
|
1904
1996
|
const output = [];
|
|
1997
|
+
const pendingToolResults = [];
|
|
1905
1998
|
for (const message of messages) {
|
|
1906
1999
|
switch (message.role) {
|
|
1907
2000
|
case "system": {
|
|
2001
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1908
2002
|
const text = contentPartsToText(message.content);
|
|
1909
2003
|
if (text) systemParts.push(text);
|
|
1910
2004
|
break;
|
|
@@ -1912,13 +2006,11 @@ var toAnthropicMessages = (messages) => {
|
|
|
1912
2006
|
case "reasoning":
|
|
1913
2007
|
break;
|
|
1914
2008
|
case "tool": {
|
|
1915
|
-
|
|
1916
|
-
role: "user",
|
|
1917
|
-
content: [toToolResultBlock(message)]
|
|
1918
|
-
});
|
|
2009
|
+
pendingToolResults.push(toToolResultBlock(message));
|
|
1919
2010
|
break;
|
|
1920
2011
|
}
|
|
1921
2012
|
case "assistant": {
|
|
2013
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1922
2014
|
const blocks = [];
|
|
1923
2015
|
blocks.push(...toContentBlocks(message.content));
|
|
1924
2016
|
if (message.tool_calls?.length) {
|
|
@@ -1931,6 +2023,7 @@ var toAnthropicMessages = (messages) => {
|
|
|
1931
2023
|
break;
|
|
1932
2024
|
}
|
|
1933
2025
|
case "user": {
|
|
2026
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1934
2027
|
const blocks = ensureToolResultBlocks(toContentBlocks(message.content));
|
|
1935
2028
|
output.push({
|
|
1936
2029
|
role: "user",
|
|
@@ -1942,19 +2035,23 @@ var toAnthropicMessages = (messages) => {
|
|
|
1942
2035
|
break;
|
|
1943
2036
|
}
|
|
1944
2037
|
}
|
|
2038
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1945
2039
|
const system = systemParts.length ? systemParts.join("\n\n") : void 0;
|
|
1946
|
-
return { system, messages: output };
|
|
2040
|
+
return { system, messages: dropOrphanToolUseBlocks(output) };
|
|
1947
2041
|
};
|
|
1948
2042
|
var extractText = (blocks) => blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
1949
2043
|
var toUsage = (response) => {
|
|
1950
2044
|
if (!response.usage) return null;
|
|
1951
|
-
const
|
|
2045
|
+
const baseInputTokens = response.usage.input_tokens ?? 0;
|
|
2046
|
+
const cacheCreateTokens = response.usage.cache_creation_input_tokens ?? 0;
|
|
2047
|
+
const cacheReadTokens = response.usage.cache_read_input_tokens ?? 0;
|
|
2048
|
+
const inputTokens = baseInputTokens + cacheCreateTokens + cacheReadTokens;
|
|
1952
2049
|
const outputTokens = response.usage.output_tokens ?? 0;
|
|
1953
2050
|
return {
|
|
1954
2051
|
model: response.model ?? "",
|
|
1955
2052
|
input_tokens: inputTokens,
|
|
1956
|
-
input_cached_tokens:
|
|
1957
|
-
input_cache_creation_tokens:
|
|
2053
|
+
input_cached_tokens: cacheReadTokens,
|
|
2054
|
+
input_cache_creation_tokens: cacheCreateTokens,
|
|
1958
2055
|
output_tokens: outputTokens,
|
|
1959
2056
|
total_tokens: inputTokens + outputTokens
|
|
1960
2057
|
};
|
|
@@ -2058,6 +2155,9 @@ var toAnthropicHostedSearchTool = (tool) => {
|
|
|
2058
2155
|
var PROVIDER_NAME = "anthropic";
|
|
2059
2156
|
var DEFAULT_MODEL = ANTHROPIC_DEFAULT_MODEL;
|
|
2060
2157
|
var DEFAULT_MAX_TOKENS = 4096;
|
|
2158
|
+
var DEFAULT_PROMPT_CACHE_CONTROL = {
|
|
2159
|
+
type: "ephemeral"
|
|
2160
|
+
};
|
|
2061
2161
|
var ChatAnthropic = class {
|
|
2062
2162
|
provider = PROVIDER_NAME;
|
|
2063
2163
|
model;
|
|
@@ -2093,6 +2193,9 @@ var ChatAnthropic = class {
|
|
|
2093
2193
|
...tools ? { tools } : {},
|
|
2094
2194
|
...tool_choice ? { tool_choice } : {}
|
|
2095
2195
|
};
|
|
2196
|
+
if (request.cache_control === void 0) {
|
|
2197
|
+
request.cache_control = DEFAULT_PROMPT_CACHE_CONTROL;
|
|
2198
|
+
}
|
|
2096
2199
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
2097
2200
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
2098
2201
|
const response = await this.client.messages.create(
|
|
@@ -2187,8 +2290,8 @@ var ChatAnthropic = class {
|
|
|
2187
2290
|
};
|
|
2188
2291
|
|
|
2189
2292
|
// src/llm/openai/chat.ts
|
|
2190
|
-
var import_openai3 = __toESM(require("openai"), 1);
|
|
2191
2293
|
var import_node_crypto2 = require("crypto");
|
|
2294
|
+
var import_openai3 = __toESM(require("openai"), 1);
|
|
2192
2295
|
|
|
2193
2296
|
// src/llm/openai/response-utils.ts
|
|
2194
2297
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -2316,16 +2419,6 @@ var isOpenAIAssistantInputContent = (value) => {
|
|
|
2316
2419
|
}
|
|
2317
2420
|
return false;
|
|
2318
2421
|
};
|
|
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
2422
|
var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
2330
2423
|
if (!value || typeof value !== "object") {
|
|
2331
2424
|
return false;
|
|
@@ -2333,6 +2426,12 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
2333
2426
|
const record = value;
|
|
2334
2427
|
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
2335
2428
|
};
|
|
2429
|
+
var toReplayableFunctionCallItemId = (value) => {
|
|
2430
|
+
if (typeof value !== "string") {
|
|
2431
|
+
return void 0;
|
|
2432
|
+
}
|
|
2433
|
+
return value.startsWith("fc") ? value : void 0;
|
|
2434
|
+
};
|
|
2336
2435
|
var toAssistantInputContent = (part) => {
|
|
2337
2436
|
switch (part.type) {
|
|
2338
2437
|
case "text":
|
|
@@ -2493,9 +2592,6 @@ function toResponsesInput(messages) {
|
|
|
2493
2592
|
continue;
|
|
2494
2593
|
}
|
|
2495
2594
|
if (message.role === "reasoning") {
|
|
2496
|
-
if (isReplayableOpenAIHistoryItem(message.raw_item)) {
|
|
2497
|
-
items.push(message.raw_item);
|
|
2498
|
-
}
|
|
2499
2595
|
continue;
|
|
2500
2596
|
}
|
|
2501
2597
|
if (message.role === "assistant") {
|
|
@@ -2590,8 +2686,16 @@ function toAssistantMessageItem(message) {
|
|
|
2590
2686
|
}
|
|
2591
2687
|
function toFunctionCallItem(call) {
|
|
2592
2688
|
if (isReplayableOpenAIFunctionCallItem(call.provider_meta)) {
|
|
2593
|
-
const
|
|
2594
|
-
|
|
2689
|
+
const replayable = call.provider_meta;
|
|
2690
|
+
const replayableId = toReplayableFunctionCallItemId(replayable.id);
|
|
2691
|
+
return {
|
|
2692
|
+
type: "function_call",
|
|
2693
|
+
call_id: replayable.call_id,
|
|
2694
|
+
name: replayable.name,
|
|
2695
|
+
arguments: replayable.arguments,
|
|
2696
|
+
...replayableId ? { id: replayableId } : {},
|
|
2697
|
+
...typeof replayable.status === "string" ? { status: replayable.status } : {}
|
|
2698
|
+
};
|
|
2595
2699
|
}
|
|
2596
2700
|
return {
|
|
2597
2701
|
type: "function_call",
|
|
@@ -2607,8 +2711,9 @@ function toFunctionCallOutputItem(message) {
|
|
|
2607
2711
|
output: toFunctionCallOutput(message.content)
|
|
2608
2712
|
};
|
|
2609
2713
|
}
|
|
2714
|
+
var isResponsesHostedSearchProvider = (provider) => provider === void 0 || provider === "openai" || provider === "openrouter";
|
|
2610
2715
|
function toOpenAiHostedSearchTool(tool) {
|
|
2611
|
-
if (tool.provider
|
|
2716
|
+
if (!isResponsesHostedSearchProvider(tool.provider)) {
|
|
2612
2717
|
return null;
|
|
2613
2718
|
}
|
|
2614
2719
|
const userLocation = tool.user_location ? {
|
|
@@ -2803,6 +2908,630 @@ var ChatOpenAI = class {
|
|
|
2803
2908
|
}
|
|
2804
2909
|
};
|
|
2805
2910
|
|
|
2911
|
+
// src/llm/openrouter/chat.ts
|
|
2912
|
+
var import_node_crypto3 = require("crypto");
|
|
2913
|
+
var import_openai5 = __toESM(require("openai"), 1);
|
|
2914
|
+
|
|
2915
|
+
// src/llm/openrouter/response-utils.ts
|
|
2916
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null;
|
|
2917
|
+
var stringifyUnknown5 = (value) => {
|
|
2918
|
+
if (value == null) return "";
|
|
2919
|
+
if (typeof value === "string") return value;
|
|
2920
|
+
try {
|
|
2921
|
+
return JSON.stringify(value);
|
|
2922
|
+
} catch {
|
|
2923
|
+
return String(value);
|
|
2924
|
+
}
|
|
2925
|
+
};
|
|
2926
|
+
var formatOtherPart4 = (part) => {
|
|
2927
|
+
const payloadText = stringifyUnknown5(part.payload);
|
|
2928
|
+
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
2929
|
+
};
|
|
2930
|
+
var isResponsesApiInputContent = (value) => {
|
|
2931
|
+
if (!isRecord3(value)) return false;
|
|
2932
|
+
const type = value.type;
|
|
2933
|
+
if (type === "input_text") {
|
|
2934
|
+
return typeof value.text === "string";
|
|
2935
|
+
}
|
|
2936
|
+
if (type === "input_image") {
|
|
2937
|
+
return typeof value.image_url === "string";
|
|
2938
|
+
}
|
|
2939
|
+
if (type === "input_file") {
|
|
2940
|
+
return typeof value.file_data === "string" || typeof value.file_id === "string";
|
|
2941
|
+
}
|
|
2942
|
+
return false;
|
|
2943
|
+
};
|
|
2944
|
+
var isOpenRouterReplayableOtherPart = (part) => (part.provider === "openrouter" || part.provider === "openai") && isResponsesApiInputContent(part.payload);
|
|
2945
|
+
var extractOutputText2 = (items) => {
|
|
2946
|
+
const texts = [];
|
|
2947
|
+
for (const item of items) {
|
|
2948
|
+
if (item.type !== "message") continue;
|
|
2949
|
+
for (const part of item.content ?? []) {
|
|
2950
|
+
if (part.type === "output_text") {
|
|
2951
|
+
texts.push(part.text);
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
return texts.join("");
|
|
2956
|
+
};
|
|
2957
|
+
var toResponseInputContent2 = (part) => {
|
|
2958
|
+
switch (part.type) {
|
|
2959
|
+
case "text":
|
|
2960
|
+
return { type: "input_text", text: part.text };
|
|
2961
|
+
case "image_url":
|
|
2962
|
+
return {
|
|
2963
|
+
type: "input_image",
|
|
2964
|
+
image_url: part.image_url.url,
|
|
2965
|
+
detail: part.image_url.detail ?? "auto"
|
|
2966
|
+
};
|
|
2967
|
+
case "document":
|
|
2968
|
+
return {
|
|
2969
|
+
type: "input_file",
|
|
2970
|
+
file_data: part.source.data,
|
|
2971
|
+
filename: "document.pdf"
|
|
2972
|
+
};
|
|
2973
|
+
case "other":
|
|
2974
|
+
if (isOpenRouterReplayableOtherPart(part)) {
|
|
2975
|
+
return part.payload;
|
|
2976
|
+
}
|
|
2977
|
+
return { type: "input_text", text: formatOtherPart4(part) };
|
|
2978
|
+
default:
|
|
2979
|
+
return { type: "input_text", text: "" };
|
|
2980
|
+
}
|
|
2981
|
+
};
|
|
2982
|
+
var toResponseInputContents2 = (content) => {
|
|
2983
|
+
if (content == null) {
|
|
2984
|
+
return "";
|
|
2985
|
+
}
|
|
2986
|
+
if (typeof content === "string") {
|
|
2987
|
+
return content;
|
|
2988
|
+
}
|
|
2989
|
+
return content.map(toResponseInputContent2);
|
|
2990
|
+
};
|
|
2991
|
+
var toFunctionCallOutput2 = (content) => {
|
|
2992
|
+
if (typeof content === "string") {
|
|
2993
|
+
return content;
|
|
2994
|
+
}
|
|
2995
|
+
return content.map(toResponseInputContent2);
|
|
2996
|
+
};
|
|
2997
|
+
|
|
2998
|
+
// src/llm/openrouter/serializer.ts
|
|
2999
|
+
var toOpenRouterOtherPart = (kind, payload) => ({
|
|
3000
|
+
type: "other",
|
|
3001
|
+
provider: "openrouter",
|
|
3002
|
+
kind,
|
|
3003
|
+
payload
|
|
3004
|
+
});
|
|
3005
|
+
var toAssistantOutputMessageContent2 = (item) => {
|
|
3006
|
+
const contents = item.content ?? [];
|
|
3007
|
+
if (contents.length === 0) {
|
|
3008
|
+
return null;
|
|
3009
|
+
}
|
|
3010
|
+
const parts = contents.map((part) => {
|
|
3011
|
+
if (part.type === "output_text") {
|
|
3012
|
+
return { type: "text", text: part.text };
|
|
3013
|
+
}
|
|
3014
|
+
return toOpenRouterOtherPart(part.type, part);
|
|
3015
|
+
});
|
|
3016
|
+
return parts;
|
|
3017
|
+
};
|
|
3018
|
+
var stringifyUnknown6 = (value) => {
|
|
3019
|
+
if (value == null) return "";
|
|
3020
|
+
if (typeof value === "string") return value;
|
|
3021
|
+
try {
|
|
3022
|
+
return JSON.stringify(value);
|
|
3023
|
+
} catch {
|
|
3024
|
+
return String(value);
|
|
3025
|
+
}
|
|
3026
|
+
};
|
|
3027
|
+
var formatOtherPart5 = (part) => {
|
|
3028
|
+
const payloadText = stringifyUnknown6(part.payload);
|
|
3029
|
+
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
3030
|
+
};
|
|
3031
|
+
var isOpenAIAssistantInputContent2 = (value) => {
|
|
3032
|
+
if (!value || typeof value !== "object") return false;
|
|
3033
|
+
const record = value;
|
|
3034
|
+
if (record.type === "output_text") {
|
|
3035
|
+
return typeof record.text === "string";
|
|
3036
|
+
}
|
|
3037
|
+
if (record.type === "refusal") {
|
|
3038
|
+
return typeof record.refusal === "string";
|
|
3039
|
+
}
|
|
3040
|
+
return false;
|
|
3041
|
+
};
|
|
3042
|
+
var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
3043
|
+
if (!value || typeof value !== "object") {
|
|
3044
|
+
return false;
|
|
3045
|
+
}
|
|
3046
|
+
const record = value;
|
|
3047
|
+
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
3048
|
+
};
|
|
3049
|
+
var toReplayableFunctionCallItemId2 = (value) => {
|
|
3050
|
+
if (typeof value !== "string") {
|
|
3051
|
+
return void 0;
|
|
3052
|
+
}
|
|
3053
|
+
return value.startsWith("fc") ? value : void 0;
|
|
3054
|
+
};
|
|
3055
|
+
var toAssistantInputContent2 = (part) => {
|
|
3056
|
+
switch (part.type) {
|
|
3057
|
+
case "text":
|
|
3058
|
+
return { type: "output_text", text: part.text };
|
|
3059
|
+
case "other":
|
|
3060
|
+
if ((part.provider === "openrouter" || part.provider === "openai") && isOpenAIAssistantInputContent2(part.payload)) {
|
|
3061
|
+
return part.payload;
|
|
3062
|
+
}
|
|
3063
|
+
return { type: "output_text", text: formatOtherPart5(part) };
|
|
3064
|
+
case "image_url":
|
|
3065
|
+
return { type: "output_text", text: "[image]" };
|
|
3066
|
+
case "document":
|
|
3067
|
+
return { type: "output_text", text: "[document]" };
|
|
3068
|
+
default:
|
|
3069
|
+
return { type: "output_text", text: "" };
|
|
3070
|
+
}
|
|
3071
|
+
};
|
|
3072
|
+
var toAssistantInputMessageContent2 = (content, refusal) => {
|
|
3073
|
+
const parts = [];
|
|
3074
|
+
if (typeof content === "string") {
|
|
3075
|
+
if (content) {
|
|
3076
|
+
parts.push({ type: "output_text", text: content });
|
|
3077
|
+
}
|
|
3078
|
+
} else if (Array.isArray(content)) {
|
|
3079
|
+
parts.push(...content.map(toAssistantInputContent2));
|
|
3080
|
+
}
|
|
3081
|
+
if (refusal) {
|
|
3082
|
+
parts.push({ type: "refusal", refusal });
|
|
3083
|
+
}
|
|
3084
|
+
return parts;
|
|
3085
|
+
};
|
|
3086
|
+
var extractReasoningText2 = (item) => {
|
|
3087
|
+
const summaryText = (item.summary ?? []).map(
|
|
3088
|
+
(part) => part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""
|
|
3089
|
+
).filter((text) => text.length > 0).join("\n");
|
|
3090
|
+
if (summaryText) return summaryText;
|
|
3091
|
+
const contentText = (item.content ?? []).map(
|
|
3092
|
+
(part) => part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""
|
|
3093
|
+
).filter((text) => text.length > 0).join("\n");
|
|
3094
|
+
return contentText;
|
|
3095
|
+
};
|
|
3096
|
+
var extractWebSearchSummary2 = (item) => {
|
|
3097
|
+
const parts = [`WebSearch status=${item.status}`];
|
|
3098
|
+
const record = item;
|
|
3099
|
+
const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
|
|
3100
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
3101
|
+
) : [];
|
|
3102
|
+
if (queries.length) {
|
|
3103
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
3104
|
+
}
|
|
3105
|
+
const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
|
|
3106
|
+
if (sources.length) {
|
|
3107
|
+
parts.push(`sources=${sources.length}`);
|
|
3108
|
+
}
|
|
3109
|
+
return parts.join(" | ");
|
|
3110
|
+
};
|
|
3111
|
+
var toMessageSequence2 = (response) => {
|
|
3112
|
+
const messages = [];
|
|
3113
|
+
for (const item of response.output) {
|
|
3114
|
+
switch (item.type) {
|
|
3115
|
+
case "reasoning": {
|
|
3116
|
+
messages.push({
|
|
3117
|
+
role: "reasoning",
|
|
3118
|
+
content: extractReasoningText2(item),
|
|
3119
|
+
raw_item: item
|
|
3120
|
+
});
|
|
3121
|
+
break;
|
|
3122
|
+
}
|
|
3123
|
+
case "function_call": {
|
|
3124
|
+
const toolCall = {
|
|
3125
|
+
id: item.call_id,
|
|
3126
|
+
type: "function",
|
|
3127
|
+
function: { name: item.name, arguments: item.arguments },
|
|
3128
|
+
provider_meta: item
|
|
3129
|
+
};
|
|
3130
|
+
messages.push({
|
|
3131
|
+
role: "assistant",
|
|
3132
|
+
content: null,
|
|
3133
|
+
tool_calls: [toolCall]
|
|
3134
|
+
});
|
|
3135
|
+
break;
|
|
3136
|
+
}
|
|
3137
|
+
case "message": {
|
|
3138
|
+
messages.push({
|
|
3139
|
+
role: "assistant",
|
|
3140
|
+
content: toAssistantOutputMessageContent2(item)
|
|
3141
|
+
});
|
|
3142
|
+
break;
|
|
3143
|
+
}
|
|
3144
|
+
case "web_search_call": {
|
|
3145
|
+
messages.push({
|
|
3146
|
+
role: "reasoning",
|
|
3147
|
+
content: extractWebSearchSummary2(item),
|
|
3148
|
+
raw_item: item
|
|
3149
|
+
});
|
|
3150
|
+
break;
|
|
3151
|
+
}
|
|
3152
|
+
default: {
|
|
3153
|
+
messages.push({
|
|
3154
|
+
role: "assistant",
|
|
3155
|
+
content: [toOpenRouterOtherPart(item.type, item)]
|
|
3156
|
+
});
|
|
3157
|
+
break;
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
return messages;
|
|
3162
|
+
};
|
|
3163
|
+
function extractInstructions2(messages) {
|
|
3164
|
+
const chunks = [];
|
|
3165
|
+
for (const message of messages) {
|
|
3166
|
+
if (message.role !== "system") {
|
|
3167
|
+
continue;
|
|
3168
|
+
}
|
|
3169
|
+
const content = message.content;
|
|
3170
|
+
if (content == null) {
|
|
3171
|
+
continue;
|
|
3172
|
+
}
|
|
3173
|
+
if (typeof content === "string") {
|
|
3174
|
+
const trimmed = content.trim();
|
|
3175
|
+
if (trimmed) {
|
|
3176
|
+
chunks.push(trimmed);
|
|
3177
|
+
}
|
|
3178
|
+
continue;
|
|
3179
|
+
}
|
|
3180
|
+
const text = content.map((part) => {
|
|
3181
|
+
switch (part.type) {
|
|
3182
|
+
case "text":
|
|
3183
|
+
return part.text;
|
|
3184
|
+
default:
|
|
3185
|
+
return "";
|
|
3186
|
+
}
|
|
3187
|
+
}).join("").trim();
|
|
3188
|
+
if (text) {
|
|
3189
|
+
chunks.push(text);
|
|
3190
|
+
}
|
|
3191
|
+
}
|
|
3192
|
+
return chunks.length ? chunks.join("\n\n") : void 0;
|
|
3193
|
+
}
|
|
3194
|
+
function toResponsesInput2(messages) {
|
|
3195
|
+
const items = [];
|
|
3196
|
+
for (const message of messages) {
|
|
3197
|
+
if (message.role === "system") {
|
|
3198
|
+
continue;
|
|
3199
|
+
}
|
|
3200
|
+
if (message.role === "tool") {
|
|
3201
|
+
items.push(toFunctionCallOutputItem2(message));
|
|
3202
|
+
continue;
|
|
3203
|
+
}
|
|
3204
|
+
if (message.role === "assistant" && message.tool_calls?.length) {
|
|
3205
|
+
const assistantMessageItem = toAssistantMessageItem2(message);
|
|
3206
|
+
if (assistantMessageItem) {
|
|
3207
|
+
items.push(assistantMessageItem);
|
|
3208
|
+
}
|
|
3209
|
+
for (const call of message.tool_calls) {
|
|
3210
|
+
items.push(toFunctionCallItem2(call));
|
|
3211
|
+
}
|
|
3212
|
+
continue;
|
|
3213
|
+
}
|
|
3214
|
+
if (message.role === "reasoning") {
|
|
3215
|
+
continue;
|
|
3216
|
+
}
|
|
3217
|
+
if (message.role === "assistant") {
|
|
3218
|
+
const assistantMessageItem = toAssistantMessageItem2(message);
|
|
3219
|
+
if (assistantMessageItem) {
|
|
3220
|
+
items.push(assistantMessageItem);
|
|
3221
|
+
}
|
|
3222
|
+
continue;
|
|
3223
|
+
}
|
|
3224
|
+
items.push({
|
|
3225
|
+
type: "message",
|
|
3226
|
+
role: message.role,
|
|
3227
|
+
content: toUserMessageContent2(message.content)
|
|
3228
|
+
});
|
|
3229
|
+
}
|
|
3230
|
+
return items;
|
|
3231
|
+
}
|
|
3232
|
+
function toResponsesTools2(tools) {
|
|
3233
|
+
if (!tools || tools.length === 0) {
|
|
3234
|
+
return void 0;
|
|
3235
|
+
}
|
|
3236
|
+
const mapped = [];
|
|
3237
|
+
for (const tool of tools) {
|
|
3238
|
+
if (isFunctionToolDefinition(tool)) {
|
|
3239
|
+
mapped.push({
|
|
3240
|
+
type: "function",
|
|
3241
|
+
name: tool.name,
|
|
3242
|
+
description: tool.description,
|
|
3243
|
+
parameters: tool.parameters,
|
|
3244
|
+
strict: tool.strict ?? false
|
|
3245
|
+
});
|
|
3246
|
+
continue;
|
|
3247
|
+
}
|
|
3248
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
3249
|
+
const hosted = toOpenRouterHostedSearchTool(tool);
|
|
3250
|
+
if (hosted) {
|
|
3251
|
+
mapped.push(hosted);
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
return mapped.length ? mapped : void 0;
|
|
3256
|
+
}
|
|
3257
|
+
function toResponsesToolChoice2(choice) {
|
|
3258
|
+
if (!choice) {
|
|
3259
|
+
return void 0;
|
|
3260
|
+
}
|
|
3261
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
3262
|
+
return choice;
|
|
3263
|
+
}
|
|
3264
|
+
return { type: "function", name: choice };
|
|
3265
|
+
}
|
|
3266
|
+
function toChatInvokeCompletion3(response) {
|
|
3267
|
+
const usage = response.usage ? {
|
|
3268
|
+
model: response.model,
|
|
3269
|
+
input_tokens: response.usage.input_tokens,
|
|
3270
|
+
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
3271
|
+
output_tokens: response.usage.output_tokens,
|
|
3272
|
+
total_tokens: response.usage.total_tokens
|
|
3273
|
+
} : null;
|
|
3274
|
+
const messages = toMessageSequence2(response);
|
|
3275
|
+
if (!messages.length) {
|
|
3276
|
+
const fallbackText = typeof response.output_text === "string" ? response.output_text : extractOutputText2(response.output);
|
|
3277
|
+
if (fallbackText) {
|
|
3278
|
+
messages.push({ role: "assistant", content: fallbackText });
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
return {
|
|
3282
|
+
messages,
|
|
3283
|
+
usage,
|
|
3284
|
+
stop_reason: response.incomplete_details?.reason ?? response.status ?? null,
|
|
3285
|
+
provider_meta: {
|
|
3286
|
+
response_id: response.id
|
|
3287
|
+
}
|
|
3288
|
+
};
|
|
3289
|
+
}
|
|
3290
|
+
function toUserMessageContent2(content) {
|
|
3291
|
+
return toResponseInputContents2(content);
|
|
3292
|
+
}
|
|
3293
|
+
function toAssistantMessageItem2(message) {
|
|
3294
|
+
const content = toAssistantInputMessageContent2(
|
|
3295
|
+
message.content,
|
|
3296
|
+
message.refusal
|
|
3297
|
+
);
|
|
3298
|
+
if (content.length === 0) {
|
|
3299
|
+
return null;
|
|
3300
|
+
}
|
|
3301
|
+
return {
|
|
3302
|
+
type: "message",
|
|
3303
|
+
role: "assistant",
|
|
3304
|
+
content
|
|
3305
|
+
};
|
|
3306
|
+
}
|
|
3307
|
+
function toFunctionCallItem2(call) {
|
|
3308
|
+
if (isReplayableOpenAIFunctionCallItem2(call.provider_meta)) {
|
|
3309
|
+
const replayable = call.provider_meta;
|
|
3310
|
+
const replayableId = toReplayableFunctionCallItemId2(replayable.id);
|
|
3311
|
+
return {
|
|
3312
|
+
type: "function_call",
|
|
3313
|
+
call_id: replayable.call_id,
|
|
3314
|
+
name: replayable.name,
|
|
3315
|
+
arguments: replayable.arguments,
|
|
3316
|
+
...replayableId ? { id: replayableId } : {},
|
|
3317
|
+
...typeof replayable.status === "string" ? { status: replayable.status } : {}
|
|
3318
|
+
};
|
|
3319
|
+
}
|
|
3320
|
+
return {
|
|
3321
|
+
type: "function_call",
|
|
3322
|
+
call_id: call.id,
|
|
3323
|
+
name: call.function.name,
|
|
3324
|
+
arguments: call.function.arguments
|
|
3325
|
+
};
|
|
3326
|
+
}
|
|
3327
|
+
function toFunctionCallOutputItem2(message) {
|
|
3328
|
+
return {
|
|
3329
|
+
type: "function_call_output",
|
|
3330
|
+
call_id: message.tool_call_id,
|
|
3331
|
+
output: toFunctionCallOutput2(message.content)
|
|
3332
|
+
};
|
|
3333
|
+
}
|
|
3334
|
+
var isResponsesHostedSearchProvider2 = (provider) => provider === void 0 || provider === "openai" || provider === "openrouter";
|
|
3335
|
+
function toOpenRouterHostedSearchTool(tool) {
|
|
3336
|
+
if (!isResponsesHostedSearchProvider2(tool.provider)) {
|
|
3337
|
+
return null;
|
|
3338
|
+
}
|
|
3339
|
+
const userLocation = tool.user_location ? {
|
|
3340
|
+
type: "approximate",
|
|
3341
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
3342
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
3343
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
3344
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
3345
|
+
} : void 0;
|
|
3346
|
+
return {
|
|
3347
|
+
type: "web_search",
|
|
3348
|
+
...tool.search_context_size ? { search_context_size: tool.search_context_size } : {},
|
|
3349
|
+
...tool.allowed_domains?.length ? {
|
|
3350
|
+
filters: {
|
|
3351
|
+
allowed_domains: tool.allowed_domains
|
|
3352
|
+
}
|
|
3353
|
+
} : {},
|
|
3354
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
3355
|
+
};
|
|
3356
|
+
}
|
|
3357
|
+
|
|
3358
|
+
// src/llm/openrouter/chat.ts
|
|
3359
|
+
var PROVIDER_NAME3 = "openrouter";
|
|
3360
|
+
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
3361
|
+
var DEFAULT_MODEL3 = OPENAI_DEFAULT_MODEL;
|
|
3362
|
+
var DEFAULT_REASONING_EFFORT2 = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
3363
|
+
var DEFAULT_REASONING_SUMMARY2 = "auto";
|
|
3364
|
+
var getSessionIdHeaderValue2 = (promptCacheKey) => {
|
|
3365
|
+
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
3366
|
+
};
|
|
3367
|
+
var ChatOpenRouter = class {
|
|
3368
|
+
provider = PROVIDER_NAME3;
|
|
3369
|
+
model;
|
|
3370
|
+
client;
|
|
3371
|
+
defaultReasoningEffort;
|
|
3372
|
+
defaultTextVerbosity;
|
|
3373
|
+
debugInvokeSeq = 0;
|
|
3374
|
+
lastDebugRequestPayload = null;
|
|
3375
|
+
constructor(options = {}) {
|
|
3376
|
+
this.client = options.client ?? new import_openai5.default({
|
|
3377
|
+
baseURL: OPENROUTER_BASE_URL,
|
|
3378
|
+
...options.clientOptions ?? {}
|
|
3379
|
+
});
|
|
3380
|
+
this.model = options.model ?? DEFAULT_MODEL3;
|
|
3381
|
+
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT2;
|
|
3382
|
+
this.defaultTextVerbosity = options.textVerbosity;
|
|
3383
|
+
}
|
|
3384
|
+
async ainvoke(input, context) {
|
|
3385
|
+
const {
|
|
3386
|
+
messages,
|
|
3387
|
+
tools: toolDefs,
|
|
3388
|
+
toolChoice,
|
|
3389
|
+
options,
|
|
3390
|
+
model,
|
|
3391
|
+
signal
|
|
3392
|
+
} = input;
|
|
3393
|
+
const inputItems = toResponsesInput2(messages);
|
|
3394
|
+
const instructions = extractInstructions2(messages);
|
|
3395
|
+
const tools = toResponsesTools2(toolDefs);
|
|
3396
|
+
const tool_choice = toResponsesToolChoice2(toolChoice);
|
|
3397
|
+
const { reasoningEffort, textVerbosity, ...rest } = options ?? {};
|
|
3398
|
+
const request = {
|
|
3399
|
+
model: model ?? this.model,
|
|
3400
|
+
input: inputItems,
|
|
3401
|
+
...rest,
|
|
3402
|
+
...tools ? { tools } : {},
|
|
3403
|
+
...tool_choice ? { tool_choice } : {}
|
|
3404
|
+
};
|
|
3405
|
+
if (request.store === void 0) {
|
|
3406
|
+
request.store = false;
|
|
3407
|
+
}
|
|
3408
|
+
if (instructions) {
|
|
3409
|
+
request.instructions = instructions;
|
|
3410
|
+
}
|
|
3411
|
+
const hasWebSearchTool = tools?.some(
|
|
3412
|
+
(tool) => tool.type === "web_search" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11"
|
|
3413
|
+
);
|
|
3414
|
+
const includeSet = new Set(request.include ?? []);
|
|
3415
|
+
includeSet.add("reasoning.encrypted_content");
|
|
3416
|
+
if (hasWebSearchTool) {
|
|
3417
|
+
includeSet.add("web_search_call.action.sources");
|
|
3418
|
+
includeSet.add("web_search_call.results");
|
|
3419
|
+
}
|
|
3420
|
+
request.include = Array.from(includeSet);
|
|
3421
|
+
const effort = reasoningEffort ?? this.defaultReasoningEffort;
|
|
3422
|
+
request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY2 };
|
|
3423
|
+
const verbosity = textVerbosity ?? this.defaultTextVerbosity;
|
|
3424
|
+
if (verbosity) {
|
|
3425
|
+
request.text = {
|
|
3426
|
+
...request.text ?? {},
|
|
3427
|
+
verbosity
|
|
3428
|
+
};
|
|
3429
|
+
}
|
|
3430
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
3431
|
+
request.prompt_cache_key = context.sessionKey;
|
|
3432
|
+
}
|
|
3433
|
+
const sessionIdHeader = getSessionIdHeaderValue2(request.prompt_cache_key);
|
|
3434
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
3435
|
+
await this.debugRequestIfEnabled(request, debugSeq, sessionIdHeader);
|
|
3436
|
+
const streamRequest = {
|
|
3437
|
+
...request,
|
|
3438
|
+
stream: true
|
|
3439
|
+
};
|
|
3440
|
+
const response = await this.client.responses.stream(
|
|
3441
|
+
streamRequest,
|
|
3442
|
+
signal || sessionIdHeader ? {
|
|
3443
|
+
...signal ? { signal } : {},
|
|
3444
|
+
...sessionIdHeader ? {
|
|
3445
|
+
headers: {
|
|
3446
|
+
session_id: sessionIdHeader
|
|
3447
|
+
}
|
|
3448
|
+
} : {}
|
|
3449
|
+
} : void 0
|
|
3450
|
+
).finalResponse();
|
|
3451
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3452
|
+
return toChatInvokeCompletion3(response);
|
|
3453
|
+
}
|
|
3454
|
+
nextDebugInvokeSeq() {
|
|
3455
|
+
const seq = this.debugInvokeSeq + 1;
|
|
3456
|
+
this.debugInvokeSeq = seq;
|
|
3457
|
+
return seq;
|
|
3458
|
+
}
|
|
3459
|
+
async debugRequestIfEnabled(request, seq, sessionIdHeader) {
|
|
3460
|
+
const settings = getProviderLogSettings();
|
|
3461
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
const payload = safeJsonStringify(request);
|
|
3465
|
+
const hash = (0, import_node_crypto3.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3466
|
+
const toolsHash = (0, import_node_crypto3.createHash)("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
3467
|
+
const instructionsHash = (0, import_node_crypto3.createHash)("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
3468
|
+
const previous = this.lastDebugRequestPayload;
|
|
3469
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3470
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
3471
|
+
if (settings.enabled) {
|
|
3472
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${(0, import_node_crypto3.createHash)("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
3473
|
+
console.error(
|
|
3474
|
+
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
3475
|
+
);
|
|
3476
|
+
}
|
|
3477
|
+
if (settings.dumpDir) {
|
|
3478
|
+
try {
|
|
3479
|
+
await writeProviderLogDump(
|
|
3480
|
+
settings,
|
|
3481
|
+
PROVIDER_NAME3,
|
|
3482
|
+
seq,
|
|
3483
|
+
"request",
|
|
3484
|
+
request
|
|
3485
|
+
);
|
|
3486
|
+
} catch (error) {
|
|
3487
|
+
if (settings.enabled) {
|
|
3488
|
+
console.error(
|
|
3489
|
+
`[openrouter.request] dump_failed seq=${seq} error=${String(error)}`
|
|
3490
|
+
);
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
this.lastDebugRequestPayload = payload;
|
|
3495
|
+
}
|
|
3496
|
+
async debugResponseIfEnabled(response, seq) {
|
|
3497
|
+
const settings = getProviderLogSettings();
|
|
3498
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3499
|
+
return;
|
|
3500
|
+
}
|
|
3501
|
+
if (settings.enabled) {
|
|
3502
|
+
const usage = response.usage;
|
|
3503
|
+
const cachedInputTokens = usage?.input_tokens_details?.cached_tokens ?? 0;
|
|
3504
|
+
const outputItems = Array.isArray(response.output) ? response.output : [];
|
|
3505
|
+
const outputKinds = /* @__PURE__ */ new Set();
|
|
3506
|
+
for (const item of outputItems) {
|
|
3507
|
+
const kind = item && typeof item === "object" && "type" in item ? String(item.type ?? "unknown") : "unknown";
|
|
3508
|
+
outputKinds.add(kind);
|
|
3509
|
+
}
|
|
3510
|
+
const usageIn = usage?.input_tokens ?? 0;
|
|
3511
|
+
console.error(
|
|
3512
|
+
`[openrouter.response] seq=${seq} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
3513
|
+
);
|
|
3514
|
+
}
|
|
3515
|
+
if (settings.dumpDir) {
|
|
3516
|
+
try {
|
|
3517
|
+
await writeProviderLogDump(
|
|
3518
|
+
settings,
|
|
3519
|
+
PROVIDER_NAME3,
|
|
3520
|
+
seq,
|
|
3521
|
+
"response",
|
|
3522
|
+
response
|
|
3523
|
+
);
|
|
3524
|
+
} catch (error) {
|
|
3525
|
+
if (settings.enabled) {
|
|
3526
|
+
console.error(
|
|
3527
|
+
`[openrouter.response] dump_failed seq=${seq} error=${String(error)}`
|
|
3528
|
+
);
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
}
|
|
3533
|
+
};
|
|
3534
|
+
|
|
2806
3535
|
// src/prompts.ts
|
|
2807
3536
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
2808
3537
|
var import_node_url = require("url");
|
|
@@ -2931,6 +3660,7 @@ function defineTool(toolOptions) {
|
|
|
2931
3660
|
Agent,
|
|
2932
3661
|
ChatAnthropic,
|
|
2933
3662
|
ChatOpenAI,
|
|
3663
|
+
ChatOpenRouter,
|
|
2934
3664
|
DEFAULT_MODEL_REGISTRY,
|
|
2935
3665
|
GOOGLE_MODELS,
|
|
2936
3666
|
OPENAI_DEFAULT_MODEL,
|