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