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