oira666_pi-browser-agent 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +101 -0
- package/package.json +28 -0
- package/src/broker/protocol.ts +127 -0
- package/src/broker/server.ts +331 -0
- package/src/broker/task-store.ts +192 -0
- package/src/index.ts +132 -0
- package/src/tools/_register.ts +89 -0
- package/src/tools/browser_agent_tools.ts +72 -0
- package/src/tools/browser_js_navigation_tools.ts +458 -0
- package/src/tools/browser_observability_tools.ts +167 -0
- package/src/tools/browser_task_tools.ts +383 -0
- package/src/tools/read_only/common.ts +173 -0
- package/src/tools/read_only/index.ts +312 -0
- package/src/util/paths.ts +19 -0
- package/src/util/truncate.ts +34 -0
- package/tests/broker.test.ts +241 -0
- package/tests/index.test.ts +153 -0
- package/tests/protocol.test.ts +48 -0
- package/tests/task-store.test.ts +35 -0
- package/tests/tools/browser-js-navigation-tools.test.ts +223 -0
- package/tests/tools/browser-observability-tools.test.ts +100 -0
- package/tests/tools/browser-read-only-tools.test.ts +225 -0
- package/tests/tools/browser-task-tools.test.ts +348 -0
- package/tests/tools/meta-tool.test.ts +110 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
import type { TSchema } from '@sinclair/typebox';
|
|
8
|
+
|
|
9
|
+
import type { BrowserAgentBroker } from '../../broker/server.ts';
|
|
10
|
+
import type { ResponseFrame } from '../../broker/protocol.ts';
|
|
11
|
+
import { truncateAndSpill } from '../../util/truncate.ts';
|
|
12
|
+
|
|
13
|
+
export interface ToolResult {
|
|
14
|
+
content: Array<{ type: 'text'; text: string }>;
|
|
15
|
+
details: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ReadOnlyToolDefinition<TParams = Record<string, unknown>> {
|
|
19
|
+
name: string;
|
|
20
|
+
label: string;
|
|
21
|
+
description: string;
|
|
22
|
+
promptSnippet: string;
|
|
23
|
+
parameters: TSchema;
|
|
24
|
+
execute: (toolCallId: string, params: TParams) => Promise<ToolResult>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class BrowserReadOnlyToolError extends Error {
|
|
28
|
+
code: string;
|
|
29
|
+
details?: unknown;
|
|
30
|
+
|
|
31
|
+
constructor(code: string, message: string, details?: unknown) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = 'BrowserReadOnlyToolError';
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.details = details;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function textResult(text: string, details: Record<string, unknown>): ToolResult {
|
|
40
|
+
return {
|
|
41
|
+
content: [{ type: 'text', text }],
|
|
42
|
+
details,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function coerceError(error: unknown, fallbackCode = 'E_INTERNAL'): BrowserReadOnlyToolError {
|
|
47
|
+
if (error instanceof BrowserReadOnlyToolError) {
|
|
48
|
+
return error;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (error && typeof error === 'object') {
|
|
52
|
+
const maybe = error as { code?: unknown; message?: unknown; details?: unknown };
|
|
53
|
+
if (typeof maybe.code === 'string' && typeof maybe.message === 'string') {
|
|
54
|
+
return new BrowserReadOnlyToolError(maybe.code, maybe.message, maybe.details);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
59
|
+
const normalizedCode =
|
|
60
|
+
message === 'E_BRIDGE_DISCONNECTED'
|
|
61
|
+
? 'E_BRIDGE_DISCONNECTED'
|
|
62
|
+
: /timed out/i.test(message)
|
|
63
|
+
? 'E_TIMEOUT'
|
|
64
|
+
: fallbackCode;
|
|
65
|
+
|
|
66
|
+
return new BrowserReadOnlyToolError(normalizedCode, message);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function ensureBridgeConnected(broker: BrowserAgentBroker): void {
|
|
70
|
+
const probe = broker.probeConnectivity();
|
|
71
|
+
if (!probe.brokerListening) {
|
|
72
|
+
throw new BrowserReadOnlyToolError('E_BRIDGE_DISCONNECTED', `Browser agent broker is not listening at ${probe.url}.`, probe);
|
|
73
|
+
}
|
|
74
|
+
if (!probe.bridgeConnected) {
|
|
75
|
+
throw new BrowserReadOnlyToolError('E_BRIDGE_DISCONNECTED', 'Browser agent bridge is not connected.', probe);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function requestBridge<TData>(
|
|
80
|
+
broker: BrowserAgentBroker,
|
|
81
|
+
type: string,
|
|
82
|
+
params: unknown,
|
|
83
|
+
options: { timeoutMs?: number } = {},
|
|
84
|
+
): Promise<{ response: ResponseFrame; data: TData }> {
|
|
85
|
+
ensureBridgeConnected(broker);
|
|
86
|
+
|
|
87
|
+
let response: ResponseFrame;
|
|
88
|
+
try {
|
|
89
|
+
response = await broker.request(type, params, options);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw coerceError(error, 'E_INTERNAL');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
throw new BrowserReadOnlyToolError(
|
|
96
|
+
response.error?.code || 'E_INTERNAL',
|
|
97
|
+
response.error?.message || `Bridge request ${type} failed`,
|
|
98
|
+
response.error?.details,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { response, data: response.data as TData };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function formatJsonResult(title: string, value: unknown, ext = 'json') {
|
|
106
|
+
const serialized = JSON.stringify(value, null, 2);
|
|
107
|
+
const truncated = await truncateAndSpill(serialized, ext);
|
|
108
|
+
const prefix = `${title}\n\n`;
|
|
109
|
+
return {
|
|
110
|
+
text: prefix + truncated.text,
|
|
111
|
+
truncated: truncated.truncated,
|
|
112
|
+
fullOutputPath: truncated.fullOutputPath,
|
|
113
|
+
serialized,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function formatTextResult(title: string, value: string, ext = 'txt') {
|
|
118
|
+
const truncated = await truncateAndSpill(value, ext);
|
|
119
|
+
const prefix = `${title}\n\n`;
|
|
120
|
+
return {
|
|
121
|
+
text: prefix + truncated.text,
|
|
122
|
+
truncated: truncated.truncated,
|
|
123
|
+
fullOutputPath: truncated.fullOutputPath,
|
|
124
|
+
raw: value,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function spillBase64Payload(base64: string, ext: string): Promise<string> {
|
|
129
|
+
const path = join(tmpdir(), `pi-browser-agent-${randomBytes(6).toString('hex')}.${ext}`);
|
|
130
|
+
await writeFile(path, Buffer.from(base64, 'base64'));
|
|
131
|
+
return path;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function normalizeScreenshotPayload(data: any): any {
|
|
135
|
+
if (!data || typeof data !== 'object') {
|
|
136
|
+
throw new BrowserReadOnlyToolError('E_INTERNAL', 'Screenshot payload was missing');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const normalized = {
|
|
140
|
+
mime: typeof data.mime === 'string' ? data.mime : 'image/jpeg',
|
|
141
|
+
data_base64: typeof data.data_base64 === 'string' ? data.data_base64 : typeof data.dataBase64 === 'string' ? data.dataBase64 : undefined,
|
|
142
|
+
width: typeof data.width === 'number' ? data.width : undefined,
|
|
143
|
+
height: typeof data.height === 'number' ? data.height : undefined,
|
|
144
|
+
url: typeof data.url === 'string' ? data.url : undefined,
|
|
145
|
+
title: typeof data.title === 'string' ? data.title : undefined,
|
|
146
|
+
path: typeof data.path === 'string' ? data.path : undefined,
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
if (!normalized.data_base64 && !normalized.path) {
|
|
150
|
+
throw new BrowserReadOnlyToolError('E_INTERNAL', 'Screenshot payload did not include image data');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return normalized;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function inferFileExtensionFromMime(mime: string): string {
|
|
157
|
+
if (mime.includes('png')) return 'png';
|
|
158
|
+
if (mime.includes('webp')) return 'webp';
|
|
159
|
+
return 'jpg';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function defaultTimeoutMs(toolName: string): number {
|
|
163
|
+
switch (toolName) {
|
|
164
|
+
case 'browser_wait_for':
|
|
165
|
+
return 35_000;
|
|
166
|
+
case 'browser_get_screenshot':
|
|
167
|
+
case 'browser_get_accessibility_tree':
|
|
168
|
+
case 'browser_get_performance_metrics':
|
|
169
|
+
return 20_000;
|
|
170
|
+
default:
|
|
171
|
+
return 15_000;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { Type } from '@sinclair/typebox';
|
|
2
|
+
|
|
3
|
+
import type { BrowserAgentBroker } from '../../broker/server.ts';
|
|
4
|
+
import {
|
|
5
|
+
BrowserReadOnlyToolError,
|
|
6
|
+
type ReadOnlyToolDefinition,
|
|
7
|
+
coerceError,
|
|
8
|
+
defaultTimeoutMs,
|
|
9
|
+
formatJsonResult,
|
|
10
|
+
formatTextResult,
|
|
11
|
+
inferFileExtensionFromMime,
|
|
12
|
+
normalizeScreenshotPayload,
|
|
13
|
+
requestBridge,
|
|
14
|
+
spillBase64Payload,
|
|
15
|
+
textResult,
|
|
16
|
+
} from './common.ts';
|
|
17
|
+
|
|
18
|
+
const SCREENSHOT_INLINE_LIMIT_BYTES = 256 * 1024;
|
|
19
|
+
|
|
20
|
+
function levelsType() {
|
|
21
|
+
return Type.Array(Type.Union([
|
|
22
|
+
Type.Literal('log'),
|
|
23
|
+
Type.Literal('info'),
|
|
24
|
+
Type.Literal('warn'),
|
|
25
|
+
Type.Literal('error'),
|
|
26
|
+
Type.Literal('debug'),
|
|
27
|
+
]));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function waitUntilType() {
|
|
31
|
+
return Type.Union([Type.Literal('load'), Type.Literal('networkidle'), Type.Literal('settle')]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function includeType(values: string[]) {
|
|
35
|
+
return Type.Array(Type.Union(values.map((value) => Type.Literal(value))));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function createJsonReadOnlyTool<TParams>(
|
|
39
|
+
broker: BrowserAgentBroker,
|
|
40
|
+
config: {
|
|
41
|
+
name: string;
|
|
42
|
+
label: string;
|
|
43
|
+
description: string;
|
|
44
|
+
promptSnippet: string;
|
|
45
|
+
parameters: any;
|
|
46
|
+
title: (data: any, params: TParams) => string;
|
|
47
|
+
normalizeData?: (data: any) => unknown;
|
|
48
|
+
timeoutMs?: (params: TParams) => number;
|
|
49
|
+
},
|
|
50
|
+
): ReadOnlyToolDefinition<TParams> {
|
|
51
|
+
return {
|
|
52
|
+
name: config.name,
|
|
53
|
+
label: config.label,
|
|
54
|
+
description: config.description,
|
|
55
|
+
promptSnippet: config.promptSnippet,
|
|
56
|
+
parameters: config.parameters,
|
|
57
|
+
async execute(_toolCallId: string, params: TParams) {
|
|
58
|
+
try {
|
|
59
|
+
const { data, response } = await requestBridge<any>(broker, config.name, params, {
|
|
60
|
+
timeoutMs: config.timeoutMs ? config.timeoutMs(params) : defaultTimeoutMs(config.name),
|
|
61
|
+
});
|
|
62
|
+
const normalized = config.normalizeData ? config.normalizeData(data) : data;
|
|
63
|
+
const formatted = await formatJsonResult(config.title(normalized, params), normalized);
|
|
64
|
+
return textResult(formatted.text, {
|
|
65
|
+
ok: true,
|
|
66
|
+
requestType: config.name,
|
|
67
|
+
response,
|
|
68
|
+
result: normalized,
|
|
69
|
+
truncated: formatted.truncated,
|
|
70
|
+
fullOutputPath: formatted.fullOutputPath,
|
|
71
|
+
});
|
|
72
|
+
} catch (error) {
|
|
73
|
+
const info = coerceError(error);
|
|
74
|
+
return textResult(`${config.label} failed: ${info.message}`, {
|
|
75
|
+
ok: false,
|
|
76
|
+
requestType: config.name,
|
|
77
|
+
error: { code: info.code, message: info.message, details: info.details },
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any> {
|
|
85
|
+
return {
|
|
86
|
+
name: 'browser_get_screenshot',
|
|
87
|
+
label: 'browser_get_screenshot',
|
|
88
|
+
description:
|
|
89
|
+
'Capture a compressed browser screenshot. Prefer selector/full_page options only when you need them. Large screenshots are spilled to a temp file and the file path is returned.',
|
|
90
|
+
promptSnippet: 'Capture a browser screenshot.',
|
|
91
|
+
parameters: Type.Object({
|
|
92
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
93
|
+
tab_id: Type.Optional(Type.Number()),
|
|
94
|
+
use_active_tab: Type.Optional(Type.Boolean()),
|
|
95
|
+
full_page: Type.Optional(Type.Boolean()),
|
|
96
|
+
selector: Type.Optional(Type.String({ minLength: 1 })),
|
|
97
|
+
wait_until: Type.Optional(waitUntilType()),
|
|
98
|
+
format: Type.Optional(Type.Union([Type.Literal('jpeg'), Type.Literal('png')])),
|
|
99
|
+
quality: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
100
|
+
max_width: Type.Optional(Type.Number({ minimum: 1 })),
|
|
101
|
+
}),
|
|
102
|
+
async execute(_toolCallId: string, params: any) {
|
|
103
|
+
try {
|
|
104
|
+
const { data, response } = await requestBridge<any>(broker, 'browser_get_screenshot', params, {
|
|
105
|
+
timeoutMs: defaultTimeoutMs('browser_get_screenshot'),
|
|
106
|
+
});
|
|
107
|
+
const normalized = normalizeScreenshotPayload(data);
|
|
108
|
+
let path = normalized.path;
|
|
109
|
+
let dataBase64 = normalized.data_base64;
|
|
110
|
+
const inlineBytes = dataBase64 ? Buffer.byteLength(dataBase64, 'base64') : 0;
|
|
111
|
+
|
|
112
|
+
if (!path && dataBase64 && inlineBytes > SCREENSHOT_INLINE_LIMIT_BYTES) {
|
|
113
|
+
path = await spillBase64Payload(dataBase64, inferFileExtensionFromMime(normalized.mime));
|
|
114
|
+
dataBase64 = undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const location = path ? `saved to ${path}` : `returned inline (${inlineBytes} bytes)`;
|
|
118
|
+
return textResult(
|
|
119
|
+
`Captured screenshot for ${normalized.title || normalized.url || 'tab'}; ${location}.`,
|
|
120
|
+
{
|
|
121
|
+
ok: true,
|
|
122
|
+
requestType: 'browser_get_screenshot',
|
|
123
|
+
response,
|
|
124
|
+
result: {
|
|
125
|
+
...normalized,
|
|
126
|
+
data_base64: dataBase64,
|
|
127
|
+
path,
|
|
128
|
+
},
|
|
129
|
+
inlined: !!dataBase64,
|
|
130
|
+
spilledToFile: !!path,
|
|
131
|
+
inlineBytes,
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
const info = coerceError(error);
|
|
136
|
+
return textResult(`browser_get_screenshot failed: ${info.message}`, {
|
|
137
|
+
ok: false,
|
|
138
|
+
requestType: 'browser_get_screenshot',
|
|
139
|
+
error: { code: info.code, message: info.message, details: info.details },
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any> {
|
|
147
|
+
return {
|
|
148
|
+
name: 'browser_get_html',
|
|
149
|
+
label: 'browser_get_html',
|
|
150
|
+
description:
|
|
151
|
+
'Extract HTML from a page. Prefer a CSS selector to return only the subtree you need. If the output is large, it is truncated and the full HTML is written to a temp file.',
|
|
152
|
+
promptSnippet: 'Get rendered HTML from the browser.',
|
|
153
|
+
parameters: Type.Object({
|
|
154
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
155
|
+
tab_id: Type.Optional(Type.Number()),
|
|
156
|
+
use_active_tab: Type.Optional(Type.Boolean()),
|
|
157
|
+
selector: Type.Optional(Type.String({ minLength: 1 })),
|
|
158
|
+
selector_all: Type.Optional(Type.Boolean()),
|
|
159
|
+
rendered: Type.Optional(Type.Boolean()),
|
|
160
|
+
wait_until: Type.Optional(waitUntilType()),
|
|
161
|
+
strip: Type.Optional(includeType(['script', 'style', 'comments'])),
|
|
162
|
+
max_bytes: Type.Optional(Type.Number({ minimum: 1 })),
|
|
163
|
+
}),
|
|
164
|
+
async execute(_toolCallId: string, params: any) {
|
|
165
|
+
try {
|
|
166
|
+
const { data, response } = await requestBridge<any>(broker, 'browser_get_html', params, {
|
|
167
|
+
timeoutMs: defaultTimeoutMs('browser_get_html'),
|
|
168
|
+
});
|
|
169
|
+
if (typeof data?.html !== 'string' && typeof data?.content !== 'string') {
|
|
170
|
+
throw new BrowserReadOnlyToolError(
|
|
171
|
+
'E_PROTOCOL',
|
|
172
|
+
'browser_get_html response did not include html/content payload',
|
|
173
|
+
{ data },
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
const html = typeof data?.html === 'string' ? data.html : (data.content as string);
|
|
177
|
+
const formatted = await formatTextResult(`HTML for ${data?.url || params.url || 'current page'}`, html, 'html');
|
|
178
|
+
return textResult(formatted.text, {
|
|
179
|
+
ok: true,
|
|
180
|
+
requestType: 'browser_get_html',
|
|
181
|
+
response,
|
|
182
|
+
result: { ...data, html },
|
|
183
|
+
truncated: formatted.truncated,
|
|
184
|
+
fullOutputPath: formatted.fullOutputPath,
|
|
185
|
+
});
|
|
186
|
+
} catch (error) {
|
|
187
|
+
const info = coerceError(error);
|
|
188
|
+
return textResult(`browser_get_html failed: ${info.message}`, {
|
|
189
|
+
ok: false,
|
|
190
|
+
requestType: 'browser_get_html',
|
|
191
|
+
error: { code: info.code, message: info.message, details: info.details },
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnlyToolDefinition[] {
|
|
199
|
+
return [
|
|
200
|
+
createScreenshotTool(broker),
|
|
201
|
+
createHtmlTool(broker),
|
|
202
|
+
createJsonReadOnlyTool(broker, {
|
|
203
|
+
name: 'browser_get_dom_info',
|
|
204
|
+
label: 'browser_get_dom_info',
|
|
205
|
+
description:
|
|
206
|
+
'Inspect DOM details for matching elements. Prefer a specific selector and narrow include fields. Supported include values: attributes, rect, textContent, innerHTML, accessibility, visibility, event_listeners, outer_html. Aliases also accepted: text -> textContent, html -> innerHTML, boundingBox -> rect. Large results are truncated and spilled to a temp file.',
|
|
207
|
+
promptSnippet: 'Inspect DOM details for selected elements.',
|
|
208
|
+
parameters: Type.Object({
|
|
209
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
210
|
+
selector: Type.String({ minLength: 1 }),
|
|
211
|
+
selector_all: Type.Optional(Type.Boolean()),
|
|
212
|
+
limit: Type.Optional(Type.Number({ minimum: 1, maximum: 200 })),
|
|
213
|
+
include: Type.Optional(includeType(['attributes', 'rect', 'textContent', 'innerHTML', 'accessibility', 'visibility', 'event_listeners', 'outer_html', 'text', 'html', 'boundingBox'])),},{
|
|
214
|
+
}),
|
|
215
|
+
title: (_data, params) => `DOM info for selector ${String((params as any).selector)}`,
|
|
216
|
+
}),
|
|
217
|
+
createJsonReadOnlyTool(broker, {
|
|
218
|
+
name: 'browser_get_computed_styles',
|
|
219
|
+
label: 'browser_get_computed_styles',
|
|
220
|
+
description:
|
|
221
|
+
'Read computed CSS styles. Prefer listing only the properties you need. Large results are truncated and spilled to a temp file.',
|
|
222
|
+
promptSnippet: 'Read computed CSS styles for a selector.',
|
|
223
|
+
parameters: Type.Object({
|
|
224
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
225
|
+
selector: Type.String({ minLength: 1 }),
|
|
226
|
+
properties: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
|
|
227
|
+
pseudo: Type.Optional(Type.String({ minLength: 1 })),
|
|
228
|
+
include_matched_rules: Type.Optional(Type.Boolean()),
|
|
229
|
+
include_inherited: Type.Optional(Type.Boolean()),
|
|
230
|
+
include_box_model: Type.Optional(Type.Boolean()),
|
|
231
|
+
}),
|
|
232
|
+
title: (_data, params) => `Computed styles for selector ${String((params as any).selector)}`,
|
|
233
|
+
}),
|
|
234
|
+
createJsonReadOnlyTool(broker, {
|
|
235
|
+
name: 'browser_list_tabs',
|
|
236
|
+
label: 'browser_list_tabs',
|
|
237
|
+
description: 'List browser tabs and identify the dedicated agent tab.',
|
|
238
|
+
promptSnippet: 'List browser tabs.',
|
|
239
|
+
parameters: Type.Object({}),
|
|
240
|
+
title: (data) => `Open browser tabs (${Array.isArray(data) ? data.length : 0})`,
|
|
241
|
+
normalizeData: (data) => (Array.isArray(data) ? data : data?.tabs ?? []),
|
|
242
|
+
}),
|
|
243
|
+
createJsonReadOnlyTool(broker, {
|
|
244
|
+
name: 'browser_wait_for',
|
|
245
|
+
label: 'browser_wait_for',
|
|
246
|
+
description: 'Wait for a selector, text, or URL condition. Returns the matched condition and timing details.',
|
|
247
|
+
promptSnippet: 'Wait for a page condition.',
|
|
248
|
+
parameters: Type.Object({
|
|
249
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
250
|
+
tab_id: Type.Optional(Type.Number()),
|
|
251
|
+
selector: Type.Optional(Type.String({ minLength: 1 })),
|
|
252
|
+
text: Type.Optional(Type.String({ minLength: 1 })),
|
|
253
|
+
url_matches: Type.Optional(Type.String({ minLength: 1 })),
|
|
254
|
+
state: Type.Optional(Type.Union([Type.Literal('visible'), Type.Literal('hidden'), Type.Literal('detached'), Type.Literal('attached')])),
|
|
255
|
+
timeout_ms: Type.Optional(Type.Number({ minimum: 1 })),
|
|
256
|
+
}),
|
|
257
|
+
title: (data) => `Wait result: ${String(data?.status || 'unknown')}`,
|
|
258
|
+
timeoutMs: (params: any) => {
|
|
259
|
+
const requested = Number(params?.timeout_ms || 30_000);
|
|
260
|
+
return Math.max(requested, 1) + 1_500;
|
|
261
|
+
},
|
|
262
|
+
}),
|
|
263
|
+
createJsonReadOnlyTool(broker, {
|
|
264
|
+
name: 'browser_get_accessibility_tree',
|
|
265
|
+
label: 'browser_get_accessibility_tree',
|
|
266
|
+
description:
|
|
267
|
+
'Read the accessibility tree. Prefer a root selector or include filters when possible. Large trees are truncated and spilled to a temp file.',
|
|
268
|
+
promptSnippet: 'Read the accessibility tree.',
|
|
269
|
+
parameters: Type.Object({
|
|
270
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
271
|
+
root_selector: Type.Optional(Type.String({ minLength: 1 })),
|
|
272
|
+
interesting_only: Type.Optional(Type.Boolean()),
|
|
273
|
+
max_depth: Type.Optional(Type.Number({ minimum: 1 })),
|
|
274
|
+
include: Type.Optional(includeType(['role', 'name', 'value', 'description', 'properties', 'children'])),
|
|
275
|
+
}),
|
|
276
|
+
title: () => 'Accessibility tree',
|
|
277
|
+
}),
|
|
278
|
+
createJsonReadOnlyTool(broker, {
|
|
279
|
+
name: 'browser_get_performance_metrics',
|
|
280
|
+
label: 'browser_get_performance_metrics',
|
|
281
|
+
description: 'Read performance metrics, timing, layout, memory, paint, and optional web-vitals data.',
|
|
282
|
+
promptSnippet: 'Read browser performance metrics.',
|
|
283
|
+
parameters: Type.Object({
|
|
284
|
+
url: Type.Optional(Type.String({ minLength: 1 })),
|
|
285
|
+
include: Type.Optional(includeType(['metrics', 'timing', 'web_vitals', 'layout', 'memory', 'paint'])),
|
|
286
|
+
}),
|
|
287
|
+
title: () => 'Performance metrics',
|
|
288
|
+
timeoutMs: (params: any) => ((params?.include as string[] | undefined)?.includes('web_vitals') ? 27_500 : defaultTimeoutMs('browser_get_performance_metrics')),
|
|
289
|
+
}),
|
|
290
|
+
];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function createReadOnlyBrowserToolMap(broker: BrowserAgentBroker): Map<string, ReadOnlyToolDefinition> {
|
|
294
|
+
return new Map(createReadOnlyBrowserTools(broker).map((tool) => [tool.name, tool]));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export const READ_ONLY_BROWSER_TOOL_NAMES = [
|
|
298
|
+
'browser_get_screenshot',
|
|
299
|
+
'browser_get_html',
|
|
300
|
+
'browser_get_dom_info',
|
|
301
|
+
'browser_get_computed_styles',
|
|
302
|
+
'browser_list_tabs',
|
|
303
|
+
'browser_wait_for',
|
|
304
|
+
'browser_get_accessibility_tree',
|
|
305
|
+
'browser_get_performance_metrics',
|
|
306
|
+
] as const;
|
|
307
|
+
|
|
308
|
+
export function createReadOnlyBrowserToolDefinitionsSummary() {
|
|
309
|
+
return READ_ONLY_BROWSER_TOOL_NAMES.map((name) => ({ name }));
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export { BrowserReadOnlyToolError };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { mkdir } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export function getStateDir(): string {
|
|
6
|
+
if (process.platform === 'win32') {
|
|
7
|
+
return join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'pi-browser-agent');
|
|
8
|
+
}
|
|
9
|
+
if (process.platform === 'darwin') {
|
|
10
|
+
return join(homedir(), 'Library', 'Application Support', 'pi-browser-agent');
|
|
11
|
+
}
|
|
12
|
+
return join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'pi-browser-agent');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function ensureStateDir(subdir?: string): Promise<string> {
|
|
16
|
+
const dir = subdir ? join(getStateDir(), subdir) : getStateDir();
|
|
17
|
+
await mkdir(dir, { recursive: true });
|
|
18
|
+
return dir;
|
|
19
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_MAX_BYTES = 50_000;
|
|
7
|
+
export const DEFAULT_MAX_LINES = 2_000;
|
|
8
|
+
|
|
9
|
+
export async function truncateAndSpill(text: string, ext = 'txt', maxBytes = DEFAULT_MAX_BYTES, maxLines = DEFAULT_MAX_LINES) {
|
|
10
|
+
const lines = text.split('\n');
|
|
11
|
+
const truncatedLines = lines.slice(0, maxLines);
|
|
12
|
+
let content = truncatedLines.join('\n');
|
|
13
|
+
let truncated = truncatedLines.length < lines.length;
|
|
14
|
+
|
|
15
|
+
if (Buffer.byteLength(content, 'utf8') > maxBytes) {
|
|
16
|
+
truncated = true;
|
|
17
|
+
while (Buffer.byteLength(content, 'utf8') > maxBytes && truncatedLines.length > 0) {
|
|
18
|
+
truncatedLines.pop();
|
|
19
|
+
content = truncatedLines.join('\n');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (!truncated) {
|
|
24
|
+
return { text: content, truncated: false, fullOutputPath: undefined };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const fullOutputPath = join(tmpdir(), `pi-browser-agent-${randomBytes(6).toString('hex')}.${ext}`);
|
|
28
|
+
await writeFile(fullOutputPath, text, 'utf8');
|
|
29
|
+
return {
|
|
30
|
+
text: `${content}\n\n[Output truncated. Full output: ${fullOutputPath}]`,
|
|
31
|
+
truncated: true,
|
|
32
|
+
fullOutputPath,
|
|
33
|
+
};
|
|
34
|
+
}
|