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

sandbox-server.ts

130 lines4.1 KB

1/**
2 * Boot an `opencode serve` HTTP server INSIDE a sandbox and expose its port so
3 * the host `@opencode-ai/sdk` client can connect over `baseUrl`. Mirrors the
4 * SDK's own server launch (`opencode serve --hostname=H --port=P`, ready when
5 * stdout logs `opencode server listening`).
6 */
7import type { SandboxHandle, SpawnHandle } from '@tanstack/ai-sandbox'
8​
9const READY_MARKER = 'opencode server listening'
10​
11export interface SandboxOpencodeServer {
12 /** URL the host uses to reach the in-sandbox server. */
13 baseUrl: string
14 /**
15 * Headers that authenticate requests to {@link baseUrl}, when the provider's
16 * channel is token-gated (e.g. Daytona's `x-daytona-preview-token`). The host
17 * opencode client must send these on every request or the preview proxy 404s.
18 */
19 headers?: Record<string, string>
20 /** Stop the server process. */
21 dispose: () => Promise<void>
23​
24export interface StartServerOptions {
25 port: number
26 hostname?: string
27 cwd: string
28 /** Extra env for the server process (e.g. `OPENCODE_CONFIG_CONTENT`). */
29 env?: Record<string, string>
30 timeoutMs?: number
31 signal?: AbortSignal
33​
34export async function startOpencodeServerInSandbox(
35 sandbox: SandboxHandle,
36 options: StartServerOptions,
37): Promise<SandboxOpencodeServer> {
38 const hostname = options.hostname ?? '0.0.0.0'
39 const command = `opencode serve --hostname=${hostname} --port=${options.port}`
40 const proc: SpawnHandle = await sandbox.process.spawn(command, {
41 cwd: options.cwd,
42 ...(options.env ? { env: options.env } : {}),
43 ...(options.signal ? { signal: options.signal } : {}),
44 })
45​
46 await waitForReady(proc, options.timeoutMs ?? 30_000)
47​
48 const channel = await sandbox.ports.connect(options.port)
49 // Carry the channel's auth so the host client can reach a token-gated preview.
50 // Prefer ready-made `headers`; fall back to a bearer token if that's all the
51 // provider issued.
52 const headers =
53 channel.headers ??
54 (channel.token ? { Authorization: `Bearer ${channel.token}` } : undefined)
55 return {
56 baseUrl: channel.url,
57 ...(headers ? { headers } : {}),
58 dispose: () => proc.kill(),
59 }
61​
62function waitForReady(proc: SpawnHandle, timeoutMs: number): Promise<void> {
63 return new Promise<void>((resolve, reject) => {
64 let stdout = ''
65 // Capture stderr too: opencode logs startup failures (e.g. "address already
66 // in use" when a previous run's server still holds the port) to stderr, not
67 // stdout. Without this the error message is empty and the real cause is lost.
68 let stderr = ''
69 // Holder object so reads stay typed as `boolean` across async closures
70 // (a plain `let` gets flow-narrowed to a literal and trips lint).
71 const state = { settled: false }
72 const settle = (fn: () => void): void => {
73 if (state.settled) return
74 state.settled = true
75 clearTimeout(timer)
76 fn()
77 }
78 const diagnostics = (): string =>
79 [stdout, stderr]
80 .map((s) => s.trim())
81 .filter(Boolean)
82 .join('\n')
83 .slice(-500)
84 const timer = setTimeout(
85 () =>
86 settle(() =>
87 reject(
88 new Error(
89 `opencode serve did not become ready within ${timeoutMs}ms${
90 diagnostics() ? `: ${diagnostics()}` : ''
91 }`,
92 ),
93 ),
94 ),
95 timeoutMs,
96 )
97​
98 // Drain stderr in the background so its text is available for diagnostics.
99 void (async () => {
100 try {
101 for await (const chunk of proc.stderr) stderr += chunk
102 } catch {
103 // Ignore: stderr drain errors are non-fatal; stdout drives readiness.
104 }
105 })()
106​
107 void (async () => {
108 try {
109 for await (const chunk of proc.stdout) {
110 stdout += chunk
111 if (stdout.includes(READY_MARKER)) {
112 settle(resolve)
113 return
114 }
115 }
116 settle(() =>
117 reject(
118 new Error(
119 `opencode serve exited before becoming ready${
120 diagnostics() ? `: ${diagnostics()}` : ' (no output)'
121 }`,
122 ),
123 ),
124 )
125 } catch (error) {
126 settle(() => reject(error))
127 }
128 })()
129 })