@myrialabs/clopen 0.2.24 → 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 (60) 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/029_migrate_messages_to_unified.ts +1108 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/engine-queries.ts +195 -36
  7. package/backend/database/queries/index.ts +1 -2
  8. package/backend/database/queries/message-queries.ts +84 -139
  9. package/backend/database/queries/session-queries.ts +167 -21
  10. package/backend/database/queries/snapshot-queries.ts +5 -4
  11. package/backend/database/queries/utils-queries.ts +2 -2
  12. package/backend/engine/adapters/claude/environment.ts +4 -5
  13. package/backend/engine/adapters/claude/message-converter.ts +501 -0
  14. package/backend/engine/adapters/claude/stream.ts +52 -47
  15. package/backend/engine/adapters/opencode/config.ts +7 -7
  16. package/backend/engine/adapters/opencode/message-converter.ts +266 -326
  17. package/backend/engine/adapters/opencode/stream.ts +84 -101
  18. package/backend/engine/types.ts +17 -11
  19. package/backend/project/status-manager.ts +10 -13
  20. package/backend/snapshot/helpers.ts +46 -90
  21. package/backend/snapshot/snapshot-service.ts +1 -1
  22. package/backend/utils/paths.ts +22 -1
  23. package/backend/ws/chat/index.ts +1 -11
  24. package/backend/ws/chat/stream.ts +101 -61
  25. package/backend/ws/engine/claude/accounts.ts +27 -7
  26. package/backend/ws/engine/claude/status.ts +3 -2
  27. package/backend/ws/engine/opencode/providers.ts +25 -24
  28. package/backend/ws/git/commit-message.ts +6 -8
  29. package/backend/ws/messages/crud.ts +4 -59
  30. package/backend/ws/sessions/crud.ts +78 -130
  31. package/backend/ws/sessions/index.ts +1 -9
  32. package/backend/ws/settings/crud.ts +14 -11
  33. package/backend/ws/snapshot/restore.ts +23 -26
  34. package/backend/ws/snapshot/timeline.ts +5 -5
  35. package/dist/assets/{index-w7Uwi2Jz.js → index-B95VOHJY.js} +2 -2
  36. package/dist/assets/main-D1QNkcRL.js +257 -0
  37. package/dist/assets/main-rtLiuU_x.css +1 -0
  38. package/dist/index.html +2 -2
  39. package/package.json +4 -4
  40. package/shared/constants/engines.ts +141 -56
  41. package/shared/types/database/schema.ts +39 -40
  42. package/shared/types/stores/settings.ts +8 -4
  43. package/shared/types/unified/common.ts +21 -0
  44. package/shared/types/unified/display.ts +25 -0
  45. package/shared/types/unified/engine.ts +61 -0
  46. package/shared/types/unified/index.ts +108 -0
  47. package/shared/types/unified/message.ts +151 -0
  48. package/shared/types/unified/stream.ts +157 -0
  49. package/shared/types/unified/tool.ts +268 -0
  50. package/shared/utils/message-formatter.ts +9 -73
  51. package/shared/utils/path.ts +3 -2
  52. package/tsconfig.json +1 -1
  53. package/backend/database/queries/opencode-provider-queries.ts +0 -190
  54. package/backend/engine/adapters/claude/path-utils.ts +0 -38
  55. package/backend/ws/chat/background.ts +0 -201
  56. package/dist/assets/main-B4q8wX9B.js +0 -257
  57. package/dist/assets/main-Bfz5Urp3.css +0 -1
  58. package/shared/types/engine/index.ts +0 -45
  59. package/shared/types/messaging/index.ts +0 -242
  60. 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
 
@@ -6,7 +6,7 @@
6
6
  * - Provides restart logic for the OpenCode server
7
7
  */
8
8
 
9
- import { settingsQueries, opencodeProviderQueries } from '../../../database/queries';
9
+ import { settingsQueries, engineQueries } from '../../../database/queries';
10
10
  import { debug } from '$shared/utils/logger';
11
11
 
12
12
  const MODELS_DEV_URL = 'https://models.dev/api.json';
@@ -116,15 +116,15 @@ export interface OpenCodeProviderConfigResult {
116
116
  * hardcoded "apiKey" in the config JSON.
117
117
  */
118
118
  export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
119
- const providers = opencodeProviderQueries.getEnabledProviders();
119
+ const providers = engineQueries.getEnabledProviders('opencode');
120
120
  const enabledProviders: string[] = ['opencode'];
121
121
  const envVars: Record<string, string> = {};
122
122
 
123
123
  for (const provider of providers) {
124
- const activeAccount = opencodeProviderQueries.getActiveAccount(provider.id);
124
+ const activeAccount = engineQueries.getActiveAccount(provider.id);
125
125
  if (!activeAccount) continue;
126
126
 
127
- enabledProviders.push(provider.provider_id);
127
+ enabledProviders.push(provider.slug);
128
128
 
129
129
  // Parse stored options which may contain additional env var values
130
130
  let options: Record<string, string> = {};
@@ -136,12 +136,12 @@ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
136
136
 
137
137
  // Look up the catalog entry to get the actual env var names
138
138
  const cached = getCachedModelsDevCatalog();
139
- const catalogEntry = cached?.catalog.find(c => c.id === provider.provider_id);
139
+ const catalogEntry = cached?.catalog.find(c => c.id === provider.slug);
140
140
  const envNames = catalogEntry?.env || [];
141
141
 
142
- // First env var gets the active account's API key
142
+ // First env var gets the active account's credential
143
143
  if (envNames.length > 0) {
144
- envVars[envNames[0]] = activeAccount.api_key;
144
+ envVars[envNames[0]] = activeAccount.credential;
145
145
  }
146
146
 
147
147
  // Additional env vars from options (stored by their env var name)