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

actions.ts

403 lines12.5 KB

1import { parseKeyCombo, toCombo, toKey } from './keys'
2import type { ComputerDriver, MouseButton } from './types'
3​
4/** One Anthropic `scroll_amount` step, in pixels. */
5const SCROLL_STEP = 100
6​
7// ponytail: an OpenAI `wait` has no duration. 2 s is the wait in the OpenAI samples.
8const OPENAI_WAIT_MS = 2000
9​
10// The Anthropic computer tool docs give these limits: `repeat` is 1 to 100, and a
11// `hold_key` or `wait` duration is up to 300 seconds. Reject here, before any key goes down.
12const MAX_KEY_REPEAT = 100
13const MAX_WAIT_SECONDS = 300
14​
15type Point = { x: number; y: number }
16type Input = Record<string, unknown>
17​
18function isRecord(value: unknown): value is Input {
19 return typeof value === 'object' && value !== null && !Array.isArray(value)
21​
22function sleep(ms: number) {
23 return new Promise<void>((resolve) => setTimeout(resolve, ms))
25​
26function invalid(key: string, expected: string) {
27 return new Error(`Invalid computer action: "${key}" must be ${expected}.`)
29​
30function readNumber(input: Input, key: string) {
31 const value = input[key]
32 if (typeof value !== 'number' || !Number.isFinite(value)) {
33 throw invalid(key, 'a number')
34 }
35 return value
37​
38function readString(input: Input, key: string) {
39 const value = input[key]
40 if (typeof value !== 'string') throw invalid(key, 'a string')
41 return value
43​
44function readOptionalString(input: Input, key: string) {
45 const value = input[key]
46 if (value === undefined || value === null) return undefined
47 if (typeof value !== 'string') throw invalid(key, 'a string')
48 return value
50​
51function readNumbers(input: Input, key: string, length: number) {
52 const value = input[key]
53 const isValid =
54 Array.isArray(value) &&
55 value.length === length &&
56 value.every((item) => typeof item === 'number' && Number.isFinite(item))
57 if (!isValid) throw invalid(key, `an array of ${length} numbers`)
58 return value.filter((item) => typeof item === 'number')
60​
61function readCoordinate(input: Input, key: string) {
62 const [x = 0, y = 0] = readNumbers(input, key, 2)
63 return { x, y }
65​
66function readRepeat(input: Input) {
67 if (input['repeat'] === undefined || input['repeat'] === null) return 1
68 const repeat = readNumber(input, 'repeat')
69 if (!Number.isInteger(repeat) || repeat < 1 || repeat > MAX_KEY_REPEAT) {
70 throw invalid('repeat', `an integer from 1 to ${MAX_KEY_REPEAT}`)
71 }
72 return repeat
74​
75function readSeconds(input: Input, key: string) {
76 const value = readNumber(input, key)
77 if (value < 0 || value > MAX_WAIT_SECONDS) {
78 throw invalid(key, `a number from 0 to ${MAX_WAIT_SECONDS}`)
79 }
80 return value
82​
83/** Presses `keys` in order, runs `action`, then releases the keys that went down. */
84async function withKeys(
85 driver: ComputerDriver,
86 keys: Array<string>,
87 action: () => Promise<void>,
88) {
89 const pressed: Array<string> = []
90 let releaseError: unknown
91 try {
92 for (const key of keys) {
93 await driver.keyDown(key)
94 pressed.push(key)
95 }
96 await action()
97 } finally {
98 // One failed keyUp does not stop the rest.
99 for (const key of pressed.reverse()) {
100 await driver.keyUp(key).catch((error: unknown) => {
101 releaseError ??= error
102 })
103 }
104 }
105 // Reached only when the action succeeded, so an action error wins.
106 if (releaseError !== undefined) throw releaseError
108​
109async function drag(driver: ComputerDriver, path: Array<Point>) {
110 const [start, ...rest] = path
111 if (start === undefined) throw invalid('path', 'a non-empty array')
112 await driver.move(start.x, start.y)
113 await driver.mouseDown('left')
114 try {
115 for (const point of rest) await driver.move(point.x, point.y)
116 } finally {
117 await driver.mouseUp('left')
118 }
120​
121// ---------------------------------------------------------------------------
122// Anthropic: `{ action: 'left_click', coordinate: [x, y], ... }`
123// ---------------------------------------------------------------------------
124​
125const ANTHROPIC_CLICKS: Record<string, { button: MouseButton; count: number }> =
126 {
127 left_click: { button: 'left', count: 1 },
128 right_click: { button: 'right', count: 1 },
129 middle_click: { button: 'middle', count: 1 },
130 double_click: { button: 'left', count: 2 },
131 triple_click: { button: 'left', count: 3 },
132 }
133​
134/** The `coordinate` of the action, or the mouse position when it has none. */
135async function anthropicPoint(driver: ComputerDriver, input: Input) {
136 if (input['coordinate'] !== undefined && input['coordinate'] !== null) {
137 return readCoordinate(input, 'coordinate')
138 }
139 if (!driver.cursorPosition) {
140 throw new Error(
141 'Invalid computer action: "coordinate" is missing, and the computer driver has no cursorPosition method.',
142 )
143 }
144 return driver.cursorPosition()
146​
147function anthropicModifiers(input: Input) {
148 const text = readOptionalString(input, 'text')
149 return text ? parseKeyCombo(text) : []
151​
152function scrollDelta(direction: string, pixels: number) {
153 switch (direction) {
154 case 'up':
155 return { deltaX: 0, deltaY: -pixels }
156 case 'down':
157 return { deltaX: 0, deltaY: pixels }
158 case 'left':
159 return { deltaX: -pixels, deltaY: 0 }
160 case 'right':
161 return { deltaX: pixels, deltaY: 0 }
162 default:
163 throw invalid('scroll_direction', '"up", "down", "left", or "right"')
164 }
166​
167async function runAnthropicAction(
168 driver: ComputerDriver,
169 action: string,
170 input: Input,
171) {
172 const click = ANTHROPIC_CLICKS[action]
173 if (click) {
174 const { x, y } = await anthropicPoint(driver, input)
175 await withKeys(driver, anthropicModifiers(input), () =>
176 driver.click(x, y, click),
177 )
178 return undefined
179 }
180​
181 switch (action) {
182 case 'screenshot':
183 return undefined
184 case 'key': {
185 const combos = readString(input, 'text').split(/\s+/).filter(Boolean)
186 const repeat = readRepeat(input)
187 for (let i = 0; i < repeat; i++) {
188 for (const combo of combos) await driver.press(parseKeyCombo(combo))
189 }
190 return undefined
191 }
192 case 'type':
193 await driver.type(readString(input, 'text'))
194 return undefined
195 case 'mouse_move': {
196 const { x, y } = readCoordinate(input, 'coordinate')
197 await driver.move(x, y)
198 return undefined
199 }
200 case 'left_click_drag': {
201 const path = [
202 readCoordinate(input, 'start_coordinate'),
203 readCoordinate(input, 'coordinate'),
204 ]
205 await withKeys(driver, anthropicModifiers(input), () =>
206 drag(driver, path),
207 )
208 return undefined
209 }
210 case 'left_mouse_down':
211 await driver.mouseDown('left')
212 return undefined
213 case 'left_mouse_up':
214 await driver.mouseUp('left')
215 return undefined
216 case 'scroll': {
217 const { x, y } = await anthropicPoint(driver, input)
218 const pixels = readNumber(input, 'scroll_amount') * SCROLL_STEP
219 const direction = readString(input, 'scroll_direction')
220 const { deltaX, deltaY } = scrollDelta(direction, pixels)
221 await withKeys(driver, anthropicModifiers(input), () =>
222 driver.scroll(x, y, deltaX, deltaY),
223 )
224 return undefined
225 }
226 case 'hold_key': {
227 const keys = parseKeyCombo(readString(input, 'text'))
228 const ms = readSeconds(input, 'duration') * 1000
229 await withKeys(driver, keys, () => sleep(ms))
230 return undefined
231 }
232 case 'wait':
233 await sleep(readSeconds(input, 'duration') * 1000)
234 return undefined
235 case 'cursor_position': {
236 if (!driver.cursorPosition) {
237 throw new Error(
238 'The computer driver has no cursorPosition method, so the "cursor_position" action is not available.',
239 )
240 }
241 const { x, y } = await driver.cursorPosition()
242 return { type: 'text' as const, text: `X=${x},Y=${y}` }
243 }
244 case 'zoom': {
245 if (!driver.zoom) {
246 throw new Error(
247 'The computer driver has no zoom method, so the "zoom" action is not available.',
248 )
249 }
250 const [x0 = 0, y0 = 0, x1 = 0, y1 = 0] = readNumbers(input, 'region', 4)
251 const bytes = await driver.zoom({
252 x: x0,
253 y: y0,
254 width: x1 - x0,
255 height: y1 - y0,
256 })
257 return { type: 'image' as const, bytes }
258 }
259 default:
260 throw new Error(`Unknown computer action "${action}".`)
261 }
263​
264// ---------------------------------------------------------------------------
265// OpenAI: `{ action: { type: 'click', ... } }` or `{ actions: [...] }`
266// ---------------------------------------------------------------------------
267​
268const OPENAI_BUTTONS: Record<string, MouseButton> = {
269 left: 'left',
270 right: 'right',
271 wheel: 'middle',
272 back: 'back',
273 forward: 'forward',
275​
276function openaiModifiers(input: Input) {
277 const keys = input['keys']
278 if (keys === undefined || keys === null) return []
279 const isValid =
280 Array.isArray(keys) && keys.every((key) => typeof key === 'string')
281 if (!isValid) throw invalid('keys', 'an array of strings')
282 return keys.filter((key) => typeof key === 'string').map(toKey)
284​
285function readPath(input: Input) {
286 const path = input['path']
287 if (!Array.isArray(path)) throw invalid('path', 'an array of points')
288 return path.map((point) => {
289 if (!isRecord(point)) throw invalid('path', 'an array of points')
290 return { x: readNumber(point, 'x'), y: readNumber(point, 'y') }
291 })
293​
294async function runOpenAIAction(driver: ComputerDriver, input: unknown) {
295 if (!isRecord(input)) throw invalid('action', 'an object')
296 const type = readString(input, 'type')
297 const modifiers = openaiModifiers(input)
298​
299 switch (type) {
300 case 'screenshot':
301 return
302 case 'click': {
303 const button = OPENAI_BUTTONS[readString(input, 'button')]
304 if (!button) {
305 throw invalid(
306 'button',
307 '"left", "right", "wheel", "back", or "forward"',
308 )
309 }
310 const x = readNumber(input, 'x')
311 const y = readNumber(input, 'y')
312 await withKeys(driver, modifiers, () =>
313 driver.click(x, y, { button, count: 1 }),
314 )
315 return
316 }
317 case 'double_click': {
318 const x = readNumber(input, 'x')
319 const y = readNumber(input, 'y')
320 await withKeys(driver, modifiers, () =>
321 driver.click(x, y, { button: 'left', count: 2 }),
322 )
323 return
324 }
325 case 'drag': {
326 const path = readPath(input)
327 await withKeys(driver, modifiers, () => drag(driver, path))
328 return
329 }
330 case 'keypress': {
331 const keys = input['keys']
332 const isValid =
333 Array.isArray(keys) &&
334 keys.length > 0 &&
335 keys.every((key) => typeof key === 'string')
336 if (!isValid) throw invalid('keys', 'a non-empty array of strings')
337 await driver.press(toCombo(keys.filter((key) => typeof key === 'string')))
338 return
339 }
340 case 'move': {
341 const x = readNumber(input, 'x')
342 const y = readNumber(input, 'y')
343 await withKeys(driver, modifiers, () => driver.move(x, y))
344 return
345 }
346 case 'scroll': {
347 const x = readNumber(input, 'x')
348 const y = readNumber(input, 'y')
349 const deltaX = readNumber(input, 'scroll_x')
350 const deltaY = readNumber(input, 'scroll_y')
351 await withKeys(driver, modifiers, () =>
352 driver.scroll(x, y, deltaX, deltaY),
353 )
354 return
355 }
356 case 'type':
357 await driver.type(readString(input, 'text'))
358 return
359 case 'wait':
360 await sleep(OPENAI_WAIT_MS)
361 return
362 default:
363 throw new Error(`Unknown computer action "${type}".`)
364 }
366​
367/**
368 * Runs one computer tool call from the model on a driver.
369 *
370 * The input shape picks the provider:
371 * - A string `action` is an Anthropic action.
372 * - An object `action` or an `actions` array is an OpenAI call. A batch runs
373 * in order.
374 *
375 * The result is `undefined` when the action has no output of its own. Then
376 * the caller takes a screenshot. `zoom` gives `{ type: 'image', bytes }` and
377 * `cursor_position` gives `{ type: 'text', text }`.
378 *
379 * Throws an `Error` for an input that is not valid, an unknown action, or a
380 * `zoom` or `cursor_position` action when the driver has no such method.
381 *
382 * @param driver - The driver that controls the computer.
383 * @param input - The raw tool input from the model.
384 */
385export async function runComputerAction(
386 driver: ComputerDriver,
387 input: unknown,
388) {
389 if (!isRecord(input)) throw invalid('input', 'an object')
390 const { action, actions } = input
391 if (typeof action === 'string') {
392 return runAnthropicAction(driver, action, input)
393 }
394 if (Array.isArray(actions)) {
395 for (const item of actions) await runOpenAIAction(driver, item)
396 return undefined
397 }
398 if (isRecord(action)) {
399 await runOpenAIAction(driver, action)
400 return undefined
401 }
402 throw invalid('action', 'a string, an object, or an "actions" array')