Open History to see the last commit
1import { EventType, buildBaseUsage } from '@tanstack/ai'
2import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
3import type {
4 AcpSessionUpdate,
5 AcpStopReason,
6 AcpToolCallUpdate,
7 AcpUsage,
8} from '../types/acp-types'
9
10export const BRIDGED_MCP_SERVER_NAME = 'tanstack'
11
12export type AcpStreamEvent =
13 | { kind: 'session'; sessionId: string }
14 | { kind: 'update'; update: AcpSessionUpdate }
15 | { kind: 'done'; stopReason: AcpStopReason; usage?: AcpUsage }
16
17export interface AcpTranslateLabels {
18 sessionIdEvent: string
19 planEvent?: string
20 refusalMessage?: string
21 /**
22 * When set, non-text agent message content (image / audio / resource /
23 * resource_link blocks) is surfaced as a CUSTOM event under this name instead
24 * of being dropped. Each event's `value` is `{ content: <ACP content block> }`.
25 * Omit to keep the text-only behavior.
26 */
27 contentEvent?: string
28}
29
30export interface TranslateContext {
31 model: string
32 runId: string
33 threadId: string
34 parentRunId?: string
35 genId: () => string
36 labels: AcpTranslateLabels
37 bridgedToolNames?: ReadonlySet<string>
38 onAcpEvent?: (event: AcpStreamEvent) => void
39}
40
41export function matchBridgedToolName(
42 title: string | null | undefined,
43 bridgedToolNames: ReadonlySet<string> | undefined,
44): string | undefined {
45 if (!title || !bridgedToolNames) return undefined
46 if (bridgedToolNames.has(title)) return title
47 for (const name of bridgedToolNames) {
48 if (title.startsWith(`${name} (`)) return name
49 }
50 return undefined
51}
52
53function resolveToolName(
54 update: AcpToolCallUpdate,
55 bridgedToolNames: ReadonlySet<string> | undefined,
56): string {
57 return (
58 matchBridgedToolName(update.title, bridgedToolNames) ??
59 update.kind ??
60 'tool'
61 )
62}
63
64function stringifyToolOutput(update: AcpToolCallUpdate): string {
65 if (update.rawOutput !== undefined) {
66 return typeof update.rawOutput === 'string'
67 ? update.rawOutput
68 : JSON.stringify(update.rawOutput)
69 }
70 const blocks = update.content ?? []
71 const text = blocks
72 .map((block) =>
73 block.content && typeof block.content.text === 'string'
74 ? block.content.text
75 : '',
76 )
77 .join('')
78 // Preserve non-text tool content (diff / terminal / image / resource blocks)
79 // by serializing the structured array, rather than collapsing to a stub.
80 const hasNonText = blocks.some(
81 (block) =>
82 block.type !== 'content' ||
83 (block.content !== undefined && block.content.type !== 'text'),
84 )
85 if (hasNonText) return JSON.stringify(blocks)
86 if (text !== '') return text
87 return JSON.stringify({ status: update.status ?? 'completed' })
88}
89
90function buildUsage(usage: AcpUsage | undefined): TokenUsage | undefined {
91 if (!usage) return undefined
92 const promptTokens = usage.inputTokens ?? 0
93 const completionTokens = usage.outputTokens ?? 0
94 const result = buildBaseUsage({
95 promptTokens,
96 completionTokens,
97 totalTokens: usage.totalTokens ?? promptTokens + completionTokens,
98 })
99 if (usage.cachedReadTokens) {
100 result.promptTokensDetails = { cachedTokens: usage.cachedReadTokens }
101 }
102 if (usage.thoughtTokens) {
103 result.completionTokensDetails = { reasoningTokens: usage.thoughtTokens }
104 }
105 return result
106}
107
108export async function* translateAcpStream(
109 events: AsyncIterable<AcpStreamEvent>,
110 ctx: TranslateContext,
111): AsyncIterable<AdapterYieldChunk> {
112 const { model, runId, threadId, genId, labels } = ctx
113 const now = () => Date.now()
114
115 let runStarted = false
116 const unresolvedToolCalls = new Set<string>()
117 const knownToolCalls = new Set<string>()
118
119 let textMessageId: string | null = null
120 let textContent = ''
121 let reasoningId: string | null = null
122
123 function* startRun(): Generator<AdapterYieldChunk> {
124 if (runStarted) return
125 runStarted = true
126 yield {
127 type: EventType.RUN_STARTED,
128 runId,
129 threadId,
130 model,
131 timestamp: now(),
132 ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),
133 }
134 }
135
136 function* closeText(): Generator<AdapterYieldChunk> {
137 if (textMessageId !== null) {
138 yield {
139 type: EventType.TEXT_MESSAGE_END,
140 messageId: textMessageId,
141 model,
142 timestamp: now(),
143 }
144 }
145 textMessageId = null
146 textContent = ''
147 }
148
149 function* closeReasoning(): Generator<AdapterYieldChunk> {
150 if (reasoningId !== null) {
151 yield {
152 type: EventType.REASONING_MESSAGE_END,
153 messageId: reasoningId,
154 model,
155 timestamp: now(),
156 }
157 yield {
158 type: EventType.REASONING_END,
159 messageId: reasoningId,
160 model,
161 timestamp: now(),
162 }
163 }
164 reasoningId = null
165 }
166
167 function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {
168 for (const toolCallId of unresolvedToolCalls) {
169 yield {
170 type: EventType.TOOL_CALL_RESULT,
171 toolCallId,
172 messageId: genId(),
173 model,
174 timestamp: now(),
175 content: JSON.stringify({ status: 'interrupted' }),
176 }
177 }
178 unresolvedToolCalls.clear()
179 }
180
181 function* openToolCall(
182 update: AcpToolCallUpdate,
183 ): Generator<AdapterYieldChunk> {
184 if (knownToolCalls.has(update.toolCallId)) return
185 knownToolCalls.add(update.toolCallId)
186 const toolCallName = resolveToolName(update, ctx.bridgedToolNames)
187 const input = {
188 ...(update.title != null && { title: update.title }),
189 ...(update.rawInput !== undefined && update.rawInput !== null
190 ? typeof update.rawInput === 'object'
191 ? (update.rawInput as Record<string, unknown>)
192 : { input: update.rawInput }
193 : {}),
194 }
195 const args = JSON.stringify(input)
196 yield {
197 type: EventType.TOOL_CALL_START,
198 toolCallId: update.toolCallId,
199 toolCallName,
200 model,
201 timestamp: now(),
202 }
203 yield {
204 type: EventType.TOOL_CALL_ARGS,
205 toolCallId: update.toolCallId,
206 model,
207 timestamp: now(),
208 delta: args,
209 args,
210 }
211 yield {
212 type: EventType.TOOL_CALL_END,
213 toolCallId: update.toolCallId,
214 toolCallName,
215 model,
216 timestamp: now(),
217 input,
218 }
219 unresolvedToolCalls.add(update.toolCallId)
220 }
221
222 function* resolveToolCall(
223 update: AcpToolCallUpdate,
224 ): Generator<AdapterYieldChunk> {
225 yield* openToolCall(update)
226 unresolvedToolCalls.delete(update.toolCallId)
227 yield {
228 type: EventType.TOOL_CALL_RESULT,
229 toolCallId: update.toolCallId,
230 messageId: genId(),
231 model,
232 timestamp: now(),
233 content: stringifyToolOutput(update),
234 ...(update.status === 'failed' && { state: 'output-error' as const }),
235 }
236 }
237
238 function* handleUpdate(
239 update: AcpSessionUpdate,
240 ): Generator<AdapterYieldChunk> {
241 if (update.sessionUpdate === 'agent_message_chunk') {
242 yield* closeReasoning()
243 // Non-text content (image / audio / resource / resource_link): surface it
244 // as a CUSTOM event when the harness opted in, instead of dropping it.
245 if (update.content.type !== 'text') {
246 if (labels.contentEvent !== undefined) {
247 yield* closeText()
248 yield {
249 type: EventType.CUSTOM,
250 model,
251 timestamp: now(),
252 name: labels.contentEvent,
253 value: { content: update.content },
254 }
255 }
256 return
257 }
258 const text =
259 typeof update.content.text === 'string' ? update.content.text : ''
260 if (text === '') return
261 if (textMessageId === null) {
262 textMessageId = genId()
263 yield {
264 type: EventType.TEXT_MESSAGE_START,
265 messageId: textMessageId,
266 model,
267 timestamp: now(),
268 role: 'assistant',
269 }
270 }
271 textContent += text
272 yield {
273 type: EventType.TEXT_MESSAGE_CONTENT,
274 messageId: textMessageId,
275 model,
276 timestamp: now(),
277 delta: text,
278 content: textContent,
279 }
280 } else if (update.sessionUpdate === 'agent_thought_chunk') {
281 yield* closeText()
282 const thought =
283 typeof update.content.text === 'string' ? update.content.text : ''
284 if (thought === '') return
285 if (reasoningId === null) {
286 reasoningId = genId()
287 yield {
288 type: EventType.REASONING_START,
289 messageId: reasoningId,
290 model,
291 timestamp: now(),
292 }
293 yield {
294 type: EventType.REASONING_MESSAGE_START,
295 messageId: reasoningId,
296 role: 'reasoning' as const,
297 model,
298 timestamp: now(),
299 }
300 }
301 yield {
302 type: EventType.REASONING_MESSAGE_CONTENT,
303 messageId: reasoningId,
304 delta: thought,
305 model,
306 timestamp: now(),
307 }
308 } else if (update.sessionUpdate === 'tool_call') {
309 yield* closeText()
310 yield* closeReasoning()
311 yield* openToolCall(update)
312 if (update.status === 'completed' || update.status === 'failed') {
313 yield* resolveToolCall(update)
314 }
315 } else if (update.sessionUpdate === 'tool_call_update') {
316 if (update.status === 'completed' || update.status === 'failed') {
317 yield* resolveToolCall(update)
318 } else if (
319 update.status === 'in_progress' &&
320 update.rawInput !== undefined
321 ) {
322 yield* closeText()
323 yield* closeReasoning()
324 if (!knownToolCalls.has(update.toolCallId)) {
325 yield* openToolCall(update)
326 } else {
327 const input = {
328 ...(update.title != null && { title: update.title }),
329 ...(typeof update.rawInput === 'object' && update.rawInput !== null
330 ? (update.rawInput as Record<string, unknown>)
331 : { input: update.rawInput }),
332 }
333 const args = JSON.stringify(input)
334 yield {
335 type: EventType.TOOL_CALL_ARGS,
336 toolCallId: update.toolCallId,
337 model,
338 timestamp: now(),
339 delta: args,
340 args,
341 }
342 }
343 }
344 } else if (
345 update.sessionUpdate === 'plan' &&
346 labels.planEvent !== undefined
347 ) {
348 yield {
349 type: EventType.CUSTOM,
350 model,
351 timestamp: now(),
352 name: labels.planEvent,
353 value: { entries: update.entries },
354 }
355 }
356 }
357
358 try {
359 for await (const event of events) {
360 ctx.onAcpEvent?.(event)
361
362 if (event.kind === 'session') {
363 yield* startRun()
364 yield {
365 type: EventType.CUSTOM,
366 model,
367 timestamp: now(),
368 name: labels.sessionIdEvent,
369 value: { sessionId: event.sessionId },
370 }
371 } else if (event.kind === 'update') {
372 yield* startRun()
373 yield* handleUpdate(event.update)
374 } else {
375 yield* startRun()
376 yield* closeText()
377 yield* closeReasoning()
378 yield* synthesizeUnresolvedResults()
379
380 if (event.stopReason === 'refusal') {
381 const message =
382 labels.refusalMessage ?? 'The harness refused the request.'
383 yield {
384 type: EventType.RUN_ERROR,
385 model,
386 timestamp: now(),
387 message,
388 code: 'refusal',
389 error: { message, code: 'refusal' },
390 }
391 } else {
392 const usage = buildUsage(event.usage)
393 const finishReason =
394 event.stopReason === 'max_tokens' ||
395 event.stopReason === 'max_turn_requests'
396 ? ('length' as const)
397 : ('stop' as const)
398 yield {
399 type: EventType.RUN_FINISHED,
400 runId,
401 threadId,
402 model,
403 timestamp: now(),
404 finishReason,
405 ...(usage !== undefined && { usage }),
406 }
407 }
408 }
409 }
410 } catch (error) {
411 yield* closeText()
412 yield* closeReasoning()
413 yield* synthesizeUnresolvedResults()
414 throw error
415 }
416}