forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdkMessageAdapter.ts
More file actions
302 lines (277 loc) · 8.85 KB
/
sdkMessageAdapter.ts
File metadata and controls
302 lines (277 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import type {
SDKAssistantMessage,
SDKCompactBoundaryMessage,
SDKMessage,
SDKPartialAssistantMessage,
SDKResultMessage,
SDKStatusMessage,
SDKSystemMessage,
SDKToolProgressMessage,
} from '../entrypoints/agentSdkTypes.js'
import type {
AssistantMessage,
Message,
StreamEvent,
SystemMessage,
} from '../types/message.js'
import { logForDebugging } from '../utils/debug.js'
import { fromSDKCompactMetadata } from '../utils/messages/mappers.js'
import { createUserMessage } from '../utils/messages.js'
/**
* Converts SDKMessage from CCR to REPL Message types.
*
* The CCR backend sends SDK-format messages via WebSocket. The REPL expects
* internal Message types for rendering. This adapter bridges the two.
*/
/**
* Convert an SDKAssistantMessage to an AssistantMessage
*/
function convertAssistantMessage(msg: SDKAssistantMessage): AssistantMessage {
return {
type: 'assistant',
message: msg.message,
uuid: msg.uuid,
requestId: undefined,
timestamp: new Date().toISOString(),
error: msg.error,
}
}
/**
* Convert an SDKPartialAssistantMessage (streaming) to a StreamEvent
*/
function convertStreamEvent(msg: SDKPartialAssistantMessage): StreamEvent {
return {
type: 'stream_event',
event: msg.event,
}
}
/**
* Convert an SDKResultMessage to a SystemMessage
*/
function convertResultMessage(msg: SDKResultMessage): SystemMessage {
const isError = msg.subtype !== 'success'
const content = isError
? msg.errors?.join(', ') || 'Unknown error'
: 'Session completed successfully'
return {
type: 'system',
subtype: 'informational',
content,
level: isError ? 'warning' : 'info',
uuid: msg.uuid,
timestamp: new Date().toISOString(),
}
}
/**
* Convert an SDKSystemMessage (init) to a SystemMessage
*/
function convertInitMessage(msg: SDKSystemMessage): SystemMessage {
return {
type: 'system',
subtype: 'informational',
content: `Remote session initialized (model: ${msg.model})`,
level: 'info',
uuid: msg.uuid,
timestamp: new Date().toISOString(),
}
}
/**
* Convert an SDKStatusMessage to a SystemMessage
*/
function convertStatusMessage(msg: SDKStatusMessage): SystemMessage | null {
if (!msg.status) {
return null
}
return {
type: 'system',
subtype: 'informational',
content:
msg.status === 'compacting'
? 'Compacting conversation…'
: `Status: ${msg.status}`,
level: 'info',
uuid: msg.uuid,
timestamp: new Date().toISOString(),
}
}
/**
* Convert an SDKToolProgressMessage to a SystemMessage.
* We use a system message instead of ProgressMessage since the Progress type
* is a complex union that requires tool-specific data we don't have from CCR.
*/
function convertToolProgressMessage(
msg: SDKToolProgressMessage,
): SystemMessage {
return {
type: 'system',
subtype: 'informational',
content: `Tool ${msg.tool_name} running for ${msg.elapsed_time_seconds}s…`,
level: 'info',
uuid: msg.uuid,
timestamp: new Date().toISOString(),
toolUseID: msg.tool_use_id,
}
}
/**
* Convert an SDKCompactBoundaryMessage to a SystemMessage
*/
function convertCompactBoundaryMessage(
msg: SDKCompactBoundaryMessage,
): SystemMessage {
return {
type: 'system',
subtype: 'compact_boundary',
content: 'Conversation compacted',
level: 'info',
uuid: msg.uuid,
timestamp: new Date().toISOString(),
compactMetadata: fromSDKCompactMetadata(msg.compact_metadata),
}
}
/**
* Result of converting an SDKMessage
*/
export type ConvertedMessage =
| { type: 'message'; message: Message }
| { type: 'stream_event'; event: StreamEvent }
| { type: 'ignored' }
type ConvertOptions = {
/** Convert user messages containing tool_result content blocks into UserMessages.
* Used by direct connect mode where tool results come from the remote server
* and need to be rendered locally. CCR mode ignores user messages since they
* are handled differently. */
convertToolResults?: boolean
/**
* Convert user text messages into UserMessages for display. Used when
* converting historical events where user-typed messages need to be shown.
* In live WS mode these are already added locally by the REPL so they're
* ignored by default.
*/
convertUserTextMessages?: boolean
}
/**
* Convert an SDKMessage to REPL message format
*/
export function convertSDKMessage(
msg: SDKMessage,
opts?: ConvertOptions,
): ConvertedMessage {
switch (msg.type) {
case 'assistant':
return { type: 'message', message: convertAssistantMessage(msg) }
case 'user': {
const content = msg.message?.content
// Tool result messages from the remote server need to be converted so
// they render and collapse like local tool results. Detect via content
// shape (tool_result blocks) — parent_tool_use_id is NOT reliable: the
// agent-side normalizeMessage() hardcodes it to null for top-level
// tool results, so it can't distinguish tool results from prompt echoes.
const isToolResult =
Array.isArray(content) && content.some(b => b.type === 'tool_result')
if (opts?.convertToolResults && isToolResult) {
return {
type: 'message',
message: createUserMessage({
content,
toolUseResult: msg.tool_use_result,
uuid: msg.uuid,
timestamp: msg.timestamp,
}),
}
}
// When converting historical events, user-typed messages need to be
// rendered (they weren't added locally by the REPL). Skip tool_results
// here — already handled above.
if (opts?.convertUserTextMessages && !isToolResult) {
if (typeof content === 'string' || Array.isArray(content)) {
return {
type: 'message',
message: createUserMessage({
content,
toolUseResult: msg.tool_use_result,
uuid: msg.uuid,
timestamp: msg.timestamp,
}),
}
}
}
// User-typed messages (string content) are already added locally by REPL.
// In CCR mode, all user messages are ignored (tool results handled differently).
return { type: 'ignored' }
}
case 'stream_event':
return { type: 'stream_event', event: convertStreamEvent(msg) }
case 'result':
// Only show result messages for errors. Success results are noise
// in multi-turn sessions (isLoading=false is sufficient signal).
if (msg.subtype !== 'success') {
return { type: 'message', message: convertResultMessage(msg) }
}
return { type: 'ignored' }
case 'system':
if (msg.subtype === 'init') {
return { type: 'message', message: convertInitMessage(msg) }
}
if (msg.subtype === 'status') {
const statusMsg = convertStatusMessage(msg)
return statusMsg
? { type: 'message', message: statusMsg }
: { type: 'ignored' }
}
if (msg.subtype === 'compact_boundary') {
return {
type: 'message',
message: convertCompactBoundaryMessage(msg),
}
}
// hook_response and other subtypes
logForDebugging(
`[sdkMessageAdapter] Ignoring system message subtype: ${msg.subtype}`,
)
return { type: 'ignored' }
case 'tool_progress':
return { type: 'message', message: convertToolProgressMessage(msg) }
case 'auth_status':
// Auth status is handled separately, not converted to a display message
logForDebugging('[sdkMessageAdapter] Ignoring auth_status message')
return { type: 'ignored' }
case 'tool_use_summary':
// Tool use summaries are SDK-only events, not displayed in REPL
logForDebugging('[sdkMessageAdapter] Ignoring tool_use_summary message')
return { type: 'ignored' }
case 'rate_limit_event':
// Rate limit events are SDK-only events, not displayed in REPL
logForDebugging('[sdkMessageAdapter] Ignoring rate_limit_event message')
return { type: 'ignored' }
default: {
// Gracefully ignore unknown message types. The backend may send new
// types before the client is updated; logging helps with debugging
// without crashing or losing the session.
logForDebugging(
`[sdkMessageAdapter] Unknown message type: ${(msg as { type: string }).type}`,
)
return { type: 'ignored' }
}
}
}
/**
* Check if an SDKMessage indicates the session has ended
*/
export function isSessionEndMessage(msg: SDKMessage): boolean {
return msg.type === 'result'
}
/**
* Check if an SDKResultMessage indicates success
*/
export function isSuccessResult(msg: SDKResultMessage): boolean {
return msg.subtype === 'success'
}
/**
* Extract the result text from a successful SDKResultMessage
*/
export function getResultText(msg: SDKResultMessage): string | null {
if (msg.subtype === 'success') {
return msg.result
}
return null
}