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

provider.ts

153 lines4.8 KB

1import { randomUUID } from 'node:crypto'
2import { SpritesClient } from './client'
3import { SPRITES_CAPS, SPRITE_DEFAULT_HTTP_PORT, SpritesHandle } from './handle'
4import type { SpriteUrlAuth } from './client'
5import type {
6 SandboxCapabilities,
7 SandboxCreateInput,
8 SandboxDestroyInput,
9 SandboxHandle,
10 SandboxProvider,
11 SandboxResumeInput,
12} from '@tanstack/ai-sandbox'
13​
14export interface SpritesSandboxConfig {
15 /**
16 * Sprites API token (`org/projectNumber/tokenId/secret`). Falls back to the
17 * `SPRITES_API_KEY` env var when omitted.
18 */
19 apiKey?: string
20 /**
21 * Sprites control-plane base URL. Falls back to `SPRITES_API_URL`, then
22 * `https://api.sprites.dev`.
23 */
24 apiUrl?: string
25 /**
26 * Working directory inside the Sprite. The `/workspace` virtual root maps
27 * here. Defaults to `/home/sprite`.
28 */
29 workdir?: string
30 /**
31 * URL auth mode for created Sprites. `'public'` (default) makes the Sprite's
32 * URL reachable without an org token — required to reach a service via
33 * `ports.connect()`. Use `'sprite'` to keep it org-token gated.
34 */
35 urlAuth?: SpriteUrlAuth
36 /** Internal port proxied to the public URL. Defaults to 8080. */
37 httpPort?: number
38 /** Block on fleet capacity instead of failing fast when creating a Sprite. */
39 waitForCapacity?: boolean
41​
42const DEFAULT_WORKDIR = '/home/sprite'
43const NAME_PREFIX = 'tanstack-ai'
44​
45class SpritesProvider implements SandboxProvider {
46 readonly name = 'sprites'
47 private readonly client: SpritesClient
48​
49 constructor(private readonly config: SpritesSandboxConfig) {
50 const apiKey = config.apiKey ?? process.env.SPRITES_API_KEY
51 if (!apiKey) {
52 throw new Error(
53 'Sprites API key is required. Pass `apiKey` or set the SPRITES_API_KEY environment variable.',
54 )
55 }
56 const baseUrl = config.apiUrl ?? process.env.SPRITES_API_URL
57 this.client = new SpritesClient({
58 apiKey,
59 ...(baseUrl ? { baseUrl } : {}),
60 })
61 }
62​
63 capabilities(): SandboxCapabilities {
64 return SPRITES_CAPS
65 }
66​
67 private get workdir(): string {
68 return this.config.workdir ?? DEFAULT_WORKDIR
69 }
70​
71 private get httpPort(): number {
72 return this.config.httpPort ?? SPRITE_DEFAULT_HTTP_PORT
73 }
74​
75 private get urlAuth(): SpriteUrlAuth {
76 return this.config.urlAuth ?? 'public'
77 }
78​
79 private handle(sprite: { name: string; url: string }): SpritesHandle {
80 return new SpritesHandle({
81 client: this.client,
82 name: sprite.name,
83 url: sprite.url,
84 workdir: this.workdir,
85 httpPort: this.httpPort,
86 urlAuth: this.urlAuth,
87 })
88 }
89​
90 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
91 // Honor the deterministic id ensure() supplies (see SandboxCreateInput.id).
92 // The sprite's preview URL is keyed by name, so a random name would strand
93 // an out-of-band reconnect (a preview iframe) on a different sprite than the
94 // one the agent edits. Fall back to a random name for direct/advanced use.
95 const name =
96 input.id ??
97 `${NAME_PREFIX}-${randomUUID().replace(/-/g, '').slice(0, 12)}`
98 const sprite = await this.client.createSprite(name, {
99 ...(this.config.waitForCapacity !== undefined
100 ? { waitForCapacity: this.config.waitForCapacity }
101 : {}),
102 ...(input.signal ? { signal: input.signal } : {}),
103 })
104​
105 if (sprite.urlAuth !== this.urlAuth) {
106 await this.client.setUrlAuth(sprite.name, this.urlAuth, input.signal)
107 }
108​
109 // Ensure the workspace dir exists before any cwd-bound command runs in it.
110 // Run from `/` (not the workdir, which does not exist yet) so the exec's own
111 // cwd resolution does not fail for a non-default `workdir`.
112 const mkdir = this.client.exec(sprite.name, {
113 argv: ['mkdir', '-p', this.workdir],
114 cwd: '/',
115 ...(input.signal ? { signal: input.signal } : {}),
116 })
117 const code = await mkdir.wait()
118 if (code !== 0) {
119 throw new Error(
120 `Sprites: failed to create workspace directory "${this.workdir}" (exit ${code}).`,
121 )
122 }
123​
124 const handle = this.handle(sprite)
125 if (input.env) await handle.env.set(input.env)
126 return handle
127 }
128​
129 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
130 try {
131 const sprite = await this.client.getSprite(input.id, input.signal)
132 return this.handle(sprite)
133 } catch {
134 // Gone / not found.
135 return null
136 }
137 }
138​
139 async destroy(input: SandboxDestroyInput): Promise<void> {
140 await this.client.deleteSprite(input.id, input.signal)
141 }
143​
144/**
145 * Sprites sandbox provider — runs harness adapters inside isolated Fly.io
146 * Sprite stateful sandboxes. Requires a Sprites API token (`config.apiKey` or
147 * the `SPRITES_API_KEY` env var).
148 */
149export function spritesSandbox(
150 config: SpritesSandboxConfig = {},
151): SandboxProvider {
152 return new SpritesProvider(config)