@codelia/core 0.1.18 → 0.1.20
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/prompts/system.md +10 -17
package/dist/index.js
CHANGED
|
@@ -177,7 +177,7 @@ var MessageHistoryAdapter = class {
|
|
|
177
177
|
};
|
|
178
178
|
|
|
179
179
|
// src/llm/openai/history.ts
|
|
180
|
-
var
|
|
180
|
+
var ResponsesHistoryAdapter = class extends MessageHistoryAdapter {
|
|
181
181
|
};
|
|
182
182
|
|
|
183
183
|
// src/models/anthropic.ts
|
|
@@ -237,6 +237,7 @@ function createModelRegistry(specs) {
|
|
|
237
237
|
aliasesByProvider: {
|
|
238
238
|
openai: {},
|
|
239
239
|
anthropic: {},
|
|
240
|
+
openrouter: {},
|
|
240
241
|
google: {}
|
|
241
242
|
}
|
|
242
243
|
};
|
|
@@ -284,6 +285,7 @@ function cloneAliases(aliasesByProvider) {
|
|
|
284
285
|
return {
|
|
285
286
|
openai: { ...aliasesByProvider.openai },
|
|
286
287
|
anthropic: { ...aliasesByProvider.anthropic },
|
|
288
|
+
openrouter: { ...aliasesByProvider.openrouter },
|
|
287
289
|
google: { ...aliasesByProvider.google }
|
|
288
290
|
};
|
|
289
291
|
}
|
|
@@ -293,7 +295,7 @@ function applyModelMetadata(registry, index) {
|
|
|
293
295
|
aliasesByProvider: cloneAliases(registry.aliasesByProvider)
|
|
294
296
|
};
|
|
295
297
|
for (const [providerId, providerModels] of Object.entries(index.models)) {
|
|
296
|
-
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "google") {
|
|
298
|
+
if (providerId !== "openai" && providerId !== "anthropic" && providerId !== "openrouter" && providerId !== "google") {
|
|
297
299
|
continue;
|
|
298
300
|
}
|
|
299
301
|
const provider = providerId;
|
|
@@ -534,7 +536,11 @@ var CompactionService = class _CompactionService {
|
|
|
534
536
|
}
|
|
535
537
|
const qualified = parseQualifiedModelId(modelId);
|
|
536
538
|
if (qualified) {
|
|
537
|
-
const qualifiedDirect = resolveModel(
|
|
539
|
+
const qualifiedDirect = resolveModel(
|
|
540
|
+
this.modelRegistry,
|
|
541
|
+
qualified.modelId,
|
|
542
|
+
qualified.provider
|
|
543
|
+
) ?? resolveModel(
|
|
538
544
|
this.modelRegistry,
|
|
539
545
|
`${qualified.provider}/${qualified.modelId}`,
|
|
540
546
|
qualified.provider
|
|
@@ -587,7 +593,7 @@ var parseQualifiedModelId = (modelId) => {
|
|
|
587
593
|
if (!rest) {
|
|
588
594
|
return null;
|
|
589
595
|
}
|
|
590
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
596
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
591
597
|
return null;
|
|
592
598
|
}
|
|
593
599
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -770,7 +776,7 @@ var parseQualifiedModelId2 = (modelId) => {
|
|
|
770
776
|
if (!rest) {
|
|
771
777
|
return null;
|
|
772
778
|
}
|
|
773
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
779
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
774
780
|
return null;
|
|
775
781
|
}
|
|
776
782
|
return { provider: providerRaw, modelId: rest };
|
|
@@ -976,6 +982,7 @@ var throwIfAborted = (signal) => {
|
|
|
976
982
|
throw createAbortError();
|
|
977
983
|
}
|
|
978
984
|
};
|
|
985
|
+
var isResponsesHistoryProvider = (provider) => provider === "openai" || provider === "openrouter";
|
|
979
986
|
var Agent = class {
|
|
980
987
|
llm;
|
|
981
988
|
tools;
|
|
@@ -994,7 +1001,7 @@ var Agent = class {
|
|
|
994
1001
|
usageService;
|
|
995
1002
|
constructor(options) {
|
|
996
1003
|
this.llm = options.llm;
|
|
997
|
-
this.history = this.llm.provider
|
|
1004
|
+
this.history = isResponsesHistoryProvider(this.llm.provider) ? new ResponsesHistoryAdapter() : new MessageHistoryAdapter();
|
|
998
1005
|
this.tools = options.tools;
|
|
999
1006
|
this.hostedTools = options.hostedTools ?? [];
|
|
1000
1007
|
this.systemPrompt = options.systemPrompt ?? void 0;
|
|
@@ -1204,10 +1211,7 @@ var Agent = class {
|
|
|
1204
1211
|
await this.trimToolOutputs();
|
|
1205
1212
|
throwIfAborted(signal);
|
|
1206
1213
|
const invokeInput = this.history.prepareInvokeInput({
|
|
1207
|
-
tools: [
|
|
1208
|
-
...this.tools.map((t) => t.definition),
|
|
1209
|
-
...this.hostedTools
|
|
1210
|
-
],
|
|
1214
|
+
tools: [...this.tools.map((t) => t.definition), ...this.hostedTools],
|
|
1211
1215
|
toolChoice: this.toolChoice
|
|
1212
1216
|
});
|
|
1213
1217
|
const invokeContext = this.buildInvokeContext(session);
|
|
@@ -1222,12 +1226,7 @@ var Agent = class {
|
|
|
1222
1226
|
this.recordLlmResponse(session, seq, response);
|
|
1223
1227
|
this.usageService.updateUsageSummary(response.usage);
|
|
1224
1228
|
this.history.commitModelResponse(response);
|
|
1225
|
-
const {
|
|
1226
|
-
reasoningTexts,
|
|
1227
|
-
assistantTexts,
|
|
1228
|
-
toolCalls,
|
|
1229
|
-
hostedToolCalls
|
|
1230
|
-
} = collectModelOutput(response.messages);
|
|
1229
|
+
const { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls } = collectModelOutput(response.messages);
|
|
1231
1230
|
for (const reasoningText of reasoningTexts) {
|
|
1232
1231
|
const reasoningEvent = {
|
|
1233
1232
|
type: "reasoning",
|
|
@@ -1578,15 +1577,15 @@ var parseQualifiedModelId3 = (modelId) => {
|
|
|
1578
1577
|
if (!rest) {
|
|
1579
1578
|
return null;
|
|
1580
1579
|
}
|
|
1581
|
-
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "google") {
|
|
1580
|
+
if (providerRaw !== "openai" && providerRaw !== "anthropic" && providerRaw !== "openrouter" && providerRaw !== "google") {
|
|
1582
1581
|
return null;
|
|
1583
1582
|
}
|
|
1584
1583
|
return { provider: providerRaw, modelId: rest };
|
|
1585
1584
|
};
|
|
1586
1585
|
|
|
1587
1586
|
// src/llm/anthropic/chat.ts
|
|
1588
|
-
import Anthropic from "@anthropic-ai/sdk";
|
|
1589
1587
|
import { createHash } from "crypto";
|
|
1588
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
1590
1589
|
|
|
1591
1590
|
// src/llm/provider-log.ts
|
|
1592
1591
|
import { promises as fs } from "fs";
|
|
@@ -1843,12 +1842,106 @@ var toAnthropicToolChoice = (choice) => {
|
|
|
1843
1842
|
if (choice === "none") return void 0;
|
|
1844
1843
|
return { type: "tool", name: choice };
|
|
1845
1844
|
};
|
|
1845
|
+
var mergePendingToolResults = (pendingToolResults, output) => {
|
|
1846
|
+
if (pendingToolResults.length === 0) return;
|
|
1847
|
+
output.push({
|
|
1848
|
+
role: "user",
|
|
1849
|
+
content: [...pendingToolResults]
|
|
1850
|
+
});
|
|
1851
|
+
pendingToolResults.length = 0;
|
|
1852
|
+
};
|
|
1853
|
+
var isToolUseBlock = (block) => isRecord(block) && block.type === "tool_use";
|
|
1854
|
+
var isToolResultBlock = (block) => isRecord(block) && block.type === "tool_result";
|
|
1855
|
+
var isAssistantWithToolUseBlocks = (message) => message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => isToolUseBlock(block));
|
|
1856
|
+
var coalesceConsecutiveAssistantToolUseMessages = (messages) => {
|
|
1857
|
+
const normalized = [];
|
|
1858
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
1859
|
+
const current = messages[index];
|
|
1860
|
+
if (!isAssistantWithToolUseBlocks(current)) {
|
|
1861
|
+
normalized.push(current);
|
|
1862
|
+
continue;
|
|
1863
|
+
}
|
|
1864
|
+
const mergedBlocks = [...current.content];
|
|
1865
|
+
let nextIndex = index + 1;
|
|
1866
|
+
while (nextIndex < messages.length) {
|
|
1867
|
+
const candidate = messages[nextIndex];
|
|
1868
|
+
if (!isAssistantWithToolUseBlocks(candidate)) break;
|
|
1869
|
+
mergedBlocks.push(...candidate.content);
|
|
1870
|
+
nextIndex += 1;
|
|
1871
|
+
}
|
|
1872
|
+
normalized.push({
|
|
1873
|
+
role: "assistant",
|
|
1874
|
+
content: ensureMessageBlocks(mergedBlocks)
|
|
1875
|
+
});
|
|
1876
|
+
index = nextIndex - 1;
|
|
1877
|
+
}
|
|
1878
|
+
return normalized;
|
|
1879
|
+
};
|
|
1880
|
+
var dropOrphanToolUseBlocks = (messages) => {
|
|
1881
|
+
const normalizedMessages = coalesceConsecutiveAssistantToolUseMessages(messages);
|
|
1882
|
+
const sanitized = [];
|
|
1883
|
+
for (let index = 0; index < normalizedMessages.length; index += 1) {
|
|
1884
|
+
const current = normalizedMessages[index];
|
|
1885
|
+
if (!Array.isArray(current.content) || current.role !== "assistant") {
|
|
1886
|
+
sanitized.push(current);
|
|
1887
|
+
continue;
|
|
1888
|
+
}
|
|
1889
|
+
const toolUseIds = /* @__PURE__ */ new Set();
|
|
1890
|
+
for (const block of current.content) {
|
|
1891
|
+
if (isToolUseBlock(block)) {
|
|
1892
|
+
toolUseIds.add(block.id);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
if (toolUseIds.size === 0) {
|
|
1896
|
+
sanitized.push(current);
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
const next = normalizedMessages[index + 1];
|
|
1900
|
+
if (!next || next.role !== "user" || !Array.isArray(next.content)) {
|
|
1901
|
+
const filtered = current.content.filter(
|
|
1902
|
+
(block) => !isToolUseBlock(block)
|
|
1903
|
+
);
|
|
1904
|
+
if (filtered.length > 0) {
|
|
1905
|
+
sanitized.push({ ...current, content: filtered });
|
|
1906
|
+
}
|
|
1907
|
+
continue;
|
|
1908
|
+
}
|
|
1909
|
+
const toolResultIds = /* @__PURE__ */ new Set();
|
|
1910
|
+
for (const block of next.content) {
|
|
1911
|
+
if (isToolResultBlock(block)) {
|
|
1912
|
+
toolResultIds.add(block.tool_use_id);
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
const allowedIds = /* @__PURE__ */ new Set();
|
|
1916
|
+
for (const id of toolUseIds) {
|
|
1917
|
+
if (toolResultIds.has(id)) {
|
|
1918
|
+
allowedIds.add(id);
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
const filteredCurrent = current.content.filter(
|
|
1922
|
+
(block) => !isToolUseBlock(block) || allowedIds.has(block.id)
|
|
1923
|
+
);
|
|
1924
|
+
if (filteredCurrent.length > 0) {
|
|
1925
|
+
sanitized.push({ ...current, content: filteredCurrent });
|
|
1926
|
+
}
|
|
1927
|
+
const filteredNext = next.content.filter(
|
|
1928
|
+
(block) => !isToolResultBlock(block) || allowedIds.has(block.tool_use_id)
|
|
1929
|
+
);
|
|
1930
|
+
if (filteredNext.length > 0) {
|
|
1931
|
+
sanitized.push({ ...next, content: filteredNext });
|
|
1932
|
+
}
|
|
1933
|
+
index += 1;
|
|
1934
|
+
}
|
|
1935
|
+
return sanitized;
|
|
1936
|
+
};
|
|
1846
1937
|
var toAnthropicMessages = (messages) => {
|
|
1847
1938
|
const systemParts = [];
|
|
1848
1939
|
const output = [];
|
|
1940
|
+
const pendingToolResults = [];
|
|
1849
1941
|
for (const message of messages) {
|
|
1850
1942
|
switch (message.role) {
|
|
1851
1943
|
case "system": {
|
|
1944
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1852
1945
|
const text = contentPartsToText(message.content);
|
|
1853
1946
|
if (text) systemParts.push(text);
|
|
1854
1947
|
break;
|
|
@@ -1856,13 +1949,11 @@ var toAnthropicMessages = (messages) => {
|
|
|
1856
1949
|
case "reasoning":
|
|
1857
1950
|
break;
|
|
1858
1951
|
case "tool": {
|
|
1859
|
-
|
|
1860
|
-
role: "user",
|
|
1861
|
-
content: [toToolResultBlock(message)]
|
|
1862
|
-
});
|
|
1952
|
+
pendingToolResults.push(toToolResultBlock(message));
|
|
1863
1953
|
break;
|
|
1864
1954
|
}
|
|
1865
1955
|
case "assistant": {
|
|
1956
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1866
1957
|
const blocks = [];
|
|
1867
1958
|
blocks.push(...toContentBlocks(message.content));
|
|
1868
1959
|
if (message.tool_calls?.length) {
|
|
@@ -1875,6 +1966,7 @@ var toAnthropicMessages = (messages) => {
|
|
|
1875
1966
|
break;
|
|
1876
1967
|
}
|
|
1877
1968
|
case "user": {
|
|
1969
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1878
1970
|
const blocks = ensureToolResultBlocks(toContentBlocks(message.content));
|
|
1879
1971
|
output.push({
|
|
1880
1972
|
role: "user",
|
|
@@ -1886,19 +1978,23 @@ var toAnthropicMessages = (messages) => {
|
|
|
1886
1978
|
break;
|
|
1887
1979
|
}
|
|
1888
1980
|
}
|
|
1981
|
+
mergePendingToolResults(pendingToolResults, output);
|
|
1889
1982
|
const system = systemParts.length ? systemParts.join("\n\n") : void 0;
|
|
1890
|
-
return { system, messages: output };
|
|
1983
|
+
return { system, messages: dropOrphanToolUseBlocks(output) };
|
|
1891
1984
|
};
|
|
1892
1985
|
var extractText = (blocks) => blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
1893
1986
|
var toUsage = (response) => {
|
|
1894
1987
|
if (!response.usage) return null;
|
|
1895
|
-
const
|
|
1988
|
+
const baseInputTokens = response.usage.input_tokens ?? 0;
|
|
1989
|
+
const cacheCreateTokens = response.usage.cache_creation_input_tokens ?? 0;
|
|
1990
|
+
const cacheReadTokens = response.usage.cache_read_input_tokens ?? 0;
|
|
1991
|
+
const inputTokens = baseInputTokens + cacheCreateTokens + cacheReadTokens;
|
|
1896
1992
|
const outputTokens = response.usage.output_tokens ?? 0;
|
|
1897
1993
|
return {
|
|
1898
1994
|
model: response.model ?? "",
|
|
1899
1995
|
input_tokens: inputTokens,
|
|
1900
|
-
input_cached_tokens:
|
|
1901
|
-
input_cache_creation_tokens:
|
|
1996
|
+
input_cached_tokens: cacheReadTokens,
|
|
1997
|
+
input_cache_creation_tokens: cacheCreateTokens,
|
|
1902
1998
|
output_tokens: outputTokens,
|
|
1903
1999
|
total_tokens: inputTokens + outputTokens
|
|
1904
2000
|
};
|
|
@@ -2002,6 +2098,9 @@ var toAnthropicHostedSearchTool = (tool) => {
|
|
|
2002
2098
|
var PROVIDER_NAME = "anthropic";
|
|
2003
2099
|
var DEFAULT_MODEL = ANTHROPIC_DEFAULT_MODEL;
|
|
2004
2100
|
var DEFAULT_MAX_TOKENS = 4096;
|
|
2101
|
+
var DEFAULT_PROMPT_CACHE_CONTROL = {
|
|
2102
|
+
type: "ephemeral"
|
|
2103
|
+
};
|
|
2005
2104
|
var ChatAnthropic = class {
|
|
2006
2105
|
provider = PROVIDER_NAME;
|
|
2007
2106
|
model;
|
|
@@ -2037,6 +2136,9 @@ var ChatAnthropic = class {
|
|
|
2037
2136
|
...tools ? { tools } : {},
|
|
2038
2137
|
...tool_choice ? { tool_choice } : {}
|
|
2039
2138
|
};
|
|
2139
|
+
if (request.cache_control === void 0) {
|
|
2140
|
+
request.cache_control = DEFAULT_PROMPT_CACHE_CONTROL;
|
|
2141
|
+
}
|
|
2040
2142
|
const debugSeq = this.nextDebugInvokeSeq();
|
|
2041
2143
|
await this.debugRequestIfEnabled(request, debugSeq);
|
|
2042
2144
|
const response = await this.client.messages.create(
|
|
@@ -2131,8 +2233,8 @@ var ChatAnthropic = class {
|
|
|
2131
2233
|
};
|
|
2132
2234
|
|
|
2133
2235
|
// src/llm/openai/chat.ts
|
|
2134
|
-
import OpenAI from "openai";
|
|
2135
2236
|
import { createHash as createHash2 } from "crypto";
|
|
2237
|
+
import OpenAI from "openai";
|
|
2136
2238
|
|
|
2137
2239
|
// src/llm/openai/response-utils.ts
|
|
2138
2240
|
var isRecord2 = (value) => typeof value === "object" && value !== null;
|
|
@@ -2260,16 +2362,6 @@ var isOpenAIAssistantInputContent = (value) => {
|
|
|
2260
2362
|
}
|
|
2261
2363
|
return false;
|
|
2262
2364
|
};
|
|
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
2365
|
var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
2274
2366
|
if (!value || typeof value !== "object") {
|
|
2275
2367
|
return false;
|
|
@@ -2277,6 +2369,12 @@ var isReplayableOpenAIFunctionCallItem = (value) => {
|
|
|
2277
2369
|
const record = value;
|
|
2278
2370
|
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
2279
2371
|
};
|
|
2372
|
+
var toReplayableFunctionCallItemId = (value) => {
|
|
2373
|
+
if (typeof value !== "string") {
|
|
2374
|
+
return void 0;
|
|
2375
|
+
}
|
|
2376
|
+
return value.startsWith("fc") ? value : void 0;
|
|
2377
|
+
};
|
|
2280
2378
|
var toAssistantInputContent = (part) => {
|
|
2281
2379
|
switch (part.type) {
|
|
2282
2380
|
case "text":
|
|
@@ -2437,9 +2535,6 @@ function toResponsesInput(messages) {
|
|
|
2437
2535
|
continue;
|
|
2438
2536
|
}
|
|
2439
2537
|
if (message.role === "reasoning") {
|
|
2440
|
-
if (isReplayableOpenAIHistoryItem(message.raw_item)) {
|
|
2441
|
-
items.push(message.raw_item);
|
|
2442
|
-
}
|
|
2443
2538
|
continue;
|
|
2444
2539
|
}
|
|
2445
2540
|
if (message.role === "assistant") {
|
|
@@ -2534,8 +2629,16 @@ function toAssistantMessageItem(message) {
|
|
|
2534
2629
|
}
|
|
2535
2630
|
function toFunctionCallItem(call) {
|
|
2536
2631
|
if (isReplayableOpenAIFunctionCallItem(call.provider_meta)) {
|
|
2537
|
-
const
|
|
2538
|
-
|
|
2632
|
+
const replayable = call.provider_meta;
|
|
2633
|
+
const replayableId = toReplayableFunctionCallItemId(replayable.id);
|
|
2634
|
+
return {
|
|
2635
|
+
type: "function_call",
|
|
2636
|
+
call_id: replayable.call_id,
|
|
2637
|
+
name: replayable.name,
|
|
2638
|
+
arguments: replayable.arguments,
|
|
2639
|
+
...replayableId ? { id: replayableId } : {},
|
|
2640
|
+
...typeof replayable.status === "string" ? { status: replayable.status } : {}
|
|
2641
|
+
};
|
|
2539
2642
|
}
|
|
2540
2643
|
return {
|
|
2541
2644
|
type: "function_call",
|
|
@@ -2551,8 +2654,9 @@ function toFunctionCallOutputItem(message) {
|
|
|
2551
2654
|
output: toFunctionCallOutput(message.content)
|
|
2552
2655
|
};
|
|
2553
2656
|
}
|
|
2657
|
+
var isResponsesHostedSearchProvider = (provider) => provider === void 0 || provider === "openai" || provider === "openrouter";
|
|
2554
2658
|
function toOpenAiHostedSearchTool(tool) {
|
|
2555
|
-
if (tool.provider
|
|
2659
|
+
if (!isResponsesHostedSearchProvider(tool.provider)) {
|
|
2556
2660
|
return null;
|
|
2557
2661
|
}
|
|
2558
2662
|
const userLocation = tool.user_location ? {
|
|
@@ -2747,6 +2851,630 @@ var ChatOpenAI = class {
|
|
|
2747
2851
|
}
|
|
2748
2852
|
};
|
|
2749
2853
|
|
|
2854
|
+
// src/llm/openrouter/chat.ts
|
|
2855
|
+
import { createHash as createHash3 } from "crypto";
|
|
2856
|
+
import OpenAI2 from "openai";
|
|
2857
|
+
|
|
2858
|
+
// src/llm/openrouter/response-utils.ts
|
|
2859
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null;
|
|
2860
|
+
var stringifyUnknown5 = (value) => {
|
|
2861
|
+
if (value == null) return "";
|
|
2862
|
+
if (typeof value === "string") return value;
|
|
2863
|
+
try {
|
|
2864
|
+
return JSON.stringify(value);
|
|
2865
|
+
} catch {
|
|
2866
|
+
return String(value);
|
|
2867
|
+
}
|
|
2868
|
+
};
|
|
2869
|
+
var formatOtherPart4 = (part) => {
|
|
2870
|
+
const payloadText = stringifyUnknown5(part.payload);
|
|
2871
|
+
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
2872
|
+
};
|
|
2873
|
+
var isResponsesApiInputContent = (value) => {
|
|
2874
|
+
if (!isRecord3(value)) return false;
|
|
2875
|
+
const type = value.type;
|
|
2876
|
+
if (type === "input_text") {
|
|
2877
|
+
return typeof value.text === "string";
|
|
2878
|
+
}
|
|
2879
|
+
if (type === "input_image") {
|
|
2880
|
+
return typeof value.image_url === "string";
|
|
2881
|
+
}
|
|
2882
|
+
if (type === "input_file") {
|
|
2883
|
+
return typeof value.file_data === "string" || typeof value.file_id === "string";
|
|
2884
|
+
}
|
|
2885
|
+
return false;
|
|
2886
|
+
};
|
|
2887
|
+
var isOpenRouterReplayableOtherPart = (part) => (part.provider === "openrouter" || part.provider === "openai") && isResponsesApiInputContent(part.payload);
|
|
2888
|
+
var extractOutputText2 = (items) => {
|
|
2889
|
+
const texts = [];
|
|
2890
|
+
for (const item of items) {
|
|
2891
|
+
if (item.type !== "message") continue;
|
|
2892
|
+
for (const part of item.content ?? []) {
|
|
2893
|
+
if (part.type === "output_text") {
|
|
2894
|
+
texts.push(part.text);
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
return texts.join("");
|
|
2899
|
+
};
|
|
2900
|
+
var toResponseInputContent2 = (part) => {
|
|
2901
|
+
switch (part.type) {
|
|
2902
|
+
case "text":
|
|
2903
|
+
return { type: "input_text", text: part.text };
|
|
2904
|
+
case "image_url":
|
|
2905
|
+
return {
|
|
2906
|
+
type: "input_image",
|
|
2907
|
+
image_url: part.image_url.url,
|
|
2908
|
+
detail: part.image_url.detail ?? "auto"
|
|
2909
|
+
};
|
|
2910
|
+
case "document":
|
|
2911
|
+
return {
|
|
2912
|
+
type: "input_file",
|
|
2913
|
+
file_data: part.source.data,
|
|
2914
|
+
filename: "document.pdf"
|
|
2915
|
+
};
|
|
2916
|
+
case "other":
|
|
2917
|
+
if (isOpenRouterReplayableOtherPart(part)) {
|
|
2918
|
+
return part.payload;
|
|
2919
|
+
}
|
|
2920
|
+
return { type: "input_text", text: formatOtherPart4(part) };
|
|
2921
|
+
default:
|
|
2922
|
+
return { type: "input_text", text: "" };
|
|
2923
|
+
}
|
|
2924
|
+
};
|
|
2925
|
+
var toResponseInputContents2 = (content) => {
|
|
2926
|
+
if (content == null) {
|
|
2927
|
+
return "";
|
|
2928
|
+
}
|
|
2929
|
+
if (typeof content === "string") {
|
|
2930
|
+
return content;
|
|
2931
|
+
}
|
|
2932
|
+
return content.map(toResponseInputContent2);
|
|
2933
|
+
};
|
|
2934
|
+
var toFunctionCallOutput2 = (content) => {
|
|
2935
|
+
if (typeof content === "string") {
|
|
2936
|
+
return content;
|
|
2937
|
+
}
|
|
2938
|
+
return content.map(toResponseInputContent2);
|
|
2939
|
+
};
|
|
2940
|
+
|
|
2941
|
+
// src/llm/openrouter/serializer.ts
|
|
2942
|
+
var toOpenRouterOtherPart = (kind, payload) => ({
|
|
2943
|
+
type: "other",
|
|
2944
|
+
provider: "openrouter",
|
|
2945
|
+
kind,
|
|
2946
|
+
payload
|
|
2947
|
+
});
|
|
2948
|
+
var toAssistantOutputMessageContent2 = (item) => {
|
|
2949
|
+
const contents = item.content ?? [];
|
|
2950
|
+
if (contents.length === 0) {
|
|
2951
|
+
return null;
|
|
2952
|
+
}
|
|
2953
|
+
const parts = contents.map((part) => {
|
|
2954
|
+
if (part.type === "output_text") {
|
|
2955
|
+
return { type: "text", text: part.text };
|
|
2956
|
+
}
|
|
2957
|
+
return toOpenRouterOtherPart(part.type, part);
|
|
2958
|
+
});
|
|
2959
|
+
return parts;
|
|
2960
|
+
};
|
|
2961
|
+
var stringifyUnknown6 = (value) => {
|
|
2962
|
+
if (value == null) return "";
|
|
2963
|
+
if (typeof value === "string") return value;
|
|
2964
|
+
try {
|
|
2965
|
+
return JSON.stringify(value);
|
|
2966
|
+
} catch {
|
|
2967
|
+
return String(value);
|
|
2968
|
+
}
|
|
2969
|
+
};
|
|
2970
|
+
var formatOtherPart5 = (part) => {
|
|
2971
|
+
const payloadText = stringifyUnknown6(part.payload);
|
|
2972
|
+
return payloadText ? `[other:${part.provider}/${part.kind}] ${payloadText}` : `[other:${part.provider}/${part.kind}]`;
|
|
2973
|
+
};
|
|
2974
|
+
var isOpenAIAssistantInputContent2 = (value) => {
|
|
2975
|
+
if (!value || typeof value !== "object") return false;
|
|
2976
|
+
const record = value;
|
|
2977
|
+
if (record.type === "output_text") {
|
|
2978
|
+
return typeof record.text === "string";
|
|
2979
|
+
}
|
|
2980
|
+
if (record.type === "refusal") {
|
|
2981
|
+
return typeof record.refusal === "string";
|
|
2982
|
+
}
|
|
2983
|
+
return false;
|
|
2984
|
+
};
|
|
2985
|
+
var isReplayableOpenAIFunctionCallItem2 = (value) => {
|
|
2986
|
+
if (!value || typeof value !== "object") {
|
|
2987
|
+
return false;
|
|
2988
|
+
}
|
|
2989
|
+
const record = value;
|
|
2990
|
+
return record.type === "function_call" && typeof record.call_id === "string" && typeof record.name === "string" && typeof record.arguments === "string";
|
|
2991
|
+
};
|
|
2992
|
+
var toReplayableFunctionCallItemId2 = (value) => {
|
|
2993
|
+
if (typeof value !== "string") {
|
|
2994
|
+
return void 0;
|
|
2995
|
+
}
|
|
2996
|
+
return value.startsWith("fc") ? value : void 0;
|
|
2997
|
+
};
|
|
2998
|
+
var toAssistantInputContent2 = (part) => {
|
|
2999
|
+
switch (part.type) {
|
|
3000
|
+
case "text":
|
|
3001
|
+
return { type: "output_text", text: part.text };
|
|
3002
|
+
case "other":
|
|
3003
|
+
if ((part.provider === "openrouter" || part.provider === "openai") && isOpenAIAssistantInputContent2(part.payload)) {
|
|
3004
|
+
return part.payload;
|
|
3005
|
+
}
|
|
3006
|
+
return { type: "output_text", text: formatOtherPart5(part) };
|
|
3007
|
+
case "image_url":
|
|
3008
|
+
return { type: "output_text", text: "[image]" };
|
|
3009
|
+
case "document":
|
|
3010
|
+
return { type: "output_text", text: "[document]" };
|
|
3011
|
+
default:
|
|
3012
|
+
return { type: "output_text", text: "" };
|
|
3013
|
+
}
|
|
3014
|
+
};
|
|
3015
|
+
var toAssistantInputMessageContent2 = (content, refusal) => {
|
|
3016
|
+
const parts = [];
|
|
3017
|
+
if (typeof content === "string") {
|
|
3018
|
+
if (content) {
|
|
3019
|
+
parts.push({ type: "output_text", text: content });
|
|
3020
|
+
}
|
|
3021
|
+
} else if (Array.isArray(content)) {
|
|
3022
|
+
parts.push(...content.map(toAssistantInputContent2));
|
|
3023
|
+
}
|
|
3024
|
+
if (refusal) {
|
|
3025
|
+
parts.push({ type: "refusal", refusal });
|
|
3026
|
+
}
|
|
3027
|
+
return parts;
|
|
3028
|
+
};
|
|
3029
|
+
var extractReasoningText2 = (item) => {
|
|
3030
|
+
const summaryText = (item.summary ?? []).map(
|
|
3031
|
+
(part) => part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""
|
|
3032
|
+
).filter((text) => text.length > 0).join("\n");
|
|
3033
|
+
if (summaryText) return summaryText;
|
|
3034
|
+
const contentText = (item.content ?? []).map(
|
|
3035
|
+
(part) => part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""
|
|
3036
|
+
).filter((text) => text.length > 0).join("\n");
|
|
3037
|
+
return contentText;
|
|
3038
|
+
};
|
|
3039
|
+
var extractWebSearchSummary2 = (item) => {
|
|
3040
|
+
const parts = [`WebSearch status=${item.status}`];
|
|
3041
|
+
const record = item;
|
|
3042
|
+
const queries = Array.isArray(record.action?.queries) ? record.action?.queries.filter(
|
|
3043
|
+
(entry) => typeof entry === "string" && entry.length > 0
|
|
3044
|
+
) : [];
|
|
3045
|
+
if (queries.length) {
|
|
3046
|
+
parts.push(`queries=${queries.join(" | ")}`);
|
|
3047
|
+
}
|
|
3048
|
+
const sources = Array.isArray(record.action?.sources) ? record.action?.sources : [];
|
|
3049
|
+
if (sources.length) {
|
|
3050
|
+
parts.push(`sources=${sources.length}`);
|
|
3051
|
+
}
|
|
3052
|
+
return parts.join(" | ");
|
|
3053
|
+
};
|
|
3054
|
+
var toMessageSequence2 = (response) => {
|
|
3055
|
+
const messages = [];
|
|
3056
|
+
for (const item of response.output) {
|
|
3057
|
+
switch (item.type) {
|
|
3058
|
+
case "reasoning": {
|
|
3059
|
+
messages.push({
|
|
3060
|
+
role: "reasoning",
|
|
3061
|
+
content: extractReasoningText2(item),
|
|
3062
|
+
raw_item: item
|
|
3063
|
+
});
|
|
3064
|
+
break;
|
|
3065
|
+
}
|
|
3066
|
+
case "function_call": {
|
|
3067
|
+
const toolCall = {
|
|
3068
|
+
id: item.call_id,
|
|
3069
|
+
type: "function",
|
|
3070
|
+
function: { name: item.name, arguments: item.arguments },
|
|
3071
|
+
provider_meta: item
|
|
3072
|
+
};
|
|
3073
|
+
messages.push({
|
|
3074
|
+
role: "assistant",
|
|
3075
|
+
content: null,
|
|
3076
|
+
tool_calls: [toolCall]
|
|
3077
|
+
});
|
|
3078
|
+
break;
|
|
3079
|
+
}
|
|
3080
|
+
case "message": {
|
|
3081
|
+
messages.push({
|
|
3082
|
+
role: "assistant",
|
|
3083
|
+
content: toAssistantOutputMessageContent2(item)
|
|
3084
|
+
});
|
|
3085
|
+
break;
|
|
3086
|
+
}
|
|
3087
|
+
case "web_search_call": {
|
|
3088
|
+
messages.push({
|
|
3089
|
+
role: "reasoning",
|
|
3090
|
+
content: extractWebSearchSummary2(item),
|
|
3091
|
+
raw_item: item
|
|
3092
|
+
});
|
|
3093
|
+
break;
|
|
3094
|
+
}
|
|
3095
|
+
default: {
|
|
3096
|
+
messages.push({
|
|
3097
|
+
role: "assistant",
|
|
3098
|
+
content: [toOpenRouterOtherPart(item.type, item)]
|
|
3099
|
+
});
|
|
3100
|
+
break;
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
return messages;
|
|
3105
|
+
};
|
|
3106
|
+
function extractInstructions2(messages) {
|
|
3107
|
+
const chunks = [];
|
|
3108
|
+
for (const message of messages) {
|
|
3109
|
+
if (message.role !== "system") {
|
|
3110
|
+
continue;
|
|
3111
|
+
}
|
|
3112
|
+
const content = message.content;
|
|
3113
|
+
if (content == null) {
|
|
3114
|
+
continue;
|
|
3115
|
+
}
|
|
3116
|
+
if (typeof content === "string") {
|
|
3117
|
+
const trimmed = content.trim();
|
|
3118
|
+
if (trimmed) {
|
|
3119
|
+
chunks.push(trimmed);
|
|
3120
|
+
}
|
|
3121
|
+
continue;
|
|
3122
|
+
}
|
|
3123
|
+
const text = content.map((part) => {
|
|
3124
|
+
switch (part.type) {
|
|
3125
|
+
case "text":
|
|
3126
|
+
return part.text;
|
|
3127
|
+
default:
|
|
3128
|
+
return "";
|
|
3129
|
+
}
|
|
3130
|
+
}).join("").trim();
|
|
3131
|
+
if (text) {
|
|
3132
|
+
chunks.push(text);
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
return chunks.length ? chunks.join("\n\n") : void 0;
|
|
3136
|
+
}
|
|
3137
|
+
function toResponsesInput2(messages) {
|
|
3138
|
+
const items = [];
|
|
3139
|
+
for (const message of messages) {
|
|
3140
|
+
if (message.role === "system") {
|
|
3141
|
+
continue;
|
|
3142
|
+
}
|
|
3143
|
+
if (message.role === "tool") {
|
|
3144
|
+
items.push(toFunctionCallOutputItem2(message));
|
|
3145
|
+
continue;
|
|
3146
|
+
}
|
|
3147
|
+
if (message.role === "assistant" && message.tool_calls?.length) {
|
|
3148
|
+
const assistantMessageItem = toAssistantMessageItem2(message);
|
|
3149
|
+
if (assistantMessageItem) {
|
|
3150
|
+
items.push(assistantMessageItem);
|
|
3151
|
+
}
|
|
3152
|
+
for (const call of message.tool_calls) {
|
|
3153
|
+
items.push(toFunctionCallItem2(call));
|
|
3154
|
+
}
|
|
3155
|
+
continue;
|
|
3156
|
+
}
|
|
3157
|
+
if (message.role === "reasoning") {
|
|
3158
|
+
continue;
|
|
3159
|
+
}
|
|
3160
|
+
if (message.role === "assistant") {
|
|
3161
|
+
const assistantMessageItem = toAssistantMessageItem2(message);
|
|
3162
|
+
if (assistantMessageItem) {
|
|
3163
|
+
items.push(assistantMessageItem);
|
|
3164
|
+
}
|
|
3165
|
+
continue;
|
|
3166
|
+
}
|
|
3167
|
+
items.push({
|
|
3168
|
+
type: "message",
|
|
3169
|
+
role: message.role,
|
|
3170
|
+
content: toUserMessageContent2(message.content)
|
|
3171
|
+
});
|
|
3172
|
+
}
|
|
3173
|
+
return items;
|
|
3174
|
+
}
|
|
3175
|
+
function toResponsesTools2(tools) {
|
|
3176
|
+
if (!tools || tools.length === 0) {
|
|
3177
|
+
return void 0;
|
|
3178
|
+
}
|
|
3179
|
+
const mapped = [];
|
|
3180
|
+
for (const tool of tools) {
|
|
3181
|
+
if (isFunctionToolDefinition(tool)) {
|
|
3182
|
+
mapped.push({
|
|
3183
|
+
type: "function",
|
|
3184
|
+
name: tool.name,
|
|
3185
|
+
description: tool.description,
|
|
3186
|
+
parameters: tool.parameters,
|
|
3187
|
+
strict: tool.strict ?? false
|
|
3188
|
+
});
|
|
3189
|
+
continue;
|
|
3190
|
+
}
|
|
3191
|
+
if (isHostedSearchToolDefinition(tool)) {
|
|
3192
|
+
const hosted = toOpenRouterHostedSearchTool(tool);
|
|
3193
|
+
if (hosted) {
|
|
3194
|
+
mapped.push(hosted);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
return mapped.length ? mapped : void 0;
|
|
3199
|
+
}
|
|
3200
|
+
function toResponsesToolChoice2(choice) {
|
|
3201
|
+
if (!choice) {
|
|
3202
|
+
return void 0;
|
|
3203
|
+
}
|
|
3204
|
+
if (choice === "auto" || choice === "required" || choice === "none") {
|
|
3205
|
+
return choice;
|
|
3206
|
+
}
|
|
3207
|
+
return { type: "function", name: choice };
|
|
3208
|
+
}
|
|
3209
|
+
function toChatInvokeCompletion3(response) {
|
|
3210
|
+
const usage = response.usage ? {
|
|
3211
|
+
model: response.model,
|
|
3212
|
+
input_tokens: response.usage.input_tokens,
|
|
3213
|
+
input_cached_tokens: response.usage.input_tokens_details?.cached_tokens,
|
|
3214
|
+
output_tokens: response.usage.output_tokens,
|
|
3215
|
+
total_tokens: response.usage.total_tokens
|
|
3216
|
+
} : null;
|
|
3217
|
+
const messages = toMessageSequence2(response);
|
|
3218
|
+
if (!messages.length) {
|
|
3219
|
+
const fallbackText = typeof response.output_text === "string" ? response.output_text : extractOutputText2(response.output);
|
|
3220
|
+
if (fallbackText) {
|
|
3221
|
+
messages.push({ role: "assistant", content: fallbackText });
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
return {
|
|
3225
|
+
messages,
|
|
3226
|
+
usage,
|
|
3227
|
+
stop_reason: response.incomplete_details?.reason ?? response.status ?? null,
|
|
3228
|
+
provider_meta: {
|
|
3229
|
+
response_id: response.id
|
|
3230
|
+
}
|
|
3231
|
+
};
|
|
3232
|
+
}
|
|
3233
|
+
function toUserMessageContent2(content) {
|
|
3234
|
+
return toResponseInputContents2(content);
|
|
3235
|
+
}
|
|
3236
|
+
function toAssistantMessageItem2(message) {
|
|
3237
|
+
const content = toAssistantInputMessageContent2(
|
|
3238
|
+
message.content,
|
|
3239
|
+
message.refusal
|
|
3240
|
+
);
|
|
3241
|
+
if (content.length === 0) {
|
|
3242
|
+
return null;
|
|
3243
|
+
}
|
|
3244
|
+
return {
|
|
3245
|
+
type: "message",
|
|
3246
|
+
role: "assistant",
|
|
3247
|
+
content
|
|
3248
|
+
};
|
|
3249
|
+
}
|
|
3250
|
+
function toFunctionCallItem2(call) {
|
|
3251
|
+
if (isReplayableOpenAIFunctionCallItem2(call.provider_meta)) {
|
|
3252
|
+
const replayable = call.provider_meta;
|
|
3253
|
+
const replayableId = toReplayableFunctionCallItemId2(replayable.id);
|
|
3254
|
+
return {
|
|
3255
|
+
type: "function_call",
|
|
3256
|
+
call_id: replayable.call_id,
|
|
3257
|
+
name: replayable.name,
|
|
3258
|
+
arguments: replayable.arguments,
|
|
3259
|
+
...replayableId ? { id: replayableId } : {},
|
|
3260
|
+
...typeof replayable.status === "string" ? { status: replayable.status } : {}
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
return {
|
|
3264
|
+
type: "function_call",
|
|
3265
|
+
call_id: call.id,
|
|
3266
|
+
name: call.function.name,
|
|
3267
|
+
arguments: call.function.arguments
|
|
3268
|
+
};
|
|
3269
|
+
}
|
|
3270
|
+
function toFunctionCallOutputItem2(message) {
|
|
3271
|
+
return {
|
|
3272
|
+
type: "function_call_output",
|
|
3273
|
+
call_id: message.tool_call_id,
|
|
3274
|
+
output: toFunctionCallOutput2(message.content)
|
|
3275
|
+
};
|
|
3276
|
+
}
|
|
3277
|
+
var isResponsesHostedSearchProvider2 = (provider) => provider === void 0 || provider === "openai" || provider === "openrouter";
|
|
3278
|
+
function toOpenRouterHostedSearchTool(tool) {
|
|
3279
|
+
if (!isResponsesHostedSearchProvider2(tool.provider)) {
|
|
3280
|
+
return null;
|
|
3281
|
+
}
|
|
3282
|
+
const userLocation = tool.user_location ? {
|
|
3283
|
+
type: "approximate",
|
|
3284
|
+
...tool.user_location.city ? { city: tool.user_location.city } : {},
|
|
3285
|
+
...tool.user_location.country ? { country: tool.user_location.country } : {},
|
|
3286
|
+
...tool.user_location.region ? { region: tool.user_location.region } : {},
|
|
3287
|
+
...tool.user_location.timezone ? { timezone: tool.user_location.timezone } : {}
|
|
3288
|
+
} : void 0;
|
|
3289
|
+
return {
|
|
3290
|
+
type: "web_search",
|
|
3291
|
+
...tool.search_context_size ? { search_context_size: tool.search_context_size } : {},
|
|
3292
|
+
...tool.allowed_domains?.length ? {
|
|
3293
|
+
filters: {
|
|
3294
|
+
allowed_domains: tool.allowed_domains
|
|
3295
|
+
}
|
|
3296
|
+
} : {},
|
|
3297
|
+
...userLocation ? { user_location: userLocation } : {}
|
|
3298
|
+
};
|
|
3299
|
+
}
|
|
3300
|
+
|
|
3301
|
+
// src/llm/openrouter/chat.ts
|
|
3302
|
+
var PROVIDER_NAME3 = "openrouter";
|
|
3303
|
+
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
3304
|
+
var DEFAULT_MODEL3 = OPENAI_DEFAULT_MODEL;
|
|
3305
|
+
var DEFAULT_REASONING_EFFORT2 = OPENAI_DEFAULT_REASONING_EFFORT;
|
|
3306
|
+
var DEFAULT_REASONING_SUMMARY2 = "auto";
|
|
3307
|
+
var getSessionIdHeaderValue2 = (promptCacheKey) => {
|
|
3308
|
+
return typeof promptCacheKey === "string" && promptCacheKey.length > 0 ? promptCacheKey : void 0;
|
|
3309
|
+
};
|
|
3310
|
+
var ChatOpenRouter = class {
|
|
3311
|
+
provider = PROVIDER_NAME3;
|
|
3312
|
+
model;
|
|
3313
|
+
client;
|
|
3314
|
+
defaultReasoningEffort;
|
|
3315
|
+
defaultTextVerbosity;
|
|
3316
|
+
debugInvokeSeq = 0;
|
|
3317
|
+
lastDebugRequestPayload = null;
|
|
3318
|
+
constructor(options = {}) {
|
|
3319
|
+
this.client = options.client ?? new OpenAI2({
|
|
3320
|
+
baseURL: OPENROUTER_BASE_URL,
|
|
3321
|
+
...options.clientOptions ?? {}
|
|
3322
|
+
});
|
|
3323
|
+
this.model = options.model ?? DEFAULT_MODEL3;
|
|
3324
|
+
this.defaultReasoningEffort = options.reasoningEffort ?? DEFAULT_REASONING_EFFORT2;
|
|
3325
|
+
this.defaultTextVerbosity = options.textVerbosity;
|
|
3326
|
+
}
|
|
3327
|
+
async ainvoke(input, context) {
|
|
3328
|
+
const {
|
|
3329
|
+
messages,
|
|
3330
|
+
tools: toolDefs,
|
|
3331
|
+
toolChoice,
|
|
3332
|
+
options,
|
|
3333
|
+
model,
|
|
3334
|
+
signal
|
|
3335
|
+
} = input;
|
|
3336
|
+
const inputItems = toResponsesInput2(messages);
|
|
3337
|
+
const instructions = extractInstructions2(messages);
|
|
3338
|
+
const tools = toResponsesTools2(toolDefs);
|
|
3339
|
+
const tool_choice = toResponsesToolChoice2(toolChoice);
|
|
3340
|
+
const { reasoningEffort, textVerbosity, ...rest } = options ?? {};
|
|
3341
|
+
const request = {
|
|
3342
|
+
model: model ?? this.model,
|
|
3343
|
+
input: inputItems,
|
|
3344
|
+
...rest,
|
|
3345
|
+
...tools ? { tools } : {},
|
|
3346
|
+
...tool_choice ? { tool_choice } : {}
|
|
3347
|
+
};
|
|
3348
|
+
if (request.store === void 0) {
|
|
3349
|
+
request.store = false;
|
|
3350
|
+
}
|
|
3351
|
+
if (instructions) {
|
|
3352
|
+
request.instructions = instructions;
|
|
3353
|
+
}
|
|
3354
|
+
const hasWebSearchTool = tools?.some(
|
|
3355
|
+
(tool) => tool.type === "web_search" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11"
|
|
3356
|
+
);
|
|
3357
|
+
const includeSet = new Set(request.include ?? []);
|
|
3358
|
+
includeSet.add("reasoning.encrypted_content");
|
|
3359
|
+
if (hasWebSearchTool) {
|
|
3360
|
+
includeSet.add("web_search_call.action.sources");
|
|
3361
|
+
includeSet.add("web_search_call.results");
|
|
3362
|
+
}
|
|
3363
|
+
request.include = Array.from(includeSet);
|
|
3364
|
+
const effort = reasoningEffort ?? this.defaultReasoningEffort;
|
|
3365
|
+
request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY2 };
|
|
3366
|
+
const verbosity = textVerbosity ?? this.defaultTextVerbosity;
|
|
3367
|
+
if (verbosity) {
|
|
3368
|
+
request.text = {
|
|
3369
|
+
...request.text ?? {},
|
|
3370
|
+
verbosity
|
|
3371
|
+
};
|
|
3372
|
+
}
|
|
3373
|
+
if (context?.sessionKey && !request.prompt_cache_key) {
|
|
3374
|
+
request.prompt_cache_key = context.sessionKey;
|
|
3375
|
+
}
|
|
3376
|
+
const sessionIdHeader = getSessionIdHeaderValue2(request.prompt_cache_key);
|
|
3377
|
+
const debugSeq = this.nextDebugInvokeSeq();
|
|
3378
|
+
await this.debugRequestIfEnabled(request, debugSeq, sessionIdHeader);
|
|
3379
|
+
const streamRequest = {
|
|
3380
|
+
...request,
|
|
3381
|
+
stream: true
|
|
3382
|
+
};
|
|
3383
|
+
const response = await this.client.responses.stream(
|
|
3384
|
+
streamRequest,
|
|
3385
|
+
signal || sessionIdHeader ? {
|
|
3386
|
+
...signal ? { signal } : {},
|
|
3387
|
+
...sessionIdHeader ? {
|
|
3388
|
+
headers: {
|
|
3389
|
+
session_id: sessionIdHeader
|
|
3390
|
+
}
|
|
3391
|
+
} : {}
|
|
3392
|
+
} : void 0
|
|
3393
|
+
).finalResponse();
|
|
3394
|
+
await this.debugResponseIfEnabled(response, debugSeq);
|
|
3395
|
+
return toChatInvokeCompletion3(response);
|
|
3396
|
+
}
|
|
3397
|
+
nextDebugInvokeSeq() {
|
|
3398
|
+
const seq = this.debugInvokeSeq + 1;
|
|
3399
|
+
this.debugInvokeSeq = seq;
|
|
3400
|
+
return seq;
|
|
3401
|
+
}
|
|
3402
|
+
async debugRequestIfEnabled(request, seq, sessionIdHeader) {
|
|
3403
|
+
const settings = getProviderLogSettings();
|
|
3404
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3405
|
+
return;
|
|
3406
|
+
}
|
|
3407
|
+
const payload = safeJsonStringify(request);
|
|
3408
|
+
const hash = createHash3("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3409
|
+
const toolsHash = createHash3("sha256").update(safeJsonStringify(request.tools ?? [])).digest("hex").slice(0, 12);
|
|
3410
|
+
const instructionsHash = createHash3("sha256").update(String(request.instructions ?? "")).digest("hex").slice(0, 12);
|
|
3411
|
+
const previous = this.lastDebugRequestPayload;
|
|
3412
|
+
const shared = previous ? sharedPrefixChars(previous, payload) : payload.length;
|
|
3413
|
+
const sharedRatio = payload.length ? (shared / payload.length * 100).toFixed(1) : "100.0";
|
|
3414
|
+
if (settings.enabled) {
|
|
3415
|
+
const sessionHeaderSuffix = sessionIdHeader ? ` session_id_header=on session_id_hash=${createHash3("sha256").update(sessionIdHeader).digest("hex").slice(0, 12)}` : " session_id_header=off";
|
|
3416
|
+
console.error(
|
|
3417
|
+
`[openrouter.request] seq=${seq} bytes=${payload.length} sha256_16=${hash} shared_prefix=${shared} shared_ratio=${sharedRatio}% tools_sha=${toolsHash} instructions_sha=${instructionsHash}${sessionHeaderSuffix}`
|
|
3418
|
+
);
|
|
3419
|
+
}
|
|
3420
|
+
if (settings.dumpDir) {
|
|
3421
|
+
try {
|
|
3422
|
+
await writeProviderLogDump(
|
|
3423
|
+
settings,
|
|
3424
|
+
PROVIDER_NAME3,
|
|
3425
|
+
seq,
|
|
3426
|
+
"request",
|
|
3427
|
+
request
|
|
3428
|
+
);
|
|
3429
|
+
} catch (error) {
|
|
3430
|
+
if (settings.enabled) {
|
|
3431
|
+
console.error(
|
|
3432
|
+
`[openrouter.request] dump_failed seq=${seq} error=${String(error)}`
|
|
3433
|
+
);
|
|
3434
|
+
}
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
this.lastDebugRequestPayload = payload;
|
|
3438
|
+
}
|
|
3439
|
+
async debugResponseIfEnabled(response, seq) {
|
|
3440
|
+
const settings = getProviderLogSettings();
|
|
3441
|
+
if (!settings.enabled && !settings.dumpDir) {
|
|
3442
|
+
return;
|
|
3443
|
+
}
|
|
3444
|
+
if (settings.enabled) {
|
|
3445
|
+
const usage = response.usage;
|
|
3446
|
+
const cachedInputTokens = usage?.input_tokens_details?.cached_tokens ?? 0;
|
|
3447
|
+
const outputItems = Array.isArray(response.output) ? response.output : [];
|
|
3448
|
+
const outputKinds = /* @__PURE__ */ new Set();
|
|
3449
|
+
for (const item of outputItems) {
|
|
3450
|
+
const kind = item && typeof item === "object" && "type" in item ? String(item.type ?? "unknown") : "unknown";
|
|
3451
|
+
outputKinds.add(kind);
|
|
3452
|
+
}
|
|
3453
|
+
const usageIn = usage?.input_tokens ?? 0;
|
|
3454
|
+
console.error(
|
|
3455
|
+
`[openrouter.response] seq=${seq} id=${response.id} status=${response.status} items=${outputItems.length} kinds=${Array.from(outputKinds).join(",")} tok_in=${usageIn} cached_in=${cachedInputTokens}`
|
|
3456
|
+
);
|
|
3457
|
+
}
|
|
3458
|
+
if (settings.dumpDir) {
|
|
3459
|
+
try {
|
|
3460
|
+
await writeProviderLogDump(
|
|
3461
|
+
settings,
|
|
3462
|
+
PROVIDER_NAME3,
|
|
3463
|
+
seq,
|
|
3464
|
+
"response",
|
|
3465
|
+
response
|
|
3466
|
+
);
|
|
3467
|
+
} catch (error) {
|
|
3468
|
+
if (settings.enabled) {
|
|
3469
|
+
console.error(
|
|
3470
|
+
`[openrouter.response] dump_failed seq=${seq} error=${String(error)}`
|
|
3471
|
+
);
|
|
3472
|
+
}
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
};
|
|
3477
|
+
|
|
2750
3478
|
// src/prompts.ts
|
|
2751
3479
|
import path2 from "path";
|
|
2752
3480
|
import { fileURLToPath } from "url";
|
|
@@ -2873,6 +3601,7 @@ export {
|
|
|
2873
3601
|
Agent,
|
|
2874
3602
|
ChatAnthropic,
|
|
2875
3603
|
ChatOpenAI,
|
|
3604
|
+
ChatOpenRouter,
|
|
2876
3605
|
DEFAULT_MODEL_REGISTRY,
|
|
2877
3606
|
GOOGLE_MODELS,
|
|
2878
3607
|
OPENAI_DEFAULT_MODEL,
|