Open History to see the last commit
1---
2title: Custom Computer Use Driver
3id: computer-use-custom-driver
4order: 4
5description: "Let the model use your own machine. Write a ComputerDriver with a small set of mouse, keyboard, and screenshot methods, and a ComputerDriverFactory to give each thread its own machine."
6keywords:
7 - tanstack ai
8 - computer use
9 - ComputerDriver
10 - ComputerDriverFactory
11 - custom driver
12 - virtual machine
13---
14
15A custom driver connects `createComputerUse` to a machine that has no built-in driver, such as a VM, a remote desktop, or a lab device.
16
17Write a `ComputerDriver`, and [computer use](./computer-use) runs on it with no other change.
18
19## 1. Write the driver
20
21A driver is an object with a screen size and a small set of methods. This example sends each method to an HTTP agent that runs on the machine.
22
23```ts
24// app/my-driver.ts
25import type { ComputerDriver } from '@tanstack/ai-computer-use'
26
27export function createMyDriver(base: string) {
28 async function send(path: string, body: object) {
29 const response = await fetch(`${base}${path}`, {
30 method: 'POST',
31 headers: { 'Content-Type': 'application/json' },
32 body: JSON.stringify(body),
33 })
34 if (!response.ok) throw new Error(`${path} failed: ${response.status}`)
35 }
36
37 const driver: ComputerDriver = {
38 display: { width: 1920, height: 1080 },
39 environment: 'windows',
40 async screenshot() {
41 const response = await fetch(`${base}/screenshot`)
42 if (!response.ok) throw new Error(`/screenshot failed: ${response.status}`)
43 return new Uint8Array(await response.arrayBuffer())
44 },
45 click: (x, y, { button, count }) => send('/click', { x, y, button, count }),
46 move: (x, y) => send('/move', { x, y }),
47 mouseDown: (button) => send('/mouse-down', { button }),
48 mouseUp: (button) => send('/mouse-up', { button }),
49 scroll: (x, y, deltaX, deltaY) => send('/scroll', { x, y, deltaX, deltaY }),
50 keyDown: (key) => send('/key-down', { key }),
51 keyUp: (key) => send('/key-up', { key }),
52 press: (keys) => send('/press', { keys }),
53 type: (text) => send('/type', { text }),
54 }
55 return driver
56}
57```
58
59## 2. Give it to `createComputerUse`
60
61```ts
62import { createComputerUse } from '@tanstack/ai-computer-use'
63import type { ComputerDriver } from '@tanstack/ai-computer-use'
64
65// From app/my-driver.ts above.
66declare function createMyDriver(base: string): ComputerDriver
67
68const computerUse = createComputerUse({
69 driver: createMyDriver('http://localhost:8000'),
70})
71```
72
73Give `computerUse.tools`, `computerUse.middleware`, and `computerUse.interrupt` to `chat()`, as in the [computer use setup](./computer-use).
74
75## 3. Try it
76
77Start your agent on the machine, and send a task in the chat. Your agent gets the first `/screenshot` request, then the clicks and the key presses. The model now uses your own machine.
78
79## How it works
80
81Your driver does only the small steps. The core builds the rest from them:
82
83- **Drags**: `move`, `mouseDown`, more `move` calls, then `mouseUp`.
84- **Modifier clicks and scrolls**: `keyDown` for each modifier, the action, then `keyUp` in reverse order.
85- **`hold_key` and `wait`**: the core holds the keys or waits, then continues.
86- **Key names**: the core changes OpenAI and Anthropic key names to `KeyboardEvent.key` names.
87- **Screenshots**: after a normal action, the core waits `screenshotDelay` ms and calls `screenshot()`. An OpenAI batch waits once, after the last action, then takes one screenshot. `zoom` and `cursor_position` return their own result, so the core does not call `screenshot()` for them.
88
89A driver is one machine. Every thread shares it, so it serves one conversation at a time. `createComputerUse` never closes it. To give each thread its own machine, write a [driver factory](#one-machine-for-each-thread).
90
91## Advanced
92
93### The contract
94
95Coordinates are in pixels, in `display` space. Key names are `KeyboardEvent.key` names, for example `'Enter'`, `'Control'`, or `'a'`.
96
97| Member | What it does |
98| --- | --- |
99| `display` | The screen size in pixels. Screenshots have this size. |
100| `environment` | `'browser'`, `'linux'`, `'mac'`, or `'windows'`. |
101| `screenshot()` | Returns PNG bytes as a `Uint8Array`. |
102| `click(x, y, { button, count })` | Clicks `count` times. `button` is `left`, `right`, `middle`, `back`, or `forward`. |
103| `move(x, y)` | Moves the mouse. |
104| `mouseDown(button)`, `mouseUp(button)` | Presses or releases a button at the mouse position. |
105| `scroll(x, y, deltaX, deltaY)` | Scrolls at the point. The deltas are in pixels. |
106| `keyDown(key)`, `keyUp(key)` | Presses or releases one key. |
107| `press(keys)` | Presses one combo, like `['Control', 's']`. |
108| `type(text)` | Types text as a user does. |
109
110### Add the optional methods
111
112Four methods are optional:
113
114- `zoom(region)`: returns PNG bytes of one region at full size. The region has `x`, `y`, `width`, and `height`. `computer_toolset_20260801` and `computer_20251124` turn on `zoom` when the driver has this method. `computer_20250124` does not.
115- `cursorPosition()`: returns the mouse position as `{ x, y }`. Only `computer_toolset_20260801` turns on `cursor_position`, and only when the driver has this method.
116- `navigate(url)`: opens the URL. `computerUse.tools` then has the `navigate` tool. The tool accepts only `http:` and `https:` URLs.
117- `close()`: frees the machine. `createComputerUse` calls it only on a driver that a factory made.
118
119For example, to add `cursorPosition`, add this function to `app/my-driver.ts`. It narrows the JSON from your agent before it returns it:
120
121```ts
122export async function readCursorPosition(base: string) {
123 const response = await fetch(`${base}/cursor`)
124 const data: unknown = await response.json()
125 const isPoint =
126 typeof data === 'object' &&
127 data !== null &&
128 'x' in data &&
129 'y' in data &&
130 typeof data.x === 'number' &&
131 typeof data.y === 'number'
132 if (!isPoint) throw new Error('The agent sent no cursor position.')
133 return { x: data.x, y: data.y }
134}
135```
136
137Then add `cursorPosition: () => readCursorPosition(base)` to `driver` in `createMyDriver`.
138
139### One machine for each thread
140
141One shared machine serves one conversation at a time. To give each thread its own machine, write a `ComputerDriverFactory`. `createComputerUse` calls `create` on the first action of each thread.
142
143This example asks a pool service for one VM for each thread, and stops the VM when the thread closes:
144
145```ts
146// app/my-machines.ts
147import type {
148 ComputerDriver,
149 ComputerDriverFactory,
150} from '@tanstack/ai-computer-use'
151
152// From app/my-driver.ts above.
153declare function createMyDriver(base: string): ComputerDriver
154
155const pool = 'http://localhost:9000'
156
157export const myMachines: ComputerDriverFactory = {
158 display: { width: 1920, height: 1080 },
159 environment: 'windows',
160 capabilities: { zoom: false, cursorPosition: false, navigate: false },
161 async create({ threadId }) {
162 const machine = `${pool}/machines/${encodeURIComponent(threadId)}`
163 const response = await fetch(machine, { method: 'PUT' })
164 if (!response.ok) throw new Error(`Start failed: ${response.status}`)
165 return {
166 ...createMyDriver(`${machine}/agent`),
167 close: async () => {
168 await fetch(machine, { method: 'DELETE' })
169 },
170 }
171 },
172}
173```
174
175Then give the factory to `createComputerUse`:
176
177```ts
178import { createComputerUse } from '@tanstack/ai-computer-use'
179import type { ComputerDriverFactory } from '@tanstack/ai-computer-use'
180
181// From app/my-machines.ts above.
182declare const myMachines: ComputerDriverFactory
183
184const computerUse = createComputerUse({ driver: myMachines })
185```
186
187The factory has these members:
188
189| Member | What it does |
190| --- | --- |
191| `display` | The screen size of every machine. Each driver from `create` has this `display`. |
192| `environment` | The kind of every machine. |
193| `capabilities` | `{ zoom, cursorPosition, navigate }`: the optional methods that every driver from `create` has. The tool is built before any machine exists, so the factory tells it. |
194| `create({ threadId })` | Makes the driver of one thread. If it throws, the model gets the error. The next model turn calls `create` again. |
195| `close()` | Optional. Frees what the threads share. `computerUse.close()` calls it after it closes every thread. |
196
197When a thread closes or goes idle, `createComputerUse` calls `close()` on the driver of that thread.