@causyne/agent 1.20.69 → 1.20.70

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/src/commands.js CHANGED
@@ -52,6 +52,15 @@ import { getPackageVersion } from './version.js';
52
52
  import { listGroups } from './checkpoints.js';
53
53
  import { renameSession, getSession } from './sessionStore.js';
54
54
  import { listPlugins } from './plugins/pluginManager.js';
55
+ import {
56
+ getOpenRouterStatus,
57
+ startLoopbackAuth,
58
+ saveOpenRouterKey,
59
+ disconnectOpenRouter,
60
+ setOpenRouterDataCollection,
61
+ buildAuthorizationUrl,
62
+ generatePkceCodes
63
+ } from './auth/openrouterAuth.js';
55
64
 
56
65
  export const SCOPES = ['local'];
57
66
 
@@ -1588,6 +1597,113 @@ export const COMMANDS = [
1588
1597
  }
1589
1598
  },
1590
1599
 
1600
+ {
1601
+ name: 'openrouter',
1602
+ aliases: ['free'],
1603
+ scope: 'local',
1604
+ usage: '/openrouter [status | connect | disconnect | privacy <deny|allow>]',
1605
+ description: 'Connect OpenRouter account for free cloud AI models (openrouter/free)',
1606
+ dialogTitle: 'OpenRouter Free',
1607
+ complete: () => [
1608
+ { value: 'status', label: 'status', description: 'view connection and data collection status' },
1609
+ { value: 'connect', label: 'connect', description: 'connect your OpenRouter account via OAuth PKCE' },
1610
+ { value: 'privacy deny', label: 'privacy deny', description: 'strict privacy (default): restrict provider data collection' },
1611
+ { value: 'privacy allow', label: 'privacy allow', description: 'permit routing to training-eligible providers' },
1612
+ { value: 'disconnect', label: 'disconnect', description: 'disconnect OpenRouter account' }
1613
+ ],
1614
+ run: async (argv, ctx = {}) => {
1615
+ const sub = (argv[0] || 'status').toLowerCase();
1616
+
1617
+ if (sub === 'status') {
1618
+ const status = getOpenRouterStatus();
1619
+ const lines = [
1620
+ 'OpenRouter Free Models — Connection Status',
1621
+ '',
1622
+ ` • Connected : ${status.connected ? 'YES' : 'NO'}`,
1623
+ ` • Active Provider : ${status.active ? 'YES (OpenRouter is active)' : 'NO (using ' + (loadConfig().provider || 'none') + ')'}`,
1624
+ ` • Default Model : ${status.model}`,
1625
+ ` • Privacy Policy : provider.data_collection = "${status.dataCollection}"`,
1626
+ ` • Stored Key : ${status.maskedKey || 'none'} (${status.keySource || 'unconfigured'})`,
1627
+ '',
1628
+ status.connected
1629
+ ? 'OpenRouter Free is ready. Run "/model openrouter/free" to select it.'
1630
+ : 'To connect your account, run "/openrouter connect".'
1631
+ ];
1632
+ return ok(lines.join('\n'));
1633
+ }
1634
+
1635
+ if (sub === 'disconnect') {
1636
+ disconnectOpenRouter();
1637
+ return ok('OpenRouter account disconnected and API key removed from local vault.');
1638
+ }
1639
+
1640
+ if (sub === 'privacy' || sub === 'data-collection') {
1641
+ const val = (argv[1] || '').toLowerCase();
1642
+ if (val !== 'deny' && val !== 'allow') {
1643
+ return fail('Usage: /openrouter privacy <deny | allow>');
1644
+ }
1645
+ setOpenRouterDataCollection(val);
1646
+ const disclosure = val === 'allow'
1647
+ ? '\nNotice: Setting data_collection to "allow" means training-eligible providers are eligible for routing. It does not by itself establish user consent to model training or guarantee training occurs.'
1648
+ : '\nNotice: Strict privacy active. Provider data collection for model training is strictly denied.';
1649
+ return ok(`OpenRouter data_collection policy set to "${val}".${disclosure}`);
1650
+ }
1651
+
1652
+ if (sub === 'connect') {
1653
+ const candidateKey = argv[1];
1654
+ if (candidateKey && candidateKey.trim()) {
1655
+ saveOpenRouterKey(candidateKey.trim(), { setAsActive: true });
1656
+ return ok('Saved OpenRouter API key and switched active model to openrouter/free.');
1657
+ }
1658
+
1659
+ const isSsh = Boolean(process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION);
1660
+ if (isSsh) {
1661
+ const pkce = generatePkceCodes();
1662
+ const authUrl = buildAuthorizationUrl('urn:ietf:wg:oauth:2.0:oob', pkce.codeChallenge, pkce.state);
1663
+ const lines = [
1664
+ 'SSH / Headless environment detected.',
1665
+ 'Please open the following authorization URL in your browser:',
1666
+ '',
1667
+ ` ${authUrl}`,
1668
+ '',
1669
+ 'After authorizing, configure your key using:',
1670
+ ' /openrouter connect <your-api-key>'
1671
+ ];
1672
+ return ok(lines.join('\n'));
1673
+ }
1674
+
1675
+ try {
1676
+ const resultPromise = startLoopbackAuth({
1677
+ timeoutMs: 120_000,
1678
+ openBrowser: true
1679
+ });
1680
+
1681
+ if (ctx.prompt && typeof ctx.prompt.scheduleDraw === 'function') {
1682
+ ctx.prompt.scheduleDraw();
1683
+ }
1684
+
1685
+ const { apiKey } = await resultPromise;
1686
+ saveOpenRouterKey(apiKey, { setAsActive: true });
1687
+
1688
+ if (ctx.loop) {
1689
+ ctx.loop.config = loadConfig();
1690
+ }
1691
+ if (ctx.prompt) {
1692
+ if (typeof ctx.prompt.updateModel === 'function') {
1693
+ ctx.prompt.updateModel('openrouter', 'openrouter/free');
1694
+ }
1695
+ }
1696
+
1697
+ return ok('Successfully authenticated with OpenRouter! Now using openrouter/free.');
1698
+ } catch (err) {
1699
+ return fail(`OpenRouter connection error: ${err.message || err}\nFallback: run "/openrouter connect <api-key>" with an API key from https://openrouter.ai/keys`);
1700
+ }
1701
+ }
1702
+
1703
+ return fail('Usage: /openrouter [status | connect | disconnect | privacy <deny|allow>]');
1704
+ }
1705
+ },
1706
+
1591
1707
  {
1592
1708
  name: 'mcp',
1593
1709
  scope: 'local',
@@ -46,6 +46,8 @@ export function normalizeProviderKey(provider) {
46
46
  return 'moonshot';
47
47
  if (p === 'muse' || p === 'meta')
48
48
  return 'muse';
49
+ if (p === 'openrouter' || p === 'openrouter-free' || p === 'openrouter/free')
50
+ return 'openrouter';
49
51
  if (p === 'openai-compatible' || p === 'custom')
50
52
  return 'openai-compatible';
51
53
  if (p === 'antigravity' || p === 'agy')
@@ -253,6 +255,13 @@ export function getAvailableProvidersOverview(config = {}) {
253
255
  defaultModel: DEFAULT_MODEL_BY_PROVIDER['ollama'] || 'llama3.3',
254
256
  models: MODEL_CATALOGUE['Ollama (Local)'] ? [...MODEL_CATALOGUE['Ollama (Local)']] : []
255
257
  },
258
+ {
259
+ id: 'openrouter',
260
+ label: 'OpenRouter (Free Models)',
261
+ envVar: 'OPENROUTER_API_KEY',
262
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER['openrouter'] || 'openrouter/free',
263
+ models: MODEL_CATALOGUE['OpenRouter (Free)'] ? [...MODEL_CATALOGUE['OpenRouter (Free)']] : ['openrouter/free']
264
+ },
256
265
  {
257
266
  id: 'xai',
258
267
  label: 'xAI (Grok)',
@@ -999,6 +1008,44 @@ export async function fetchLiveModels(provider, config = {}) {
999
1008
  return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1000
1009
  }
1001
1010
  }
1011
+ if (norm === 'openrouter') {
1012
+ const host = (baseUrl || 'https://openrouter.ai/api/v1').replace(/\/+$/, '');
1013
+ const headers = {
1014
+ 'HTTP-Referer': 'https://causyne.com',
1015
+ 'X-Title': 'Causyne Agent'
1016
+ };
1017
+ if (apiKey)
1018
+ headers['Authorization'] = `Bearer ${apiKey}`;
1019
+ const res = await fetch(`${host}/models`, {
1020
+ headers,
1021
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1022
+ });
1023
+ if (!res.ok)
1024
+ return ['openrouter/free'];
1025
+ const data = (await res.json());
1026
+ if (Array.isArray(data.data)) {
1027
+ const freeModels = data.data
1028
+ .filter((m) => {
1029
+ if (!m.id)
1030
+ return false;
1031
+ if (m.id === 'openrouter/free')
1032
+ return true;
1033
+ if (m.id.endsWith(':free'))
1034
+ return true;
1035
+ const promptZero = m.pricing?.prompt === '0' || m.pricing?.prompt === 0;
1036
+ const complZero = m.pricing?.completion === '0' || m.pricing?.completion === 0;
1037
+ return promptZero && complZero;
1038
+ })
1039
+ .map((m) => m.id || '')
1040
+ .filter(Boolean)
1041
+ .sort();
1042
+ if (!freeModels.includes('openrouter/free')) {
1043
+ freeModels.unshift('openrouter/free');
1044
+ }
1045
+ return freeModels;
1046
+ }
1047
+ return ['openrouter/free'];
1048
+ }
1002
1049
  if (norm === 'openai-compatible') {
1003
1050
  if (!baseUrl)
1004
1051
  return [];
@@ -71,6 +71,7 @@ export function normalizeProviderKey(provider: string): string {
71
71
  if (p === 'xai' || p === 'grok') return 'xai';
72
72
  if (p === 'moonshot' || p === 'kimi') return 'moonshot';
73
73
  if (p === 'muse' || p === 'meta') return 'muse';
74
+ if (p === 'openrouter' || p === 'openrouter-free' || p === 'openrouter/free') return 'openrouter';
74
75
  if (p === 'openai-compatible' || p === 'custom') return 'openai-compatible';
75
76
  if (p === 'antigravity' || p === 'agy') return 'antigravity';
76
77
  if (p === 'acp') return 'acp';
@@ -316,6 +317,13 @@ export function getAvailableProvidersOverview(
316
317
  defaultModel: DEFAULT_MODEL_BY_PROVIDER['ollama'] || 'llama3.3',
317
318
  models: MODEL_CATALOGUE['Ollama (Local)'] ? [...MODEL_CATALOGUE['Ollama (Local)']] : []
318
319
  },
320
+ {
321
+ id: 'openrouter',
322
+ label: 'OpenRouter (Free Models)',
323
+ envVar: 'OPENROUTER_API_KEY',
324
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER['openrouter'] || 'openrouter/free',
325
+ models: MODEL_CATALOGUE['OpenRouter (Free)'] ? [...MODEL_CATALOGUE['OpenRouter (Free)']] : ['openrouter/free']
326
+ },
319
327
  {
320
328
  id: 'xai',
321
329
  label: 'xAI (Grok)',
@@ -1066,6 +1074,45 @@ export async function fetchLiveModels(
1066
1074
  }
1067
1075
  }
1068
1076
 
1077
+ if (norm === 'openrouter') {
1078
+ const host = (baseUrl || 'https://openrouter.ai/api/v1').replace(/\/+$/, '');
1079
+ const headers: Record<string, string> = {
1080
+ 'HTTP-Referer': 'https://causyne.com',
1081
+ 'X-Title': 'Causyne Agent'
1082
+ };
1083
+ if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
1084
+ const res = await fetch(`${host}/models`, {
1085
+ headers,
1086
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1087
+ });
1088
+ if (!res.ok) return ['openrouter/free'];
1089
+ const data = (await res.json()) as {
1090
+ data?: Array<{
1091
+ id?: string;
1092
+ pricing?: { prompt?: string | number; completion?: string | number };
1093
+ }>;
1094
+ };
1095
+ if (Array.isArray(data.data)) {
1096
+ const freeModels = data.data
1097
+ .filter((m) => {
1098
+ if (!m.id) return false;
1099
+ if (m.id === 'openrouter/free') return true;
1100
+ if (m.id.endsWith(':free')) return true;
1101
+ const promptZero = m.pricing?.prompt === '0' || m.pricing?.prompt === 0;
1102
+ const complZero = m.pricing?.completion === '0' || m.pricing?.completion === 0;
1103
+ return promptZero && complZero;
1104
+ })
1105
+ .map((m) => m.id || '')
1106
+ .filter(Boolean)
1107
+ .sort();
1108
+ if (!freeModels.includes('openrouter/free')) {
1109
+ freeModels.unshift('openrouter/free');
1110
+ }
1111
+ return freeModels;
1112
+ }
1113
+ return ['openrouter/free'];
1114
+ }
1115
+
1069
1116
  if (norm === 'openai-compatible') {
1070
1117
  if (!baseUrl) return [];
1071
1118
  const host = baseUrl.replace(/\/+$/, '');
@@ -137,7 +137,8 @@ export const MODEL_CATALOGUE = {
137
137
  'Pi (Local Peer)': ['default'],
138
138
  'ACP (Peer Agents)': ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'hermes', 'qwen', 'copilot', 'kimi', 'goose'],
139
139
  'OpenCode (ACP)': PEER_MODEL_CATALOGUE.opencode,
140
- 'Claude Code (ACP)': PEER_MODEL_CATALOGUE.claude
140
+ 'Claude Code (ACP)': PEER_MODEL_CATALOGUE.claude,
141
+ 'OpenRouter (Free)': ['openrouter/free']
141
142
  };
142
143
 
143
144
  /** Provider labels in picker order. */
@@ -168,6 +169,7 @@ export const DEFAULT_MODEL_BY_PROVIDER = {
168
169
  'acp/goose': 'goose',
169
170
  'acp/hermes': 'hermes',
170
171
  antigravity: 'Gemini 3.8 Flash (Low)',
172
+ openrouter: 'openrouter/free',
171
173
  pi: 'default',
172
174
  'openai-compatible': ''
173
175
  };
@@ -207,7 +209,8 @@ export const UTILITY_MODEL_BY_PROVIDER = {
207
209
  'dashscope-byok': 'qwen3.6-flash',
208
210
  anthropic: 'claude-haiku-4-5', // $1/$5 against opus's $5/$25
209
211
  openai: 'gpt-5.4-mini', // $0.75/$4.50 against sol's $5/$30
210
- gemini: 'gemini-3.1-flash-lite' // $0.25/$1.50 against flash's $1.50/$9
212
+ gemini: 'gemini-3.1-flash-lite', // $0.25/$1.50 against flash's $1.50/$9
213
+ openrouter: 'openrouter/free'
211
214
  };
212
215
 
213
216
  export function allCatalogueModels() {
@@ -84,6 +84,8 @@ export class LLMProvider {
84
84
  get supportsVision(): boolean;
85
85
  get supportsAudio(): boolean;
86
86
  supportsToolSearch?(): boolean;
87
+ prepareMessages(messages: any[]): any[];
88
+ normalizeUsage(rawUsage: any): ChatResponseUsage;
87
89
  chat(messages: any[], options?: ChatOptions): Promise<ChatResponse>;
88
90
  }
89
91
 
@@ -19,6 +19,7 @@ import { MuseProvider } from './muse.js';
19
19
  import { AcpProvider, isAcpProvider } from './acp.js';
20
20
  import { PiProvider, isPiProvider } from './pi.js';
21
21
  import { AntigravityProvider, isAntigravityProvider } from './antigravity.js';
22
+ import { OpenRouterProvider } from './openrouter.js';
22
23
 
23
24
  export function createProvider(config) {
24
25
  const p = config.provider?.toLowerCase();
@@ -35,6 +36,7 @@ export function createProvider(config) {
35
36
  // Meta Model API. 'meta' and 'muse' both reach it: the vendor is Meta, the
36
37
  // model family is Muse, and users say either.
37
38
  if (p === 'muse' || p === 'meta') return new MuseProvider(config);
39
+ if (p === 'openrouter' || p === 'openrouter-free') return new OpenRouterProvider(config);
38
40
  if (isAcpProvider(p)) return new AcpProvider(config);
39
41
  if (isPiProvider(p)) return new PiProvider(config);
40
42
  if (isAntigravityProvider(p)) return new AntigravityProvider(config);
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Causyne Agent — OpenRouter Free Provider
3
+ *
4
+ * Implements genuine zero-cost hosted model inference via the official
5
+ * OpenRouter Free router (`openrouter/free`) and verified zero-cost models.
6
+ * Enforces strict zero-cost boundaries, default data_collection: "deny",
7
+ * streaming SSE, and safe tool-call parsing without paid model fallbacks.
8
+ */
9
+ import { LLMProvider } from './base.js';
10
+ import { canonicalModelId } from '../modelIds.js';
11
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
12
+ export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
13
+ export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
14
+ export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
15
+ export class FreeModeCostGuardError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = 'FreeModeCostGuardError';
19
+ }
20
+ }
21
+ export class OpenRouterRateLimitError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = 'OpenRouterRateLimitError';
25
+ }
26
+ }
27
+ export class OpenRouterPrivacyConstraintError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = 'OpenRouterPrivacyConstraintError';
31
+ }
32
+ }
33
+ export class OpenRouterProvider extends LLMProvider {
34
+ dataCollection;
35
+ freeOnly;
36
+ constructor(config = {}) {
37
+ super(config);
38
+ this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
39
+ this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
40
+ this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
41
+ this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
42
+ // Verify model cost constraint upon instantiation
43
+ if (this.freeOnly) {
44
+ this.assertFreeModel(this.model);
45
+ }
46
+ }
47
+ /**
48
+ * Determine whether a model identifier represents a zero-cost free route.
49
+ */
50
+ isFreeModel(modelId) {
51
+ const clean = (modelId || '').trim().toLowerCase();
52
+ if (clean === 'openrouter/free' || clean === 'free')
53
+ return true;
54
+ if (clean.endsWith(':free'))
55
+ return true;
56
+ return false;
57
+ }
58
+ /**
59
+ * Enforce that the requested model is strictly zero-cost.
60
+ */
61
+ assertFreeModel(modelId) {
62
+ if (!this.isFreeModel(modelId)) {
63
+ throw new FreeModeCostGuardError(`Model '${modelId}' is not an authorized free model. Free mode strictly forbids paid models to prevent unintended charges.`);
64
+ }
65
+ }
66
+ /**
67
+ * Execute chat completion with OpenRouter, supporting streaming, tools, and privacy tags.
68
+ */
69
+ async chat(messages, options = {}) {
70
+ if (this.freeOnly) {
71
+ this.assertFreeModel(this.model);
72
+ }
73
+ const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
74
+ if (!apiKey) {
75
+ throw new Error('OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.');
76
+ }
77
+ const preparedMessages = this.prepareMessages(messages);
78
+ const shouldStream = typeof options.onChunk === 'function';
79
+ const payload = {
80
+ model: this.model,
81
+ messages: preparedMessages,
82
+ temperature: options.temperature ?? 0.1,
83
+ stream: shouldStream,
84
+ provider: {
85
+ data_collection: this.dataCollection
86
+ }
87
+ };
88
+ if (options['jsonMode']) {
89
+ payload['response_format'] = { type: 'json_object' };
90
+ }
91
+ if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
92
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
93
+ payload['tools'] = scanReport.adaptedTools;
94
+ payload['tool_choice'] = 'auto';
95
+ }
96
+ const headers = {
97
+ 'Content-Type': 'application/json',
98
+ 'Authorization': `Bearer ${apiKey}`,
99
+ 'HTTP-Referer': 'https://causyne.com',
100
+ 'X-Title': 'Causyne Agent'
101
+ };
102
+ let response;
103
+ const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
104
+ const fetchInit = {
105
+ method: 'POST',
106
+ headers,
107
+ body: JSON.stringify(payload)
108
+ };
109
+ if (options.signal) {
110
+ fetchInit.signal = options.signal;
111
+ }
112
+ try {
113
+ response = await fetch(endpoint, fetchInit);
114
+ }
115
+ catch (err) {
116
+ if (err?.name === 'AbortError' || options.signal?.aborted) {
117
+ throw err;
118
+ }
119
+ throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
120
+ }
121
+ if (!response.ok) {
122
+ const errorText = await response.text().catch(() => '');
123
+ this.handleHttpErrors(response.status, errorText);
124
+ }
125
+ if (shouldStream && response.body) {
126
+ return this.handleStreamingResponse(response, options);
127
+ }
128
+ else {
129
+ return this.handleJsonResponse(response);
130
+ }
131
+ }
132
+ /**
133
+ * Map HTTP error codes into user-friendly and security-preserving exceptions.
134
+ */
135
+ handleHttpErrors(status, errorText) {
136
+ if (status === 429) {
137
+ throw new OpenRouterRateLimitError('OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.');
138
+ }
139
+ const lowered = (errorText || '').toLowerCase();
140
+ if (status === 400 || status === 404) {
141
+ if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
142
+ throw new OpenRouterPrivacyConstraintError(`No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
143
+ `You can retry shortly, or inspect your preference with /openrouter status.`);
144
+ }
145
+ if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
146
+ throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.');
147
+ }
148
+ }
149
+ throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
150
+ }
151
+ /**
152
+ * Process a non-streaming JSON response from OpenRouter.
153
+ */
154
+ async handleJsonResponse(response) {
155
+ const data = (await response.json());
156
+ let content = '';
157
+ let toolCalls = [];
158
+ let reasoningContent = '';
159
+ if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
160
+ const message = data.choices[0].message;
161
+ content = message.content || '';
162
+ toolCalls = this.normalizeToolCalls(message.tool_calls);
163
+ reasoningContent = message.reasoning || message.reasoning_content || '';
164
+ }
165
+ const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
166
+ const usage = this.normalizeUsage(rawUsage);
167
+ return {
168
+ content,
169
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
170
+ reasoningContent: reasoningContent || undefined,
171
+ usage
172
+ };
173
+ }
174
+ /**
175
+ * Process a streaming SSE response from OpenRouter.
176
+ */
177
+ async handleStreamingResponse(response, options) {
178
+ const reader = response.body.getReader();
179
+ const decoder = new TextDecoder('utf-8');
180
+ let content = '';
181
+ let reasoningContent = '';
182
+ let buffer = '';
183
+ const toolCallsMap = new Map();
184
+ let rawUsage = null;
185
+ try {
186
+ while (true) {
187
+ if (options.signal?.aborted) {
188
+ await reader.cancel().catch(() => { });
189
+ break;
190
+ }
191
+ const { done, value } = await reader.read();
192
+ if (done)
193
+ break;
194
+ buffer += decoder.decode(value, { stream: true });
195
+ const lines = buffer.split('\n');
196
+ buffer = lines.pop() || '';
197
+ for (const line of lines) {
198
+ const trimmed = line.trim();
199
+ if (!trimmed || trimmed.startsWith(':'))
200
+ continue; // Skip comments/keepalive
201
+ if (trimmed === 'data: [DONE]')
202
+ continue;
203
+ if (trimmed.startsWith('data: ')) {
204
+ const jsonStr = trimmed.slice(6);
205
+ let parsed;
206
+ try {
207
+ parsed = JSON.parse(jsonStr);
208
+ }
209
+ catch {
210
+ continue;
211
+ }
212
+ if (parsed.usage) {
213
+ rawUsage = parsed.usage;
214
+ }
215
+ const choice = parsed.choices?.[0];
216
+ if (!choice)
217
+ continue;
218
+ const delta = choice.delta;
219
+ if (delta) {
220
+ // 1. Text chunk
221
+ if (delta.content) {
222
+ content += delta.content;
223
+ if (options.onChunk) {
224
+ options.onChunk(delta.content);
225
+ }
226
+ }
227
+ // 2. Reasoning chunk
228
+ const reasoning = delta.reasoning || delta.reasoning_content;
229
+ if (reasoning) {
230
+ reasoningContent += reasoning;
231
+ if (options.onReasoningChunk) {
232
+ options.onReasoningChunk(reasoning);
233
+ }
234
+ }
235
+ // 3. Tool calls assembly
236
+ if (Array.isArray(delta.tool_calls)) {
237
+ for (const tc of delta.tool_calls) {
238
+ const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
239
+ let existing = toolCallsMap.get(idx);
240
+ if (!existing) {
241
+ existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
242
+ toolCallsMap.set(idx, existing);
243
+ }
244
+ if (tc.id)
245
+ existing.id = tc.id;
246
+ if (tc.function?.name)
247
+ existing.name += tc.function.name;
248
+ if (tc.function?.arguments)
249
+ existing.arguments += tc.function.arguments;
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ }
256
+ }
257
+ finally {
258
+ reader.releaseLock();
259
+ }
260
+ const toolCalls = [];
261
+ for (const item of toolCallsMap.values()) {
262
+ if (item.name) {
263
+ toolCalls.push({
264
+ id: item.id,
265
+ type: 'function',
266
+ function: {
267
+ name: item.name,
268
+ arguments: item.arguments || '{}'
269
+ }
270
+ });
271
+ }
272
+ }
273
+ const usage = this.normalizeUsage(rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
274
+ return {
275
+ content,
276
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
277
+ reasoningContent: reasoningContent || undefined,
278
+ usage
279
+ };
280
+ }
281
+ /**
282
+ * Safely normalize tool calls from provider message.
283
+ */
284
+ normalizeToolCalls(rawCalls) {
285
+ if (!Array.isArray(rawCalls))
286
+ return [];
287
+ const normalized = [];
288
+ for (let i = 0; i < rawCalls.length; i++) {
289
+ const tc = rawCalls[i];
290
+ if (!tc || typeof tc !== 'object')
291
+ continue;
292
+ const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
293
+ const name = tc.function?.name || tc.name || '';
294
+ if (!name || typeof name !== 'string')
295
+ continue;
296
+ let args = tc.function?.arguments;
297
+ if (typeof args !== 'string') {
298
+ try {
299
+ args = JSON.stringify(args || {});
300
+ }
301
+ catch {
302
+ args = '{}';
303
+ }
304
+ }
305
+ normalized.push({
306
+ id,
307
+ type: 'function',
308
+ function: {
309
+ name,
310
+ arguments: args
311
+ }
312
+ });
313
+ }
314
+ return normalized;
315
+ }
316
+ }