Open History to see the last commit
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
78}
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) }
89}
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 }
131}
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
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 threadId,
319 context: options.context,
320 emitCustomEvent: channel.emitCustomEvent,
321 ...(externalSignal ? { signal: externalSignal } : {}),
322 })
323 }
324
325 // Approval-requested events for `ask`-policy actions with no client
326 // decision yet, emitted after the stream so the client can approve + re-run.
327 const approvalRequests: Array<AdapterYieldChunk> = []
328
329 const queue = new AsyncQueue<OpencodeStreamEvent>()
330 const mode =
331 modelOptions?.permissionMode ??
332 this.adapterConfig.permissionMode ??
333 'default'
334 const permissionHandler: PermissionHandler =
335 this.adapterConfig.onPermissionRequest ??
336 ((request) => {
337 const result = resolveInteractivePermission(
338 request,
339 mode,
340 bridgedToolNames,
341 options.approvals,
342 )
343 if (result.approvalId !== undefined) {
344 approvalRequests.push(
345 buildApprovalRequestedEvent({
346 approvalId: result.approvalId,
347 title: result.title ?? request.title,
348 threadId,
349 runId,
350 detail: { provider: 'opencode' },
351 }),
352 )
353 }
354 return result.response
355 })
356
357 logger.request(
358 `activity=chat provider=opencode model=${this.model} sandbox=${sandbox.provider} messages=${options.messages.length} resume=${sessionId ?? 'none'}`,
359 { provider: 'opencode', model: this.model },
360 )
361
362 // `chat({ reasoning })` goes on the model's config entry.
363 const reasoningOptions = opencodeReasoningOptions(
364 modelID,
365 options.reasoning,
366 OPENCODE_MODEL_REASONING[this.model],
367 )
368 const serverEnv =
369 bridge || reasoningOptions
370 ? {
371 OPENCODE_CONFIG_CONTENT: JSON.stringify({
372 ...(bridge && {
373 mcp: {
374 [bridge.name]: {
375 type: 'remote',
376 url: bridge.url,
377 enabled: true,
378 headers: { Authorization: `Bearer ${bridge.token}` },
379 },
380 },
381 }),
382 ...(reasoningOptions && {
383 provider: {
384 [providerID]: {
385 models: { [modelID]: { options: reasoningOptions } },
386 },
387 },
388 }),
389 }),
390 }
391 : undefined
392
393 server = await startOpencodeServerInSandbox(sandbox, {
394 port: this.adapterConfig.port ?? DEFAULT_PORT,
395 ...(this.adapterConfig.hostname !== undefined && {
396 hostname: this.adapterConfig.hostname,
397 }),
398 cwd: directory,
399 ...(serverEnv ? { env: serverEnv } : {}),
400 ...(externalSignal ? { signal: externalSignal } : {}),
401 })
402
403 handle = await startOpencodeSession({
404 baseUrl: server.baseUrl,
405 // Forward the channel's auth headers (e.g. Daytona's preview token) so
406 // the host client can reach a token-gated preview proxy.
407 ...(server.headers !== undefined && { headers: server.headers }),
408 // NOTE: do NOT pass `directory` here. `directory` is the VIRTUAL sandbox
409 // path (e.g. `/workspace`); the server is already spawned with that as its
410 // cwd (the provider handle maps it to the real workdir — `/workspace`
411 // inside Docker, a host temp dir for local-process). Forwarding the
412 // virtual path to the host-side opencode HTTP API breaks local-process,
413 // where `/workspace` doesn't exist → the API stalls until the request
414 // times out. Omitting it makes opencode use the server's (correct) cwd.
415 providerID,
416 modelID,
417 ...(sessionId !== undefined && { resumeSessionId: sessionId }),
418 onEvent: (event) => queue.push({ kind: 'event', event }),
419 onPermissionRequest: permissionHandler,
420 onError: (error) => queue.fail(error),
421 })
422 const session = handle
423
424 if (externalSignal !== undefined) {
425 onAbort = () => void session.abort().catch(() => undefined)
426 if (externalSignal.aborted) onAbort()
427 else externalSignal.addEventListener('abort', onAbort, { once: true })
428 }
429
430 queue.push({ kind: 'session', sessionId: session.sessionId })
431
432 let promptText = this.applySystemPrompts(
433 options,
434 session.resumed || sessionId === undefined
435 ? resumePrompt
436 : buildPrompt(options.messages, undefined).prompt,
437 )
438 if (options.outputSchema) {
439 promptText = appendOutputSchemaInstruction(
440 promptText,
441 options.outputSchema,
442 )
443 }
444
445 let lastAssistantText = ''
446 session
447 .prompt(promptText)
448 .then(({ message, text }) => {
449 lastAssistantText = text
450 queue.push({ kind: 'done', message })
451 queue.end()
452 })
453 .catch((error: unknown) => queue.fail(error))
454
455 let heldFinished: AdapterYieldChunk | undefined
456 let lastTextMessageId: string | undefined
457 for await (const chunk of mergeChunkStreams(
458 translateOpencodeStream(queue, {
459 model: this.model,
460 runId,
461 threadId,
462 ...(options.parentRunId !== undefined && {
463 parentRunId: options.parentRunId,
464 }),
465 genId: () => this.generateId(),
466 bridgedToolNames,
467 onStreamEvent: (event) =>
468 logger.provider(`provider=opencode kind=${event.kind}`, {
469 chunk: event,
470 }),
471 }),
472 channel.stream,
473 )) {
474 if (options.outputSchema && chunk.type === EventType.RUN_FINISHED) {
475 heldFinished = chunk
476 continue
477 }
478 if (
479 chunk.type === EventType.TEXT_MESSAGE_START &&
480 typeof chunk.messageId === 'string' &&
481 chunk.messageId !== ''
482 ) {
483 lastTextMessageId = chunk.messageId
484 }
485 yield chunk
486 }
487
488 if (options.outputSchema) {
489 try {
490 const object = parseJsonFromAssistantText(lastAssistantText)
491 const messageId = lastTextMessageId ?? this.generateId()
492 yield structuredOutputStartChunk({
493 messageId,
494 model: this.model,
495 threadId,
496 runId,
497 })
498 yield structuredOutputCompleteChunk({
499 messageId,
500 model: this.model,
501 threadId,
502 runId,
503 object,
504 raw: lastAssistantText,
505 })
506 } catch (error: unknown) {
507 const message =
508 error instanceof Error
509 ? error.message
510 : 'Failed to parse structured output'
511 yield {
512 type: EventType.RUN_ERROR,
513 model: this.model,
514 timestamp: Date.now(),
515 message,
516 error: { message },
517 }
518 }
519 }
520 if (heldFinished) yield heldFinished
521
522 // Surface pending approval requests (ask-policy actions awaiting a client
523 // decision); the client approves and re-runs to continue.
524 for (const event of approvalRequests) yield event
525 } catch (error: unknown) {
526 const err = error as Error & { code?: string }
527 const rawEvent = toRunErrorRawEvent(error)
528 logger.errors('opencode.chatStream fatal', {
529 error,
530 source: 'opencode.chatStream',
531 })
532 yield {
533 type: EventType.RUN_ERROR,
534 model: options.model,
535 timestamp: Date.now(),
536 message: err.message || 'Unknown error occurred',
537 ...(err.code !== undefined && { code: err.code }),
538 ...(rawEvent !== undefined && { rawEvent }),
539 error: {
540 message: err.message || 'Unknown error occurred',
541 ...(err.code !== undefined && { code: err.code }),
542 },
543 }
544 } finally {
545 if (externalSignal !== undefined && onAbort !== undefined) {
546 externalSignal.removeEventListener('abort', onAbort)
547 }
548 channel.close()
549 // Each step gets a time limit: a step that never settles (a sandbox
550 // `kill()` that never returns, a bridge request held open) must not
551 // hold back RUN_FINISHED.
552 const bounded = (step: () => Promise<void> | undefined) =>
553 Promise.race([
554 Promise.resolve()
555 .then(step)
556 .catch((error: unknown) =>
557 logger.errors('opencode teardown failed', {
558 error,
559 source: 'opencode.chatStream',
560 }),
561 ),
562 new Promise<void>((resolve) =>
563 setTimeout(resolve, TEARDOWN_STEP_MS).unref?.(),
564 ),
565 ])
566 await bounded(() => handle?.dispose())
567 await bounded(() => server?.dispose())
568 await bounded(() => bridge?.close())
569 }
570 }
571
572 structuredOutput(
573 _options: StructuredOutputOptions<OpencodeTextProviderOptions>,
574 ): Promise<StructuredOutputResult<unknown>> {
575 return Promise.reject(
576 new Error(
577 'This harness honors outputSchema on chat() in the same turn. ' +
578 'Pass outputSchema to chat(), or use a model adapter for a one-shot extract.',
579 ),
580 )
581 }
582}
583
584/**
585 * Creates an OpenCode harness adapter that runs **inside a sandbox**.
586 *
587 * It declares `requires: [SandboxCapability]`, spawns `opencode serve` inside
588 * the sandbox provided by `withSandbox(...)`, exposes its port, and connects
589 * the `@opencode-ai/sdk` HTTP client to it. OpenCode owns the agent loop and
590 * executes its native tools against the sandbox workspace. The sandbox image
591 * must provide the `opencode` executable (Docker: also publish the server port
592 * via `publishPorts`). The chat() tools reach OpenCode through an MCP bridge.
593 */
594export function opencodeText<TModel extends OpencodeModel>(
595 model: TModel,
596 config: OpencodeTextConfig = {},
597): OpencodeTextAdapter<TModel> {
598 return new OpencodeTextAdapter(config, model)
599}