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

provider.ts

193 lines6.3 KB

1import { APIError, Sandbox } from '@vercel/sandbox'
2import { VERCEL_CAPS, VercelHandle } from './handle'
3import type {
4 SandboxCapabilities,
5 SandboxCreateInput,
6 SandboxDestroyInput,
7 SandboxHandle,
8 SandboxProvider,
9 SandboxResumeInput,
10} from '@tanstack/ai-sandbox'
11​
12export interface VercelSandboxConfig {
13 /**
14 * Vercel access token. Falls back to the `VERCEL_TOKEN` / `VERCEL_OIDC_TOKEN`
15 * env vars (read by the SDK) when omitted.
16 */
17 token?: string
18 /** Vercel team id. Falls back to `VERCEL_TEAM_ID`. */
19 teamId?: string
20 /** Vercel project id. Falls back to `VERCEL_PROJECT_ID`. */
21 projectId?: string
22 /** Runtime image, e.g. `node24`, `node22`, `python3.13`. Defaults to `node24`. */
23 runtime?: string
24 /** Sandbox lifetime in milliseconds before it is stopped automatically. */
25 timeout?: number
26 /** Ports to expose; reachable from the host via `ports.connect(port)`. */
27 ports?: Array<number>
28 /**
29 * Create a persistent (named) sandbox that survives `stop()` and can be
30 * reconnected with `resume({ id })`. Defaults to false (ephemeral), in which
31 * case `resume` resolves null once the sandbox has stopped.
32 */
33 persistent?: boolean
34 /**
35 * Working directory inside the sandbox. The `/workspace` virtual root maps
36 * here. Defaults to `/vercel/sandbox`.
37 */
38 workdir?: string
40​
41const DEFAULT_WORKDIR = '/vercel/sandbox'
42const DEFAULT_RUNTIME = 'node24'
43const USER_AGENT_TOKEN = '@tanstack/ai'
44​
45export function withSandboxUserAgent(
46 inner: typeof globalThis.fetch = globalThis.fetch,
47): typeof globalThis.fetch {
48 return (input, init) => {
49 const headers = new Headers(init?.headers)
50 const existing = headers.get('user-agent')
51 headers.set(
52 'user-agent',
53 existing ? `${existing} ${USER_AGENT_TOKEN}` : USER_AGENT_TOKEN,
54 )
55 return inner(input, { ...init, headers })
56 }
58​
59/**
60 * True when `error` is the Vercel SDK's "directory already exists" failure — an
61 * {@link APIError} with HTTP 400 whose body reports an `EEXIST`-style message.
62 * Used to make the non-idempotent native `mkDir` safe to call on a workdir that
63 * may already exist (notably the default `/vercel/sandbox`).
64 */
65export function isDirAlreadyExistsError(error: unknown): boolean {
66 if (!(error instanceof APIError) || error.response.status !== 400)
67 return false
68 const json: unknown = error.json
69 const detail =
70 typeof json === 'object' &&
71 json !== null &&
72 'error' in json &&
73 typeof json.error === 'object' &&
74 json.error !== null &&
75 'message' in json.error &&
76 typeof json.error.message === 'string'
77 ? json.error.message
78 : error.message
79 return /exists/i.test(detail)
81​
82class VercelProvider implements SandboxProvider {
83 readonly name = 'vercel'
84​
85 private readonly fetch = withSandboxUserAgent()
86​
87 constructor(private readonly config: VercelSandboxConfig) {}
88​
89 capabilities(): SandboxCapabilities {
90 return VERCEL_CAPS
91 }
92​
93 private get workdir(): string {
94 return this.config.workdir ?? DEFAULT_WORKDIR
95 }
96​
97 private get ports(): Array<number> {
98 return this.config.ports ?? []
99 }
100​
101 /** Auth overrides shared by create/get/stop, omitting undefined fields. */
102 private auth(): { token?: string; teamId?: string; projectId?: string } {
103 const out: { token?: string; teamId?: string; projectId?: string } = {}
104 // Fall back to env when not set in config. We must resolve these ourselves:
105 // when given no explicit `token`, the Vercel SDK runs its OWN credential
106 // resolution, which PREFERS `VERCEL_OIDC_TOKEN` over the access-token path —
107 // so a stale/expired OIDC token wins and access-token auth never kicks in.
108 // Passing `token` explicitly forces access-token auth.
109 const token = this.config.token ?? process.env.VERCEL_TOKEN
110 const teamId = this.config.teamId ?? process.env.VERCEL_TEAM_ID
111 const projectId = this.config.projectId ?? process.env.VERCEL_PROJECT_ID
112 if (token) out.token = token
113 if (teamId) out.teamId = teamId
114 if (projectId) out.projectId = projectId
115 return out
116 }
117​
118 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
119 const sandbox = await Sandbox.create({
120 ...this.auth(),
121 fetch: this.fetch,
122 runtime: this.config.runtime ?? DEFAULT_RUNTIME,
123 ...(this.config.timeout !== undefined
124 ? { timeout: this.config.timeout }
125 : {}),
126 ...(this.ports.length ? { ports: this.ports } : {}),
127 ...(this.config.persistent !== undefined
128 ? { persistent: this.config.persistent }
129 : {}),
130 ...(input.env ? { env: input.env } : {}),
131 })
132 // Ensure the workspace dir exists via the native (cwd-independent) mkDir —
133 // running a command with a not-yet-existing `cwd` would fail, so we must not
134 // route this through the handle (which runs every command in `workdir`).
135 //
136 // The SDK's `mkDir` is NOT idempotent: it returns HTTP 400 (`file_error` /
137 // "File exists") when the target already exists, and the default workdir
138 // `/vercel/sandbox` ships in the runtime image — so a fresh sandbox already
139 // has it. Treat an "already exists" failure as success; rethrow anything else.
140 try {
141 await sandbox.mkDir(this.workdir)
142 } catch (error) {
143 if (!isDirAlreadyExistsError(error)) throw error
144 }
145 return new VercelHandle({
146 sandbox,
147 workdir: this.workdir,
148 ports: this.ports,
149 })
150 }
151​
152 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
153 try {
154 const sandbox = await Sandbox.get({
155 name: input.id,
156 ...this.auth(),
157 fetch: this.fetch,
158 })
159 return new VercelHandle({
160 sandbox,
161 workdir: this.workdir,
162 ports: this.ports,
163 })
164 } catch {
165 // Gone / not found / expired.
166 return null
167 }
168 }
169​
170 async destroy(input: SandboxDestroyInput): Promise<void> {
171 try {
172 const sandbox = await Sandbox.get({
173 name: input.id,
174 ...this.auth(),
175 fetch: this.fetch,
176 })
177 await sandbox.stop()
178 } catch {
179 // Already stopped / gone.
180 }
181 }
183​
184/**
185 * Vercel Sandbox provider — runs harness adapters inside isolated Vercel
186 * microVMs. Requires a Vercel access token (`config.token` or the
187 * `VERCEL_TOKEN` / `VERCEL_OIDC_TOKEN` env var) plus team/project scope.
188 */
189export function vercelSandbox(
190 config: VercelSandboxConfig = {},
191): SandboxProvider {
192 return new VercelProvider(config)