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

translate.ts

468 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 model,
226 timestamp: now(),
227 }
228 yield {
229 type: EventType.TOOL_CALL_ARGS,
230 toolCallId: item.id,
231 model,
232 timestamp: now(),
233 delta: args,
234 args,
235 }
236 yield {
237 type: EventType.TOOL_CALL_END,
238 toolCallId: item.id,
239 toolCallName,
240 model,
241 timestamp: now(),
242 input,
243 }
244 unresolvedToolCalls.add(item.id)
245 }
246​
247 const openText = new Map<string, { emitted: number; ended: boolean }>()
248 let lastAgentMessage: { id: string; text: string } | undefined
249​
250 function* startText(messageId: string): Generator<AdapterYieldChunk> {
251 if (openText.has(messageId)) return
252 openText.set(messageId, { emitted: 0, ended: false })
253 yield {
254 type: EventType.TEXT_MESSAGE_START,
255 messageId,
256 model,
257 timestamp: now(),
258 role: 'assistant',
259 }
260 }
261​
262 function* emitTextDelta(
263 messageId: string,
264 text: string,
265 ): Generator<AdapterYieldChunk> {
266 yield* startText(messageId)
267 const state = openText.get(messageId)
268 if (state === undefined || state.ended) return
269 if (text.length <= state.emitted) return
270 const delta = text.slice(state.emitted)
271 state.emitted = text.length
272 yield {
273 type: EventType.TEXT_MESSAGE_CONTENT,
274 messageId,
275 model,
276 timestamp: now(),
277 delta,
278 content: text,
279 }
280 }
281​
282 function* endText(messageId: string): Generator<AdapterYieldChunk> {
283 const state = openText.get(messageId)
284 if (state === undefined || state.ended) return
285 state.ended = true
286 yield {
287 type: EventType.TEXT_MESSAGE_END,
288 messageId,
289 model,
290 timestamp: now(),
291 }
292 }
293​
294 function* handleAgentMessage(
295 item: { id: string; text: string },
296 done: boolean,
297 ): Generator<AdapterYieldChunk> {
298 yield* emitTextDelta(item.id, item.text)
299 lastAgentMessage = { id: item.id, text: item.text }
300 if (done) yield* endText(item.id)
301 }
302​
303 function* emitStructuredFromLast(): Generator<AdapterYieldChunk> {
304 if (ctx.expectStructuredOutput !== true) return
305 if (lastAgentMessage === undefined) return
306 const item = lastAgentMessage
307 lastAgentMessage = undefined
308 try {
309 const object = parseJsonFromAssistantText(item.text)
310 yield structuredOutputStartChunk({
311 messageId: item.id,
312 model,
313 threadId,
314 runId,
315 })
316 yield structuredOutputCompleteChunk({
317 messageId: item.id,
318 model,
319 threadId,
320 runId,
321 object,
322 raw: item.text,
323 })
324 } catch (error: unknown) {
325 const parserMessage =
326 error instanceof Error
327 ? error.message
328 : 'Invalid structured output JSON'
329 const preview = item.text.trim().slice(0, 200)
330 const message =
331 preview === '' ? parserMessage : `${parserMessage} Content: ${preview}`
332 yield {
333 type: EventType.RUN_ERROR,
334 model,
335 timestamp: now(),
336 message,
337 code: 'structured-output-parse-failed',
338 error: { message, code: 'structured-output-parse-failed' },
339 }
340 }
341 }
342​
343 function* handleItemCompleted(
344 item: CodexThreadItem,
345 ): Generator<AdapterYieldChunk> {
346 if (item.type === 'agent_message') {
347 yield* handleAgentMessage(item, true)
348 } else if (item.type === 'reasoning') {
349 const reasoningId = item.id
350 yield {
351 type: EventType.REASONING_START,
352 messageId: reasoningId,
353 model,
354 timestamp: now(),
355 }
356 yield {
357 type: EventType.REASONING_MESSAGE_START,
358 messageId: reasoningId,
359 role: 'reasoning' as const,
360 model,
361 timestamp: now(),
362 }
363 yield {
364 type: EventType.REASONING_MESSAGE_CONTENT,
365 messageId: reasoningId,
366 delta: item.text,
367 model,
368 timestamp: now(),
369 }
370 yield {
371 type: EventType.REASONING_MESSAGE_END,
372 messageId: reasoningId,
373 model,
374 timestamp: now(),
375 }
376 yield {
377 type: EventType.REASONING_END,
378 messageId: reasoningId,
379 model,
380 timestamp: now(),
381 }
382 } else if (isToolItem(item)) {
383 yield* openToolCall(item)
384 unresolvedToolCalls.delete(item.id)
385 const { content, isError } = toolResultForItem(item)
386 yield {
387 type: EventType.TOOL_CALL_RESULT,
388 toolCallId: item.id,
389 messageId: genId(),
390 model,
391 timestamp: now(),
392 content,
393 ...(isError && { state: 'output-error' as const }),
394 }
395 }
396 // `error` items are non-fatal diagnostics; `turn.failed` is the fatal
397 // signal. They are surfaced via onThreadEvent logging only.
398 }
399​
400 try {
401 for await (const event of events) {
402 ctx.onThreadEvent?.(event)
403​
404 if (event.type === 'thread.started') {
405 yield* startRun()
406 ctx.onSessionId?.(event.thread_id)
407 yield {
408 type: EventType.CUSTOM,
409 model,
410 timestamp: now(),
411 name: SESSION_ID_EVENT,
412 value: { sessionId: event.thread_id },
413 }
414 continue
415 }
416​
417 // Resumed threads don't re-emit thread.started; anything else still
418 // needs RUN_STARTED first.
419 yield* startRun()
420​
421 if (event.type === 'item.started' || event.type === 'item.updated') {
422 if (event.item.type === 'agent_message') {
423 yield* handleAgentMessage(event.item, false)
424 } else if (event.type === 'item.started' && isToolItem(event.item)) {
425 yield* openToolCall(event.item)
426 }
427 } else if (event.type === 'item.completed') {
428 yield* handleItemCompleted(event.item)
429 } else if (event.type === 'turn.completed') {
430 yield* emitStructuredFromLast()
431 yield* synthesizeUnresolvedResults()
432 const usage = buildUsage(event.usage)
433 yield {
434 type: EventType.RUN_FINISHED,
435 runId,
436 threadId,
437 model,
438 timestamp: now(),
439 finishReason: 'stop',
440 ...(usage !== undefined && { usage }),
441 }
442 } else if (event.type === 'turn.failed' || event.type === 'error') {
443 yield* synthesizeUnresolvedResults()
444 const message =
445 event.type === 'turn.failed'
446 ? (event.error?.message ?? 'Codex turn failed')
447 : event.message
448 yield {
449 type: EventType.RUN_ERROR,
450 model,
451 timestamp: now(),
452 message,
453 error: { message },
454 }
455 }
456 // turn.started carries no chunk-stream state. item.updated for tools
457 // (streaming command output, todo ticks) is dropped on purpose.
458 }
459 yield* emitStructuredFromLast()
460 } catch (error) {
461 // The run is dying (abort or SDK failure). Pair any started tool calls
462 // with a synthetic result first so the next request's pending-tool-call
463 // scan doesn't try to execute them, then let the adapter surface the
464 // error as RUN_ERROR.
465 yield* synthesizeUnresolvedResults()
466 throw error
467 }