@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
@@ -0,0 +1,501 @@
1
+ /**
2
+ * Claude Code SDK → Unified Type Converters
3
+ *
4
+ * Converts SDK-specific message types to EngineOutput (unified types).
5
+ * Uses proper SDK types (SDKAssistantMessage, SDKUserMessage, etc.)
6
+ * instead of opaque Record<string, unknown> casts.
7
+ *
8
+ * Mirrors the pattern in opencode/message-converter.ts.
9
+ */
10
+
11
+ import type {
12
+ SDKMessage,
13
+ SDKAssistantMessage,
14
+ SDKUserMessage,
15
+ SDKPartialAssistantMessage,
16
+ SDKResultSuccess,
17
+ SDKResultError,
18
+ SDKSystemMessage,
19
+ SDKCompactBoundaryMessage,
20
+ SDKRateLimitEvent,
21
+ } from '@anthropic-ai/claude-agent-sdk';
22
+ import type { BetaContentBlock } from '@anthropic-ai/sdk/resources/beta/messages/messages';
23
+ import type { BetaUsage } from '@anthropic-ai/sdk/resources/beta/messages/messages';
24
+ import type {
25
+ EngineOutput,
26
+ UserMessage,
27
+ AssistantMessage,
28
+ ReasoningMessage,
29
+ CompactBoundaryMessage,
30
+ UserContentBlock,
31
+ AssistantContentBlock,
32
+ ToolUseBlock,
33
+ TextDeltaEvent,
34
+ StreamLifecycleEvent,
35
+ SuccessResultEvent,
36
+ ErrorResultEvent,
37
+ SystemInitEvent,
38
+ RateLimitEvent,
39
+ TokenUsage,
40
+ StopReason,
41
+ } from '$shared/types/unified';
42
+
43
+ // ============================================================
44
+ // Helper Mappers
45
+ // ============================================================
46
+
47
+ /** Map SDK stop_reason to unified StopReason */
48
+ function mapStopReason(sdkStop: string | null | undefined): StopReason | null {
49
+ switch (sdkStop) {
50
+ case 'end_turn': return 'end_turn';
51
+ case 'tool_use': return 'tool_use';
52
+ case 'max_tokens': return 'max_tokens';
53
+ case 'interrupted': return 'interrupted';
54
+ default: return sdkStop ? 'end_turn' : null;
55
+ }
56
+ }
57
+
58
+ /** Map SDK BetaUsage to unified TokenUsage */
59
+ function mapUsage(sdkUsage: BetaUsage | null | undefined): TokenUsage | null {
60
+ if (!sdkUsage) return null;
61
+ return {
62
+ inputTokens: sdkUsage.input_tokens || 0,
63
+ outputTokens: sdkUsage.output_tokens || 0,
64
+ cacheCreationInputTokens: sdkUsage.cache_creation_input_tokens || 0,
65
+ cacheReadInputTokens: sdkUsage.cache_read_input_tokens || 0,
66
+ };
67
+ }
68
+
69
+ /** Map raw usage from result messages (NonNullableUsage shape) */
70
+ function mapRawUsage(raw: Record<string, number> | null | undefined): TokenUsage {
71
+ if (!raw) return { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
72
+ return {
73
+ inputTokens: raw.input_tokens || 0,
74
+ outputTokens: raw.output_tokens || 0,
75
+ cacheCreationInputTokens: raw.cache_creation_input_tokens || 0,
76
+ cacheReadInputTokens: raw.cache_read_input_tokens || 0,
77
+ };
78
+ }
79
+
80
+ // ============================================================
81
+ // Tool Input Converter (snake_case → camelCase)
82
+ // ============================================================
83
+
84
+ /** Grep option mapping for dash-prefixed parameters → camelCase */
85
+ const GREP_OPTION_MAP: Record<string, string> = {
86
+ '-i': 'caseInsensitive',
87
+ '-n': 'lineNumbers',
88
+ '-A': 'afterContext',
89
+ '-B': 'beforeContext',
90
+ '-C': 'context',
91
+ };
92
+
93
+ /** Convert snake_case string to camelCase */
94
+ function snakeToCamel(str: string): string {
95
+ return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
96
+ }
97
+
98
+ /**
99
+ * Convert raw SDK tool input to unified camelCase format.
100
+ * Handles standard snake_case → camelCase and Grep's dash-prefixed options.
101
+ * Already-camelCase properties (e.g. multiline, activeForm) pass through unchanged.
102
+ */
103
+ function convertToolInput(toolName: string, raw: Record<string, unknown>): Record<string, unknown> {
104
+ const converted: Record<string, unknown> = {};
105
+ for (const [key, value] of Object.entries(raw)) {
106
+ if (toolName === 'Grep' && key in GREP_OPTION_MAP) {
107
+ converted[GREP_OPTION_MAP[key]] = value;
108
+ } else {
109
+ converted[snakeToCamel(key)] = value;
110
+ }
111
+ }
112
+ return converted;
113
+ }
114
+
115
+ // ============================================================
116
+ // Content Block Converters
117
+ // ============================================================
118
+
119
+ /** Convert SDK BetaContentBlock[] to unified AssistantContentBlock[] (excluding thinking) */
120
+ export function mapAssistantContent(sdkContent: BetaContentBlock[]): AssistantContentBlock[] {
121
+ const blocks: AssistantContentBlock[] = [];
122
+ for (const block of sdkContent) {
123
+ switch (block.type) {
124
+ case 'text':
125
+ blocks.push({ type: 'text', text: block.text });
126
+ break;
127
+ case 'tool_use':
128
+ blocks.push({
129
+ type: 'tool_use',
130
+ id: block.id,
131
+ name: block.name === 'Task' ? 'Agent' : block.name,
132
+ input: convertToolInput(block.name, block.input as Record<string, unknown>),
133
+ result: null,
134
+ subActivities: [],
135
+ skillPrompt: null,
136
+ interrupted: false,
137
+ } as ToolUseBlock);
138
+ break;
139
+ }
140
+ }
141
+ return blocks;
142
+ }
143
+
144
+ /** Convert SDK user content to unified UserContentBlock[] */
145
+ export function mapUserContent(sdkContent: string | Array<Record<string, unknown>>): UserContentBlock[] {
146
+ if (typeof sdkContent === 'string') {
147
+ return [{ type: 'text', text: sdkContent }];
148
+ }
149
+ const blocks: UserContentBlock[] = [];
150
+ for (const block of sdkContent) {
151
+ switch (block.type) {
152
+ case 'text':
153
+ blocks.push({ type: 'text', text: block.text as string });
154
+ break;
155
+ case 'tool_result':
156
+ blocks.push({
157
+ type: 'tool_result',
158
+ toolUseId: block.tool_use_id as string,
159
+ content: (block.content as string) || '',
160
+ isError: !!(block.is_error),
161
+ });
162
+ break;
163
+ case 'image': {
164
+ const source = block.source as Record<string, unknown> | undefined;
165
+ blocks.push({
166
+ type: 'image',
167
+ mediaType: (source?.media_type as string) || '',
168
+ data: (source?.data as string) || '',
169
+ });
170
+ break;
171
+ }
172
+ case 'document': {
173
+ const source = block.source as Record<string, unknown> | undefined;
174
+ blocks.push({
175
+ type: 'document',
176
+ mediaType: (source?.media_type as string) || '',
177
+ data: (source?.data as string) || '',
178
+ title: (block.title as string) || null,
179
+ });
180
+ break;
181
+ }
182
+ }
183
+ }
184
+ if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
185
+ return blocks;
186
+ }
187
+
188
+ // ============================================================
189
+ // Message Converters
190
+ // ============================================================
191
+
192
+ /** Convert SDKAssistantMessage → ReasoningMessage (if thinking) + AssistantMessage */
193
+ export function convertAssistantMessage(msg: SDKAssistantMessage): EngineOutput[] {
194
+ const sessionId = msg.session_id;
195
+ const betaMessage = msg.message;
196
+ const content = betaMessage.content;
197
+ const outputs: EngineOutput[] = [];
198
+
199
+ // Extract thinking blocks → ReasoningMessage
200
+ const thinkingBlocks = content.filter(b => b.type === 'thinking');
201
+ if (thinkingBlocks.length > 0) {
202
+ const reasoningText = thinkingBlocks
203
+ .map(b => b.type === 'thinking' ? b.thinking : '')
204
+ .join('\n');
205
+ const reasoning: ReasoningMessage = {
206
+ type: 'reasoning',
207
+ createdAt: new Date().toISOString(),
208
+ messageId: crypto.randomUUID(),
209
+ sessionId,
210
+ parent: { messageId: null, sessionId: null, toolUseId: null },
211
+ engine: { type: 'claude-code', provider: 'anthropic', model: { id: betaMessage.model || '', name: '' }, account: { id: 0, name: '' } },
212
+ text: reasoningText,
213
+ };
214
+ outputs.push(reasoning);
215
+ }
216
+
217
+ // Build AssistantMessage with non-thinking content
218
+ const otherBlocks = content.filter(b => b.type !== 'thinking' && b.type !== 'redacted_thinking');
219
+ const assistantContent = mapAssistantContent(
220
+ otherBlocks.length > 0 ? otherBlocks : [{ type: 'text', text: '', citations: null } as BetaContentBlock]
221
+ );
222
+
223
+ const assistant: AssistantMessage = {
224
+ type: 'assistant',
225
+ createdAt: new Date().toISOString(),
226
+ messageId: msg.uuid || crypto.randomUUID(),
227
+ sessionId,
228
+ parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
229
+ engine: { type: 'claude-code', provider: 'anthropic', model: { id: betaMessage.model || '', name: '' }, account: { id: 0, name: '' } },
230
+ content: assistantContent,
231
+ stopReason: mapStopReason(betaMessage.stop_reason),
232
+ usage: mapUsage(betaMessage.usage),
233
+ };
234
+ outputs.push(assistant);
235
+
236
+ return outputs;
237
+ }
238
+
239
+ /** Convert SDKUserMessage → UserMessage */
240
+ export function convertUserMessage(msg: SDKUserMessage): UserMessage {
241
+ const sdkContent = msg.message.content;
242
+ const content = mapUserContent(sdkContent as string | Array<Record<string, unknown>>);
243
+
244
+ return {
245
+ type: 'user',
246
+ createdAt: new Date().toISOString(),
247
+ messageId: msg.uuid || crypto.randomUUID(),
248
+ sessionId: msg.session_id || null,
249
+ parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
250
+ engine: { type: 'claude-code', provider: 'anthropic', model: { id: '', name: '' }, account: { id: 0, name: '' } },
251
+ sender: { id: '', name: '' },
252
+ content,
253
+ synthetic: true, // SDK-generated tool_result messages
254
+ };
255
+ }
256
+
257
+ /** Convert SDKPartialAssistantMessage (stream_event) → TextDeltaEvent | StreamLifecycleEvent */
258
+ export function convertStreamEvent(msg: SDKPartialAssistantMessage): EngineOutput[] {
259
+ const sessionId = msg.session_id;
260
+ const event = msg.event;
261
+ const outputs: EngineOutput[] = [];
262
+
263
+ switch (event.type) {
264
+ case 'message_start':
265
+ case 'message_stop': {
266
+ const lifecycle: StreamLifecycleEvent = {
267
+ type: 'stream_event',
268
+ event: event.type === 'message_start' ? 'start' : 'stop',
269
+ sessionId,
270
+ reasoning: false,
271
+ };
272
+ outputs.push(lifecycle);
273
+ break;
274
+ }
275
+
276
+ case 'content_block_start': {
277
+ const blockType = event.content_block.type;
278
+ if (blockType === 'thinking') {
279
+ outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent);
280
+ } else if (blockType === 'text') {
281
+ outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent);
282
+ }
283
+ break;
284
+ }
285
+
286
+ case 'content_block_delta': {
287
+ const delta = event.delta;
288
+ if (delta.type === 'thinking_delta') {
289
+ const text: TextDeltaEvent = {
290
+ type: 'stream_event',
291
+ event: 'delta',
292
+ sessionId,
293
+ text: delta.thinking || '',
294
+ reasoning: true,
295
+ };
296
+ outputs.push(text);
297
+ } else if (delta.type === 'text_delta') {
298
+ const text: TextDeltaEvent = {
299
+ type: 'stream_event',
300
+ event: 'delta',
301
+ sessionId,
302
+ text: delta.text || '',
303
+ reasoning: false,
304
+ };
305
+ outputs.push(text);
306
+ }
307
+ break;
308
+ }
309
+
310
+ case 'content_block_stop': {
311
+ outputs.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: false } as StreamLifecycleEvent);
312
+ break;
313
+ }
314
+ }
315
+
316
+ return outputs;
317
+ }
318
+
319
+ /** Convert SDKResultSuccess → SuccessResultEvent */
320
+ export function convertResultSuccess(msg: SDKResultSuccess): SuccessResultEvent {
321
+ return {
322
+ type: 'result',
323
+ subtype: 'success',
324
+ sessionId: msg.session_id,
325
+ numTurns: msg.num_turns || 0,
326
+ totalCostUsd: msg.total_cost_usd || 0,
327
+ usage: mapRawUsage(msg.usage as unknown as Record<string, number>),
328
+ stopReason: msg.stop_reason || null,
329
+ };
330
+ }
331
+
332
+ /** Convert SDKResultError → ErrorResultEvent */
333
+ export function convertResultError(msg: SDKResultError): ErrorResultEvent {
334
+ return {
335
+ type: 'result',
336
+ subtype: msg.subtype === 'error_max_turns' ? 'error_max_turns'
337
+ : msg.subtype === 'error_max_budget_usd' ? 'error_max_budget'
338
+ : 'error_during_execution',
339
+ sessionId: msg.session_id,
340
+ errors: msg.errors || [],
341
+ };
342
+ }
343
+
344
+ /** Convert SDKSystemMessage (init) → SystemInitEvent */
345
+ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
346
+ return {
347
+ type: 'system_init',
348
+ sessionId: msg.session_id,
349
+ model: msg.model || '',
350
+ engine: 'claude-code',
351
+ tools: msg.tools || [],
352
+ mcpServers: (msg.mcp_servers || []).map(s => ({
353
+ name: s.name || '',
354
+ status: (s.status as 'connected' | 'disconnected' | 'error') || 'disconnected',
355
+ })),
356
+ };
357
+ }
358
+
359
+ /** Convert SDKCompactBoundaryMessage → CompactBoundaryMessage */
360
+ export function convertCompactBoundary(msg: SDKCompactBoundaryMessage): CompactBoundaryMessage {
361
+ return {
362
+ type: 'compact_boundary',
363
+ createdAt: new Date().toISOString(),
364
+ messageId: msg.uuid || crypto.randomUUID(),
365
+ sessionId: msg.session_id,
366
+ parent: { messageId: null, sessionId: null, toolUseId: null },
367
+ engine: { type: 'claude-code', provider: 'anthropic', model: { id: '', name: '' }, account: { id: 0, name: '' } },
368
+ trigger: msg.compact_metadata.trigger,
369
+ preTokens: msg.compact_metadata.pre_tokens || 0,
370
+ };
371
+ }
372
+
373
+ /** Convert SDKRateLimitEvent → RateLimitEvent (returns null for non-actionable 'allowed' status) */
374
+ export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null {
375
+ const info = msg.rate_limit_info;
376
+ // Only emit for actual warnings/rejections — 'allowed' is just informational
377
+ if (info.status === 'allowed') return null;
378
+ return {
379
+ type: 'rate_limit',
380
+ sessionId: msg.session_id,
381
+ status: info.status === 'rejected' ? 'rejected' : 'allowed_warning',
382
+ utilization: info.utilization || 0,
383
+ resetsAt: info.resetsAt || null,
384
+ };
385
+ }
386
+
387
+ // ============================================================
388
+ // Top-Level Converter
389
+ // ============================================================
390
+
391
+ /**
392
+ * Convert a single SDKMessage to zero or more EngineOutput events.
393
+ *
394
+ * Dispatches on the SDK message discriminant using proper SDK types.
395
+ * Handles thinking block extraction: assistant messages with thinking
396
+ * blocks yield a ReasoningMessage first, then the AssistantMessage
397
+ * with thinking blocks stripped.
398
+ */
399
+ export function* convertSdkMessage(msg: SDKMessage): Generator<EngineOutput> {
400
+ switch (msg.type) {
401
+ case 'assistant':
402
+ for (const output of convertAssistantMessage(msg as SDKAssistantMessage)) {
403
+ yield output;
404
+ }
405
+ break;
406
+
407
+ case 'user':
408
+ // SDKUserMessage and SDKUserMessageReplay both have type: 'user'
409
+ yield convertUserMessage(msg as SDKUserMessage);
410
+ break;
411
+
412
+ case 'stream_event':
413
+ for (const output of convertStreamEvent(msg as SDKPartialAssistantMessage)) {
414
+ yield output;
415
+ }
416
+ break;
417
+
418
+ case 'result':
419
+ if (msg.subtype === 'success') {
420
+ yield convertResultSuccess(msg as SDKResultSuccess);
421
+ } else {
422
+ yield convertResultError(msg as SDKResultError);
423
+ }
424
+ break;
425
+
426
+ case 'system': {
427
+ const systemMsg = msg as SDKSystemMessage | SDKCompactBoundaryMessage;
428
+ if ('subtype' in systemMsg) {
429
+ if (systemMsg.subtype === 'init') {
430
+ yield convertSystemInit(systemMsg as SDKSystemMessage);
431
+ } else if (systemMsg.subtype === 'compact_boundary') {
432
+ yield convertCompactBoundary(systemMsg as SDKCompactBoundaryMessage);
433
+ }
434
+ }
435
+ break;
436
+ }
437
+
438
+ case 'rate_limit_event': {
439
+ const rlEvent = convertRateLimit(msg as SDKRateLimitEvent);
440
+ if (rlEvent) yield rlEvent;
441
+ break;
442
+ }
443
+
444
+ // Transient SDK message types — skip
445
+ default:
446
+ break;
447
+ }
448
+ }
449
+
450
+ // ============================================================
451
+ // Prompt Converter (Unified → SDK)
452
+ // ============================================================
453
+
454
+ /**
455
+ * Convert a UserMessage prompt to SDKUserMessage format for the Claude SDK.
456
+ */
457
+ export function toSdkUserMessage(msg: UserMessage): SDKUserMessage {
458
+ const sdkContent: Array<Record<string, unknown>> = [];
459
+
460
+ for (const block of msg.content) {
461
+ switch (block.type) {
462
+ case 'text':
463
+ sdkContent.push({ type: 'text', text: block.text });
464
+ break;
465
+ case 'image':
466
+ sdkContent.push({
467
+ type: 'image',
468
+ source: { type: 'base64', media_type: block.mediaType, data: block.data },
469
+ });
470
+ break;
471
+ case 'document':
472
+ sdkContent.push({
473
+ type: 'document',
474
+ source: { type: 'base64', media_type: block.mediaType, data: block.data },
475
+ title: block.title,
476
+ });
477
+ break;
478
+ case 'tool_result':
479
+ sdkContent.push({
480
+ type: 'tool_result',
481
+ tool_use_id: block.toolUseId,
482
+ content: block.content,
483
+ is_error: block.isError,
484
+ });
485
+ break;
486
+ }
487
+ }
488
+
489
+ // SDK accepts string for simple text-only prompts
490
+ const content = sdkContent.length === 1 && sdkContent[0].type === 'text'
491
+ ? sdkContent[0].text as string
492
+ : sdkContent;
493
+
494
+ return {
495
+ type: 'user',
496
+ uuid: msg.messageId,
497
+ session_id: msg.sessionId,
498
+ parent_tool_use_id: msg.parent.toolUseId,
499
+ message: { role: 'user', content },
500
+ } as unknown as SDKUserMessage;
501
+ }