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