-
Notifications
You must be signed in to change notification settings - Fork 692
Expand file tree
/
Copy pathcomputer-use.ts
More file actions
244 lines (220 loc) · 7.15 KB
/
computer-use.ts
File metadata and controls
244 lines (220 loc) · 7.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { chromium, Browser, Page } from 'playwright';
import { Agent, run, withTrace, computerTool, Computer } from '@openai/agents';
async function singletonComputer() {
// If your app never runs multiple computer using agents at the same time,
// you can create a singleton computer and use it in all your agents.
const computer = await new LocalPlaywrightComputer().init();
try {
const agent = new Agent({
name: 'Browser user',
model: 'gpt-5.4',
instructions:
'You are a helpful agent. Find the current weather in Tokyo.',
tools: [computerTool({ computer })],
});
await withTrace('CUA Example', async () => {
const result = await run(
agent,
'What is the weather in Tokyo right now?',
);
console.log(`\nFinal response:\n${result.finalOutput}`);
});
} finally {
await computer.dispose();
}
}
async function computerPerRequest() {
// If your app runs multiple computer using agents at the same time,
// you can create a computer per request.
const agent = new Agent({
name: 'Browser user',
model: 'gpt-5.4',
instructions: 'You are a helpful agent. Find the current weather in Tokyo.',
tools: [
computerTool({
// initialize a new computer for each run and dispose it after the run is complete
computer: {
create: async ({ runContext }) => {
console.log('Initializing computer for run context:', runContext);
return await new LocalPlaywrightComputer().init();
},
dispose: async ({ runContext, computer }) => {
console.log('Disposing of computer for run context:', runContext);
await computer.dispose();
},
},
}),
],
});
await withTrace('CUA Example', async () => {
const result = await run(agent, 'What is the weather in Tokyo right now?');
console.log(`\nFinal response:\n${result.finalOutput}`);
});
}
// --- CUA KEY TO PLAYWRIGHT KEY MAP ---
const CUA_KEY_TO_PLAYWRIGHT_KEY: Record<string, string> = {
'/': 'Divide',
'\\': 'Backslash',
alt: 'Alt',
arrowdown: 'ArrowDown',
arrowleft: 'ArrowLeft',
arrowright: 'ArrowRight',
arrowup: 'ArrowUp',
backspace: 'Backspace',
capslock: 'CapsLock',
cmd: 'Meta',
ctrl: 'Control',
delete: 'Delete',
end: 'End',
enter: 'Enter',
esc: 'Escape',
home: 'Home',
insert: 'Insert',
option: 'Alt',
pagedown: 'PageDown',
pageup: 'PageUp',
shift: 'Shift',
space: ' ',
super: 'Meta',
tab: 'Tab',
win: 'Meta',
};
// --- LocalPlaywrightComputer Implementation ---
class LocalPlaywrightComputer implements Computer {
private _browser: Browser | null = null;
private _page: Page | null = null;
get dimensions(): [number, number] {
return [1024, 768];
}
get environment(): 'browser' {
return 'browser';
}
get browser(): Browser {
if (!this._browser) throw new Error('Browser not initialized');
return this._browser;
}
get page(): Page {
if (!this._page) throw new Error('Page not initialized');
return this._page;
}
async _get_browser_and_page(): Promise<[Browser, Page]> {
const [width, height] = this.dimensions;
const browser = await chromium.launch({
headless: false,
args: [`--window-size=${width},${height}`],
});
const page = await browser.newPage();
await page.setViewportSize({ width, height });
await page.goto('https://www.bing.com/');
return [browser, page];
}
async init(): Promise<this> {
[this._browser, this._page] = await this._get_browser_and_page();
return this;
}
async dispose(): Promise<void> {
console.log('Disposing of browser and page');
if (this._browser) await this._browser.close();
this._browser = null;
this._page = null;
}
async screenshot(): Promise<string> {
console.log('Taking a screenshot');
try {
if (!this._page) throw new Error('Page not initialized');
if (!this._browser) throw new Error('Browser not initialized');
if (typeof this._page.isClosed === 'function' && this._page.isClosed()) {
throw new Error('Page is already closed');
}
// Be more lenient: fall back to 'load' if networkidle stalls (e.g., long polling ads/widgets).
try {
await this._page.waitForLoadState('networkidle', { timeout: 15000 });
} catch (_err) {
console.warn('networkidle wait timed out; retrying with load state');
await this._page.waitForLoadState('load', { timeout: 15000 });
}
// One retry of the screenshot to reduce transient failures.
const buf = await this._page.screenshot({ fullPage: false });
return Buffer.from(buf).toString('base64');
} catch (err) {
console.error('Screenshot failed:', err);
throw err;
}
}
async click(
x: number,
y: number,
button: 'left' | 'right' | 'wheel' | 'back' | 'forward' = 'left',
): Promise<void> {
console.log(`Clicking at (${x}, ${y})`);
// Playwright only supports 'left', 'right', 'middle'; others fallback to 'left'
let playwrightButton: 'left' | 'right' | 'middle' = 'left';
if (button === 'right') playwrightButton = 'right';
await this.page.mouse.click(x, y, { button: playwrightButton });
}
async doubleClick(x: number, y: number): Promise<void> {
console.log('doubleClick');
await this.page.mouse.dblclick(x, y);
}
async scroll(
x: number,
y: number,
scrollX: number,
scrollY: number,
): Promise<void> {
console.log(`Scrolling to (${x}, ${y}) by (${scrollX}, ${scrollY})`);
await this.page.mouse.move(x, y);
await this.page.evaluate(
([sx, sy]) => window.scrollBy(sx, sy),
[scrollX, scrollY],
);
}
async type(text: string): Promise<void> {
console.log(`Typing: ${text}`);
await this.page.keyboard.type(text);
}
async wait(): Promise<void> {
console.log('Waiting');
await new Promise((resolve) => setTimeout(resolve, 1000));
}
async move(x: number, y: number): Promise<void> {
console.log(`Moving to (${x}, ${y})`);
await this.page.mouse.move(x, y);
}
async keypress(keys: string[]): Promise<void> {
console.log(`Pressing keys: ${keys}`);
const mappedKeys = keys.map(
(key) => CUA_KEY_TO_PLAYWRIGHT_KEY[key.toLowerCase()] || key,
);
for (const key of mappedKeys) {
await this.page.keyboard.down(key);
}
for (const key of mappedKeys.reverse()) {
await this.page.keyboard.up(key);
}
}
async drag(path: Array<[number, number]>): Promise<void> {
console.log(`Dragging path: ${path}`);
if (!path.length) return;
await this.page.mouse.move(path[0][0], path[0][1]);
await this.page.mouse.down();
for (const [px, py] of path.slice(1)) {
await this.page.mouse.move(px, py);
}
await this.page.mouse.up();
}
}
const mode = (process.argv[2] ?? '').toLowerCase();
if (mode === 'singleton') {
// Choose singleton mode for cases where concurrent runs are not expected.
singletonComputer().catch((error) => {
console.error(error);
process.exit(1);
});
} else {
// Default to per-request mode to avoid sharing state across runs.
computerPerRequest().catch((error) => {
console.error(error);
process.exit(1);
});
}