Open History to see the last commit
1import { base64ToUint8Array, generateId } from '@tanstack/ai-utils'
2import type {
3 ComputerDriver,
4 ComputerDriverFactory,
5 MouseButton,
6} from '@tanstack/ai-computer-use'
7import type { SandboxHandle, SandboxProvider } from '@tanstack/ai-sandbox'
8
9/** Options for {@link createSandboxComputerDriver}. */
10export interface SandboxComputerDriverOptions {
11 /** The sandbox to control. The driver does not create or destroy it. */
12 sandbox: Pick<SandboxHandle, 'process'>
13 /**
14 * The screen size in pixels when the driver starts the display. When a
15 * display already runs, the driver uses its size. The default is
16 * `{ width: 1024, height: 768 }`.
17 */
18 display?: { width: number; height: number }
19}
20
21/** Options for {@link sandboxComputer}. */
22export interface SandboxComputerOptions {
23 /** Creates one sandbox for each thread, like `e2bSandbox({ template: 'desktop' })`. */
24 provider: SandboxProvider
25 /** The screen size in pixels. The default is `{ width: 1024, height: 768 }`. */
26 display?: { width: number; height: number }
27}
28
29const DEFAULT_DISPLAY = { width: 1024, height: 768 }
30
31/** Every command runs against this X display. */
32const X = 'DISPLAY=:0'
33
34/** `KeyboardEvent.key` names that differ from the xdotool names. Other names pass through. */
35const XDOTOOL_KEYS: Record<string, string> = {
36 Control: 'ctrl',
37 Shift: 'shift',
38 Alt: 'alt',
39 Meta: 'super',
40 Enter: 'Return',
41 Backspace: 'BackSpace',
42 ArrowLeft: 'Left',
43 ArrowRight: 'Right',
44 ArrowUp: 'Up',
45 ArrowDown: 'Down',
46 PageUp: 'Page_Up',
47 PageDown: 'Page_Down',
48 CapsLock: 'Caps_Lock',
49 ' ': 'space',
50 '+': 'plus',
51}
52
53/** xdotool button numbers. */
54const BUTTONS: Record<MouseButton, number> = {
55 left: 1,
56 middle: 2,
57 right: 3,
58 back: 8,
59 forward: 9,
60}
61
62// ponytail: one scroll click is 100 px. Fine steps below 100 px round to one click.
63const PIXELS_PER_SCROLL_CLICK = 100
64
65// ponytail: same chunking and delay as `@e2b/desktop` write. Long xdotool
66// type calls drop characters. Lower the delay if typing is too slow.
67const TYPE_CHUNK = 25
68const TYPE_DELAY_MS = 75
69
70function toXdotoolKey(key: string) {
71 return XDOTOOL_KEYS[key] ?? key
72}
73
74/** Quote one value for a POSIX shell. The model picks key names and text, so they never reach the shell raw. */
75function quote(value: string) {
76 return `'${value.replaceAll("'", `'"'"'`)}'`
77}
78
79function int(value: number) {
80 if (!Number.isInteger(value)) {
81 throw new Error(`Expected an integer, got ${value}`)
82 }
83 return value
84}
85
86function scrollClicks(pixels: number) {
87 return Math.max(1, Math.round(Math.abs(pixels) / PIXELS_PER_SCROLL_CLICK))
88}
89
90function moveTo(x: number, y: number) {
91 return `mousemove ${Math.round(x)} ${Math.round(y)}`
92}
93
94/**
95 * Create a driver for a Linux desktop in a sandbox from `@tanstack/ai-sandbox`.
96 *
97 * The image must have `xdotool`, `xdpyinfo`, and `scrot` or ImageMagick
98 * `import`. When no X display
99 * runs on `:0`, the driver starts `Xvfb`, and `startxfce4` when the image has
100 * it. The E2B `desktop` template has all of these.
101 */
102export async function createSandboxComputerDriver({
103 sandbox,
104 display: size = DEFAULT_DISPLAY,
105}: SandboxComputerDriverOptions) {
106 async function run(command: string) {
107 const result = await sandbox.process.exec(command)
108 if (result.exitCode !== 0) {
109 throw new Error(
110 `Sandbox command failed with exit code ${result.exitCode}: ${command}\n${result.stderr}`,
111 )
112 }
113 return result.stdout
114 }
115 const xdotool = (args: string) => run(`${X} xdotool ${args}`)
116
117 // Prints each missing tool. `@import` means no scrot, but ImageMagick
118 // `import` takes the screenshots, like on Amazon Linux.
119 const found = (
120 await run(
121 'for t in xdotool xdpyinfo; do command -v $t >/dev/null || echo $t; done; command -v scrot >/dev/null || { command -v import >/dev/null && echo @import || echo scrot; }',
122 )
123 )
124 .trim()
125 .split(/\s+/)
126 .filter(Boolean)
127 const missing = found.filter((tool) => tool !== '@import')
128 if (missing.length > 0) {
129 throw new Error(
130 `The sandbox has no desktop tools: ${missing.join(', ')}. Use a desktop image, like the E2B "desktop" template.`,
131 )
132 }
133 const capture = found.includes('@import')
134 ? 'import -window root'
135 : 'scrot --pointer'
136
137 const running = await sandbox.process.exec(`${X} xdpyinfo >/dev/null 2>&1`)
138 if (running.exitCode !== 0) {
139 // Output goes to /dev/null, so no provider buffer fills up.
140 await sandbox.process.spawn(
141 `Xvfb :0 -ac -screen 0 ${int(size.width)}x${int(size.height)}x24 -nolisten tcp >/dev/null 2>&1`,
142 )
143 await run(
144 `for i in $(seq 50); do ${X} xdpyinfo >/dev/null 2>&1 && exit 0; sleep 0.2; done; echo 'Xvfb did not start' >&2; exit 1`,
145 )
146 // ponytail: no wait for the session. Early screenshots can show an empty
147 // screen, and the model takes another one.
148 await sandbox.process.spawn(
149 `command -v startxfce4 >/dev/null && ${X} startxfce4 >/dev/null 2>&1`,
150 )
151 }
152
153 const info = await run(`${X} xdpyinfo`)
154 const match = /dimensions:\s+(\d+)x(\d+)/.exec(info)
155 if (!match) {
156 throw new Error('Could not read the screen size from xdpyinfo.')
157 }
158
159 const driver = {
160 display: { width: Number(match[1]), height: Number(match[2]) },
161 environment: 'linux',
162 async screenshot() {
163 const file = `/tmp/${generateId('tanstack-screenshot')}.png`
164 // One round trip: capture, print as base64, delete. Not `status`: zsh
165 // (the Daytona shell) makes it read-only.
166 const base64 = await run(
167 `${X} ${capture} ${file} && base64 -w0 ${file}; code=$?; rm -f ${file}; exit $code`,
168 )
169 return base64ToUint8Array(base64.trim())
170 },
171 async click(x, y, { button, count }) {
172 await xdotool(
173 `${moveTo(x, y)} click --repeat ${int(count)} ${BUTTONS[button]}`,
174 )
175 },
176 async move(x, y) {
177 await xdotool(moveTo(x, y))
178 },
179 async mouseDown(button) {
180 await xdotool(`mousedown ${BUTTONS[button]}`)
181 },
182 async mouseUp(button) {
183 await xdotool(`mouseup ${BUTTONS[button]}`)
184 },
185 async scroll(x, y, deltaX, deltaY) {
186 // xdotool buttons 4 and 5 scroll up and down, 6 and 7 left and right.
187 let args = moveTo(x, y)
188 if (deltaY !== 0) {
189 args += ` click --repeat ${scrollClicks(deltaY)} ${deltaY > 0 ? 5 : 4}`
190 }
191 if (deltaX !== 0) {
192 args += ` click --repeat ${scrollClicks(deltaX)} ${deltaX > 0 ? 7 : 6}`
193 }
194 await xdotool(args)
195 },
196 async keyDown(key) {
197 await xdotool(`keydown -- ${quote(toXdotoolKey(key))}`)
198 },
199 async keyUp(key) {
200 await xdotool(`keyup -- ${quote(toXdotoolKey(key))}`)
201 },
202 async press(keys) {
203 await xdotool(`key -- ${quote(keys.map(toXdotoolKey).join('+'))}`)
204 },
205 async type(text) {
206 if (text === '') return
207 const chunks: Array<string> = []
208 for (let i = 0; i < text.length; i += TYPE_CHUNK) {
209 chunks.push(text.slice(i, i + TYPE_CHUNK))
210 }
211 await run(
212 chunks
213 .map(
214 (chunk) =>
215 `${X} xdotool type --delay ${TYPE_DELAY_MS} -- ${quote(chunk)}`,
216 )
217 .join(' && '),
218 )
219 },
220 async cursorPosition() {
221 const out = await xdotool('getmouselocation')
222 const position = /x:(\d+)\s+y:(\d+)/.exec(out)
223 if (!position) {
224 throw new Error(`Could not read the cursor position: ${out}`)
225 }
226 return { x: Number(position[1]), y: Number(position[2]) }
227 },
228 } satisfies ComputerDriver
229 return driver
230}
231
232/**
233 * Create a driver factory that creates one sandbox for each thread.
234 *
235 * Each sandbox comes from `provider.create`. When `createComputerUse` closes
236 * a thread, or the thread goes idle, the sandbox of that thread is
237 * destroyed. The drivers have `cursorPosition`. They have no `zoom` and no
238 * `navigate`, because a desktop has no address. The model opens the browser
239 * on the desktop.
240 *
241 * @example
242 * const computer = createComputerUse({
243 * driver: sandboxComputer({
244 * provider: e2bSandbox({ template: 'desktop' }),
245 * }),
246 * })
247 */
248export function sandboxComputer({
249 provider,
250 display = DEFAULT_DISPLAY,
251}: SandboxComputerOptions) {
252 const factory: ComputerDriverFactory = {
253 display,
254 environment: 'linux',
255 capabilities: { zoom: false, cursorPosition: true, navigate: false },
256 async create() {
257 const sandbox = await provider.create({})
258 try {
259 const driver = await createSandboxComputerDriver({ sandbox, display })
260 const { width, height } = driver.display
261 if (width !== display.width || height !== display.height) {
262 throw new Error(
263 `The sandbox display is ${width}x${height}, not ${display.width}x${display.height}. Set display to the size of the running display.`,
264 )
265 }
266 return { ...driver, close: () => sandbox.destroy() }
267 } catch (error) {
268 // Keep the setup error. A failed destroy does not replace it.
269 await sandbox.destroy().catch((destroyError: unknown) => {
270 console.error(
271 'Failed to destroy the sandbox after setup failed.',
272 destroyError,
273 )
274 })
275 throw error
276 }
277 },
278 }
279 return factory
280}