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