@myrialabs/clopen 0.2.24 → 0.3.1

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 +552 -0
  14. package/backend/engine/adapters/claude/stream.ts +59 -47
  15. package/backend/engine/adapters/opencode/config.ts +7 -7
  16. package/backend/engine/adapters/opencode/message-converter.ts +328 -352
  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-BVWBZlgD.js} +2 -2
  36. package/dist/assets/main-Cgbs6dR7.js +246 -0
  37. package/dist/assets/main-TEa2MRnh.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 +130 -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 +409 -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 { createSdkMessageConverter, 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,44 @@ 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,
122
+ // Explicit adaptive thinking with summarized display so Opus 4.6+ emits
123
+ // visible thinking_delta events; without this the SDK can default to
124
+ // 'omitted' and reasoning blocks arrive empty.
125
+ thinking: { type: 'adaptive', display: 'summarized' },
113
126
  // Custom permission handler: blocks on AskUserQuestion until user answers,
114
127
  // auto-allows everything else. Works alongside bypassPermissions.
115
- canUseTool: async (_toolName, input, options) => {
128
+ canUseTool: async (_toolName, input, canUseToolOptions) => {
116
129
  if (_toolName === 'AskUserQuestion') {
117
- debug.log('engine', `AskUserQuestion detected (toolUseID: ${options.toolUseID}), waiting for user input...`);
130
+ debug.log('engine', `AskUserQuestion detected (toolUseID: ${canUseToolOptions.toolUseID}), waiting for user input...`);
118
131
  return new Promise<PermissionResult>((resolve) => {
119
132
  // Handle abort (stream cancelled while waiting)
120
- if (options.signal.aborted) {
133
+ if (canUseToolOptions.signal.aborted) {
121
134
  resolve({ behavior: 'deny', message: 'Cancelled' });
122
135
  return;
123
136
  }
124
137
  const onAbort = () => {
125
- this.pendingUserAnswers.delete(options.toolUseID);
138
+ this.pendingUserAnswers.delete(canUseToolOptions.toolUseID);
126
139
  resolve({ behavior: 'deny', message: 'Cancelled' });
127
140
  };
128
- options.signal.addEventListener('abort', onAbort, { once: true });
141
+ canUseToolOptions.signal.addEventListener('abort', onAbort, { once: true });
129
142
 
130
- this.pendingUserAnswers.set(options.toolUseID, {
143
+ this.pendingUserAnswers.set(canUseToolOptions.toolUseID, {
131
144
  resolve: (result: PermissionResult) => {
132
- options.signal.removeEventListener('abort', onAbort);
145
+ canUseToolOptions.signal.removeEventListener('abort', onAbort);
133
146
  resolve(result);
134
147
  },
135
148
  removeAbortListener: () => {
136
- options.signal.removeEventListener('abort', onAbort);
149
+ canUseToolOptions.signal.removeEventListener('abort', onAbort);
137
150
  },
138
151
  input
139
152
  });
@@ -142,7 +155,7 @@ export class ClaudeCodeEngine implements AIEngine {
142
155
  // Auto-allow all other tools
143
156
  return { behavior: 'allow' as const, updatedInput: input };
144
157
  },
145
- ...(model && { model }),
158
+ ...(modelId && { model: modelId }),
146
159
  ...(resume && { resume }),
147
160
  ...(maxTurns && { maxTurns }),
148
161
  ...(includePartialMessages && { includePartialMessages }),
@@ -151,16 +164,11 @@ export class ClaudeCodeEngine implements AIEngine {
151
164
  ...(allowedMcpTools.length > 0 && { allowedTools: allowedMcpTools })
152
165
  };
153
166
 
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
- }
167
+ // Convert UserMessage → SDKUserMessage for SDK
168
+ const sdkPrompt = toSdkUserMessage(prompt);
169
+ const promptIterable = (async function* () {
170
+ yield sdkPrompt;
171
+ })();
164
172
 
165
173
  const queryInstance = query({
166
174
  prompt: promptIterable,
@@ -169,8 +177,12 @@ export class ClaudeCodeEngine implements AIEngine {
169
177
 
170
178
  this.activeQuery = queryInstance;
171
179
 
172
- for await (const message of queryInstance) {
173
- yield message;
180
+ // Per-query stateful converter so block-stop reasoning tracking persists
181
+ // across the stream of SDK messages.
182
+ const convertSdkMessage = createSdkMessageConverter();
183
+ for await (const sdkMessage of queryInstance) {
184
+ // Convert SDK message → EngineOutput (may yield 0-N events per SDK message)
185
+ yield* convertSdkMessage(sdkMessage);
174
186
  }
175
187
 
176
188
  } catch (error) {
@@ -267,11 +279,11 @@ export class ClaudeCodeEngine implements AIEngine {
267
279
  async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
268
280
  const {
269
281
  prompt,
270
- model = 'haiku',
282
+ modelId,
271
283
  schema,
272
284
  projectPath,
273
285
  abortController,
274
- claudeAccountId
286
+ accountId
275
287
  } = options;
276
288
 
277
289
  if (!this._isInitialized) {
@@ -279,7 +291,7 @@ export class ClaudeCodeEngine implements AIEngine {
279
291
  }
280
292
 
281
293
  const controller = abortController || new AbortController();
282
- const normalizedPath = normalizePath(projectPath);
294
+ const resolvedPath = resolveOsPath(projectPath);
283
295
 
284
296
  // Optimized for one-shot structured generation:
285
297
  // - tools: [] prevents tool use (no agentic loops)
@@ -291,8 +303,8 @@ export class ClaudeCodeEngine implements AIEngine {
291
303
  const sdkOptions: Options = {
292
304
  permissionMode: 'bypassPermissions' as PermissionMode,
293
305
  allowDangerouslySkipPermissions: true,
294
- cwd: normalizedPath,
295
- env: getEngineEnv(claudeAccountId),
306
+ cwd: resolvedPath,
307
+ env: getEngineEnv(accountId),
296
308
  systemPrompt: 'You are a structured data generator. Return JSON matching the provided schema.',
297
309
  tools: [],
298
310
  outputFormat: {
@@ -302,7 +314,7 @@ export class ClaudeCodeEngine implements AIEngine {
302
314
  persistSession: false,
303
315
  effort: 'low',
304
316
  thinking: { type: 'disabled' },
305
- ...(model && { model }),
317
+ ...(modelId && { model: modelId }),
306
318
  abortController: controller
307
319
  };
308
320
 
@@ -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)