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

translate.ts

699 lines21.4 KB

1import { EventType, buildBaseUsage } from '@tanstack/ai'
2import {
3 parseJsonFromAssistantText,
4 structuredOutputCompleteChunk,
5 structuredOutputStartChunk,
6} from '@tanstack/ai/adapter-internals'
7import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
8import type {
9 AgentSdkMessage,
10 SdkAssistantMessage,
11 SdkPartialAssistantMessage,
12 SdkResultMessage,
13 SdkToolResultContent,
14 SdkUsage,
15 SdkUserMessage,
16} from './sdk-types'
17​
18/** Name of the CUSTOM event carrying the Claude Code session id. */
19export const SESSION_ID_EVENT = 'claude-code.session-id'
20​
21/** Server name used for bridged TanStack tools (model sees `mcp__tanstack__<name>`). */
22export const BRIDGED_MCP_SERVER_NAME = 'tanstack'
23​
24const BRIDGED_MCP_PREFIX = `mcp__${BRIDGED_MCP_SERVER_NAME}__`
25​
26/**
27 * Claude Code `--json-schema` injects a fake tool named StructuredOutput.
28 * The model "calls" it with the schema JSON. The result message may omit
29 * `structured_output`; harvest the tool input in that case.
30 */
31export const SYNTHETIC_STRUCTURED_OUTPUT_TOOL = 'StructuredOutput'
32​
33/** Claude Code-specific usage details attached to RUN_FINISHED usage. */
34export type ClaudeCodeProviderUsageDetails = {
35 /** Total cost of the harness run in USD, as reported by Claude Code. */
36 totalCostUsd?: number
38​
39export interface TranslateContext {
40 model: string
41 runId: string
42 threadId: string
43 parentRunId?: string
44 genId: () => string
45 /** Called as soon as the harness reports its session id. */
46 onSessionId?: (sessionId: string) => void
47 /** Called for each raw SDK message, for logging. */
48 onSdkMessage?: (message: AgentSdkMessage) => void
49 /** Emit structured-output events from `result.structured_output`. */
50 expectStructuredOutput?: boolean
52​
53/**
54 * Strip the bridged MCP server prefix so tool-call events match the TanStack
55 * tool names the application registered. Built-in harness tools (Bash, Read,
56 * Edit, ...) and foreign MCP tools pass through verbatim.
57 */
58export function stripMcpPrefix(name: string): string {
59 return name.startsWith(BRIDGED_MCP_PREFIX)
60 ? name.slice(BRIDGED_MCP_PREFIX.length)
61 : name
63​
64function isUsefulStructuredObject(value: unknown): boolean {
65 return (
66 value !== null &&
67 typeof value === 'object' &&
68 !Array.isArray(value) &&
69 Object.keys(value).length > 0
70 )
72​
73function rememberStructuredOutput(current: unknown, next: unknown): unknown {
74 return isUsefulStructuredObject(next) ? next : current
76​
77function stringifyToolResultContent(
78 content: SdkToolResultContent | undefined,
79): string {
80 if (content === undefined) return ''
81 if (typeof content === 'string') return content
82 return content
83 .map((block) => (typeof block.text === 'string' ? block.text : ''))
84 .join('')
86​
87function buildUsage(
88 usage: SdkUsage | undefined,
89 totalCostUsd: number | undefined,
90): TokenUsage<ClaudeCodeProviderUsageDetails> | undefined {
91 if (!usage) return undefined
92 const cacheWrite = usage.cache_creation_input_tokens ?? 0
93 const cacheRead = usage.cache_read_input_tokens ?? 0
94 // `input_tokens` counts only the uncached input. Add the cache reads and
95 // writes so promptTokens is the total input, the same as other providers.
96 const promptTokens = (usage.input_tokens ?? 0) + cacheRead + cacheWrite
97 const completionTokens = usage.output_tokens ?? 0
98 const result = buildBaseUsage<ClaudeCodeProviderUsageDetails>({
99 promptTokens,
100 completionTokens,
101 totalTokens: promptTokens + completionTokens,
102 })
103 const promptTokensDetails = {
104 ...(cacheWrite ? { cacheWriteTokens: cacheWrite } : {}),
105 ...(cacheRead ? { cachedTokens: cacheRead } : {}),
106 }
107 if (Object.keys(promptTokensDetails).length > 0) {
108 result.promptTokensDetails = promptTokensDetails
109 }
110 if (totalCostUsd !== undefined) {
111 result.providerUsageDetails = { totalCostUsd }
112 }
113 return result
115​
116/**
117 * Translate a Claude Code Agent SDK message stream into AG-UI StreamChunk
118 * events.
119 *
120 * The harness runs its own agent loop and executes its own tools, so the
121 * translation always ends with `finishReason: 'stop'` (or `'length'` /
122 * RUN_ERROR) — never `'tool_calls'`. Harness tool activity is emitted as
123 * already-resolved TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so
124 * UIs can render it, while the TanStack engine never tries to execute them.
125 *
126 * Invariant: every TOOL_CALL_START is eventually paired with a
127 * TOOL_CALL_RESULT (synthesized as `{"status":"interrupted"}` when the run
128 * ends or aborts before the harness reported one) so the engine's
129 * pending-tool-call scan on the next request never force-executes them.
130 */
131export async function* translateSdkStream(
132 sdkMessages: AsyncIterable<AgentSdkMessage>,
133 ctx: TranslateContext,
134): AsyncIterable<AdapterYieldChunk> {
135 const { model, runId, threadId, genId } = ctx
136 const now = () => Date.now()
137​
138 let runStarted = false
139 /** Tool calls started but with no result yet. */
140 const unresolvedToolCalls = new Set<string>()
141 const syntheticOutputToolIds = new Set<string>()
142 let capturedStructuredOutput: unknown
143 let assistantTextForHarvest = ''
144 let partialStructuredJson = ''
145 let partialIsStructuredOutput = false
146 /** Anthropic message ids whose text/thinking already streamed via partials. */
147 const streamedMessageIds = new Set<string>()
148 /** Tool-call ids already streamed via partials, so the complete message dedupes them. */
149 const streamedToolCallIds = new Set<string>()
150​
151 // Partial-stream state
152 let partialMessageId: string | null = null
153 const partialBlockTypes = new Map<number, string>()
154 let partialTextMessageId: string | null = null
155 let partialTextContent = ''
156 let partialTextStarted = false
157 let partialReasoningId: string | null = null
158 const partialToolCalls = new Map<
159 number,
160 { id: string; name: string; args: string }
161 >()
162​
163 function* startRun(): Generator<AdapterYieldChunk> {
164 if (runStarted) return
165 runStarted = true
166 yield {
167 type: EventType.RUN_STARTED,
168 runId,
169 threadId,
170 model,
171 timestamp: now(),
172 ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),
173 }
174 }
175​
176 function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {
177 for (const toolCallId of unresolvedToolCalls) {
178 yield {
179 type: EventType.TOOL_CALL_RESULT,
180 toolCallId,
181 messageId: genId(),
182 model,
183 timestamp: now(),
184 content: JSON.stringify({ status: 'interrupted' }),
185 }
186 }
187 unresolvedToolCalls.clear()
188 }
189​
190 function* closePartialText(): Generator<AdapterYieldChunk> {
191 if (partialTextStarted && partialTextMessageId) {
192 yield {
193 type: EventType.TEXT_MESSAGE_END,
194 messageId: partialTextMessageId,
195 model,
196 timestamp: now(),
197 }
198 }
199 partialTextStarted = false
200 partialTextMessageId = null
201 partialTextContent = ''
202 }
203​
204 function* closePartialReasoning(): Generator<AdapterYieldChunk> {
205 if (partialReasoningId) {
206 yield {
207 type: EventType.REASONING_MESSAGE_END,
208 messageId: partialReasoningId,
209 model,
210 timestamp: now(),
211 }
212 yield {
213 type: EventType.REASONING_END,
214 messageId: partialReasoningId,
215 model,
216 timestamp: now(),
217 }
218 }
219 partialReasoningId = null
220 }
221​
222 function* closePartialToolUse(
223 index: number,
224 interrupted = false,
225 ): Generator<AdapterYieldChunk> {
226 const toolCall = partialToolCalls.get(index)
227 if (toolCall) {
228 let input: unknown = {}
229 try {
230 const parsed = toolCall.args ? JSON.parse(toolCall.args) : {}
231 input = parsed && typeof parsed === 'object' ? parsed : {}
232 } catch (error) {
233 if (!interrupted) throw error
234 }
235 partialToolCalls.delete(index)
236 yield {
237 type: EventType.TOOL_CALL_END,
238 toolCallId: toolCall.id,
239 toolCallName: toolCall.name,
240 toolName: toolCall.name,
241 model,
242 timestamp: now(),
243 input,
244 }
245 unresolvedToolCalls.add(toolCall.id)
246 }
247 }
248​
249 function* closePartialToolUses(
250 interrupted = false,
251 ): Generator<AdapterYieldChunk> {
252 for (const index of [...partialToolCalls.keys()]) {
253 yield* closePartialToolUse(index, interrupted)
254 }
255 }
256​
257 function* emitStructuredOutput(
258 object: unknown,
259 ): Generator<AdapterYieldChunk> {
260 const raw = JSON.stringify(object)
261 const messageId = genId()
262 yield structuredOutputStartChunk({
263 messageId,
264 model,
265 threadId,
266 runId,
267 })
268 yield structuredOutputCompleteChunk({
269 messageId,
270 model,
271 threadId,
272 runId,
273 object,
274 raw,
275 })
276 }
277​
278 function* emitToolUse(block: {
279 id: string
280 name: string
281 input: unknown
282 }): Generator<AdapterYieldChunk> {
283 const toolCallName = stripMcpPrefix(block.name)
284 if (
285 ctx.expectStructuredOutput === true &&
286 toolCallName === SYNTHETIC_STRUCTURED_OUTPUT_TOOL
287 ) {
288 capturedStructuredOutput = rememberStructuredOutput(
289 capturedStructuredOutput,
290 block.input,
291 )
292 syntheticOutputToolIds.add(block.id)
293 return
294 }
295 const args = JSON.stringify(block.input ?? {})
296 yield {
297 type: EventType.TOOL_CALL_START,
298 toolCallId: block.id,
299 toolCallName,
300 toolName: toolCallName,
301 model,
302 timestamp: now(),
303 }
304 yield {
305 type: EventType.TOOL_CALL_ARGS,
306 toolCallId: block.id,
307 model,
308 timestamp: now(),
309 delta: args,
310 args,
311 }
312 yield {
313 type: EventType.TOOL_CALL_END,
314 toolCallId: block.id,
315 toolCallName,
316 toolName: toolCallName,
317 model,
318 timestamp: now(),
319 input: block.input ?? {},
320 }
321 unresolvedToolCalls.add(block.id)
322 }
323​
324 function* handleAssistant(
325 message: SdkAssistantMessage,
326 ): Generator<AdapterYieldChunk> {
327 const alreadyStreamed =
328 message.message.id !== undefined &&
329 streamedMessageIds.has(message.message.id)
330​
331 for (const block of message.message.content) {
332 if (block.type === 'text') {
333 if (alreadyStreamed) continue
334 const messageId = message.message.id ?? genId()
335 const text = (block as { text: string }).text
336 if (!alreadyStreamed) assistantTextForHarvest += text
337 yield {
338 type: EventType.TEXT_MESSAGE_START,
339 messageId,
340 model,
341 timestamp: now(),
342 role: 'assistant',
343 }
344 yield {
345 type: EventType.TEXT_MESSAGE_CONTENT,
346 messageId,
347 model,
348 timestamp: now(),
349 delta: text,
350 content: text,
351 }
352 yield {
353 type: EventType.TEXT_MESSAGE_END,
354 messageId,
355 model,
356 timestamp: now(),
357 }
358 } else if (block.type === 'thinking') {
359 if (alreadyStreamed) continue
360 const reasoningId = genId()
361 const thinking = (block as { thinking: string }).thinking
362 yield {
363 type: EventType.REASONING_START,
364 messageId: reasoningId,
365 model,
366 timestamp: now(),
367 }
368 yield {
369 type: EventType.REASONING_MESSAGE_START,
370 messageId: reasoningId,
371 role: 'reasoning' as const,
372 model,
373 timestamp: now(),
374 }
375 yield {
376 type: EventType.REASONING_MESSAGE_CONTENT,
377 messageId: reasoningId,
378 delta: thinking,
379 model,
380 timestamp: now(),
381 }
382 yield {
383 type: EventType.REASONING_MESSAGE_END,
384 messageId: reasoningId,
385 model,
386 timestamp: now(),
387 }
388 yield {
389 type: EventType.REASONING_END,
390 messageId: reasoningId,
391 model,
392 timestamp: now(),
393 }
394 } else if (block.type === 'tool_use') {
395 const toolBlock = block as { id: string; name: string; input: unknown }
396 // Skip the tool call if the partial stream already emitted it.
397 if (streamedToolCallIds.has(toolBlock.id)) continue
398 yield* emitToolUse(toolBlock)
399 }
400 }
401 }
402​
403 function* handleUser(message: SdkUserMessage): Generator<AdapterYieldChunk> {
404 const content = message.message.content
405 if (typeof content === 'string') return
406 for (const block of content) {
407 if (block.type !== 'tool_result') continue
408 const toolResult = block as {
409 tool_use_id: string
410 content?: SdkToolResultContent
411 is_error?: boolean
412 }
413 if (syntheticOutputToolIds.has(toolResult.tool_use_id)) {
414 syntheticOutputToolIds.delete(toolResult.tool_use_id)
415 continue
416 }
417 unresolvedToolCalls.delete(toolResult.tool_use_id)
418 yield {
419 type: EventType.TOOL_CALL_RESULT,
420 toolCallId: toolResult.tool_use_id,
421 messageId: genId(),
422 model,
423 timestamp: now(),
424 content: stringifyToolResultContent(toolResult.content),
425 ...(toolResult.is_error === true && { state: 'output-error' as const }),
426 }
427 }
428 }
429​
430 function* handleResult(
431 message: SdkResultMessage,
432 ): Generator<AdapterYieldChunk> {
433 yield* closePartialText()
434 yield* closePartialReasoning()
435 yield* closePartialToolUses()
436 yield* synthesizeUnresolvedResults()
437​
438 const usage = buildUsage(message.usage, message.total_cost_usd)
439 if (ctx.expectStructuredOutput === true) {
440 const fromResult = isUsefulStructuredObject(message.structured_output)
441 ? message.structured_output
442 : undefined
443 const fromTool = isUsefulStructuredObject(capturedStructuredOutput)
444 ? capturedStructuredOutput
445 : undefined
446 let fromText: unknown
447 if (fromResult === undefined && fromTool === undefined) {
448 const raw = assistantTextForHarvest || message.result || ''
449 if (raw.trim() !== '') {
450 try {
451 fromText = parseJsonFromAssistantText(raw)
452 } catch {
453 fromText = undefined
454 }
455 }
456 }
457 const object = fromResult ?? fromTool ?? fromText
458 if (isUsefulStructuredObject(object)) {
459 yield* emitStructuredOutput(object)
460 }
461 }
462 if (message.subtype === 'success') {
463 yield {
464 type: EventType.RUN_FINISHED,
465 runId,
466 threadId,
467 model,
468 timestamp: now(),
469 finishReason: 'stop',
470 ...(usage !== undefined && { usage }),
471 }
472 } else if (message.subtype === 'error_max_turns') {
473 yield {
474 type: EventType.RUN_FINISHED,
475 runId,
476 threadId,
477 model,
478 timestamp: now(),
479 finishReason: 'length',
480 ...(usage !== undefined && { usage }),
481 }
482 } else {
483 const errorMessage =
484 message.errors && message.errors.length > 0
485 ? message.errors.join('; ')
486 : `Claude Code run failed: ${message.subtype}`
487 yield {
488 type: EventType.RUN_ERROR,
489 model,
490 timestamp: now(),
491 message: errorMessage,
492 code: message.subtype,
493 error: { message: errorMessage, code: message.subtype },
494 }
495 }
496 }
497​
498 function* handleStreamEvent(
499 message: SdkPartialAssistantMessage,
500 ): Generator<AdapterYieldChunk> {
501 const event = message.event
502 if (event.type === 'message_start') {
503 partialMessageId = event.message.id ?? genId()
504 streamedMessageIds.add(partialMessageId)
505 } else if (event.type === 'content_block_start') {
506 const block = event.content_block
507 const partialBlockType = block.type
508 partialBlockTypes.set(event.index, partialBlockType)
509 partialIsStructuredOutput =
510 ctx.expectStructuredOutput === true &&
511 block.type === 'tool_use' &&
512 block.name === SYNTHETIC_STRUCTURED_OUTPUT_TOOL
513 if (partialIsStructuredOutput) {
514 partialStructuredJson = ''
515 if (typeof block.id === 'string') {
516 syntheticOutputToolIds.add(block.id)
517 }
518 if ('input' in block) {
519 capturedStructuredOutput = rememberStructuredOutput(
520 capturedStructuredOutput,
521 block.input,
522 )
523 }
524 }
525 if (partialBlockType === 'text') {
526 partialTextMessageId = partialMessageId ?? genId()
527 partialTextContent = ''
528 if (!partialTextStarted) {
529 partialTextStarted = true
530 yield {
531 type: EventType.TEXT_MESSAGE_START,
532 messageId: partialTextMessageId,
533 model,
534 timestamp: now(),
535 role: 'assistant',
536 }
537 }
538 } else if (partialBlockType === 'thinking') {
539 partialReasoningId = genId()
540 yield {
541 type: EventType.REASONING_START,
542 messageId: partialReasoningId,
543 model,
544 timestamp: now(),
545 }
546 yield {
547 type: EventType.REASONING_MESSAGE_START,
548 messageId: partialReasoningId,
549 role: 'reasoning' as const,
550 model,
551 timestamp: now(),
552 }
553 } else if (
554 partialBlockType === 'tool_use' &&
555 !partialIsStructuredOutput &&
556 typeof block.id === 'string' &&
557 typeof block.name === 'string'
558 ) {
559 const name = stripMcpPrefix(block.name)
560 partialToolCalls.set(event.index, { id: block.id, name, args: '' })
561 streamedToolCallIds.add(block.id)
562 yield {
563 type: EventType.TOOL_CALL_START,
564 toolCallId: block.id,
565 toolCallName: name,
566 toolName: name,
567 model,
568 timestamp: now(),
569 ...(partialMessageId !== null && {
570 parentMessageId: partialMessageId,
571 }),
572 }
573 }
574 } else if (event.type === 'content_block_delta') {
575 if (
576 event.delta.type === 'text_delta' &&
577 partialTextStarted &&
578 partialTextMessageId &&
579 typeof event.delta.text === 'string'
580 ) {
581 partialTextContent += event.delta.text
582 assistantTextForHarvest += event.delta.text
583 yield {
584 type: EventType.TEXT_MESSAGE_CONTENT,
585 messageId: partialTextMessageId,
586 model,
587 timestamp: now(),
588 delta: event.delta.text,
589 content: partialTextContent,
590 }
591 } else if (
592 event.delta.type === 'input_json_delta' &&
593 partialIsStructuredOutput &&
594 typeof event.delta.partial_json === 'string'
595 ) {
596 partialStructuredJson += event.delta.partial_json
597 } else if (
598 event.delta.type === 'thinking_delta' &&
599 partialReasoningId &&
600 typeof event.delta.thinking === 'string'
601 ) {
602 yield {
603 type: EventType.REASONING_MESSAGE_CONTENT,
604 messageId: partialReasoningId,
605 delta: event.delta.thinking,
606 model,
607 timestamp: now(),
608 }
609 } else if (
610 event.delta.type === 'input_json_delta' &&
611 typeof event.delta.partial_json === 'string'
612 ) {
613 const toolCall = partialToolCalls.get(event.index)
614 if (toolCall) {
615 toolCall.args += event.delta.partial_json
616 yield {
617 type: EventType.TOOL_CALL_ARGS,
618 toolCallId: toolCall.id,
619 model,
620 timestamp: now(),
621 delta: event.delta.partial_json,
622 }
623 }
624 }
625 } else if (event.type === 'content_block_stop') {
626 const partialBlockType = partialBlockTypes.get(event.index)
627 partialBlockTypes.delete(event.index)
628 if (partialIsStructuredOutput && partialStructuredJson !== '') {
629 try {
630 capturedStructuredOutput = rememberStructuredOutput(
631 capturedStructuredOutput,
632 JSON.parse(partialStructuredJson),
633 )
634 } catch {
635 // Incomplete JSON; the complete assistant tool_use may still arrive.
636 }
637 }
638 if (partialBlockType === 'text') {
639 yield* closePartialText()
640 } else if (partialBlockType === 'thinking') {
641 yield* closePartialReasoning()
642 } else if (partialBlockType === 'tool_use') {
643 yield* closePartialToolUse(event.index)
644 }
645 partialIsStructuredOutput = false
646 partialStructuredJson = ''
647 }
648 }
649​
650 try {
651 for await (const sdkMessage of sdkMessages) {
652 ctx.onSdkMessage?.(sdkMessage)
653​
654 if (sdkMessage.type === 'system' && sdkMessage.subtype === 'init') {
655 yield* startRun()
656 ctx.onSessionId?.(sdkMessage.session_id)
657 yield {
658 type: EventType.CUSTOM,
659 model,
660 timestamp: now(),
661 name: SESSION_ID_EVENT,
662 value: {
663 sessionId: sdkMessage.session_id,
664 model: sdkMessage.model,
665 tools: sdkMessage.tools,
666 skills: sdkMessage.skills ?? [],
667 },
668 }
669 continue
670 }
671​
672 // Anything before init still needs RUN_STARTED first.
673 yield* startRun()
674​
675 if (sdkMessage.type === 'stream_event') {
676 if (sdkMessage.parent_tool_use_id !== null) continue
677 yield* handleStreamEvent(sdkMessage)
678 } else if (sdkMessage.type === 'assistant') {
679 if (sdkMessage.parent_tool_use_id !== null) continue
680 yield* handleAssistant(sdkMessage)
681 } else if (sdkMessage.type === 'user') {
682 if (sdkMessage.parent_tool_use_id !== null) continue
683 yield* handleUser(sdkMessage)
684 } else if (sdkMessage.type === 'result') {
685 yield* handleResult(sdkMessage)
686 }
687 // All other SDK message types (status, hooks, notifications, ...) are
688 // harness-internal and intentionally ignored.
689 }
690 } catch (error) {
691 // The run is dying (abort or SDK failure). Close any half-streamed tool
692 // calls, then pair every started tool call with a synthetic result so the
693 // next request's pending-tool-call scan doesn't try to execute them. Then
694 // let the adapter surface the error as RUN_ERROR.
695 yield* closePartialToolUses(true)
696 yield* synthesizeUnresolvedResults()
697 throw error
698 }