@causyne/agent 1.20.69 → 1.20.71
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/package.json +1 -1
- package/src/assets/logo.png +0 -0
- package/src/auth/openrouterAuth.js +489 -0
- package/src/auth/openrouterAuth.ts +588 -0
- package/src/commands.js +116 -0
- package/src/dynamicCatalogue.js +47 -0
- package/src/dynamicCatalogue.ts +47 -0
- package/src/modelCatalogue.js +5 -2
- package/src/providers/base.d.ts +2 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/openrouter.js +316 -0
- package/src/providers/openrouter.ts +361 -0
- package/src/tui/home.js +1 -0
- package/src/tui/modelPicker.js +183 -21
- package/src/tui/modelPicker.ts +193 -26
|
@@ -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,
|
package/src/tui/modelPicker.js
CHANGED
|
@@ -9,6 +9,7 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
|
|
|
9
9
|
// @ts-expect-error untyped local TUI selectList
|
|
10
10
|
import { fuzzyFilter } from './selectList.js';
|
|
11
11
|
import { loadConfig, saveConfig } from '../config.js';
|
|
12
|
+
import { startLoopbackAuth, saveOpenRouterKey } from '../auth/openrouterAuth.js';
|
|
12
13
|
import { getAvailableProvidersOverview, resolveAvailableProvidersOverview, resolveAvailableModels } from '../dynamicCatalogue.js';
|
|
13
14
|
async function showConfiguringAnimation(providerLabel) {
|
|
14
15
|
if (!process.stdout.isTTY)
|
|
@@ -130,9 +131,12 @@ export function buildModelPickerItems(config, overview, options = {}) {
|
|
|
130
131
|
}
|
|
131
132
|
}
|
|
132
133
|
}
|
|
133
|
-
// 2. BYOK Providers (Cloud & Local APIs)
|
|
134
|
+
// 2. BYOK Providers (Cloud & Local APIs) — excluding OpenRouter in BYOK tab
|
|
134
135
|
if (tab === 'all' || tab === 'byok') {
|
|
135
136
|
for (const p of overview.byok) {
|
|
137
|
+
if (p.id === 'openrouter') {
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
136
140
|
const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
|
|
137
141
|
const catTitle = p.id === 'ollama'
|
|
138
142
|
? `BYOK · ${p.label}`
|
|
@@ -140,7 +144,13 @@ export function buildModelPickerItems(config, overview, options = {}) {
|
|
|
140
144
|
const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
|
|
141
145
|
for (const m of models) {
|
|
142
146
|
const isCurrent = isCurrentProvider && activeModel === m;
|
|
143
|
-
const desc = isCurrent
|
|
147
|
+
const desc = isCurrent
|
|
148
|
+
? '● active'
|
|
149
|
+
: p.id === 'ollama'
|
|
150
|
+
? 'local'
|
|
151
|
+
: p.isConfigured
|
|
152
|
+
? 'configured'
|
|
153
|
+
: 'needs API key';
|
|
144
154
|
items.push({
|
|
145
155
|
id: `${p.id}/${m}`,
|
|
146
156
|
label: m,
|
|
@@ -160,10 +170,46 @@ export function buildModelPickerItems(config, overview, options = {}) {
|
|
|
160
170
|
}
|
|
161
171
|
}
|
|
162
172
|
}
|
|
173
|
+
// 3. Free Cloud Models (OpenRouter Free)
|
|
174
|
+
if (tab === 'all' || tab === 'free') {
|
|
175
|
+
const openrouterPeer = overview.byok.find(p => p.id === 'openrouter');
|
|
176
|
+
const isConfigured = Boolean((config.provider === 'openrouter' && config.apiKey) ||
|
|
177
|
+
config.providerKeys?.openrouter ||
|
|
178
|
+
process.env.OPENROUTER_API_KEY);
|
|
179
|
+
const isCurrentProvider = activeProvider === 'openrouter';
|
|
180
|
+
const models = openrouterPeer?.models && openrouterPeer.models.length > 0
|
|
181
|
+
? openrouterPeer.models
|
|
182
|
+
: ['openrouter/free'];
|
|
183
|
+
const catTitle = isConfigured
|
|
184
|
+
? 'Free Cloud · OpenRouter (ready)'
|
|
185
|
+
: 'Free Cloud · OpenRouter (connect account)';
|
|
186
|
+
for (const m of models) {
|
|
187
|
+
const isCurrent = isCurrentProvider && activeModel === m;
|
|
188
|
+
const desc = isCurrent
|
|
189
|
+
? '● active (free)'
|
|
190
|
+
: (isConfigured ? 'free inference' : 'connect OpenRouter · free');
|
|
191
|
+
items.push({
|
|
192
|
+
id: `openrouter/${m}`,
|
|
193
|
+
label: m,
|
|
194
|
+
category: catTitle,
|
|
195
|
+
description: desc,
|
|
196
|
+
value: {
|
|
197
|
+
type: 'free',
|
|
198
|
+
providerId: 'openrouter',
|
|
199
|
+
modelId: m,
|
|
200
|
+
providerLabel: 'OpenRouter Free',
|
|
201
|
+
installed: true,
|
|
202
|
+
isCurrent,
|
|
203
|
+
isConfigured,
|
|
204
|
+
envVar: 'OPENROUTER_API_KEY'
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
163
209
|
return items;
|
|
164
210
|
}
|
|
165
211
|
/**
|
|
166
|
-
* Sovereign Model Picker Layer with
|
|
212
|
+
* Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
|
|
167
213
|
* and interactive 10-model pagination.
|
|
168
214
|
*/
|
|
169
215
|
export class ModelPickerLayer extends SelectLayer {
|
|
@@ -175,17 +221,19 @@ export class ModelPickerLayer extends SelectLayer {
|
|
|
175
221
|
allItems;
|
|
176
222
|
constructor(options) {
|
|
177
223
|
const activeProvider = (options.config.provider || '').toLowerCase().trim();
|
|
178
|
-
const initialTab = activeProvider === '
|
|
179
|
-
|
|
180
|
-
activeProvider === '
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
224
|
+
const initialTab = activeProvider === 'openrouter'
|
|
225
|
+
? 'free'
|
|
226
|
+
: (activeProvider === 'antigravity' ||
|
|
227
|
+
activeProvider === 'agy' ||
|
|
228
|
+
activeProvider === 'acp' ||
|
|
229
|
+
activeProvider.startsWith('acp/')
|
|
230
|
+
? 'acp'
|
|
231
|
+
: 'byok');
|
|
184
232
|
const expandedPeers = new Set();
|
|
185
233
|
const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
|
|
186
234
|
super({
|
|
187
235
|
title: 'Select Model',
|
|
188
|
-
placeholder: 'type to filter (e.g. gemini, sonnet,
|
|
236
|
+
placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
|
|
189
237
|
emptyText: 'No models matched your search in this tab',
|
|
190
238
|
items: allItems,
|
|
191
239
|
width: 78,
|
|
@@ -261,7 +309,8 @@ export class ModelPickerLayer extends SelectLayer {
|
|
|
261
309
|
body(width, height) {
|
|
262
310
|
const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
|
|
263
311
|
const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
|
|
264
|
-
const
|
|
312
|
+
const tabFREE = this.activeTab === 'free' ? paint('accent', bold('● FREE')) : dim('FREE');
|
|
313
|
+
const tabBar = ` | ${tabACP} | ${tabBYOK} | ${tabFREE} | ${dim('(Tab / ← → switch tab)')}`;
|
|
265
314
|
const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
|
|
266
315
|
const listHeight = Math.max(1, height - 2);
|
|
267
316
|
const { rows } = this.list.render(width, listHeight);
|
|
@@ -273,27 +322,50 @@ export class ModelPickerLayer extends SelectLayer {
|
|
|
273
322
|
return null;
|
|
274
323
|
// 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
|
|
275
324
|
if (event.name === 'tab') {
|
|
276
|
-
|
|
325
|
+
if (this.activeTab === 'acp')
|
|
326
|
+
this.switchTab('byok');
|
|
327
|
+
else if (this.activeTab === 'byok')
|
|
328
|
+
this.switchTab('free');
|
|
329
|
+
else
|
|
330
|
+
this.switchTab('acp');
|
|
277
331
|
return 'handled';
|
|
278
332
|
}
|
|
279
|
-
if (event.name === 'left'
|
|
333
|
+
if (event.name === 'left') {
|
|
280
334
|
if (!this.list.query || event.alt || event.ctrl || event.meta) {
|
|
281
|
-
this.
|
|
282
|
-
|
|
335
|
+
if (this.activeTab === 'free') {
|
|
336
|
+
this.switchTab('byok');
|
|
337
|
+
return 'handled';
|
|
338
|
+
}
|
|
339
|
+
else if (this.activeTab === 'byok') {
|
|
340
|
+
this.switchTab('acp');
|
|
341
|
+
return 'handled';
|
|
342
|
+
}
|
|
283
343
|
}
|
|
284
344
|
}
|
|
285
|
-
if (event.name === 'right'
|
|
345
|
+
if (event.name === 'right') {
|
|
286
346
|
if (!this.list.query || event.alt || event.ctrl || event.meta) {
|
|
287
|
-
this.
|
|
288
|
-
|
|
347
|
+
if (this.activeTab === 'acp') {
|
|
348
|
+
this.switchTab('byok');
|
|
349
|
+
return 'handled';
|
|
350
|
+
}
|
|
351
|
+
else if (this.activeTab === 'byok') {
|
|
352
|
+
this.switchTab('free');
|
|
353
|
+
return 'handled';
|
|
354
|
+
}
|
|
289
355
|
}
|
|
290
356
|
}
|
|
291
357
|
if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
|
|
292
|
-
this.
|
|
358
|
+
if (this.activeTab === 'free')
|
|
359
|
+
this.switchTab('byok');
|
|
360
|
+
else if (this.activeTab === 'byok')
|
|
361
|
+
this.switchTab('acp');
|
|
293
362
|
return 'handled';
|
|
294
363
|
}
|
|
295
364
|
if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
|
|
296
|
-
this.
|
|
365
|
+
if (this.activeTab === 'acp')
|
|
366
|
+
this.switchTab('byok');
|
|
367
|
+
else if (this.activeTab === 'byok')
|
|
368
|
+
this.switchTab('free');
|
|
297
369
|
return 'handled';
|
|
298
370
|
}
|
|
299
371
|
// 2. Delegate to SelectList for navigation / query typing
|
|
@@ -385,7 +457,97 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
|
|
|
385
457
|
notifyPrompt(target.providerId, target.modelId);
|
|
386
458
|
return `Now using ${target.providerLabel} / ${target.modelId}.`;
|
|
387
459
|
}
|
|
388
|
-
// Case 2:
|
|
460
|
+
// Case 2: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
|
|
461
|
+
if (target.providerId === 'openrouter') {
|
|
462
|
+
let existingKey = '';
|
|
463
|
+
const providerKeys = config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
|
|
464
|
+
if (config['provider'] === 'openrouter' && typeof config['apiKey'] === 'string' && config['apiKey']) {
|
|
465
|
+
existingKey = config['apiKey'];
|
|
466
|
+
}
|
|
467
|
+
else if (providerKeys['openrouter']) {
|
|
468
|
+
existingKey = providerKeys['openrouter'];
|
|
469
|
+
}
|
|
470
|
+
else if (process.env.OPENROUTER_API_KEY) {
|
|
471
|
+
existingKey = process.env.OPENROUTER_API_KEY;
|
|
472
|
+
}
|
|
473
|
+
if (existingKey) {
|
|
474
|
+
config['provider'] = 'openrouter';
|
|
475
|
+
config['model'] = target.modelId;
|
|
476
|
+
config['apiKey'] = existingKey;
|
|
477
|
+
config['providerKeys'] = providerKeys;
|
|
478
|
+
config['providerKeys']['openrouter'] = existingKey;
|
|
479
|
+
store.saveConfig(config);
|
|
480
|
+
void resolveAvailableModels('openrouter', { ...config, apiKey: existingKey }, true).catch(() => { });
|
|
481
|
+
if (options.loop) {
|
|
482
|
+
options.loop.config = config;
|
|
483
|
+
if (typeof options.loop.updateTierLimits === 'function') {
|
|
484
|
+
options.loop.updateTierLimits();
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
notifyPrompt('openrouter', target.modelId);
|
|
488
|
+
return `Now using OpenRouter Free / ${target.modelId}.`;
|
|
489
|
+
}
|
|
490
|
+
// Unconfigured OpenRouter: prompt where pressing Enter once immediately starts OAuth redirect
|
|
491
|
+
const entered = await new Promise((resolve) => {
|
|
492
|
+
const layer = new InputLayer({
|
|
493
|
+
title: 'Connect OpenRouter · Free Cloud Inference',
|
|
494
|
+
lines: [
|
|
495
|
+
'Press [Enter] to open your browser and authorize with OpenRouter.',
|
|
496
|
+
'Or paste an existing OpenRouter API key (Esc to cancel).'
|
|
497
|
+
],
|
|
498
|
+
mask: false,
|
|
499
|
+
placeholder: 'Press Enter to authorize in browser, or paste API key',
|
|
500
|
+
onSubmit: resolve,
|
|
501
|
+
onCancel: () => resolve(null)
|
|
502
|
+
});
|
|
503
|
+
prompt.openLayer(layer);
|
|
504
|
+
});
|
|
505
|
+
if (entered === null) {
|
|
506
|
+
return 'Cancelled. OpenRouter connection was not completed. Model was not changed.';
|
|
507
|
+
}
|
|
508
|
+
const cleanInput = entered.trim();
|
|
509
|
+
if (!cleanInput) {
|
|
510
|
+
// User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
|
|
511
|
+
try {
|
|
512
|
+
if (process.stdout.isTTY) {
|
|
513
|
+
process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
|
|
514
|
+
process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
|
|
515
|
+
}
|
|
516
|
+
const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
|
|
517
|
+
saveOpenRouterKey(apiKey, { setAsActive: true, store });
|
|
518
|
+
const updatedConfig = store.loadConfig();
|
|
519
|
+
if (options.loop) {
|
|
520
|
+
options.loop.config = updatedConfig;
|
|
521
|
+
if (typeof options.loop.updateTierLimits === 'function') {
|
|
522
|
+
options.loop.updateTierLimits();
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
notifyPrompt('openrouter', target.modelId);
|
|
526
|
+
return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
|
|
527
|
+
}
|
|
528
|
+
catch (err) {
|
|
529
|
+
return (`✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
|
|
530
|
+
`Solutions:\n` +
|
|
531
|
+
`1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
|
|
532
|
+
`2. For headless or SSH environments, create a free API key at:\n` +
|
|
533
|
+
` https://openrouter.ai/keys\n` +
|
|
534
|
+
` and run: /openrouter connect <your-api-key>`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
// User pasted an API key
|
|
538
|
+
await showConfiguringAnimation('OpenRouter');
|
|
539
|
+
saveOpenRouterKey(cleanInput, { setAsActive: true, store });
|
|
540
|
+
const updatedConfig = store.loadConfig();
|
|
541
|
+
if (options.loop) {
|
|
542
|
+
options.loop.config = updatedConfig;
|
|
543
|
+
if (typeof options.loop.updateTierLimits === 'function') {
|
|
544
|
+
options.loop.updateTierLimits();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
notifyPrompt('openrouter', target.modelId);
|
|
548
|
+
return `✓ Saved API key. Now using OpenRouter Free / ${target.modelId}.`;
|
|
549
|
+
}
|
|
550
|
+
// Case 3: BYOK Provider (Cloud or Local API)
|
|
389
551
|
let existingKey = '';
|
|
390
552
|
const providerKeys = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
|
|
391
553
|
if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {
|