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.
@@ -0,0 +1,167 @@
1
+ import { Type } from '@sinclair/typebox';
2
+
3
+ import type { BrowserAgentBroker } from '../broker/server.ts';
4
+ import {
5
+ coerceError,
6
+ defaultTimeoutMs,
7
+ formatJsonResult,
8
+ requestBridge,
9
+ textResult,
10
+ } from './read_only/common.ts';
11
+
12
+ interface ToolResult {
13
+ content: Array<{ type: 'text'; text: string }>;
14
+ details: Record<string, unknown>;
15
+ }
16
+
17
+ function withDefaultActiveTabTarget(params: Record<string, unknown>) {
18
+ if (typeof params.tab_id === 'number' || typeof params.url === 'string' || params.use_active_tab === true) {
19
+ return params;
20
+ }
21
+ return {
22
+ ...params,
23
+ use_active_tab: true,
24
+ };
25
+ }
26
+
27
+ function consoleLogText(details: any) {
28
+ return [
29
+ `Console log query returned ${details.returned} entry(s) from tab ${details.tabId}.`,
30
+ details.disconnectReason ? `Disconnect: ${details.disconnectReason}` : null,
31
+ details.preview ? `\n${details.preview}` : null,
32
+ ].filter(Boolean).join('\n');
33
+ }
34
+
35
+ function networkText(details: any) {
36
+ return [
37
+ `Network query returned ${details.returned} entry(s) from tab ${details.tabId}.`,
38
+ details.disconnectReason ? `Disconnect: ${details.disconnectReason}` : null,
39
+ details.preview ? `\n${details.preview}` : null,
40
+ ].filter(Boolean).join('\n');
41
+ }
42
+
43
+ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
44
+ return {
45
+ name: 'browser_get_console_logs',
46
+ label: 'browser_get_console_logs',
47
+ description:
48
+ 'Read buffered browser console logs. If you do not pass tab_id or url, this tool defaults to the active tab. Prefer passing filters such as levels, substring, regex, since, or last to narrow the result. If the output is large, it is truncated and the full result is written to a temp file whose path is included in the response.',
49
+ promptSnippet: 'Read filtered browser console logs.',
50
+ parameters: Type.Object({
51
+ tab_id: Type.Optional(Type.Number()),
52
+ url: Type.Optional(Type.String()),
53
+ use_active_tab: Type.Optional(Type.Boolean()),
54
+ levels: Type.Optional(Type.Array(Type.Union([
55
+ Type.Literal('log'), Type.Literal('info'), Type.Literal('warn'), Type.Literal('error'), Type.Literal('debug'),
56
+ ]))),
57
+ substring: Type.Optional(Type.String()),
58
+ regex: Type.Optional(Type.String()),
59
+ since: Type.Optional(Type.Number()),
60
+ last: Type.Optional(Type.Number({ minimum: 1 })),
61
+ include_exceptions: Type.Optional(Type.Boolean()),
62
+ include_stack: Type.Optional(Type.Boolean()),
63
+ timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
64
+ }),
65
+ async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
66
+ const requestParams = withDefaultActiveTabTarget(params);
67
+ try {
68
+ const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_console_logs', requestParams, {
69
+ timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_console_logs')),
70
+ });
71
+
72
+ const rendered = await formatJsonResult('Browser console logs', data, 'json');
73
+ const details = {
74
+ ok: true,
75
+ tabId: data.tabId,
76
+ total: data.total,
77
+ returned: data.returned,
78
+ disconnectedAt: data.disconnectedAt,
79
+ disconnectReason: data.disconnectReason,
80
+ truncation: rendered.truncated,
81
+ fullOutputPath: rendered.fullOutputPath,
82
+ preview: rendered.text,
83
+ };
84
+ return textResult(consoleLogText(details), details);
85
+ } catch (error) {
86
+ const info = coerceError(error);
87
+ return textResult(`browser_get_console_logs failed: ${info.message}`, {
88
+ ok: false,
89
+ error: { code: info.code, message: info.message, details: info.details },
90
+ });
91
+ }
92
+ },
93
+ };
94
+ }
95
+
96
+ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
97
+ return {
98
+ name: 'browser_get_network',
99
+ label: 'browser_get_network',
100
+ description:
101
+ 'Read buffered browser network activity. If you do not pass tab_id or url, this tool defaults to the active tab. Always pass filters such as status, type, url_contains, failed_only, since, or last, because unfiltered results may be large. Use include_request_body or include_response_body only when needed; bodies are size-capped. Large output is truncated and the full result is written to a temp file whose path is included in the response.',
102
+ promptSnippet: 'Read filtered browser network activity.',
103
+ parameters: Type.Object({
104
+ tab_id: Type.Optional(Type.Number()),
105
+ url: Type.Optional(Type.String()),
106
+ use_active_tab: Type.Optional(Type.Boolean()),
107
+ filter: Type.Optional(Type.Object({
108
+ method: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
109
+ status: Type.Optional(Type.Union([Type.Number(), Type.Array(Type.Number())])),
110
+ status_gte: Type.Optional(Type.Number()),
111
+ status_lt: Type.Optional(Type.Number()),
112
+ type: Type.Optional(Type.Array(Type.String())),
113
+ url_contains: Type.Optional(Type.String()),
114
+ url_matches: Type.Optional(Type.String()),
115
+ mime_contains: Type.Optional(Type.String()),
116
+ failed_only: Type.Optional(Type.Boolean()),
117
+ since: Type.Optional(Type.Number()),
118
+ until: Type.Optional(Type.Number()),
119
+ duration_gte_ms: Type.Optional(Type.Number()),
120
+ last: Type.Optional(Type.Number({ minimum: 1 })),
121
+ initiator_contains: Type.Optional(Type.String()),
122
+ })),
123
+ include_request_headers: Type.Optional(Type.Boolean()),
124
+ include_response_headers: Type.Optional(Type.Boolean()),
125
+ include_request_body: Type.Optional(Type.Boolean()),
126
+ include_response_body: Type.Optional(Type.Boolean()),
127
+ body_max_bytes: Type.Optional(Type.Number({ minimum: 1, maximum: 1024 * 1024 })),
128
+ include_timing: Type.Optional(Type.Boolean()),
129
+ timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
130
+ }),
131
+ async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
132
+ const requestParams = withDefaultActiveTabTarget(params);
133
+ try {
134
+ const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_network', requestParams, {
135
+ timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_network')),
136
+ });
137
+
138
+ const rendered = await formatJsonResult('Browser network activity', data, 'json');
139
+ const details = {
140
+ ok: true,
141
+ tabId: data.tabId,
142
+ total: data.total,
143
+ returned: data.returned,
144
+ disconnectedAt: data.disconnectedAt,
145
+ disconnectReason: data.disconnectReason,
146
+ truncation: rendered.truncated,
147
+ fullOutputPath: rendered.fullOutputPath,
148
+ preview: rendered.text,
149
+ };
150
+ return textResult(networkText(details), details);
151
+ } catch (error) {
152
+ const info = coerceError(error);
153
+ return textResult(`browser_get_network failed: ${info.message}`, {
154
+ ok: false,
155
+ error: { code: info.code, message: info.message, details: info.details },
156
+ });
157
+ }
158
+ },
159
+ };
160
+ }
161
+
162
+ export function createBufferedObservabilityToolDefinitions(broker: BrowserAgentBroker) {
163
+ return {
164
+ browser_get_console_logs: createBrowserGetConsoleLogsTool(broker),
165
+ browser_get_network: createBrowserGetNetworkTool(broker),
166
+ };
167
+ }
@@ -0,0 +1,383 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { Type } from '@sinclair/typebox';
4
+
5
+ import type { BrowserAgentBroker } from '../broker/server.ts';
6
+ import type { ResponseFrame } from '../broker/protocol.ts';
7
+ import { assertValidTaskId, TaskCorruptionError, type TaskStoreEntry } from '../broker/task-store.ts';
8
+
9
+ interface ToolResult {
10
+ content: Array<{ type: 'text'; text: string }>;
11
+ details: Record<string, unknown>;
12
+ }
13
+
14
+ const TERMINAL_TASK_STATUSES = new Set(['done', 'error', 'stopped', 'rejected']);
15
+
16
+ function terminalStatusOf(data: any): string | null {
17
+ if (typeof data?.status === 'string' && TERMINAL_TASK_STATUSES.has(data.status)) {
18
+ return data.status;
19
+ }
20
+ if (data?.cancelled === true) {
21
+ return 'stopped';
22
+ }
23
+ return null;
24
+ }
25
+
26
+ function runtimeErrorFromData(data: any, status: string): { code: string; message: string; details?: unknown } | null {
27
+ if (status !== 'error') {
28
+ return null;
29
+ }
30
+
31
+ if (data?.error && typeof data.error.code === 'string' && typeof data.error.message === 'string') {
32
+ return data.error;
33
+ }
34
+
35
+ return {
36
+ code: 'E_RUNTIME',
37
+ message: typeof data?.message === 'string' && data.message ? data.message : 'Browser task failed',
38
+ details: data,
39
+ };
40
+ }
41
+
42
+ function errorInfoFromUnknown(error: unknown): { code: string; message: string; details?: unknown } {
43
+ if (error && typeof error === 'object') {
44
+ const maybe = error as { code?: unknown; message?: unknown; details?: unknown };
45
+ if (typeof maybe.code === 'string' && typeof maybe.message === 'string') {
46
+ return { code: maybe.code, message: maybe.message, details: maybe.details };
47
+ }
48
+ }
49
+
50
+ const message = error instanceof Error ? error.message : String(error);
51
+ return {
52
+ code: message === 'E_BRIDGE_DISCONNECTED' ? 'E_BRIDGE_DISCONNECTED' : 'E_INTERNAL',
53
+ message,
54
+ };
55
+ }
56
+
57
+ function textResult(text: string, details: Record<string, unknown>): ToolResult {
58
+ return {
59
+ content: [{ type: 'text', text }],
60
+ details,
61
+ };
62
+ }
63
+
64
+ function statusText(status: string): string {
65
+ switch (status) {
66
+ case 'done':
67
+ return 'completed';
68
+ case 'stopped':
69
+ return 'stopped';
70
+ case 'error':
71
+ return 'failed';
72
+ case 'running':
73
+ return 'running';
74
+ case 'rejected':
75
+ return 'rejected';
76
+ default:
77
+ return status;
78
+ }
79
+ }
80
+
81
+ async function appendSafe(broker: BrowserAgentBroker, taskId: string, entry: TaskStoreEntry): Promise<void> {
82
+ try {
83
+ await broker.taskStore.append(taskId, entry);
84
+ } catch {
85
+ // Never let history persistence break parent tool execution.
86
+ }
87
+ }
88
+
89
+ async function safeReadHistory(broker: BrowserAgentBroker, taskId: string): Promise<TaskStoreEntry[]> {
90
+ try {
91
+ return await broker.taskStore.read(taskId);
92
+ } catch {
93
+ return [];
94
+ }
95
+ }
96
+
97
+ async function readHistoryStrict(
98
+ broker: BrowserAgentBroker,
99
+ taskId: string,
100
+ ): Promise<{ ok: true; history: TaskStoreEntry[] } | { ok: false; corrupted: boolean; error: { code: string; message: string } }> {
101
+ try {
102
+ return { ok: true, history: await broker.taskStore.read(taskId) };
103
+ } catch (error) {
104
+ if (error instanceof TaskCorruptionError) {
105
+ return {
106
+ ok: false,
107
+ corrupted: true,
108
+ error: { code: 'E_HISTORY_CORRUPTED', message: error.message },
109
+ };
110
+ }
111
+ // Any other error (e.g. ENOENT) means there's no readable history.
112
+ return {
113
+ ok: false,
114
+ corrupted: false,
115
+ error: { code: 'E_NOT_FOUND', message: `Task ${taskId} was not found` },
116
+ };
117
+ }
118
+ }
119
+
120
+ function summarizeHistory(taskId: string, history: TaskStoreEntry[]) {
121
+ const first = history[0] ?? {};
122
+ const last = history[history.length - 1] ?? {};
123
+ return {
124
+ taskId,
125
+ status: typeof last.status === 'string' ? last.status : typeof first.status === 'string' ? first.status : 'unknown',
126
+ startedAt: typeof first.startedAt === 'number' ? first.startedAt : undefined,
127
+ endedAt: typeof last.endedAt === 'number' ? last.endedAt : undefined,
128
+ task: typeof first.task === 'string' ? first.task : undefined,
129
+ result: last.result,
130
+ error: last.error,
131
+ events: history.length,
132
+ };
133
+ }
134
+
135
+ async function finishRecordedTask(
136
+ broker: BrowserAgentBroker,
137
+ taskId: string,
138
+ status: string,
139
+ extras: Record<string, unknown>,
140
+ ): Promise<TaskStoreEntry[]> {
141
+ await appendSafe(broker, taskId, {
142
+ kind: 'task_finished',
143
+ taskId,
144
+ status,
145
+ endedAt: Date.now(),
146
+ ...extras,
147
+ });
148
+ return await safeReadHistory(broker, taskId);
149
+ }
150
+
151
+
152
+ function formatHistorySummaryText(historySummary: any): string | null {
153
+ if (!historySummary || typeof historySummary !== 'object') {
154
+ return null;
155
+ }
156
+ if (typeof historySummary.text === 'string' && historySummary.text.trim()) {
157
+ return historySummary.text.trim();
158
+ }
159
+ const recentSteps = Array.isArray(historySummary.recentSteps) ? historySummary.recentSteps : [];
160
+ if (recentSteps.length === 0) {
161
+ return null;
162
+ }
163
+ return recentSteps
164
+ .map((step: any, index: number) => {
165
+ const parts = [];
166
+ const num = typeof step?.stepNumber === 'number' ? step.stepNumber + 1 : index + 1;
167
+ if (typeof step?.evaluation === 'string' && step.evaluation) parts.push(`evaluation: ${step.evaluation}`);
168
+ if (typeof step?.nextGoal === 'string' && step.nextGoal) parts.push(`next: ${step.nextGoal}`);
169
+ if (typeof step?.actionResult === 'string' && step.actionResult) parts.push(`result: ${step.actionResult}`);
170
+ return `${num}. ${parts.join(' | ') || 'step recorded'}`;
171
+ })
172
+ .join('\n');
173
+ }
174
+
175
+ function formatResponseText(taskId: string, status: string, message?: string, historySummary?: any): string {
176
+ const lines = [
177
+ `Browser task ${taskId}`,
178
+ `Status: ${statusText(status)}`,
179
+ `Success: ${status === 'done' ? 'yes' : 'no'}`,
180
+ message ? `Message: ${message}` : null,
181
+ ].filter(Boolean) as string[];
182
+
183
+ const historyText = formatHistorySummaryText(historySummary);
184
+ if (historyText) {
185
+ lines.push('History summary:');
186
+ lines.push(historyText);
187
+ }
188
+
189
+ return lines.join('\n');
190
+ }
191
+
192
+ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
193
+ return {
194
+ name: 'browser_run_task',
195
+ label: 'browser_run_task',
196
+ description: 'Run a browser task end-to-end. The task might be secribed with natural English',
197
+ promptSnippet: 'Run a browser task.',
198
+ parameters: Type.Object({
199
+ task: Type.String({ minLength: 1 }),
200
+ debugMode: Type.Optional(Type.Boolean()),
201
+ timeoutMs: Type.Optional(Type.Number({ minimum: 1 })),
202
+ }),
203
+ async execute(_toolCallId: string, params: { task: string; debugMode?: boolean; timeoutMs?: number }): Promise<ToolResult> {
204
+ const probe = broker.probeConnectivity();
205
+ const taskId = randomUUID();
206
+ const startedAt = Date.now();
207
+
208
+ await appendSafe(broker, taskId, {
209
+ kind: 'task_started',
210
+ taskId,
211
+ task: params.task,
212
+ status: 'running',
213
+ startedAt,
214
+ request: { debugMode: params.debugMode ?? false, timeoutMs: params.timeoutMs },
215
+ });
216
+
217
+ let response: ResponseFrame;
218
+ try {
219
+ response = await broker.request(
220
+ 'browser_run_task',
221
+ { taskId, task: params.task, debugMode: params.debugMode ?? false },
222
+ { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000 },
223
+ );
224
+ } catch (error) {
225
+ const errorInfo = errorInfoFromUnknown(error);
226
+ const history = await finishRecordedTask(broker, taskId, 'error', {
227
+ error: errorInfo,
228
+ bridge: { connected: broker.probeConnectivity().bridgeConnected },
229
+ });
230
+ return textResult(formatResponseText(taskId, 'error', errorInfo.message), {
231
+ ok: false,
232
+ success: false,
233
+ taskId,
234
+ status: 'error',
235
+ error: errorInfo,
236
+ probe,
237
+ history,
238
+ summary: summarizeHistory(taskId, history),
239
+ historySummary: null,
240
+ });
241
+ }
242
+
243
+ if (!response.ok) {
244
+ const errorInfo = {
245
+ code: response.error?.code || 'E_INTERNAL',
246
+ message: response.error?.message || 'Browser task failed',
247
+ details: response.error?.details,
248
+ };
249
+ const history = await finishRecordedTask(broker, taskId, errorInfo.code === 'E_BUSY' ? 'rejected' : 'error', {
250
+ error: errorInfo,
251
+ });
252
+ return textResult(formatResponseText(taskId, errorInfo.code === 'E_BUSY' ? 'rejected' : 'error', errorInfo.message), {
253
+ ok: false,
254
+ success: false,
255
+ taskId,
256
+ status: errorInfo.code === 'E_BUSY' ? 'rejected' : 'error',
257
+ error: errorInfo,
258
+ response,
259
+ probe,
260
+ history,
261
+ summary: summarizeHistory(taskId, history),
262
+ historySummary: null,
263
+ });
264
+ }
265
+
266
+ const resolvedStatus = terminalStatusOf(response.data);
267
+ if (!resolvedStatus) {
268
+ const errorInfo = {
269
+ code: 'E_PROTOCOL',
270
+ message: 'Bridge returned a success response for browser_run_task without a recognized terminal status',
271
+ details: { data: response.data },
272
+ };
273
+ const history = await finishRecordedTask(broker, taskId, 'error', { error: errorInfo });
274
+ return textResult(formatResponseText(taskId, 'error', errorInfo.message), {
275
+ ok: false,
276
+ success: false,
277
+ taskId,
278
+ status: 'error',
279
+ error: errorInfo,
280
+ response,
281
+ probe,
282
+ history,
283
+ summary: summarizeHistory(taskId, history),
284
+ historySummary: null,
285
+ });
286
+ }
287
+ const status = resolvedStatus;
288
+ const runtimeError = runtimeErrorFromData(response.data, status);
289
+ const history = await finishRecordedTask(broker, taskId, status, runtimeError ? { error: runtimeError } : { result: response.data });
290
+ const message = typeof (response.data as any)?.message === 'string' ? (response.data as any).message : undefined;
291
+
292
+ const historySummary = (response.data as any)?.historySummary;
293
+
294
+ return textResult(formatResponseText(taskId, status, message, historySummary), {
295
+ ok: !runtimeError,
296
+ success: status === 'done' && !runtimeError,
297
+ taskId,
298
+ status,
299
+ result: runtimeError ? undefined : response.data,
300
+ error: runtimeError || undefined,
301
+ probe,
302
+ history,
303
+ summary: summarizeHistory(taskId, history),
304
+ historySummary,
305
+ });
306
+ },
307
+ };
308
+ }
309
+
310
+ export function createBrowserGetTaskHistoryTool(broker: BrowserAgentBroker) {
311
+ return {
312
+ name: 'browser_get_task_history',
313
+ label: 'browser_get_task_history',
314
+ description: 'Read stored browser task history.',
315
+ promptSnippet: 'Read task history.',
316
+ parameters: Type.Object({
317
+ taskId: Type.String({ minLength: 1 }),
318
+ }),
319
+ async execute(_toolCallId: string, params: { taskId: string }): Promise<ToolResult> {
320
+ try {
321
+ assertValidTaskId(params.taskId);
322
+ } catch (error) {
323
+ const errorInfo = errorInfoFromUnknown(error);
324
+ return textResult(`Invalid browser task id ${params.taskId}.`, {
325
+ ok: false,
326
+ taskId: params.taskId,
327
+ error: errorInfo,
328
+ });
329
+ }
330
+
331
+ const readResult = await readHistoryStrict(broker, params.taskId);
332
+ if (!readResult.ok) {
333
+ // Distinguish corrupted history from "not found" so operators aren't
334
+ // misled into thinking no data ever existed.
335
+ const prefix = readResult.corrupted
336
+ ? `Browser task history for ${params.taskId} is corrupted.`
337
+ : `No browser task history found for ${params.taskId}.`;
338
+ return textResult(prefix, {
339
+ ok: false,
340
+ taskId: params.taskId,
341
+ corrupted: readResult.corrupted,
342
+ error: readResult.error,
343
+ });
344
+ }
345
+ const history = readResult.history;
346
+ if (history.length === 0) {
347
+ return textResult(`No browser task history found for ${params.taskId}.`, {
348
+ ok: false,
349
+ taskId: params.taskId,
350
+ error: { code: 'E_NOT_FOUND', message: `Task ${params.taskId} was not found` },
351
+ });
352
+ }
353
+
354
+ return textResult(`Loaded ${history.length} history event(s) for browser task ${params.taskId}.`, {
355
+ ok: true,
356
+ taskId: params.taskId,
357
+ history,
358
+ summary: summarizeHistory(params.taskId, history),
359
+ });
360
+ },
361
+ };
362
+ }
363
+
364
+ export function createBrowserListTasksTool(broker: BrowserAgentBroker) {
365
+ return {
366
+ name: 'browser_list_tasks',
367
+ label: 'browser_list_tasks',
368
+ description: 'List recent browser tasks.',
369
+ promptSnippet: 'List recent browser tasks.',
370
+ parameters: Type.Object({
371
+ limit: Type.Optional(Type.Number({ minimum: 1, maximum: 200 })),
372
+ status: Type.Optional(Type.String()),
373
+ }),
374
+ async execute(_toolCallId: string, params: { limit?: number; status?: string }): Promise<ToolResult> {
375
+ const tasks = await broker.taskStore.list({ limit: params.limit, status: params.status });
376
+ return textResult(`Loaded ${tasks.length} browser task(s).`, {
377
+ ok: true,
378
+ tasks,
379
+ });
380
+ },
381
+ };
382
+ }
383
+