agent-browser 0.18.0 → 0.20.0

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.
Files changed (82) hide show
  1. package/README.md +150 -122
  2. package/bin/agent-browser-darwin-arm64 +0 -0
  3. package/bin/agent-browser-darwin-x64 +0 -0
  4. package/bin/agent-browser-linux-arm64 +0 -0
  5. package/bin/agent-browser-linux-x64 +0 -0
  6. package/bin/agent-browser-win32-x64.exe +0 -0
  7. package/package.json +6 -40
  8. package/scripts/postinstall.js +12 -15
  9. package/skills/agent-browser/SKILL.md +37 -32
  10. package/skills/electron/SKILL.md +5 -5
  11. package/dist/action-policy.d.ts +0 -14
  12. package/dist/action-policy.d.ts.map +0 -1
  13. package/dist/action-policy.js +0 -253
  14. package/dist/action-policy.js.map +0 -1
  15. package/dist/actions.d.ts +0 -18
  16. package/dist/actions.d.ts.map +0 -1
  17. package/dist/actions.js +0 -2120
  18. package/dist/actions.js.map +0 -1
  19. package/dist/auth-cli.d.ts +0 -2
  20. package/dist/auth-cli.d.ts.map +0 -1
  21. package/dist/auth-cli.js +0 -97
  22. package/dist/auth-cli.js.map +0 -1
  23. package/dist/auth-vault.d.ts +0 -36
  24. package/dist/auth-vault.d.ts.map +0 -1
  25. package/dist/auth-vault.js +0 -125
  26. package/dist/auth-vault.js.map +0 -1
  27. package/dist/browser.d.ts +0 -592
  28. package/dist/browser.d.ts.map +0 -1
  29. package/dist/browser.js +0 -2190
  30. package/dist/browser.js.map +0 -1
  31. package/dist/confirmation.d.ts +0 -8
  32. package/dist/confirmation.d.ts.map +0 -1
  33. package/dist/confirmation.js +0 -30
  34. package/dist/confirmation.js.map +0 -1
  35. package/dist/daemon.d.ts +0 -71
  36. package/dist/daemon.d.ts.map +0 -1
  37. package/dist/daemon.js +0 -671
  38. package/dist/daemon.js.map +0 -1
  39. package/dist/diff.d.ts +0 -18
  40. package/dist/diff.d.ts.map +0 -1
  41. package/dist/diff.js +0 -271
  42. package/dist/diff.js.map +0 -1
  43. package/dist/domain-filter.d.ts +0 -28
  44. package/dist/domain-filter.d.ts.map +0 -1
  45. package/dist/domain-filter.js +0 -149
  46. package/dist/domain-filter.js.map +0 -1
  47. package/dist/encryption.d.ts +0 -73
  48. package/dist/encryption.d.ts.map +0 -1
  49. package/dist/encryption.js +0 -171
  50. package/dist/encryption.js.map +0 -1
  51. package/dist/inspect-server.d.ts +0 -26
  52. package/dist/inspect-server.d.ts.map +0 -1
  53. package/dist/inspect-server.js +0 -218
  54. package/dist/inspect-server.js.map +0 -1
  55. package/dist/ios-actions.d.ts +0 -11
  56. package/dist/ios-actions.d.ts.map +0 -1
  57. package/dist/ios-actions.js +0 -228
  58. package/dist/ios-actions.js.map +0 -1
  59. package/dist/ios-manager.d.ts +0 -266
  60. package/dist/ios-manager.d.ts.map +0 -1
  61. package/dist/ios-manager.js +0 -1073
  62. package/dist/ios-manager.js.map +0 -1
  63. package/dist/protocol.d.ts +0 -28
  64. package/dist/protocol.d.ts.map +0 -1
  65. package/dist/protocol.js +0 -986
  66. package/dist/protocol.js.map +0 -1
  67. package/dist/snapshot.d.ts +0 -67
  68. package/dist/snapshot.d.ts.map +0 -1
  69. package/dist/snapshot.js +0 -514
  70. package/dist/snapshot.js.map +0 -1
  71. package/dist/state-utils.d.ts +0 -77
  72. package/dist/state-utils.d.ts.map +0 -1
  73. package/dist/state-utils.js +0 -178
  74. package/dist/state-utils.js.map +0 -1
  75. package/dist/stream-server.d.ts +0 -117
  76. package/dist/stream-server.d.ts.map +0 -1
  77. package/dist/stream-server.js +0 -309
  78. package/dist/stream-server.js.map +0 -1
  79. package/dist/types.d.ts +0 -925
  80. package/dist/types.d.ts.map +0 -1
  81. package/dist/types.js +0 -2
  82. package/dist/types.js.map +0 -1
package/dist/daemon.js DELETED
@@ -1,671 +0,0 @@
1
- import * as net from 'net';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
- import * as os from 'os';
5
- import { BrowserManager } from './browser.js';
6
- import { IOSManager } from './ios-manager.js';
7
- import { parseCommand, serializeResponse, errorResponse } from './protocol.js';
8
- import { executeCommand, initActionPolicy } from './actions.js';
9
- import { executeIOSCommand } from './ios-actions.js';
10
- import { StreamServer } from './stream-server.js';
11
- import { getEncryptionKey, encryptData, isValidSessionName, cleanupExpiredStates, getAutoStateFilePath, } from './state-utils.js';
12
- /**
13
- * Backpressure-aware socket write.
14
- * If the kernel buffer is full (socket.write returns false),
15
- * waits for the 'drain' event before resolving.
16
- */
17
- export function safeWrite(socket, payload) {
18
- return new Promise((resolve, reject) => {
19
- if (socket.destroyed) {
20
- resolve();
21
- return;
22
- }
23
- const canContinue = socket.write(payload);
24
- if (canContinue) {
25
- resolve();
26
- }
27
- else if (socket.destroyed) {
28
- resolve();
29
- }
30
- else {
31
- const cleanup = () => {
32
- socket.removeListener('drain', onDrain);
33
- socket.removeListener('error', onError);
34
- socket.removeListener('close', onClose);
35
- };
36
- const onDrain = () => {
37
- cleanup();
38
- resolve();
39
- };
40
- const onError = (err) => {
41
- cleanup();
42
- reject(err);
43
- };
44
- const onClose = () => {
45
- cleanup();
46
- resolve();
47
- };
48
- socket.once('drain', onDrain);
49
- socket.once('error', onError);
50
- socket.once('close', onClose);
51
- }
52
- });
53
- }
54
- // Platform detection
55
- const isWindows = process.platform === 'win32';
56
- // Session support - each session gets its own socket/pid
57
- let currentSession = process.env.AGENT_BROWSER_SESSION || 'default';
58
- // Stream server for browser preview
59
- let streamServer = null;
60
- // Idle timeout - shut down daemon after period of inactivity
61
- // Configurable via AGENT_BROWSER_IDLE_TIMEOUT_MS env var (default: 15 minutes, 0 to disable)
62
- const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;
63
- const IDLE_TIMEOUT_MS = (() => {
64
- const env = process.env.AGENT_BROWSER_IDLE_TIMEOUT_MS;
65
- if (env !== undefined) {
66
- const val = parseInt(env, 10);
67
- return isNaN(val) ? DEFAULT_IDLE_TIMEOUT_MS : val;
68
- }
69
- return DEFAULT_IDLE_TIMEOUT_MS;
70
- })();
71
- let idleTimer = null;
72
- // Default stream port (can be overridden with AGENT_BROWSER_STREAM_PORT)
73
- const DEFAULT_STREAM_PORT = 9223;
74
- /**
75
- * Save state to file with optional encryption.
76
- */
77
- async function saveStateToFile(browser, filepath) {
78
- const context = browser.getContext();
79
- if (!context) {
80
- throw new Error('No browser context available');
81
- }
82
- const state = await context.storageState();
83
- const jsonData = JSON.stringify(state, null, 2);
84
- const key = getEncryptionKey();
85
- if (key) {
86
- const encrypted = encryptData(jsonData, key);
87
- fs.writeFileSync(filepath, JSON.stringify(encrypted, null, 2));
88
- return { encrypted: true };
89
- }
90
- fs.writeFileSync(filepath, jsonData);
91
- return { encrypted: false };
92
- }
93
- const AUTO_EXPIRE_ENV = 'AGENT_BROWSER_STATE_EXPIRE_DAYS';
94
- const DEFAULT_EXPIRE_DAYS = 30;
95
- function runCleanupExpiredStates() {
96
- const expireDaysStr = process.env[AUTO_EXPIRE_ENV];
97
- const expireDays = expireDaysStr ? parseInt(expireDaysStr, 10) : DEFAULT_EXPIRE_DAYS;
98
- if (isNaN(expireDays) || expireDays <= 0) {
99
- return;
100
- }
101
- try {
102
- const deleted = cleanupExpiredStates(expireDays);
103
- if (deleted.length > 0 && process.env.AGENT_BROWSER_DEBUG === '1') {
104
- console.error(`[DEBUG] Auto-expired ${deleted.length} state file(s) older than ${expireDays} days`);
105
- }
106
- }
107
- catch (err) {
108
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
109
- console.error(`[DEBUG] Failed to clean up expired states:`, err);
110
- }
111
- }
112
- }
113
- /**
114
- * Get the validated session name and auto-state file path.
115
- * Centralizes session name validation to prevent path traversal.
116
- */
117
- function getSessionAutoStatePath() {
118
- const sessionNameRaw = process.env.AGENT_BROWSER_SESSION_NAME;
119
- if (!sessionNameRaw)
120
- return undefined;
121
- if (!isValidSessionName(sessionNameRaw)) {
122
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
123
- console.error(`[SECURITY] Invalid session name rejected: ${sessionNameRaw}`);
124
- }
125
- return undefined;
126
- }
127
- const sessionId = process.env.AGENT_BROWSER_SESSION || 'default';
128
- try {
129
- const autoStatePath = getAutoStateFilePath(sessionNameRaw, sessionId);
130
- return autoStatePath && fs.existsSync(autoStatePath) ? autoStatePath : undefined;
131
- }
132
- catch {
133
- return undefined;
134
- }
135
- }
136
- /**
137
- * Get the auto-state file path for saving (creates sessions dir if needed).
138
- * Returns undefined if no valid session name is configured.
139
- */
140
- function getSessionSaveStatePath() {
141
- const sessionNameRaw = process.env.AGENT_BROWSER_SESSION_NAME;
142
- if (!sessionNameRaw)
143
- return undefined;
144
- if (!isValidSessionName(sessionNameRaw))
145
- return undefined;
146
- const sessionId = process.env.AGENT_BROWSER_SESSION || 'default';
147
- try {
148
- return getAutoStateFilePath(sessionNameRaw, sessionId) ?? undefined;
149
- }
150
- catch {
151
- return undefined;
152
- }
153
- }
154
- /**
155
- * Set the current session
156
- */
157
- export function setSession(session) {
158
- currentSession = session;
159
- }
160
- /**
161
- * Get the current session
162
- */
163
- export function getSession() {
164
- return currentSession;
165
- }
166
- /**
167
- * Get port number for TCP mode (Windows)
168
- * Uses a hash of the session name to get a consistent port
169
- */
170
- export function getPortForSession(session) {
171
- let hash = 0;
172
- for (let i = 0; i < session.length; i++) {
173
- hash = (hash << 5) - hash + session.charCodeAt(i);
174
- hash |= 0;
175
- }
176
- // Port range 49152-65535 (dynamic/private ports)
177
- return 49152 + (Math.abs(hash) % 16383);
178
- }
179
- /**
180
- * Get the base directory for socket/pid files.
181
- * Priority: AGENT_BROWSER_SOCKET_DIR > XDG_RUNTIME_DIR > ~/.agent-browser > tmpdir
182
- */
183
- export function getAppDir() {
184
- // 1. XDG_RUNTIME_DIR (Linux standard)
185
- if (process.env.XDG_RUNTIME_DIR) {
186
- return path.join(process.env.XDG_RUNTIME_DIR, 'agent-browser');
187
- }
188
- // 2. Home directory fallback (like Docker Desktop's ~/.docker/run/)
189
- const homeDir = os.homedir();
190
- if (homeDir) {
191
- return path.join(homeDir, '.agent-browser');
192
- }
193
- // 3. Last resort: temp dir
194
- return path.join(os.tmpdir(), 'agent-browser');
195
- }
196
- export function getSocketDir() {
197
- // Allow explicit override for socket directory
198
- if (process.env.AGENT_BROWSER_SOCKET_DIR) {
199
- return process.env.AGENT_BROWSER_SOCKET_DIR;
200
- }
201
- return getAppDir();
202
- }
203
- /**
204
- * Get the socket path for the current session (Unix) or port (Windows)
205
- */
206
- export function getSocketPath(session) {
207
- const sess = session ?? currentSession;
208
- if (isWindows) {
209
- return String(getPortForSession(sess));
210
- }
211
- return path.join(getSocketDir(), `${sess}.sock`);
212
- }
213
- /**
214
- * Get the port file path for Windows (stores the port number)
215
- */
216
- export function getPortFile(session) {
217
- const sess = session ?? currentSession;
218
- return path.join(getSocketDir(), `${sess}.port`);
219
- }
220
- /**
221
- * Get the PID file path for the current session
222
- */
223
- export function getPidFile(session) {
224
- const sess = session ?? currentSession;
225
- return path.join(getSocketDir(), `${sess}.pid`);
226
- }
227
- /**
228
- * Check if daemon is running for the current session
229
- */
230
- export function isDaemonRunning(session) {
231
- const pidFile = getPidFile(session);
232
- if (!fs.existsSync(pidFile))
233
- return false;
234
- try {
235
- const pid = parseInt(fs.readFileSync(pidFile, 'utf8').trim(), 10);
236
- // Check if process exists (works on both Unix and Windows)
237
- process.kill(pid, 0);
238
- return true;
239
- }
240
- catch (err) {
241
- // EPERM means the process exists but we lack permission to signal it
242
- // (e.g. caller is inside a macOS sandbox). Only ESRCH means it's gone.
243
- if (err instanceof Error && err.code === 'EPERM') {
244
- return true;
245
- }
246
- // Process doesn't exist, clean up stale files
247
- cleanupSocket(session);
248
- return false;
249
- }
250
- }
251
- /**
252
- * Get connection info for the current session
253
- * Returns { type: 'unix', path: string } or { type: 'tcp', port: number }
254
- */
255
- export function getConnectionInfo(session) {
256
- const sess = session ?? currentSession;
257
- if (isWindows) {
258
- return { type: 'tcp', port: getPortForSession(sess) };
259
- }
260
- return { type: 'unix', path: path.join(getSocketDir(), `${sess}.sock`) };
261
- }
262
- /**
263
- * Clean up socket and PID file for the current session
264
- */
265
- export function cleanupSocket(session) {
266
- const pidFile = getPidFile(session);
267
- const streamPortFile = getStreamPortFile(session);
268
- try {
269
- if (fs.existsSync(pidFile))
270
- fs.unlinkSync(pidFile);
271
- if (fs.existsSync(streamPortFile))
272
- fs.unlinkSync(streamPortFile);
273
- if (isWindows) {
274
- const portFile = getPortFile(session);
275
- if (fs.existsSync(portFile))
276
- fs.unlinkSync(portFile);
277
- }
278
- else {
279
- const socketPath = getSocketPath(session);
280
- if (fs.existsSync(socketPath))
281
- fs.unlinkSync(socketPath);
282
- }
283
- }
284
- catch {
285
- // Ignore cleanup errors
286
- }
287
- }
288
- /**
289
- * Get the stream port file path
290
- */
291
- export function getStreamPortFile(session) {
292
- const sess = session ?? currentSession;
293
- return path.join(getSocketDir(), `${sess}.stream`);
294
- }
295
- /**
296
- * Start the daemon server
297
- * @param options.streamPort Port for WebSocket stream server (0 to disable)
298
- * @param options.provider Provider type ('ios' for iOS Simulator, undefined for desktop)
299
- */
300
- export async function startDaemon(options) {
301
- // Ensure socket directory exists with restricted permissions (owner-only access)
302
- const socketDir = getSocketDir();
303
- if (!fs.existsSync(socketDir)) {
304
- fs.mkdirSync(socketDir, { recursive: true, mode: 0o700 });
305
- }
306
- // Clean up any stale socket
307
- cleanupSocket();
308
- // Clean up expired state files on startup
309
- runCleanupExpiredStates();
310
- // Initialize action policy enforcement
311
- initActionPolicy();
312
- // Determine provider from options or environment
313
- const provider = options?.provider ?? process.env.AGENT_BROWSER_PROVIDER;
314
- const isIOS = provider === 'ios';
315
- // Create appropriate manager
316
- const manager = isIOS ? new IOSManager() : new BrowserManager();
317
- let shuttingDown = false;
318
- // Start stream server if port is specified (or use default if env var is set)
319
- // Note: Stream server only works with BrowserManager (desktop), not iOS
320
- const streamPort = options?.streamPort ??
321
- (process.env.AGENT_BROWSER_STREAM_PORT
322
- ? parseInt(process.env.AGENT_BROWSER_STREAM_PORT, 10)
323
- : 0);
324
- if (streamPort > 0 && !isIOS && manager instanceof BrowserManager) {
325
- streamServer = new StreamServer(manager, streamPort);
326
- await streamServer.start();
327
- // Write stream port to file for clients to discover
328
- const streamPortFile = getStreamPortFile();
329
- fs.writeFileSync(streamPortFile, streamPort.toString());
330
- }
331
- // Idle timeout: shut down daemon if no commands arrive within the timeout period.
332
- // Reset on every incoming command. Set AGENT_BROWSER_IDLE_TIMEOUT_MS=0 to disable.
333
- let shutdownRef = null;
334
- function resetIdleTimer() {
335
- if (IDLE_TIMEOUT_MS <= 0)
336
- return;
337
- if (idleTimer)
338
- clearTimeout(idleTimer);
339
- idleTimer = setTimeout(() => {
340
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
341
- console.error(`[DEBUG] Idle timeout reached (${IDLE_TIMEOUT_MS}ms), shutting down daemon`);
342
- }
343
- if (shutdownRef)
344
- shutdownRef();
345
- }, IDLE_TIMEOUT_MS);
346
- // Don't let the idle timer keep the process alive on its own
347
- if (idleTimer && typeof idleTimer === 'object' && 'unref' in idleTimer) {
348
- idleTimer.unref();
349
- }
350
- }
351
- // Start the idle timer immediately
352
- resetIdleTimer();
353
- const server = net.createServer((socket) => {
354
- let buffer = '';
355
- let httpChecked = false;
356
- // Command serialization: queue incoming lines and process them one at a time.
357
- // This prevents concurrent command execution which can cause socket.write
358
- // buffer contention and EAGAIN errors on the Rust CLI side.
359
- const commandQueue = [];
360
- let processing = false;
361
- async function processQueue() {
362
- if (processing)
363
- return;
364
- processing = true;
365
- while (commandQueue.length > 0) {
366
- const line = commandQueue.shift();
367
- // Reset idle timer on every command
368
- resetIdleTimer();
369
- try {
370
- const parseResult = parseCommand(line);
371
- if (!parseResult.success) {
372
- const resp = errorResponse(parseResult.id ?? 'unknown', parseResult.error);
373
- await safeWrite(socket, serializeResponse(resp) + '\n');
374
- continue;
375
- }
376
- // Handle device_list specially - it works without a session and always uses IOSManager
377
- if (parseResult.command.action === 'device_list') {
378
- const iosManager = new IOSManager();
379
- try {
380
- const devices = await iosManager.listAllDevices();
381
- const response = {
382
- id: parseResult.command.id,
383
- success: true,
384
- data: { devices },
385
- };
386
- await safeWrite(socket, serializeResponse(response) + '\n');
387
- }
388
- catch (err) {
389
- const message = err instanceof Error ? err.message : String(err);
390
- await safeWrite(socket, serializeResponse(errorResponse(parseResult.command.id, message)) + '\n');
391
- }
392
- continue;
393
- }
394
- // Auto-launch if not already launched and this isn't a launch/close/state_load command
395
- if (!manager.isLaunched() &&
396
- parseResult.command.action !== 'launch' &&
397
- parseResult.command.action !== 'close' &&
398
- parseResult.command.action !== 'state_load') {
399
- if (isIOS && manager instanceof IOSManager) {
400
- // Auto-launch iOS Safari
401
- // Check for device in command first (for reused daemons), then fall back to env vars
402
- const cmd = parseResult.command;
403
- const iosDevice = cmd.iosDevice || process.env.AGENT_BROWSER_IOS_DEVICE;
404
- await manager.launch({
405
- device: iosDevice,
406
- udid: process.env.AGENT_BROWSER_IOS_UDID,
407
- });
408
- }
409
- else if (manager instanceof BrowserManager) {
410
- // Auto-launch desktop browser
411
- const extensions = process.env.AGENT_BROWSER_EXTENSIONS
412
- ? process.env.AGENT_BROWSER_EXTENSIONS.split(/[,\n]/)
413
- .map((p) => p.trim())
414
- .filter(Boolean)
415
- : undefined;
416
- // Parse args from env (comma or newline separated)
417
- const argsEnv = process.env.AGENT_BROWSER_ARGS;
418
- const args = argsEnv
419
- ? argsEnv
420
- .split(/[,\n]/)
421
- .map((a) => a.trim())
422
- .filter((a) => a.length > 0)
423
- : undefined;
424
- // Parse proxy from env
425
- const proxyServer = process.env.AGENT_BROWSER_PROXY;
426
- const proxyBypass = process.env.AGENT_BROWSER_PROXY_BYPASS;
427
- const proxy = proxyServer
428
- ? {
429
- server: proxyServer,
430
- ...(proxyBypass && { bypass: proxyBypass }),
431
- }
432
- : undefined;
433
- const ignoreHTTPSErrors = process.env.AGENT_BROWSER_IGNORE_HTTPS_ERRORS === '1';
434
- const allowFileAccess = process.env.AGENT_BROWSER_ALLOW_FILE_ACCESS === '1';
435
- const colorSchemeEnv = process.env.AGENT_BROWSER_COLOR_SCHEME;
436
- const colorScheme = colorSchemeEnv === 'dark' ||
437
- colorSchemeEnv === 'light' ||
438
- colorSchemeEnv === 'no-preference'
439
- ? colorSchemeEnv
440
- : undefined;
441
- await manager.launch({
442
- id: 'auto',
443
- action: 'launch',
444
- headless: process.env.AGENT_BROWSER_HEADED !== '1' &&
445
- process.env.AGENT_BROWSER_HEADED !== 'true',
446
- executablePath: process.env.AGENT_BROWSER_EXECUTABLE_PATH,
447
- extensions: extensions,
448
- profile: process.env.AGENT_BROWSER_PROFILE,
449
- storageState: process.env.AGENT_BROWSER_STATE,
450
- args,
451
- userAgent: process.env.AGENT_BROWSER_USER_AGENT,
452
- proxy,
453
- ignoreHTTPSErrors: ignoreHTTPSErrors,
454
- allowFileAccess: allowFileAccess,
455
- colorScheme,
456
- autoStateFilePath: getSessionAutoStatePath(),
457
- });
458
- }
459
- }
460
- // Recover from stale state: browser is launched but all pages were closed
461
- if (manager instanceof BrowserManager &&
462
- manager.isLaunched() &&
463
- !manager.hasPages() &&
464
- parseResult.command.action !== 'launch' &&
465
- parseResult.command.action !== 'close') {
466
- await manager.ensurePage();
467
- }
468
- // Handle explicit launch with auto-load state
469
- if (parseResult.command.action === 'launch' &&
470
- manager instanceof BrowserManager &&
471
- !parseResult.command.autoStateFilePath) {
472
- const autoStatePath = getSessionAutoStatePath();
473
- if (autoStatePath) {
474
- parseResult.command.autoStateFilePath = autoStatePath;
475
- }
476
- }
477
- // Handle close command specially - shuts down daemon
478
- if (parseResult.command.action === 'close') {
479
- // Auto-save state before closing
480
- if (manager instanceof BrowserManager && manager.isLaunched()) {
481
- const savePath = getSessionSaveStatePath();
482
- if (savePath) {
483
- try {
484
- const { encrypted } = await saveStateToFile(manager, savePath);
485
- fs.chmodSync(savePath, 0o600);
486
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
487
- console.error(`Auto-saved session state: ${savePath}${encrypted ? ' (encrypted)' : ''}`);
488
- }
489
- }
490
- catch (err) {
491
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
492
- console.error(`Failed to auto-save session state:`, err);
493
- }
494
- }
495
- }
496
- }
497
- const response = isIOS && manager instanceof IOSManager
498
- ? await executeIOSCommand(parseResult.command, manager)
499
- : await executeCommand(parseResult.command, manager);
500
- await safeWrite(socket, serializeResponse(response) + '\n');
501
- if (!shuttingDown) {
502
- shuttingDown = true;
503
- setTimeout(() => {
504
- server.close();
505
- cleanupSocket();
506
- process.exit(0);
507
- }, 100);
508
- }
509
- commandQueue.length = 0;
510
- processing = false;
511
- return;
512
- }
513
- // Execute command with appropriate handler
514
- const response = isIOS && manager instanceof IOSManager
515
- ? await executeIOSCommand(parseResult.command, manager)
516
- : await executeCommand(parseResult.command, manager);
517
- // Add any launch warnings to the response
518
- if (manager instanceof BrowserManager) {
519
- const warnings = manager.getAndClearWarnings();
520
- if (warnings.length > 0 && response.success && response.data) {
521
- response.data.warnings = warnings;
522
- }
523
- }
524
- await safeWrite(socket, serializeResponse(response) + '\n');
525
- }
526
- catch (err) {
527
- const message = err instanceof Error ? err.message : String(err);
528
- await safeWrite(socket, serializeResponse(errorResponse('error', message)) + '\n').catch(() => { }); // Socket may already be destroyed
529
- }
530
- }
531
- processing = false;
532
- }
533
- socket.on('data', (data) => {
534
- buffer += data.toString();
535
- // Security: Detect and reject HTTP requests to prevent cross-origin attacks.
536
- // Browsers using fetch() must send HTTP headers (e.g., "POST / HTTP/1.1"),
537
- // while legitimate clients send raw JSON starting with "{".
538
- if (!httpChecked) {
539
- httpChecked = true;
540
- const trimmed = buffer.trimStart();
541
- if (/^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|CONNECT|TRACE)\s/i.test(trimmed)) {
542
- socket.destroy();
543
- return;
544
- }
545
- }
546
- // Extract complete lines and enqueue them for serial processing
547
- while (buffer.includes('\n')) {
548
- const newlineIdx = buffer.indexOf('\n');
549
- const line = buffer.substring(0, newlineIdx);
550
- buffer = buffer.substring(newlineIdx + 1);
551
- if (!line.trim())
552
- continue;
553
- commandQueue.push(line);
554
- }
555
- processQueue().catch((err) => {
556
- // Socket write failures during queue processing are non-fatal;
557
- // the client has likely disconnected.
558
- // Only log err.message to avoid leaking sensitive fields (e.g. passwords) from command objects.
559
- console.warn('[warn] processQueue error:', err?.message ?? String(err));
560
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
561
- console.error('[DEBUG] processQueue error stack:', err?.stack ?? err?.message ?? String(err));
562
- }
563
- });
564
- });
565
- socket.on('error', () => {
566
- // Client disconnected, ignore
567
- });
568
- });
569
- const pidFile = getPidFile();
570
- // Write PID file before listening
571
- fs.writeFileSync(pidFile, process.pid.toString());
572
- if (isWindows) {
573
- // Windows: use TCP socket on localhost
574
- const port = getPortForSession(currentSession);
575
- const portFile = getPortFile();
576
- fs.writeFileSync(portFile, port.toString());
577
- server.listen(port, '127.0.0.1', () => {
578
- // Daemon is ready on TCP port
579
- });
580
- }
581
- else {
582
- // Unix: use Unix domain socket
583
- const socketPath = getSocketPath();
584
- server.listen(socketPath, () => {
585
- // Daemon is ready
586
- });
587
- }
588
- server.on('error', (err) => {
589
- console.error('Server error:', err);
590
- cleanupSocket();
591
- process.exit(1);
592
- });
593
- // Handle shutdown signals
594
- const shutdown = async () => {
595
- if (shuttingDown)
596
- return;
597
- shuttingDown = true;
598
- // Clear idle timer
599
- if (idleTimer) {
600
- clearTimeout(idleTimer);
601
- idleTimer = null;
602
- }
603
- // Auto-save session state before closing (same as the explicit `close` command path)
604
- if (manager instanceof BrowserManager && manager.isLaunched()) {
605
- const savePath = getSessionSaveStatePath();
606
- if (savePath) {
607
- try {
608
- const { encrypted } = await saveStateToFile(manager, savePath);
609
- fs.chmodSync(savePath, 0o600);
610
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
611
- console.error(`Auto-saved session state before shutdown: ${savePath}${encrypted ? ' (encrypted)' : ''}`);
612
- }
613
- }
614
- catch (err) {
615
- if (process.env.AGENT_BROWSER_DEBUG === '1') {
616
- console.error(`Failed to auto-save session state before shutdown:`, err);
617
- }
618
- }
619
- }
620
- }
621
- // Stop stream server if running
622
- if (streamServer) {
623
- await streamServer.stop();
624
- streamServer = null;
625
- // Clean up stream port file
626
- const streamPortFile = getStreamPortFile();
627
- try {
628
- if (fs.existsSync(streamPortFile))
629
- fs.unlinkSync(streamPortFile);
630
- }
631
- catch {
632
- // Ignore cleanup errors
633
- }
634
- }
635
- await manager.close();
636
- server.close();
637
- cleanupSocket();
638
- process.exit(0);
639
- };
640
- // Wire up idle timeout to shutdown
641
- shutdownRef = shutdown;
642
- process.on('SIGINT', shutdown);
643
- process.on('SIGTERM', shutdown);
644
- process.on('SIGHUP', shutdown);
645
- // Handle unexpected errors - always cleanup
646
- process.on('uncaughtException', (err) => {
647
- console.error('Uncaught exception:', err);
648
- cleanupSocket();
649
- process.exit(1);
650
- });
651
- process.on('unhandledRejection', (reason) => {
652
- console.error('Unhandled rejection:', reason);
653
- cleanupSocket();
654
- process.exit(1);
655
- });
656
- // Cleanup on normal exit
657
- process.on('exit', () => {
658
- cleanupSocket();
659
- });
660
- // Keep process alive
661
- process.stdin.resume();
662
- }
663
- // Run daemon if this is the entry point
664
- if (process.argv[1]?.endsWith('daemon.js') || process.env.AGENT_BROWSER_DAEMON === '1') {
665
- startDaemon().catch((err) => {
666
- console.error('Daemon error:', err);
667
- cleanupSocket();
668
- process.exit(1);
669
- });
670
- }
671
- //# sourceMappingURL=daemon.js.map