-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
579 lines (504 loc) · 18.2 KB
/
index.ts
File metadata and controls
579 lines (504 loc) · 18.2 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import { MelonyPlugin, Event } from "melony";
import { z } from "zod";
import * as fs from "fs";
import { Stagehand } from "@browserbasehq/stagehand";
import type { ModelMessage, V3Options } from "@browserbasehq/stagehand";
import { ui } from "@melony/ui-kit/server";
// ---------------------------------------------------------------------------
// Tool definitions
// ---------------------------------------------------------------------------
export const browserToolDefinitions = {
browser_action: {
description:
"Perform a multi-step browser task using natural language. The agent will autonomously navigate, interact, and extract data to fulfill the instruction.",
inputSchema: z.object({
instruction: z
.string()
.describe(
"The high-level goal to achieve, e.g. 'Go to GitHub, find the most starred repo for typescript, and tell me its name and stars count'"
),
}),
},
browser_screenshot: {
description: "Take a screenshot of the current page and return page info.",
inputSchema: z.object({}),
},
browser_cleanup: {
description: "Close the browser and release all resources.",
inputSchema: z.object({}),
},
};
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface BrowserToolsOptions {
/**
* Model configuration. Accepts:
* - A string like "openai/gpt-4o", "anthropic/claude-3-5-sonnet-latest", or just "gpt-4o" / "claude-3-5-sonnet-latest"
* - A Stagehand model config object: { modelName: "gpt-4o", apiKey?: "..." }
*/
model?: V3Options["model"];
/** Additional Stagehand constructor options */
stagehandConfig?: Partial<Omit<V3Options, "env">>;
/** The directory to store the browser's user data */
userDataDir?: string;
// system prompt
systemPrompt?: string;
}
export interface BrowserStatusEvent extends Event {
type: "browser:status";
data: { message: string; severity?: "info" | "success" | "error" };
}
export interface BrowserStateUpdateEvent extends Event {
type: "browser:state-update";
data: {
url: string;
title: string;
screenshot?: string;
};
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function normalizeAssistantMessage(message: ModelMessage): string[] {
if (typeof message?.content === "string") {
return [message.content];
}
if (Array.isArray(message?.content)) {
return message.content
.map((m: any) => {
if (typeof m === "string") return m;
if (m.type === "text") return m.text;
if (m.type === "tool-call") {
const tc = m;
if (tc.toolName === "act") return `> **Action:** ${tc.input?.action}`;
if (tc.toolName === "goto") return `> **Navigate to:** ${tc.input?.url}`;
if (tc.toolName === "extract") return `> **Extracting information...**`;
if (tc.toolName === "observe") return `> **Observing page...**`;
return `> **Tool Call:** ${tc.toolName}`;
}
return null;
})
.filter((m): m is string => m !== null);
}
return [];
}
function normalizeToolMessage(message: ModelMessage): string {
const content = message.content;
if (!content) return "";
// Try to parse if it's JSON
let data;
if (typeof content === "string") {
try {
data = JSON.parse(content);
} catch {
data = content;
}
} else {
data = content;
}
// Handle Stagehand's tool-result array
if (Array.isArray(data)) {
return data
.map((item: any) => {
if (item.type === "tool-result") {
const toolName = item.toolName;
const outputValue = item.output?.value;
const success = outputValue?.success ?? true;
const emoji = success ? "✅" : "❌";
let details = "";
if (toolName === "goto") {
details = `Reached ${outputValue?.url || "destination"}`;
} else if (toolName === "act") {
details = outputValue?.action || "Action successful";
} else if (toolName === "extract") {
details = "Data extracted";
if (outputValue) {
const summary = JSON.stringify(outputValue);
details += ": " + (summary.length > 200 ? summary.slice(0, 200) + "..." : summary);
}
} else if (toolName === "done") {
details = outputValue?.reasoning || "Task finished";
} else if (toolName === "ariaTree") {
// For ariaTree, item.output.value is often an array of content blocks
if (Array.isArray(outputValue) && outputValue[0]?.text) {
const text = outputValue[0].text;
details = "Accessibility tree retrieved (" + (text.length > 100 ? text.slice(0, 100).replace(/\n/g, " ") + "..." : text.replace(/\n/g, " ")) + ")";
} else {
details = "Accessibility tree retrieved";
}
} else if (toolName === "keys") {
details = `Pressed ${outputValue?.value || "keys"}`;
} else {
const summary = JSON.stringify(outputValue || {});
details = summary.length > 200 ? summary.slice(0, 200) + "..." : summary;
}
return ` - *Result (${toolName}):* ${emoji} ${details}`;
}
return ` - *Result:* ${JSON.stringify(item).slice(0, 200)}`;
})
.join("\n");
}
const strContent = typeof content === "string" ? content : JSON.stringify(content);
if (strContent.length > 500) {
return ` - *Result:* ${strContent.slice(0, 500)}...`;
}
return ` - *Result:* ${strContent}`;
}
// ---------------------------------------------------------------------------
// Plugin factory
// ---------------------------------------------------------------------------
export const browserToolsPlugin = (
options: BrowserToolsOptions = {}
): MelonyPlugin<any, any> => {
const SESSION_KEY = "__browser_tools_plugin_session__";
type BrowserSessionState = {
stagehand?: Stagehand;
initPromise?: Promise<Stagehand>;
usage: {
inputTokens: number;
outputTokens: number;
totalTokens: number;
};
};
const getSession = (): BrowserSessionState => {
const g = globalThis as typeof globalThis & {
[SESSION_KEY]?: BrowserSessionState;
};
if (!g[SESSION_KEY]) {
g[SESSION_KEY] = {
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
};
} else if (!g[SESSION_KEY].usage) {
g[SESSION_KEY].usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
}
return g[SESSION_KEY]!;
};
const isSessionError = (error: unknown) => {
const message = (error as Error | undefined)?.message?.toLowerCase() || "";
return (
message.includes("target closed") ||
message.includes("has been closed") ||
message.includes("browser has been closed") ||
message.includes("context closed") ||
message.includes("session closed")
);
};
const clearSession = async () => {
const session = getSession();
const current = session.stagehand;
session.stagehand = undefined;
session.initPromise = undefined;
if (current) {
await current.close().catch(() => { });
}
};
const resolveModelConfig = () => {
const model = options.model;
if (!model) {
return { model: "openai/gpt-4o" };
}
if (typeof model === "string") {
return { model };
}
if (
typeof model === "object" &&
"specificationVersion" in model &&
(model as any).specificationVersion === "v3"
) {
const v3Model = model as any;
const provider = v3Model.config?.provider?.split(".")[0];
const modelId = v3Model.modelId;
if (provider && modelId) {
return { model: `${provider}/${modelId}` };
}
}
return { model };
};
async function ensureStagehand(): Promise<Stagehand> {
const session = getSession();
if (session.stagehand) {
try {
// Probe active page to ensure the session is still valid.
const page = session.stagehand.context.activePage();
if (page) {
return session.stagehand;
}
} catch {
await clearSession();
}
}
if (session.initPromise) {
return session.initPromise;
}
session.initPromise = (async () => {
if (options.userDataDir && !fs.existsSync(options.userDataDir)) {
console.log(
`[browser-tools] Creating userDataDir: ${options.userDataDir}`
);
fs.mkdirSync(options.userDataDir, { recursive: true });
}
const opts: V3Options = {
env: "LOCAL",
verbose: 1,
selfHeal: true,
experimental: true,
disableAPI: true,
...options.stagehandConfig,
localBrowserLaunchOptions: {
...options.stagehandConfig?.localBrowserLaunchOptions,
...(options.userDataDir ? { userDataDir: options.userDataDir } : {}),
},
};
const sh = new Stagehand(opts);
await sh.init();
session.stagehand = sh;
return sh;
})()
.catch(async (error) => {
await clearSession();
throw error;
})
.finally(() => {
session.initPromise = undefined;
});
return session.initPromise;
}
/** Get the active page from the stagehand context, throwing if none */
function getPage(sh: Stagehand) {
const page = sh.context.activePage();
if (!page) {
throw new Error("No active browser page. Navigate to a URL first.");
}
return page;
}
return (builder) => {
// -- helpers ------------------------------------------------------------
async function* yieldState(sh: Stagehand) {
try {
const page = getPage(sh);
if (!page) return;
// Wait for page to stabilize before screenshotting
await page.waitForLoadState("load", 5000).catch(() => { });
await page.waitForLoadState("networkidle", 2000).catch(() => { });
await page.waitForTimeout(500).catch(() => { });
const url = page.url();
const title = await page.title();
const buf = await page
.screenshot({ type: "jpeg", quality: 60 })
.catch(() => null);
const base64 = buf ? Buffer.from(buf).toString("base64") : undefined;
yield {
type: "browser:state-update",
data: { url, title, screenshot: base64 },
} as BrowserStateUpdateEvent;
} catch (e) {
console.error("[browser-tools] state update failed:", e);
}
}
function actionResult(
action: string,
toolCallId: string,
result: string
) {
return {
type: "action:result",
data: { action, toolCallId, result },
};
}
// -- browser_action ----------------------------------------------------
builder.on("action:browser_action" as any, async function* (event) {
const { toolCallId, instruction } = event.data;
yield {
type: "browser:status",
data: { message: `Executing browser action: ${instruction}` },
} as BrowserStatusEvent;
try {
const modelConfig = resolveModelConfig();
const sh = await ensureStagehand();
const agent = sh.agent({
mode: "dom",
...modelConfig,
systemPrompt: options.systemPrompt || "You are a helpful browser automation assistant. Achieve the user's goal by navigating, interacting with elements, and extracting information as needed.",
stream: true,
});
const streamResult = await agent.execute({
instruction,
maxSteps: 20,
});
for await (const part of streamResult.fullStream) {
// if (part.type === "text-delta" || part.type === "reasoning-delta") {
// const delta = (part as any).textDelta || (part as any).reasoningDelta;
// if (delta) {
// yield {
// type: "browser:status",
// data: { message: delta },
// } as BrowserStatusEvent;
// }
// }
if (part.type === "error") {
yield {
type: "browser:status",
data: {
message: `Error: ${(part as any).error}`,
severity: "error",
},
} as BrowserStatusEvent;
}
if (part.type === "tool-call") {
const tc = part as any;
let msg = `Action: ${tc.toolName}`;
if (tc.toolName === "act")
msg = `Browser action: ${tc.input?.action}`;
else if (tc.toolName === "goto")
msg = `Navigating to: ${tc.input?.url}`;
else if (tc.toolName === "extract")
msg = `Extracting information...`;
yield {
type: "browser:status",
data: { message: msg },
} as BrowserStatusEvent;
}
if (part.type === "tool-result") {
// yield* yieldState(sh);
}
}
const result = await streamResult.result;
const executionTrace: string[] = [];
if (result.messages) {
for (const m of result.messages) {
if (m.role === "assistant") {
executionTrace.push(...normalizeAssistantMessage(m));
} else if (m.role === "tool") {
executionTrace.push(normalizeToolMessage(m));
}
}
}
console.log(
"executionTrace",
JSON.stringify(executionTrace, null, 2)
);
// Yield usage
if (result.usage) {
const state = getSession();
const usageEventType = "usage:update";
const usageScope = "browser_action";
const modelId =
typeof modelConfig.model === "string"
? modelConfig.model
: (modelConfig.model as any)?.modelName || "openai/gpt-4o";
const turn = {
inputTokens: result.usage.input_tokens ?? 0,
outputTokens: result.usage.output_tokens ?? 0,
totalTokens:
(result.usage.input_tokens ?? 0) +
(result.usage.output_tokens ?? 0),
};
state.usage.inputTokens += turn.inputTokens;
state.usage.outputTokens += turn.outputTokens;
state.usage.totalTokens += turn.totalTokens;
yield {
type: usageEventType,
data: {
scope: usageScope,
model: modelId,
turn,
session: {
inputTokens: state.usage.inputTokens,
outputTokens: state.usage.outputTokens,
totalTokens: state.usage.totalTokens,
},
},
} as Event;
}
// Final state update
yield* yieldState(sh);
yield {
type: "browser:status",
data: { message: result.message },
} as BrowserStatusEvent;
const history = executionTrace.length > 0
? "\n\n### Browser Execution History\n\n" + executionTrace.join("\n")
: "";
yield actionResult("browser_action", toolCallId, result.message + history);
} catch (error: any) {
if (isSessionError(error)) {
await clearSession();
}
yield actionResult("browser_action", toolCallId, `Error: ${error.message}`);
}
});
// -- browser_screenshot -------------------------------------------------
builder.on("action:browser_screenshot" as any, async function* (event) {
const { toolCallId } = event.data;
try {
const sh = await ensureStagehand();
const page = getPage(sh);
const url = page.url();
const title = await page.title();
yield* yieldState(sh);
yield actionResult("browser_screenshot", toolCallId, `URL: ${url}\nTitle: ${title}`);
} catch (error: any) {
if (isSessionError(error)) {
await clearSession();
}
yield actionResult("browser_screenshot", toolCallId, `Error: ${error.message}`);
}
});
// -- browser_cleanup ----------------------------------------------------
builder.on("action:browser_cleanup" as any, async function* (event) {
const { toolCallId } = event.data;
try {
await clearSession();
yield actionResult("browser_cleanup", toolCallId, "Browser closed");
} catch (error: any) {
await clearSession();
yield actionResult("browser_cleanup", toolCallId, `Error: ${error.message}`);
}
});
// Register UI handlers
browserToolsUIPlugin()(builder);
};
};
// ---------------------------------------------------------------------------
// UI Plugin
// ---------------------------------------------------------------------------
export const browserToolsUIPlugin =
(): MelonyPlugin<any, any> => (builder) => {
builder.on(
"browser:status" as any,
async function* (event: BrowserStatusEvent) {
yield ui.event(ui.text(event.data.message, { size: "xs", color: event.data.severity === "error" ? "destructiveForeground" : "foreground" }));
}
);
builder.on(
"browser:state-update" as any,
async function* (event: BrowserStateUpdateEvent) {
if (event.data.screenshot) {
yield ui.event(
ui.box({ border: true, padding: "md", radius: "md" }, [
ui.col({ gap: "md" }, [
ui.col({ gap: "xs" }, [
ui.text(event.data.title, { size: "sm" }),
ui.text(event.data.url, { size: "xs", color: "mutedForeground" }),
]),
ui.box({ border: true, radius: "md", overflow: "hidden" }, [
ui.image(`data:image/jpeg;base64,${event.data.screenshot}`),
]),
]),
])
);
}
}
);
};
// ---------------------------------------------------------------------------
// Plugin Entry for Registry
// ---------------------------------------------------------------------------
export const plugin = {
name: "browser-tools",
description: "Browse the web and interact with pages using Stagehand",
toolDefinitions: browserToolDefinitions,
factory: (options: BrowserToolsOptions) => browserToolsPlugin(options),
};
export default plugin;