oira666_pi-browser-agent 0.0.9 → 0.0.11

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.9",
3
+ "version": "0.0.11",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
package/src/index.ts CHANGED
@@ -1,237 +1,322 @@
1
- import { join } from 'node:path';
2
-
3
- import { BrowserAgentBroker, type BrokerLogger } from './broker/server.ts';
4
- import { RemoteBrowserAgentBroker } from './broker/remote.ts';
5
- import { TaskStore } from './broker/task-store.ts';
6
- import { ensureStateDir } from './util/paths.ts';
7
- import { listInstances, removeInstanceFile, writeInstanceFile } from './util/instances.ts';
8
- import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
9
- import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
10
-
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 };
17
-
18
- let brokerSingleton: BrowserAgentBrokerLike | null = null;
19
- let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
20
- let startupMessage: string | null = null;
21
-
22
- export function getBroker(): BrowserAgentBrokerLike | null {
23
- return brokerSingleton;
24
- }
25
-
26
- export function getStartupMessage(): string | null {
27
- return startupMessage;
28
- }
29
-
30
- export async function resetForTests(): Promise<void> {
31
- if (brokerSingleton) {
32
- try {
33
- await brokerSingleton.stop();
34
- } catch {
35
- // ignore in tests; callers are resetting state intentionally
36
- }
37
- }
38
- brokerSingleton = null;
39
- brokerStartup = null;
40
- startupMessage = null;
41
- }
42
-
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> {
78
- const tasksDir = await ensureStateDir('tasks');
79
- const preferredPort = Number(process.env.PI_BA_PORT || 7878);
80
- const host = process.env.PI_BA_HOST || '127.0.0.1';
81
-
82
- // Robust multi-instance mode:
83
- // - One primary process owns the broker listener on 7878 and receives the
84
- // Chrome extension bridge.
85
- // - Secondary pi processes that lose the 7878 bind race proxy requests
86
- // through the primary broker instead of requiring Chrome to connect to
87
- // their fallback ports (fragile under MV3 service-worker sleep/backoff).
88
- const primaryBroker = new BrowserAgentBroker({
89
- host,
90
- port: preferredPort,
91
- portRange: 1,
92
- fallbackToEphemeral: false,
93
- logger,
94
- taskStore: new TaskStore({ dir: join(tasksDir) }),
95
- });
96
-
97
- try {
98
- await primaryBroker.start();
99
- try {
100
- await listInstances({ gcStale: true });
101
- await writeInstanceFile({
102
- pid: process.pid,
103
- port: primaryBroker.port,
104
- host: primaryBroker.host,
105
- url: primaryBroker.url,
106
- cwd: process.cwd(),
107
- startedAt: new Date().toISOString(),
108
- });
109
- } catch (error) {
110
- logger.warn?.('[pi-browser-agent] failed to publish instance discovery file', error);
111
- }
112
- return primaryBroker;
113
- } catch (error) {
114
- const code = (error as NodeJS.ErrnoException)?.code;
115
- if (code !== 'EADDRINUSE' || process.env.PI_BA_NO_EPHEMERAL) {
116
- throw error;
117
- }
118
-
119
- const remoteBroker = new RemoteBrowserAgentBroker({
120
- host,
121
- port: preferredPort,
122
- logger,
123
- taskStore: new TaskStore({ dir: join(tasksDir) }),
124
- });
125
- try {
126
- await remoteBroker.start();
127
- } catch (remoteError) {
128
- const message = remoteError instanceof Error ? remoteError.message : String(remoteError);
129
- if (message.includes('not a pi-browser-agent broker')) {
130
- throw new Error(`Port ${preferredPort} is busy, but it is not pi-browser-agent`);
131
- }
132
- if (message.includes('old pi-browser-agent broker')) {
133
- throw new Error(`Old browser broker on ${preferredPort}; restart the first pi instance`);
134
- }
135
- throw remoteError;
136
- }
137
- return remoteBroker;
138
- }
139
- }
140
-
141
- async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
142
- // If an existing broker is healthy, reuse it.
143
- if (brokerSingleton) {
144
- const probe = brokerSingleton.probeConnectivity();
145
- if (probe.brokerListening) {
146
- return brokerSingleton;
147
- }
148
- // Non-listening singleton (e.g. after a prior failure). Drop it and retry.
149
- brokerSingleton = null;
150
- }
151
-
152
- // Serialize startup: at most one in-flight start attempt at a time.
153
- if (brokerStartup) {
154
- return await brokerStartup;
155
- }
156
-
157
- brokerStartup = (async () => {
158
- try {
159
- const broker = await createAndStartBroker(logger);
160
- // Only publish a broker as the singleton after a successful bind.
161
- brokerSingleton = broker;
162
- return broker;
163
- } finally {
164
- // Clear the in-flight promise so subsequent starts can retry on failure.
165
- brokerStartup = null;
166
- }
167
- })();
168
-
169
- return await brokerStartup;
170
- }
171
-
172
- export default async function piBrowserAgentExtension(pi: {
173
- on: (event: string, handler: (_event: unknown, ctx?: ExtensionContextLike) => Promise<void> | void) => void;
174
- registerTool: (tool: any) => void;
175
- }) {
176
- const registerSessionTool = async (ctx?: ExtensionContextLike) => {
177
- resetBrowserAgentToolState();
178
- resetRegisteredBrowserTools();
179
- const logger = createUiLogger(ctx);
180
-
181
- try {
182
- const broker = await getOrCreateBroker(logger);
183
- startupMessage = null;
184
- pi.registerTool(createBrowserAgentToolsTool(pi, broker));
185
- // pi reads the tool registry at session_start; any later registerTool()
186
- // calls (e.g. from a meta-tool invocation) are dropped. Register the
187
- // full browser_* suite eagerly whenever the broker is listening. The
188
- // tools themselves probe the bridge at call time and return structured
189
- // errors if the Chrome extension bridge is disconnected.
190
- const probe = broker.probeConnectivity();
191
- if (probe.brokerListening) {
192
- registerAllTools(pi, { broker });
193
- }
194
- } catch (error) {
195
- startupMessage = error instanceof Error ? error.message : String(error);
196
- ctx?.ui?.notify?.(`Browser agent unavailable: ${startupMessage}`, 'error');
197
- // Install the meta-tool against a non-started fallback broker so the
198
- // session still exposes a diagnostic surface. Do NOT publish this broker
199
- // as the singleton — we want a real bind retry on the next session.
200
- const fallbackBroker = new BrowserAgentBroker({
201
- logger,
202
- taskStore: new TaskStore({ dir: join(await ensureStateDir('tasks')) }),
203
- });
204
- pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker));
205
- // Intentionally do NOT call registerAllTools here: the fallback broker
206
- // is not listening, so the full suite would have no working backend.
207
- }
208
- };
209
-
210
- pi.on('session_start', async (_event, ctx) => {
211
- await registerSessionTool(ctx);
212
- });
213
-
214
- pi.on('session_shutdown', async (_event, ctx) => {
215
- brokerStartup = null;
216
- if (!brokerSingleton) {
217
- startupMessage = null;
218
- return;
219
- }
220
- const broker = brokerSingleton;
221
- brokerSingleton = null;
222
- startupMessage = null;
223
- try {
224
- await broker.stop();
225
- } catch (error) {
226
- const message = error instanceof Error ? error.message : String(error);
227
- ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
228
- } finally {
229
- try {
230
- await removeInstanceFile(process.pid);
231
- } catch (error) {
232
- const message = error instanceof Error ? error.message : String(error);
233
- ctx?.ui?.notify?.(`pi-browser-agent instance cleanup failed: ${message}`, 'warning');
234
- }
235
- }
236
- });
237
- }
1
+ import { join } from 'node:path';
2
+
3
+ import { BrowserAgentBroker, type BrokerLogger } from './broker/server.ts';
4
+ import { RemoteBrowserAgentBroker } from './broker/remote.ts';
5
+ import { TaskStore } from './broker/task-store.ts';
6
+ import { ensureStateDir } from './util/paths.ts';
7
+ import { listInstances, removeInstanceFile, writeInstanceFile } from './util/instances.ts';
8
+ import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
9
+ import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
10
+
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 };
17
+
18
+ let brokerSingleton: BrowserAgentBrokerLike | null = null;
19
+ let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
20
+ let startupMessage: string | null = null;
21
+
22
+ export function getBroker(): BrowserAgentBrokerLike | null {
23
+ return brokerSingleton;
24
+ }
25
+
26
+ export function getStartupMessage(): string | null {
27
+ return startupMessage;
28
+ }
29
+
30
+ export async function resetForTests(): Promise<void> {
31
+ if (brokerSingleton) {
32
+ try {
33
+ await brokerSingleton.stop();
34
+ } catch {
35
+ // ignore in tests; callers are resetting state intentionally
36
+ }
37
+ }
38
+ brokerSingleton = null;
39
+ brokerStartup = null;
40
+ startupMessage = null;
41
+ }
42
+
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> {
78
+ const tasksDir = await ensureStateDir('tasks');
79
+ const preferredPort = Number(process.env.PI_BA_PORT || 7878);
80
+ const host = process.env.PI_BA_HOST || '127.0.0.1';
81
+
82
+ // Robust multi-instance mode:
83
+ // - One primary process owns the broker listener on 7878 and receives the
84
+ // Chrome extension bridge.
85
+ // - Secondary pi processes that lose the 7878 bind race proxy requests
86
+ // through the primary broker instead of requiring Chrome to connect to
87
+ // their fallback ports (fragile under MV3 service-worker sleep/backoff).
88
+ const primaryBroker = new BrowserAgentBroker({
89
+ host,
90
+ port: preferredPort,
91
+ portRange: 1,
92
+ fallbackToEphemeral: false,
93
+ logger,
94
+ taskStore: new TaskStore({ dir: join(tasksDir) }),
95
+ });
96
+
97
+ try {
98
+ await primaryBroker.start();
99
+ try {
100
+ await listInstances({ gcStale: true });
101
+ await writeInstanceFile({
102
+ pid: process.pid,
103
+ port: primaryBroker.port,
104
+ host: primaryBroker.host,
105
+ url: primaryBroker.url,
106
+ cwd: process.cwd(),
107
+ startedAt: new Date().toISOString(),
108
+ });
109
+ } catch (error) {
110
+ logger.warn?.('[pi-browser-agent] failed to publish instance discovery file', error);
111
+ }
112
+ return primaryBroker;
113
+ } catch (error) {
114
+ const code = (error as NodeJS.ErrnoException)?.code;
115
+ if (code !== 'EADDRINUSE' || process.env.PI_BA_NO_EPHEMERAL) {
116
+ throw error;
117
+ }
118
+
119
+ const remoteBroker = new RemoteBrowserAgentBroker({
120
+ host,
121
+ port: preferredPort,
122
+ logger,
123
+ taskStore: new TaskStore({ dir: join(tasksDir) }),
124
+ });
125
+ try {
126
+ await remoteBroker.start();
127
+ } catch (remoteError) {
128
+ const message = remoteError instanceof Error ? remoteError.message : String(remoteError);
129
+ if (message.includes('not a pi-browser-agent broker')) {
130
+ throw new Error(`Port ${preferredPort} is busy, but it is not pi-browser-agent`);
131
+ }
132
+ if (message.includes('old pi-browser-agent broker')) {
133
+ throw new Error(`Old browser broker on ${preferredPort}; restart the first pi instance`);
134
+ }
135
+ throw remoteError;
136
+ }
137
+ return remoteBroker;
138
+ }
139
+ }
140
+
141
+ let signalHandlersInstalled = false;
142
+ let suspending = false;
143
+
144
+ /**
145
+ * Make Ctrl+Z (SIGTSTP) graceful.
146
+ *
147
+ * By default a suspended process keeps its TCP listener bound while frozen, so
148
+ * the primary broker would hold port 7878 (and the Chrome extension bridge)
149
+ * hostage without ever servicing it. That wedges every other pi process, which
150
+ * proxies through the primary. Instead we intercept SIGTSTP, cleanly stop the
151
+ * broker (freeing the port and closing the bridge so secondaries auto-promote
152
+ * a new primary via RemoteBrowserAgentBroker.promoteOrReconnect), and only then
153
+ * actually suspend via SIGSTOP (which cannot be caught, so it truly stops the
154
+ * process like the default Ctrl+Z). On SIGCONT we re-acquire the broker.
155
+ */
156
+ function installSuspendResumeHandlers(): void {
157
+ if (signalHandlersInstalled) return;
158
+ // SIGTSTP/SIGCONT are POSIX-only; nothing to do on Windows.
159
+ if (process.platform === 'win32') return;
160
+ signalHandlersInstalled = true;
161
+
162
+ process.on('SIGTSTP', () => {
163
+ if (suspending) return;
164
+ suspending = true;
165
+ const broker = brokerSingleton;
166
+ void (async () => {
167
+ try {
168
+ // Abort any in-flight startup and release the port + bridge.
169
+ brokerStartup = null;
170
+ if (broker) {
171
+ await broker.stop();
172
+ try { await removeInstanceFile(process.pid); } catch { /* ignore */ }
173
+ }
174
+ } catch (error) {
175
+ console.warn('[pi-browser-agent] graceful suspend cleanup failed', error);
176
+ } finally {
177
+ // Now actually suspend. SIGSTOP is uncatchable, so this reliably stops
178
+ // the process just like the default Ctrl+Z behaviour would have.
179
+ try { process.kill(process.pid, 'SIGSTOP'); } catch { /* ignore */ }
180
+ }
181
+ })();
182
+ });
183
+
184
+ process.on('SIGCONT', () => {
185
+ if (!suspending) return;
186
+ suspending = false;
187
+ const broker = brokerSingleton;
188
+ if (!broker) return;
189
+ void (async () => {
190
+ try {
191
+ // Re-acquire the broker on the SAME instance the session tools captured.
192
+ // - primary (BrowserAgentBroker): rebinds 7878 if still free;
193
+ // - remote proxy (RemoteBrowserAgentBroker): reconnects / re-promotes.
194
+ await broker.start();
195
+ if (broker instanceof BrowserAgentBroker) {
196
+ try {
197
+ await writeInstanceFile({
198
+ pid: process.pid,
199
+ port: broker.port,
200
+ host: broker.host,
201
+ url: broker.url,
202
+ cwd: process.cwd(),
203
+ startedAt: new Date().toISOString(),
204
+ });
205
+ } catch { /* ignore */ }
206
+ }
207
+ } catch (error) {
208
+ const code = (error as NodeJS.ErrnoException)?.code;
209
+ if (code === 'EADDRINUSE') {
210
+ // Another pi process became primary while we were suspended. It now
211
+ // owns 7878 and the bridge; this session's captured primary broker
212
+ // can't proxy, so browser tools here stay inactive until restart.
213
+ console.warn('[pi-browser-agent] another pi instance owns the broker port after resume; browser tools in this session are inactive until it is restarted');
214
+ } else {
215
+ console.warn('[pi-browser-agent] broker restart after resume failed', error);
216
+ }
217
+ }
218
+ })();
219
+ });
220
+ }
221
+
222
+ async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
223
+ // If an existing broker is healthy, reuse it.
224
+ if (brokerSingleton) {
225
+ const probe = brokerSingleton.probeConnectivity();
226
+ if (probe.brokerListening) {
227
+ return brokerSingleton;
228
+ }
229
+ // Non-listening singleton (e.g. after a prior failure). Drop it and retry.
230
+ brokerSingleton = null;
231
+ }
232
+
233
+ // Serialize startup: at most one in-flight start attempt at a time.
234
+ if (brokerStartup) {
235
+ return await brokerStartup;
236
+ }
237
+
238
+ brokerStartup = (async () => {
239
+ try {
240
+ const broker = await createAndStartBroker(logger);
241
+ // Only publish a broker as the singleton after a successful bind.
242
+ brokerSingleton = broker;
243
+ return broker;
244
+ } finally {
245
+ // Clear the in-flight promise so subsequent starts can retry on failure.
246
+ brokerStartup = null;
247
+ }
248
+ })();
249
+
250
+ return await brokerStartup;
251
+ }
252
+
253
+ export default async function piBrowserAgentExtension(pi: {
254
+ on: (event: string, handler: (_event: unknown, ctx?: ExtensionContextLike) => Promise<void> | void) => void;
255
+ registerTool: (tool: any) => void;
256
+ }) {
257
+ const registerSessionTool = async (ctx?: ExtensionContextLike) => {
258
+ resetBrowserAgentToolState();
259
+ resetRegisteredBrowserTools();
260
+ const logger = createUiLogger(ctx);
261
+
262
+ try {
263
+ const broker = await getOrCreateBroker(logger);
264
+ startupMessage = null;
265
+ pi.registerTool(createBrowserAgentToolsTool(pi, broker));
266
+ // pi reads the tool registry at session_start; any later registerTool()
267
+ // calls (e.g. from a meta-tool invocation) are dropped. Register the
268
+ // full browser_* suite eagerly whenever the broker is listening. The
269
+ // tools themselves probe the bridge at call time and return structured
270
+ // errors if the Chrome extension bridge is disconnected.
271
+ const probe = broker.probeConnectivity();
272
+ if (probe.brokerListening) {
273
+ registerAllTools(pi, { broker });
274
+ }
275
+ } catch (error) {
276
+ startupMessage = error instanceof Error ? error.message : String(error);
277
+ ctx?.ui?.notify?.(`Browser agent unavailable: ${startupMessage}`, 'error');
278
+ // Install the meta-tool against a non-started fallback broker so the
279
+ // session still exposes a diagnostic surface. Do NOT publish this broker
280
+ // as the singleton — we want a real bind retry on the next session.
281
+ const fallbackBroker = new BrowserAgentBroker({
282
+ logger,
283
+ taskStore: new TaskStore({ dir: join(await ensureStateDir('tasks')) }),
284
+ });
285
+ pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker));
286
+ // Intentionally do NOT call registerAllTools here: the fallback broker
287
+ // is not listening, so the full suite would have no working backend.
288
+ }
289
+ };
290
+
291
+ // Install once per process so Ctrl+Z releases the broker port instead of
292
+ // freezing it while still bound.
293
+ installSuspendResumeHandlers();
294
+
295
+ pi.on('session_start', async (_event, ctx) => {
296
+ await registerSessionTool(ctx);
297
+ });
298
+
299
+ pi.on('session_shutdown', async (_event, ctx) => {
300
+ brokerStartup = null;
301
+ if (!brokerSingleton) {
302
+ startupMessage = null;
303
+ return;
304
+ }
305
+ const broker = brokerSingleton;
306
+ brokerSingleton = null;
307
+ startupMessage = null;
308
+ try {
309
+ await broker.stop();
310
+ } catch (error) {
311
+ const message = error instanceof Error ? error.message : String(error);
312
+ ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
313
+ } finally {
314
+ try {
315
+ await removeInstanceFile(process.pid);
316
+ } catch (error) {
317
+ const message = error instanceof Error ? error.message : String(error);
318
+ ctx?.ui?.notify?.(`pi-browser-agent instance cleanup failed: ${message}`, 'warning');
319
+ }
320
+ }
321
+ });
322
+ }
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import { randomBytes } from 'node:crypto';
3
- import { writeFile } from 'node:fs/promises';
3
+ import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
 
@@ -10,6 +10,10 @@ 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
+ const SCREENSHOT_TEMP_DIR = join(tmpdir(), 'pi-browser-agent', 'screenshots');
14
+ const SCREENSHOT_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000;
15
+ let screenshotCleanupStarted = false;
16
+
13
17
  export type ToolResultContentBlock =
14
18
  | { type: 'text'; text: string }
15
19
  | { type: 'image'; data: string; mimeType: string };
@@ -143,8 +147,45 @@ export async function formatTextResult(title: string, value: string, ext = 'txt'
143
147
  };
144
148
  }
145
149
 
150
+ async function cleanupOldScreenshotTempFiles(): Promise<void> {
151
+ const now = Date.now();
152
+ let entries: string[];
153
+ try {
154
+ entries = await readdir(SCREENSHOT_TEMP_DIR);
155
+ } catch {
156
+ return;
157
+ }
158
+
159
+ await Promise.all(entries.map(async (entry) => {
160
+ const path = join(SCREENSHOT_TEMP_DIR, entry);
161
+ try {
162
+ const info = await stat(path);
163
+ if (!info.isFile()) {
164
+ return;
165
+ }
166
+ const createdAt = Number.isFinite(info.birthtimeMs) && info.birthtimeMs > 0 ? info.birthtimeMs : info.mtimeMs;
167
+ if (now - createdAt > SCREENSHOT_TEMP_MAX_AGE_MS) {
168
+ await rm(path, { force: true });
169
+ }
170
+ } catch {
171
+ // Best-effort cleanup only; never fail the screenshot tool because temp cleanup failed.
172
+ }
173
+ }));
174
+ }
175
+
176
+ function startScreenshotTempCleanup(): void {
177
+ if (screenshotCleanupStarted) {
178
+ return;
179
+ }
180
+ screenshotCleanupStarted = true;
181
+ void cleanupOldScreenshotTempFiles();
182
+ }
183
+
146
184
  export async function spillBase64Payload(base64: string, ext: string): Promise<string> {
147
- const path = join(tmpdir(), `pi-browser-agent-${randomBytes(6).toString('hex')}.${ext}`);
185
+ startScreenshotTempCleanup();
186
+ await mkdir(SCREENSHOT_TEMP_DIR, { recursive: true });
187
+ const safeExt = /^[a-z0-9]+$/i.test(ext) ? ext : 'bin';
188
+ const path = join(SCREENSHOT_TEMP_DIR, `screenshot-${randomBytes(6).toString('hex')}.${safeExt}`);
148
189
  await writeFile(path, Buffer.from(base64, 'base64'));
149
190
  return path;
150
191
  }