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

driver.ts

192 lines6.6 KB

1import { createRequire } from 'node:module'
2import { toPng } from './png'
3import type { ComputerDriver, MouseButton } from '@tanstack/ai-computer-use'
4import type { Bitmap } from './png'
5​
6/** The parts of `@jitsi/robotjs` that the driver uses. */
7export interface RobotLike {
8 getScreenSize: () => { width: number; height: number }
9 getMousePos: () => { x: number; y: number }
10 moveMouse: (x: number, y: number) => void
11 mouseClick: (button?: string, double?: boolean) => void
12 mouseToggle: (down?: string, button?: string) => void
13 scrollMouse: (x: number, y: number) => void
14 keyToggle: (key: string, down: string) => void
15 typeString: (text: string) => void
16 screen: {
17 capture: (x?: number, y?: number, width?: number, height?: number) => Bitmap
18 }
20​
21/** Options for {@link localComputer}. */
22export interface LocalComputerOptions {
23 /**
24 * The size of the screenshots that the model sees. The driver scales each
25 * screenshot down to this size, and scales each point from the model up to
26 * the screen. The default is the screen size, scaled down to fit in
27 * 1280 x 800.
28 */
29 display?: { width: number; height: number }
30 /** The robot that moves the mouse and presses the keys. The default is `@jitsi/robotjs`. */
31 robot?: RobotLike
33​
34/** The largest default display. Bigger screenshots cost more tokens, and the providers scale them down anyway. */
35const MAX_DISPLAY = { width: 1280, height: 800 }
36​
37/** `KeyboardEvent.key` names that differ from the robotjs names. Other names are lowercased. */
38const ROBOT_KEYS: Record<string, string> = {
39 ArrowUp: 'up',
40 ArrowDown: 'down',
41 ArrowLeft: 'left',
42 ArrowRight: 'right',
43 Meta: 'command',
44 ContextMenu: 'menu',
45 ' ': 'space',
47​
48function toRobotKey(key: string) {
49 return ROBOT_KEYS[key] ?? (key.length === 1 ? key : key.toLowerCase())
51​
52function toRobotButton(button: MouseButton) {
53 if (button === 'back' || button === 'forward') {
54 throw new Error(`The local computer has no "${button}" mouse button.`)
55 }
56 return button
58​
59function currentEnvironment() {
60 if (process.platform === 'win32') return 'windows'
61 if (process.platform === 'darwin') return 'mac'
62 return 'linux'
64​
65/** robotjs scrolls in pixels on macOS, in wheel clicks on Linux, and in 120 units for each wheel notch on Windows. */
66function scrollUnits(pixels: number) {
67 if (pixels === 0 || process.platform === 'darwin') return pixels
68 // ponytail: one wheel notch is about 100 px.
69 const notches = pixels / 100
70 if (process.platform === 'win32') return Math.round(notches * 120)
71 return Math.sign(pixels) * Math.max(1, Math.round(Math.abs(notches)))
73​
74function fitDisplay(screen: { width: number; height: number }) {
75 const scale = Math.min(
76 1,
77 MAX_DISPLAY.width / screen.width,
78 MAX_DISPLAY.height / screen.height,
79 )
80 return {
81 width: Math.round(screen.width * scale),
82 height: Math.round(screen.height * scale),
83 }
85​
86/** Load robotjs on the first call, so an import of this package does not load the native addon. */
87function loadRobot() {
88 return createRequire(import.meta.url)('@jitsi/robotjs')
90​
91/**
92 * Create a `ComputerDriver` for the machine that runs this code. The model
93 * controls the real mouse, keyboard, and main screen.
94 *
95 * All threads share this one machine. `createComputerUse` never closes it.
96 *
97 * CAUTION: the model can do on this machine what you can do. Use a VM or
98 * `sandboxComputer` from `@tanstack/ai-computer-sandbox` when you cannot watch it.
99 *
100 * Needs `@jitsi/robotjs`. On macOS, give the app that runs Node the
101 * Accessibility and Screen Recording permissions. On Linux, it needs X11.
102 *
103 * @example
104 * const computerUse = createComputerUse({ driver: localComputer() })
105 */
106export function localComputer(options: LocalComputerOptions = {}) {
107 const robot: RobotLike = options.robot ?? loadRobot()
108 const screen = robot.getScreenSize()
109 const display = options.display ?? fitDisplay(screen)
110​
111 /** Scale a point or a size from the display to the screen. */
112 const toScreen = (x: number, y: number) => ({
113 x: Math.round((x * screen.width) / display.width),
114 y: Math.round((y * screen.height) / display.height),
115 })
116 const moveTo = (x: number, y: number) => {
117 const point = toScreen(x, y)
118 robot.moveMouse(point.x, point.y)
119 }
120​
121 return {
122 display,
123 environment: currentEnvironment(),
124 screenshot: async () =>
125 toPng(robot.screen.capture(), display.width, display.height),
126 async click(x, y, { button, count }) {
127 const name = toRobotButton(button)
128 moveTo(x, y)
129 // robotjs sends a real double click, which macOS needs.
130 if (count === 2) return robot.mouseClick(name, true)
131 // ponytail: macOS sees a triple click as three single clicks.
132 for (let i = 0; i < count; i++) robot.mouseClick(name)
133 },
134 async move(x, y) {
135 moveTo(x, y)
136 },
137 async mouseDown(button) {
138 robot.mouseToggle('down', toRobotButton(button))
139 },
140 async mouseUp(button) {
141 robot.mouseToggle('up', toRobotButton(button))
142 },
143 async scroll(x, y, deltaX, deltaY) {
144 moveTo(x, y)
145 const delta = toScreen(deltaX, deltaY)
146 // robotjs scrolls right and down for negative values.
147 robot.scrollMouse(scrollUnits(-delta.x), scrollUnits(-delta.y))
148 },
149 async keyDown(key) {
150 robot.keyToggle(toRobotKey(key), 'down')
151 },
152 async keyUp(key) {
153 robot.keyToggle(toRobotKey(key), 'up')
154 },
155 async press(keys) {
156 // Release the pressed keys also when a later key is not valid.
157 const pressed: Array<string> = []
158 try {
159 for (const name of keys.map(toRobotKey)) {
160 robot.keyToggle(name, 'down')
161 pressed.push(name)
162 }
163 } finally {
164 for (const name of pressed.reverse()) robot.keyToggle(name, 'up')
165 }
166 },
167 async type(text) {
168 robot.typeString(text)
169 },
170 async cursorPosition() {
171 const { x, y } = robot.getMousePos()
172 return {
173 x: Math.round((x * display.width) / screen.width),
174 y: Math.round((y * display.height) / screen.height),
175 }
176 },
177 async zoom(region) {
178 // robotjs does not check the region. A region off the screen can crash Node.
179 const start = toScreen(region.x, region.y)
180 const end = toScreen(region.x + region.width, region.y + region.height)
181 const x = Math.min(Math.max(start.x, 0), screen.width - 1)
182 const y = Math.min(Math.max(start.y, 0), screen.height - 1)
183 const bitmap = robot.screen.capture(
184 x,
185 y,
186 Math.max(1, Math.min(end.x, screen.width) - x),
187 Math.max(1, Math.min(end.y, screen.height) - y),
188 )
189 return toPng(bitmap, bitmap.width, bitmap.height)
190 },
191 } satisfies ComputerDriver