import { EventType, buildBaseUsage } from '@tanstack/ai' import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai' import type { OpencodeAssistantMessage, OpencodeEvent, OpencodePart, OpencodeStreamEvent, OpencodeTokens, } from './sdk-types' /** Name of the CUSTOM event carrying the OpenCode session id. */ export const SESSION_ID_EVENT = 'opencode.session-id' /** Name of the CUSTOM event carrying the harness's todo list updates. */ export const TODO_EVENT = 'opencode.todo' /** Server name used for bridged TanStack tools. */ export const BRIDGED_MCP_SERVER_NAME = 'tanstack' export interface TranslateContext { model: string runId: string threadId: string parentRunId?: string genId: () => string /** * Names of bridged TanStack tools, used to surface the harness's MCP tool * calls under the names the application registered. */ bridgedToolNames?: ReadonlySet /** Called for each raw stream event, for logging. */ onStreamEvent?: (event: OpencodeStreamEvent) => void } /** * Resolve the AG-UI tool-call name for an OpenCode tool part. OpenCode names * MCP tools `_`, so bridged TanStack tools arrive as * `tanstack_` and are surfaced under the names the application * registered; everything else (built-in `read`, `edit`, `bash`, ... and * foreign MCP tools) uses the harness tool name verbatim. */ export function resolveToolName( tool: string, bridgedToolNames: ReadonlySet | undefined, ): string { if (!bridgedToolNames || bridgedToolNames.size === 0) return tool if (bridgedToolNames.has(tool)) return tool if (tool.startsWith('tanstack_') && bridgedToolNames.has(tool.slice(9))) { return tool.slice(9) } return tool } function buildUsage( tokens: OpencodeTokens | undefined, cost: number | undefined, ): TokenUsage | undefined { if (!tokens) return undefined const promptTokens = tokens.input ?? 0 const completionTokens = tokens.output ?? 0 const result = buildBaseUsage({ promptTokens, completionTokens, totalTokens: promptTokens + completionTokens, }) if (tokens.cache?.read || tokens.cache?.write) { result.promptTokensDetails = { ...(tokens.cache.read ? { cachedTokens: tokens.cache.read } : {}), ...(tokens.cache.write ? { cacheWriteTokens: tokens.cache.write } : {}), } } if (tokens.reasoning) { result.completionTokensDetails = { reasoningTokens: tokens.reasoning } } // ponytail: opencode reports 0 for a model with no price. Leave cost out // then, so a price table of the caller still applies. if (cost) result.cost = cost return result } function sameTokens( a: OpencodeTokens | undefined, b: OpencodeTokens | undefined, ): boolean { return ( a !== undefined && b !== undefined && a.input === b.input && a.output === b.output && a.reasoning === b.reasoning && a.cache?.read === b.cache?.read && a.cache?.write === b.cache?.write ) } type TextPart = Extract type ReasoningPart = Extract type ToolPart = Extract type StepFinishPart = Extract const isTextPart = (part: OpencodePart): part is TextPart => part.type === 'text' const isReasoningPart = (part: OpencodePart): part is ReasoningPart => part.type === 'reasoning' const isToolPart = (part: OpencodePart): part is ToolPart => part.type === 'tool' const isStepFinishPart = (part: OpencodePart): part is StepFinishPart => part.type === 'step-finish' function messageError( message: OpencodeAssistantMessage, ): { message: string } | undefined { if (!message.error) return undefined return { message: message.error.data?.message ?? message.error.name } } /** * Translate an OpenCode event stream into AG-UI StreamChunk events. * * The harness runs its own agent loop and executes its own tools, so the * translation always ends with `finishReason: 'stop'` (or `'length'` / * RUN_ERROR) — never `'tool_calls'`. Harness tool activity is emitted as * already-resolved TOOL_CALL_START/ARGS/END + TOOL_CALL_RESULT sequences so * UIs can render it, while the TanStack engine never tries to execute them. * * OpenCode delivers true token-level deltas for both assistant text and * reasoning via `message.part.updated` events (a `delta` string when * incremental, otherwise the full part text, from which the delta is * derived). OpenCode 1.x sends the deltas as `message.part.delta` events. The * final assistant message — finish reason, token usage, and any fatal error — * arrives as the terminal `done` event. * * Invariant: every TOOL_CALL_START is eventually paired with a * TOOL_CALL_RESULT (synthesized as `{"status":"interrupted"}` when the run * ends or aborts before the harness reported one) so the engine's * pending-tool-call scan on the next request never force-executes them. */ export async function* translateOpencodeStream( events: AsyncIterable, ctx: TranslateContext, ): AsyncIterable { const { model, runId, threadId, genId } = ctx const now = () => Date.now() let runStarted = false /** Tool calls started but with no result yet, keyed by callID. */ const unresolvedToolCalls = new Set() /** Tool call ids that already emitted TOOL_CALL_START/ARGS/END. */ const openedToolCalls = new Set() /** Tool call ids that already emitted a TOOL_CALL_RESULT. */ const resolvedToolCalls = new Set() /** Message roles from message.updated events, keyed by message id. */ const messageRoles = new Map() /** Parts held until their parent message role arrives. */ const pendingParts = new Map< string, Array<{ part: OpencodePart; delta?: string }> >() /** Accumulated text per text-part id, for delta derivation. */ const textAccumulators = new Map() /** The latest update of each part, for the `message.part.delta` events. */ const knownParts = new Map() let openTextId: string | null = null let openReasoningId: string | null = null /** * Finished agent-loop steps of this turn, keyed by part id so a repeated * update of one part is not counted twice. Each step-finish part carries * that step's tokens and cost. */ const finishedSteps = new Map() /** Usage summed over all steps, or the final message's usage. */ function turnUsage( message: OpencodeAssistantMessage, ): TokenUsage | undefined { if (finishedSteps.size === 0) { return buildUsage(message.tokens, message.cost) } const tokens = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 }, } let cost = 0 const recorded = [...finishedSteps.values()] const own = recorded.filter((s) => s.messageID === message.id) // One message can hold several steps. opencode keeps the tokens of its // last step and the cost of all its steps on the message. const ownCost = own.reduce((sum, s) => sum + (s.cost ?? 0), 0) const steps: Array<{ tokens?: OpencodeTokens; cost?: number }> = [ ...recorded.filter((s) => s.messageID !== message.id), ...own.map((s) => ({ tokens: s.tokens })), { cost: message.cost ?? ownCost }, ] // The last step-finish part can arrive after `done`. Then the message // tokens (the last step's) stand in for that step. The last recorded // part is that step only when its tokens, and its reason when the // message has one, match: an earlier step can share the reason. const last = own.at(-1) const lastStepSeen = last !== undefined && sameTokens(last.tokens, message.tokens) && (message.finish === undefined || last.reason === message.finish) if (!lastStepSeen) steps.push({ tokens: message.tokens }) for (const step of steps) { tokens.input += step.tokens?.input ?? 0 tokens.output += step.tokens?.output ?? 0 tokens.reasoning += step.tokens?.reasoning ?? 0 tokens.cache.read += step.tokens?.cache?.read ?? 0 tokens.cache.write += step.tokens?.cache?.write ?? 0 cost += step.cost ?? 0 } return buildUsage(tokens, cost) } function* startRun(): Generator { if (runStarted) return runStarted = true yield { type: EventType.RUN_STARTED, runId, threadId, model, timestamp: now(), ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }), } } function* closeText(): Generator { if (openTextId !== null) { yield { type: EventType.TEXT_MESSAGE_END, messageId: openTextId, model, timestamp: now(), } openTextId = null } } function* closeReasoning(): Generator { if (openReasoningId !== null) { yield { type: EventType.REASONING_MESSAGE_END, messageId: openReasoningId, model, timestamp: now(), } yield { type: EventType.REASONING_END, messageId: openReasoningId, model, timestamp: now(), } openReasoningId = null } } function* synthesizeUnresolvedResults(): Generator { for (const toolCallId of unresolvedToolCalls) { yield { type: EventType.TOOL_CALL_RESULT, toolCallId, messageId: genId(), model, timestamp: now(), content: JSON.stringify({ status: 'interrupted' }), } } unresolvedToolCalls.clear() } function* handleTextPart( part: Extract, delta: string | undefined, ): Generator { yield* closeReasoning() const prev = textAccumulators.get(part.id) ?? '' let deltaText: string if (typeof delta === 'string' && delta !== '') { deltaText = delta textAccumulators.set(part.id, prev + delta) } else { const full = part.text deltaText = full.startsWith(prev) ? full.slice(prev.length) : full textAccumulators.set(part.id, full) } if (deltaText === '') return if (openTextId !== part.id) { yield* closeText() openTextId = part.id yield { type: EventType.TEXT_MESSAGE_START, messageId: part.id, model, timestamp: now(), role: 'assistant', } } yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId: part.id, model, timestamp: now(), delta: deltaText, content: textAccumulators.get(part.id) ?? deltaText, } } function* handleReasoningPart( part: Extract, delta: string | undefined, ): Generator { yield* closeText() const prev = textAccumulators.get(part.id) ?? '' let deltaText: string if (typeof delta === 'string' && delta !== '') { deltaText = delta textAccumulators.set(part.id, prev + delta) } else { const full = part.text deltaText = full.startsWith(prev) ? full.slice(prev.length) : full textAccumulators.set(part.id, full) } if (deltaText === '') return if (openReasoningId !== part.id) { yield* closeReasoning() openReasoningId = part.id yield { type: EventType.REASONING_START, messageId: part.id, model, timestamp: now(), } yield { type: EventType.REASONING_MESSAGE_START, messageId: part.id, role: 'reasoning' as const, model, timestamp: now(), } } yield { type: EventType.REASONING_MESSAGE_CONTENT, messageId: part.id, delta: deltaText, model, timestamp: now(), } } function* openToolCall( part: Extract, ): Generator { if (openedToolCalls.has(part.callID)) return openedToolCalls.add(part.callID) const toolCallName = resolveToolName(part.tool, ctx.bridgedToolNames) const input = part.state.input ?? {} const args = JSON.stringify(input) yield { type: EventType.TOOL_CALL_START, toolCallId: part.callID, toolCallName, model, timestamp: now(), } yield { type: EventType.TOOL_CALL_ARGS, toolCallId: part.callID, model, timestamp: now(), delta: args, args, } yield { type: EventType.TOOL_CALL_END, toolCallId: part.callID, toolCallName, model, timestamp: now(), input, } unresolvedToolCalls.add(part.callID) } function* handleToolPart( part: Extract, ): Generator { if (part.state.status === 'pending') return yield* closeText() yield* closeReasoning() yield* openToolCall(part) const state = part.state if (state.status !== 'completed' && state.status !== 'error') return if (resolvedToolCalls.has(part.callID)) return resolvedToolCalls.add(part.callID) unresolvedToolCalls.delete(part.callID) const isError = state.status === 'error' yield { type: EventType.TOOL_CALL_RESULT, toolCallId: part.callID, messageId: genId(), model, timestamp: now(), content: isError ? state.error : state.output, ...(isError && { state: 'output-error' as const }), } } function* handlePart( part: OpencodePart, delta: string | undefined, ): Generator { if (isTextPart(part)) { yield* handleTextPart(part, delta) } else if (isReasoningPart(part)) { yield* handleReasoningPart(part, delta) } else if (isToolPart(part)) { yield* handleToolPart(part) } else if (isStepFinishPart(part)) { finishedSteps.set(part.id, part) } // Other part kinds (file, step-start, snapshot, ...) carry no state the // chunk stream needs. } function* setMessageRole( messageId: string, role: 'user' | 'assistant', ): Generator { messageRoles.set(messageId, role) const parts = pendingParts.get(messageId) if (parts === undefined) return pendingParts.delete(messageId) if (role === 'user') return for (const { part, delta } of parts) yield* handlePart(part, delta) } function* handleEvent(event: OpencodeEvent): Generator { if (event.type === 'message.updated') { yield* setMessageRole( event.properties.info.id, event.properties.info.role, ) } else if (event.type === 'message.part.delta') { // OpenCode 1.x sends the new text of a part in its own event. The part // keeps the text, so its last update matches the text that was sent. // A delta for a part not seen yet is skipped: the next update of the // part carries its text. const { partID, field, delta } = event.properties const known = knownParts.get(partID) if ( field === 'text' && delta !== '' && known !== undefined && (isTextPart(known) || isReasoningPart(known)) ) { const part = { ...known, text: known.text + delta } knownParts.set(partID, part) const role = messageRoles.get(part.messageID) if (role === 'assistant') { yield* handlePart(part, delta) } else if (role === undefined) { // The role comes later: keep the text on the held update. const held = pendingParts.get(part.messageID) ?? [] const index = held.findIndex((pending) => pending.part.id === partID) if (index !== -1) held[index] = { part } } } } else if (event.type === 'message.part.updated') { const { part, delta } = event.properties knownParts.set(part.id, part) const role = messageRoles.get(part.messageID) if (role === undefined) { const parts = pendingParts.get(part.messageID) ?? [] // A text or reasoning part carries its full text, so keep only its // latest update. Keeping each update holds every snapshot in memory. const index = isToolPart(part) ? -1 : parts.findIndex((pending) => pending.part.id === part.id) if (index === -1) parts.push({ part, delta }) else parts[index] = { part } pendingParts.set(part.messageID, parts) } else if (role === 'assistant') { yield* handlePart(part, delta) } } else if (event.type === 'todo.updated') { yield { type: EventType.CUSTOM, model, timestamp: now(), name: TODO_EVENT, value: { todos: event.properties.todos }, } } // session.idle / session.error are redundant with the terminal `done` // event and are ignored. The prompt of the session handle resolves only // after session.idle, so every part of the turn comes before `done`. } function* finish( message: OpencodeAssistantMessage, ): Generator { yield* startRun() // The final message is the assistant reply, so flush any parts that beat // its message.updated. OpenCode sends message.updated when it creates a // message, so parts of any other message still waiting here are dropped. yield* setMessageRole(message.id, 'assistant') yield* closeText() yield* closeReasoning() yield* synthesizeUnresolvedResults() const usage = turnUsage(message) const error = messageError(message) if (error) { yield { type: EventType.RUN_ERROR, model, timestamp: now(), message: error.message, error, ...(usage && { usage }), } return } const finishReason = message.finish === 'length' ? 'length' : 'stop' yield { type: EventType.RUN_FINISHED, runId, threadId, model, timestamp: now(), finishReason, ...(usage !== undefined && { usage }), } } try { for await (const streamEvent of events) { ctx.onStreamEvent?.(streamEvent) if (streamEvent.kind === 'session') { yield* startRun() yield { type: EventType.CUSTOM, model, timestamp: now(), name: SESSION_ID_EVENT, value: { sessionId: streamEvent.sessionId }, } } else if (streamEvent.kind === 'event') { yield* startRun() yield* handleEvent(streamEvent.event) } else { yield* finish(streamEvent.message) } } } catch (error) { // The run is dying (abort, server exit, or connection failure). Close any // open message and pair started tool calls with a synthetic result first // so the next request's pending-tool-call scan doesn't try to execute // them, then let the adapter surface the error as RUN_ERROR. yield* closeText() yield* closeReasoning() yield* synthesizeUnresolvedResults() throw error } }