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

create-computer-use.ts

427 lines15.0 KB

1import { brandProviderTool, toolDefinition } from '@tanstack/ai'
2import { arrayBufferToBase64 } from '@tanstack/ai-utils'
3import { z } from 'zod'
4import { runComputerAction } from './actions'
5import { computerSafetyCheck, safetyCheckSchema } from './safety-check'
6import type {
7 ChatMiddleware,
8 ChatMiddlewareContext,
9 ImagePart,
10 ProviderTool,
11 ToolExecutionContext,
12} from '@tanstack/ai'
13import type { ComputerUseToolMetadata } from '@tanstack/ai/adapter-internals'
14import type { ComputerDriver, ComputerDriverFactory } from './types'
15​
16/** Options for `createComputerUse`. */
17export interface CreateComputerUseOptions {
18 /**
19 * The machine to control.
20 *
21 * - A driver is one machine. Every thread shares it. `createComputerUse`
22 * never closes it.
23 * - A driver factory makes one machine per thread, on the first call of the
24 * thread. `createComputerUse` closes that machine when the thread closes
25 * or goes idle.
26 */
27 driver: ComputerDriver | ComputerDriverFactory
28 /**
29 * The time in ms between an action and its screenshot. The page or the
30 * desktop gets this time to settle. The default is 500.
31 */
32 screenshotDelay?: number
33 /**
34 * The time in ms that a thread can stay idle. After this time, the state of
35 * the thread is dropped, and its machine from the factory is closed. The
36 * next call of the thread gets a new machine. `false` keeps every thread
37 * until `close`. The default is 600000 (10 minutes).
38 */
39 idleTimeout?: number | false
41​
42const TOOL_NAME = 'computer'
43​
44/** The thread of a call with no `threadId`, like a direct `execute()` call. */
45const SHARED_THREAD = 'computer-use:shared'
46​
47/** The state of one thread. */
48interface ThreadState {
49 id: string
50 /** The machine from the factory. It stays unset for a driver that the app passed in. */
51 driver: Promise<ComputerDriver> | undefined
52 /** This thread's last queued action. A shared driver uses one queue for every thread. */
53 queue: Promise<unknown>
54 /** The number of actions in the queue. */
55 pending: number
56 turnFailed: boolean
57 approved: Set<string>
58 declined: Set<string>
59 timer: ReturnType<typeof setTimeout> | undefined
61​
62const navigateDefinition = toolDefinition({
63 name: 'navigate',
64 description: 'Go to a URL in the browser. Returns a screenshot.',
65 inputSchema: z.object({
66 url: z
67 .string()
68 .describe(
69 'The full URL that starts with https:// or http://, like https://tanstack.com.',
70 ),
71 }),
72})
73​
74type ComputerTool = ProviderTool<string, 'computer'>
75type NavigateTool = ReturnType<typeof navigateDefinition.server>
76​
77/** The parts of a computer tool input that the safety check reads. */
78const checkedInputSchema = z.object({
79 pending_safety_checks: z.array(safetyCheckSchema).nullish(),
80 action: z.unknown().optional(),
81 actions: z.unknown().optional(),
82})
83​
84/** The safety checks and the action of an input, or `null` when they do not parse. */
85function readCheckedInput(input: unknown) {
86 const parsed = checkedInputSchema.safeParse(input)
87 if (!parsed.success) return null
88 const { action, actions } = parsed.data
89 const checks = parsed.data.pending_safety_checks ?? []
90 return { checks, action: action ?? actions ?? null }
92​
93function parseArguments(text: string) {
94 try {
95 return JSON.parse(text)
96 } catch {
97 return undefined
98 }
100​
101/** True for an `http:` or an `https:` URL. */
102function isWebUrl(url: string) {
103 try {
104 const { protocol } = new URL(url)
105 return protocol === 'https:' || protocol === 'http:'
106 } catch {
107 return false
108 }
110​
111function sleep(ms: number) {
112 return new Promise<void>((resolve) => setTimeout(resolve, ms))
114​
115function imageResult(bytes: Uint8Array) {
116 const part: ImagePart = {
117 type: 'image',
118 source: {
119 type: 'data',
120 // Copy the bytes. The ArrayBuffer of a small Node Buffer is a shared pool.
121 value: arrayBufferToBase64(new Uint8Array(bytes).buffer),
122 mimeType: 'image/png',
123 },
124 }
125 return [part]
127​
128/** The computer tool calls in the last assistant message. */
129function computerToolCalls(ctx: ChatMiddlewareContext) {
130 const message = ctx.messages.findLast((item) => item.role === 'assistant')
131 const toolCalls = message?.toolCalls ?? []
132 return toolCalls.filter((call) => call.function.name === TOOL_NAME)
134​
135/**
136 * Create a provider-agnostic computer tool. Each thread gets its own state.
137 * A driver factory gives each thread its own machine. A driver that you pass
138 * in is one machine, and its actions run one at a time across threads.
139 *
140 * The OpenAI and Anthropic adapters swap the computer tool for their native
141 * computer tool. A normal action returns a screenshot. An OpenAI batch
142 * returns one screenshot after the last action. `zoom` returns the zoom
143 * image, and `cursor_position` returns text. Those two do not take another
144 * screenshot.
145 *
146 * - `tools`: pass it to `chat({ tools })`. It is `[computer]`. When the
147 * driver can navigate, it is `[computer, navigate]`.
148 * - `middleware`: pass it to `chat({ middleware })`. It runs the failed-turn
149 * rule and the OpenAI safety checks.
150 * - `interrupt`: pass it to `chat({ interrupts })`. It is the same object as
151 * `computerSafetyCheck`.
152 * - `close(threadId)`: close the machine of one thread. `close()` closes
153 * every thread, then the driver factory.
154 *
155 * The thread is the `threadId` of `chat()`. Pass the thread id of the client
156 * to `chat()`. In one thread, actions run one at a time, in call order. After
157 * an action throws, the other calls of the same model turn throw too. A call
158 * with OpenAI safety checks runs only after a person approves it. When a
159 * thread stays idle for `idleTimeout`, its state is dropped and its machine
160 * from the factory is closed.
161 *
162 * @param options - The driver or the driver factory, the optional
163 * `screenshotDelay` in ms, and the optional `idleTimeout` in ms.
164 *
165 * @example
166 * ```ts
167 * const computerUse = createComputerUse({
168 * driver: playwrightComputer({ startUrl: 'https://tanstack.com' }),
169 * })
170 *
171 * chat({
172 * adapter: openaiText('gpt-6.1-sol'),
173 * messages,
174 * threadId,
175 * tools: computerUse.tools,
176 * middleware: [computerUse.middleware],
177 * interrupts: [computerUse.interrupt],
178 * })
179 * ```
180 */
181export function createComputerUse({
182 driver,
183 screenshotDelay = 500,
184 idleTimeout = 600_000,
185}: CreateComputerUseOptions): {
186 tools: [ComputerTool] | [ComputerTool, NavigateTool]
187 // The .d.ts names typeof computerSafetyCheck here, not a copy of its type.
188 // TypeScript 5 sees two copies as different types, and chat() rejects them.
189 middleware: ChatMiddleware<unknown, typeof computerSafetyCheck>
190 interrupt: typeof computerSafetyCheck
191 close: (threadId?: string) => Promise<void>
192} {
193 // ponytail: the machines live in this process only. When the next request
194 // of a thread reaches another server, the thread gets a new machine there.
195 // ponytail: without a stable threadId, chat() makes a new id for each
196 // request, so each request gets a new machine. Pass threadId to chat().
197 // ponytail: when a person answers a safety check after idleTimeout, the
198 // approved action runs on a new machine. Set idleTimeout above that wait.
199 // ponytail: one queue for a shared driver. Per-thread queues if two
200 // threads on one machine must overlap.
201 const threads = new Map<string, ThreadState>()
202 const sharesOneMachine = !('create' in driver)
203 let sharedQueue: Promise<unknown> = Promise.resolve()
204​
205 function startTimer(thread: ThreadState) {
206 clearTimeout(thread.timer)
207 const isOpen = threads.get(thread.id) === thread
208 if (idleTimeout === false || !isOpen) return
209 thread.timer = setTimeout(() => {
210 // Nobody waits for an idle close. Log the error so a stuck machine is visible.
211 closeThread(thread).catch((error: unknown) => {
212 console.error(
213 `Failed to close the idle computer thread ${thread.id}.`,
214 error,
215 )
216 })
217 }, idleTimeout)
218 thread.timer.unref?.()
219 }
220​
221 function threadOf(threadId: string) {
222 const known = threads.get(threadId)
223 if (known) return known
224 const thread: ThreadState = {
225 id: threadId,
226 driver: undefined,
227 queue: Promise.resolve(),
228 pending: 0,
229 turnFailed: false,
230 approved: new Set(),
231 declined: new Set(),
232 timer: undefined,
233 }
234 threads.set(threadId, thread)
235 startTimer(thread)
236 return thread
237 }
238​
239 /** Drop the thread, wait for its queue, then close its machine from the factory. */
240 async function closeThread(thread: ThreadState) {
241 if (threads.get(thread.id) === thread) threads.delete(thread.id)
242 clearTimeout(thread.timer)
243 await thread.queue
244 const machine = await thread.driver
245 await machine?.close?.()
246 }
247​
248 function machineOf(thread: ThreadState) {
249 if (!('create' in driver)) return driver
250 thread.driver ??= driver
251 .create({ threadId: thread.id })
252 .catch((error: unknown) => {
253 // The next call of the thread calls create again.
254 thread.driver = undefined
255 throw error
256 })
257 return thread.driver
258 }
259​
260 /** Run `work` in the queue of the thread, with the failed-turn rule. */
261 function runInThread<T>(
262 threadId: string | undefined,
263 work: (thread: ThreadState) => Promise<T>,
264 ) {
265 const thread = threadOf(threadId ?? SHARED_THREAD)
266 clearTimeout(thread.timer)
267 thread.pending += 1
268 const previous = sharesOneMachine ? sharedQueue : thread.queue
269 const run = previous.then(async () => {
270 if (thread.turnFailed) {
271 throw new Error(
272 'Not executed: an earlier computer action in this turn failed.',
273 )
274 }
275 try {
276 return await work(thread)
277 } catch (error) {
278 thread.turnFailed = true
279 throw error
280 }
281 })
282 // Swallow here so the next action runs. `run` still rejects for the caller.
283 // On a shared driver, `settled` follows the actions of other threads, so
284 // closing a thread waits for them too. Closing a thread never closes a
285 // shared driver, so this wait does no harm.
286 const settled = run
287 .catch(() => undefined)
288 .then(() => {
289 thread.pending -= 1
290 if (thread.pending === 0) startTimer(thread)
291 })
292 if (sharesOneMachine) sharedQueue = settled
293 thread.queue = settled
294 return run
295 }
296​
297 const capabilities =
298 'create' in driver
299 ? driver.capabilities
300 : {
301 zoom: typeof driver.zoom === 'function',
302 cursorPosition: typeof driver.cursorPosition === 'function',
303 navigate: typeof driver.navigate === 'function',
304 }
305​
306 const metadata = {
307 __kind: 'computer_use',
308 display: driver.display,
309 environment: driver.environment,
310 capabilities: {
311 zoom: capabilities.zoom,
312 cursorPosition: capabilities.cursorPosition,
313 },
314 } satisfies ComputerUseToolMetadata
315​
316 const computer = brandProviderTool<ComputerTool>({
317 name: TOOL_NAME,
318 description: 'Use a computer with a mouse and a keyboard.',
319 metadata,
320 execute(input: unknown, context?: ToolExecutionContext) {
321 return runInThread(context?.threadId, async (thread) => {
322 const checked = readCheckedInput(input)
323 // Fail closed: checks that do not parse also need an approval.
324 const hasChecks = checked === null || checked.checks.length > 0
325 const toolCallId = context?.toolCallId
326 const isApproved =
327 toolCallId !== undefined && thread.approved.has(toolCallId)
328 if (hasChecks && !isApproved) {
329 throw new Error(
330 'Refused: this computer action has safety checks that nobody approved. Add the `interrupt` from createComputerUse to chat({ interrupts }) and the `middleware` to chat({ middleware }).',
331 )
332 }
333 const machine = await machineOf(thread)
334 const result = await runComputerAction(machine, input)
335 if (result === undefined) {
336 await sleep(screenshotDelay)
337 return imageResult(await machine.screenshot())
338 }
339 return result.type === 'image' ? imageResult(result.bytes) : result.text
340 })
341 },
342 })
343​
344 const navigate = navigateDefinition.server(({ url }, context) =>
345 runInThread(context?.threadId, async (thread) => {
346 if (!isWebUrl(url)) {
347 throw new Error(
348 'Refused: navigate needs a full URL that starts with https:// or http://, like https://tanstack.com.',
349 )
350 }
351 const machine = await machineOf(thread)
352 if (machine.navigate === undefined) {
353 throw new Error('The computer driver has no navigate method.')
354 }
355 await machine.navigate(url)
356 await sleep(screenshotDelay)
357 return imageResult(await machine.screenshot())
358 }),
359 )
360​
361 const middleware: ChatMiddleware<unknown, typeof computerSafetyCheck> = {
362 name: 'computer-use',
363 onConfig(ctx) {
364 const thread = threads.get(ctx.threadId)
365 if (ctx.phase === 'beforeModel' && thread) thread.turnFailed = false
366 },
367 onInterruptBoundary(ctx) {
368 if (ctx.phase !== 'beforeTools') return undefined
369 const thread = threads.get(ctx.threadId)
370 const interrupts = computerToolCalls(ctx).flatMap((call) => {
371 const hasDecision =
372 thread?.approved.has(call.id) || thread?.declined.has(call.id)
373 if (hasDecision) return []
374 const checked = readCheckedInput(
375 parseArguments(call.function.arguments),
376 )
377 // The tool refuses a call whose checks do not parse.
378 if (checked === null || checked.checks.length === 0) return []
379 const { checks, action } = checked
380 return [
381 computerSafetyCheck.interrupt({
382 key: call.id,
383 reason: 'computer-safety-check',
384 message:
385 checks.find((check) => check.message)?.message ??
386 'Approve this computer action.',
387 payload: { checks, action },
388 }),
389 ]
390 })
391 return interrupts.length > 0 ? { interrupts } : undefined
392 },
393 onInterruptResolution(ctx, resolutions) {
394 const results = resolutions.for(computerSafetyCheck)
395 if (results.length === 0) return undefined
396 const thread = threadOf(ctx.threadId)
397 const isAllApproved = results.every(
398 (result) => result.status === 'resolved' && result.response.approved,
399 )
400 const decided = isAllApproved ? thread.approved : thread.declined
401 for (const result of results) decided.add(result.request.key)
402 return { toolResume: isAllApproved ? 'continue' : 'cancel' }
403 },
404 }
405​
406 async function close(threadId?: string) {
407 if (threadId !== undefined) {
408 const thread = threads.get(threadId)
409 if (thread) await closeThread(thread)
410 return
411 }
412 const all = [...threads.values()]
413 // A failed thread close does not keep the browser open. Every close runs,
414 // then the first error is thrown.
415 const results = await Promise.allSettled(
416 all.map((thread) => closeThread(thread)),
417 )
418 if ('create' in driver) await driver.close?.()
419 const failed = results.find((result) => result.status === 'rejected')
420 if (failed) throw failed.reason
421 }
422​
423 const tools: [ComputerTool] | [ComputerTool, NavigateTool] =
424 capabilities.navigate ? [computer, navigate] : [computer]
425​
426 return { tools, middleware, interrupt: computerSafetyCheck, close }