@causyne/agent 1.20.68 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.68",
3
+ "version": "1.20.70",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -54,6 +54,7 @@ import path from 'path';
54
54
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
55
55
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
56
56
  import { createProvider } from './providers/factory.js';
57
+ import { isNativeMutation } from './providers/antigravity.js';
57
58
  import { resolveMentionedContext } from './promptMentions.js';
58
59
  import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
59
60
  import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
@@ -1890,6 +1891,7 @@ export class AgentLoop {
1890
1891
  const recoveryPaths = new Set();
1891
1892
  let modelCallIndex = 0;
1892
1893
  let mediaExplorationRecoveries = 0;
1894
+ let taskMutationCount = 0;
1893
1895
  let reasoningOnlyRecoveries = 0;
1894
1896
  let planHandoffRecoveries = 0;
1895
1897
  let incompleteTurnContinuations = 0;
@@ -2438,8 +2440,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
2438
2440
  auditLog.log({ event: 'native_action', taskId: this.taskId,
2439
2441
  provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2440
2442
  ...(action.id ? { actionId: action.id } : {}) });
2441
- if (action.status === 'completed' && action.id && !isChecklistTool) {
2442
- completedNativeActionIds.add(String(action.id));
2443
+ if (action.status === 'completed' && !isChecklistTool) {
2444
+ const actionKey = action.id ? String(action.id) : `${action.name}:${completedNativeActionIds.size}`;
2445
+ if (!completedNativeActionIds.has(actionKey)) {
2446
+ completedNativeActionIds.add(actionKey);
2447
+ this.stepsCompleted++;
2448
+ }
2443
2449
  }
2444
2450
  const isCompleted = action.status === 'completed';
2445
2451
  const isFailed = action.status === 'failed';
@@ -2501,8 +2507,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2501
2507
  const lowerName = action.name.toLowerCase();
2502
2508
  const rawDetail = String(action.detail || '');
2503
2509
  const lowerDetail = rawDetail.toLowerCase();
2504
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)) {
2510
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2511
+ || isNativeMutation(action.name, actionArgs)) {
2505
2512
  nativeMutationCount++;
2513
+ taskMutationCount++;
2514
+ mediaExplorationRecoveries = 0;
2506
2515
  if (nativeMutationCount === 1 && this._implementationPlanSeeded) {
2507
2516
  this.advanceImplementationPlanProgress('mutation');
2508
2517
  }
@@ -2793,7 +2802,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2793
2802
  const hasExternalActions = completedExternalActions.length > 0;
2794
2803
  const isIncompleteTurn = Boolean(response.incompleteTurn);
2795
2804
  if (hasExternalActions) {
2796
- this.stepsCompleted += completedExternalActions.length;
2805
+ this.stepsCompleted += Math.max(0, completedExternalActions.length - completedNativeActionIds.size);
2797
2806
  for (const extAction of completedExternalActions) {
2798
2807
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
2799
2808
  if (extPlan) {
@@ -4478,17 +4487,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
4478
4487
  }
4479
4488
  if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
4480
4489
  auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
4481
- inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
4490
+ inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries, mutations: taskMutationCount });
4482
4491
  if (mediaExplorationRecoveries++ === 0) {
4483
- this.messages.push({ role: 'system', content: '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
4484
- 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
4485
- 'Make one targeted workspace edit now, then run one focused verification. ' +
4486
- 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
4492
+ this.messages.push({ role: 'system', content: taskMutationCount > 0
4493
+ ? '[TASK RECOVERY] Repeated identical tool polling or inspection was paused after workspace edits. Do not repeat identical probes; verify the completed changes once and present the final result.'
4494
+ : '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
4495
+ 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
4496
+ 'Make one targeted workspace edit now, then run one focused verification. ' +
4497
+ 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
4487
4498
  this.memoryManager.saveHistory(this.messages);
4488
- this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
4499
+ this.emitEvent({ type: 'notice', message: taskMutationCount > 0
4500
+ ? 'Repeated status probe paused; continuing from completed workspace edits.'
4501
+ : 'Repeated inspection paused; continuing once with a direct edit instruction.' });
4489
4502
  continue;
4490
4503
  }
4491
- this.emitEvent({ type: 'error', message: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4504
+ this.emitEvent({ type: 'error', message: taskMutationCount > 0
4505
+ ? 'The provider repeated an identical tool call after a recovery checkpoint. Workspace edits are preserved on disk.'
4506
+ : 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4492
4507
  break;
4493
4508
  }
4494
4509
  if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
package/src/agentLoop.ts CHANGED
@@ -95,6 +95,7 @@ import path from 'path';
95
95
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
96
96
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
97
97
  import { createProvider } from './providers/factory.js';
98
+ import { isNativeMutation } from './providers/antigravity.js';
98
99
  import { resolveMentionedContext } from './promptMentions.js';
99
100
  import { isLaunchOnlyPrompt, launchScopeError } from './launchIntent.js';
100
101
  import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from './tui/codeProgress.js';
@@ -1976,6 +1977,7 @@ export class AgentLoop {
1976
1977
  const recoveryPaths = new Set<string>();
1977
1978
  let modelCallIndex = 0;
1978
1979
  let mediaExplorationRecoveries = 0;
1980
+ let taskMutationCount = 0;
1979
1981
  let reasoningOnlyRecoveries = 0;
1980
1982
  let planHandoffRecoveries = 0;
1981
1983
  let incompleteTurnContinuations = 0;
@@ -2544,8 +2546,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
2544
2546
  auditLog.log({ event: 'native_action', taskId: this.taskId,
2545
2547
  provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
2546
2548
  ...(action.id ? { actionId: action.id } : {}) });
2547
- if (action.status === 'completed' && action.id && !isChecklistTool) {
2548
- completedNativeActionIds.add(String(action.id));
2549
+ if (action.status === 'completed' && !isChecklistTool) {
2550
+ const actionKey = action.id ? String(action.id) : `${action.name}:${completedNativeActionIds.size}`;
2551
+ if (!completedNativeActionIds.has(actionKey)) {
2552
+ completedNativeActionIds.add(actionKey);
2553
+ this.stepsCompleted++;
2554
+ }
2549
2555
  }
2550
2556
  const isCompleted = action.status === 'completed';
2551
2557
  const isFailed = action.status === 'failed';
@@ -2602,8 +2608,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2602
2608
  const lowerName = action.name.toLowerCase();
2603
2609
  const rawDetail = String(action.detail || '');
2604
2610
  const lowerDetail = rawDetail.toLowerCase();
2605
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)) {
2611
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2612
+ || isNativeMutation(action.name, actionArgs)) {
2606
2613
  nativeMutationCount++;
2614
+ taskMutationCount++;
2615
+ mediaExplorationRecoveries = 0;
2607
2616
  if (nativeMutationCount === 1 && this._implementationPlanSeeded) {
2608
2617
  this.advanceImplementationPlanProgress('mutation');
2609
2618
  } else if (nativeMutationCount % 2 === 0) {
@@ -2919,7 +2928,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2919
2928
  const isIncompleteTurn = Boolean((response as any).incompleteTurn);
2920
2929
 
2921
2930
  if (hasExternalActions) {
2922
- this.stepsCompleted += completedExternalActions.length;
2931
+ this.stepsCompleted += Math.max(0, completedExternalActions.length - completedNativeActionIds.size);
2923
2932
  for (const extAction of completedExternalActions) {
2924
2933
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
2925
2934
  if (extPlan) {
@@ -4728,19 +4737,25 @@ You are operating in a text-and-code modality without direct image pixel renderi
4728
4737
  }
4729
4738
  if (e?.code === 'AGY_EXPLORATION_LOOP' || e?.code === 'AGENT_EXPLORATION_LOOP' || e?.code === 'STALL_EXPLORATION_LOOP') {
4730
4739
  auditLog.log({ event: 'media_exploration_checkpoint', taskId: this.taskId,
4731
- inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries });
4740
+ inspectionCount: e.inspectionCount, recovery: mediaExplorationRecoveries, mutations: taskMutationCount });
4732
4741
  if (mediaExplorationRecoveries++ === 0) {
4733
4742
  this.messages.push({ role: 'system', content:
4734
- '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
4735
- 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
4736
- 'Make one targeted workspace edit now, then run one focused verification. ' +
4737
- 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
4743
+ taskMutationCount > 0
4744
+ ? '[TASK RECOVERY] Repeated identical tool polling or inspection was paused after workspace edits. Do not repeat identical probes; verify the completed changes once and present the final result.'
4745
+ : '[TASK RECOVERY] Consecutive read-only inspections without workspace changes were paused. ' +
4746
+ 'The user requested a concrete change. Reuse the observations already gathered; do not repeat probes. ' +
4747
+ 'Make one targeted workspace edit now, then run one focused verification. ' +
4748
+ 'If editing is blocked, report the exact blocker. Do not claim completion from inspection alone.' });
4738
4749
  this.memoryManager.saveHistory(this.messages);
4739
- this.emitEvent({ type: 'notice', message: 'Repeated inspection paused; continuing once with a direct edit instruction.' });
4750
+ this.emitEvent({ type: 'notice', message: taskMutationCount > 0
4751
+ ? 'Repeated status probe paused; continuing from completed workspace edits.'
4752
+ : 'Repeated inspection paused; continuing once with a direct edit instruction.' });
4740
4753
  continue;
4741
4754
  }
4742
4755
  this.emitEvent({ type: 'error', message:
4743
- 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4756
+ taskMutationCount > 0
4757
+ ? 'The provider repeated an identical tool call after a recovery checkpoint. Workspace edits are preserved on disk.'
4758
+ : 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4744
4759
  break;
4745
4760
  }
4746
4761
  if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Causyne Agent — OpenRouter Free Authentication & OAuth PKCE Flow
3
+ *
4
+ * Implements the official OpenRouter OAuth PKCE authorization with S256,
5
+ * loopback callback server on ephemeral 127.0.0.1 port, headless/manual fallback,
6
+ * and secure credential storage in Causyne's encrypted configuration vault.
7
+ */
8
+ import http from 'node:http';
9
+ import crypto from 'node:crypto';
10
+ import { URL } from 'node:url';
11
+ import { loadConfig, saveConfig } from '../config.js';
12
+ import { openWithNativeOS } from '../tools/desktopOpen.js';
13
+ export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
14
+ export const OPENROUTER_TOKEN_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
15
+ export const OPENROUTER_FREE_MODEL = 'openrouter/free';
16
+ export class OpenRouterAuthError extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = 'OpenRouterAuthError';
20
+ }
21
+ }
22
+ /**
23
+ * Generate cryptographically secure PKCE verifier, S256 challenge, and CSRF state token.
24
+ */
25
+ export function generatePkceCodes() {
26
+ // 32 random bytes as base64url string yields 43 characters (RFC 7636 compliant: 43-128 chars)
27
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
28
+ const codeChallenge = crypto
29
+ .createHash('sha256')
30
+ .update(codeVerifier)
31
+ .digest('base64url');
32
+ const state = crypto.randomBytes(16).toString('hex');
33
+ return {
34
+ codeVerifier,
35
+ codeChallenge,
36
+ codeChallengeMethod: 'S256',
37
+ state
38
+ };
39
+ }
40
+ /**
41
+ * Build the official OpenRouter OAuth authorization URL.
42
+ */
43
+ export function buildAuthorizationUrl(callbackUrl, codeChallenge, state) {
44
+ const url = new URL(OPENROUTER_AUTH_URL);
45
+ url.searchParams.set('callback_url', callbackUrl);
46
+ url.searchParams.set('code_challenge', codeChallenge);
47
+ url.searchParams.set('code_challenge_method', 'S256');
48
+ url.searchParams.set('state', state);
49
+ return url.toString();
50
+ }
51
+ /**
52
+ * Exchange the authorization code for an OpenRouter API key using PKCE verifier.
53
+ */
54
+ export async function exchangeCodeForApiKey(code, codeVerifier, fetchFn = fetch) {
55
+ const cleanCode = (code || '').trim();
56
+ const cleanVerifier = (codeVerifier || '').trim();
57
+ if (!cleanCode) {
58
+ throw new OpenRouterAuthError('Authorization code cannot be empty.');
59
+ }
60
+ if (!cleanVerifier) {
61
+ throw new OpenRouterAuthError('PKCE code verifier cannot be empty.');
62
+ }
63
+ const payload = {
64
+ code: cleanCode,
65
+ code_verifier: cleanVerifier,
66
+ code_challenge_method: 'S256'
67
+ };
68
+ let response;
69
+ try {
70
+ response = await fetchFn(OPENROUTER_TOKEN_EXCHANGE_URL, {
71
+ method: 'POST',
72
+ headers: {
73
+ 'Content-Type': 'application/json',
74
+ 'HTTP-Referer': 'https://causyne.com',
75
+ 'X-Title': 'Causyne Agent'
76
+ },
77
+ body: JSON.stringify(payload)
78
+ });
79
+ }
80
+ catch (err) {
81
+ throw new OpenRouterAuthError(`Failed to reach OpenRouter token exchange: ${err?.message || err}`);
82
+ }
83
+ if (!response.ok) {
84
+ const errorBody = await response.text().catch(() => '');
85
+ throw new OpenRouterAuthError(`OpenRouter token exchange failed (HTTP ${response.status}): ${errorBody || 'Invalid code or verifier'}`);
86
+ }
87
+ const data = (await response.json().catch(() => null));
88
+ const apiKey = data?.key?.trim();
89
+ if (!apiKey) {
90
+ throw new OpenRouterAuthError('OpenRouter response did not contain an API key.');
91
+ }
92
+ return apiKey;
93
+ }
94
+ /**
95
+ * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
96
+ */
97
+ export async function startLoopbackAuth(options = {}) {
98
+ const timeoutMs = options.timeoutMs ?? 120_000;
99
+ const openBrowser = options.openBrowser ?? true;
100
+ const fetchFn = options.fetchFn ?? fetch;
101
+ const pkce = generatePkceCodes();
102
+ return new Promise((resolve, reject) => {
103
+ let resolved = false;
104
+ let timeoutTimer = null;
105
+ const cleanup = () => {
106
+ if (timeoutTimer) {
107
+ clearTimeout(timeoutTimer);
108
+ timeoutTimer = null;
109
+ }
110
+ try {
111
+ server.close();
112
+ }
113
+ catch {
114
+ // Ignore close errors
115
+ }
116
+ };
117
+ const server = http.createServer(async (req, res) => {
118
+ try {
119
+ const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
120
+ if (reqUrl.pathname !== '/callback') {
121
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
122
+ res.end('Not Found');
123
+ return;
124
+ }
125
+ const code = reqUrl.searchParams.get('code');
126
+ const state = reqUrl.searchParams.get('state');
127
+ if (!state || state !== pkce.state) {
128
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
129
+ res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
130
+ '<h2 style="color:#ef4444;">Authorization Error: State Mismatch</h2>' +
131
+ '<p>The received CSRF verification state did not match the session. Please try again.</p>' +
132
+ '</body></html>');
133
+ if (!resolved) {
134
+ resolved = true;
135
+ cleanup();
136
+ reject(new OpenRouterAuthError('State mismatch detected during OpenRouter callback.'));
137
+ }
138
+ return;
139
+ }
140
+ if (!code) {
141
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
142
+ res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
143
+ '<h2 style="color:#ef4444;">Authorization Failed</h2>' +
144
+ '<p>No authorization code was returned by OpenRouter.</p>' +
145
+ '</body></html>');
146
+ if (!resolved) {
147
+ resolved = true;
148
+ cleanup();
149
+ reject(new OpenRouterAuthError('No authorization code returned from callback.'));
150
+ }
151
+ return;
152
+ }
153
+ // Send friendly HTML response to user's browser
154
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
155
+ res.end('<html><body style="font-family:sans-serif;padding:40px;background:#0d1117;color:#c9d1d9;text-align:center;">' +
156
+ '<h2 style="color:#2ea043;margin-bottom:12px;">Causyne Agent Connected Successfully</h2>' +
157
+ '<p style="font-size:16px;color:#8b949e;">Your OpenRouter account has been authorized. You can close this window and return to your terminal.</p>' +
158
+ '</body></html>');
159
+ // Perform token exchange
160
+ const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
161
+ if (!resolved) {
162
+ resolved = true;
163
+ cleanup();
164
+ resolve({ apiKey });
165
+ }
166
+ }
167
+ catch (err) {
168
+ if (!resolved) {
169
+ resolved = true;
170
+ cleanup();
171
+ reject(err);
172
+ }
173
+ }
174
+ });
175
+ server.on('error', (err) => {
176
+ if (!resolved) {
177
+ resolved = true;
178
+ cleanup();
179
+ reject(new OpenRouterAuthError(`Loopback server failed to bind: ${err.message}`));
180
+ }
181
+ });
182
+ server.listen(0, '127.0.0.1', () => {
183
+ const addr = server.address();
184
+ if (!addr || typeof addr === 'string') {
185
+ cleanup();
186
+ reject(new OpenRouterAuthError('Failed to retrieve loopback server port.'));
187
+ return;
188
+ }
189
+ const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
190
+ const authUrl = buildAuthorizationUrl(callbackUrl, pkce.codeChallenge, pkce.state);
191
+ if (options.onUrlReady) {
192
+ options.onUrlReady(authUrl);
193
+ }
194
+ if (openBrowser) {
195
+ openWithNativeOS(authUrl).catch(() => {
196
+ // If browser opening fails, user can copy URL manually
197
+ });
198
+ }
199
+ timeoutTimer = setTimeout(() => {
200
+ if (!resolved) {
201
+ resolved = true;
202
+ cleanup();
203
+ reject(new OpenRouterAuthError(`Authorization timed out after ${Math.round(timeoutMs / 1000)} seconds.`));
204
+ }
205
+ }, timeoutMs);
206
+ });
207
+ });
208
+ }
209
+ /**
210
+ * Mask an API key for safe display in logs and status screens.
211
+ */
212
+ export function maskApiKey(key) {
213
+ const clean = (key || '').trim();
214
+ if (!clean)
215
+ return 'none';
216
+ if (clean.length <= 8)
217
+ return '********';
218
+ return `${clean.slice(0, 7)}...${clean.slice(-4)}`;
219
+ }
220
+ /**
221
+ * Save user OpenRouter key into local encrypted configuration vault.
222
+ */
223
+ export function saveOpenRouterKey(apiKey, options = {}) {
224
+ const cleanKey = (apiKey || '').trim();
225
+ if (!cleanKey) {
226
+ throw new OpenRouterAuthError('Cannot save an empty OpenRouter API key.');
227
+ }
228
+ const store = options.store || { loadConfig, saveConfig };
229
+ const currentConfig = store.loadConfig() || {};
230
+ const providerKeys = {
231
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
232
+ };
233
+ providerKeys['openrouter'] = cleanKey;
234
+ currentConfig.providerKeys = providerKeys;
235
+ if (options.dataCollection) {
236
+ currentConfig.openrouterDataCollection = options.dataCollection;
237
+ }
238
+ else if (!currentConfig.openrouterDataCollection) {
239
+ currentConfig.openrouterDataCollection = 'deny';
240
+ }
241
+ if (options.setAsActive) {
242
+ currentConfig.provider = 'openrouter';
243
+ currentConfig.model = OPENROUTER_FREE_MODEL;
244
+ currentConfig.apiKey = cleanKey;
245
+ }
246
+ store.saveConfig(currentConfig);
247
+ return currentConfig;
248
+ }
249
+ /**
250
+ * Disconnect OpenRouter credentials from local vault.
251
+ */
252
+ export function disconnectOpenRouter(store = { loadConfig, saveConfig }) {
253
+ const currentConfig = store.loadConfig() || {};
254
+ const providerKeys = {
255
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
256
+ };
257
+ delete providerKeys['openrouter'];
258
+ currentConfig.providerKeys = providerKeys;
259
+ if (currentConfig.provider === 'openrouter') {
260
+ currentConfig.provider = 'deepseek';
261
+ currentConfig.model = 'deepseek-chat';
262
+ currentConfig.apiKey = providerKeys['deepseek'] || '';
263
+ }
264
+ store.saveConfig(currentConfig);
265
+ return currentConfig;
266
+ }
267
+ /**
268
+ * Retrieve live OpenRouter connection and privacy status.
269
+ */
270
+ export function getOpenRouterStatus(cfg) {
271
+ const config = cfg || loadConfig() || {};
272
+ const vaultKey = config.providerKeys?.openrouter || (config.provider === 'openrouter' ? config.apiKey : '');
273
+ const envKey = process.env.OPENROUTER_API_KEY;
274
+ const connectedKey = vaultKey || envKey || '';
275
+ const isConnected = Boolean(connectedKey);
276
+ const isActive = config.provider === 'openrouter';
277
+ const currentModel = isActive ? (config.model || OPENROUTER_FREE_MODEL) : OPENROUTER_FREE_MODEL;
278
+ const dataCollection = config.openrouterDataCollection === 'allow' ? 'allow' : 'deny';
279
+ return {
280
+ connected: isConnected,
281
+ active: isActive,
282
+ model: currentModel,
283
+ dataCollection,
284
+ maskedKey: isConnected ? maskApiKey(connectedKey) : undefined,
285
+ keySource: vaultKey ? 'vault' : (envKey ? 'environment' : undefined)
286
+ };
287
+ }
288
+ /**
289
+ * Update user's OpenRouter data collection preference.
290
+ */
291
+ export function setOpenRouterDataCollection(preference, store = { loadConfig, saveConfig }) {
292
+ const config = store.loadConfig() || {};
293
+ config.openrouterDataCollection = preference;
294
+ store.saveConfig(config);
295
+ return config;
296
+ }