-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathacpContentMapper.ts
More file actions
382 lines (344 loc) · 11.4 KB
/
acpContentMapper.ts
File metadata and controls
382 lines (344 loc) · 11.4 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import type * as schema from '@agentclientprotocol/sdk/dist/schema.js'
import type { AssistantMessageBlock } from '@shared/chat'
import { createStreamEvent, type LLMCoreStreamEvent } from '@shared/types/core/llm-events'
export interface PlanEntry {
content: string
priority?: string | null
status?: string | null
}
export interface MappedContent {
events: LLMCoreStreamEvent[]
blocks: AssistantMessageBlock[]
/** Structured plan entries from the agent (optional) */
planEntries?: PlanEntry[]
/** Current mode ID from mode change notification (optional) */
currentModeId?: string
}
interface ToolCallState {
sessionId: string
toolCallId: string
toolName: string
argumentsBuffer: string
status?: schema.ToolCallStatus | null
started: boolean
}
const now = () => Date.now()
export class AcpContentMapper {
private readonly toolCallStates = new Map<string, ToolCallState>()
map(notification: schema.SessionNotification): MappedContent {
const { update, sessionId } = notification
const payload: MappedContent = { events: [], blocks: [] }
switch (update.sessionUpdate) {
case 'agent_message_chunk':
this.pushContent(update.content, 'text', payload)
break
case 'agent_thought_chunk':
this.pushContent(update.content, 'reasoning', payload)
break
case 'tool_call':
case 'tool_call_update':
this.handleToolCallUpdate(sessionId, update, payload)
break
case 'plan':
console.info('[ACP] Plan update received:', JSON.stringify(update))
this.handlePlanUpdate(update, payload)
break
case 'current_mode_update':
console.info('[ACP] Mode update received:', update)
this.handleModeUpdate(update, payload)
break
case 'available_commands_update':
console.info(
'[ACP] Available commands update:',
JSON.stringify(update.availableCommands?.map((c) => c.name) ?? [])
)
break
case 'user_message_chunk':
// ignore echo
break
default:
// Handle any unrecognized session update types
const sessionUpdate = (update as { sessionUpdate?: string }).sessionUpdate
console.warn('[ACP] Unhandled session update type:', sessionUpdate)
console.debug('[ACP] Full update data:', JSON.stringify(update))
break
}
return payload
}
private pushContent(
content:
| { type: 'text'; text: string }
| { type: 'image'; data: string; mimeType: string }
| { type: 'audio'; data: string; mimeType: string }
| { type: 'resource_link'; uri: string }
| { type: 'resource'; resource: unknown }
| undefined,
channel: 'text' | 'reasoning',
payload: MappedContent
) {
if (!content) return
switch (content.type) {
case 'text':
if (channel === 'text') {
payload.events.push(createStreamEvent.text(content.text))
payload.blocks.push(this.createBlock('content', content.text))
} else {
payload.events.push(createStreamEvent.reasoning(content.text))
payload.blocks.push(this.createBlock('reasoning_content', content.text))
}
break
case 'image':
payload.events.push(
createStreamEvent.imageData({ data: content.data, mimeType: content.mimeType })
)
payload.blocks.push(
this.createBlock('image', undefined, {
image_data: { data: content.data, mimeType: content.mimeType }
})
)
break
case 'audio':
this.emitAsText(`[audio ${content.mimeType}]`, channel, payload)
break
case 'resource_link':
this.emitAsText(content.uri, channel, payload)
break
case 'resource':
this.emitAsText(JSON.stringify(content.resource), channel, payload)
break
default:
this.emitAsText(JSON.stringify(content), channel, payload)
break
}
}
private emitAsText(text: string, channel: 'text' | 'reasoning', payload: MappedContent) {
if (channel === 'text') {
payload.events.push(createStreamEvent.text(text))
payload.blocks.push(this.createBlock('content', text))
} else {
payload.events.push(createStreamEvent.reasoning(text))
payload.blocks.push(this.createBlock('reasoning_content', text))
}
}
private handleToolCallUpdate(
sessionId: string,
update: Extract<
schema.SessionNotification['update'],
{ sessionUpdate: 'tool_call' | 'tool_call_update' }
>,
payload: MappedContent
) {
const toolCallId = update.toolCallId
if (!toolCallId) return
const rawTitle = 'title' in update ? (update.title ?? undefined) : undefined
const title = typeof rawTitle === 'string' ? rawTitle.trim() || undefined : undefined
const status = 'status' in update ? (update.status ?? undefined) : undefined
const state = this.getOrCreateToolCallState(sessionId, toolCallId, title)
if (title && state.toolName !== title) {
state.toolName = title
}
const previousStatus = state.status
if (status) {
state.status = status
}
this.emitToolCallStartIfNeeded(state, payload)
const shouldEmitReasoning =
update.sessionUpdate === 'tool_call' || (status && status !== previousStatus)
if (shouldEmitReasoning) {
const reasoningText = this.buildToolCallReasoning(state.toolName, status)
if (reasoningText) {
payload.events.push(createStreamEvent.reasoning(reasoningText))
payload.blocks.push(
this.createBlock('action', reasoningText, { action_type: 'tool_call_permission' })
)
}
}
const content = 'content' in update ? (update.content ?? undefined) : undefined
const chunk = this.formatToolCallContent(content, '')
if (chunk) {
this.emitToolCallChunk(state, chunk, payload)
}
if (status === 'completed' || status === 'failed') {
this.emitToolCallEnd(state, payload, status === 'failed')
}
}
private handlePlanUpdate(
update: Extract<schema.SessionNotification['update'], { sessionUpdate: 'plan' }>,
payload: MappedContent
) {
const entries = update.entries || []
if (!entries.length) return
// Store structured plan entries
payload.planEntries = entries.map((entry) => ({
content: entry.content,
priority: entry.priority ?? null,
status: entry.status ?? null
}))
// Create dedicated plan block
payload.events.push(createStreamEvent.reasoning('')) // Empty event for plan
payload.blocks.push(
this.createBlock('plan', '', {
extra: { plan_entries: payload.planEntries }
})
)
}
private handleModeUpdate(
update: Extract<schema.SessionNotification['update'], { sessionUpdate: 'current_mode_update' }>,
payload: MappedContent
) {
const modeId = update.currentModeId
if (!modeId) return
// Store mode change
payload.currentModeId = modeId
// Emit as reasoning for visibility
const text = `Mode changed to: ${modeId}`
payload.events.push(createStreamEvent.reasoning(text))
payload.blocks.push(
this.createBlock('reasoning_content', text, {
extra: { mode_change: modeId }
})
)
}
private formatToolCallContent(
contents?: schema.ToolCallContent[] | null,
joiner: string = '\n'
): string {
if (!contents?.length) {
return ''
}
return contents
.map((item) => {
if (item.type === 'content') {
const block = item.content
switch (block.type) {
case 'text':
return block.text
case 'image':
return '[image]'
case 'audio':
return '[audio]'
case 'resource':
return '[resource]'
case 'resource_link':
return block.uri
default:
return JSON.stringify(block)
}
}
if (item.type === 'terminal') {
return 'output' in item && typeof item.output === 'string'
? item.output
: `[terminal:${item.terminalId}]`
}
if (item.type === 'diff') {
return item.path ? `diff: ${item.path}` : '[diff]'
}
return JSON.stringify(item)
})
.filter(Boolean)
.join(joiner)
}
private tryParseJsonArguments(buffer: string, toolCallId: string): string | undefined {
const trimmed = buffer.trim()
if (!trimmed) {
return undefined
}
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
return trimmed
}
try {
JSON.parse(trimmed)
return trimmed
} catch (error) {
const preview = trimmed.length > 120 ? `${trimmed.slice(0, 120)}…` : trimmed
console.warn(
`[ACP] Tool call arguments appear incomplete (toolCallId=${toolCallId}): ${preview}`,
error
)
return trimmed
}
}
private buildToolCallReasoning(
title?: string,
status?: schema.ToolCallStatus | null
): string | null {
const statusText = status ? status.replace(/_/g, ' ') : undefined
const segments = ['Tool call', title, statusText].filter(Boolean)
return segments.length ? segments.join(' - ') : null
}
private emitToolCallStartIfNeeded(state: ToolCallState, payload: MappedContent) {
if (state.started) return
state.started = true
payload.events.push(createStreamEvent.toolCallStart(state.toolCallId, state.toolName))
}
private emitToolCallChunk(state: ToolCallState, chunk: string, payload: MappedContent) {
state.argumentsBuffer += chunk
payload.events.push(createStreamEvent.toolCallChunk(state.toolCallId, chunk))
payload.blocks.push(
this.createBlock('tool_call', state.argumentsBuffer, {
status: 'loading',
tool_call: {
id: state.toolCallId,
name: state.toolName,
params: state.argumentsBuffer
}
})
)
}
private emitToolCallEnd(state: ToolCallState, payload: MappedContent, isError: boolean) {
const toolCallId = state.toolCallId
const finalArgs = this.tryParseJsonArguments(state.argumentsBuffer, toolCallId)
payload.events.push(createStreamEvent.toolCallEnd(toolCallId, finalArgs))
payload.blocks.push(
this.createBlock('tool_call', finalArgs, {
status: isError ? 'error' : 'success',
tool_call: {
id: toolCallId,
name: state.toolName,
params: finalArgs
}
})
)
this.toolCallStates.delete(this.getToolCallStateKey(state.sessionId, toolCallId))
}
private getOrCreateToolCallState(
sessionId: string,
toolCallId: string,
toolName?: string
): ToolCallState {
const key = this.getToolCallStateKey(sessionId, toolCallId)
const existing = this.toolCallStates.get(key)
if (existing) {
if (toolName && existing.toolName !== toolName) {
existing.toolName = toolName
}
return existing
}
const state: ToolCallState = {
sessionId,
toolCallId,
toolName: toolName ?? toolCallId,
argumentsBuffer: '',
status: undefined,
started: false
}
this.toolCallStates.set(key, state)
return state
}
private getToolCallStateKey(sessionId: string, toolCallId: string): string {
return `${sessionId}:${toolCallId}`
}
private createBlock(
type: AssistantMessageBlock['type'],
content?: string,
extra?: Partial<AssistantMessageBlock>
): AssistantMessageBlock {
return {
type,
content,
status: 'success',
timestamp: now(),
...extra
} as AssistantMessageBlock
}
}