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

cli.ts

298 lines8.1 KB

1import { spawn } from 'node:child_process'
2​
3export interface SbxRunResult {
4 stdout: string
5 stderr: string
6 exitCode: number
7}
8​
9export interface SbxSpawnOptions {
10 onClose: (result: SbxRunResult) => void
11 onError: (error: Error) => void
12 onStdout?: (chunk: Buffer) => void
13 onStderr?: (chunk: Buffer) => void
14 signal?: AbortSignal
16​
17export type SbxSpawn = (
18 binary: string,
19 args: Array<string>,
20 opts: SbxSpawnOptions,
21) => { kill: () => void }
22​
23export interface SbxLsEntry {
24 name: string
25 status?: string
26 workspace?: string
28​
29const INSTALL_HELP =
30 'sbx is not on PATH. Install Docker Sandboxes: macOS `brew trust docker/tap` then `brew install docker/tap/sbx`; Windows enable HypervisorPlatform then `winget install -h Docker.sbx`; Linux `curl -fsSL https://get.docker.com | sudo REPO_ONLY=1 sh` then `apt-get install docker-sbx` and add your user to the kvm group. Then retry.'
31​
32const LOGIN_HELP =
33 'sbx is not logged in. Run `sbx login`, or in CI pipe a PAT to `sbx login --password-stdin`.'
34​
35export function defaultSpawn(
36 binary: string,
37 args: Array<string>,
38 opts: SbxSpawnOptions,
39): { kill: () => void } {
40 const child = spawn(binary, args, {
41 stdio: ['ignore', 'pipe', 'pipe'],
42 windowsHide: true,
43 })
44 const stdout: Array<Buffer> = []
45 const stderr: Array<Buffer> = []
46 child.stdout?.on('data', (chunk: Buffer) => {
47 stdout.push(chunk)
48 opts.onStdout?.(chunk)
49 })
50 child.stderr?.on('data', (chunk: Buffer) => {
51 stderr.push(chunk)
52 opts.onStderr?.(chunk)
53 })
54 const onAbort = (): void => {
55 child.kill()
56 }
57 const detach = (): void => {
58 if (opts.signal) opts.signal.removeEventListener('abort', onAbort)
59 }
60 child.on('error', (error) => {
61 detach()
62 opts.onError(error)
63 })
64 child.on('close', (code) => {
65 detach()
66 opts.onClose({
67 stdout: Buffer.concat(stdout).toString('utf8'),
68 stderr: Buffer.concat(stderr).toString('utf8'),
69 exitCode: code ?? 1,
70 })
71 })
72 if (opts.signal) {
73 opts.signal.addEventListener('abort', onAbort, { once: true })
74 if (opts.signal.aborted) child.kill()
75 }
76 return {
77 kill: () => {
78 detach()
79 child.kill()
80 },
81 }
83​
84export function mapSbxError(error: unknown, binary: string): Error {
85 if (
86 error &&
87 typeof error === 'object' &&
88 'code' in error &&
89 (error as { code?: string }).code === 'ENOENT'
90 ) {
91 return new Error(INSTALL_HELP)
92 }
93 if (error instanceof Error) return error
94 return new Error(`${binary} failed: ${String(error)}`)
96​
97const HOST_CLI_COMMANDS = new Set(['ls', 'create', 'policy', 'rm', 'ports'])
98​
99function isHostCliCommand(args: Array<string>): boolean {
100 const command = args[0]
101 return command !== undefined && HOST_CLI_COMMANDS.has(command)
103​
104function throwIfFailed(
105 result: SbxRunResult,
106 binary: string,
107 args: Array<string>,
108): SbxRunResult {
109 if (result.exitCode === 0) return result
110 const stderr = result.stderr.trim()
111 // Guest exec can print "unauthorized" on stderr. Only host CLI
112 // stderr on host commands is a login error. Never scan `exec`.
113 if (isHostCliCommand(args) && isLoginError(stderr.toLowerCase())) {
114 throw new Error(`${LOGIN_HELP}\n${stderr}`)
115 }
116 throw new Error(
117 stderr === ''
118 ? `${binary} ${args.join(' ')} exited ${result.exitCode}`
119 : stderr,
120 )
122​
123function isLoginError(text: string): boolean {
124 return (
125 text.includes('not logged in') ||
126 text.includes('not authenticated') ||
127 text.includes('unauthoriz') ||
128 text.includes('login required')
129 )
131​
132export async function runSbx(
133 args: Array<string>,
134 options: {
135 binary?: string
136 spawn?: SbxSpawn
137 signal?: AbortSignal
138 /** When true, return the raw result even on a non-zero exit. */
139 allowNonZero?: boolean
140 } = {},
141): Promise<SbxRunResult> {
142 const binary = options.binary ?? 'sbx'
143 const spawnFn = options.spawn ?? defaultSpawn
144 const result = await new Promise<SbxRunResult>((resolve, reject) => {
145 spawnFn(binary, args, {
146 ...(options.signal ? { signal: options.signal } : {}),
147 onClose: resolve,
148 onError: (error) => reject(mapSbxError(error, binary)),
149 })
150 })
151 if (options.allowNonZero) {
152 // Guest exec can print "unauthorized" on stdout. Only host CLI
153 // stderr on host commands is a login error. Never scan `exec`.
154 const stderr = result.stderr.trim()
155 if (isHostCliCommand(args) && isLoginError(stderr.toLowerCase())) {
156 throw new Error(`${LOGIN_HELP}\n${stderr}`)
157 }
158 return result
159 }
160 return throwIfFailed(result, binary, args)
162​
163export function runSbxStreaming(
164 args: Array<string>,
165 options: {
166 binary?: string
167 spawn?: SbxSpawn
168 signal?: AbortSignal
169 onStdout?: (chunk: Buffer) => void
170 onStderr?: (chunk: Buffer) => void
171 } = {},
172): {
173 wait: () => Promise<SbxRunResult>
174 kill: () => void
175} {
176 const binary = options.binary ?? 'sbx'
177 const spawnFn = options.spawn ?? defaultSpawn
178 let childKill: (() => void) | undefined
179 const wait = new Promise<SbxRunResult>((resolve, reject) => {
180 const handle = spawnFn(binary, args, {
181 ...(options.signal ? { signal: options.signal } : {}),
182 ...(options.onStdout ? { onStdout: options.onStdout } : {}),
183 ...(options.onStderr ? { onStderr: options.onStderr } : {}),
184 onClose: resolve,
185 onError: (error) => reject(mapSbxError(error, binary)),
186 })
187 childKill = handle.kill
188 })
189 return {
190 wait: () => wait,
191 kill: () => {
192 childKill?.()
193 },
194 }
196​
197function asRecord(value: unknown): Record<string, unknown> | null {
198 if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
199 return value as Record<string, unknown>
200 }
201 return null
203​
204function readEntry(value: unknown): SbxLsEntry | null {
205 const rec = asRecord(value)
206 if (!rec) return null
207 const name =
208 typeof rec.name === 'string'
209 ? rec.name
210 : typeof rec.Name === 'string'
211 ? rec.Name
212 : null
213 if (name === null) return null
214 const status =
215 typeof rec.status === 'string'
216 ? rec.status
217 : typeof rec.State === 'string'
218 ? rec.State
219 : typeof rec.state === 'string'
220 ? rec.state
221 : undefined
222 const workspace =
223 typeof rec.workspace === 'string'
224 ? rec.workspace
225 : typeof rec.Workspace === 'string'
226 ? rec.Workspace
227 : undefined
228 return {
229 name,
230 ...(status !== undefined ? { status } : {}),
231 ...(workspace !== undefined ? { workspace } : {}),
232 }
234​
235/**
236 * Real CLI: `sbx exec [flags] SANDBOX COMMAND`. Flags after the name are
237 * treated as the command, so `-w` / `-e` must come first.
238 */
239export function sbxExecArgs(
240 name: string,
241 command: string,
242 opts?: { cwd?: string; env?: Record<string, string> },
243): Array<string> {
244 const args = ['exec']
245 if (opts?.cwd) args.push('-w', opts.cwd)
246 for (const [key, value] of Object.entries(opts?.env ?? {})) {
247 args.push('-e', `${key}=${value}`)
248 }
249 args.push('--', name, 'sh', '-c', command)
250 return args
252​
253/**
254 * sandboxd may print a start banner before JSON (docker/sbx-releases#201).
255 * Walk every `{` / `[` until one slice parses.
256 */
257export function parseJsonAfterBanner(stdout: string): unknown {
258 let lastError: unknown
259 let sawStart = false
260 for (let i = 0; i < stdout.length; i++) {
261 const ch = stdout[i]
262 if (ch !== '{' && ch !== '[') continue
263 sawStart = true
264 try {
265 return JSON.parse(stdout.slice(i)) as unknown
266 } catch (error) {
267 lastError = error
268 }
269 }
270 if (!sawStart) {
271 throw new SyntaxError(
272 `sbx JSON: no object or array in: ${stdout.slice(0, 200)}`,
273 )
274 }
275 throw lastError instanceof Error
276 ? lastError
277 : new SyntaxError(`sbx JSON: ${stdout.slice(0, 200)}`)
279​
280export function parseSbxLs(stdout: string): Array<SbxLsEntry> {
281 const parsed = parseJsonAfterBanner(stdout)
282 const list = Array.isArray(parsed)
283 ? parsed
284 : (asRecord(parsed)?.sandboxes ??
285 asRecord(parsed)?.Sandboxes ??
286 asRecord(parsed)?.items)
287 if (!Array.isArray(list)) {
288 throw new Error(
289 `sbx ls --json: unexpected shape: ${stdout.trim().slice(0, 200)}`,
290 )
291 }
292 const entries: Array<SbxLsEntry> = []
293 for (const item of list) {
294 const entry = readEntry(item)
295 if (entry) entries.push(entry)
296 }
297 return entries