oira666_pi-browser-agent 0.0.11 → 0.0.13

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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-browser-agent",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -82,6 +82,25 @@ export class RemoteBrowserAgentBroker {
82
82
  }
83
83
  }
84
84
 
85
+ /** Lazily ensure a primary broker is reachable on demand. Tools call this at
86
+ * the start of every request so a killed primary is replaced without waiting
87
+ * for the socket-close handler: reconnect to the current primary, or (if
88
+ * none is listening) compete to become the new primary. Idempotent and safe
89
+ * to call concurrently — `promoteOrReconnect()` dedupes the bind race. */
90
+ async ensureReady(): Promise<void> {
91
+ if (this.promotedBroker) {
92
+ await this.promotedBroker.ensureReady();
93
+ return;
94
+ }
95
+ try {
96
+ await this.ensureConnected();
97
+ this.remoteProbe = await this.probePrimary();
98
+ this.startupError = null;
99
+ } catch {
100
+ await this.promoteOrReconnect();
101
+ }
102
+ }
103
+
85
104
  async stop(): Promise<void> {
86
105
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
87
106
  const socket = this.socket;
@@ -141,6 +141,24 @@ export class BrowserAgentBroker {
141
141
  }
142
142
  }
143
143
 
144
+ /** Lazily (re)acquire the broker listener on demand. Tools call this at the
145
+ * start of every request so that a process whose broker was stopped (or was
146
+ * never bound, or whose primary died) competes for the port at request time
147
+ * instead of failing permanently. No-op when already listening; on failure
148
+ * (e.g. another process already won the port) it leaves `startupError` set so
149
+ * `probeConnectivity()` reports not-listening and the caller surfaces a clear
150
+ * message, while a later request can still retry. */
151
+ async ensureReady(): Promise<void> {
152
+ if (this.server) {
153
+ return;
154
+ }
155
+ try {
156
+ await this.start();
157
+ } catch (error) {
158
+ this.logger.warn?.('[pi-browser-agent] ensureReady: broker (re)start failed', error);
159
+ }
160
+ }
161
+
144
162
  /** Try to bind to the preferred port, walk up the configured range on
145
163
  * EADDRINUSE, and finally fall back to an OS-assigned ephemeral port.
146
164
  * Updates `this.port` to the actual bound port on success. */
package/src/index.ts CHANGED
@@ -282,7 +282,7 @@ export default async function piBrowserAgentExtension(pi: {
282
282
  logger,
283
283
  taskStore: new TaskStore({ dir: join(await ensureStateDir('tasks')) }),
284
284
  });
285
- pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker));
285
+ pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker, { managed: false }));
286
286
  // Intentionally do NOT call registerAllTools here: the fallback broker
287
287
  // is not listening, so the full suite would have no working backend.
288
288
  }
@@ -37,7 +37,11 @@ function buildSuccessMessage(probe: ReturnType<BrowserAgentBroker['probeConnecti
37
37
  return lines.join('\n');
38
38
  }
39
39
 
40
- export function createBrowserAgentToolsTool(_pi: { registerTool: (tool: any) => void }, broker: BrowserAgentBroker) {
40
+ export function createBrowserAgentToolsTool(
41
+ _pi: { registerTool: (tool: any) => void },
42
+ broker: BrowserAgentBroker,
43
+ { managed = true }: { managed?: boolean } = {},
44
+ ) {
41
45
  return {
42
46
  name: 'activate_browser_agent_tools',
43
47
  label: 'Activate Browser Agent Tools',
@@ -46,6 +50,13 @@ export function createBrowserAgentToolsTool(_pi: { registerTool: (tool: any) =>
46
50
  promptSnippet: 'Check the browser integration status for this session.',
47
51
  parameters: Type.Object({}),
48
52
  async execute(_toolCallId: string, _params: Record<string, unknown>) {
53
+ // Lazily (re)acquire the broker so a killed primary is replaced on demand
54
+ // when someone actually asks for the browser tools. Only do this for the
55
+ // lifecycle-managed singleton — never for the throwaway fallback broker,
56
+ // which is not tracked for shutdown and must not leak a listener.
57
+ if (managed) {
58
+ await broker.ensureReady?.();
59
+ }
49
60
  const probe = broker.probeConnectivity();
50
61
  if (!probe.brokerReachable || !probe.brokerListening) {
51
62
  return {
@@ -37,6 +37,8 @@ async function brokerToolRequest(
37
37
  timeoutMs: number,
38
38
  ): Promise<{ ok: true; data: unknown } | { ok: false; error: { code: string; message: string; details?: unknown } }> {
39
39
  try {
40
+ // Lazily (re)acquire the broker so a killed primary is replaced on demand.
41
+ await broker.ensureReady?.();
40
42
  const response = await broker.request(type, params, { timeoutMs });
41
43
  if (!response.ok) {
42
44
  return {
@@ -193,17 +193,33 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
193
193
  return {
194
194
  name: 'browser_run_task',
195
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.',
196
+ description: 'Run a browser task end-to-end. The task may be described in natural English. Defaults to the active browser tab; pass tab_id for deterministic targeting.',
197
+ promptSnippet: 'Run a browser task in the active or explicitly targeted tab.',
198
198
  parameters: Type.Object({
199
199
  task: Type.String({ minLength: 1 }),
200
+ tab_id: Type.Optional(Type.Number()),
201
+ use_active_tab: Type.Optional(Type.Boolean()),
200
202
  debugMode: Type.Optional(Type.Boolean()),
201
203
  timeoutMs: Type.Optional(Type.Number({ minimum: 1 })),
202
204
  }),
203
- async execute(_toolCallId: string, params: { task: string; debugMode?: boolean; timeoutMs?: number }): Promise<ToolResult> {
205
+ async execute(
206
+ _toolCallId: string,
207
+ params: { task: string; tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs?: number },
208
+ ): Promise<ToolResult> {
209
+ // Lazily (re)acquire the broker so a killed primary is replaced on demand.
210
+ await broker.ensureReady?.();
204
211
  const probe = broker.probeConnectivity();
205
212
  const taskId = randomUUID();
206
213
  const startedAt = Date.now();
214
+ const target = typeof params.tab_id === 'number'
215
+ ? { tab_id: params.tab_id }
216
+ : { use_active_tab: params.use_active_tab ?? true };
217
+ const request = {
218
+ taskId,
219
+ task: params.task,
220
+ debugMode: params.debugMode ?? false,
221
+ ...target,
222
+ };
207
223
 
208
224
  await appendSafe(broker, taskId, {
209
225
  kind: 'task_started',
@@ -211,14 +227,14 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
211
227
  task: params.task,
212
228
  status: 'running',
213
229
  startedAt,
214
- request: { debugMode: params.debugMode ?? false, timeoutMs: params.timeoutMs },
230
+ request: { ...request, timeoutMs: params.timeoutMs },
215
231
  });
216
232
 
217
233
  let response: ResponseFrame;
218
234
  try {
219
235
  response = await broker.request(
220
236
  'browser_run_task',
221
- { taskId, task: params.task, debugMode: params.debugMode ?? false },
237
+ request,
222
238
  { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000 },
223
239
  );
224
240
  } catch (error) {
@@ -104,6 +104,9 @@ export async function requestBridge<TData>(
104
104
  params: unknown,
105
105
  options: { timeoutMs?: number } = {},
106
106
  ): Promise<{ response: ResponseFrame; data: TData }> {
107
+ // Lazily (re)acquire the broker before the readiness check so a killed
108
+ // primary is replaced (or reconnected to) on this request instead of failing.
109
+ await broker.ensureReady?.();
107
110
  ensureBridgeConnected(broker);
108
111
 
109
112
  let response: ResponseFrame;
@@ -283,6 +283,41 @@ test('remote broker promotes itself when the primary broker exits', async () =>
283
283
  await remote.stop();
284
284
  });
285
285
 
286
+ test('remote broker ensureReady() lazily promotes when the primary is gone', async () => {
287
+ const port = await getFreePort();
288
+ const primary = await createBroker(port);
289
+ await primary.start();
290
+
291
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-ensure-'));
292
+ const remote = new RemoteBrowserAgentBroker({
293
+ host: '127.0.0.1',
294
+ port,
295
+ logger: { info() {}, warn() {}, error() {} },
296
+ requestTimeoutMs: 2_000,
297
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
298
+ });
299
+ await remote.start();
300
+ assert.equal(remote.probeConnectivity().brokerListening, true);
301
+
302
+ // Primary process dies. No tool request or close handler has run yet from the
303
+ // caller's perspective — the next browser tool call drives recovery.
304
+ await primary.stop();
305
+
306
+ // ensureReady() awaits the reconnect-or-promote decision, so once it resolves
307
+ // the remote must own the port (it competed and won the bind race).
308
+ await remote.ensureReady();
309
+
310
+ const probe = remote.probeConnectivity();
311
+ assert.equal(probe.brokerListening, true);
312
+ assert.equal(probe.url, `ws://127.0.0.1:${port}`);
313
+
314
+ // A fresh hard broker must not be able to bind the same port: single owner.
315
+ const intruder = await createBroker(port);
316
+ await assert.rejects(() => intruder.start(), /EADDRINUSE|address already in use/i);
317
+
318
+ await remote.stop();
319
+ });
320
+
286
321
  test('with many secondaries, exactly one promotes when the primary stops and all keep working', async () => {
287
322
  const port = await getFreePort();
288
323
  const primary = await createBroker(port);
@@ -84,10 +84,12 @@ function textOf(result: any): string {
84
84
  return result.content[0]?.text || '';
85
85
  }
86
86
 
87
- test('browser_run_task happy path records history and browser_list/get_history return useful data', async () => {
87
+ test('browser_run_task happy path targets the active tab and records useful history', async () => {
88
88
  const { broker } = await createBroker();
89
+ let receivedRequest: any;
89
90
  const socket = await connectBridge(broker, async (frame, ws) => {
90
91
  if (frame.type !== 'browser_run_task') return;
92
+ receivedRequest = frame.params;
91
93
  ws.send(JSON.stringify({
92
94
  v: 1,
93
95
  kind: 'response',
@@ -115,11 +117,14 @@ test('browser_run_task happy path records history and browser_list/get_history r
115
117
  assert.equal(runResult.details.success, true);
116
118
  assert.equal(runResult.details.status, 'done');
117
119
  assert.equal(runResult.details.historySummary.steps, 2);
120
+ assert.equal(receivedRequest.use_active_tab, true);
121
+ assert.equal(receivedRequest.tab_id, undefined);
118
122
  const taskId = String(runResult.details.taskId);
119
123
 
120
124
  const historyResult = await tools.get('browser_get_task_history').execute('call-2', { taskId });
121
125
  assert.equal(historyResult.details.ok, true);
122
126
  assert.equal(historyResult.details.history.length, 2);
127
+ assert.equal(historyResult.details.history[0].request.use_active_tab, true);
123
128
  assert.equal(historyResult.details.summary.status, 'done');
124
129
 
125
130
  const listResult = await tools.get('browser_list_tasks').execute('call-3', { limit: 10 });
@@ -133,6 +138,40 @@ test('browser_run_task happy path records history and browser_list/get_history r
133
138
  }
134
139
  });
135
140
 
141
+ test('browser_run_task forwards an explicit tab_id instead of selecting the active tab', async () => {
142
+ const { broker } = await createBroker();
143
+ let receivedRequest: any;
144
+ const socket = await connectBridge(broker, async (frame, ws) => {
145
+ if (frame.type !== 'browser_run_task') return;
146
+ receivedRequest = frame.params;
147
+ ws.send(JSON.stringify({
148
+ v: 1,
149
+ kind: 'response',
150
+ id: frame.id,
151
+ ok: true,
152
+ data: { status: 'done', message: 'Used requested tab' },
153
+ }));
154
+ });
155
+ const tools = createToolHarness(broker);
156
+
157
+ try {
158
+ const result = await tools.get('browser_run_task').execute('call-1', {
159
+ task: 'Click the button',
160
+ tab_id: 374936994,
161
+ });
162
+ assert.equal(result.details.ok, true);
163
+ assert.equal(receivedRequest.tab_id, 374936994);
164
+ assert.equal(receivedRequest.use_active_tab, undefined);
165
+
166
+ const history = await tools.get('browser_get_task_history').execute('call-2', { taskId: result.details.taskId });
167
+ assert.equal(history.details.history[0].request.tab_id, 374936994);
168
+ assert.equal(history.details.history[0].request.use_active_tab, undefined);
169
+ } finally {
170
+ socket.close();
171
+ await broker.stop();
172
+ }
173
+ });
174
+
136
175
  test('concurrent browser_run_task attempts return E_BUSY without crashing the caller', async () => {
137
176
  const { broker } = await createBroker();
138
177
  let activeRunId: string | null = null;