@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
@@ -15,6 +15,7 @@ import type { OpencodeClient } from '@opencode-ai/sdk';
15
15
  import type { Subprocess } from 'bun';
16
16
  import { getOpenCodeMcpConfig } from '../../../mcp';
17
17
  import { settingsQueries } from '../../../database/queries';
18
+ import { generateOpenCodeProviderConfig } from './config';
18
19
  import { debug } from '$shared/utils/logger';
19
20
 
20
21
  const OPENCODE_HOST = '127.0.0.1';
@@ -142,8 +143,25 @@ async function init(): Promise<void> {
142
143
  }
143
144
  }
144
145
 
145
- const configContent = Object.keys(mcpConfig).length > 0
146
- ? JSON.stringify({ mcp: mcpConfig })
146
+ // Build provider config from DB (enabled providers + env vars)
147
+ const providerConfig = generateOpenCodeProviderConfig();
148
+ if (providerConfig.enabledProviders.length > 0) {
149
+ debug.log('engine', `Open Code server: enabling ${providerConfig.enabledProviders.length} provider(s): ${providerConfig.enabledProviders.join(', ')}`);
150
+ }
151
+ if (Object.keys(providerConfig.envVars).length > 0) {
152
+ debug.log('engine', `Open Code server: injecting ${Object.keys(providerConfig.envVars).length} env var(s): ${Object.keys(providerConfig.envVars).join(', ')}`);
153
+ }
154
+
155
+ // Merge MCP config + enabled_providers into a single OPENCODE_CONFIG_CONTENT
156
+ const mergedConfig: Record<string, unknown> = {};
157
+ if (Object.keys(mcpConfig).length > 0) {
158
+ mergedConfig.mcp = mcpConfig;
159
+ }
160
+ if (providerConfig.enabledProviders.length > 0) {
161
+ mergedConfig.enabled_providers = providerConfig.enabledProviders;
162
+ }
163
+ const configContent = Object.keys(mergedConfig).length > 0
164
+ ? JSON.stringify(mergedConfig)
147
165
  : '{}';
148
166
 
149
167
  debug.log('engine', `Spawning: ${args.join(' ')}`);
@@ -153,6 +171,7 @@ async function init(): Promise<void> {
153
171
  stderr: 'pipe',
154
172
  env: {
155
173
  ...process.env,
174
+ ...providerConfig.envVars,
156
175
  OPENCODE_CONFIG_CONTENT: configContent,
157
176
  },
158
177
  });
@@ -230,18 +249,41 @@ export function getServerUrl(): string | null {
230
249
  /**
231
250
  * Dispose the OpenCode client and stop the server.
232
251
  *
233
- * Only kills the child process when we spawned it. Reused servers stay alive
234
- * so the next session can pick them up without spawning a new process.
252
+ * @param forRestart — When true, always kills the server process (even if
253
+ * we didn't spawn it) and purges the stored URL so the next init() spawns
254
+ * a fresh server with updated config. Used by the Restart Server flow.
255
+ *
256
+ * When false (default), only kills the child process when we spawned it.
257
+ * Reused servers stay alive so the next session can pick them up.
235
258
  */
236
- export async function disposeOpenCodeClient(): Promise<void> {
237
- if (serverHandle && ownsProcess) {
238
- try {
239
- debug.log('engine', `Stopping Open Code server (${serverHandle.url})...`);
240
- serverHandle.close();
241
- settingsQueries.delete(DB_KEY);
242
- } catch (error) {
243
- debug.error('engine', 'Error stopping Open Code server:', error);
259
+ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
260
+ if (serverHandle) {
261
+ if (ownsProcess || forRestart) {
262
+ try {
263
+ debug.log('engine', `Stopping Open Code server (${serverHandle.url}, forRestart=${forRestart})...`);
264
+ if (ownsProcess) {
265
+ serverHandle.close();
266
+ } else if (forRestart) {
267
+ // Server we didn't spawn — kill it by sending a request or just
268
+ // purging the stored URL. The server process may be external, but
269
+ // clearing DB ensures we spawn a new one on next init().
270
+ try {
271
+ await fetch(`${serverHandle.url}/shutdown`, {
272
+ method: 'POST',
273
+ signal: AbortSignal.timeout(2000),
274
+ });
275
+ } catch {
276
+ // shutdown endpoint may not exist — that's fine
277
+ }
278
+ }
279
+ settingsQueries.delete(DB_KEY);
280
+ } catch (error) {
281
+ debug.error('engine', 'Error stopping Open Code server:', error);
282
+ }
244
283
  }
284
+ } else if (forRestart) {
285
+ // No active handle but forRestart requested — ensure DB is clean
286
+ settingsQueries.delete(DB_KEY);
245
287
  }
246
288
 
247
289
  clearClientState();
@@ -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
  }