@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
@@ -1,23 +1,37 @@
1
1
  /**
2
- * Open Code → Claude SDK Message Converter
2
+ * Open Code → EngineOutput Converter
3
3
  *
4
- * Converts Open Code SDK messages and parts into Claude SDK format (SDKMessage)
5
- * with type-safe tool input normalization (camelCase → snake_case).
4
+ * Converts Open Code SDK messages and parts into EngineOutput (unified types)
5
+ * with type-safe tool input normalization.
6
6
  *
7
7
  * Content blocks are split into separate messages:
8
8
  * - Consecutive text blocks → one message
9
9
  * - Each tool_use block → its own message
10
10
  */
11
11
 
12
- import type { SDKMessage, EngineSDKMessage } from '$shared/types/messaging';
13
- import type { ToolResult } from '$shared/types/messaging/tool';
14
12
  import { resolveOpenCodeToolName } from '../../../mcp';
15
13
  import type { Message as OCMessage, Part, ToolPart, AssistantMessage } from '@opencode-ai/sdk';
16
14
  import type {
15
+ EngineOutput,
16
+ UserMessage,
17
+ AssistantMessage as UnifiedAssistantMessage,
18
+ ReasoningMessage,
19
+ TextDeltaEvent,
20
+ StreamLifecycleEvent,
21
+ SuccessResultEvent,
22
+ ErrorResultEvent,
23
+ SystemInitEvent,
24
+ TextBlock,
25
+ ToolUseBlock,
26
+ ToolResult,
27
+ AssistantContentBlock,
28
+ UserContentBlock,
29
+ TokenUsage,
30
+ StopReason,
17
31
  BashInput,
18
- FileReadInput,
19
- FileEditInput,
20
- FileWriteInput,
32
+ ReadInput,
33
+ EditInput,
34
+ WriteInput,
21
35
  GlobInput,
22
36
  GrepInput,
23
37
  WebFetchInput,
@@ -26,7 +40,7 @@ import type {
26
40
  ListMcpResourcesInput,
27
41
  ReadMcpResourceInput,
28
42
  TodoWriteInput,
29
- } from '@anthropic-ai/claude-agent-sdk/sdk-tools';
43
+ } from '$shared/types/unified';
30
44
 
31
45
  // ============================================================
32
46
  // Types
@@ -64,33 +78,14 @@ export function getToolInput(toolPart: ToolPart): OCToolInput {
64
78
  }
65
79
 
66
80
  /**
67
- * Normalized tool input types.
68
- * Only includes tools that exist in OpenCode SDK:
69
- * bash, read, edit, write, glob, grep, webfetch, websearch,
70
- * question, todowrite, todoread, patch, list, skill, lsp
81
+ * Normalized tool input types (unified camelCase format).
71
82
  */
72
83
  type NormalizedToolInput =
73
- | BashInput | FileReadInput | FileEditInput | FileWriteInput
84
+ | BashInput | ReadInput | EditInput | WriteInput
74
85
  | GlobInput | GrepInput | WebFetchInput | WebSearchInput
75
86
  | AskUserQuestionInput | TodoWriteInput
76
- | ListMcpResourcesInput | ReadMcpResourceInput;
77
-
78
- /** Text content block */
79
- interface TextContentBlock {
80
- type: 'text';
81
- text: string;
82
- }
83
-
84
- /** Tool use content block with optional result */
85
- interface ToolUseContentBlock {
86
- type: 'tool_use';
87
- id: string;
88
- name: string;
89
- input: NormalizedToolInput;
90
- $result?: ToolResult;
91
- }
92
-
93
- type ContentBlock = TextContentBlock | ToolUseContentBlock;
87
+ | ListMcpResourcesInput | ReadMcpResourceInput
88
+ | Record<string, unknown>;
94
89
 
95
90
  // ============================================================
96
91
  // Tool Name Mapping
@@ -186,9 +181,9 @@ function camelToSnake(s: string): string {
186
181
  // Per-Tool Input Normalizers
187
182
  // ============================================================
188
183
 
189
- function normalizeReadInput(raw: OCToolInput): FileReadInput {
190
- const result: FileReadInput = {
191
- file_path: str(raw, 'file_path', 'filePath'),
184
+ function normalizeReadInput(raw: OCToolInput): ReadInput {
185
+ const result: ReadInput = {
186
+ filePath: str(raw, 'file_path', 'filePath'),
192
187
  };
193
188
  const offset = optNum(raw, 'offset', 'offset');
194
189
  if (offset != null) result.offset = offset;
@@ -197,20 +192,20 @@ function normalizeReadInput(raw: OCToolInput): FileReadInput {
197
192
  return result;
198
193
  }
199
194
 
200
- function normalizeEditInput(raw: OCToolInput): FileEditInput {
201
- const result: FileEditInput = {
202
- file_path: str(raw, 'file_path', 'filePath'),
203
- old_string: str(raw, 'old_string', 'oldString'),
204
- new_string: str(raw, 'new_string', 'newString'),
195
+ function normalizeEditInput(raw: OCToolInput): EditInput {
196
+ const result: EditInput = {
197
+ filePath: str(raw, 'file_path', 'filePath'),
198
+ oldString: str(raw, 'old_string', 'oldString'),
199
+ newString: str(raw, 'new_string', 'newString'),
205
200
  };
206
201
  const replaceAll = optBool(raw, 'replace_all', 'replaceAll');
207
- if (replaceAll != null) result.replace_all = replaceAll;
202
+ if (replaceAll != null) result.replaceAll = replaceAll;
208
203
  return result;
209
204
  }
210
205
 
211
- function normalizeWriteInput(raw: OCToolInput): FileWriteInput {
206
+ function normalizeWriteInput(raw: OCToolInput): WriteInput {
212
207
  return {
213
- file_path: str(raw, 'file_path', 'filePath'),
208
+ filePath: str(raw, 'file_path', 'filePath'),
214
209
  content: str(raw, 'content', 'content'),
215
210
  };
216
211
  }
@@ -224,7 +219,7 @@ function normalizeBashInput(raw: OCToolInput): BashInput {
224
219
  const description = optStr(raw, 'description', 'description');
225
220
  if (description != null) result.description = description;
226
221
  const runInBackground = optBool(raw, 'run_in_background', 'runInBackground');
227
- if (runInBackground != null) result.run_in_background = runInBackground;
222
+ if (runInBackground != null) result.runInBackground = runInBackground;
228
223
  return result;
229
224
  }
230
225
 
@@ -243,36 +238,36 @@ function normalizeGrepInput(raw: OCToolInput): GrepInput {
243
238
  };
244
239
  const path = optStr(raw, 'path', 'path');
245
240
  if (path != null) result.path = path;
246
- // OpenCode uses 'include' for file filter, Claude Code uses 'glob'
241
+ // OpenCode uses 'include' for file filter
247
242
  const glob = optStr(raw, 'glob', 'glob') ?? optStr(raw, 'include', 'include');
248
243
  if (glob != null) result.glob = glob;
249
- const outputMode = optStr(raw, 'output_mode', 'outputMode') as GrepInput['output_mode'];
250
- if (outputMode != null) result.output_mode = outputMode;
244
+ const outputMode = optStr(raw, 'output_mode', 'outputMode') as GrepInput['outputMode'];
245
+ if (outputMode != null) result.outputMode = outputMode;
251
246
  const type = optStr(raw, 'type', 'type');
252
247
  if (type != null) result.type = type;
253
248
  const headLimit = optNum(raw, 'head_limit', 'headLimit');
254
- if (headLimit != null) result.head_limit = headLimit;
249
+ if (headLimit != null) result.headLimit = headLimit;
255
250
  const offset = optNum(raw, 'offset', 'offset');
256
251
  if (offset != null) result.offset = offset;
257
252
  const multiline = optBool(raw, 'multiline', 'multiline');
258
253
  if (multiline != null) result.multiline = multiline;
259
- const caseInsensitive = optBool(raw, '-i', '-i');
260
- if (caseInsensitive != null) result['-i'] = caseInsensitive;
261
- const beforeContext = optNum(raw, '-B', '-B');
262
- if (beforeContext != null) result['-B'] = beforeContext;
263
- const afterContext = optNum(raw, '-A', '-A');
264
- if (afterContext != null) result['-A'] = afterContext;
265
- const context = optNum(raw, '-C', '-C');
266
- if (context != null) result['-C'] = context;
267
- const lineNumbers = optBool(raw, '-n', '-n');
268
- if (lineNumbers != null) result['-n'] = lineNumbers;
254
+ const caseInsensitive = optBool(raw, '-i', 'caseInsensitive');
255
+ if (caseInsensitive != null) result.caseInsensitive = caseInsensitive;
256
+ const beforeContext = optNum(raw, '-B', 'beforeContext');
257
+ if (beforeContext != null) result.beforeContext = beforeContext;
258
+ const afterContext = optNum(raw, '-A', 'afterContext');
259
+ if (afterContext != null) result.afterContext = afterContext;
260
+ const context = optNum(raw, '-C', 'context');
261
+ if (context != null) result.context = context;
262
+ const lineNumbers = optBool(raw, '-n', 'lineNumbers');
263
+ if (lineNumbers != null) result.lineNumbers = lineNumbers;
269
264
  return result;
270
265
  }
271
266
 
272
267
  function normalizeWebFetchInput(raw: OCToolInput): WebFetchInput {
273
268
  return {
274
269
  url: str(raw, 'url', 'url'),
275
- // OpenCode uses 'format', Claude Code uses 'prompt'
270
+ // OpenCode uses 'format', unified uses 'prompt'
276
271
  prompt: str(raw, 'prompt', 'prompt') || str(raw, 'format', 'format'),
277
272
  };
278
273
  }
@@ -283,11 +278,11 @@ function normalizeWebSearchInput(raw: OCToolInput): WebSearchInput {
283
278
  };
284
279
  const allowedDomains = raw.allowed_domains ?? raw.allowedDomains;
285
280
  if (Array.isArray(allowedDomains) && allowedDomains.length) {
286
- result.allowed_domains = allowedDomains as string[];
281
+ result.allowedDomains = allowedDomains as string[];
287
282
  }
288
283
  const blockedDomains = raw.blocked_domains ?? raw.blockedDomains;
289
284
  if (Array.isArray(blockedDomains) && blockedDomains.length) {
290
- result.blocked_domains = blockedDomains as string[];
285
+ result.blockedDomains = blockedDomains as string[];
291
286
  }
292
287
  return result;
293
288
  }
@@ -389,55 +384,25 @@ function isToolError(status: string, content: string): boolean {
389
384
  // Stop Reason Mapping
390
385
  // ============================================================
391
386
 
392
- /** Map OpenCode finish reason → Claude Code stop_reason */
393
- function mapStopReason(finish: string | undefined): string | null {
387
+ /** Map OpenCode finish reason → unified StopReason */
388
+ function mapStopReason(finish: string | undefined): StopReason | null {
394
389
  switch (finish) {
395
390
  case 'tool-calls': return 'tool_use';
396
391
  case 'stop': return 'end_turn';
397
392
  case 'length': return 'max_tokens';
398
- default: return finish || 'end_turn';
393
+ default: return finish ? 'end_turn' : null;
399
394
  }
400
395
  }
401
396
 
402
- // ============================================================
403
- // Message Builder Helper
404
- // ============================================================
405
-
406
- interface AssistantMessageParams {
407
- content: ContentBlock[];
408
- ocMessage: OCMessage;
409
- modelId: string;
410
- usage?: {
411
- input_tokens: number;
412
- output_tokens: number;
413
- cache_creation_input_tokens: number;
414
- cache_read_input_tokens: number;
415
- };
416
- sessionId: string;
417
- stopReason: string | null;
418
- uuid: string;
419
- parentToolUseId?: string | null;
420
- }
421
-
422
- /** Build a single SDKAssistantMessage from content blocks */
423
- function buildAssistantSDKMessage(params: AssistantMessageParams): SDKMessage {
397
+ /** Map OpenCode tokens → unified TokenUsage */
398
+ function mapUsage(tokens: { input?: number; output?: number; cache?: { write?: number; read?: number } } | undefined): TokenUsage | null {
399
+ if (!tokens) return null;
424
400
  return {
425
- type: 'assistant',
426
- message: {
427
- model: params.modelId,
428
- id: params.uuid,
429
- type: 'message',
430
- role: 'assistant',
431
- content: params.content,
432
- stop_reason: params.stopReason,
433
- stop_sequence: null,
434
- ...(params.usage && { usage: params.usage }),
435
- context_management: null
436
- },
437
- parent_tool_use_id: params.parentToolUseId ?? null,
438
- session_id: params.sessionId,
439
- uuid: params.uuid
440
- } as unknown as SDKMessage;
401
+ inputTokens: tokens.input || 0,
402
+ outputTokens: tokens.output || 0,
403
+ cacheCreationInputTokens: tokens.cache?.write || 0,
404
+ cacheReadInputTokens: tokens.cache?.read || 0,
405
+ };
441
406
  }
442
407
 
443
408
  // ============================================================
@@ -445,93 +410,92 @@ function buildAssistantSDKMessage(params: AssistantMessageParams): SDKMessage {
445
410
  // ============================================================
446
411
 
447
412
  /**
448
- * Convert Open Code user message → SDKMessage (user type)
413
+ * Convert Open Code user message → UserMessage (unified)
449
414
  */
450
415
  export function convertUserMessage(
451
416
  ocMessage: OCMessage,
452
417
  ocParts: Part[],
453
418
  sessionId: string
454
- ): SDKMessage {
455
- const textBlocks: TextContentBlock[] = [];
419
+ ): UserMessage {
420
+ const content: UserContentBlock[] = [];
456
421
 
457
422
  for (const part of ocParts) {
458
423
  if (part.type === 'text') {
459
- textBlocks.push({ type: 'text', text: part.text || '' });
424
+ content.push({ type: 'text', text: part.text || '' });
460
425
  }
461
426
  }
462
427
 
463
- if (textBlocks.length === 0) {
464
- textBlocks.push({ type: 'text', text: '' });
428
+ if (content.length === 0) {
429
+ content.push({ type: 'text', text: '' });
465
430
  }
466
431
 
467
432
  return {
468
433
  type: 'user',
469
- uuid: ocMessage.id || crypto.randomUUID(),
470
- session_id: sessionId,
471
- parent_tool_use_id: null,
472
- message: {
473
- role: 'user',
474
- content: textBlocks.length === 1
475
- ? textBlocks[0].text
476
- : textBlocks
477
- }
478
- } as unknown as SDKMessage;
434
+ createdAt: new Date().toISOString(),
435
+ messageId: ocMessage.id || crypto.randomUUID(),
436
+ sessionId,
437
+ parent: { messageId: null, sessionId: null, toolUseId: null },
438
+ engine: { type: 'opencode' as const, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
439
+ sender: { id: '', name: '' },
440
+ content,
441
+ synthetic: false,
442
+ };
479
443
  }
480
444
 
481
445
  /**
482
- * Convert Open Code assistant message + parts → SDKMessage[] (split by content type)
446
+ * Convert Open Code assistant message + parts → EngineOutput[]
483
447
  *
484
448
  * Splits content into separate messages:
485
449
  * - Consecutive text blocks → one message
486
450
  * - Each tool_use block → its own message
487
- *
488
- * This matches Claude Code's UI behavior where each tool call is a separate bubble.
489
451
  */
490
452
  export function convertAssistantMessages(
491
453
  ocMessage: OCMessage,
492
454
  ocParts: Part[],
493
455
  sessionId: string
494
- ): SDKMessage[] {
456
+ ): EngineOutput[] {
495
457
  // 1. Build typed content blocks from parts
496
- const allBlocks: ContentBlock[] = [];
458
+ const allBlocks: AssistantContentBlock[] = [];
497
459
 
498
460
  for (const part of ocParts) {
499
461
  if (part.type === 'text') {
500
- allBlocks.push({ type: 'text', text: part.text || '' });
462
+ allBlocks.push({ type: 'text', text: part.text || '' } as TextBlock);
501
463
  } else if (part.type === 'tool') {
502
464
  const toolPart = part as ToolPart;
503
465
  const claudeName = mapToolName(toolPart.tool || 'unknown');
504
466
  const resolvedInput = getToolInput(toolPart);
505
467
  const normalizedInput = normalizeToolInput(claudeName, resolvedInput);
468
+ const toolUseId = toolPart.callID || toolPart.id || crypto.randomUUID();
506
469
 
507
- const block: ToolUseContentBlock = {
508
- type: 'tool_use',
509
- id: toolPart.callID || toolPart.id || crypto.randomUUID(),
510
- name: claudeName,
511
- input: normalizedInput,
512
- };
513
-
470
+ let result: ToolResult | null = null;
514
471
  if (toolPart.state.status === 'completed') {
515
472
  const output = toolPart.state.output || '';
516
- block.$result = {
473
+ result = {
517
474
  type: 'tool_result',
518
- tool_use_id: block.id,
475
+ toolUseId,
519
476
  content: output,
520
- ...(isToolError('completed', output) && { is_error: true }),
477
+ isError: isToolError('completed', output),
521
478
  };
522
479
  } else if (toolPart.state.status === 'error') {
523
- block.$result = {
480
+ result = {
524
481
  type: 'tool_result',
525
- tool_use_id: block.id,
482
+ toolUseId,
526
483
  content: toolPart.state.error || 'Tool execution failed',
527
- is_error: true,
484
+ isError: true,
528
485
  };
529
486
  }
530
487
 
531
- allBlocks.push(block);
532
- }
533
- else if (part.type === 'subtask') {
534
- // Subtask = Agent/sub-agent invocation
488
+ allBlocks.push({
489
+ type: 'tool_use',
490
+ id: toolUseId,
491
+ name: claudeName,
492
+ input: normalizedInput,
493
+ result,
494
+ subActivities: [],
495
+ skillPrompt: null,
496
+ interrupted: false,
497
+ } as ToolUseBlock);
498
+ } else if (part.type === 'subtask') {
535
499
  const subtaskPart = part as any;
536
500
  allBlocks.push({
537
501
  type: 'tool_use',
@@ -540,61 +504,55 @@ export function convertAssistantMessages(
540
504
  input: {
541
505
  prompt: subtaskPart.prompt || '',
542
506
  description: subtaskPart.description || '',
543
- subagent_type: subtaskPart.agent || 'general-purpose',
544
- } as NormalizedToolInput,
545
- });
507
+ subagentType: subtaskPart.agent || 'general-purpose',
508
+ },
509
+ result: null,
510
+ subActivities: [],
511
+ skillPrompt: null,
512
+ interrupted: false,
513
+ } as ToolUseBlock);
546
514
  }
547
515
  // Skip: reasoning, step-start, step-finish, snapshot, patch, agent, retry, compaction
548
516
  }
549
517
 
550
518
  // 2. Split into groups: consecutive text → one group, each tool_use → its own group
551
- const groups: ContentBlock[][] = [];
552
- let currentTextGroup: TextContentBlock[] = [];
519
+ const groups: AssistantContentBlock[][] = [];
520
+ let currentTextGroup: TextBlock[] = [];
553
521
 
554
522
  for (const block of allBlocks) {
555
523
  if (block.type === 'text') {
556
524
  currentTextGroup.push(block);
557
525
  } else {
558
- // Flush accumulated text blocks as a group
559
526
  if (currentTextGroup.length > 0) {
560
527
  groups.push([...currentTextGroup]);
561
528
  currentTextGroup = [];
562
529
  }
563
- // Each tool_use is its own group
564
530
  groups.push([block]);
565
531
  }
566
532
  }
567
- // Flush remaining text
568
533
  if (currentTextGroup.length > 0) {
569
534
  groups.push([...currentTextGroup]);
570
535
  }
571
-
572
- // If no content at all, add an empty text block
573
536
  if (groups.length === 0) {
574
- groups.push([{ type: 'text', text: '' }]);
537
+ groups.push([{ type: 'text', text: '' } as TextBlock]);
575
538
  }
576
539
 
577
- // 3. Build SDKMessages from groups
540
+ // 3. Build unified messages from groups
578
541
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
579
- const modelId = assistantMsg ? `${assistantMsg.providerID}/${assistantMsg.modelID}` : '';
542
+ const providerID = assistantMsg?.providerID || '';
543
+ const modelID = assistantMsg?.modelID || '';
580
544
  const mappedStop = mapStopReason(assistantMsg?.finish);
581
- const usage = assistantMsg?.tokens ? {
582
- input_tokens: assistantMsg.tokens.input || 0,
583
- output_tokens: assistantMsg.tokens.output || 0,
584
- cache_creation_input_tokens: assistantMsg.tokens.cache?.write || 0,
585
- cache_read_input_tokens: assistantMsg.tokens.cache?.read || 0,
586
- } : undefined;
545
+ const usage = mapUsage(assistantMsg?.tokens);
587
546
 
588
- const messages: SDKMessage[] = [];
589
- const baseUuid = ocMessage.id || crypto.randomUUID();
547
+ const messages: EngineOutput[] = [];
548
+ const baseId = ocMessage.id || crypto.randomUUID();
590
549
 
591
550
  for (let i = 0; i < groups.length; i++) {
592
551
  const isLast = i === groups.length - 1;
593
552
  const group = groups[i];
594
553
  const hasToolUse = group.some(b => b.type === 'tool_use');
595
554
 
596
- // Determine stop_reason for this split
597
- let stopReason: string | null;
555
+ let stopReason: StopReason | null;
598
556
  if (isLast) {
599
557
  stopReason = mappedStop;
600
558
  } else if (hasToolUse) {
@@ -603,250 +561,232 @@ export function convertAssistantMessages(
603
561
  stopReason = null;
604
562
  }
605
563
 
606
- messages.push(buildAssistantSDKMessage({
607
- content: group,
608
- ocMessage,
609
- modelId,
610
- // Only the last message carries usage (to avoid double-counting)
611
- usage: isLast ? usage : undefined,
564
+ const msg: UnifiedAssistantMessage = {
565
+ type: 'assistant',
566
+ createdAt: new Date().toISOString(),
567
+ messageId: i === 0 ? baseId : crypto.randomUUID(),
612
568
  sessionId,
569
+ parent: { messageId: null, sessionId: null, toolUseId: null },
570
+ engine: { type: 'opencode' as const, provider: providerID, model: { id: modelID, name: '' }, account: { id: 0, name: '' } },
571
+ content: group,
613
572
  stopReason,
614
- uuid: i === 0 ? baseUuid : crypto.randomUUID(),
615
- }));
573
+ usage: isLast ? usage : null,
574
+ };
575
+ messages.push(msg);
616
576
  }
617
577
 
618
578
  return messages;
619
579
  }
620
580
 
621
581
  /**
622
- * Convert Open Code result/completion → SDKResultMessage
582
+ * Convert Open Code result/completion → ResultEvent
623
583
  */
624
584
  export function convertResultMessage(
625
585
  ocMessage: OCMessage,
626
586
  sessionId: string
627
- ): SDKMessage {
587
+ ): EngineOutput {
628
588
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
629
589
 
590
+ if (assistantMsg?.error) {
591
+ return {
592
+ type: 'result',
593
+ subtype: 'error_during_execution',
594
+ sessionId,
595
+ errors: [JSON.stringify(assistantMsg.error)],
596
+ } as ErrorResultEvent;
597
+ }
598
+
630
599
  return {
631
600
  type: 'result',
632
- subtype: assistantMsg?.error ? 'error_during_execution' : 'success',
633
- uuid: crypto.randomUUID(),
634
- session_id: sessionId,
635
- duration_ms: assistantMsg?.time?.completed
636
- ? (assistantMsg.time.completed - assistantMsg.time.created) * 1000
637
- : 0,
638
- duration_api_ms: 0,
639
- is_error: !!assistantMsg?.error,
640
- num_turns: 1,
641
- total_cost_usd: assistantMsg?.cost || 0,
642
- usage: {
643
- input_tokens: assistantMsg?.tokens?.input || 0,
644
- output_tokens: assistantMsg?.tokens?.output || 0,
645
- cache_creation_input_tokens: assistantMsg?.tokens?.cache?.write || 0,
646
- cache_read_input_tokens: assistantMsg?.tokens?.cache?.read || 0
601
+ subtype: 'success',
602
+ sessionId,
603
+ numTurns: 1,
604
+ totalCostUsd: assistantMsg?.cost || 0,
605
+ usage: mapUsage(assistantMsg?.tokens) || {
606
+ inputTokens: 0, outputTokens: 0,
607
+ cacheCreationInputTokens: 0, cacheReadInputTokens: 0,
647
608
  },
648
- ...(assistantMsg?.error
649
- ? { errors: [JSON.stringify(assistantMsg.error)] }
650
- : { result: '' }
651
- )
652
- } as unknown as SDKMessage;
609
+ stopReason: assistantMsg?.finish || null,
610
+ } as SuccessResultEvent;
653
611
  }
654
612
 
655
613
  /**
656
- * Convert Open Code system/init event → SDKSystemMessage
614
+ * Convert Open Code system/init event → SystemInitEvent
657
615
  */
658
- export function convertSystemInitMessage(sessionId: string, model: string): SDKMessage {
616
+ export function convertSystemInitMessage(sessionId: string, model: string): SystemInitEvent {
659
617
  return {
660
- type: 'system',
661
- subtype: 'init',
662
- uuid: crypto.randomUUID(),
663
- session_id: sessionId,
664
- tools: [],
665
- mcp_servers: [],
618
+ type: 'system_init',
619
+ sessionId,
666
620
  model,
667
- permissionMode: 'bypassPermissions',
668
- cwd: process.cwd(),
669
- apiKeySource: 'user',
670
- slash_commands: [],
671
- skills: [],
672
- plugins: [],
673
- claude_code_version: 'opencode',
674
- output_style: 'text'
675
- } as unknown as SDKMessage;
621
+ engine: 'opencode',
622
+ tools: [],
623
+ mcpServers: [],
624
+ };
676
625
  }
677
626
 
678
627
  /**
679
- * Convert Open Code text delta → SDKPartialAssistantMessage
628
+ * Convert Open Code text delta → TextDeltaEvent
680
629
  */
681
630
  export function convertPartialTextDelta(
682
631
  text: string,
683
632
  sessionId: string,
684
- parentToolUseId: string | null = null
685
- ): SDKMessage {
633
+ ): TextDeltaEvent {
686
634
  return {
687
635
  type: 'stream_event',
688
- event: {
689
- type: 'content_block_delta',
690
- index: 0,
691
- delta: { type: 'text_delta', text }
692
- },
693
- parent_tool_use_id: parentToolUseId,
694
- uuid: crypto.randomUUID(),
695
- session_id: sessionId
696
- } as unknown as SDKMessage;
636
+ event: 'delta',
637
+ sessionId,
638
+ text,
639
+ reasoning: false,
640
+ };
697
641
  }
698
642
 
699
643
  /**
700
- * Convert Open Code stream start → SDKPartialAssistantMessage
644
+ * Convert Open Code stream start → StreamLifecycleEvent
701
645
  */
702
- export function convertStreamStart(sessionId: string): SDKMessage {
646
+ export function convertStreamStart(sessionId: string): StreamLifecycleEvent {
703
647
  return {
704
648
  type: 'stream_event',
705
- event: { type: 'message_start', message: { role: 'assistant', content: [] } },
706
- parent_tool_use_id: null,
707
- uuid: crypto.randomUUID(),
708
- session_id: sessionId
709
- } as unknown as SDKMessage;
649
+ event: 'start',
650
+ sessionId,
651
+ reasoning: false,
652
+ };
710
653
  }
711
654
 
712
655
  /**
713
- * Convert Open Code stream stop → SDKPartialAssistantMessage
656
+ * Convert Open Code stream stop → StreamLifecycleEvent
714
657
  */
715
- export function convertStreamStop(sessionId: string): SDKMessage {
658
+ export function convertStreamStop(sessionId: string): StreamLifecycleEvent {
716
659
  return {
717
660
  type: 'stream_event',
718
- event: { type: 'message_stop' },
719
- parent_tool_use_id: null,
720
- uuid: crypto.randomUUID(),
721
- session_id: sessionId
722
- } as unknown as SDKMessage;
661
+ event: 'stop',
662
+ sessionId,
663
+ reasoning: false,
664
+ };
723
665
  }
724
666
 
725
667
  /**
726
- * Convert a single tool part → assistant message with tool_use only (no $result).
727
- * Used for progressive tool rendering — tool appears immediately in UI
728
- * before the tool finishes executing.
668
+ * Convert a single tool part → AssistantMessage with tool_use only (no result).
669
+ * Used for progressive tool rendering.
729
670
  */
730
671
  export function convertToolUseOnly(
731
672
  toolPart: ToolPart,
732
673
  ocMessage: OCMessage,
733
674
  sessionId: string,
734
- parentToolUseId: string | null = null,
735
- ): SDKMessage {
675
+ parentToolUseId?: string,
676
+ ): UnifiedAssistantMessage {
736
677
  const claudeName = mapToolName(toolPart.tool || 'unknown');
737
678
  const resolvedInput = getToolInput(toolPart);
738
679
  const normalizedInput = normalizeToolInput(claudeName, resolvedInput);
739
680
  const toolUseId = toolPart.callID || toolPart.id || crypto.randomUUID();
740
681
 
741
682
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
742
- const modelId = assistantMsg ? `${assistantMsg.providerID}/${assistantMsg.modelID}` : '';
683
+ const provId = assistantMsg?.providerID || '';
684
+ const mdlId = assistantMsg?.modelID || '';
743
685
 
744
- return buildAssistantSDKMessage({
686
+ return {
687
+ type: 'assistant',
688
+ createdAt: new Date().toISOString(),
689
+ messageId: crypto.randomUUID(),
690
+ sessionId,
691
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId || null },
692
+ engine: { type: 'opencode' as const, provider: provId, model: { id: mdlId, name: '' }, account: { id: 0, name: '' } },
745
693
  content: [{
746
694
  type: 'tool_use',
747
695
  id: toolUseId,
748
696
  name: claudeName,
749
697
  input: normalizedInput,
750
- }],
751
- ocMessage,
752
- modelId,
753
- sessionId,
698
+ result: null,
699
+ subActivities: [],
700
+ skillPrompt: null,
701
+ interrupted: false,
702
+ } as ToolUseBlock],
754
703
  stopReason: 'tool_use',
755
- uuid: crypto.randomUUID(),
756
- parentToolUseId,
757
- });
704
+ usage: null,
705
+ };
758
706
  }
759
707
 
760
708
  /**
761
- * Convert reasoning text → assistant message with metadata.reasoning flag.
762
- * Displayed as separate "Reasoning" bubble in UI.
709
+ * Convert reasoning text → ReasoningMessage
763
710
  */
764
711
  export function convertReasoningMessage(
765
712
  reasoningText: string,
766
713
  ocMessage: OCMessage,
767
714
  sessionId: string,
768
- ): EngineSDKMessage {
715
+ ): ReasoningMessage {
769
716
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
770
- const modelId = assistantMsg ? `${assistantMsg.providerID}/${assistantMsg.modelID}` : '';
717
+ const provId = assistantMsg?.providerID || '';
718
+ const mdlId = assistantMsg?.modelID || '';
771
719
 
772
720
  return {
773
- ...buildAssistantSDKMessage({
774
- content: [{ type: 'text', text: reasoningText }],
775
- ocMessage,
776
- modelId,
777
- sessionId,
778
- stopReason: null,
779
- uuid: crypto.randomUUID(),
780
- }),
781
- metadata: { reasoning: true },
721
+ type: 'reasoning',
722
+ createdAt: new Date().toISOString(),
723
+ messageId: crypto.randomUUID(),
724
+ sessionId,
725
+ parent: { messageId: null, sessionId: null, toolUseId: null },
726
+ engine: { type: 'opencode' as const, provider: provId, model: { id: mdlId, name: '' }, account: { id: 0, name: '' } },
727
+ text: reasoningText,
782
728
  };
783
729
  }
784
730
 
785
731
  /**
786
- * Convert reasoning delta → stream event with metadata.reasoning flag.
732
+ * Convert reasoning delta → TextDeltaEvent (reasoning: true)
787
733
  */
788
734
  export function convertPartialReasoningDelta(
789
735
  text: string,
790
736
  sessionId: string,
791
- ): EngineSDKMessage {
792
- // Synthetic stream event — partial SDK structure by design
737
+ ): TextDeltaEvent {
793
738
  return {
794
739
  type: 'stream_event',
795
- event: {
796
- type: 'content_block_delta',
797
- index: 0,
798
- delta: { type: 'text_delta', text }
799
- },
800
- metadata: { reasoning: true },
801
- parent_tool_use_id: null,
802
- uuid: crypto.randomUUID(),
803
- session_id: sessionId
804
- } as unknown as EngineSDKMessage;
740
+ event: 'delta',
741
+ sessionId,
742
+ text,
743
+ reasoning: true,
744
+ };
805
745
  }
806
746
 
807
747
  /**
808
- * Convert reasoning stream start → stream event with metadata.reasoning flag.
748
+ * Convert reasoning stream start → StreamLifecycleEvent (reasoning: true)
809
749
  */
810
- export function convertReasoningStreamStart(sessionId: string): EngineSDKMessage {
811
- // Synthetic stream event — partial SDK structure by design
750
+ export function convertReasoningStreamStart(sessionId: string): StreamLifecycleEvent {
812
751
  return {
813
752
  type: 'stream_event',
814
- event: { type: 'message_start', message: { role: 'assistant', content: [] } },
815
- metadata: { reasoning: true },
816
- parent_tool_use_id: null,
817
- uuid: crypto.randomUUID(),
818
- session_id: sessionId
819
- } as unknown as EngineSDKMessage;
753
+ event: 'start',
754
+ sessionId,
755
+ reasoning: true,
756
+ };
820
757
  }
821
758
 
822
759
  /**
823
- * Convert reasoning stream stop → stream event with metadata.reasoning flag.
760
+ * Convert reasoning stream stop → StreamLifecycleEvent (reasoning: true)
824
761
  */
825
- export function convertReasoningStreamStop(sessionId: string): EngineSDKMessage {
826
- // Synthetic stream event — partial SDK structure by design
762
+ export function convertReasoningStreamStop(sessionId: string): StreamLifecycleEvent {
827
763
  return {
828
764
  type: 'stream_event',
829
- event: { type: 'message_stop' },
830
- metadata: { reasoning: true },
831
- parent_tool_use_id: null,
832
- uuid: crypto.randomUUID(),
833
- session_id: sessionId
834
- } as unknown as EngineSDKMessage;
765
+ event: 'stop',
766
+ sessionId,
767
+ reasoning: true,
768
+ };
835
769
  }
836
770
 
837
771
  /**
838
- * Convert a subtask part → assistant message with Agent tool_use.
839
- * Used for progressive rendering when OpenCode emits subtask parts.
772
+ * Convert a subtask part → AssistantMessage with Agent tool_use.
840
773
  */
841
774
  export function convertSubtaskToolUseOnly(
842
775
  subtaskPart: { id: string; prompt: string; description: string; agent: string },
843
776
  ocMessage: OCMessage,
844
777
  sessionId: string,
845
- ): SDKMessage {
778
+ ): UnifiedAssistantMessage {
846
779
  const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
847
- const modelId = assistantMsg ? `${assistantMsg.providerID}/${assistantMsg.modelID}` : '';
780
+ const provId = assistantMsg?.providerID || '';
781
+ const mdlId = assistantMsg?.modelID || '';
848
782
 
849
- return buildAssistantSDKMessage({
783
+ return {
784
+ type: 'assistant',
785
+ createdAt: new Date().toISOString(),
786
+ messageId: crypto.randomUUID(),
787
+ sessionId,
788
+ parent: { messageId: null, sessionId: null, toolUseId: null },
789
+ engine: { type: 'opencode' as const, provider: provId, model: { id: mdlId, name: '' }, account: { id: 0, name: '' } },
850
790
  content: [{
851
791
  type: 'tool_use',
852
792
  id: subtaskPart.id || crypto.randomUUID(),
@@ -854,27 +794,26 @@ export function convertSubtaskToolUseOnly(
854
794
  input: {
855
795
  prompt: subtaskPart.prompt || '',
856
796
  description: subtaskPart.description || '',
857
- subagent_type: subtaskPart.agent || 'general-purpose',
858
- } as NormalizedToolInput,
859
- }],
860
- ocMessage,
861
- modelId,
862
- sessionId,
797
+ subagentType: subtaskPart.agent || 'general-purpose',
798
+ },
799
+ result: null,
800
+ subActivities: [],
801
+ skillPrompt: null,
802
+ interrupted: false,
803
+ } as ToolUseBlock],
863
804
  stopReason: 'tool_use',
864
- uuid: crypto.randomUUID(),
865
- });
805
+ usage: null,
806
+ };
866
807
  }
867
808
 
868
809
  /**
869
- * Convert a completed/errored tool part → user message with tool_result.
870
- * Sent after the tool finishes executing, matching Claude Code's pattern
871
- * where tool_result arrives as a separate user message.
810
+ * Convert a completed/errored tool part → UserMessage with tool_result content.
872
811
  */
873
812
  export function convertToolResultOnly(
874
813
  toolPart: ToolPart,
875
814
  sessionId: string,
876
- parentToolUseId: string | null = null,
877
- ): SDKMessage {
815
+ parentToolUseId?: string,
816
+ ): UserMessage {
878
817
  const toolUseId = toolPart.callID || toolPart.id || crypto.randomUUID();
879
818
 
880
819
  let content: string;
@@ -890,17 +829,18 @@ export function convertToolResultOnly(
890
829
 
891
830
  return {
892
831
  type: 'user',
893
- uuid: crypto.randomUUID(),
894
- session_id: sessionId,
895
- parent_tool_use_id: parentToolUseId,
896
- message: {
897
- role: 'user',
898
- content: [{
899
- type: 'tool_result',
900
- tool_use_id: toolUseId,
901
- content,
902
- ...(hasError && { is_error: true }),
903
- }]
904
- }
905
- } as unknown as SDKMessage;
832
+ createdAt: new Date().toISOString(),
833
+ messageId: crypto.randomUUID(),
834
+ sessionId,
835
+ parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId || null },
836
+ engine: { type: 'opencode' as const, provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } },
837
+ sender: { id: '', name: '' },
838
+ content: [{
839
+ type: 'tool_result',
840
+ toolUseId,
841
+ content,
842
+ isError: hasError,
843
+ }],
844
+ synthetic: true,
845
+ };
906
846
  }