@myrialabs/clopen 0.2.24 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/backend/chat/helpers.ts +2 -20
  3. package/backend/chat/stream-manager.ts +556 -547
  4. package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/engine-queries.ts +195 -36
  7. package/backend/database/queries/index.ts +1 -2
  8. package/backend/database/queries/message-queries.ts +84 -139
  9. package/backend/database/queries/session-queries.ts +167 -21
  10. package/backend/database/queries/snapshot-queries.ts +5 -4
  11. package/backend/database/queries/utils-queries.ts +2 -2
  12. package/backend/engine/adapters/claude/environment.ts +4 -5
  13. package/backend/engine/adapters/claude/message-converter.ts +501 -0
  14. package/backend/engine/adapters/claude/stream.ts +52 -47
  15. package/backend/engine/adapters/opencode/config.ts +7 -7
  16. package/backend/engine/adapters/opencode/message-converter.ts +266 -326
  17. package/backend/engine/adapters/opencode/stream.ts +84 -101
  18. package/backend/engine/types.ts +17 -11
  19. package/backend/project/status-manager.ts +10 -13
  20. package/backend/snapshot/helpers.ts +46 -90
  21. package/backend/snapshot/snapshot-service.ts +1 -1
  22. package/backend/utils/paths.ts +22 -1
  23. package/backend/ws/chat/index.ts +1 -11
  24. package/backend/ws/chat/stream.ts +101 -61
  25. package/backend/ws/engine/claude/accounts.ts +27 -7
  26. package/backend/ws/engine/claude/status.ts +3 -2
  27. package/backend/ws/engine/opencode/providers.ts +25 -24
  28. package/backend/ws/git/commit-message.ts +6 -8
  29. package/backend/ws/messages/crud.ts +4 -59
  30. package/backend/ws/sessions/crud.ts +78 -130
  31. package/backend/ws/sessions/index.ts +1 -9
  32. package/backend/ws/settings/crud.ts +14 -11
  33. package/backend/ws/snapshot/restore.ts +23 -26
  34. package/backend/ws/snapshot/timeline.ts +5 -5
  35. package/dist/assets/{index-w7Uwi2Jz.js → index-B95VOHJY.js} +2 -2
  36. package/dist/assets/main-D1QNkcRL.js +257 -0
  37. package/dist/assets/main-rtLiuU_x.css +1 -0
  38. package/dist/index.html +2 -2
  39. package/package.json +4 -4
  40. package/shared/constants/engines.ts +141 -56
  41. package/shared/types/database/schema.ts +39 -40
  42. package/shared/types/stores/settings.ts +8 -4
  43. package/shared/types/unified/common.ts +21 -0
  44. package/shared/types/unified/display.ts +25 -0
  45. package/shared/types/unified/engine.ts +61 -0
  46. package/shared/types/unified/index.ts +108 -0
  47. package/shared/types/unified/message.ts +151 -0
  48. package/shared/types/unified/stream.ts +157 -0
  49. package/shared/types/unified/tool.ts +268 -0
  50. package/shared/utils/message-formatter.ts +9 -73
  51. package/shared/utils/path.ts +3 -2
  52. package/tsconfig.json +1 -1
  53. package/backend/database/queries/opencode-provider-queries.ts +0 -190
  54. package/backend/engine/adapters/claude/path-utils.ts +0 -38
  55. package/backend/ws/chat/background.ts +0 -201
  56. package/dist/assets/main-B4q8wX9B.js +0 -257
  57. package/dist/assets/main-Bfz5Urp3.css +0 -1
  58. package/shared/types/engine/index.ts +0 -45
  59. package/shared/types/messaging/index.ts +0 -242
  60. package/shared/types/messaging/tool.ts +0 -374
@@ -2,16 +2,16 @@
2
2
  * Open Code Engine Adapter
3
3
  *
4
4
  * Wraps the @opencode-ai/sdk into the AIEngine interface.
5
- * Converts Open Code messages/events → SDKMessage (Claude format)
6
- * so stream-manager and frontend remain unchanged.
5
+ * Converts Open Code messages/events → EngineOutput (unified types)
6
+ * so stream-manager and frontend remain engine-agnostic.
7
7
  *
8
8
  * Server lifecycle is managed by ./server.ts (Bun.spawn).
9
9
  * This file only contains the OpenCodeEngine class (per-project instance).
10
10
  */
11
11
 
12
- import type { SDKMessage, SDKUserMessage, EngineSDKMessage } from '$shared/types/messaging';
12
+ import type { EngineOutput, UserMessage } from '$shared/types/unified';
13
13
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
14
- import type { EngineModel } from '$shared/types/engine';
14
+ import type { EngineModel } from '$shared/types/unified';
15
15
  import type {
16
16
  Provider,
17
17
  Model,
@@ -43,27 +43,6 @@ import {
43
43
  import { ensureClient, getClient, getServerUrl } from './server';
44
44
  import { debug } from '$shared/utils/logger';
45
45
 
46
- /** Map SDK Model.status to our category */
47
- function mapStatusToCategory(status: Model['status']): EngineModel['category'] {
48
- switch (status) {
49
- case 'deprecated': return 'legacy';
50
- case 'alpha':
51
- case 'beta': return 'stable';
52
- default: return 'latest';
53
- }
54
- }
55
-
56
- /** Build capability tags from SDK Model.capabilities */
57
- function buildCapabilityTags(model: Model): string[] {
58
- const tags: string[] = [];
59
- const caps = model.capabilities;
60
-
61
- if (caps.reasoning) tags.push('Reasoning');
62
- if (caps.attachment) tags.push('Attachments');
63
-
64
- return tags;
65
- }
66
-
67
46
  // ============================================================================
68
47
  // OpenCode Engine (per-project instance)
69
48
  // ============================================================================
@@ -123,19 +102,48 @@ export class OpenCodeEngine implements AIEngine {
123
102
  const providerModels: Record<string, Model> = provider.models ?? {};
124
103
 
125
104
  for (const [modelKey, model] of Object.entries(providerModels)) {
126
- const modelId = model.id || modelKey;
127
- const compoundId = `opencode:${provider.id}/${modelId}`;
128
-
129
105
  models.push({
130
- id: compoundId,
131
- engine: 'opencode',
132
- modelId: `${provider.id}/${modelId}`,
133
- name: model.name || modelId,
134
- provider: provider.id,
135
- description: `${model.name || modelId} via ${provider.name || provider.id}`,
136
- capabilities: buildCapabilityTags(model),
137
- contextWindow: model.limit.context,
138
- category: mapStatusToCategory(model.status),
106
+ engine: {
107
+ type: 'opencode',
108
+ provider: provider.id,
109
+ model: {
110
+ id: model.id,
111
+ name: model.name,
112
+ },
113
+ account: {
114
+ id: 0,
115
+ name: '',
116
+ },
117
+ },
118
+ limit: {
119
+ input: model.limit.context,
120
+ output: model.limit.output,
121
+ },
122
+ modalities: {
123
+ input: {
124
+ text: model.capabilities.input.text,
125
+ image: model.capabilities.input.image,
126
+ audio: model.capabilities.input.audio,
127
+ video: model.capabilities.input.video,
128
+ pdf: model.capabilities.input.pdf,
129
+ },
130
+ output: {
131
+ text: model.capabilities.output.text,
132
+ image: model.capabilities.output.image,
133
+ audio: model.capabilities.output.audio,
134
+ video: model.capabilities.output.video,
135
+ pdf: model.capabilities.output.pdf,
136
+ },
137
+ },
138
+ capabilities: {
139
+ reasoning: model.capabilities.reasoning,
140
+ tools: model.capabilities.toolcall,
141
+ structuredOutput: true,
142
+ },
143
+ cost: {
144
+ input: model.cost.input,
145
+ output: model.cost.output,
146
+ },
139
147
  });
140
148
  }
141
149
  }
@@ -150,19 +158,20 @@ export class OpenCodeEngine implements AIEngine {
150
158
  }
151
159
 
152
160
  /**
153
- * Stream a query through Open Code SDK, yielding SDKMessage (Claude format)
161
+ * Stream a query through Open Code SDK, yielding EngineOutput (unified types)
154
162
  *
155
163
  * Flow: subscribe to events FIRST, then send prompt asynchronously.
156
164
  * This ensures no events are missed between sending and subscribing.
157
165
  */
158
- async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineSDKMessage, void, unknown> {
166
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
159
167
  const client = await ensureClient();
160
168
 
161
169
  const {
162
170
  projectPath,
163
171
  prompt,
164
172
  resume,
165
- model = 'claude-sonnet',
173
+ providerSlug,
174
+ modelId,
166
175
  abortController
167
176
  } = options;
168
177
 
@@ -204,7 +213,7 @@ export class OpenCodeEngine implements AIEngine {
204
213
 
205
214
  this.activeSessionId = sessionId;
206
215
 
207
- yield convertSystemInitMessage(sessionId, model);
216
+ yield convertSystemInitMessage(sessionId, modelId);
208
217
  yield convertStreamStart(sessionId);
209
218
 
210
219
  // 1. Subscribe to event stream FIRST (before sending prompt)
@@ -213,15 +222,12 @@ export class OpenCodeEngine implements AIEngine {
213
222
  signal: this.activeAbortController.signal
214
223
  });
215
224
 
216
- // 2. Send prompt asynchronously (non-blocking) — parse "providerId/modelId"
217
- const idx = model.indexOf('/');
218
- const [providerID, modelID] = idx >= 0 ? [model.substring(0, idx), model.substring(idx + 1)] : ['', model];
219
-
225
+ // 2. Send prompt asynchronously (non-blocking)
220
226
  client.session.promptAsync({
221
227
  path: { id: sessionId },
222
228
  body: {
223
229
  parts: promptParts as any,
224
- ...(providerID && modelID ? { model: { providerID, modelID } } : {}),
230
+ ...(providerSlug && modelId ? { model: { providerID: providerSlug, modelID: modelId } } : {}),
225
231
  },
226
232
  query: { directory: projectPath },
227
233
  }).catch(error => {
@@ -973,61 +979,41 @@ export class OpenCodeEngine implements AIEngine {
973
979
  }
974
980
 
975
981
  /**
976
- * Extract prompt parts (text + file attachments) from SDKUserMessage.
977
- * Converts Claude-format image/document blocks to OpenCode FilePartInput format.
982
+ * Extract prompt parts (text + file attachments) from UserMessage.
983
+ * Converts unified content blocks to OpenCode FilePartInput format.
978
984
  */
979
- private extractPromptParts(prompt: SDKUserMessage): Array<
985
+ private extractPromptParts(prompt: UserMessage): Array<
980
986
  | { type: 'text'; text: string }
981
987
  | { type: 'file'; mime: string; filename?: string; url: string }
982
988
  > {
983
- const msg = prompt as Record<string, unknown>;
984
- const message = msg.message as Record<string, unknown> | undefined;
985
- if (!message) return [{ type: 'text', text: '' }];
986
-
987
- if (typeof message.content === 'string') {
988
- return [{ type: 'text', text: message.content }];
989
- }
990
-
991
- if (Array.isArray(message.content)) {
992
- const parts: Array<
993
- | { type: 'text'; text: string }
994
- | { type: 'file'; mime: string; filename?: string; url: string }
995
- > = [];
996
-
997
- for (const block of message.content as Array<Record<string, unknown>>) {
998
- if (block.type === 'text') {
999
- parts.push({ type: 'text', text: block.text as string });
1000
- } else if (block.type === 'image' && block.source) {
1001
- // Claude format: { type: 'image', source: { type: 'base64', media_type, data } }
1002
- const source = block.source as Record<string, unknown>;
1003
- if (source.type === 'base64' && source.data && source.media_type) {
1004
- parts.push({
1005
- type: 'file',
1006
- mime: source.media_type as string,
1007
- url: `data:${source.media_type};base64,${source.data}`,
1008
- });
1009
- }
1010
- } else if (block.type === 'document' && block.source) {
1011
- // Claude format: { type: 'document', source: { type: 'base64', media_type, data }, title }
1012
- const source = block.source as Record<string, unknown>;
1013
- if (source.type === 'base64' && source.data && source.media_type) {
1014
- parts.push({
1015
- type: 'file',
1016
- mime: source.media_type as string,
1017
- filename: (block.title as string) || undefined,
1018
- url: `data:${source.media_type};base64,${source.data}`,
1019
- });
1020
- }
1021
- }
1022
- }
1023
-
1024
- if (parts.length === 0) {
1025
- parts.push({ type: 'text', text: '' });
989
+ const parts: Array<
990
+ | { type: 'text'; text: string }
991
+ | { type: 'file'; mime: string; filename?: string; url: string }
992
+ > = [];
993
+
994
+ for (const block of prompt.content) {
995
+ if (block.type === 'text') {
996
+ parts.push({ type: 'text', text: block.text });
997
+ } else if (block.type === 'image') {
998
+ parts.push({
999
+ type: 'file',
1000
+ mime: block.mediaType,
1001
+ url: `data:${block.mediaType};base64,${block.data}`,
1002
+ });
1003
+ } else if (block.type === 'document') {
1004
+ parts.push({
1005
+ type: 'file',
1006
+ mime: block.mediaType,
1007
+ filename: block.title || undefined,
1008
+ url: `data:${block.mediaType};base64,${block.data}`,
1009
+ });
1026
1010
  }
1027
- return parts;
1028
1011
  }
1029
1012
 
1030
- return [{ type: 'text', text: '' }];
1013
+ if (parts.length === 0) {
1014
+ parts.push({ type: 'text', text: '' });
1015
+ }
1016
+ return parts;
1031
1017
  }
1032
1018
 
1033
1019
  /**
@@ -1038,7 +1024,8 @@ export class OpenCodeEngine implements AIEngine {
1038
1024
  async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
1039
1025
  const {
1040
1026
  prompt,
1041
- model = 'claude-sonnet',
1027
+ providerSlug,
1028
+ modelId,
1042
1029
  schema,
1043
1030
  projectPath,
1044
1031
  abortController
@@ -1059,24 +1046,20 @@ export class OpenCodeEngine implements AIEngine {
1059
1046
  throw new Error('Failed to create OpenCode session');
1060
1047
  }
1061
1048
 
1062
- // Parse model into providerID/modelID
1063
- const idx = model.indexOf('/');
1064
- const [providerID, modelID] = idx >= 0 ? [model.substring(0, idx), model.substring(idx + 1)] : ['', model];
1065
-
1066
1049
  // Wrap prompt with JSON instruction since v1 doesn't support format option
1067
1050
  const jsonPrompt = `${prompt}
1068
1051
 
1069
1052
  IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text:
1070
1053
  ${JSON.stringify(schema, null, 2)}`;
1071
1054
 
1072
- debug.log('engine', `[OC structured] Sending prompt to session ${sessionId}, model=${model}`);
1055
+ debug.log('engine', `[OC structured] Sending prompt to session ${sessionId}, provider=${providerSlug}, modelId=${modelId}`);
1073
1056
 
1074
1057
  // Use v1 SDK synchronous prompt method — waits for completion
1075
1058
  const response = await client.session.prompt({
1076
1059
  path: { id: sessionId },
1077
1060
  body: {
1078
1061
  parts: [{ type: 'text', text: jsonPrompt }],
1079
- ...(providerID && modelID ? { model: { providerID, modelID } } : {}),
1062
+ ...(providerSlug && modelId ? { model: { providerID: providerSlug, modelID: modelId } } : {}),
1080
1063
  tools: {}
1081
1064
  },
1082
1065
  query: { directory: projectPath },
@@ -2,14 +2,14 @@
2
2
  * Engine Types (Backend)
3
3
  *
4
4
  * Defines the AIEngine interface that all engine adapters must implement.
5
- * Every adapter normalizes its output to Claude SDK format (SDKMessage)
5
+ * Every adapter converts SDK-specific events to EngineOutput (unified format)
6
6
  * so stream-manager and frontend remain engine-agnostic.
7
7
  */
8
8
 
9
- import type { SDKMessage, SDKUserMessage, EngineSDKMessage } from '$shared/types/messaging';
10
- import type { EngineType, EngineModel } from '$shared/types/engine';
9
+ import type { EngineType, UserMessage, EngineOutput } from '$shared/types/unified';
10
+ import type { EngineModel } from '$shared/types/unified';
11
11
 
12
- export type { EngineType, EngineModel };
12
+ export type { EngineType };
13
13
 
14
14
  /** Execution context for MCP tool handlers (project isolation) */
15
15
  export interface McpExecutionContext {
@@ -21,14 +21,17 @@ export interface McpExecutionContext {
21
21
  /** Options passed to engine.streamQuery() */
22
22
  export interface EngineQueryOptions {
23
23
  projectPath: string;
24
- prompt: SDKUserMessage;
24
+ prompt: UserMessage;
25
25
  resume?: string;
26
26
  forkSession?: boolean;
27
27
  maxTurns?: number;
28
- model?: string;
28
+ /** Provider slug (e.g. 'anthropic', 'openai'). Required for OpenCode. */
29
+ providerSlug: string;
30
+ /** Model ID (e.g. 'claude-opus-4-6', 'gpt-5'). */
31
+ modelId: string;
29
32
  includePartialMessages?: boolean;
30
33
  abortController?: AbortController;
31
- claudeAccountId?: number;
34
+ accountId?: number;
32
35
  /** Context bound to MCP tool handlers for project isolation */
33
36
  mcpContext?: McpExecutionContext;
34
37
  }
@@ -36,11 +39,14 @@ export interface EngineQueryOptions {
36
39
  /** Options for one-shot structured generation (no tools, no streaming) */
37
40
  export interface StructuredGenerationOptions {
38
41
  prompt: string;
39
- model?: string;
42
+ /** Provider slug (e.g. 'anthropic', 'openai'). Required for OpenCode. */
43
+ providerSlug: string;
44
+ /** Model ID. */
45
+ modelId: string;
40
46
  schema: Record<string, unknown>;
41
47
  projectPath: string;
42
48
  abortController?: AbortController;
43
- claudeAccountId?: number;
49
+ accountId?: number;
44
50
  }
45
51
 
46
52
  /** The contract every engine adapter must fulfil */
@@ -59,9 +65,9 @@ export interface AIEngine {
59
65
 
60
66
  /**
61
67
  * Stream a query.
62
- * MUST yield messages in Claude SDK format (SDKMessage).
68
+ * MUST yield events in EngineOutput format (unified types).
63
69
  */
64
- streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineSDKMessage, void, unknown>;
70
+ streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown>;
65
71
 
66
72
  /** Cancel the active query */
67
73
  cancel(): Promise<void>;
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { streamManager, type StreamState } from '../chat/stream-manager.js';
7
7
  import { ws } from '../utils/ws.js';
8
+ import type { UnifiedMessage } from '$shared/types/unified';
8
9
 
9
10
  // Interactive tools that block the stream waiting for user input
10
11
  const INTERACTIVE_TOOLS = new Set(['AskUserQuestion']);
@@ -18,26 +19,22 @@ const INTERACTIVE_TOOLS = new Set(['AskUserQuestion']);
18
19
  function detectStreamWaitingInput(stream: StreamState): boolean {
19
20
  if (stream.status !== 'active') return false;
20
21
 
21
- // SSEEventData.message is SDKMessage: { type, message: { content: [...] } }
22
- // Content blocks live at msg.message.content, NOT msg.content
23
22
  const answeredToolIds = new Set<string>();
24
23
  for (const event of stream.messages) {
25
- const msg = event.message;
26
- if (!msg || (msg as any).type !== 'user') continue;
27
- const content = Array.isArray((msg as any).message?.content) ? (msg as any).message.content : [];
28
- for (const item of content) {
29
- if (item.type === 'tool_result' && item.tool_use_id) {
30
- answeredToolIds.add(item.tool_use_id);
24
+ const msg = (event as { message?: UnifiedMessage }).message;
25
+ if (!msg || msg.type !== 'user') continue;
26
+ for (const block of msg.content) {
27
+ if (block.type === 'tool_result' && block.toolUseId) {
28
+ answeredToolIds.add(block.toolUseId);
31
29
  }
32
30
  }
33
31
  }
34
32
 
35
33
  for (const event of stream.messages) {
36
- const msg = event.message;
37
- if (!msg || (msg as any).type !== 'assistant') continue;
38
- const content = Array.isArray((msg as any).message?.content) ? (msg as any).message.content : [];
39
- if (content.some((item: any) =>
40
- item.type === 'tool_use' && INTERACTIVE_TOOLS.has(item.name) && item.id && !answeredToolIds.has(item.id)
34
+ const msg = (event as { message?: UnifiedMessage }).message;
35
+ if (!msg || msg.type !== 'assistant') continue;
36
+ if (msg.content.some(block =>
37
+ block.type === 'tool_use' && INTERACTIVE_TOOLS.has(block.name) && block.id && !answeredToolIds.has(block.id)
41
38
  )) {
42
39
  return true;
43
40
  }
@@ -1,7 +1,8 @@
1
1
  import { snapshotQueries, messageQueries, checkpointQueries } from '../database/queries';
2
2
  import { debug } from '$shared/utils/logger';
3
- import type { SDKMessage } from '$shared/types/messaging';
3
+ import { loadMessage } from '$shared/utils/message-formatter';
4
4
  import type { DatabaseMessage } from '$shared/types/database/schema';
5
+ import type { UnifiedMessage, UserMessage } from '$shared/types/unified';
5
6
 
6
7
  /**
7
8
  * Snapshot domain helper functions
@@ -37,50 +38,31 @@ export interface TimelineResponse {
37
38
  /**
38
39
  * Check if a user message is an internal/non-genuine user message.
39
40
  *
40
- * The SDK uses `type: 'user'` for several kinds of messages that are NOT
41
- * typed by the real human user:
41
+ * Internal messages include:
42
42
  * 1. Tool-result confirmations — content contains `tool_result` blocks
43
- * 2. Sub-agent / Task prompts — `parent_tool_use_id` is non-null
44
- * 3. Post-compaction synthetic summaries — `isSynthetic` is true
45
- *
46
- * Only messages that pass none of these checks are genuine user input.
43
+ * 2. Sub-agent / Task prompts — parentToolUseId is non-null
44
+ * 3. Post-compaction synthetic summaries — synthetic is true
47
45
  */
48
- export function isInternalToolMessage(sdkMessage: any): boolean {
49
- if (sdkMessage.type !== 'user') return false;
50
-
51
- // Sub-agent or tool-result message (parent_tool_use_id is set)
52
- if (sdkMessage.parent_tool_use_id != null) return true;
46
+ export function isInternalToolMessage(msg: UnifiedMessage): boolean {
47
+ if (msg.type !== 'user') return false;
48
+ const user = msg as UserMessage;
53
49
 
54
- // Synthetic message generated after context compaction
55
- if (sdkMessage.isSynthetic === true) return true;
50
+ if (user.parent.toolUseId != null) return true;
51
+ if (user.synthetic) return true;
56
52
 
57
- const content = sdkMessage.message?.content;
58
- if (!content) return false;
59
-
60
- // Check if content is array and contains tool_result blocks
61
- if (Array.isArray(content)) {
62
- return content.some((block: any) => block.type === 'tool_result');
63
- }
64
-
65
- return false;
53
+ return user.content.some(block => block.type === 'tool_result');
66
54
  }
67
55
 
68
56
  /**
69
- * Extract user message text from SDK message
57
+ * Extract text from a UnifiedMessage.
70
58
  */
71
- export function extractMessageText(sdkMessage: SDKMessage): string {
72
- if ('message' in sdkMessage && sdkMessage.message?.content) {
73
- const content = sdkMessage.message.content;
74
- if (typeof content === 'string') {
75
- return content;
76
- } else if (Array.isArray(content)) {
77
- const textBlock = content.find(
78
- (item: any) => typeof item === 'object' && 'text' in item
79
- );
80
- if (textBlock && 'text' in textBlock) {
81
- return textBlock.text;
82
- }
83
- }
59
+ export function extractMessageText(msg: UnifiedMessage): string {
60
+ if (msg.type === 'reasoning') return msg.text;
61
+ if (msg.type === 'compact_boundary') return '';
62
+
63
+ // user or assistant — both have content arrays
64
+ for (const block of msg.content) {
65
+ if (block.type === 'text' && block.text) return block.text;
84
66
  }
85
67
  return '';
86
68
  }
@@ -88,13 +70,12 @@ export function extractMessageText(sdkMessage: SDKMessage): string {
88
70
  /**
89
71
  * Check if a database message is a checkpoint (real user message with text)
90
72
  */
91
- export function isCheckpointMessage(msg: DatabaseMessage): boolean {
73
+ export function isCheckpointMessage(row: DatabaseMessage): boolean {
92
74
  try {
93
- const sdk = JSON.parse(msg.sdk_message) as SDKMessage;
94
- if (sdk.type !== 'user') return false;
95
- if (isInternalToolMessage(sdk)) return false;
96
- const text = extractMessageText(sdk);
97
- return text.trim() !== '';
75
+ const msg = loadMessage(row);
76
+ if (msg.type !== 'user') return false;
77
+ if (isInternalToolMessage(msg)) return false;
78
+ return extractMessageText(msg).trim() !== '';
98
79
  } catch {
99
80
  return false;
100
81
  }
@@ -224,7 +205,6 @@ export function findSessionEnd(
224
205
  }
225
206
 
226
207
  // Fallback: timestamp-based approach
227
- // Walk chronologically through messages after checkpoint until next real user message
228
208
  debug.log('snapshot', `findSessionEnd: parent-based returned checkpoint itself, trying timestamp fallback`);
229
209
  const timestampResult = findSessionEndByTimestamp(checkpointMsg, allMessages);
230
210
 
@@ -237,6 +217,17 @@ export function findSessionEnd(
237
217
  return checkpointMsg;
238
218
  }
239
219
 
220
+ /**
221
+ * Check if a DatabaseMessage is a session continuation
222
+ * (assistant, internal user, or compact boundary — NOT a real user message).
223
+ */
224
+ function isSessionContinuation(row: DatabaseMessage): boolean {
225
+ const msg = loadMessage(row);
226
+ if (msg.type === 'assistant' || msg.type === 'reasoning' || msg.type === 'compact_boundary') return true;
227
+ if (msg.type === 'user' && isInternalToolMessage(msg)) return true;
228
+ return false;
229
+ }
230
+
240
231
  /**
241
232
  * Parent-based session end finder.
242
233
  * Walks through childrenMap (parent_message_id relationships).
@@ -260,36 +251,12 @@ function findSessionEndByParent(
260
251
 
261
252
  while (true) {
262
253
  const children = childrenMap.get(current.id) || [];
263
- children.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
264
-
265
- let sessionContinuation: DatabaseMessage | null = null;
266
-
267
- for (const child of children) {
268
- try {
269
- const sdk = JSON.parse(child.sdk_message);
270
- if (sdk.type === 'assistant') {
271
- sessionContinuation = child;
272
- break;
273
- }
274
- if (sdk.type === 'user' && isInternalToolMessage(sdk)) {
275
- sessionContinuation = child;
276
- break;
277
- }
278
- // System messages (e.g. compact_boundary) are part of session continuation
279
- if (sdk.type === 'system') {
280
- sessionContinuation = child;
281
- break;
282
- }
283
- } catch {
284
- continue;
285
- }
286
- }
254
+ children.sort((a, b) => a.created_at.localeCompare(b.created_at));
287
255
 
288
- if (!sessionContinuation) {
289
- return lastValidEnd;
290
- }
256
+ const continuation = children.find(child => isSessionContinuation(child));
257
+ if (!continuation) return lastValidEnd;
291
258
 
292
- current = sessionContinuation;
259
+ current = continuation;
293
260
  lastValidEnd = current;
294
261
  }
295
262
  }
@@ -303,7 +270,7 @@ function findSessionEndByTimestamp(
303
270
  checkpointMsg: DatabaseMessage,
304
271
  allMessages: DatabaseMessage[]
305
272
  ): DatabaseMessage {
306
- const sorted = [...allMessages].sort((a, b) => a.timestamp.localeCompare(b.timestamp));
273
+ const sorted = [...allMessages].sort((a, b) => a.created_at.localeCompare(b.created_at));
307
274
 
308
275
  const checkpointIndex = sorted.findIndex(m => m.id === checkpointMsg.id);
309
276
  if (checkpointIndex === -1) return checkpointMsg;
@@ -311,23 +278,12 @@ function findSessionEndByTimestamp(
311
278
  let lastValidEnd = checkpointMsg;
312
279
 
313
280
  for (let i = checkpointIndex + 1; i < sorted.length; i++) {
314
- const msg = sorted[i];
315
- try {
316
- const sdk = JSON.parse(msg.sdk_message);
317
-
318
- if (sdk.type === 'assistant') {
319
- lastValidEnd = msg;
320
- } else if (sdk.type === 'user' && isInternalToolMessage(sdk)) {
321
- lastValidEnd = msg;
322
- } else if (sdk.type === 'system') {
323
- // System messages (e.g. compact_boundary) are part of session continuation
324
- lastValidEnd = msg;
325
- } else if (sdk.type === 'user' && !isInternalToolMessage(sdk)) {
326
- // Hit the next real user message (checkpoint) - stop
327
- break;
328
- }
329
- } catch {
330
- continue;
281
+ const row = sorted[i];
282
+ if (isSessionContinuation(row)) {
283
+ lastValidEnd = row;
284
+ } else {
285
+ // Hit a real user message — stop
286
+ break;
331
287
  }
332
288
  }
333
289
 
@@ -347,7 +347,7 @@ export class SnapshotService {
347
347
  const headMsg = messageQueries.getById(currentHead);
348
348
  if (headMsg) {
349
349
  for (let i = sessionSnapshots.length - 1; i >= 0; i--) {
350
- if (sessionSnapshots[i].created_at <= headMsg.timestamp) {
350
+ if (sessionSnapshots[i].created_at <= headMsg.created_at) {
351
351
  if (sessionSnapshots[i].created_at < targetTime) {
352
352
  referenceTime = sessionSnapshots[i].created_at;
353
353
  }
@@ -1,4 +1,4 @@
1
- import { join } from 'path';
1
+ import { join, resolve } from 'path';
2
2
  import { homedir } from 'os';
3
3
 
4
4
  /**
@@ -9,3 +9,24 @@ import { homedir } from 'os';
9
9
  export function getClopenDir(): string {
10
10
  return join(homedir(), process.env.NODE_ENV === 'development' ? '.clopen-dev' : '.clopen');
11
11
  }
12
+
13
+ /**
14
+ * Resolve a path to an OS-native absolute path.
15
+ * On Windows: resolves relative paths, prepends drive letter, converts to backslashes.
16
+ * On POSIX: returns path as-is (already absolute from OS perspective).
17
+ */
18
+ export function resolveOsPath(projectPath: string): string {
19
+ let resolved = projectPath;
20
+ if (process.platform === 'win32') {
21
+ if (!projectPath.match(/^[A-Za-z]:\\/)) {
22
+ if (projectPath.startsWith('\\')) {
23
+ const currentDrive = process.cwd().substring(0, 2);
24
+ resolved = currentDrive + projectPath;
25
+ } else {
26
+ resolved = resolve(projectPath);
27
+ }
28
+ }
29
+ resolved = resolved.replace(/\//g, '\\');
30
+ }
31
+ return resolved;
32
+ }
@@ -2,20 +2,10 @@
2
2
  * Chat Router
3
3
  *
4
4
  * Combines all chat WebSocket handlers into a single router.
5
- * Replaces the old SSE-based chat streaming system.
6
- *
7
- * Structure:
8
- * - stream.ts: Real-time chat streaming events (stream, cancel)
9
- * - background.ts: Background streaming management (start, state, messages, cancel)
10
5
  */
11
6
 
12
7
  import { createRouter } from '$shared/utils/ws-server';
13
8
  import { streamHandler } from './stream';
14
- import { backgroundHandler } from './background';
15
9
 
16
10
  export const chatRouter = createRouter()
17
- // Real-time streaming
18
- .merge(streamHandler)
19
-
20
- // Background streaming
21
- .merge(backgroundHandler);
11
+ .merge(streamHandler);