Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

translate.ts

418 lines11.7 KB

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
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
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
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 )
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' })
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
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 toolName: toolCallName,
201 model,
202 timestamp: now(),
203 }
204 yield {
205 type: EventType.TOOL_CALL_ARGS,
206 toolCallId: update.toolCallId,
207 model,
208 timestamp: now(),
209 delta: args,
210 args,
211 }
212 yield {
213 type: EventType.TOOL_CALL_END,
214 toolCallId: update.toolCallId,
215 toolCallName,
216 toolName: toolCallName,
217 model,
218 timestamp: now(),
219 input,
220 }
221 unresolvedToolCalls.add(update.toolCallId)
222 }
223​
224 function* resolveToolCall(
225 update: AcpToolCallUpdate,
226 ): Generator<AdapterYieldChunk> {
227 yield* openToolCall(update)
228 unresolvedToolCalls.delete(update.toolCallId)
229 yield {
230 type: EventType.TOOL_CALL_RESULT,
231 toolCallId: update.toolCallId,
232 messageId: genId(),
233 model,
234 timestamp: now(),
235 content: stringifyToolOutput(update),
236 ...(update.status === 'failed' && { state: 'output-error' as const }),
237 }
238 }
239​
240 function* handleUpdate(
241 update: AcpSessionUpdate,
242 ): Generator<AdapterYieldChunk> {
243 if (update.sessionUpdate === 'agent_message_chunk') {
244 yield* closeReasoning()
245 // Non-text content (image / audio / resource / resource_link): surface it
246 // as a CUSTOM event when the harness opted in, instead of dropping it.
247 if (update.content.type !== 'text') {
248 if (labels.contentEvent !== undefined) {
249 yield* closeText()
250 yield {
251 type: EventType.CUSTOM,
252 model,
253 timestamp: now(),
254 name: labels.contentEvent,
255 value: { content: update.content },
256 }
257 }
258 return
259 }
260 const text =
261 typeof update.content.text === 'string' ? update.content.text : ''
262 if (text === '') return
263 if (textMessageId === null) {
264 textMessageId = genId()
265 yield {
266 type: EventType.TEXT_MESSAGE_START,
267 messageId: textMessageId,
268 model,
269 timestamp: now(),
270 role: 'assistant',
271 }
272 }
273 textContent += text
274 yield {
275 type: EventType.TEXT_MESSAGE_CONTENT,
276 messageId: textMessageId,
277 model,
278 timestamp: now(),
279 delta: text,
280 content: textContent,
281 }
282 } else if (update.sessionUpdate === 'agent_thought_chunk') {
283 yield* closeText()
284 const thought =
285 typeof update.content.text === 'string' ? update.content.text : ''
286 if (thought === '') return
287 if (reasoningId === null) {
288 reasoningId = genId()
289 yield {
290 type: EventType.REASONING_START,
291 messageId: reasoningId,
292 model,
293 timestamp: now(),
294 }
295 yield {
296 type: EventType.REASONING_MESSAGE_START,
297 messageId: reasoningId,
298 role: 'reasoning' as const,
299 model,
300 timestamp: now(),
301 }
302 }
303 yield {
304 type: EventType.REASONING_MESSAGE_CONTENT,
305 messageId: reasoningId,
306 delta: thought,
307 model,
308 timestamp: now(),
309 }
310 } else if (update.sessionUpdate === 'tool_call') {
311 yield* closeText()
312 yield* closeReasoning()
313 yield* openToolCall(update)
314 if (update.status === 'completed' || update.status === 'failed') {
315 yield* resolveToolCall(update)
316 }
317 } else if (update.sessionUpdate === 'tool_call_update') {
318 if (update.status === 'completed' || update.status === 'failed') {
319 yield* resolveToolCall(update)
320 } else if (
321 update.status === 'in_progress' &&
322 update.rawInput !== undefined
323 ) {
324 yield* closeText()
325 yield* closeReasoning()
326 if (!knownToolCalls.has(update.toolCallId)) {
327 yield* openToolCall(update)
328 } else {
329 const input = {
330 ...(update.title != null && { title: update.title }),
331 ...(typeof update.rawInput === 'object' && update.rawInput !== null
332 ? (update.rawInput as Record<string, unknown>)
333 : { input: update.rawInput }),
334 }
335 const args = JSON.stringify(input)
336 yield {
337 type: EventType.TOOL_CALL_ARGS,
338 toolCallId: update.toolCallId,
339 model,
340 timestamp: now(),
341 delta: args,
342 args,
343 }
344 }
345 }
346 } else if (
347 update.sessionUpdate === 'plan' &&
348 labels.planEvent !== undefined
349 ) {
350 yield {
351 type: EventType.CUSTOM,
352 model,
353 timestamp: now(),
354 name: labels.planEvent,
355 value: { entries: update.entries },
356 }
357 }
358 }
359​
360 try {
361 for await (const event of events) {
362 ctx.onAcpEvent?.(event)
363​
364 if (event.kind === 'session') {
365 yield* startRun()
366 yield {
367 type: EventType.CUSTOM,
368 model,
369 timestamp: now(),
370 name: labels.sessionIdEvent,
371 value: { sessionId: event.sessionId },
372 }
373 } else if (event.kind === 'update') {
374 yield* startRun()
375 yield* handleUpdate(event.update)
376 } else {
377 yield* startRun()
378 yield* closeText()
379 yield* closeReasoning()
380 yield* synthesizeUnresolvedResults()
381​
382 if (event.stopReason === 'refusal') {
383 const message =
384 labels.refusalMessage ?? 'The harness refused the request.'
385 yield {
386 type: EventType.RUN_ERROR,
387 model,
388 timestamp: now(),
389 message,
390 code: 'refusal',
391 error: { message, code: 'refusal' },
392 }
393 } else {
394 const usage = buildUsage(event.usage)
395 const finishReason =
396 event.stopReason === 'max_tokens' ||
397 event.stopReason === 'max_turn_requests'
398 ? ('length' as const)
399 : ('stop' as const)
400 yield {
401 type: EventType.RUN_FINISHED,
402 runId,
403 threadId,
404 model,
405 timestamp: now(),
406 finishReason,
407 ...(usage !== undefined && { usage }),
408 }
409 }
410 }
411 }
412 } catch (error) {
413 yield* closeText()
414 yield* closeReasoning()
415 yield* synthesizeUnresolvedResults()
416 throw error
417 }