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

translate.ts

470 lines14.0 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 { CodexThreadEvent, CodexThreadItem, CodexUsage } from './sdk-types'
9​
10/** Name of the CUSTOM event carrying the Codex thread (session) id. */
11export const SESSION_ID_EVENT = 'codex.session-id'
12​
13/** Server name used for bridged TanStack tools. */
14export const BRIDGED_MCP_SERVER_NAME = 'tanstack'
15​
16export interface TranslateContext {
17 model: string
18 runId: string
19 threadId: string
20 parentRunId?: string
21 genId: () => string
22 /** Called as soon as the harness reports its thread id. */
23 onSessionId?: (sessionId: string) => void
24 /** Called for each raw SDK thread event, for logging. */
25 onThreadEvent?: (event: CodexThreadEvent) => void
26 /** Treat the last agent_message as schema JSON. */
27 expectStructuredOutput?: boolean
29​
30/**
31 * Resolve the AG-UI tool-call name for a Codex thread item. Bridged TanStack
32 * tools come back as `mcp_tool_call` items on the `tanstack` server and are
33 * surfaced under the names the application registered; foreign MCP tools are
34 * namespaced `mcp__<server>__<tool>`; harness-native items use their item
35 * type verbatim (`command_execution`, `file_change`, ...).
36 */
37export function toolNameForItem(item: CodexThreadItem): string {
38 if (item.type === 'mcp_tool_call') {
39 return item.server === BRIDGED_MCP_SERVER_NAME
40 ? item.tool
41 : `mcp__${item.server}__${item.tool}`
42 }
43 return item.type
45​
46/** Thread items the translator surfaces as already-resolved tool calls. */
47type CodexToolItem = Extract<
48 CodexThreadItem,
49 {
50 type:
51 | 'command_execution'
52 | 'mcp_tool_call'
53 | 'file_change'
54 | 'web_search'
55 | 'todo_list'
56 }
58​
59function toolArgsForItem(item: CodexToolItem): unknown {
60 switch (item.type) {
61 case 'command_execution':
62 return { command: item.command }
63 case 'mcp_tool_call':
64 return item.arguments ?? {}
65 case 'file_change':
66 return { changes: item.changes }
67 case 'web_search':
68 return { query: item.query }
69 case 'todo_list':
70 return {}
71 }
73​
74function toolResultForItem(item: CodexToolItem): {
75 content: string
76 isError: boolean
77} {
78 switch (item.type) {
79 case 'command_execution':
80 return {
81 content: JSON.stringify({
82 aggregated_output: item.aggregated_output ?? '',
83 ...(item.exit_code !== undefined && { exit_code: item.exit_code }),
84 status: item.status,
85 }),
86 isError: item.status === 'failed',
87 }
88 case 'mcp_tool_call': {
89 if (item.error) {
90 return { content: item.error.message, isError: true }
91 }
92 const text = (item.result?.content ?? [])
93 .map((block) => (typeof block.text === 'string' ? block.text : ''))
94 .join('')
95 if (text !== '') {
96 return { content: text, isError: item.status === 'failed' }
97 }
98 if (item.result?.structured_content !== undefined) {
99 return {
100 content: JSON.stringify(item.result.structured_content),
101 isError: item.status === 'failed',
102 }
103 }
104 return {
105 content: JSON.stringify({ status: item.status }),
106 isError: item.status === 'failed',
107 }
108 }
109 case 'file_change':
110 return {
111 content: JSON.stringify({ changes: item.changes, status: item.status }),
112 isError: item.status === 'failed',
113 }
114 case 'web_search':
115 return {
116 content: JSON.stringify({ status: 'completed' }),
117 isError: false,
118 }
119 case 'todo_list':
120 return { content: JSON.stringify({ items: item.items }), isError: false }
121 }
123​
124function isToolItem(item: CodexThreadItem): item is CodexToolItem {
125 return (
126 item.type === 'command_execution' ||
127 item.type === 'mcp_tool_call' ||
128 item.type === 'file_change' ||
129 item.type === 'web_search' ||
130 item.type === 'todo_list'
131 )
133​
134function buildUsage(usage: CodexUsage | undefined): TokenUsage | undefined {
135 if (!usage) return undefined
136 const promptTokens = usage.input_tokens ?? 0
137 const completionTokens = usage.output_tokens ?? 0
138 const result = buildBaseUsage({
139 promptTokens,
140 completionTokens,
141 totalTokens: promptTokens + completionTokens,
142 })
143 if (usage.cached_input_tokens) {
144 result.promptTokensDetails = { cachedTokens: usage.cached_input_tokens }
145 }
146 if (usage.reasoning_output_tokens) {
147 result.completionTokensDetails = {
148 reasoningTokens: usage.reasoning_output_tokens,
149 }
150 }
151 return result
153​
154/**
155 * Translate a Codex SDK thread-event stream into AG-UI StreamChunk events.
156 *
157 * The harness runs its own agent loop and executes its own tools, so the
158 * translation always ends with `finishReason: 'stop'` (or RUN_ERROR) — never
159 * `'tool_calls'`. Harness tool activity (commands, file changes, MCP calls,
160 * web searches, todo lists) is emitted as already-resolved
161 * TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so UIs can render it
162 * while the TanStack engine never tries to execute them.
163 *
164 * Codex reports assistant text on `item.started` / `item.updated` /
165 * `item.completed`. Each `agent_message` streams as START/CONTENT/END, with
166 * CONTENT deltas from growing `item.text`. When `expectStructuredOutput` is
167 * set, the last agent message is also parsed as the schema object on
168 * `turn.completed`.
169 *
170 * Invariant: every TOOL_CALL_START is eventually paired with a
171 * TOOL_CALL_RESULT (synthesized as `{"status":"interrupted"}` when the run
172 * ends or aborts before the harness reported one) so the engine's
173 * pending-tool-call scan on the next request never force-executes them.
174 */
175export async function* translateThreadEvents(
176 events: AsyncIterable<CodexThreadEvent>,
177 ctx: TranslateContext,
178): AsyncIterable<AdapterYieldChunk> {
179 const { model, runId, threadId, genId } = ctx
180 const now = () => Date.now()
181​
182 let runStarted = false
183 /** Tool calls started but with no result yet. */
184 const unresolvedToolCalls = new Set<string>()
185 /** Item ids that already emitted TOOL_CALL_START/ARGS/END. */
186 const openedToolItems = new Set<string>()
187​
188 function* startRun(): Generator<AdapterYieldChunk> {
189 if (runStarted) return
190 runStarted = true
191 yield {
192 type: EventType.RUN_STARTED,
193 runId,
194 threadId,
195 model,
196 timestamp: now(),
197 ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),
198 }
199 }
200​
201 function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {
202 for (const toolCallId of unresolvedToolCalls) {
203 yield {
204 type: EventType.TOOL_CALL_RESULT,
205 toolCallId,
206 messageId: genId(),
207 model,
208 timestamp: now(),
209 content: JSON.stringify({ status: 'interrupted' }),
210 }
211 }
212 unresolvedToolCalls.clear()
213 }
214​
215 function* openToolCall(item: CodexToolItem): Generator<AdapterYieldChunk> {
216 if (openedToolItems.has(item.id)) return
217 openedToolItems.add(item.id)
218 const toolCallName = toolNameForItem(item)
219 const input = toolArgsForItem(item)
220 const args = JSON.stringify(input)
221 yield {
222 type: EventType.TOOL_CALL_START,
223 toolCallId: item.id,
224 toolCallName,
225 toolName: toolCallName,
226 model,
227 timestamp: now(),
228 }
229 yield {
230 type: EventType.TOOL_CALL_ARGS,
231 toolCallId: item.id,
232 model,
233 timestamp: now(),
234 delta: args,
235 args,
236 }
237 yield {
238 type: EventType.TOOL_CALL_END,
239 toolCallId: item.id,
240 toolCallName,
241 toolName: toolCallName,
242 model,
243 timestamp: now(),
244 input,
245 }
246 unresolvedToolCalls.add(item.id)
247 }
248​
249 const openText = new Map<string, { emitted: number; ended: boolean }>()
250 let lastAgentMessage: { id: string; text: string } | undefined
251​
252 function* startText(messageId: string): Generator<AdapterYieldChunk> {
253 if (openText.has(messageId)) return
254 openText.set(messageId, { emitted: 0, ended: false })
255 yield {
256 type: EventType.TEXT_MESSAGE_START,
257 messageId,
258 model,
259 timestamp: now(),
260 role: 'assistant',
261 }
262 }
263​
264 function* emitTextDelta(
265 messageId: string,
266 text: string,
267 ): Generator<AdapterYieldChunk> {
268 yield* startText(messageId)
269 const state = openText.get(messageId)
270 if (state === undefined || state.ended) return
271 if (text.length <= state.emitted) return
272 const delta = text.slice(state.emitted)
273 state.emitted = text.length
274 yield {
275 type: EventType.TEXT_MESSAGE_CONTENT,
276 messageId,
277 model,
278 timestamp: now(),
279 delta,
280 content: text,
281 }
282 }
283​
284 function* endText(messageId: string): Generator<AdapterYieldChunk> {
285 const state = openText.get(messageId)
286 if (state === undefined || state.ended) return
287 state.ended = true
288 yield {
289 type: EventType.TEXT_MESSAGE_END,
290 messageId,
291 model,
292 timestamp: now(),
293 }
294 }
295​
296 function* handleAgentMessage(
297 item: { id: string; text: string },
298 done: boolean,
299 ): Generator<AdapterYieldChunk> {
300 yield* emitTextDelta(item.id, item.text)
301 lastAgentMessage = { id: item.id, text: item.text }
302 if (done) yield* endText(item.id)
303 }
304​
305 function* emitStructuredFromLast(): Generator<AdapterYieldChunk> {
306 if (ctx.expectStructuredOutput !== true) return
307 if (lastAgentMessage === undefined) return
308 const item = lastAgentMessage
309 lastAgentMessage = undefined
310 try {
311 const object = parseJsonFromAssistantText(item.text)
312 yield structuredOutputStartChunk({
313 messageId: item.id,
314 model,
315 threadId,
316 runId,
317 })
318 yield structuredOutputCompleteChunk({
319 messageId: item.id,
320 model,
321 threadId,
322 runId,
323 object,
324 raw: item.text,
325 })
326 } catch (error: unknown) {
327 const parserMessage =
328 error instanceof Error
329 ? error.message
330 : 'Invalid structured output JSON'
331 const preview = item.text.trim().slice(0, 200)
332 const message =
333 preview === '' ? parserMessage : `${parserMessage} Content: ${preview}`
334 yield {
335 type: EventType.RUN_ERROR,
336 model,
337 timestamp: now(),
338 message,
339 code: 'structured-output-parse-failed',
340 error: { message, code: 'structured-output-parse-failed' },
341 }
342 }
343 }
344​
345 function* handleItemCompleted(
346 item: CodexThreadItem,
347 ): Generator<AdapterYieldChunk> {
348 if (item.type === 'agent_message') {
349 yield* handleAgentMessage(item, true)
350 } else if (item.type === 'reasoning') {
351 const reasoningId = item.id
352 yield {
353 type: EventType.REASONING_START,
354 messageId: reasoningId,
355 model,
356 timestamp: now(),
357 }
358 yield {
359 type: EventType.REASONING_MESSAGE_START,
360 messageId: reasoningId,
361 role: 'reasoning' as const,
362 model,
363 timestamp: now(),
364 }
365 yield {
366 type: EventType.REASONING_MESSAGE_CONTENT,
367 messageId: reasoningId,
368 delta: item.text,
369 model,
370 timestamp: now(),
371 }
372 yield {
373 type: EventType.REASONING_MESSAGE_END,
374 messageId: reasoningId,
375 model,
376 timestamp: now(),
377 }
378 yield {
379 type: EventType.REASONING_END,
380 messageId: reasoningId,
381 model,
382 timestamp: now(),
383 }
384 } else if (isToolItem(item)) {
385 yield* openToolCall(item)
386 unresolvedToolCalls.delete(item.id)
387 const { content, isError } = toolResultForItem(item)
388 yield {
389 type: EventType.TOOL_CALL_RESULT,
390 toolCallId: item.id,
391 messageId: genId(),
392 model,
393 timestamp: now(),
394 content,
395 ...(isError && { state: 'output-error' as const }),
396 }
397 }
398 // `error` items are non-fatal diagnostics; `turn.failed` is the fatal
399 // signal. They are surfaced via onThreadEvent logging only.
400 }
401​
402 try {
403 for await (const event of events) {
404 ctx.onThreadEvent?.(event)
405​
406 if (event.type === 'thread.started') {
407 yield* startRun()
408 ctx.onSessionId?.(event.thread_id)
409 yield {
410 type: EventType.CUSTOM,
411 model,
412 timestamp: now(),
413 name: SESSION_ID_EVENT,
414 value: { sessionId: event.thread_id },
415 }
416 continue
417 }
418​
419 // Resumed threads don't re-emit thread.started; anything else still
420 // needs RUN_STARTED first.
421 yield* startRun()
422​
423 if (event.type === 'item.started' || event.type === 'item.updated') {
424 if (event.item.type === 'agent_message') {
425 yield* handleAgentMessage(event.item, false)
426 } else if (event.type === 'item.started' && isToolItem(event.item)) {
427 yield* openToolCall(event.item)
428 }
429 } else if (event.type === 'item.completed') {
430 yield* handleItemCompleted(event.item)
431 } else if (event.type === 'turn.completed') {
432 yield* emitStructuredFromLast()
433 yield* synthesizeUnresolvedResults()
434 const usage = buildUsage(event.usage)
435 yield {
436 type: EventType.RUN_FINISHED,
437 runId,
438 threadId,
439 model,
440 timestamp: now(),
441 finishReason: 'stop',
442 ...(usage !== undefined && { usage }),
443 }
444 } else if (event.type === 'turn.failed' || event.type === 'error') {
445 yield* synthesizeUnresolvedResults()
446 const message =
447 event.type === 'turn.failed'
448 ? (event.error?.message ?? 'Codex turn failed')
449 : event.message
450 yield {
451 type: EventType.RUN_ERROR,
452 model,
453 timestamp: now(),
454 message,
455 error: { message },
456 }
457 }
458 // turn.started carries no chunk-stream state. item.updated for tools
459 // (streaming command output, todo ticks) is dropped on purpose.
460 }
461 yield* emitStructuredFromLast()
462 } catch (error) {
463 // The run is dying (abort or SDK failure). Pair any started tool calls
464 // with a synthetic result first so the next request's pending-tool-call
465 // scan doesn't try to execute them, then let the adapter surface the
466 // error as RUN_ERROR.
467 yield* synthesizeUnresolvedResults()
468 throw error
469 }