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 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
114}
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 model,
241 timestamp: now(),
242 input,
243 }
244 unresolvedToolCalls.add(toolCall.id)
245 }
246 }
247
248 function* closePartialToolUses(
249 interrupted = false,
250 ): Generator<AdapterYieldChunk> {
251 for (const index of [...partialToolCalls.keys()]) {
252 yield* closePartialToolUse(index, interrupted)
253 }
254 }
255
256 function* emitStructuredOutput(
257 object: unknown,
258 ): Generator<AdapterYieldChunk> {
259 const raw = JSON.stringify(object)
260 const messageId = genId()
261 yield structuredOutputStartChunk({
262 messageId,
263 model,
264 threadId,
265 runId,
266 })
267 yield structuredOutputCompleteChunk({
268 messageId,
269 model,
270 threadId,
271 runId,
272 object,
273 raw,
274 })
275 }
276
277 function* emitToolUse(block: {
278 id: string
279 name: string
280 input: unknown
281 }): Generator<AdapterYieldChunk> {
282 const toolCallName = stripMcpPrefix(block.name)
283 if (
284 ctx.expectStructuredOutput === true &&
285 toolCallName === SYNTHETIC_STRUCTURED_OUTPUT_TOOL
286 ) {
287 capturedStructuredOutput = rememberStructuredOutput(
288 capturedStructuredOutput,
289 block.input,
290 )
291 syntheticOutputToolIds.add(block.id)
292 return
293 }
294 const args = JSON.stringify(block.input ?? {})
295 yield {
296 type: EventType.TOOL_CALL_START,
297 toolCallId: block.id,
298 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 model,
315 timestamp: now(),
316 input: block.input ?? {},
317 }
318 unresolvedToolCalls.add(block.id)
319 }
320
321 function* handleAssistant(
322 message: SdkAssistantMessage,
323 ): Generator<AdapterYieldChunk> {
324 const alreadyStreamed =
325 message.message.id !== undefined &&
326 streamedMessageIds.has(message.message.id)
327
328 for (const block of message.message.content) {
329 if (block.type === 'text') {
330 if (alreadyStreamed) continue
331 const messageId = message.message.id ?? genId()
332 const text = (block as { text: string }).text
333 if (!alreadyStreamed) assistantTextForHarvest += text
334 yield {
335 type: EventType.TEXT_MESSAGE_START,
336 messageId,
337 model,
338 timestamp: now(),
339 role: 'assistant',
340 }
341 yield {
342 type: EventType.TEXT_MESSAGE_CONTENT,
343 messageId,
344 model,
345 timestamp: now(),
346 delta: text,
347 content: text,
348 }
349 yield {
350 type: EventType.TEXT_MESSAGE_END,
351 messageId,
352 model,
353 timestamp: now(),
354 }
355 } else if (block.type === 'thinking') {
356 if (alreadyStreamed) continue
357 const reasoningId = genId()
358 const thinking = (block as { thinking: string }).thinking
359 yield {
360 type: EventType.REASONING_START,
361 messageId: reasoningId,
362 model,
363 timestamp: now(),
364 }
365 yield {
366 type: EventType.REASONING_MESSAGE_START,
367 messageId: reasoningId,
368 role: 'reasoning' as const,
369 model,
370 timestamp: now(),
371 }
372 yield {
373 type: EventType.REASONING_MESSAGE_CONTENT,
374 messageId: reasoningId,
375 delta: thinking,
376 model,
377 timestamp: now(),
378 }
379 yield {
380 type: EventType.REASONING_MESSAGE_END,
381 messageId: reasoningId,
382 model,
383 timestamp: now(),
384 }
385 yield {
386 type: EventType.REASONING_END,
387 messageId: reasoningId,
388 model,
389 timestamp: now(),
390 }
391 } else if (block.type === 'tool_use') {
392 const toolBlock = block as { id: string; name: string; input: unknown }
393 // Skip the tool call if the partial stream already emitted it.
394 if (streamedToolCallIds.has(toolBlock.id)) continue
395 yield* emitToolUse(toolBlock)
396 }
397 }
398 }
399
400 function* handleUser(message: SdkUserMessage): Generator<AdapterYieldChunk> {
401 const content = message.message.content
402 if (typeof content === 'string') return
403 for (const block of content) {
404 if (block.type !== 'tool_result') continue
405 const toolResult = block as {
406 tool_use_id: string
407 content?: SdkToolResultContent
408 is_error?: boolean
409 }
410 if (syntheticOutputToolIds.has(toolResult.tool_use_id)) {
411 syntheticOutputToolIds.delete(toolResult.tool_use_id)
412 continue
413 }
414 unresolvedToolCalls.delete(toolResult.tool_use_id)
415 yield {
416 type: EventType.TOOL_CALL_RESULT,
417 toolCallId: toolResult.tool_use_id,
418 messageId: genId(),
419 model,
420 timestamp: now(),
421 content: stringifyToolResultContent(toolResult.content),
422 ...(toolResult.is_error === true && { state: 'output-error' as const }),
423 }
424 }
425 }
426
427 function* handleResult(
428 message: SdkResultMessage,
429 ): Generator<AdapterYieldChunk> {
430 yield* closePartialText()
431 yield* closePartialReasoning()
432 yield* closePartialToolUses()
433 yield* synthesizeUnresolvedResults()
434
435 const usage = buildUsage(message.usage, message.total_cost_usd)
436 if (ctx.expectStructuredOutput === true) {
437 const fromResult = isUsefulStructuredObject(message.structured_output)
438 ? message.structured_output
439 : undefined
440 const fromTool = isUsefulStructuredObject(capturedStructuredOutput)
441 ? capturedStructuredOutput
442 : undefined
443 let fromText: unknown
444 if (fromResult === undefined && fromTool === undefined) {
445 const raw = assistantTextForHarvest || message.result || ''
446 if (raw.trim() !== '') {
447 try {
448 fromText = parseJsonFromAssistantText(raw)
449 } catch {
450 fromText = undefined
451 }
452 }
453 }
454 const object = fromResult ?? fromTool ?? fromText
455 if (isUsefulStructuredObject(object)) {
456 yield* emitStructuredOutput(object)
457 }
458 }
459 if (message.subtype === 'success') {
460 yield {
461 type: EventType.RUN_FINISHED,
462 runId,
463 threadId,
464 model,
465 timestamp: now(),
466 finishReason: 'stop',
467 ...(usage !== undefined && { usage }),
468 }
469 } else if (message.subtype === 'error_max_turns') {
470 yield {
471 type: EventType.RUN_FINISHED,
472 runId,
473 threadId,
474 model,
475 timestamp: now(),
476 finishReason: 'length',
477 ...(usage !== undefined && { usage }),
478 }
479 } else {
480 const errorMessage =
481 message.errors && message.errors.length > 0
482 ? message.errors.join('; ')
483 : `Claude Code run failed: ${message.subtype}`
484 yield {
485 type: EventType.RUN_ERROR,
486 model,
487 timestamp: now(),
488 message: errorMessage,
489 code: message.subtype,
490 error: { message: errorMessage, code: message.subtype },
491 }
492 }
493 }
494
495 function* handleStreamEvent(
496 message: SdkPartialAssistantMessage,
497 ): Generator<AdapterYieldChunk> {
498 const event = message.event
499 if (event.type === 'message_start') {
500 partialMessageId = event.message.id ?? genId()
501 streamedMessageIds.add(partialMessageId)
502 } else if (event.type === 'content_block_start') {
503 const block = event.content_block
504 const partialBlockType = block.type
505 partialBlockTypes.set(event.index, partialBlockType)
506 partialIsStructuredOutput =
507 ctx.expectStructuredOutput === true &&
508 block.type === 'tool_use' &&
509 block.name === SYNTHETIC_STRUCTURED_OUTPUT_TOOL
510 if (partialIsStructuredOutput) {
511 partialStructuredJson = ''
512 if (typeof block.id === 'string') {
513 syntheticOutputToolIds.add(block.id)
514 }
515 if ('input' in block) {
516 capturedStructuredOutput = rememberStructuredOutput(
517 capturedStructuredOutput,
518 block.input,
519 )
520 }
521 }
522 if (partialBlockType === 'text') {
523 partialTextMessageId = partialMessageId ?? genId()
524 partialTextContent = ''
525 if (!partialTextStarted) {
526 partialTextStarted = true
527 yield {
528 type: EventType.TEXT_MESSAGE_START,
529 messageId: partialTextMessageId,
530 model,
531 timestamp: now(),
532 role: 'assistant',
533 }
534 }
535 } else if (partialBlockType === 'thinking') {
536 partialReasoningId = genId()
537 yield {
538 type: EventType.REASONING_START,
539 messageId: partialReasoningId,
540 model,
541 timestamp: now(),
542 }
543 yield {
544 type: EventType.REASONING_MESSAGE_START,
545 messageId: partialReasoningId,
546 role: 'reasoning' as const,
547 model,
548 timestamp: now(),
549 }
550 } else if (
551 partialBlockType === 'tool_use' &&
552 !partialIsStructuredOutput &&
553 typeof block.id === 'string' &&
554 typeof block.name === 'string'
555 ) {
556 const name = stripMcpPrefix(block.name)
557 partialToolCalls.set(event.index, { id: block.id, name, args: '' })
558 streamedToolCallIds.add(block.id)
559 yield {
560 type: EventType.TOOL_CALL_START,
561 toolCallId: block.id,
562 toolCallName: name,
563 model,
564 timestamp: now(),
565 ...(partialMessageId !== null && {
566 parentMessageId: partialMessageId,
567 }),
568 }
569 }
570 } else if (event.type === 'content_block_delta') {
571 if (
572 event.delta.type === 'text_delta' &&
573 partialTextStarted &&
574 partialTextMessageId &&
575 typeof event.delta.text === 'string'
576 ) {
577 partialTextContent += event.delta.text
578 assistantTextForHarvest += event.delta.text
579 yield {
580 type: EventType.TEXT_MESSAGE_CONTENT,
581 messageId: partialTextMessageId,
582 model,
583 timestamp: now(),
584 delta: event.delta.text,
585 content: partialTextContent,
586 }
587 } else if (
588 event.delta.type === 'input_json_delta' &&
589 partialIsStructuredOutput &&
590 typeof event.delta.partial_json === 'string'
591 ) {
592 partialStructuredJson += event.delta.partial_json
593 } else if (
594 event.delta.type === 'thinking_delta' &&
595 partialReasoningId &&
596 typeof event.delta.thinking === 'string'
597 ) {
598 yield {
599 type: EventType.REASONING_MESSAGE_CONTENT,
600 messageId: partialReasoningId,
601 delta: event.delta.thinking,
602 model,
603 timestamp: now(),
604 }
605 } else if (
606 event.delta.type === 'input_json_delta' &&
607 typeof event.delta.partial_json === 'string'
608 ) {
609 const toolCall = partialToolCalls.get(event.index)
610 if (toolCall) {
611 toolCall.args += event.delta.partial_json
612 yield {
613 type: EventType.TOOL_CALL_ARGS,
614 toolCallId: toolCall.id,
615 model,
616 timestamp: now(),
617 delta: event.delta.partial_json,
618 }
619 }
620 }
621 } else if (event.type === 'content_block_stop') {
622 const partialBlockType = partialBlockTypes.get(event.index)
623 partialBlockTypes.delete(event.index)
624 if (partialIsStructuredOutput && partialStructuredJson !== '') {
625 try {
626 capturedStructuredOutput = rememberStructuredOutput(
627 capturedStructuredOutput,
628 JSON.parse(partialStructuredJson),
629 )
630 } catch {
631 // Incomplete JSON; the complete assistant tool_use may still arrive.
632 }
633 }
634 if (partialBlockType === 'text') {
635 yield* closePartialText()
636 } else if (partialBlockType === 'thinking') {
637 yield* closePartialReasoning()
638 } else if (partialBlockType === 'tool_use') {
639 yield* closePartialToolUse(event.index)
640 }
641 partialIsStructuredOutput = false
642 partialStructuredJson = ''
643 }
644 }
645
646 try {
647 for await (const sdkMessage of sdkMessages) {
648 ctx.onSdkMessage?.(sdkMessage)
649
650 if (sdkMessage.type === 'system' && sdkMessage.subtype === 'init') {
651 yield* startRun()
652 ctx.onSessionId?.(sdkMessage.session_id)
653 yield {
654 type: EventType.CUSTOM,
655 model,
656 timestamp: now(),
657 name: SESSION_ID_EVENT,
658 value: {
659 sessionId: sdkMessage.session_id,
660 model: sdkMessage.model,
661 tools: sdkMessage.tools,
662 skills: sdkMessage.skills ?? [],
663 },
664 }
665 continue
666 }
667
668 // Anything before init still needs RUN_STARTED first.
669 yield* startRun()
670
671 if (sdkMessage.type === 'stream_event') {
672 if (sdkMessage.parent_tool_use_id !== null) continue
673 yield* handleStreamEvent(sdkMessage)
674 } else if (sdkMessage.type === 'assistant') {
675 if (sdkMessage.parent_tool_use_id !== null) continue
676 yield* handleAssistant(sdkMessage)
677 } else if (sdkMessage.type === 'user') {
678 if (sdkMessage.parent_tool_use_id !== null) continue
679 yield* handleUser(sdkMessage)
680 } else if (sdkMessage.type === 'result') {
681 yield* handleResult(sdkMessage)
682 }
683 // All other SDK message types (status, hooks, notifications, ...) are
684 // harness-internal and intentionally ignored.
685 }
686 } catch (error) {
687 // The run is dying (abort or SDK failure). Close any half-streamed tool
688 // calls, then pair every started tool call with a synthetic result so the
689 // next request's pending-tool-call scan doesn't try to execute them. Then
690 // let the adapter surface the error as RUN_ERROR.
691 yield* closePartialToolUses(true)
692 yield* synthesizeUnresolvedResults()
693 throw error
694 }
695}