oira666_pi-browser-agent 0.0.5 → 0.0.7
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/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
|
|
3
|
-
import { BrowserAgentBroker } from './broker/server.ts';
|
|
3
|
+
import { BrowserAgentBroker, type BrokerLogger } from './broker/server.ts';
|
|
4
4
|
import { RemoteBrowserAgentBroker } from './broker/remote.ts';
|
|
5
5
|
import { TaskStore } from './broker/task-store.ts';
|
|
6
6
|
import { ensureStateDir } from './util/paths.ts';
|
|
@@ -9,6 +9,11 @@ import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register
|
|
|
9
9
|
import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
|
|
10
10
|
|
|
11
11
|
type BrowserAgentBrokerLike = BrowserAgentBroker | RemoteBrowserAgentBroker;
|
|
12
|
+
type ExtensionUi = {
|
|
13
|
+
notify?: (message: string, type?: 'info' | 'warning' | 'error') => void;
|
|
14
|
+
setStatus?: (key: string, text: string | undefined) => void;
|
|
15
|
+
};
|
|
16
|
+
type ExtensionContextLike = { ui?: ExtensionUi };
|
|
12
17
|
|
|
13
18
|
let brokerSingleton: BrowserAgentBrokerLike | null = null;
|
|
14
19
|
let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
|
|
@@ -35,7 +40,41 @@ export async function resetForTests(): Promise<void> {
|
|
|
35
40
|
startupMessage = null;
|
|
36
41
|
}
|
|
37
42
|
|
|
38
|
-
|
|
43
|
+
function formatLogArg(value: unknown): string {
|
|
44
|
+
if (value instanceof Error) {
|
|
45
|
+
return value.stack || value.message;
|
|
46
|
+
}
|
|
47
|
+
if (typeof value === 'string') {
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
return JSON.stringify(value);
|
|
52
|
+
} catch {
|
|
53
|
+
return String(value);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function createUiLogger(ctx?: ExtensionContextLike): BrokerLogger {
|
|
58
|
+
const notify = ctx?.ui?.notify;
|
|
59
|
+
if (typeof notify !== 'function') {
|
|
60
|
+
return { info() {}, warn() {}, error() {} };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const emit = (type: 'info' | 'warning' | 'error', args: unknown[]) => {
|
|
64
|
+
const message = args.map(formatLogArg).filter(Boolean).join(' ');
|
|
65
|
+
if (message) {
|
|
66
|
+
notify(message, type);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
info: (...args: unknown[]) => emit('info', args),
|
|
72
|
+
warn: (...args: unknown[]) => emit('warning', args),
|
|
73
|
+
error: (...args: unknown[]) => emit('error', args),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function createAndStartBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
|
|
39
78
|
const tasksDir = await ensureStateDir('tasks');
|
|
40
79
|
const preferredPort = Number(process.env.PI_BA_PORT || 7878);
|
|
41
80
|
const host = process.env.PI_BA_HOST || '127.0.0.1';
|
|
@@ -99,7 +138,7 @@ async function createAndStartBroker(logger: Console): Promise<BrowserAgentBroker
|
|
|
99
138
|
}
|
|
100
139
|
}
|
|
101
140
|
|
|
102
|
-
async function getOrCreateBroker(logger:
|
|
141
|
+
async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
|
|
103
142
|
// If an existing broker is healthy, reuse it.
|
|
104
143
|
if (brokerSingleton) {
|
|
105
144
|
const probe = brokerSingleton.probeConnectivity();
|
|
@@ -131,15 +170,16 @@ async function getOrCreateBroker(logger: Console = console): Promise<BrowserAgen
|
|
|
131
170
|
}
|
|
132
171
|
|
|
133
172
|
export default async function piBrowserAgentExtension(pi: {
|
|
134
|
-
on: (event: string, handler: (_event: unknown, ctx?:
|
|
173
|
+
on: (event: string, handler: (_event: unknown, ctx?: ExtensionContextLike) => Promise<void> | void) => void;
|
|
135
174
|
registerTool: (tool: any) => void;
|
|
136
175
|
}) {
|
|
137
|
-
const registerSessionTool = async (ctx?:
|
|
176
|
+
const registerSessionTool = async (ctx?: ExtensionContextLike) => {
|
|
138
177
|
resetBrowserAgentToolState();
|
|
139
178
|
resetRegisteredBrowserTools();
|
|
179
|
+
const logger = createUiLogger(ctx);
|
|
140
180
|
|
|
141
181
|
try {
|
|
142
|
-
const broker = await getOrCreateBroker();
|
|
182
|
+
const broker = await getOrCreateBroker(logger);
|
|
143
183
|
startupMessage = null;
|
|
144
184
|
pi.registerTool(createBrowserAgentToolsTool(pi, broker));
|
|
145
185
|
// pi reads the tool registry at session_start; any later registerTool()
|
|
@@ -158,6 +198,7 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
158
198
|
// session still exposes a diagnostic surface. Do NOT publish this broker
|
|
159
199
|
// as the singleton — we want a real bind retry on the next session.
|
|
160
200
|
const fallbackBroker = new BrowserAgentBroker({
|
|
201
|
+
logger,
|
|
161
202
|
taskStore: new TaskStore({ dir: join(await ensureStateDir('tasks')) }),
|
|
162
203
|
});
|
|
163
204
|
pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker));
|
|
@@ -8,11 +8,7 @@ import {
|
|
|
8
8
|
requestBridge,
|
|
9
9
|
textResult,
|
|
10
10
|
} from './read_only/common.ts';
|
|
11
|
-
|
|
12
|
-
interface ToolResult {
|
|
13
|
-
content: Array<{ type: 'text'; text: string }>;
|
|
14
|
-
details: Record<string, unknown>;
|
|
15
|
-
}
|
|
11
|
+
import type { ToolResult } from './read_only/common.ts';
|
|
16
12
|
|
|
17
13
|
function withDefaultActiveTabTarget(params: Record<string, unknown>) {
|
|
18
14
|
if (typeof params.tab_id === 'number' || typeof params.url === 'string' || params.use_active_tab === true) {
|
|
@@ -10,8 +10,12 @@ import type { BrowserAgentBroker } from '../../broker/server.ts';
|
|
|
10
10
|
import type { ResponseFrame } from '../../broker/protocol.ts';
|
|
11
11
|
import { truncateAndSpill } from '../../util/truncate.ts';
|
|
12
12
|
|
|
13
|
+
export type ToolResultContentBlock =
|
|
14
|
+
| { type: 'text'; text: string }
|
|
15
|
+
| { type: 'image'; source: { type: 'base64'; media_type: string; data: string } };
|
|
16
|
+
|
|
13
17
|
export interface ToolResult {
|
|
14
|
-
content:
|
|
18
|
+
content: ToolResultContentBlock[];
|
|
15
19
|
details: Record<string, unknown>;
|
|
16
20
|
}
|
|
17
21
|
|
|
@@ -43,6 +47,23 @@ export function textResult(text: string, details: Record<string, unknown>): Tool
|
|
|
43
47
|
};
|
|
44
48
|
}
|
|
45
49
|
|
|
50
|
+
export function imageResult(text: string, image: { mime: string; dataBase64: string }, details: Record<string, unknown>): ToolResult {
|
|
51
|
+
return {
|
|
52
|
+
content: [
|
|
53
|
+
{ type: 'text', text },
|
|
54
|
+
{
|
|
55
|
+
type: 'image',
|
|
56
|
+
source: {
|
|
57
|
+
type: 'base64',
|
|
58
|
+
media_type: image.mime,
|
|
59
|
+
data: image.dataBase64,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
details,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
46
67
|
export function coerceError(error: unknown, fallbackCode = 'E_INTERNAL'): BrowserReadOnlyToolError {
|
|
47
68
|
if (error instanceof BrowserReadOnlyToolError) {
|
|
48
69
|
return error;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
|
|
1
3
|
import { Type } from '@sinclair/typebox';
|
|
2
4
|
|
|
3
5
|
import type { BrowserAgentBroker } from '../../broker/server.ts';
|
|
@@ -8,6 +10,7 @@ import {
|
|
|
8
10
|
defaultTimeoutMs,
|
|
9
11
|
formatJsonResult,
|
|
10
12
|
formatTextResult,
|
|
13
|
+
imageResult,
|
|
11
14
|
inferFileExtensionFromMime,
|
|
12
15
|
normalizeScreenshotPayload,
|
|
13
16
|
requestBridge,
|
|
@@ -15,7 +18,7 @@ import {
|
|
|
15
18
|
textResult,
|
|
16
19
|
} from './common.ts';
|
|
17
20
|
|
|
18
|
-
const
|
|
21
|
+
const SCREENSHOT_IMAGE_CONTENT_LIMIT_BYTES = 5 * 1024 * 1024;
|
|
19
22
|
|
|
20
23
|
function levelsType() {
|
|
21
24
|
return Type.Array(Type.Union([
|
|
@@ -81,6 +84,21 @@ function createJsonReadOnlyTool<TParams>(
|
|
|
81
84
|
};
|
|
82
85
|
}
|
|
83
86
|
|
|
87
|
+
function redactScreenshotResponse(response: any): any {
|
|
88
|
+
if (!response || typeof response !== 'object' || !response.data || typeof response.data !== 'object') {
|
|
89
|
+
return response;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
...response,
|
|
94
|
+
data: {
|
|
95
|
+
...response.data,
|
|
96
|
+
data_base64: undefined,
|
|
97
|
+
dataBase64: undefined,
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
84
102
|
function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any> {
|
|
85
103
|
return {
|
|
86
104
|
name: 'browser_get_screenshot',
|
|
@@ -107,30 +125,44 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
|
|
|
107
125
|
const normalized = normalizeScreenshotPayload(data);
|
|
108
126
|
let path = normalized.path;
|
|
109
127
|
let dataBase64 = normalized.data_base64;
|
|
110
|
-
|
|
128
|
+
let imageBytes = dataBase64 ? Buffer.byteLength(dataBase64, 'base64') : 0;
|
|
111
129
|
|
|
112
|
-
if (!
|
|
130
|
+
if (!dataBase64 && path) {
|
|
131
|
+
const buffer = await readFile(path);
|
|
132
|
+
imageBytes = buffer.length;
|
|
133
|
+
if (imageBytes <= SCREENSHOT_IMAGE_CONTENT_LIMIT_BYTES) {
|
|
134
|
+
dataBase64 = buffer.toString('base64');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (!path && dataBase64) {
|
|
113
139
|
path = await spillBase64Payload(dataBase64, inferFileExtensionFromMime(normalized.mime));
|
|
114
|
-
dataBase64 = undefined;
|
|
115
140
|
}
|
|
116
141
|
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
{
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
spilledToFile: !!path,
|
|
131
|
-
inlineBytes,
|
|
142
|
+
const canAttachImage = !!dataBase64 && imageBytes <= SCREENSHOT_IMAGE_CONTENT_LIMIT_BYTES;
|
|
143
|
+
const location = path ? `saved to ${path}` : `captured ${imageBytes} bytes`;
|
|
144
|
+
const text = canAttachImage
|
|
145
|
+
? `Captured screenshot for ${normalized.title || normalized.url || 'tab'}; attached as an image (${imageBytes} bytes). ${location}.`
|
|
146
|
+
: `Captured screenshot for ${normalized.title || normalized.url || 'tab'}; image is too large to attach (${imageBytes} bytes), ${location}.`;
|
|
147
|
+
const details = {
|
|
148
|
+
ok: true,
|
|
149
|
+
requestType: 'browser_get_screenshot',
|
|
150
|
+
response: redactScreenshotResponse(response),
|
|
151
|
+
result: {
|
|
152
|
+
...normalized,
|
|
153
|
+
data_base64: undefined,
|
|
154
|
+
path,
|
|
132
155
|
},
|
|
133
|
-
|
|
156
|
+
imageAttached: canAttachImage,
|
|
157
|
+
spilledToFile: !!path,
|
|
158
|
+
imageBytes,
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
if (canAttachImage) {
|
|
162
|
+
return imageResult(text, { mime: normalized.mime, dataBase64 }, details);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return textResult(text, details);
|
|
134
166
|
} catch (error) {
|
|
135
167
|
const info = coerceError(error);
|
|
136
168
|
return textResult(`browser_get_screenshot failed: ${info.message}`, {
|
package/tests/index.test.ts
CHANGED
|
@@ -140,6 +140,51 @@ test('extension retries broker startup on a later session after a transient bind
|
|
|
140
140
|
}
|
|
141
141
|
});
|
|
142
142
|
|
|
143
|
+
test('broker startup diagnostics are routed through the extension UI context', async () => {
|
|
144
|
+
await resetForTests();
|
|
145
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
146
|
+
const originalRange = process.env.PI_BA_PORT_RANGE;
|
|
147
|
+
const originalNoEph = process.env.PI_BA_NO_EPHEMERAL;
|
|
148
|
+
const blockedPort = await getFreePort();
|
|
149
|
+
const blocker = net.createServer();
|
|
150
|
+
const notifications: Array<{ message: string; type?: string }> = [];
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
await new Promise<void>((resolve, reject) => blocker.listen(blockedPort, '127.0.0.1', () => resolve()).once('error', reject));
|
|
154
|
+
process.env.PI_BA_PORT = String(blockedPort);
|
|
155
|
+
process.env.PI_BA_PORT_RANGE = '1';
|
|
156
|
+
process.env.PI_BA_NO_EPHEMERAL = '1';
|
|
157
|
+
|
|
158
|
+
const pi = createPiHarness();
|
|
159
|
+
await extension(pi as any);
|
|
160
|
+
const sessionStart = pi.handlers.get('session_start');
|
|
161
|
+
|
|
162
|
+
await sessionStart({}, { ui: { notify: (message: string, type?: string) => notifications.push({ message, type }) } });
|
|
163
|
+
|
|
164
|
+
assert.equal(getBroker(), null);
|
|
165
|
+
assert.ok(notifications.some((entry) => entry.type === 'warning' && entry.message.includes('primary broker port is busy')));
|
|
166
|
+
assert.ok(notifications.some((entry) => entry.type === 'error' && entry.message.includes('Browser agent unavailable')));
|
|
167
|
+
} finally {
|
|
168
|
+
await resetForTests();
|
|
169
|
+
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
|
170
|
+
if (originalPort === undefined) {
|
|
171
|
+
delete process.env.PI_BA_PORT;
|
|
172
|
+
} else {
|
|
173
|
+
process.env.PI_BA_PORT = originalPort;
|
|
174
|
+
}
|
|
175
|
+
if (originalRange === undefined) {
|
|
176
|
+
delete process.env.PI_BA_PORT_RANGE;
|
|
177
|
+
} else {
|
|
178
|
+
process.env.PI_BA_PORT_RANGE = originalRange;
|
|
179
|
+
}
|
|
180
|
+
if (originalNoEph === undefined) {
|
|
181
|
+
delete process.env.PI_BA_NO_EPHEMERAL;
|
|
182
|
+
} else {
|
|
183
|
+
process.env.PI_BA_NO_EPHEMERAL = originalNoEph;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
|
|
143
188
|
test('overlapping session_start calls yield a single shared broker instance', async () => {
|
|
144
189
|
await resetForTests();
|
|
145
190
|
const originalPort = process.env.PI_BA_PORT;
|
|
@@ -62,7 +62,7 @@ test('browser_get_html truncates oversized HTML and spills the full output to a
|
|
|
62
62
|
await rm(spillPath, { force: true });
|
|
63
63
|
});
|
|
64
64
|
|
|
65
|
-
test('browser_get_screenshot
|
|
65
|
+
test('browser_get_screenshot returns screenshots as image content and never exposes base64 in details', async () => {
|
|
66
66
|
const largeBase64 = Buffer.alloc(300 * 1024, 7).toString('base64');
|
|
67
67
|
const tools = createReadOnlyBrowserToolMap(createBrokerHarness(async (type) => {
|
|
68
68
|
assert.equal(type, 'browser_get_screenshot');
|
|
@@ -84,9 +84,13 @@ test('browser_get_screenshot spills large inline payloads to a temp file', async
|
|
|
84
84
|
|
|
85
85
|
const result = await tools.get('browser_get_screenshot')!.execute('call-1', {});
|
|
86
86
|
assert.equal(result.details.ok, true);
|
|
87
|
-
assert.equal(result.details.
|
|
87
|
+
assert.equal(result.details.imageAttached, true);
|
|
88
88
|
assert.equal(result.details.spilledToFile, true);
|
|
89
|
+
assert.equal((result.content?.[1] as any)?.type, 'image');
|
|
90
|
+
assert.equal((result.content?.[1] as any)?.source?.media_type, 'image/jpeg');
|
|
91
|
+
assert.equal((result.content?.[1] as any)?.source?.data, largeBase64);
|
|
89
92
|
assert.equal((result.details.result as any).data_base64, undefined);
|
|
93
|
+
assert.equal((result.details.response as any).data.data_base64, undefined);
|
|
90
94
|
|
|
91
95
|
const spillPath = String((result.details.result as any).path);
|
|
92
96
|
const spilled = await readFile(spillPath);
|