@myrialabs/clopen 0.2.23 → 0.3.0

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.
Files changed (62) hide show
  1. package/README.md +1 -1
  2. package/backend/chat/helpers.ts +2 -20
  3. package/backend/chat/stream-manager.ts +556 -547
  4. package/backend/database/migrations/027_create_opencode_providers_table.ts +27 -0
  5. package/backend/database/migrations/028_create_opencode_accounts_table.ts +25 -0
  6. package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/engine-queries.ts +195 -36
  9. package/backend/database/queries/message-queries.ts +84 -139
  10. package/backend/database/queries/session-queries.ts +167 -21
  11. package/backend/database/queries/snapshot-queries.ts +5 -4
  12. package/backend/database/queries/utils-queries.ts +2 -2
  13. package/backend/engine/adapters/claude/environment.ts +4 -5
  14. package/backend/engine/adapters/claude/message-converter.ts +501 -0
  15. package/backend/engine/adapters/claude/stream.ts +52 -47
  16. package/backend/engine/adapters/opencode/config.ts +156 -0
  17. package/backend/engine/adapters/opencode/message-converter.ts +266 -326
  18. package/backend/engine/adapters/opencode/server.ts +54 -12
  19. package/backend/engine/adapters/opencode/stream.ts +84 -101
  20. package/backend/engine/types.ts +17 -11
  21. package/backend/project/status-manager.ts +10 -13
  22. package/backend/snapshot/helpers.ts +46 -90
  23. package/backend/snapshot/snapshot-service.ts +1 -1
  24. package/backend/utils/paths.ts +22 -1
  25. package/backend/ws/chat/index.ts +1 -11
  26. package/backend/ws/chat/stream.ts +101 -61
  27. package/backend/ws/engine/claude/accounts.ts +27 -7
  28. package/backend/ws/engine/claude/status.ts +3 -2
  29. package/backend/ws/engine/opencode/index.ts +3 -1
  30. package/backend/ws/engine/opencode/providers.ts +300 -0
  31. package/backend/ws/git/commit-message.ts +6 -8
  32. package/backend/ws/messages/crud.ts +4 -59
  33. package/backend/ws/sessions/crud.ts +78 -130
  34. package/backend/ws/sessions/index.ts +1 -9
  35. package/backend/ws/settings/crud.ts +14 -11
  36. package/backend/ws/snapshot/restore.ts +23 -26
  37. package/backend/ws/snapshot/timeline.ts +5 -5
  38. package/dist/assets/{index-BFFIy7ZX.js → index-B95VOHJY.js} +2 -2
  39. package/dist/assets/main-D1QNkcRL.js +257 -0
  40. package/dist/assets/main-rtLiuU_x.css +1 -0
  41. package/dist/index.html +2 -2
  42. package/package.json +4 -4
  43. package/shared/constants/engines.ts +141 -56
  44. package/shared/types/database/schema.ts +39 -40
  45. package/shared/types/stores/settings.ts +8 -4
  46. package/shared/types/unified/common.ts +21 -0
  47. package/shared/types/unified/display.ts +25 -0
  48. package/shared/types/unified/engine.ts +61 -0
  49. package/shared/types/unified/index.ts +108 -0
  50. package/shared/types/unified/message.ts +151 -0
  51. package/shared/types/unified/stream.ts +157 -0
  52. package/shared/types/unified/tool.ts +268 -0
  53. package/shared/utils/message-formatter.ts +9 -73
  54. package/shared/utils/path.ts +3 -2
  55. package/tsconfig.json +1 -1
  56. package/backend/engine/adapters/claude/path-utils.ts +0 -38
  57. package/backend/ws/chat/background.ts +0 -201
  58. package/dist/assets/main-CtNvgvwE.js +0 -249
  59. package/dist/assets/main-DmshCkFM.css +0 -1
  60. package/shared/types/engine/index.ts +0 -45
  61. package/shared/types/messaging/index.ts +0 -242
  62. package/shared/types/messaging/tool.ts +0 -374
@@ -2,19 +2,33 @@
2
2
  * Claude Code Engine Adapter
3
3
  *
4
4
  * Wraps the @anthropic-ai/claude-agent-sdk into the AIEngine interface.
5
- * Messages are already in SDKMessage format — no conversion needed.
5
+ * SDK messages are converted to EngineOutput by ./message-converter.ts.
6
+ *
7
+ * Currently uses v1 query() API because v2 (unstable_v2_createSession) is
8
+ * @alpha and lacks critical options required by Clopen:
9
+ * - cwd (multi-project working directory)
10
+ * - mcpServers, systemPrompt, settingSources
11
+ * - forkSession, maxTurns, abortController, includePartialMessages
12
+ * - outputFormat (needed by generateStructured)
13
+ * When v2 SDKSessionOptions gains these, migrate streamQuery() to v2.
6
14
  */
7
15
 
8
-
9
- import { query, type SDKMessage, type EngineSDKMessage, type Options, type Query, type SDKUserMessage } from '$shared/types/messaging';
10
- import type { PermissionMode, PermissionResult } from "@anthropic-ai/claude-agent-sdk";
16
+ import { query } from '@anthropic-ai/claude-agent-sdk';
17
+ import type {
18
+ Options,
19
+ Query,
20
+ PermissionMode,
21
+ PermissionResult,
22
+ } from '@anthropic-ai/claude-agent-sdk';
23
+ import type { EngineOutput } from '$shared/types/unified';
11
24
  import type { StructuredGenerationOptions } from '../../types';
12
- import { normalizePath } from './path-utils';
25
+ import { convertSdkMessage, toSdkUserMessage } from './message-converter';
26
+ import { resolveOsPath } from '$backend/utils/paths';
13
27
  import { setupEnvironmentOnce, getEngineEnv } from './environment';
14
28
  import { handleStreamError } from './error-handler';
15
29
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
16
30
  import type { AIEngine, EngineQueryOptions } from '../../types';
17
- import type { EngineModel } from '$shared/types/engine';
31
+ import type { EngineModel } from '$shared/types/unified';
18
32
  import { CLAUDE_CODE_MODELS } from '$shared/constants/engines';
19
33
 
20
34
  import { debug } from '$shared/utils/logger';
@@ -26,11 +40,6 @@ interface PendingUserAnswer {
26
40
  input: Record<string, unknown>;
27
41
  }
28
42
 
29
- /** Type guard for AsyncIterable */
30
- function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
31
- return value != null && typeof value === 'object' && Symbol.asyncIterator in value;
32
- }
33
-
34
43
  export class ClaudeCodeEngine implements AIEngine {
35
44
  readonly name = 'claude-code' as const;
36
45
  private _isInitialized = false;
@@ -67,18 +76,18 @@ export class ClaudeCodeEngine implements AIEngine {
67
76
  }
68
77
 
69
78
  /**
70
- * Stream query with real-time callbacks
79
+ * Stream query, converting SDK messages → EngineOutput (unified types)
71
80
  */
72
- async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineSDKMessage, void, unknown> {
81
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
73
82
  const {
74
83
  projectPath,
75
84
  prompt,
76
85
  resume,
77
86
  maxTurns = undefined,
78
- model = 'sonnet',
87
+ modelId,
79
88
  includePartialMessages = false,
80
89
  abortController,
81
- claudeAccountId
90
+ accountId
82
91
  } = options;
83
92
 
84
93
  debug.log('chat', "Claude Code - Stream Query");
@@ -86,7 +95,7 @@ export class ClaudeCodeEngine implements AIEngine {
86
95
 
87
96
  this.activeController = abortController || new AbortController();
88
97
 
89
- const normalizedProjectPath = normalizePath(projectPath);
98
+ const resolvedProjectPath = resolveOsPath(projectPath);
90
99
 
91
100
  try {
92
101
  // Get custom MCP servers and allowed tools
@@ -100,40 +109,40 @@ export class ClaudeCodeEngine implements AIEngine {
100
109
 
101
110
  // SDK uses cwd from options — no process.chdir() needed.
102
111
  // Environment is passed via env option — no process.env mutation.
103
- // When claudeAccountId is specified, the env uses that account's token
104
- // instead of the globally active account.
112
+ // When accountId is specified, the env overrides the OAuth token
113
+ // with that specific account's token instead of the globally active one.
105
114
  const sdkOptions: Options = {
106
115
  permissionMode: 'bypassPermissions' as PermissionMode,
107
116
  allowDangerouslySkipPermissions: true,
108
- cwd: normalizedProjectPath,
109
- env: getEngineEnv(claudeAccountId),
117
+ cwd: resolvedProjectPath,
118
+ env: getEngineEnv(accountId),
110
119
  systemPrompt: { type: "preset", preset: "claude_code" },
111
120
  settingSources: ["user", "project", "local"],
112
121
  forkSession: true,
113
122
  // Custom permission handler: blocks on AskUserQuestion until user answers,
114
123
  // auto-allows everything else. Works alongside bypassPermissions.
115
- canUseTool: async (_toolName, input, options) => {
124
+ canUseTool: async (_toolName, input, canUseToolOptions) => {
116
125
  if (_toolName === 'AskUserQuestion') {
117
- debug.log('engine', `AskUserQuestion detected (toolUseID: ${options.toolUseID}), waiting for user input...`);
126
+ debug.log('engine', `AskUserQuestion detected (toolUseID: ${canUseToolOptions.toolUseID}), waiting for user input...`);
118
127
  return new Promise<PermissionResult>((resolve) => {
119
128
  // Handle abort (stream cancelled while waiting)
120
- if (options.signal.aborted) {
129
+ if (canUseToolOptions.signal.aborted) {
121
130
  resolve({ behavior: 'deny', message: 'Cancelled' });
122
131
  return;
123
132
  }
124
133
  const onAbort = () => {
125
- this.pendingUserAnswers.delete(options.toolUseID);
134
+ this.pendingUserAnswers.delete(canUseToolOptions.toolUseID);
126
135
  resolve({ behavior: 'deny', message: 'Cancelled' });
127
136
  };
128
- options.signal.addEventListener('abort', onAbort, { once: true });
137
+ canUseToolOptions.signal.addEventListener('abort', onAbort, { once: true });
129
138
 
130
- this.pendingUserAnswers.set(options.toolUseID, {
139
+ this.pendingUserAnswers.set(canUseToolOptions.toolUseID, {
131
140
  resolve: (result: PermissionResult) => {
132
- options.signal.removeEventListener('abort', onAbort);
141
+ canUseToolOptions.signal.removeEventListener('abort', onAbort);
133
142
  resolve(result);
134
143
  },
135
144
  removeAbortListener: () => {
136
- options.signal.removeEventListener('abort', onAbort);
145
+ canUseToolOptions.signal.removeEventListener('abort', onAbort);
137
146
  },
138
147
  input
139
148
  });
@@ -142,7 +151,7 @@ export class ClaudeCodeEngine implements AIEngine {
142
151
  // Auto-allow all other tools
143
152
  return { behavior: 'allow' as const, updatedInput: input };
144
153
  },
145
- ...(model && { model }),
154
+ ...(modelId && { model: modelId }),
146
155
  ...(resume && { resume }),
147
156
  ...(maxTurns && { maxTurns }),
148
157
  ...(includePartialMessages && { includePartialMessages }),
@@ -151,16 +160,11 @@ export class ClaudeCodeEngine implements AIEngine {
151
160
  ...(allowedMcpTools.length > 0 && { allowedTools: allowedMcpTools })
152
161
  };
153
162
 
154
- // Create async iterable from single message if needed
155
- let promptIterable: AsyncIterable<SDKUserMessage>;
156
-
157
- if (isAsyncIterable<SDKUserMessage>(prompt)) {
158
- promptIterable = prompt;
159
- } else {
160
- promptIterable = (async function* () {
161
- yield prompt as SDKUserMessage;
162
- })();
163
- }
163
+ // Convert UserMessage → SDKUserMessage for SDK
164
+ const sdkPrompt = toSdkUserMessage(prompt);
165
+ const promptIterable = (async function* () {
166
+ yield sdkPrompt;
167
+ })();
164
168
 
165
169
  const queryInstance = query({
166
170
  prompt: promptIterable,
@@ -169,8 +173,9 @@ export class ClaudeCodeEngine implements AIEngine {
169
173
 
170
174
  this.activeQuery = queryInstance;
171
175
 
172
- for await (const message of queryInstance) {
173
- yield message;
176
+ for await (const sdkMessage of queryInstance) {
177
+ // Convert SDK message → EngineOutput (may yield 0-N events per SDK message)
178
+ yield* convertSdkMessage(sdkMessage);
174
179
  }
175
180
 
176
181
  } catch (error) {
@@ -267,11 +272,11 @@ export class ClaudeCodeEngine implements AIEngine {
267
272
  async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
268
273
  const {
269
274
  prompt,
270
- model = 'haiku',
275
+ modelId,
271
276
  schema,
272
277
  projectPath,
273
278
  abortController,
274
- claudeAccountId
279
+ accountId
275
280
  } = options;
276
281
 
277
282
  if (!this._isInitialized) {
@@ -279,7 +284,7 @@ export class ClaudeCodeEngine implements AIEngine {
279
284
  }
280
285
 
281
286
  const controller = abortController || new AbortController();
282
- const normalizedPath = normalizePath(projectPath);
287
+ const resolvedPath = resolveOsPath(projectPath);
283
288
 
284
289
  // Optimized for one-shot structured generation:
285
290
  // - tools: [] prevents tool use (no agentic loops)
@@ -291,8 +296,8 @@ export class ClaudeCodeEngine implements AIEngine {
291
296
  const sdkOptions: Options = {
292
297
  permissionMode: 'bypassPermissions' as PermissionMode,
293
298
  allowDangerouslySkipPermissions: true,
294
- cwd: normalizedPath,
295
- env: getEngineEnv(claudeAccountId),
299
+ cwd: resolvedPath,
300
+ env: getEngineEnv(accountId),
296
301
  systemPrompt: 'You are a structured data generator. Return JSON matching the provided schema.',
297
302
  tools: [],
298
303
  outputFormat: {
@@ -302,7 +307,7 @@ export class ClaudeCodeEngine implements AIEngine {
302
307
  persistSession: false,
303
308
  effort: 'low',
304
309
  thinking: { type: 'disabled' },
305
- ...(model && { model }),
310
+ ...(modelId && { model: modelId }),
306
311
  abortController: controller
307
312
  };
308
313
 
@@ -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, engineQueries } 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 = engineQueries.getEnabledProviders('opencode');
120
+ const enabledProviders: string[] = ['opencode'];
121
+ const envVars: Record<string, string> = {};
122
+
123
+ for (const provider of providers) {
124
+ const activeAccount = engineQueries.getActiveAccount(provider.id);
125
+ if (!activeAccount) continue;
126
+
127
+ enabledProviders.push(provider.slug);
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.slug);
140
+ const envNames = catalogEntry?.env || [];
141
+
142
+ // First env var gets the active account's credential
143
+ if (envNames.length > 0) {
144
+ envVars[envNames[0]] = activeAccount.credential;
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
+ }