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

translate.ts

463 lines13.9 KB

1import { EventType, buildBaseUsage } from '@tanstack/ai'
2import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
3import type {
4 OpencodeAssistantMessage,
5 OpencodeEvent,
6 OpencodePart,
7 OpencodeStreamEvent,
8 OpencodeTokens,
9} from './sdk-types'
10​
11/** Name of the CUSTOM event carrying the OpenCode session id. */
12export const SESSION_ID_EVENT = 'opencode.session-id'
13​
14/** Name of the CUSTOM event carrying the harness's todo list updates. */
15export const TODO_EVENT = 'opencode.todo'
16​
17/** Server name used for bridged TanStack tools. */
18export const BRIDGED_MCP_SERVER_NAME = 'tanstack'
19​
20export interface TranslateContext {
21 model: string
22 runId: string
23 threadId: string
24 parentRunId?: string
25 genId: () => string
26 /**
27 * Names of bridged TanStack tools, used to surface the harness's MCP tool
28 * calls under the names the application registered.
29 */
30 bridgedToolNames?: ReadonlySet<string>
31 /** Called for each raw stream event, for logging. */
32 onStreamEvent?: (event: OpencodeStreamEvent) => void
34​
35/**
36 * Resolve the AG-UI tool-call name for an OpenCode tool part. OpenCode names
37 * MCP tools `<server>_<tool>`, so bridged TanStack tools arrive as
38 * `tanstack_<tool>` and are surfaced under the names the application
39 * registered; everything else (built-in `read`, `edit`, `bash`, ... and
40 * foreign MCP tools) uses the harness tool name verbatim.
41 */
42export function resolveToolName(
43 tool: string,
44 bridgedToolNames: ReadonlySet<string> | undefined,
45): string {
46 if (!bridgedToolNames || bridgedToolNames.size === 0) return tool
47 if (bridgedToolNames.has(tool)) return tool
48 if (tool.startsWith('tanstack_') && bridgedToolNames.has(tool.slice(9))) {
49 return tool.slice(9)
50 }
51 return tool
53​
54function buildUsage(
55 tokens: OpencodeTokens | undefined,
56): TokenUsage | undefined {
57 if (!tokens) return undefined
58 const promptTokens = tokens.input ?? 0
59 const completionTokens = tokens.output ?? 0
60 const result = buildBaseUsage({
61 promptTokens,
62 completionTokens,
63 totalTokens: promptTokens + completionTokens,
64 })
65 if (tokens.cache?.read) {
66 result.promptTokensDetails = { cachedTokens: tokens.cache.read }
67 }
68 if (tokens.reasoning) {
69 result.completionTokensDetails = { reasoningTokens: tokens.reasoning }
70 }
71 return result
73​
74type TextPart = Extract<OpencodePart, { type: 'text' }>
75type ReasoningPart = Extract<OpencodePart, { type: 'reasoning' }>
76type ToolPart = Extract<OpencodePart, { type: 'tool' }>
77​
78const isTextPart = (part: OpencodePart): part is TextPart =>
79 part.type === 'text'
80const isReasoningPart = (part: OpencodePart): part is ReasoningPart =>
81 part.type === 'reasoning'
82const isToolPart = (part: OpencodePart): part is ToolPart =>
83 part.type === 'tool'
84​
85function messageError(
86 message: OpencodeAssistantMessage,
87): { message: string } | undefined {
88 if (!message.error) return undefined
89 return { message: message.error.data?.message ?? message.error.name }
91​
92/**
93 * Translate an OpenCode event stream into AG-UI StreamChunk events.
94 *
95 * The harness runs its own agent loop and executes its own tools, so the
96 * translation always ends with `finishReason: 'stop'` (or `'length'` /
97 * RUN_ERROR) — never `'tool_calls'`. Harness tool activity is emitted as
98 * already-resolved TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so
99 * UIs can render it, while the TanStack engine never tries to execute them.
100 *
101 * OpenCode delivers true token-level deltas for both assistant text and
102 * reasoning via `message.part.updated` events (a `delta` string when
103 * incremental, otherwise the full part text, from which the delta is
104 * derived). The final assistant message — finish reason, token usage, and any
105 * fatal error — arrives as the terminal `done` event.
106 *
107 * Invariant: every TOOL_CALL_START is eventually paired with a
108 * TOOL_CALL_RESULT (synthesized as `{"status":"interrupted"}` when the run
109 * ends or aborts before the harness reported one) so the engine's
110 * pending-tool-call scan on the next request never force-executes them.
111 */
112export async function* translateOpencodeStream(
113 events: AsyncIterable<OpencodeStreamEvent>,
114 ctx: TranslateContext,
115): AsyncIterable<AdapterYieldChunk> {
116 const { model, runId, threadId, genId } = ctx
117 const now = () => Date.now()
118​
119 let runStarted = false
120 /** Tool calls started but with no result yet, keyed by callID. */
121 const unresolvedToolCalls = new Set<string>()
122 /** Tool call ids that already emitted TOOL_CALL_START/ARGS/END. */
123 const openedToolCalls = new Set<string>()
124 /** Tool call ids that already emitted a TOOL_CALL_RESULT. */
125 const resolvedToolCalls = new Set<string>()
126 /** Message roles from message.updated events, keyed by message id. */
127 const messageRoles = new Map<string, 'user' | 'assistant'>()
128 /** Parts held until their parent message role arrives. */
129 const pendingParts = new Map<
130 string,
131 Array<{ part: OpencodePart; delta?: string }>
132 >()
133​
134 /** Accumulated text per text-part id, for delta derivation. */
135 const textAccumulators = new Map<string, string>()
136 let openTextId: string | null = null
137 let openReasoningId: string | null = null
138​
139 function* startRun(): Generator<AdapterYieldChunk> {
140 if (runStarted) return
141 runStarted = true
142 yield {
143 type: EventType.RUN_STARTED,
144 runId,
145 threadId,
146 model,
147 timestamp: now(),
148 ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }),
149 }
150 }
151​
152 function* closeText(): Generator<AdapterYieldChunk> {
153 if (openTextId !== null) {
154 yield {
155 type: EventType.TEXT_MESSAGE_END,
156 messageId: openTextId,
157 model,
158 timestamp: now(),
159 }
160 openTextId = null
161 }
162 }
163​
164 function* closeReasoning(): Generator<AdapterYieldChunk> {
165 if (openReasoningId !== null) {
166 yield {
167 type: EventType.REASONING_MESSAGE_END,
168 messageId: openReasoningId,
169 model,
170 timestamp: now(),
171 }
172 yield {
173 type: EventType.REASONING_END,
174 messageId: openReasoningId,
175 model,
176 timestamp: now(),
177 }
178 openReasoningId = null
179 }
180 }
181​
182 function* synthesizeUnresolvedResults(): Generator<AdapterYieldChunk> {
183 for (const toolCallId of unresolvedToolCalls) {
184 yield {
185 type: EventType.TOOL_CALL_RESULT,
186 toolCallId,
187 messageId: genId(),
188 model,
189 timestamp: now(),
190 content: JSON.stringify({ status: 'interrupted' }),
191 }
192 }
193 unresolvedToolCalls.clear()
194 }
195​
196 function* handleTextPart(
197 part: Extract<OpencodePart, { type: 'text' }>,
198 delta: string | undefined,
199 ): Generator<AdapterYieldChunk> {
200 yield* closeReasoning()
201​
202 const prev = textAccumulators.get(part.id) ?? ''
203 let deltaText: string
204 if (typeof delta === 'string' && delta !== '') {
205 deltaText = delta
206 textAccumulators.set(part.id, prev + delta)
207 } else {
208 const full = part.text
209 deltaText = full.startsWith(prev) ? full.slice(prev.length) : full
210 textAccumulators.set(part.id, full)
211 }
212 if (deltaText === '') return
213​
214 if (openTextId !== part.id) {
215 yield* closeText()
216 openTextId = part.id
217 yield {
218 type: EventType.TEXT_MESSAGE_START,
219 messageId: part.id,
220 model,
221 timestamp: now(),
222 role: 'assistant',
223 }
224 }
225 yield {
226 type: EventType.TEXT_MESSAGE_CONTENT,
227 messageId: part.id,
228 model,
229 timestamp: now(),
230 delta: deltaText,
231 content: textAccumulators.get(part.id) ?? deltaText,
232 }
233 }
234​
235 function* handleReasoningPart(
236 part: Extract<OpencodePart, { type: 'reasoning' }>,
237 delta: string | undefined,
238 ): Generator<AdapterYieldChunk> {
239 yield* closeText()
240​
241 const prev = textAccumulators.get(part.id) ?? ''
242 let deltaText: string
243 if (typeof delta === 'string' && delta !== '') {
244 deltaText = delta
245 textAccumulators.set(part.id, prev + delta)
246 } else {
247 const full = part.text
248 deltaText = full.startsWith(prev) ? full.slice(prev.length) : full
249 textAccumulators.set(part.id, full)
250 }
251 if (deltaText === '') return
252​
253 if (openReasoningId !== part.id) {
254 yield* closeReasoning()
255 openReasoningId = part.id
256 yield {
257 type: EventType.REASONING_START,
258 messageId: part.id,
259 model,
260 timestamp: now(),
261 }
262 yield {
263 type: EventType.REASONING_MESSAGE_START,
264 messageId: part.id,
265 role: 'reasoning' as const,
266 model,
267 timestamp: now(),
268 }
269 }
270 yield {
271 type: EventType.REASONING_MESSAGE_CONTENT,
272 messageId: part.id,
273 delta: deltaText,
274 model,
275 timestamp: now(),
276 }
277 }
278​
279 function* openToolCall(
280 part: Extract<OpencodePart, { type: 'tool' }>,
281 ): Generator<AdapterYieldChunk> {
282 if (openedToolCalls.has(part.callID)) return
283 openedToolCalls.add(part.callID)
284 const toolCallName = resolveToolName(part.tool, ctx.bridgedToolNames)
285 const input = part.state.input ?? {}
286 const args = JSON.stringify(input)
287 yield {
288 type: EventType.TOOL_CALL_START,
289 toolCallId: part.callID,
290 toolCallName,
291 model,
292 timestamp: now(),
293 }
294 yield {
295 type: EventType.TOOL_CALL_ARGS,
296 toolCallId: part.callID,
297 model,
298 timestamp: now(),
299 delta: args,
300 args,
301 }
302 yield {
303 type: EventType.TOOL_CALL_END,
304 toolCallId: part.callID,
305 toolCallName,
306 model,
307 timestamp: now(),
308 input,
309 }
310 unresolvedToolCalls.add(part.callID)
311 }
312​
313 function* handleToolPart(
314 part: Extract<OpencodePart, { type: 'tool' }>,
315 ): Generator<AdapterYieldChunk> {
316 if (part.state.status === 'pending') return
317​
318 yield* closeText()
319 yield* closeReasoning()
320 yield* openToolCall(part)
321​
322 const state = part.state
323 if (state.status !== 'completed' && state.status !== 'error') return
324 if (resolvedToolCalls.has(part.callID)) return
325 resolvedToolCalls.add(part.callID)
326 unresolvedToolCalls.delete(part.callID)
327​
328 const isError = state.status === 'error'
329 yield {
330 type: EventType.TOOL_CALL_RESULT,
331 toolCallId: part.callID,
332 messageId: genId(),
333 model,
334 timestamp: now(),
335 content: isError ? state.error : state.output,
336 ...(isError && { state: 'output-error' as const }),
337 }
338 }
339​
340 function* handlePart(
341 part: OpencodePart,
342 delta: string | undefined,
343 ): Generator<AdapterYieldChunk> {
344 if (isTextPart(part)) {
345 yield* handleTextPart(part, delta)
346 } else if (isReasoningPart(part)) {
347 yield* handleReasoningPart(part, delta)
348 } else if (isToolPart(part)) {
349 yield* handleToolPart(part)
350 }
351 // Other part kinds (file, step-start/finish, snapshot, ...) carry no
352 // state the chunk stream needs.
353 }
354​
355 function* setMessageRole(
356 messageId: string,
357 role: 'user' | 'assistant',
358 ): Generator<AdapterYieldChunk> {
359 messageRoles.set(messageId, role)
360 const parts = pendingParts.get(messageId)
361 if (parts === undefined) return
362 pendingParts.delete(messageId)
363 if (role === 'user') return
364 for (const { part, delta } of parts) yield* handlePart(part, delta)
365 }
366​
367 function* handleEvent(event: OpencodeEvent): Generator<AdapterYieldChunk> {
368 if (event.type === 'message.updated') {
369 yield* setMessageRole(
370 event.properties.info.id,
371 event.properties.info.role,
372 )
373 } else if (event.type === 'message.part.updated') {
374 const { part, delta } = event.properties
375 const role = messageRoles.get(part.messageID)
376 if (role === undefined) {
377 const parts = pendingParts.get(part.messageID) ?? []
378 parts.push({ part, delta })
379 pendingParts.set(part.messageID, parts)
380 } else if (role === 'assistant') {
381 yield* handlePart(part, delta)
382 }
383 } else if (event.type === 'todo.updated') {
384 yield {
385 type: EventType.CUSTOM,
386 model,
387 timestamp: now(),
388 name: TODO_EVENT,
389 value: { todos: event.properties.todos },
390 }
391 }
392 // session.idle / session.error are redundant with the terminal `done`
393 // event and are ignored.
394 }
395​
396 function* finish(
397 message: OpencodeAssistantMessage,
398 ): Generator<AdapterYieldChunk> {
399 yield* startRun()
400 // The final message is the assistant reply, so flush any parts that beat
401 // its message.updated. OpenCode sends message.updated when it creates a
402 // message, so parts of any other message still waiting here are dropped.
403 yield* setMessageRole(message.id, 'assistant')
404 yield* closeText()
405 yield* closeReasoning()
406 yield* synthesizeUnresolvedResults()
407​
408 const error = messageError(message)
409 if (error) {
410 yield {
411 type: EventType.RUN_ERROR,
412 model,
413 timestamp: now(),
414 message: error.message,
415 error,
416 }
417 return
418 }
419​
420 const usage = buildUsage(message.tokens)
421 const finishReason = message.finish === 'length' ? 'length' : 'stop'
422 yield {
423 type: EventType.RUN_FINISHED,
424 runId,
425 threadId,
426 model,
427 timestamp: now(),
428 finishReason,
429 ...(usage !== undefined && { usage }),
430 }
431 }
432​
433 try {
434 for await (const streamEvent of events) {
435 ctx.onStreamEvent?.(streamEvent)
436​
437 if (streamEvent.kind === 'session') {
438 yield* startRun()
439 yield {
440 type: EventType.CUSTOM,
441 model,
442 timestamp: now(),
443 name: SESSION_ID_EVENT,
444 value: { sessionId: streamEvent.sessionId },
445 }
446 } else if (streamEvent.kind === 'event') {
447 yield* startRun()
448 yield* handleEvent(streamEvent.event)
449 } else {
450 yield* finish(streamEvent.message)
451 }
452 }
453 } catch (error) {
454 // The run is dying (abort, server exit, or connection failure). Close any
455 // open message and pair started tool calls with a synthetic result first
456 // so the next request's pending-tool-call scan doesn't try to execute
457 // them, then let the adapter surface the error as RUN_ERROR.
458 yield* closeText()
459 yield* closeReasoning()
460 yield* synthesizeUnresolvedResults()
461 throw error
462 }