@myrialabs/clopen 0.3.7 → 0.3.9
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/backend/auth/permissions.ts +41 -2
- package/backend/chat/stream-manager.ts +71 -0
- package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
- package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +43 -1
- package/backend/database/queries/db-client-connection-queries.ts +343 -0
- package/backend/database/queries/db-client-query-history-queries.ts +113 -0
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/project-queries.ts +28 -0
- package/backend/db-client/connection-manager.ts +257 -0
- package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
- package/backend/db-client/drivers/mongodb.ts +358 -0
- package/backend/db-client/drivers/mysql.ts +385 -0
- package/backend/db-client/drivers/postgres.ts +446 -0
- package/backend/db-client/drivers/redis.ts +267 -0
- package/backend/db-client/drivers/sql-builders.ts +215 -0
- package/backend/db-client/drivers/sqlite.ts +346 -0
- package/backend/db-client/drivers/types.ts +92 -0
- package/backend/db-client/query-executor.ts +126 -0
- package/backend/db-client/ssh-tunnel.ts +122 -0
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +573 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +5 -115
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +380 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/git/git-service.ts +12 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/scripts/video-stream.ts +9 -3
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/chat/stream.ts +36 -12
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +194 -0
- package/backend/ws/db-client/index.ts +17 -0
- package/backend/ws/db-client/io.ts +456 -0
- package/backend/ws/db-client/query.ts +214 -0
- package/backend/ws/db-client/schema.ts +81 -0
- package/backend/ws/db-client/structure.ts +230 -0
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/index.ts +5 -1
- package/backend/ws/files/read.ts +34 -0
- package/backend/ws/files/state.ts +42 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/index.ts +5 -1
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +5 -40
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +4 -10
- package/backend/ws/projects/status.ts +2 -0
- package/backend/ws/sessions/crud.ts +22 -33
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +12 -6
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
- package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
- package/dist/assets/main-hspyFOoK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +7 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +49 -1
- package/shared/types/db-client/connection.ts +60 -0
- package/shared/types/db-client/index.ts +6 -0
- package/shared/types/db-client/query.ts +77 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-jTnmAoXS.css +0 -1
|
@@ -1,107 +1,51 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* OpenCode
|
|
2
|
+
* OpenCode runtime config builder.
|
|
3
3
|
*
|
|
4
|
-
* -
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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.
|
|
4
|
+
* Translates DB-stored providers + active accounts into the env-var bundle
|
|
5
|
+
* (`enabledProviders`, `envVars`) consumed by the spawned OpenCode server.
|
|
6
|
+
*
|
|
7
|
+
* The catalog itself (multi-provider preset metadata fetched from
|
|
8
|
+
* models.dev) lives in `./presets.ts` — see README §4.5 for the file-naming
|
|
9
|
+
* standard.
|
|
32
10
|
*/
|
|
33
|
-
export async function fetchAndCacheModelsDevCatalog(): Promise<ModelsDevProvider[]> {
|
|
34
|
-
debug.log('engine', 'Fetching models.dev catalog...');
|
|
35
11
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
});
|
|
12
|
+
import { engineQueries } from '../../../database/queries';
|
|
13
|
+
import { getCachedModelsDevCatalog } from './presets';
|
|
39
14
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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;
|
|
15
|
+
export interface OpenCodeProviderConfigResult {
|
|
16
|
+
/** List of enabled provider IDs for OPENCODE_CONFIG_CONTENT */
|
|
17
|
+
enabledProviders: string[];
|
|
18
|
+
/** Env vars to inject (actual env var names → values) */
|
|
19
|
+
envVars: Record<string, string>;
|
|
75
20
|
}
|
|
76
21
|
|
|
77
22
|
/**
|
|
78
|
-
*
|
|
23
|
+
* Parse an account credential into a per-env-var map.
|
|
24
|
+
*
|
|
25
|
+
* Accounts created with multi-env-var providers (e.g. AWS Bedrock,
|
|
26
|
+
* Cloudflare) store all secrets as a JSON object in `credential`:
|
|
27
|
+
* `{"AWS_ACCESS_KEY_ID": "...", "AWS_SECRET_ACCESS_KEY": "..."}`.
|
|
28
|
+
*
|
|
29
|
+
* Older single-env-var accounts store the raw secret string. Returns null
|
|
30
|
+
* when the credential is not a JSON object so callers can fall back to the
|
|
31
|
+
* legacy single-key behavior.
|
|
79
32
|
*/
|
|
80
|
-
export function
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if (!cached?.value || !cachedAt?.value) return null;
|
|
85
|
-
|
|
33
|
+
export function parseCredentialMap(credential: string): Record<string, string> | null {
|
|
34
|
+
const trimmed = credential.trim();
|
|
35
|
+
if (!trimmed.startsWith('{')) return null;
|
|
86
36
|
try {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
37
|
+
const parsed = JSON.parse(trimmed);
|
|
38
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
39
|
+
const out: Record<string, string> = {};
|
|
40
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
41
|
+
if (typeof v === 'string') out[k] = v;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
91
45
|
} catch {
|
|
92
46
|
return null;
|
|
93
47
|
}
|
|
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>;
|
|
48
|
+
return null;
|
|
105
49
|
}
|
|
106
50
|
|
|
107
51
|
/**
|
|
@@ -111,9 +55,10 @@ export interface OpenCodeProviderConfigResult {
|
|
|
111
55
|
* - enabledProviders: list of provider IDs to put in OPENCODE_CONFIG_CONTENT
|
|
112
56
|
* - envVars: actual environment variables to inject into the spawned process
|
|
113
57
|
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
58
|
+
* Per-account credentials may be a JSON object holding all required env vars
|
|
59
|
+
* for that account, or a plain string (legacy single-env-var format). When
|
|
60
|
+
* plain, the value is bound to the catalog's first env name and the rest
|
|
61
|
+
* fall back to the provider's shared `options` JSON.
|
|
117
62
|
*/
|
|
118
63
|
export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
|
|
119
64
|
const providers = engineQueries.getEnabledProviders('opencode');
|
|
@@ -126,7 +71,6 @@ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
|
|
|
126
71
|
|
|
127
72
|
enabledProviders.push(provider.slug);
|
|
128
73
|
|
|
129
|
-
// Parse stored options which may contain additional env var values
|
|
130
74
|
let options: Record<string, string> = {};
|
|
131
75
|
try {
|
|
132
76
|
options = JSON.parse(provider.options || '{}');
|
|
@@ -134,20 +78,28 @@ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
|
|
|
134
78
|
options = {};
|
|
135
79
|
}
|
|
136
80
|
|
|
137
|
-
// Look up the catalog entry to get the actual env var names
|
|
138
81
|
const cached = getCachedModelsDevCatalog();
|
|
139
82
|
const catalogEntry = cached?.catalog.find(c => c.id === provider.slug);
|
|
140
83
|
const envNames = catalogEntry?.env || [];
|
|
141
84
|
|
|
142
|
-
|
|
143
|
-
if (envNames.length > 0) {
|
|
144
|
-
envVars[envNames[0]] = activeAccount.credential;
|
|
145
|
-
}
|
|
85
|
+
const credentialMap = parseCredentialMap(activeAccount.credential);
|
|
146
86
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
87
|
+
if (credentialMap) {
|
|
88
|
+
// New format: account credential carries every env var the
|
|
89
|
+
// provider needs. Provider options remain a fallback for any
|
|
90
|
+
// missing keys (e.g. region defaults).
|
|
91
|
+
for (const envName of envNames) {
|
|
92
|
+
const value = credentialMap[envName] ?? options[envName];
|
|
93
|
+
if (value) envVars[envName] = value;
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
if (envNames.length > 0) {
|
|
97
|
+
envVars[envNames[0]] = activeAccount.credential;
|
|
98
|
+
}
|
|
99
|
+
for (const envName of envNames.slice(1)) {
|
|
100
|
+
if (options[envName]) {
|
|
101
|
+
envVars[envName] = options[envName];
|
|
102
|
+
}
|
|
151
103
|
}
|
|
152
104
|
}
|
|
153
105
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Open Code SDK error handler.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors the Claude/Codex/Qwen pattern: swallow abort errors and surface a
|
|
5
|
+
* sanitised message. OpenCode's `session.error` event carries a structured
|
|
6
|
+
* `{ name, data }` payload from the SDK — `formatSessionError` extracts a
|
|
7
|
+
* human-readable string from it before the adapter throws.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { EventSessionError } from '@opencode-ai/sdk';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Extract a human-readable error message from an OpenCode `session.error` event.
|
|
14
|
+
*
|
|
15
|
+
* OpenCode SDK errors follow `{ name: string, data: { message, statusCode?,
|
|
16
|
+
* providerID?, responseBody? } }`. We don't prepend the error class name (e.g.
|
|
17
|
+
* "APIError") since those are SDK implementation details.
|
|
18
|
+
*/
|
|
19
|
+
export function formatSessionError(errorProps: EventSessionError['properties']): string {
|
|
20
|
+
const { error } = errorProps;
|
|
21
|
+
if (!error) return 'Unknown Open Code error';
|
|
22
|
+
|
|
23
|
+
const errObj = error as Record<string, any>;
|
|
24
|
+
const name = errObj.name || '';
|
|
25
|
+
const dataMsg = errObj.data?.message || '';
|
|
26
|
+
const statusCode = errObj.data?.statusCode;
|
|
27
|
+
const providerID = errObj.data?.providerID;
|
|
28
|
+
const responseBody = errObj.data?.responseBody;
|
|
29
|
+
|
|
30
|
+
let errorMsg = 'Unknown Open Code error';
|
|
31
|
+
if (dataMsg) {
|
|
32
|
+
errorMsg = dataMsg;
|
|
33
|
+
} else if (responseBody) {
|
|
34
|
+
try {
|
|
35
|
+
const body = typeof responseBody === 'string' ? JSON.parse(responseBody) : responseBody;
|
|
36
|
+
errorMsg = body?.error?.message || body?.message || String(responseBody);
|
|
37
|
+
} catch {
|
|
38
|
+
errorMsg = String(responseBody);
|
|
39
|
+
}
|
|
40
|
+
} else if (name) {
|
|
41
|
+
errorMsg = name;
|
|
42
|
+
} else if (typeof error === 'string') {
|
|
43
|
+
errorMsg = error;
|
|
44
|
+
} else {
|
|
45
|
+
errorMsg = JSON.stringify(error);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (statusCode) {
|
|
49
|
+
errorMsg += ` (status ${statusCode})`;
|
|
50
|
+
}
|
|
51
|
+
if (providerID) {
|
|
52
|
+
errorMsg += ` [provider: ${providerID}]`;
|
|
53
|
+
}
|
|
54
|
+
return errorMsg;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Swallow expected abort errors; re-throw everything else unchanged.
|
|
59
|
+
*
|
|
60
|
+
* OpenCode's catch handler is intentionally thin — `session.error` events are
|
|
61
|
+
* already pre-formatted into Error objects upstream, so we don't need a second
|
|
62
|
+
* normalisation pass here.
|
|
63
|
+
*/
|
|
64
|
+
export function handleStreamError(error: unknown): void {
|
|
65
|
+
if (error instanceof Error) {
|
|
66
|
+
if (error.name === 'AbortError' || error.message.includes('aborted')) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Open Code dynamic model discovery.
|
|
3
|
+
*
|
|
4
|
+
* Open Code's `client.config.providers()` endpoint returns the active
|
|
5
|
+
* provider/model catalog (Anthropic, OpenAI, Groq, etc. — whatever is
|
|
6
|
+
* configured server-side). We translate that response into `EngineModel[]`
|
|
7
|
+
* preserving full modality and capability metadata exposed by the SDK.
|
|
8
|
+
*
|
|
9
|
+
* Returns `[]` on any failure (network, auth, malformed body) — the
|
|
10
|
+
* picker simply renders empty rather than a stale curated list.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { EngineModel } from '$shared/types/unified';
|
|
14
|
+
import type { OpencodeClient, Provider, Model } from '@opencode-ai/sdk';
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
|
|
17
|
+
export async function fetchOpenCodeModels(client: OpencodeClient): Promise<EngineModel[]> {
|
|
18
|
+
try {
|
|
19
|
+
const response = await client.config.providers();
|
|
20
|
+
const providers: Provider[] = response.data?.providers ?? [];
|
|
21
|
+
const models: EngineModel[] = [];
|
|
22
|
+
|
|
23
|
+
for (const provider of providers) {
|
|
24
|
+
const providerModels: Record<string, Model> = provider.models ?? {};
|
|
25
|
+
|
|
26
|
+
for (const [, model] of Object.entries(providerModels)) {
|
|
27
|
+
models.push({
|
|
28
|
+
engine: {
|
|
29
|
+
type: 'opencode',
|
|
30
|
+
provider: provider.id,
|
|
31
|
+
model: {
|
|
32
|
+
id: model.id,
|
|
33
|
+
name: model.name,
|
|
34
|
+
},
|
|
35
|
+
account: {
|
|
36
|
+
id: 0,
|
|
37
|
+
name: '',
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
limit: {
|
|
41
|
+
input: model.limit.context,
|
|
42
|
+
output: model.limit.output,
|
|
43
|
+
},
|
|
44
|
+
modalities: {
|
|
45
|
+
input: {
|
|
46
|
+
text: model.capabilities.input.text,
|
|
47
|
+
image: model.capabilities.input.image,
|
|
48
|
+
audio: model.capabilities.input.audio,
|
|
49
|
+
video: model.capabilities.input.video,
|
|
50
|
+
pdf: model.capabilities.input.pdf,
|
|
51
|
+
},
|
|
52
|
+
output: {
|
|
53
|
+
text: model.capabilities.output.text,
|
|
54
|
+
image: model.capabilities.output.image,
|
|
55
|
+
audio: model.capabilities.output.audio,
|
|
56
|
+
video: model.capabilities.output.video,
|
|
57
|
+
pdf: model.capabilities.output.pdf,
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
capabilities: {
|
|
61
|
+
reasoning: model.capabilities.reasoning,
|
|
62
|
+
tools: model.capabilities.toolcall,
|
|
63
|
+
structuredOutput: true,
|
|
64
|
+
},
|
|
65
|
+
cost: {
|
|
66
|
+
input: model.cost.input,
|
|
67
|
+
output: model.cost.output,
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
debug.log('engine', `Fetched ${models.length} models from ${providers.length} Open Code providers`);
|
|
74
|
+
return models;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
debug.error('engine', 'Failed to fetch Open Code providers:', error);
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode Provider Catalog (models.dev)
|
|
3
|
+
*
|
|
4
|
+
* Multi-provider preset metadata for OpenCode — fetched from
|
|
5
|
+
* `models.dev/api.json` and cached in the settings table. Drives the
|
|
6
|
+
* "Add Provider" picker in Settings → Engines → OpenCode.
|
|
7
|
+
*
|
|
8
|
+
* This file mirrors `qwen/presets.ts` (the canonical name for multi-provider
|
|
9
|
+
* preset catalogs — see README §4.5). The runtime config builder that turns
|
|
10
|
+
* DB-stored providers into env vars + `OPENCODE_CONFIG_CONTENT` lives in
|
|
11
|
+
* `./config.ts`.
|
|
12
|
+
*/
|
|
13
|
+
import { settingsQueries } from '../../../database/queries';
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
|
|
16
|
+
const MODELS_DEV_URL = 'https://models.dev/api.json';
|
|
17
|
+
const CACHE_KEY = 'opencode.models_dev_cache';
|
|
18
|
+
const CACHE_TS_KEY = 'opencode.models_dev_cached_at';
|
|
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
|
+
const catalog: ModelsDevProvider[] = [];
|
|
54
|
+
for (const [key, entry] of Object.entries(raw)) {
|
|
55
|
+
if (!entry.npm) continue;
|
|
56
|
+
catalog.push({
|
|
57
|
+
id: entry.id || key,
|
|
58
|
+
name: entry.name || key,
|
|
59
|
+
npm: entry.npm,
|
|
60
|
+
env: entry.env || [],
|
|
61
|
+
api: entry.api || null,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
catalog.sort((a, b) => a.name.localeCompare(b.name));
|
|
66
|
+
|
|
67
|
+
settingsQueries.set(CACHE_KEY, JSON.stringify(catalog));
|
|
68
|
+
settingsQueries.set(CACHE_TS_KEY, new Date().toISOString());
|
|
69
|
+
|
|
70
|
+
debug.log('engine', `Cached ${catalog.length} providers from models.dev`);
|
|
71
|
+
return catalog;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get the cached models.dev catalog from DB. Returns null if not cached.
|
|
76
|
+
*/
|
|
77
|
+
export function getCachedModelsDevCatalog(): { catalog: ModelsDevProvider[]; cachedAt: string } | null {
|
|
78
|
+
const cached = settingsQueries.get(CACHE_KEY);
|
|
79
|
+
const cachedAt = settingsQueries.get(CACHE_TS_KEY);
|
|
80
|
+
|
|
81
|
+
if (!cached?.value || !cachedAt?.value) return null;
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
return {
|
|
85
|
+
catalog: JSON.parse(cached.value) as ModelsDevProvider[],
|
|
86
|
+
cachedAt: cachedAt.value,
|
|
87
|
+
};
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -13,8 +13,6 @@ import type { EngineOutput, UserMessage } from '$shared/types/unified';
|
|
|
13
13
|
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
14
14
|
import type { EngineModel } from '$shared/types/unified';
|
|
15
15
|
import type {
|
|
16
|
-
Provider,
|
|
17
|
-
Model,
|
|
18
16
|
EventMessageUpdated,
|
|
19
17
|
EventMessagePartUpdated,
|
|
20
18
|
EventSessionIdle,
|
|
@@ -24,6 +22,7 @@ import type {
|
|
|
24
22
|
ToolPart,
|
|
25
23
|
Message as OCMessage,
|
|
26
24
|
} from '@opencode-ai/sdk';
|
|
25
|
+
import { fetchOpenCodeModels } from './models';
|
|
27
26
|
import {
|
|
28
27
|
convertAssistantMessages,
|
|
29
28
|
convertResultMessage,
|
|
@@ -41,6 +40,7 @@ import {
|
|
|
41
40
|
getToolInput,
|
|
42
41
|
} from './message-converter';
|
|
43
42
|
import { ensureClient, getClient, getServerUrl } from './server';
|
|
43
|
+
import { formatSessionError, handleStreamError } from './error-handler';
|
|
44
44
|
import { debug } from '$shared/utils/logger';
|
|
45
45
|
|
|
46
46
|
// ============================================================================
|
|
@@ -90,71 +90,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
90
90
|
|
|
91
91
|
async getAvailableModels(): Promise<EngineModel[]> {
|
|
92
92
|
const client = await ensureClient();
|
|
93
|
-
|
|
94
|
-
try {
|
|
95
|
-
// config.providers() returns { data: { providers: Provider[] } }
|
|
96
|
-
const response = await client.config.providers();
|
|
97
|
-
const providers: Provider[] = response.data?.providers ?? [];
|
|
98
|
-
const models: EngineModel[] = [];
|
|
99
|
-
|
|
100
|
-
for (const provider of providers) {
|
|
101
|
-
// Provider.models is Record<string, Model>
|
|
102
|
-
const providerModels: Record<string, Model> = provider.models ?? {};
|
|
103
|
-
|
|
104
|
-
for (const [modelKey, model] of Object.entries(providerModels)) {
|
|
105
|
-
models.push({
|
|
106
|
-
engine: {
|
|
107
|
-
type: 'opencode',
|
|
108
|
-
provider: provider.id,
|
|
109
|
-
model: {
|
|
110
|
-
id: model.id,
|
|
111
|
-
name: model.name,
|
|
112
|
-
},
|
|
113
|
-
account: {
|
|
114
|
-
id: 0,
|
|
115
|
-
name: '',
|
|
116
|
-
},
|
|
117
|
-
},
|
|
118
|
-
limit: {
|
|
119
|
-
input: model.limit.context,
|
|
120
|
-
output: model.limit.output,
|
|
121
|
-
},
|
|
122
|
-
modalities: {
|
|
123
|
-
input: {
|
|
124
|
-
text: model.capabilities.input.text,
|
|
125
|
-
image: model.capabilities.input.image,
|
|
126
|
-
audio: model.capabilities.input.audio,
|
|
127
|
-
video: model.capabilities.input.video,
|
|
128
|
-
pdf: model.capabilities.input.pdf,
|
|
129
|
-
},
|
|
130
|
-
output: {
|
|
131
|
-
text: model.capabilities.output.text,
|
|
132
|
-
image: model.capabilities.output.image,
|
|
133
|
-
audio: model.capabilities.output.audio,
|
|
134
|
-
video: model.capabilities.output.video,
|
|
135
|
-
pdf: model.capabilities.output.pdf,
|
|
136
|
-
},
|
|
137
|
-
},
|
|
138
|
-
capabilities: {
|
|
139
|
-
reasoning: model.capabilities.reasoning,
|
|
140
|
-
tools: model.capabilities.toolcall,
|
|
141
|
-
structuredOutput: true,
|
|
142
|
-
},
|
|
143
|
-
cost: {
|
|
144
|
-
input: model.cost.input,
|
|
145
|
-
output: model.cost.output,
|
|
146
|
-
},
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
debug.log('engine', `Fetched ${models.length} models from ${providers.length} Open Code providers`);
|
|
152
|
-
return models;
|
|
153
|
-
} catch (error) {
|
|
154
|
-
debug.error('engine', 'Failed to fetch Open Code providers:', error);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
return [];
|
|
93
|
+
return fetchOpenCodeModels(client);
|
|
158
94
|
}
|
|
159
95
|
|
|
160
96
|
/**
|
|
@@ -711,48 +647,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
711
647
|
const errorProps = (event as EventSessionError).properties;
|
|
712
648
|
// Only handle errors for our session (sessionID is optional on errors)
|
|
713
649
|
if (errorProps.sessionID && errorProps.sessionID !== sessionId) break;
|
|
714
|
-
const
|
|
715
|
-
// Extract a human-readable error message.
|
|
716
|
-
// OpenCode SDK errors follow: { name: string, data: { message, statusCode?, providerID?, responseBody? } }
|
|
717
|
-
// Don't prepend error class names (e.g. "APIError") — those are SDK
|
|
718
|
-
// implementation details, not useful for the end user.
|
|
719
|
-
let errorMsg = 'Unknown Open Code error';
|
|
720
|
-
if (error) {
|
|
721
|
-
const errObj = error as Record<string, any>;
|
|
722
|
-
const name = errObj.name || '';
|
|
723
|
-
const dataMsg = errObj.data?.message || '';
|
|
724
|
-
const statusCode = errObj.data?.statusCode;
|
|
725
|
-
const providerID = errObj.data?.providerID;
|
|
726
|
-
const responseBody = errObj.data?.responseBody;
|
|
727
|
-
|
|
728
|
-
if (dataMsg) {
|
|
729
|
-
errorMsg = dataMsg;
|
|
730
|
-
} else if (responseBody) {
|
|
731
|
-
// No data.message — try to parse responseBody for the actual error
|
|
732
|
-
try {
|
|
733
|
-
const body = typeof responseBody === 'string' ? JSON.parse(responseBody) : responseBody;
|
|
734
|
-
errorMsg = body?.error?.message || body?.message || String(responseBody);
|
|
735
|
-
} catch {
|
|
736
|
-
errorMsg = String(responseBody);
|
|
737
|
-
}
|
|
738
|
-
} else if (name) {
|
|
739
|
-
errorMsg = name;
|
|
740
|
-
} else if (typeof error === 'string') {
|
|
741
|
-
errorMsg = error;
|
|
742
|
-
} else {
|
|
743
|
-
errorMsg = JSON.stringify(error);
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
// Append status code
|
|
747
|
-
if (statusCode) {
|
|
748
|
-
errorMsg += ` (status ${statusCode})`;
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
// Append provider ID to help identify which provider failed
|
|
752
|
-
if (providerID) {
|
|
753
|
-
errorMsg += ` [provider: ${providerID}]`;
|
|
754
|
-
}
|
|
755
|
-
}
|
|
650
|
+
const errorMsg = formatSessionError(errorProps);
|
|
756
651
|
debug.error('engine', '[OC] session.error:', errorMsg);
|
|
757
652
|
throw new Error(errorMsg);
|
|
758
653
|
}
|
|
@@ -761,12 +656,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
761
656
|
}
|
|
762
657
|
|
|
763
658
|
} catch (error) {
|
|
764
|
-
|
|
765
|
-
if (error.name === 'AbortError' || error.message.includes('aborted')) {
|
|
766
|
-
return;
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
throw error;
|
|
659
|
+
handleStreamError(error);
|
|
770
660
|
} finally {
|
|
771
661
|
this._isActive = false;
|
|
772
662
|
this.activeAbortController = null;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen credential JSON.
|
|
3
|
+
*
|
|
4
|
+
* `engine_accounts.credential` for Qwen accounts is stored as a JSON object
|
|
5
|
+
* carrying the API key and the chosen provider preset (DashScope CN/INTL,
|
|
6
|
+
* OpenRouter, Fireworks). Storing the preset per-account lets the user keep
|
|
7
|
+
* e.g. one DashScope and one OpenRouter account side by side.
|
|
8
|
+
*
|
|
9
|
+
* Backward compat: pre-migration accounts stored the raw API key as a plain
|
|
10
|
+
* string. `parseQwenCredential` handles both shapes; `serializeQwenCredential`
|
|
11
|
+
* always writes the JSON form. Legacy `baseUrl` overrides on existing rows are
|
|
12
|
+
* tolerated on read (then ignored) so old data doesn't crash on parse.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_QWEN_PRESET,
|
|
17
|
+
getQwenPreset,
|
|
18
|
+
type QwenProviderPresetId,
|
|
19
|
+
} from './presets';
|
|
20
|
+
|
|
21
|
+
export interface QwenCredential {
|
|
22
|
+
apiKey: string;
|
|
23
|
+
preset: QwenProviderPresetId;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const VALID_PRESETS: QwenProviderPresetId[] = [
|
|
27
|
+
'dashscope-cn',
|
|
28
|
+
'dashscope-intl',
|
|
29
|
+
'openrouter',
|
|
30
|
+
'fireworks',
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function coercePreset(value: unknown): QwenProviderPresetId {
|
|
34
|
+
if (typeof value === 'string' && (VALID_PRESETS as string[]).includes(value)) {
|
|
35
|
+
return value as QwenProviderPresetId;
|
|
36
|
+
}
|
|
37
|
+
return DEFAULT_QWEN_PRESET;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parse a stored credential string into the structured shape. Falls back to
|
|
42
|
+
* the default preset when the credential is a raw API key (pre-migration)
|
|
43
|
+
* or malformed JSON. A legacy `baseUrl` field is silently dropped.
|
|
44
|
+
*/
|
|
45
|
+
export function parseQwenCredential(stored: string | null | undefined): QwenCredential {
|
|
46
|
+
if (!stored) {
|
|
47
|
+
return { apiKey: '', preset: DEFAULT_QWEN_PRESET };
|
|
48
|
+
}
|
|
49
|
+
const trimmed = stored.trim();
|
|
50
|
+
if (!trimmed.startsWith('{')) {
|
|
51
|
+
return { apiKey: trimmed, preset: DEFAULT_QWEN_PRESET };
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(trimmed) as Record<string, unknown>;
|
|
55
|
+
const apiKey = typeof parsed.apiKey === 'string' ? parsed.apiKey : '';
|
|
56
|
+
const preset = coercePreset(parsed.preset);
|
|
57
|
+
return { apiKey, preset };
|
|
58
|
+
} catch {
|
|
59
|
+
// Malformed — treat the whole blob as the API key so the user can
|
|
60
|
+
// at least see "auth failed" rather than "no account".
|
|
61
|
+
return { apiKey: trimmed, preset: DEFAULT_QWEN_PRESET };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function serializeQwenCredential(cred: QwenCredential): string {
|
|
66
|
+
return JSON.stringify({
|
|
67
|
+
apiKey: cred.apiKey,
|
|
68
|
+
preset: cred.preset,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Resolve the effective base URL for a credential — the preset's default URL.
|
|
74
|
+
*/
|
|
75
|
+
export function resolveQwenBaseUrl(cred: QwenCredential): string | null {
|
|
76
|
+
const preset = getQwenPreset(cred.preset);
|
|
77
|
+
return preset?.defaultBaseUrl ?? null;
|
|
78
|
+
}
|