@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.
@@ -0,0 +1,361 @@
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
+
10
+ import { LLMProvider } from './base.js';
11
+ import { canonicalModelId } from '../modelIds.js';
12
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
13
+ import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
14
+
15
+ export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
16
+ export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
17
+ export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
18
+
19
+ export class FreeModeCostGuardError extends Error {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = 'FreeModeCostGuardError';
23
+ }
24
+ }
25
+
26
+ export class OpenRouterRateLimitError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = 'OpenRouterRateLimitError';
30
+ }
31
+ }
32
+
33
+ export class OpenRouterPrivacyConstraintError extends Error {
34
+ constructor(message: string) {
35
+ super(message);
36
+ this.name = 'OpenRouterPrivacyConstraintError';
37
+ }
38
+ }
39
+
40
+ export class OpenRouterProvider extends LLMProvider {
41
+ public dataCollection: 'deny' | 'allow';
42
+ public freeOnly: boolean;
43
+
44
+ constructor(config: Record<string, any> = {}) {
45
+ super(config);
46
+ this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
47
+ this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
48
+ this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
49
+ this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
50
+
51
+ // Verify model cost constraint upon instantiation
52
+ if (this.freeOnly) {
53
+ this.assertFreeModel(this.model);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Determine whether a model identifier represents a zero-cost free route.
59
+ */
60
+ public isFreeModel(modelId: string): boolean {
61
+ const clean = (modelId || '').trim().toLowerCase();
62
+ if (clean === 'openrouter/free' || clean === 'free') return true;
63
+ if (clean.endsWith(':free')) return true;
64
+ return false;
65
+ }
66
+
67
+ /**
68
+ * Enforce that the requested model is strictly zero-cost.
69
+ */
70
+ public assertFreeModel(modelId: string): void {
71
+ if (!this.isFreeModel(modelId)) {
72
+ throw new FreeModeCostGuardError(
73
+ `Model '${modelId}' is not an authorized free model. Free mode strictly forbids paid models to prevent unintended charges.`
74
+ );
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Execute chat completion with OpenRouter, supporting streaming, tools, and privacy tags.
80
+ */
81
+ public override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
82
+ if (this.freeOnly) {
83
+ this.assertFreeModel(this.model);
84
+ }
85
+
86
+ const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
87
+ if (!apiKey) {
88
+ throw new Error(
89
+ 'OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.'
90
+ );
91
+ }
92
+
93
+ const preparedMessages = this.prepareMessages(messages);
94
+ const shouldStream = typeof options.onChunk === 'function';
95
+
96
+ const payload: Record<string, any> = {
97
+ model: this.model,
98
+ messages: preparedMessages,
99
+ temperature: options.temperature ?? 0.1,
100
+ stream: shouldStream,
101
+ provider: {
102
+ data_collection: this.dataCollection
103
+ }
104
+ };
105
+
106
+ if (options['jsonMode']) {
107
+ payload['response_format'] = { type: 'json_object' };
108
+ }
109
+
110
+ if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
111
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
112
+ payload['tools'] = scanReport.adaptedTools;
113
+ payload['tool_choice'] = 'auto';
114
+ }
115
+
116
+ const headers: Record<string, string> = {
117
+ 'Content-Type': 'application/json',
118
+ 'Authorization': `Bearer ${apiKey}`,
119
+ 'HTTP-Referer': 'https://causyne.com',
120
+ 'X-Title': 'Causyne Agent'
121
+ };
122
+
123
+ let response: Response;
124
+ const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
125
+ const fetchInit: RequestInit = {
126
+ method: 'POST',
127
+ headers,
128
+ body: JSON.stringify(payload)
129
+ };
130
+ if (options.signal) {
131
+ fetchInit.signal = options.signal;
132
+ }
133
+
134
+ try {
135
+ response = await fetch(endpoint, fetchInit);
136
+ } catch (err: any) {
137
+ if (err?.name === 'AbortError' || options.signal?.aborted) {
138
+ throw err;
139
+ }
140
+ throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
141
+ }
142
+
143
+ if (!response.ok) {
144
+ const errorText = await response.text().catch(() => '');
145
+ this.handleHttpErrors(response.status, errorText);
146
+ }
147
+
148
+ if (shouldStream && response.body) {
149
+ return this.handleStreamingResponse(response, options);
150
+ } else {
151
+ return this.handleJsonResponse(response);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Map HTTP error codes into user-friendly and security-preserving exceptions.
157
+ */
158
+ private handleHttpErrors(status: number, errorText: string): never {
159
+ if (status === 429) {
160
+ throw new OpenRouterRateLimitError(
161
+ 'OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.'
162
+ );
163
+ }
164
+
165
+ const lowered = (errorText || '').toLowerCase();
166
+ if (status === 400 || status === 404) {
167
+ if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
168
+ throw new OpenRouterPrivacyConstraintError(
169
+ `No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
170
+ `You can retry shortly, or inspect your preference with /openrouter status.`
171
+ );
172
+ }
173
+ if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
174
+ throw new OpenRouterRateLimitError(
175
+ 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.'
176
+ );
177
+ }
178
+ }
179
+
180
+ throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
181
+ }
182
+
183
+ /**
184
+ * Process a non-streaming JSON response from OpenRouter.
185
+ */
186
+ private async handleJsonResponse(response: Response): Promise<ChatResponse> {
187
+ const data = (await response.json()) as any;
188
+ let content = '';
189
+ let toolCalls: ChatResponseToolCall[] = [];
190
+ let reasoningContent = '';
191
+
192
+ if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
193
+ const message = data.choices[0].message;
194
+ content = message.content || '';
195
+ toolCalls = this.normalizeToolCalls(message.tool_calls);
196
+ reasoningContent = message.reasoning || message.reasoning_content || '';
197
+ }
198
+
199
+ const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
200
+ const usage: ChatResponseUsage = this.normalizeUsage(rawUsage);
201
+
202
+ return {
203
+ content,
204
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
205
+ reasoningContent: reasoningContent || undefined,
206
+ usage
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Process a streaming SSE response from OpenRouter.
212
+ */
213
+ private async handleStreamingResponse(response: Response, options: ChatOptions): Promise<ChatResponse> {
214
+ const reader = response.body!.getReader();
215
+ const decoder = new TextDecoder('utf-8');
216
+
217
+ let content = '';
218
+ let reasoningContent = '';
219
+ let buffer = '';
220
+ const toolCallsMap = new Map<number, { id: string; name: string; arguments: string }>();
221
+ let rawUsage: any = null;
222
+
223
+ try {
224
+ while (true) {
225
+ if (options.signal?.aborted) {
226
+ await reader.cancel().catch(() => {});
227
+ break;
228
+ }
229
+
230
+ const { done, value } = await reader.read();
231
+ if (done) break;
232
+
233
+ buffer += decoder.decode(value, { stream: true });
234
+ const lines = buffer.split('\n');
235
+ buffer = lines.pop() || '';
236
+
237
+ for (const line of lines) {
238
+ const trimmed = line.trim();
239
+ if (!trimmed || trimmed.startsWith(':')) continue; // Skip comments/keepalive
240
+ if (trimmed === 'data: [DONE]') continue;
241
+
242
+ if (trimmed.startsWith('data: ')) {
243
+ const jsonStr = trimmed.slice(6);
244
+ let parsed: any;
245
+ try {
246
+ parsed = JSON.parse(jsonStr);
247
+ } catch {
248
+ continue;
249
+ }
250
+
251
+ if (parsed.usage) {
252
+ rawUsage = parsed.usage;
253
+ }
254
+
255
+ const choice = parsed.choices?.[0];
256
+ if (!choice) continue;
257
+
258
+ const delta = choice.delta;
259
+ if (delta) {
260
+ // 1. Text chunk
261
+ if (delta.content) {
262
+ content += delta.content;
263
+ if (options.onChunk) {
264
+ options.onChunk(delta.content);
265
+ }
266
+ }
267
+
268
+ // 2. Reasoning chunk
269
+ const reasoning = delta.reasoning || delta.reasoning_content;
270
+ if (reasoning) {
271
+ reasoningContent += reasoning;
272
+ if (options.onReasoningChunk) {
273
+ options.onReasoningChunk(reasoning);
274
+ }
275
+ }
276
+
277
+ // 3. Tool calls assembly
278
+ if (Array.isArray(delta.tool_calls)) {
279
+ for (const tc of delta.tool_calls) {
280
+ const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
281
+ let existing = toolCallsMap.get(idx);
282
+ if (!existing) {
283
+ existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
284
+ toolCallsMap.set(idx, existing);
285
+ }
286
+ if (tc.id) existing.id = tc.id;
287
+ if (tc.function?.name) existing.name += tc.function.name;
288
+ if (tc.function?.arguments) existing.arguments += tc.function.arguments;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+ } finally {
296
+ reader.releaseLock();
297
+ }
298
+
299
+ const toolCalls: ChatResponseToolCall[] = [];
300
+ for (const item of toolCallsMap.values()) {
301
+ if (item.name) {
302
+ toolCalls.push({
303
+ id: item.id,
304
+ type: 'function',
305
+ function: {
306
+ name: item.name,
307
+ arguments: item.arguments || '{}'
308
+ }
309
+ });
310
+ }
311
+ }
312
+
313
+ const usage: ChatResponseUsage = this.normalizeUsage(
314
+ rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
315
+ );
316
+
317
+ return {
318
+ content,
319
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
320
+ reasoningContent: reasoningContent || undefined,
321
+ usage
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Safely normalize tool calls from provider message.
327
+ */
328
+ private normalizeToolCalls(rawCalls: any[]): ChatResponseToolCall[] {
329
+ if (!Array.isArray(rawCalls)) return [];
330
+ const normalized: ChatResponseToolCall[] = [];
331
+
332
+ for (let i = 0; i < rawCalls.length; i++) {
333
+ const tc = rawCalls[i];
334
+ if (!tc || typeof tc !== 'object') continue;
335
+
336
+ const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
337
+ const name = tc.function?.name || tc.name || '';
338
+ if (!name || typeof name !== 'string') continue;
339
+
340
+ let args = tc.function?.arguments;
341
+ if (typeof args !== 'string') {
342
+ try {
343
+ args = JSON.stringify(args || {});
344
+ } catch {
345
+ args = '{}';
346
+ }
347
+ }
348
+
349
+ normalized.push({
350
+ id,
351
+ type: 'function',
352
+ function: {
353
+ name,
354
+ arguments: args
355
+ }
356
+ });
357
+ }
358
+
359
+ return normalized;
360
+ }
361
+ }
package/src/tui/home.js CHANGED
@@ -148,6 +148,7 @@ export const PROVIDERS = [
148
148
  { id: 'moonshot', label: 'Moonshot', hint: 'Kimi', category: 'BYOK (Cloud API)' },
149
149
  { id: 'xai', label: 'xAI', hint: 'Grok', category: 'BYOK (Cloud API)' },
150
150
  { id: 'openai-compatible', label: 'OpenAI-compatible endpoint', hint: 'custom base URL', category: 'BYOK (Custom)' },
151
+ { id: 'openrouter', label: 'OpenRouter (Free Models)', hint: 'free inference router · openrouter/free', category: 'Free Cloud Models' },
151
152
  { id: 'ollama', label: 'Ollama', hint: 'local / offline', category: 'BYOK (Local Server)' },
152
153
  { id: 'antigravity', label: 'Google Antigravity (AGY)', hint: resolveAgyBinary() ? 'local AGY · Gemini & Claude (ready)' : 'local AGY · (not installed)', category: 'ACP (Peer Agent)' },
153
154
  PI_SETUP_PROVIDER,
@@ -136,11 +136,21 @@ export function buildModelPickerItems(config, overview, options = {}) {
136
136
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
137
137
  const catTitle = p.id === 'ollama'
138
138
  ? `BYOK · ${p.label}`
139
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
139
+ : p.id === 'openrouter'
140
+ ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
141
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
140
142
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
141
143
  for (const m of models) {
142
144
  const isCurrent = isCurrentProvider && activeModel === m;
143
- const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
145
+ const desc = isCurrent
146
+ ? (p.id === 'openrouter' ? '● active (free)' : '● active')
147
+ : p.id === 'ollama'
148
+ ? 'local'
149
+ : p.id === 'openrouter'
150
+ ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
151
+ : p.isConfigured
152
+ ? 'configured'
153
+ : 'needs API key';
144
154
  items.push({
145
155
  id: `${p.id}/${m}`,
146
156
  label: m,
@@ -198,12 +198,22 @@ export function buildModelPickerItems(
198
198
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
199
199
  const catTitle = p.id === 'ollama'
200
200
  ? `BYOK · ${p.label}`
201
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
201
+ : p.id === 'openrouter'
202
+ ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
203
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
202
204
 
203
205
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
204
206
  for (const m of models) {
205
207
  const isCurrent = isCurrentProvider && activeModel === m;
206
- const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
208
+ const desc = isCurrent
209
+ ? (p.id === 'openrouter' ? '● active (free)' : '● active')
210
+ : p.id === 'ollama'
211
+ ? 'local'
212
+ : p.id === 'openrouter'
213
+ ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
214
+ : p.isConfigured
215
+ ? 'configured'
216
+ : 'needs API key';
207
217
  items.push({
208
218
  id: `${p.id}/${m}`,
209
219
  label: m,