Open History to see the last commit
1import {
2 PermissionDecisionCapability,
3 PermissionResources,
4 PermissionRules,
5 definePlugin,
6} from '@tanstack/ai-harness'
7import { mediaPart } from '@tanstack/ai-harness/media'
8import { base64ToUint8Array } from '@tanstack/ai-utils'
9import { createComputerUse, readCheckedInput } from './create-computer-use'
10import type {
11 AnyChatMiddleware,
12 AnyTool,
13 ContentPart,
14 ModelMessage,
15} from '@tanstack/ai'
16import type { PluginSessionApi } from '@tanstack/ai-harness'
17import type { CreateComputerUseOptions } from './create-computer-use'
18
19/** Options for the `computerUse` harness plugin. */
20export interface ComputerUsePluginOptions extends CreateComputerUseOptions {
21 /**
22 * How many of the newest screenshots the model gets. An older screenshot
23 * goes to the model as a 1x1 image. The transcript keeps every
24 * screenshot. The default is 3.
25 */
26 keepScreenshots?: number
27}
28
29/**
30 * The permission action of a computer call with OpenAI safety checks.
31 * `@unsaved:` makes it ask each time: an `always` answer saves no rule.
32 */
33const SAFETY_CHECK = 'computer-safety-check@unsaved:'
34
35/**
36 * A 1x1 PNG. It replaces an old screenshot, because the OpenAI computer call
37 * output must have an image.
38 */
39const PLACEHOLDER: ContentPart = {
40 type: 'image',
41 source: {
42 type: 'data',
43 value:
44 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
45 mimeType: 'image/png',
46 },
47}
48
49/** True when a computer input has safety checks, or checks that do not parse. */
50function hasSafetyChecks(input: unknown) {
51 const checked = readCheckedInput(input)
52 return checked === null || checked.checks.length > 0
53}
54
55/**
56 * `messages`, with the images of all but the newest `keep` results of the
57 * tools in `names` swapped for a 1x1 image. The same array when nothing
58 * changes.
59 */
60export function keepNewestScreenshots(
61 messages: Array<ModelMessage>,
62 names: ReadonlySet<string>,
63 keep: number,
64) {
65 const callIds = new Set(
66 messages.flatMap((message) =>
67 (message.toolCalls ?? [])
68 .filter((call) => names.has(call.function.name))
69 .map((call) => call.id),
70 ),
71 )
72 let seen = 0
73 let changed = false
74 const kept = [...messages].reverse().map((message) => {
75 const { content } = message
76 const isScreenshot =
77 message.role === 'tool' &&
78 message.toolCallId !== undefined &&
79 callIds.has(message.toolCallId) &&
80 Array.isArray(content) &&
81 content.some((part) => part.type === 'image')
82 if (!isScreenshot) return message
83 seen += 1
84 if (seen <= keep) return message
85 changed = true
86 const parts = content.map((part) =>
87 part.type === 'image' ? PLACEHOLDER : part,
88 )
89 return { ...message, content: parts }
90 })
91 return changed ? kept.reverse() : messages
92}
93
94/** The result of a tool, with each inline image stored in the media store. */
95async function storeImages(
96 result: unknown,
97 putMedia: PluginSessionApi['putMedia'],
98) {
99 if (!Array.isArray(result)) return result
100 const parts: Array<ContentPart> = result
101 return Promise.all(
102 parts.map(async (part) => {
103 if (part.type !== 'image' || part.source.type !== 'data') return part
104 const record = await putMedia({
105 body: base64ToUint8Array(part.source.value),
106 mimeType: part.source.mimeType,
107 name: 'screenshot.png',
108 })
109 return mediaPart(record)
110 }),
111 )
112}
113
114/**
115 * Computer use in a harness. It adds the `computer` tool, and `navigate`
116 * when the driver can navigate. Each thread of a session gets its own
117 * machine from a driver factory.
118 *
119 * - Each screenshot goes to the media store of the session. The transcript
120 * and the log keep a small `harness-media:` reference.
121 * - The model gets only the newest `keepScreenshots` screenshots.
122 * - A call with OpenAI safety checks asks the user through `permissions()`,
123 * each time. Without `permissions()`, such a call is refused. The
124 * `bypass` mode runs it with no question.
125 * - The `plan` mode of `permissions()` refuses the `computer` tool.
126 *
127 * The machines live on the host, and close when the host closes. A thread
128 * that stays idle for `idleTimeout` loses its machine.
129 *
130 * @example
131 * ```ts
132 * defineHarness({
133 * name: 'browser-agent',
134 * adapter: openaiText('gpt-6.1-sol'),
135 * plugins: [
136 * permissions(),
137 * computerUse({ driver: playwrightComputer({ startUrl: 'https://tanstack.com' }) }),
138 * ],
139 * })
140 * ```
141 */
142export function computerUse({
143 keepScreenshots = 3,
144 ...options
145}: ComputerUsePluginOptions) {
146 return definePlugin({
147 name: 'tanstack/computer-use',
148 // One browser or one sandbox pool for the host, shared by its sessions.
149 lifetime: 'host',
150 optionalRequires: [PermissionDecisionCapability],
151 setup: async ({ resources }) => {
152 const computer = await resources.acquire(
153 () => createComputerUse(options),
154 (opened) => opened.close(),
155 )
156 const names = new Set(computer.tools.map((tool) => tool.name))
157 const middleware = {
158 name: 'tanstack/computer-use',
159 onConfig: async (ctx, config) => {
160 // It resets the failed-turn rule of the thread before each model call.
161 await computer.middleware.onConfig?.(ctx, config)
162 if (ctx.phase !== 'beforeModel') return undefined
163 const messages = config.providerMessages ?? config.messages
164 const kept = keepNewestScreenshots(messages, names, keepScreenshots)
165 return kept === messages ? undefined : { providerMessages: kept }
166 },
167 } satisfies AnyChatMiddleware
168 return {
169 middleware: [middleware],
170 agentMiddleware: [middleware],
171 contribute: [
172 // `execute`, so the plan mode refuses the clicks and the key presses.
173 PermissionRules.item({
174 tool: 'computer',
175 decision: 'allow',
176 kind: 'execute',
177 }),
178 PermissionRules.item({ tool: SAFETY_CHECK, decision: 'ask' }),
179 PermissionResources.item({
180 computer: {
181 actions: (input) =>
182 hasSafetyChecks(input) ? [SAFETY_CHECK] : [],
183 },
184 }),
185 ],
186 session: (ctx) => {
187 // `permissions()` asked the user before the call ran, so the tool
188 // runs it. Without `permissions()`, the tool refuses it.
189 const isAsked =
190 ctx.getOptional(PermissionDecisionCapability) !== undefined
191 const tools = computer.tools.map((tool: AnyTool): AnyTool => {
192 const { execute } = tool
193 if (execute === undefined) return tool
194 const run = async (input: unknown, context: unknown) => {
195 if (
196 !isAsked &&
197 tool.name === 'computer' &&
198 hasSafetyChecks(input)
199 ) {
200 throw new Error(
201 'Refused: this computer action has safety checks, and nobody can approve them. Add permissions() to the plugins of the harness.',
202 )
203 }
204 const checked =
205 isAsked && tool.name === 'computer' && isRecord(input)
206 ? { ...input, pending_safety_checks: [] }
207 : input
208 const result: unknown = await execute(checked, context)
209 return storeImages(result, ctx.session.putMedia)
210 }
211 return { ...tool, execute: run }
212 })
213 return { tools }
214 },
215 }
216 },
217 })
218}
219
220function isRecord(value: unknown): value is Record<string, unknown> {
221 return typeof value === 'object' && value !== null && !Array.isArray(value)
222}