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

text.ts

598 lines21.6 KB

1import { EventType, normalizeSystemPrompts } from '@tanstack/ai'
2import {
3 appendOutputSchemaInstruction,
4 parseJsonFromAssistantText,
5 reasoningBudget,
6 resolveReasoning,
7 structuredOutputCompleteChunk,
8 structuredOutputStartChunk,
9 toRunErrorRawEvent,
10} from '@tanstack/ai/adapter-internals'
11import { BaseTextAdapter } from '@tanstack/ai/adapters'
12import {
13 DurableAttachNotSupportedError,
14 SandboxCapability,
15 buildApprovalRequestedEvent,
16 createBridgeEventChannel,
17 getSandbox,
18 getSandboxDurability,
19 getToolBridgeProvisioner,
20 getWorkspaceProjection,
21 mergeChunkStreams,
22 nodeHttpBridgeProvisioner,
23 resolveDurableRunId,
24} from '@tanstack/ai-sandbox'
25import { buildPrompt } from '../messages/prompt'
26import { startOpencodeSession } from '../process/server'
27import { startOpencodeServerInSandbox } from '../process/sandbox-server'
28import { resolveInteractivePermission } from '../process/permissions'
29import { AsyncQueue } from '../stream/queue'
30import { translateOpencodeStream } from '../stream/translate'
31import { projectOpencodeWorkspace } from './projection'
32import { OPENCODE_MODEL_REASONING } from '../model-meta'
33import type { HostToolBridge, SandboxHandle } from '@tanstack/ai-sandbox'
34import type {
35 StructuredOutputOptions,
36 StructuredOutputResult,
37} from '@tanstack/ai/adapters'
38import type {
39 DefaultMessageMetadataByModality,
40 Modality,
41 ModelReasoning,
42 AdapterYieldChunk,
43 ReasoningRequest,
44 TextOptions,
45} from '@tanstack/ai'
46import type { OpencodeSessionHandle } from '../process/server'
47import type {
48 OpencodePermissionMode,
49 PermissionHandler,
50} from '../process/permissions'
51import type { OpencodeStreamEvent } from '../stream/sdk-types'
52import type { OpencodeModel, OpenCodeModelReasoningByName } from '../model-meta'
53import type { OpencodeTextProviderOptions } from '../provider-options'
54​
55const DEFAULT_WORKDIR = '/workspace'
56const DEFAULT_PORT = 4096
57const TEARDOWN_STEP_MS = 1000
58​
59export interface OpencodeTextConfig {
60 /** Working directory inside the sandbox. Defaults to `/workspace`. */
61 directory?: string
62 /**
63 * Port the in-sandbox `opencode serve` listens on. Defaults to 4096. For the
64 * Docker provider this port must also be published (`publishPorts: [4096]`)
65 * so the host can reach it.
66 */
67 port?: number
68 /** Hostname the in-sandbox server binds. Defaults to `0.0.0.0`. */
69 hostname?: string
70 /**
71 * OpenCode permission mode driving the dynamic permission handler. Defaults
72 * to `'default'`; set `'acceptEdits'` / `'bypassPermissions'` to let the
73 * harness edit files and run commands autonomously inside the sandbox.
74 */
75 permissionMode?: OpencodePermissionMode
76 /** Custom permission handler; replaces the adapter's default policy. */
77 onPermissionRequest?: PermissionHandler
79​
80/** Split a `provider/model` id into its provider and model halves. */
81function splitModel(model: string): { providerID: string; modelID: string } {
82 const slash = model.indexOf('/')
83 if (slash <= 0 || slash === model.length - 1) {
84 throw new Error(
85 `OpenCode models must be addressed as "provider/model" (e.g. "anthropic/claude-sonnet-4-5"); received "${model}".`,
86 )
87 }
88 return { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) }
90​
91/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
92type ResolveReasoning<TModel extends string> =
93 TModel extends keyof OpenCodeModelReasoningByName
94 ? OpenCodeModelReasoningByName[TModel]
95 : never
96​
97/**
98 * OpenCode's per-model `options` for `chat({ reasoning })`, as its config docs
99 * show them: Claude takes `thinking` with a token budget (pi's table when the
100 * request sets none), other models take `reasoningEffort` and
101 * `reasoningSummary`.
102 */
103export function opencodeReasoningOptions(
104 modelID: string,
105 request: ReasoningRequest | undefined,
106 reasoning: ModelReasoning | undefined,
107): Record<string, unknown> | undefined {
108 const resolved = resolveReasoning(request, reasoning)
109 if (!resolved) return undefined
110 if (modelID.includes('claude')) {
111 if (resolved.level === 'off') return { thinking: { type: 'disabled' } }
112 return {
113 thinking: {
114 type: 'enabled',
115 budgetTokens: reasoningBudget({
116 level: resolved.level,
117 summary: resolved.summary,
118 ...(resolved.budgetTokens !== undefined
119 ? { budgetTokens: resolved.budgetTokens }
120 : {}),
121 }),
122 },
123 }
124 }
125 return {
126 reasoningEffort: resolved.value,
127 ...(resolved.summary && resolved.level !== 'off'
128 ? { reasoningSummary: 'auto' }
129 : {}),
130 }
132​
133export class OpencodeTextAdapter<
134 TModel extends OpencodeModel,
135> extends BaseTextAdapter<
136 TModel,
137 OpencodeTextProviderOptions,
138 ReadonlyArray<Modality> & readonly ['text'],
139 DefaultMessageMetadataByModality,
140 ReadonlyArray<string>,
141 unknown,
142 never,
143 ResolveReasoning<TModel>
144> {
145 readonly name = 'opencode' as const
146​
147 override readonly requires = [SandboxCapability] as const
148​
149 private readonly adapterConfig: OpencodeTextConfig
150​
151 /** `toolChoice` warnings that this instance already logged. */
152 private readonly toolChoiceWarnings = new Set<string>()
153​
154 constructor(config: OpencodeTextConfig, model: TModel) {
155 super({}, model)
156 this.adapterConfig = config
157 }
158​
159 /**
160 * The chat() tools to bridge for `toolChoice`: none for `'none'`, and only
161 * the named tool for `{ type: 'tool', name }`. OpenCode cannot force a tool
162 * call, so every value except `'auto'` logs a warning once.
163 *
164 * ponytail: the built-in tools stay on. The `tools` field of
165 * `session.prompt` is deprecated in opencode, and the server stores it as
166 * the permission rules of the session, so a later call on a resumed session
167 * keeps the limit. Use session permissions if this must change.
168 */
169 private toolsForChoice(options: TextOptions<OpencodeTextProviderOptions>) {
170 const { toolChoice, tools = [] } = options
171 if (toolChoice === undefined || toolChoice === 'auto') return tools
172 const warning =
173 toolChoice === 'required'
174 ? "opencode: toolChoice 'required' is not supported. The agent decides which tools to call."
175 : 'opencode: toolChoice limits only the chat() tools. The built-in OpenCode tools stay on.'
176 if (!this.toolChoiceWarnings.has(warning)) {
177 this.toolChoiceWarnings.add(warning)
178 options.logger.warn(warning)
179 }
180 if (toolChoice === 'none') return []
181 if (toolChoice === 'required') return tools
182 return tools.filter((tool) => tool.name === toolChoice.name)
183 }
184​
185 private sandboxFrom(
186 options: TextOptions<OpencodeTextProviderOptions>,
187 ): SandboxHandle {
188 const ctx = options.capabilities
189 if (!ctx) {
190 throw new Error(
191 'Adapter "opencode" requires a sandbox. Add withSandbox(defineSandbox({ ... })) to chat() middleware.',
192 )
193 }
194 return getSandbox(ctx)
195 }
196​
197 supportsCombinedToolsAndSchema(): boolean {
198 return true
199 }
200​
201 combinedStructuredOutputSource(): 'event' {
202 return 'event'
203 }
204​
205 private applySystemPrompts(
206 options: TextOptions<OpencodeTextProviderOptions>,
207 prompt: string,
208 ): string {
209 const systemPrompts = normalizeSystemPrompts(options.systemPrompts)
210 .map((systemPrompt) => systemPrompt.content)
211 .filter((content) => content.trim() !== '')
212 if (systemPrompts.length === 0) return prompt
213 return `${systemPrompts.join('\n\n')}\n\n${prompt}`
214 }
215​
216 async *chatStream(
217 options: TextOptions<OpencodeTextProviderOptions>,
218 ): AsyncIterable<AdapterYieldChunk> {
219 const { logger } = options
220 let server:
221 | Awaited<ReturnType<typeof startOpencodeServerInSandbox>>
222 | undefined
223 let handle: OpencodeSessionHandle | undefined
224 let bridge: HostToolBridge | undefined
225 const externalSignal =
226 options.abortController?.signal ?? options.request?.signal ?? undefined
227 let onAbort: (() => void) | undefined
228 // This adapter does not journal yet, so a generated id is still fine.
229 // Routed through the helper anyway so journaling here inherits the
230 // caller-supplied-runId requirement instead of re-deriving it.
231 const runId = resolveDurableRunId(options.runId, {
232 durable: false,
233 adapter: 'opencode',
234 fallback: () => this.generateId(),
235 })
236 const threadId = options.threadId ?? this.generateId()
237 // Surfaces custom events from bridged tools (e.g. code mode console logs)
238 // on this run's live output stream.
239 const channel = createBridgeEventChannel({
240 model: this.model,
241 threadId,
242 runId,
243 })
244​
245 try {
246 const tools = this.toolsForChoice(options)
247 const sandbox = this.sandboxFrom(options)
248 const directory =
249 options.modelOptions?.directory ??
250 this.adapterConfig.directory ??
251 DEFAULT_WORKDIR
252​
253 // Durability wired onto a path that cannot deliver it. Two outcomes, split
254 // by whether a first attempt has already run.
255 //
256 // ATTACH is fatal. `sandboxRunDriver`'s `drive()` sets `attach: true` only
257 // when a previous host was already streaming this run, so continuing past
258 // here reaches `startOpencodeServerInSandbox` + the session prompt and
259 // re-runs the agent from scratch against the workspace that attempt
260 // already mutated, appending its whole output to a log that still holds
261 // the first attempt's. This adapter has no journal to tail, no
262 // `awaitAttachableJournal` to refuse the attach up front, and no
263 // `alignedIfAttaching` to suppress the already-delivered prefix — so there
264 // is nothing between here and that corruption except this throw.
265 //
266 // A FRESH durable run only fails to be recoverable LATER, which an app may
267 // knowingly accept (it can wire `withSandbox({ runs, durability })` once at
268 // the middleware level and still route some runs through this adapter). So
269 // that is a warn, not a throw: audible, not fatal. Once per run, not per
270 // chunk — a per-chunk warning would be worse than none. Mirrors
271 // `ai-grok-build`'s `chatStreamAcp`.
272 const durability = options.capabilities
273 ? getSandboxDurability(options.capabilities, { optional: true })
274 : undefined
275 if (durability !== undefined) {
276 if (durability.attach) {
277 throw new DurableAttachNotSupportedError(
278 'opencode',
279 'this adapter drives the harness over the opencode HTTP server ' +
280 'and does not journal',
281 )
282 }
283 logger.warn(
284 'opencode: sandbox durability is wired but this adapter never ' +
285 'journals — this run will not be recoverable on reconnect. Use a ' +
286 'journaling harness adapter for runs that must survive a host ' +
287 'restart, or drop durability if these runs are not meant to.',
288 { runId, adapter: 'opencode' },
289 )
290 }
291​
292 // Project workspace skills / MCP servers into the sandbox before starting
293 // the opencode server so the workspace config is in place for the session.
294 if (options.capabilities !== undefined) {
295 const projection = getWorkspaceProjection(options.capabilities, {
296 optional: true,
297 })
298 if (projection !== undefined) {
299 await projectOpencodeWorkspace(sandbox, projection)
300 }
301 }
302​
303 const modelOptions = options.modelOptions
304 const sessionId = modelOptions?.sessionId
305 const { prompt: resumePrompt } = buildPrompt(options.messages, sessionId)
306 const { providerID, modelID } = splitModel(this.model)
307​
308 // Bridge chat()-provided tools into the in-sandbox server over MCP
309 // (configured via OPENCODE_CONFIG_CONTENT at server spawn).
310 const bridgedToolNames = new Set(tools.map((tool) => tool.name))
311 if (tools.length > 0) {
312 const provisioner =
313 (options.capabilities
314 ? getToolBridgeProvisioner(options.capabilities, { optional: true })
315 : undefined) ?? nodeHttpBridgeProvisioner
316 bridge = await provisioner.provision(tools, {
317 provider: sandbox.provider,
318 context: options.context,
319 emitCustomEvent: channel.emitCustomEvent,
320 ...(externalSignal ? { signal: externalSignal } : {}),
321 })
322 }
323​
324 // Approval-requested events for `ask`-policy actions with no client
325 // decision yet, emitted after the stream so the client can approve + re-run.
326 const approvalRequests: Array<AdapterYieldChunk> = []
327​
328 const queue = new AsyncQueue<OpencodeStreamEvent>()
329 const mode =
330 modelOptions?.permissionMode ??
331 this.adapterConfig.permissionMode ??
332 'default'
333 const permissionHandler: PermissionHandler =
334 this.adapterConfig.onPermissionRequest ??
335 ((request) => {
336 const result = resolveInteractivePermission(
337 request,
338 mode,
339 bridgedToolNames,
340 options.approvals,
341 )
342 if (result.approvalId !== undefined) {
343 approvalRequests.push(
344 buildApprovalRequestedEvent({
345 approvalId: result.approvalId,
346 title: result.title ?? request.title,
347 threadId,
348 runId,
349 detail: { provider: 'opencode' },
350 }),
351 )
352 }
353 return result.response
354 })
355​
356 logger.request(
357 `activity=chat provider=opencode model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${sessionId ?? 'none'}`,
358 { provider: 'opencode', model: this.model },
359 )
360​
361 // `chat({ reasoning })` goes on the model's config entry.
362 const reasoningOptions = opencodeReasoningOptions(
363 modelID,
364 options.reasoning,
365 OPENCODE_MODEL_REASONING[this.model],
366 )
367 const serverEnv =
368 bridge || reasoningOptions
369 ? {
370 OPENCODE_CONFIG_CONTENT: JSON.stringify({
371 ...(bridge && {
372 mcp: {
373 [bridge.name]: {
374 type: 'remote',
375 url: bridge.url,
376 enabled: true,
377 headers: { Authorization: `Bearer ${bridge.token}` },
378 },
379 },
380 }),
381 ...(reasoningOptions && {
382 provider: {
383 [providerID]: {
384 models: { [modelID]: { options: reasoningOptions } },
385 },
386 },
387 }),
388 }),
389 }
390 : undefined
391​
392 server = await startOpencodeServerInSandbox(sandbox, {
393 port: this.adapterConfig.port ?? DEFAULT_PORT,
394 ...(this.adapterConfig.hostname !== undefined && {
395 hostname: this.adapterConfig.hostname,
396 }),
397 cwd: directory,
398 ...(serverEnv ? { env: serverEnv } : {}),
399 ...(externalSignal ? { signal: externalSignal } : {}),
400 })
401​
402 handle = await startOpencodeSession({
403 baseUrl: server.baseUrl,
404 // Forward the channel's auth headers (e.g. Daytona's preview token) so
405 // the host client can reach a token-gated preview proxy.
406 ...(server.headers !== undefined && { headers: server.headers }),
407 // NOTE: do NOT pass `directory` here. `directory` is the VIRTUAL sandbox
408 // path (e.g. `/workspace`); the server is already spawned with that as its
409 // cwd (the provider handle maps it to the real workdir — `/workspace`
410 // inside Docker, a host temp dir for local-process). Forwarding the
411 // virtual path to the host-side opencode HTTP API breaks local-process,
412 // where `/workspace` doesn't exist → the API stalls until the request
413 // times out. Omitting it makes opencode use the server's (correct) cwd.
414 providerID,
415 modelID,
416 ...(sessionId !== undefined && { resumeSessionId: sessionId }),
417 onEvent: (event) => queue.push({ kind: 'event', event }),
418 onPermissionRequest: permissionHandler,
419 onError: (error) => queue.fail(error),
420 })
421 const session = handle
422​
423 if (externalSignal !== undefined) {
424 onAbort = () => void session.abort().catch(() => undefined)
425 if (externalSignal.aborted) onAbort()
426 else externalSignal.addEventListener('abort', onAbort, { once: true })
427 }
428​
429 queue.push({ kind: 'session', sessionId: session.sessionId })
430​
431 let promptText = this.applySystemPrompts(
432 options,
433 session.resumed || sessionId === undefined
434 ? resumePrompt
435 : buildPrompt(options.messages, undefined).prompt,
436 )
437 if (options.outputSchema) {
438 promptText = appendOutputSchemaInstruction(
439 promptText,
440 options.outputSchema,
441 )
442 }
443​
444 let lastAssistantText = ''
445 session
446 .prompt(promptText)
447 .then(({ message, text }) => {
448 lastAssistantText = text
449 queue.push({ kind: 'done', message })
450 queue.end()
451 })
452 .catch((error: unknown) => queue.fail(error))
453​
454 let heldFinished: AdapterYieldChunk | undefined
455 let lastTextMessageId: string | undefined
456 for await (const chunk of mergeChunkStreams(
457 translateOpencodeStream(queue, {
458 model: this.model,
459 runId,
460 threadId,
461 ...(options.parentRunId !== undefined && {
462 parentRunId: options.parentRunId,
463 }),
464 genId: () => this.generateId(),
465 bridgedToolNames,
466 onStreamEvent: (event) =>
467 logger.provider(`provider=opencode kind=${event.kind}`, {
468 chunk: event,
469 }),
470 }),
471 channel.stream,
472 )) {
473 if (options.outputSchema && chunk.type === EventType.RUN_FINISHED) {
474 heldFinished = chunk
475 continue
476 }
477 if (
478 chunk.type === EventType.TEXT_MESSAGE_START &&
479 typeof chunk.messageId === 'string' &&
480 chunk.messageId !== ''
481 ) {
482 lastTextMessageId = chunk.messageId
483 }
484 yield chunk
485 }
486​
487 if (options.outputSchema) {
488 try {
489 const object = parseJsonFromAssistantText(lastAssistantText)
490 const messageId = lastTextMessageId ?? this.generateId()
491 yield structuredOutputStartChunk({
492 messageId,
493 model: this.model,
494 threadId,
495 runId,
496 })
497 yield structuredOutputCompleteChunk({
498 messageId,
499 model: this.model,
500 threadId,
501 runId,
502 object,
503 raw: lastAssistantText,
504 })
505 } catch (error: unknown) {
506 const message =
507 error instanceof Error
508 ? error.message
509 : 'Failed to parse structured output'
510 yield {
511 type: EventType.RUN_ERROR,
512 model: this.model,
513 timestamp: Date.now(),
514 message,
515 error: { message },
516 }
517 }
518 }
519 if (heldFinished) yield heldFinished
520​
521 // Surface pending approval requests (ask-policy actions awaiting a client
522 // decision); the client approves and re-runs to continue.
523 for (const event of approvalRequests) yield event
524 } catch (error: unknown) {
525 const err = error as Error & { code?: string }
526 const rawEvent = toRunErrorRawEvent(error)
527 logger.errors('opencode.chatStream fatal', {
528 error,
529 source: 'opencode.chatStream',
530 })
531 yield {
532 type: EventType.RUN_ERROR,
533 model: options.model,
534 timestamp: Date.now(),
535 message: err.message || 'Unknown error occurred',
536 ...(err.code !== undefined && { code: err.code }),
537 ...(rawEvent !== undefined && { rawEvent }),
538 error: {
539 message: err.message || 'Unknown error occurred',
540 ...(err.code !== undefined && { code: err.code }),
541 },
542 }
543 } finally {
544 if (externalSignal !== undefined && onAbort !== undefined) {
545 externalSignal.removeEventListener('abort', onAbort)
546 }
547 channel.close()
548 // Each step gets a time limit: a step that never settles (a sandbox
549 // `kill()` that never returns, a bridge request held open) must not
550 // hold back RUN_FINISHED.
551 const bounded = (step: () => Promise<void> | undefined) =>
552 Promise.race([
553 Promise.resolve()
554 .then(step)
555 .catch((error: unknown) =>
556 logger.errors('opencode teardown failed', {
557 error,
558 source: 'opencode.chatStream',
559 }),
560 ),
561 new Promise<void>((resolve) =>
562 setTimeout(resolve, TEARDOWN_STEP_MS).unref?.(),
563 ),
564 ])
565 await bounded(() => handle?.dispose())
566 await bounded(() => server?.dispose())
567 await bounded(() => bridge?.close())
568 }
569 }
570​
571 structuredOutput(
572 _options: StructuredOutputOptions<OpencodeTextProviderOptions>,
573 ): Promise<StructuredOutputResult<unknown>> {
574 return Promise.reject(
575 new Error(
576 'This harness honors outputSchema on chat() in the same turn. ' +
577 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
578 ),
579 )
580 }
582​
583/**
584 * Creates an OpenCode harness adapter that runs **inside a sandbox**.
585 *
586 * It declares `requires: [SandboxCapability]`, spawns `opencode serve` inside
587 * the sandbox provided by `withSandbox(...)`, exposes its port, and connects
588 * the `@opencode-ai/sdk` HTTP client to it. OpenCode owns the agent loop and
589 * executes its native tools against the sandbox workspace. The sandbox image
590 * must provide the `opencode` executable (Docker: also publish the server port
591 * via `publishPorts`). The chat() tools reach OpenCode through an MCP bridge.
592 */
593export function opencodeText<TModel extends OpencodeModel>(
594 model: TModel,
595 config: OpencodeTextConfig = {},
596): OpencodeTextAdapter<TModel> {
597 return new OpencodeTextAdapter(config, model)