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

sandbox-server.ts

195 lines5.4 KB

1import { connectAcpWebSocket } from '../transport/websocket'
2import type {
3 SandboxChannel,
4 SandboxHandle,
5 SpawnHandle,
6} from '@tanstack/ai-sandbox'
7import type { AcpMessageFraming } from '../transport/types'
8import type { AcpWebSocketConnection } from '../transport/websocket'
9​
10export interface AcpSandboxServer {
11 /** WebSocket URL the orchestrator uses to reach the in-sandbox ACP server. */
12 wsUrl: string
13 /** Sandbox channel used to build {@link wsUrl} (auth headers, when issued). */
14 channel: SandboxChannel
15 /** Open the ACP JSON-RPC stream over WebSocket. */
16 connect: (signal?: AbortSignal) => Promise<AcpWebSocketConnection>
17 /** Stop the in-sandbox server process. */
18 dispose: () => Promise<void>
20​
21export interface StartAcpServerOptions {
22 port: number
23 cwd: string
24 /** Full shell command that starts the harness ACP server inside the sandbox. */
25 command: string
26 /** Build the WebSocket URL once the server is ready and the port is exposed. */
27 buildWsUrl: (input: {
28 channel: SandboxChannel
29 port: number
30 stdout: string
31 }) => string
32 /**
33 * Return true once {@link buildWsUrl} can be called. Receives accumulated
34 * stdout from the server process.
35 */
36 isReady?: (stdout: string) => boolean
37 /** Substring/regex marker used when {@link isReady} is omitted. */
38 readyMarker?: string
39 env?: Record<string, string>
40 timeoutMs?: number
41 signal?: AbortSignal
42 framing?: AcpMessageFraming
43 hostname?: string
45​
46const DEFAULT_READY_MARKER = 'WebSocket URL:'
47​
48function waitForReady(
49 proc: SpawnHandle,
50 options: Pick<StartAcpServerOptions, 'isReady' | 'readyMarker' | 'timeoutMs'>,
51): Promise<{ stdout: string; stderr: string }> {
52 const readyMarker = options.readyMarker ?? DEFAULT_READY_MARKER
53 const isReady =
54 options.isReady ?? ((output: string) => output.includes(readyMarker))
55​
56 return new Promise((resolve, reject) => {
57 let stdout = ''
58 let stderr = ''
59 const state = { settled: false }
60 const settle = (fn: () => void): void => {
61 if (state.settled) return
62 state.settled = true
63 clearTimeout(timer)
64 fn()
65 }
66 const diagnostics = (): string =>
67 [stdout, stderr]
68 .map((s) => s.trim())
69 .filter(Boolean)
70 .join('\n')
71 .slice(-500)
72 const combined = (): string => stdout + stderr
73 let stdoutDone = false
74 let stderrDone = false
75 const tryFinish = (): void => {
76 if (state.settled) return
77 if (isReady(combined())) {
78 settle(() => resolve({ stdout, stderr }))
79 return
80 }
81 if (stdoutDone && stderrDone) {
82 settle(() =>
83 reject(
84 new Error(
85 `ACP server exited before becoming ready${
86 diagnostics() ? `: ${diagnostics()}` : ' (no output)'
87 }`,
88 ),
89 ),
90 )
91 }
92 }
93​
94 const timer = setTimeout(
95 () =>
96 settle(() =>
97 reject(
98 new Error(
99 `ACP server did not become ready within ${options.timeoutMs ?? 30_000}ms${
100 diagnostics() ? `: ${diagnostics()}` : ''
101 }`,
102 ),
103 ),
104 ),
105 options.timeoutMs ?? 30_000,
106 )
107​
108 void (async () => {
109 try {
110 for await (const chunk of proc.stderr) {
111 stderr += chunk
112 tryFinish()
113 if (state.settled) return
114 }
115 } catch {
116 // non-fatal
117 } finally {
118 stderrDone = true
119 tryFinish()
120 }
121 })()
122​
123 void (async () => {
124 try {
125 for await (const chunk of proc.stdout) {
126 stdout += chunk
127 tryFinish()
128 if (state.settled) return
129 }
130 } catch (error) {
131 settle(() => reject(error))
132 return
133 } finally {
134 stdoutDone = true
135 tryFinish()
136 }
137 })()
138 })
140​
141/**
142 * Boot a harness ACP WebSocket server inside a sandbox and expose its port via
143 * {@link SandboxHandle.ports.connect}. Mirrors the `opencode serve` pattern.
144 */
145export async function startAcpServerInSandbox(
146 sandbox: SandboxHandle,
147 options: StartAcpServerOptions,
148): Promise<AcpSandboxServer> {
149 const proc = await sandbox.process.spawn(options.command, {
150 cwd: options.cwd,
151 ...(options.env ? { env: options.env } : {}),
152 ...(options.signal ? { signal: options.signal } : {}),
153 })
154​
155 const { stdout } = await waitForReady(proc, options)
156 const channel = await sandbox.ports.connect(options.port)
157 const wsUrl = options.buildWsUrl({
158 channel,
159 port: options.port,
160 stdout,
161 })
162​
163 const headers =
164 channel.headers ??
165 (channel.token ? { Authorization: `Bearer ${channel.token}` } : undefined)
166​
167 return {
168 wsUrl,
169 channel,
170 connect: (signal?: AbortSignal) =>
171 connectAcpWebSocket(wsUrl, {
172 ...(headers ? { headers } : {}),
173 ...(signal ? { signal } : {}),
174 framing: options.framing ?? 'frame',
175 }),
176 dispose: () => proc.kill(),
177 }
179​
180/** Parse a `WebSocket URL: ws://…` line printed by `grok agent serve`. */
181export function parseWebSocketUrlFromServeOutput(
182 output: string,
183): string | undefined {
184 const match = output.match(/WebSocket URL:\s*(ws\S+)/i)
185 return match?.[1]
187​
188/** Build a Grok `agent serve` WebSocket URL from a sandbox channel + secret. */
189export function buildGrokServeWebSocketUrl(
190 channelUrl: string,
191 secret: string,
192): string {
193 const wsBase = channelUrl.replace(/^http/i, 'ws').replace(/\/$/, '')
194 return `${wsBase}/ws?server-key=${encodeURIComponent(secret)}`