@myrialabs/clopen 0.2.23 → 0.2.24

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,27 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create opencode_providers table for multi-provider management';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating opencode_providers table...');
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS opencode_providers (
10
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ provider_id TEXT NOT NULL UNIQUE,
12
+ name TEXT NOT NULL,
13
+ npm TEXT NOT NULL,
14
+ api_url TEXT,
15
+ options TEXT DEFAULT '{}',
16
+ is_enabled INTEGER NOT NULL DEFAULT 1,
17
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
18
+ )
19
+ `);
20
+ debug.log('migration', 'opencode_providers table created');
21
+ };
22
+
23
+ export const down = (db: DatabaseConnection): void => {
24
+ debug.log('migration', 'Dropping opencode_providers table...');
25
+ db.exec('DROP TABLE IF EXISTS opencode_providers');
26
+ debug.log('migration', 'opencode_providers table dropped');
27
+ };
@@ -0,0 +1,25 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create opencode_accounts table for per-provider multi-account management';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating opencode_accounts table...');
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS opencode_accounts (
10
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ provider_id INTEGER NOT NULL REFERENCES opencode_providers(id) ON DELETE CASCADE,
12
+ name TEXT NOT NULL,
13
+ api_key TEXT NOT NULL,
14
+ is_active INTEGER NOT NULL DEFAULT 0,
15
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
16
+ )
17
+ `);
18
+ debug.log('migration', 'opencode_accounts table created');
19
+ };
20
+
21
+ export const down = (db: DatabaseConnection): void => {
22
+ debug.log('migration', 'Dropping opencode_accounts table...');
23
+ db.exec('DROP TABLE IF EXISTS opencode_accounts');
24
+ debug.log('migration', 'opencode_accounts table dropped');
25
+ };
@@ -25,6 +25,8 @@ import * as migration023 from './023_create_user_unread_sessions_table';
25
25
  import * as migration024 from './024_create_users_table';
26
26
  import * as migration025 from './025_create_auth_sessions_table';
27
27
  import * as migration026 from './026_create_invite_tokens_table';
28
+ import * as migration027 from './027_create_opencode_providers_table';
29
+ import * as migration028 from './028_create_opencode_accounts_table';
28
30
 
29
31
  // Export all migrations in order
30
32
  export const migrations = [
@@ -183,6 +185,18 @@ export const migrations = [
183
185
  description: migration026.description,
184
186
  up: migration026.up,
185
187
  down: migration026.down
188
+ },
189
+ {
190
+ id: '027',
191
+ description: migration027.description,
192
+ up: migration027.up,
193
+ down: migration027.down
194
+ },
195
+ {
196
+ id: '028',
197
+ description: migration028.description,
198
+ up: migration028.up,
199
+ down: migration028.down
186
200
  }
187
201
  ];
188
202
 
@@ -7,4 +7,5 @@ export { dbUtils } from './utils-queries';
7
7
  export { snapshotQueries } from './snapshot-queries';
8
8
  export { checkpointQueries } from './checkpoint-queries';
9
9
  export { engineQueries } from './engine-queries';
10
- export { authQueries } from './auth-queries';
10
+ export { authQueries } from './auth-queries';
11
+ export { opencodeProviderQueries } from './opencode-provider-queries';
@@ -0,0 +1,190 @@
1
+ import { getDatabase } from '../index';
2
+
3
+ export interface OpenCodeProvider {
4
+ id: number;
5
+ provider_id: string;
6
+ name: string;
7
+ npm: string;
8
+ api_url: string | null;
9
+ options: string;
10
+ is_enabled: number;
11
+ created_at: string;
12
+ }
13
+
14
+ export interface OpenCodeAccount {
15
+ id: number;
16
+ provider_id: number;
17
+ name: string;
18
+ api_key: string;
19
+ is_active: number;
20
+ created_at: string;
21
+ }
22
+
23
+ /** Provider with its accounts joined */
24
+ export interface OpenCodeProviderWithAccounts extends OpenCodeProvider {
25
+ accounts: OpenCodeAccount[];
26
+ }
27
+
28
+ export const opencodeProviderQueries = {
29
+ // ========================================================================
30
+ // Providers
31
+ // ========================================================================
32
+
33
+ getProviders(): OpenCodeProvider[] {
34
+ const db = getDatabase();
35
+ return db.prepare(`
36
+ SELECT * FROM opencode_providers
37
+ ORDER BY created_at ASC
38
+ `).all() as OpenCodeProvider[];
39
+ },
40
+
41
+ getEnabledProviders(): OpenCodeProvider[] {
42
+ const db = getDatabase();
43
+ return db.prepare(`
44
+ SELECT * FROM opencode_providers
45
+ WHERE is_enabled = 1
46
+ ORDER BY created_at ASC
47
+ `).all() as OpenCodeProvider[];
48
+ },
49
+
50
+ getProvider(id: number): OpenCodeProvider | null {
51
+ const db = getDatabase();
52
+ return db.prepare(`
53
+ SELECT * FROM opencode_providers WHERE id = ?
54
+ `).get(id) as OpenCodeProvider | null;
55
+ },
56
+
57
+ getProviderByProviderId(providerId: string): OpenCodeProvider | null {
58
+ const db = getDatabase();
59
+ return db.prepare(`
60
+ SELECT * FROM opencode_providers WHERE provider_id = ?
61
+ `).get(providerId) as OpenCodeProvider | null;
62
+ },
63
+
64
+ createProvider(data: {
65
+ providerId: string;
66
+ name: string;
67
+ npm: string;
68
+ apiUrl?: string;
69
+ options?: string;
70
+ }): OpenCodeProvider {
71
+ const db = getDatabase();
72
+ db.prepare(`
73
+ INSERT INTO opencode_providers (provider_id, name, npm, api_url, options)
74
+ VALUES (?, ?, ?, ?, ?)
75
+ `).run(
76
+ data.providerId,
77
+ data.name,
78
+ data.npm,
79
+ data.apiUrl || null,
80
+ data.options || '{}'
81
+ );
82
+
83
+ const inserted = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
84
+ return db.prepare('SELECT * FROM opencode_providers WHERE id = ?').get(inserted.id) as OpenCodeProvider;
85
+ },
86
+
87
+ updateProviderOptions(id: number, options: string): void {
88
+ const db = getDatabase();
89
+ db.prepare('UPDATE opencode_providers SET options = ? WHERE id = ?').run(options, id);
90
+ },
91
+
92
+ toggleProvider(id: number, enabled: boolean): void {
93
+ const db = getDatabase();
94
+ db.prepare('UPDATE opencode_providers SET is_enabled = ? WHERE id = ?').run(enabled ? 1 : 0, id);
95
+ },
96
+
97
+ deleteProvider(id: number): void {
98
+ const db = getDatabase();
99
+ // Accounts are cascade-deleted via FK constraint
100
+ db.prepare('DELETE FROM opencode_providers WHERE id = ?').run(id);
101
+ },
102
+
103
+ // ========================================================================
104
+ // Accounts
105
+ // ========================================================================
106
+
107
+ getAccountsByProvider(providerDbId: number): OpenCodeAccount[] {
108
+ const db = getDatabase();
109
+ return db.prepare(`
110
+ SELECT * FROM opencode_accounts
111
+ WHERE provider_id = ?
112
+ ORDER BY created_at ASC
113
+ `).all(providerDbId) as OpenCodeAccount[];
114
+ },
115
+
116
+ getActiveAccount(providerDbId: number): OpenCodeAccount | null {
117
+ const db = getDatabase();
118
+ return db.prepare(`
119
+ SELECT * FROM opencode_accounts
120
+ WHERE provider_id = ? AND is_active = 1
121
+ `).get(providerDbId) as OpenCodeAccount | null;
122
+ },
123
+
124
+ createAccount(providerDbId: number, name: string, apiKey: string): OpenCodeAccount {
125
+ const db = getDatabase();
126
+
127
+ // If first account for this provider, make it active
128
+ const count = (db.prepare(
129
+ 'SELECT COUNT(*) as count FROM opencode_accounts WHERE provider_id = ?'
130
+ ).get(providerDbId) as { count: number }).count;
131
+ const isActive = count === 0 ? 1 : 0;
132
+
133
+ db.prepare(`
134
+ INSERT INTO opencode_accounts (provider_id, name, api_key, is_active)
135
+ VALUES (?, ?, ?, ?)
136
+ `).run(providerDbId, name, apiKey, isActive);
137
+
138
+ const inserted = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
139
+ return db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(inserted.id) as OpenCodeAccount;
140
+ },
141
+
142
+ switchAccount(accountId: number): void {
143
+ const db = getDatabase();
144
+
145
+ // Get the provider_id for this account
146
+ const account = db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(accountId) as OpenCodeAccount | null;
147
+ if (!account) return;
148
+
149
+ // Deactivate all accounts for this provider, then activate the target
150
+ db.prepare('UPDATE opencode_accounts SET is_active = 0 WHERE provider_id = ?').run(account.provider_id);
151
+ db.prepare('UPDATE opencode_accounts SET is_active = 1 WHERE id = ?').run(accountId);
152
+ },
153
+
154
+ deleteAccount(accountId: number): void {
155
+ const db = getDatabase();
156
+
157
+ const account = db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(accountId) as OpenCodeAccount | null;
158
+ if (!account) return;
159
+
160
+ const wasActive = account.is_active === 1;
161
+ db.prepare('DELETE FROM opencode_accounts WHERE id = ?').run(accountId);
162
+
163
+ // If deleted account was active, activate first remaining account for this provider
164
+ if (wasActive) {
165
+ const remaining = db.prepare(
166
+ 'SELECT id FROM opencode_accounts WHERE provider_id = ? ORDER BY created_at ASC LIMIT 1'
167
+ ).get(account.provider_id) as { id: number } | null;
168
+ if (remaining) {
169
+ db.prepare('UPDATE opencode_accounts SET is_active = 1 WHERE id = ?').run(remaining.id);
170
+ }
171
+ }
172
+ },
173
+
174
+ renameAccount(accountId: number, name: string): void {
175
+ const db = getDatabase();
176
+ db.prepare('UPDATE opencode_accounts SET name = ? WHERE id = ?').run(name, accountId);
177
+ },
178
+
179
+ // ========================================================================
180
+ // Composite: Providers with Accounts
181
+ // ========================================================================
182
+
183
+ getProvidersWithAccounts(): OpenCodeProviderWithAccounts[] {
184
+ const providers = this.getProviders();
185
+ return providers.map(p => ({
186
+ ...p,
187
+ accounts: this.getAccountsByProvider(p.id)
188
+ }));
189
+ },
190
+ };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * OpenCode Provider Config Management
3
+ *
4
+ * - Fetches and caches provider catalog from models.dev/api.json
5
+ * - Generates OPENCODE_CONFIG_CONTENT JSON from DB providers + active accounts
6
+ * - Provides restart logic for the OpenCode server
7
+ */
8
+
9
+ import { settingsQueries, opencodeProviderQueries } from '../../../database/queries';
10
+ import { debug } from '$shared/utils/logger';
11
+
12
+ const MODELS_DEV_URL = 'https://models.dev/api.json';
13
+ const CACHE_KEY = 'opencode.models_dev_cache';
14
+ const CACHE_TS_KEY = 'opencode.models_dev_cached_at';
15
+
16
+ // ============================================================================
17
+ // Models.dev Catalog (provider metadata for the "Add Provider" picker)
18
+ // ============================================================================
19
+
20
+ /** Minimal provider info from models.dev — only what we need for the picker */
21
+ export interface ModelsDevProvider {
22
+ id: string;
23
+ name: string;
24
+ npm: string;
25
+ env: string[];
26
+ api: string | null;
27
+ }
28
+
29
+ /**
30
+ * Fetch models.dev/api.json and cache a minimal provider catalog in the DB.
31
+ * Returns the parsed catalog.
32
+ */
33
+ export async function fetchAndCacheModelsDevCatalog(): Promise<ModelsDevProvider[]> {
34
+ debug.log('engine', 'Fetching models.dev catalog...');
35
+
36
+ const response = await fetch(MODELS_DEV_URL, {
37
+ signal: AbortSignal.timeout(30_000),
38
+ });
39
+
40
+ if (!response.ok) {
41
+ throw new Error(`Failed to fetch models.dev: ${response.status} ${response.statusText}`);
42
+ }
43
+
44
+ const raw = await response.json() as Record<string, {
45
+ id?: string;
46
+ name?: string;
47
+ npm?: string;
48
+ env?: string[];
49
+ api?: string;
50
+ models?: Record<string, unknown>;
51
+ }>;
52
+
53
+ // Extract only what we need: id, name, npm, env, api
54
+ const catalog: ModelsDevProvider[] = [];
55
+ for (const [key, entry] of Object.entries(raw)) {
56
+ if (!entry.npm) continue; // Skip entries without npm package
57
+ catalog.push({
58
+ id: entry.id || key,
59
+ name: entry.name || key,
60
+ npm: entry.npm,
61
+ env: entry.env || [],
62
+ api: entry.api || null,
63
+ });
64
+ }
65
+
66
+ // Sort alphabetically by name
67
+ catalog.sort((a, b) => a.name.localeCompare(b.name));
68
+
69
+ // Cache in DB
70
+ settingsQueries.set(CACHE_KEY, JSON.stringify(catalog));
71
+ settingsQueries.set(CACHE_TS_KEY, new Date().toISOString());
72
+
73
+ debug.log('engine', `Cached ${catalog.length} providers from models.dev`);
74
+ return catalog;
75
+ }
76
+
77
+ /**
78
+ * Get the cached models.dev catalog from DB. Returns null if not cached.
79
+ */
80
+ export function getCachedModelsDevCatalog(): { catalog: ModelsDevProvider[]; cachedAt: string } | null {
81
+ const cached = settingsQueries.get(CACHE_KEY);
82
+ const cachedAt = settingsQueries.get(CACHE_TS_KEY);
83
+
84
+ if (!cached?.value || !cachedAt?.value) return null;
85
+
86
+ try {
87
+ return {
88
+ catalog: JSON.parse(cached.value) as ModelsDevProvider[],
89
+ cachedAt: cachedAt.value,
90
+ };
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ // ============================================================================
97
+ // OpenCode Config Generation
98
+ // ============================================================================
99
+
100
+ export interface OpenCodeProviderConfigResult {
101
+ /** List of enabled provider IDs for OPENCODE_CONFIG_CONTENT */
102
+ enabledProviders: string[];
103
+ /** Env vars to inject (actual env var names → values) */
104
+ envVars: Record<string, string>;
105
+ }
106
+
107
+ /**
108
+ * Generate OpenCode provider config from DB providers + active accounts.
109
+ *
110
+ * Returns:
111
+ * - enabledProviders: list of provider IDs to put in OPENCODE_CONFIG_CONTENT
112
+ * - envVars: actual environment variables to inject into the spawned process
113
+ *
114
+ * API keys are injected as env vars using the original env var names from
115
+ * the models.dev catalog (stored in the provider's options JSON), NOT as
116
+ * hardcoded "apiKey" in the config JSON.
117
+ */
118
+ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
119
+ const providers = opencodeProviderQueries.getEnabledProviders();
120
+ const enabledProviders: string[] = ['opencode'];
121
+ const envVars: Record<string, string> = {};
122
+
123
+ for (const provider of providers) {
124
+ const activeAccount = opencodeProviderQueries.getActiveAccount(provider.id);
125
+ if (!activeAccount) continue;
126
+
127
+ enabledProviders.push(provider.provider_id);
128
+
129
+ // Parse stored options which may contain additional env var values
130
+ let options: Record<string, string> = {};
131
+ try {
132
+ options = JSON.parse(provider.options || '{}');
133
+ } catch {
134
+ options = {};
135
+ }
136
+
137
+ // Look up the catalog entry to get the actual env var names
138
+ const cached = getCachedModelsDevCatalog();
139
+ const catalogEntry = cached?.catalog.find(c => c.id === provider.provider_id);
140
+ const envNames = catalogEntry?.env || [];
141
+
142
+ // First env var gets the active account's API key
143
+ if (envNames.length > 0) {
144
+ envVars[envNames[0]] = activeAccount.api_key;
145
+ }
146
+
147
+ // Additional env vars from options (stored by their env var name)
148
+ for (const envName of envNames.slice(1)) {
149
+ if (options[envName]) {
150
+ envVars[envName] = options[envName];
151
+ }
152
+ }
153
+ }
154
+
155
+ return { enabledProviders, envVars };
156
+ }
@@ -15,6 +15,7 @@ import type { OpencodeClient } from '@opencode-ai/sdk';
15
15
  import type { Subprocess } from 'bun';
16
16
  import { getOpenCodeMcpConfig } from '../../../mcp';
17
17
  import { settingsQueries } from '../../../database/queries';
18
+ import { generateOpenCodeProviderConfig } from './config';
18
19
  import { debug } from '$shared/utils/logger';
19
20
 
20
21
  const OPENCODE_HOST = '127.0.0.1';
@@ -142,8 +143,25 @@ async function init(): Promise<void> {
142
143
  }
143
144
  }
144
145
 
145
- const configContent = Object.keys(mcpConfig).length > 0
146
- ? JSON.stringify({ mcp: mcpConfig })
146
+ // Build provider config from DB (enabled providers + env vars)
147
+ const providerConfig = generateOpenCodeProviderConfig();
148
+ if (providerConfig.enabledProviders.length > 0) {
149
+ debug.log('engine', `Open Code server: enabling ${providerConfig.enabledProviders.length} provider(s): ${providerConfig.enabledProviders.join(', ')}`);
150
+ }
151
+ if (Object.keys(providerConfig.envVars).length > 0) {
152
+ debug.log('engine', `Open Code server: injecting ${Object.keys(providerConfig.envVars).length} env var(s): ${Object.keys(providerConfig.envVars).join(', ')}`);
153
+ }
154
+
155
+ // Merge MCP config + enabled_providers into a single OPENCODE_CONFIG_CONTENT
156
+ const mergedConfig: Record<string, unknown> = {};
157
+ if (Object.keys(mcpConfig).length > 0) {
158
+ mergedConfig.mcp = mcpConfig;
159
+ }
160
+ if (providerConfig.enabledProviders.length > 0) {
161
+ mergedConfig.enabled_providers = providerConfig.enabledProviders;
162
+ }
163
+ const configContent = Object.keys(mergedConfig).length > 0
164
+ ? JSON.stringify(mergedConfig)
147
165
  : '{}';
148
166
 
149
167
  debug.log('engine', `Spawning: ${args.join(' ')}`);
@@ -153,6 +171,7 @@ async function init(): Promise<void> {
153
171
  stderr: 'pipe',
154
172
  env: {
155
173
  ...process.env,
174
+ ...providerConfig.envVars,
156
175
  OPENCODE_CONFIG_CONTENT: configContent,
157
176
  },
158
177
  });
@@ -230,18 +249,41 @@ export function getServerUrl(): string | null {
230
249
  /**
231
250
  * Dispose the OpenCode client and stop the server.
232
251
  *
233
- * Only kills the child process when we spawned it. Reused servers stay alive
234
- * so the next session can pick them up without spawning a new process.
252
+ * @param forRestart — When true, always kills the server process (even if
253
+ * we didn't spawn it) and purges the stored URL so the next init() spawns
254
+ * a fresh server with updated config. Used by the Restart Server flow.
255
+ *
256
+ * When false (default), only kills the child process when we spawned it.
257
+ * Reused servers stay alive so the next session can pick them up.
235
258
  */
236
- export async function disposeOpenCodeClient(): Promise<void> {
237
- if (serverHandle && ownsProcess) {
238
- try {
239
- debug.log('engine', `Stopping Open Code server (${serverHandle.url})...`);
240
- serverHandle.close();
241
- settingsQueries.delete(DB_KEY);
242
- } catch (error) {
243
- debug.error('engine', 'Error stopping Open Code server:', error);
259
+ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
260
+ if (serverHandle) {
261
+ if (ownsProcess || forRestart) {
262
+ try {
263
+ debug.log('engine', `Stopping Open Code server (${serverHandle.url}, forRestart=${forRestart})...`);
264
+ if (ownsProcess) {
265
+ serverHandle.close();
266
+ } else if (forRestart) {
267
+ // Server we didn't spawn — kill it by sending a request or just
268
+ // purging the stored URL. The server process may be external, but
269
+ // clearing DB ensures we spawn a new one on next init().
270
+ try {
271
+ await fetch(`${serverHandle.url}/shutdown`, {
272
+ method: 'POST',
273
+ signal: AbortSignal.timeout(2000),
274
+ });
275
+ } catch {
276
+ // shutdown endpoint may not exist — that's fine
277
+ }
278
+ }
279
+ settingsQueries.delete(DB_KEY);
280
+ } catch (error) {
281
+ debug.error('engine', 'Error stopping Open Code server:', error);
282
+ }
244
283
  }
284
+ } else if (forRestart) {
285
+ // No active handle but forRestart requested — ensure DB is clean
286
+ settingsQueries.delete(DB_KEY);
245
287
  }
246
288
 
247
289
  clearClientState();
@@ -6,6 +6,8 @@
6
6
 
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { openCodeStatusHandler } from './status';
9
+ import { openCodeProviderHandler } from './providers';
9
10
 
10
11
  export const openCodeEngineRouter = createRouter()
11
- .merge(openCodeStatusHandler);
12
+ .merge(openCodeStatusHandler)
13
+ .merge(openCodeProviderHandler);