@web-auto/camo 0.1.5 → 0.1.6

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/README.md CHANGED
@@ -33,8 +33,11 @@ camo profile create myprofile
33
33
  # Set as default
34
34
  camo profile default myprofile
35
35
 
36
- # Start browser
37
- camo start --url https://example.com
36
+ # Start browser (with alias)
37
+ camo start --url https://example.com --alias main
38
+
39
+ # Start headless worker (auto-kill after idle timeout)
40
+ camo start worker-1 --headless --alias shard1 --idle-timeout 30m
38
41
 
39
42
  # Navigate
40
43
  camo goto https://www.xiaohongshu.com
@@ -68,8 +71,12 @@ camo create fingerprint --os <os> --region <region>
68
71
  ### Browser Control
69
72
 
70
73
  ```bash
71
- camo start [profileId] [--url <url>] [--headless] [--width <w> --height <h>]
74
+ camo start [profileId] [--url <url>] [--headless] [--alias <name>] [--idle-timeout <duration>] [--width <w> --height <h>]
72
75
  camo stop [profileId]
76
+ camo stop --id <instanceId>
77
+ camo stop --alias <alias>
78
+ camo stop idle
79
+ camo stop all
73
80
  camo status [profileId]
74
81
  camo shutdown # Shutdown browser-service (all sessions)
75
82
  ```
@@ -77,10 +84,12 @@ camo shutdown # Shutdown browser-service (all sessions)
77
84
  `camo start` in headful mode now persists window size per profile and reuses that size on next start.
78
85
  If no saved size exists, it defaults to near-fullscreen (full width, slight vertical reserve).
79
86
  Use `--width/--height` to override and update the saved profile size.
87
+ For headless sessions, default idle timeout is `30m` (auto-stop on inactivity). Use `--idle-timeout` (e.g. `45m`, `1800s`, `0`) to customize.
80
88
 
81
89
  ### Lifecycle & Cleanup
82
90
 
83
91
  ```bash
92
+ camo instances # List global camoufox instances (live + orphaned + idle state)
84
93
  camo sessions # List active browser sessions
85
94
  camo cleanup [profileId] # Cleanup session (release lock + stop)
86
95
  camo cleanup all # Cleanup all active sessions
@@ -332,7 +341,7 @@ Condition types:
332
341
  Camo CLI persists session information locally:
333
342
 
334
343
  - Sessions are registered in `~/.webauto/sessions/`
335
- - On restart, `camo sessions` shows both live and orphaned sessions
344
+ - On restart, `camo sessions` / `camo instances` shows live + orphaned sessions
336
345
  - Use `camo recover <profileId>` to reconnect or cleanup orphaned sessions
337
346
  - Stale sessions (>7 days) are automatically cleaned up
338
347
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@web-auto/camo",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Camoufox Browser CLI - Cross-platform browser automation",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -2,7 +2,6 @@
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import path from 'node:path';
4
4
  import { listProfiles, getDefaultProfile, loadConfig, hasStartScript, setRepoRoot } from './utils/config.mjs';
5
- import { ensureCamoufox, ensureBrowserService } from './utils/browser-service.mjs';
6
5
  import { printHelp, printProfilesAndHint } from './utils/help.mjs';
7
6
  import { handleProfileCommand } from './commands/profile.mjs';
8
7
  import { handleInitCommand } from './commands/init.mjs';
@@ -24,7 +23,7 @@ import {
24
23
  } from './commands/browser.mjs';
25
24
  import {
26
25
  handleCleanupCommand, handleForceStopCommand, handleLockCommand,
27
- handleUnlockCommand, handleSessionsCommand
26
+ handleUnlockCommand, handleSessionsCommand, handleInstancesCommand
28
27
  } from './commands/lifecycle.mjs';
29
28
  import { handleSessionWatchdogCommand } from './lifecycle/session-watchdog.mjs';
30
29
  import { safeAppendProgressEvent } from './events/progress-log.mjs';
@@ -55,6 +54,13 @@ function inferProfileId(cmd, args) {
55
54
  'new-page', 'close-page', 'switch-page', 'list-pages',
56
55
  'cleanup', 'force-stop', 'lock', 'unlock', 'sessions',
57
56
  ].includes(cmd)) {
57
+ if ((cmd === 'stop' || cmd === 'close') && (args.includes('--id') || args.includes('--alias'))) {
58
+ return null;
59
+ }
60
+ const first = positionals[0] || null;
61
+ if ((cmd === 'stop' || cmd === 'close') && (first === 'all' || first === 'idle')) {
62
+ return null;
63
+ }
58
64
  return positionals[0] || null;
59
65
  }
60
66
 
@@ -212,6 +218,11 @@ async function main() {
212
218
  return;
213
219
  }
214
220
 
221
+ if (cmd === 'instances') {
222
+ await runTrackedCommand(cmd, args, () => handleInstancesCommand(args));
223
+ return;
224
+ }
225
+
215
226
  if (cmd === 'container') {
216
227
  await runTrackedCommand(cmd, args, () => handleContainerCommand(args));
217
228
  return;
@@ -7,14 +7,25 @@ import {
7
7
  } from '../utils/config.mjs';
8
8
  import { callAPI, ensureCamoufox, ensureBrowserService, getSessionByProfile, checkBrowserService } from '../utils/browser-service.mjs';
9
9
  import { resolveProfileId, ensureUrlScheme, looksLikeUrlToken, getPositionals } from '../utils/args.mjs';
10
- import { acquireLock, releaseLock, isLocked, getLockInfo, cleanupStaleLocks } from '../lifecycle/lock.mjs';
11
- import { registerSession, updateSession, getSessionInfo, unregisterSession, listRegisteredSessions, markSessionClosed, cleanupStaleSessions, recoverSession } from '../lifecycle/session-registry.mjs';
10
+ import { acquireLock, releaseLock, cleanupStaleLocks } from '../lifecycle/lock.mjs';
11
+ import {
12
+ registerSession,
13
+ updateSession,
14
+ getSessionInfo,
15
+ unregisterSession,
16
+ listRegisteredSessions,
17
+ markSessionClosed,
18
+ cleanupStaleSessions,
19
+ resolveSessionTarget,
20
+ isSessionAliasTaken,
21
+ } from '../lifecycle/session-registry.mjs';
12
22
  import { startSessionWatchdog, stopAllSessionWatchdogs, stopSessionWatchdog } from '../lifecycle/session-watchdog.mjs';
13
23
 
14
24
  const START_WINDOW_MIN_WIDTH = 960;
15
25
  const START_WINDOW_MIN_HEIGHT = 700;
16
26
  const START_WINDOW_MAX_RESERVE = 240;
17
27
  const START_WINDOW_DEFAULT_RESERVE = 72;
28
+ const DEFAULT_HEADLESS_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
18
29
 
19
30
  function sleep(ms) {
20
31
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -29,6 +40,88 @@ function clamp(value, min, max) {
29
40
  return Math.min(Math.max(value, min), max);
30
41
  }
31
42
 
43
+ function readFlagValue(args, names) {
44
+ for (let i = 0; i < args.length; i += 1) {
45
+ if (!names.includes(args[i])) continue;
46
+ const value = args[i + 1];
47
+ if (!value || String(value).startsWith('-')) return null;
48
+ return value;
49
+ }
50
+ return null;
51
+ }
52
+
53
+ function parseDurationMs(raw, fallbackMs) {
54
+ if (raw === undefined || raw === null || String(raw).trim() === '') return fallbackMs;
55
+ const text = String(raw).trim().toLowerCase();
56
+ if (text === '0' || text === 'off' || text === 'none' || text === 'disable' || text === 'disabled') return 0;
57
+ const matched = text.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
58
+ if (!matched) {
59
+ throw new Error('Invalid --idle-timeout. Use forms like 30m, 1800s, 5000ms, 1h, 0');
60
+ }
61
+ const value = Number(matched[1]);
62
+ if (!Number.isFinite(value) || value < 0) {
63
+ throw new Error('Invalid --idle-timeout value');
64
+ }
65
+ const unit = matched[2] || 'm';
66
+ const factor = unit === 'h' ? 3600000 : unit === 'm' ? 60000 : unit === 's' ? 1000 : 1;
67
+ return Math.floor(value * factor);
68
+ }
69
+
70
+ function validateAlias(alias) {
71
+ const text = String(alias || '').trim();
72
+ if (!text) return null;
73
+ if (!/^[a-zA-Z0-9._-]+$/.test(text)) {
74
+ throw new Error('Invalid --alias. Use only letters, numbers, dot, underscore, dash.');
75
+ }
76
+ return text.slice(0, 64);
77
+ }
78
+
79
+ function formatDurationMs(ms) {
80
+ const value = Number(ms);
81
+ if (!Number.isFinite(value) || value <= 0) return 'disabled';
82
+ if (value % 3600000 === 0) return `${value / 3600000}h`;
83
+ if (value % 60000 === 0) return `${value / 60000}m`;
84
+ if (value % 1000 === 0) return `${value / 1000}s`;
85
+ return `${value}ms`;
86
+ }
87
+
88
+ function computeIdleState(session, now = Date.now()) {
89
+ const headless = session?.headless === true;
90
+ const timeoutMs = headless
91
+ ? (Number.isFinite(Number(session?.idleTimeoutMs)) ? Math.max(0, Number(session.idleTimeoutMs)) : DEFAULT_HEADLESS_IDLE_TIMEOUT_MS)
92
+ : 0;
93
+ const lastAt = Number(session?.lastActivityAt || session?.lastSeen || session?.startTime || now);
94
+ const idleMs = Math.max(0, now - (Number.isFinite(lastAt) ? lastAt : now));
95
+ const idle = headless && timeoutMs > 0 && idleMs >= timeoutMs;
96
+ return { headless, timeoutMs, idleMs, idle };
97
+ }
98
+
99
+ async function stopAndCleanupProfile(profileId, options = {}) {
100
+ const id = String(profileId || '').trim();
101
+ if (!id) return { profileId: id, ok: false, error: 'profile_required' };
102
+ const force = options.force === true;
103
+ const serviceUp = options.serviceUp === true;
104
+ let result = null;
105
+ let error = null;
106
+ if (serviceUp) {
107
+ try {
108
+ result = await callAPI('stop', force ? { profileId: id, force: true } : { profileId: id });
109
+ } catch (err) {
110
+ error = err;
111
+ }
112
+ }
113
+ stopSessionWatchdog(id);
114
+ releaseLock(id);
115
+ markSessionClosed(id);
116
+ return {
117
+ profileId: id,
118
+ ok: !error,
119
+ serviceUp,
120
+ result,
121
+ error: error ? (error.message || String(error)) : null,
122
+ };
123
+ }
124
+
32
125
  export function computeTargetViewportFromWindowMetrics(measured) {
33
126
  const innerWidth = Math.max(320, parseNumber(measured?.innerWidth, 0));
34
127
  const innerHeight = Math.max(240, parseNumber(measured?.innerHeight, 0));
@@ -154,8 +247,11 @@ export async function handleStartCommand(args) {
154
247
  const explicitHeight = heightIdx >= 0 ? parseNumber(args[heightIdx + 1], NaN) : NaN;
155
248
  const hasExplicitWidth = Number.isFinite(explicitWidth);
156
249
  const hasExplicitHeight = Number.isFinite(explicitHeight);
250
+ const alias = validateAlias(readFlagValue(args, ['--alias']));
251
+ const idleTimeoutRaw = readFlagValue(args, ['--idle-timeout']);
252
+ const parsedIdleTimeoutMs = parseDurationMs(idleTimeoutRaw, DEFAULT_HEADLESS_IDLE_TIMEOUT_MS);
157
253
  if (hasExplicitWidth !== hasExplicitHeight) {
158
- throw new Error('Usage: camo start [profileId] [--url <url>] [--headless] [--width <w> --height <h>]');
254
+ throw new Error('Usage: camo start [profileId] [--url <url>] [--headless] [--alias <name>] [--idle-timeout <duration>] [--width <w> --height <h>]');
159
255
  }
160
256
  if ((hasExplicitWidth && explicitWidth < START_WINDOW_MIN_WIDTH) || (hasExplicitHeight && explicitHeight < START_WINDOW_MIN_HEIGHT)) {
161
257
  throw new Error(`Window size too small. Minimum is ${START_WINDOW_MIN_WIDTH}x${START_WINDOW_MIN_HEIGHT}`);
@@ -169,6 +265,7 @@ export async function handleStartCommand(args) {
169
265
  const arg = args[i];
170
266
  if (arg === '--url') { i++; continue; }
171
267
  if (arg === '--width' || arg === '--height') { i++; continue; }
268
+ if (arg === '--alias' || arg === '--idle-timeout') { i++; continue; }
172
269
  if (arg === '--headless') continue;
173
270
  if (arg.startsWith('--')) continue;
174
271
 
@@ -187,23 +284,45 @@ export async function handleStartCommand(args) {
187
284
  throw new Error('No default profile set. Run: camo profile default <profileId>');
188
285
  }
189
286
  }
287
+ if (alias && isSessionAliasTaken(alias, profileId)) {
288
+ throw new Error(`Alias is already in use: ${alias}`);
289
+ }
190
290
 
191
291
  // Check for existing session in browser service
192
292
  const existing = await getSessionByProfile(profileId);
193
293
  if (existing) {
194
294
  // Session exists in browser service - update registry and lock
195
295
  acquireLock(profileId, { sessionId: existing.session_id || existing.profileId });
196
- registerSession(profileId, {
197
- sessionId: existing.session_id || existing.profileId,
198
- url: existing.current_url,
199
- mode: existing.mode,
200
- });
296
+ const saved = getSessionInfo(profileId);
297
+ const record = saved
298
+ ? updateSession(profileId, {
299
+ sessionId: existing.session_id || existing.profileId,
300
+ url: existing.current_url,
301
+ mode: existing.mode,
302
+ alias: alias || saved.alias || null,
303
+ })
304
+ : registerSession(profileId, {
305
+ sessionId: existing.session_id || existing.profileId,
306
+ url: existing.current_url,
307
+ mode: existing.mode,
308
+ alias: alias || null,
309
+ });
310
+ const idleState = computeIdleState(record);
201
311
  console.log(JSON.stringify({
202
312
  ok: true,
203
313
  sessionId: existing.session_id || existing.profileId,
314
+ instanceId: record.instanceId,
204
315
  profileId,
205
316
  message: 'Session already running',
206
317
  url: existing.current_url,
318
+ alias: record.alias || null,
319
+ idleTimeoutMs: idleState.timeoutMs,
320
+ idleTimeout: formatDurationMs(idleState.timeoutMs),
321
+ closeHint: {
322
+ byProfile: `camo stop ${profileId}`,
323
+ byId: `camo stop --id ${record.instanceId}`,
324
+ byAlias: record.alias ? `camo stop --alias ${record.alias}` : null,
325
+ },
207
326
  }, null, 2));
208
327
  startSessionWatchdog(profileId);
209
328
  return;
@@ -219,6 +338,7 @@ export async function handleStartCommand(args) {
219
338
  }
220
339
 
221
340
  const headless = args.includes('--headless');
341
+ const idleTimeoutMs = headless ? parsedIdleTimeoutMs : 0;
222
342
  const targetUrl = explicitUrl || implicitUrl;
223
343
  const result = await callAPI('start', {
224
344
  profileId,
@@ -229,12 +349,28 @@ export async function handleStartCommand(args) {
229
349
  if (result?.ok) {
230
350
  const sessionId = result.sessionId || result.profileId || profileId;
231
351
  acquireLock(profileId, { sessionId });
232
- registerSession(profileId, {
352
+ const record = registerSession(profileId, {
233
353
  sessionId,
234
354
  url: targetUrl,
235
355
  headless,
356
+ alias,
357
+ idleTimeoutMs,
358
+ lastAction: 'start',
236
359
  });
237
360
  startSessionWatchdog(profileId);
361
+ result.instanceId = record.instanceId;
362
+ result.alias = record.alias || null;
363
+ result.idleTimeoutMs = idleTimeoutMs;
364
+ result.idleTimeout = formatDurationMs(idleTimeoutMs);
365
+ result.closeHint = {
366
+ byProfile: `camo stop ${profileId}`,
367
+ byId: `camo stop --id ${record.instanceId}`,
368
+ byAlias: record.alias ? `camo stop --alias ${record.alias}` : null,
369
+ all: 'camo close all',
370
+ };
371
+ result.message = headless
372
+ ? `Started headless session. Idle timeout: ${formatDurationMs(idleTimeoutMs)}`
373
+ : 'Started session. Remember to stop it when finished.';
238
374
 
239
375
  if (!headless) {
240
376
  let windowTarget = null;
@@ -286,24 +422,115 @@ export async function handleStartCommand(args) {
286
422
  }
287
423
 
288
424
  export async function handleStopCommand(args) {
289
- await ensureBrowserService();
290
- const profileId = resolveProfileId(args, 1, getDefaultProfile);
291
- if (!profileId) throw new Error('Usage: camo stop [profileId]');
425
+ const rawTarget = String(args[1] || '').trim();
426
+ const target = rawTarget.toLowerCase();
427
+ const idTarget = readFlagValue(args, ['--id']);
428
+ const aliasTarget = readFlagValue(args, ['--alias']);
429
+ const stopIdle = target === 'idle' || args.includes('--idle');
430
+ const stopAll = target === 'all';
431
+ const serviceUp = await checkBrowserService();
292
432
 
293
- let result = null;
294
- let stopError = null;
295
- try {
296
- result = await callAPI('stop', { profileId });
297
- } catch (err) {
298
- stopError = err;
299
- } finally {
300
- stopSessionWatchdog(profileId);
301
- releaseLock(profileId);
302
- markSessionClosed(profileId);
433
+ if (stopAll) {
434
+ let liveSessions = [];
435
+ if (serviceUp) {
436
+ try {
437
+ const status = await callAPI('getStatus', {});
438
+ liveSessions = Array.isArray(status?.sessions) ? status.sessions : [];
439
+ } catch {
440
+ // Ignore and fallback to local registry.
441
+ }
442
+ }
443
+ const profileSet = new Set(liveSessions.map((item) => String(item?.profileId || '').trim()).filter(Boolean));
444
+ for (const session of listRegisteredSessions()) {
445
+ if (String(session?.status || '').trim() === 'closed') continue;
446
+ const profileId = String(session?.profileId || '').trim();
447
+ if (profileId) profileSet.add(profileId);
448
+ }
449
+
450
+ const results = [];
451
+ for (const profileId of profileSet) {
452
+ // eslint-disable-next-line no-await-in-loop
453
+ results.push(await stopAndCleanupProfile(profileId, { serviceUp }));
454
+ }
455
+ console.log(JSON.stringify({
456
+ ok: true,
457
+ mode: 'all',
458
+ serviceUp,
459
+ closed: results.filter((item) => item.ok).length,
460
+ failed: results.filter((item) => !item.ok).length,
461
+ results,
462
+ }, null, 2));
463
+ return;
303
464
  }
304
465
 
305
- if (stopError) throw stopError;
306
- console.log(JSON.stringify(result, null, 2));
466
+ if (stopIdle) {
467
+ const now = Date.now();
468
+ const idleTargets = listRegisteredSessions()
469
+ .filter((item) => String(item?.status || '').trim() === 'active')
470
+ .map((item) => ({ session: item, idle: computeIdleState(item, now) }))
471
+ .filter((item) => item.idle.idle)
472
+ .map((item) => item.session.profileId);
473
+ const results = [];
474
+ for (const profileId of idleTargets) {
475
+ // eslint-disable-next-line no-await-in-loop
476
+ results.push(await stopAndCleanupProfile(profileId, { serviceUp }));
477
+ }
478
+ console.log(JSON.stringify({
479
+ ok: true,
480
+ mode: 'idle',
481
+ serviceUp,
482
+ targetCount: idleTargets.length,
483
+ closed: results.filter((item) => item.ok).length,
484
+ failed: results.filter((item) => !item.ok).length,
485
+ results,
486
+ }, null, 2));
487
+ return;
488
+ }
489
+
490
+ let profileId = null;
491
+ let resolvedBy = 'profile';
492
+ if (idTarget) {
493
+ const resolved = resolveSessionTarget(idTarget);
494
+ if (!resolved) throw new Error(`No session found for instance id: ${idTarget}`);
495
+ profileId = resolved.profileId;
496
+ resolvedBy = resolved.reason;
497
+ } else if (aliasTarget) {
498
+ const resolved = resolveSessionTarget(aliasTarget);
499
+ if (!resolved) throw new Error(`No session found for alias: ${aliasTarget}`);
500
+ profileId = resolved.profileId;
501
+ resolvedBy = resolved.reason;
502
+ } else {
503
+ const positional = args.slice(1).find((arg) => arg && !String(arg).startsWith('--')) || null;
504
+ if (positional) {
505
+ const resolved = resolveSessionTarget(positional);
506
+ if (resolved) {
507
+ profileId = resolved.profileId;
508
+ resolvedBy = resolved.reason;
509
+ } else {
510
+ profileId = positional;
511
+ }
512
+ }
513
+ }
514
+
515
+ if (!profileId) {
516
+ profileId = getDefaultProfile();
517
+ }
518
+ if (!profileId) {
519
+ throw new Error('Usage: camo stop [profileId] | camo stop --id <instanceId> | camo stop --alias <alias> | camo stop all | camo stop idle');
520
+ }
521
+
522
+ const result = await stopAndCleanupProfile(profileId, { serviceUp });
523
+ if (!result.ok && serviceUp) {
524
+ throw new Error(result.error || `stop failed for profile: ${profileId}`);
525
+ }
526
+ console.log(JSON.stringify({
527
+ ok: true,
528
+ profileId,
529
+ resolvedBy,
530
+ serviceUp,
531
+ warning: (!serviceUp && !result.ok) ? result.error : null,
532
+ result: result.result || null,
533
+ }, null, 2));
307
534
  }
308
535
 
309
536
  export async function handleStatusCommand(args) {
@@ -5,13 +5,81 @@
5
5
  import { getDefaultProfile } from '../utils/config.mjs';
6
6
  import { callAPI, ensureBrowserService, checkBrowserService } from '../utils/browser-service.mjs';
7
7
  import { resolveProfileId } from '../utils/args.mjs';
8
- import { acquireLock, getLockInfo, releaseLock, isLocked, cleanupStaleLocks, listActiveLocks } from '../lifecycle/lock.mjs';
8
+ import { acquireLock, getLockInfo, releaseLock, cleanupStaleLocks, listActiveLocks } from '../lifecycle/lock.mjs';
9
9
  import {
10
10
  getSessionInfo, unregisterSession, markSessionClosed, cleanupStaleSessions,
11
- listRegisteredSessions, registerSession, updateSession
11
+ listRegisteredSessions, updateSession
12
12
  } from '../lifecycle/session-registry.mjs';
13
13
  import { stopAllSessionWatchdogs, stopSessionWatchdog } from '../lifecycle/session-watchdog.mjs';
14
14
 
15
+ const DEFAULT_HEADLESS_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
16
+
17
+ function computeIdleState(session, now = Date.now()) {
18
+ const headless = session?.headless === true;
19
+ const timeoutMs = headless
20
+ ? (Number.isFinite(Number(session?.idleTimeoutMs)) ? Math.max(0, Number(session.idleTimeoutMs)) : DEFAULT_HEADLESS_IDLE_TIMEOUT_MS)
21
+ : 0;
22
+ const lastAt = Number(session?.lastActivityAt || session?.lastSeen || session?.startTime || now);
23
+ const idleMs = Math.max(0, now - (Number.isFinite(lastAt) ? lastAt : now));
24
+ const idle = headless && timeoutMs > 0 && idleMs >= timeoutMs;
25
+ return { headless, timeoutMs, idleMs, idle };
26
+ }
27
+
28
+ function buildMergedSessionRows(liveSessions, registeredSessions) {
29
+ const now = Date.now();
30
+ const regMap = new Map(registeredSessions.map((item) => [item.profileId, item]));
31
+ const rows = [];
32
+ const liveMap = new Map(liveSessions.map((item) => [item.profileId, item]));
33
+
34
+ for (const live of liveSessions) {
35
+ const reg = regMap.get(live.profileId);
36
+ const idle = computeIdleState(reg || {}, now);
37
+ rows.push({
38
+ profileId: live.profileId,
39
+ sessionId: live.session_id || live.profileId,
40
+ instanceId: reg?.instanceId || live.session_id || live.profileId,
41
+ alias: reg?.alias || null,
42
+ url: live.current_url,
43
+ mode: live.mode,
44
+ headless: idle.headless,
45
+ idleTimeoutMs: idle.timeoutMs,
46
+ idleMs: idle.idleMs,
47
+ idle: idle.idle,
48
+ live: true,
49
+ registered: !!reg,
50
+ registryStatus: reg?.status,
51
+ lastSeen: reg?.lastSeen || null,
52
+ lastActivityAt: reg?.lastActivityAt || null,
53
+ });
54
+ }
55
+
56
+ for (const reg of registeredSessions) {
57
+ if (liveMap.has(reg.profileId)) continue;
58
+ if (reg.status === 'closed') continue;
59
+ const idle = computeIdleState(reg, now);
60
+ rows.push({
61
+ profileId: reg.profileId,
62
+ sessionId: reg.sessionId || reg.profileId,
63
+ instanceId: reg.instanceId || reg.sessionId || reg.profileId,
64
+ alias: reg.alias || null,
65
+ url: reg.url || null,
66
+ mode: reg.mode || null,
67
+ headless: idle.headless,
68
+ idleTimeoutMs: idle.timeoutMs,
69
+ idleMs: idle.idleMs,
70
+ idle: idle.idle,
71
+ live: false,
72
+ orphaned: true,
73
+ needsRecovery: reg.status === 'active',
74
+ registered: true,
75
+ registryStatus: reg.status,
76
+ lastSeen: reg.lastSeen || null,
77
+ lastActivityAt: reg.lastActivityAt || null,
78
+ });
79
+ }
80
+ return rows;
81
+ }
82
+
15
83
  export async function handleCleanupCommand(args) {
16
84
  const sub = args[1];
17
85
 
@@ -158,38 +226,7 @@ export async function handleSessionsCommand(args) {
158
226
  } catch {}
159
227
  }
160
228
 
161
- // Build a map of live sessions
162
- const liveMap = new Map(liveSessions.map(s => [s.profileId, s]));
163
-
164
- // Merge live and registered sessions
165
- const merged = [];
166
-
167
- // Add all live sessions
168
- for (const live of liveSessions) {
169
- const reg = getSessionInfo(live.profileId);
170
- merged.push({
171
- profileId: live.profileId,
172
- sessionId: live.session_id || live.profileId,
173
- url: live.current_url,
174
- mode: live.mode,
175
- live: true,
176
- registered: !!reg,
177
- registryStatus: reg?.status,
178
- lastSeen: reg?.lastSeen,
179
- });
180
- }
181
-
182
- // Add registered sessions that are not live (orphaned)
183
- for (const reg of registeredSessions) {
184
- if (!liveMap.has(reg.profileId) && reg.status !== 'closed') {
185
- merged.push({
186
- ...reg,
187
- live: false,
188
- orphaned: true,
189
- needsRecovery: reg.status === 'active',
190
- });
191
- }
192
- }
229
+ const merged = buildMergedSessionRows(liveSessions, registeredSessions);
193
230
 
194
231
  console.log(JSON.stringify({
195
232
  ok: true,
@@ -202,6 +239,10 @@ export async function handleSessionsCommand(args) {
202
239
  }, null, 2));
203
240
  }
204
241
 
242
+ export async function handleInstancesCommand(args) {
243
+ await handleSessionsCommand(args);
244
+ }
245
+
205
246
  export async function handleRecoverCommand(args) {
206
247
  const profileId = resolveProfileId(args, 1, getDefaultProfile);
207
248
  if (!profileId) throw new Error('Usage: camo recover [profileId]');
@@ -6,6 +6,7 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import os from 'node:os';
9
+ import crypto from 'node:crypto';
9
10
 
10
11
  const SESSION_DIR = path.join(os.homedir(), '.webauto', 'sessions');
11
12
 
@@ -15,6 +16,25 @@ function ensureSessionDir() {
15
16
  }
16
17
  }
17
18
 
19
+ function normalizeAlias(value) {
20
+ const text = String(value || '').trim();
21
+ if (!text) return null;
22
+ if (!/^[a-zA-Z0-9._-]+$/.test(text)) {
23
+ throw new Error('Invalid alias. Use only letters, numbers, dot, underscore, dash.');
24
+ }
25
+ return text.slice(0, 64);
26
+ }
27
+
28
+ function normalizeTimeoutMs(value) {
29
+ const ms = Number(value);
30
+ if (!Number.isFinite(ms) || ms < 0) return null;
31
+ return Math.floor(ms);
32
+ }
33
+
34
+ function generateInstanceId() {
35
+ return `inst_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
36
+ }
37
+
18
38
  export function getSessionFile(profileId) {
19
39
  return path.join(SESSION_DIR, `${profileId}.json`);
20
40
  }
@@ -22,14 +42,24 @@ export function getSessionFile(profileId) {
22
42
  export function registerSession(profileId, sessionInfo = {}) {
23
43
  ensureSessionDir();
24
44
  const sessionFile = getSessionFile(profileId);
45
+ const now = Date.now();
46
+ const alias = normalizeAlias(sessionInfo.alias);
47
+ const idleTimeoutMs = normalizeTimeoutMs(sessionInfo.idleTimeoutMs);
48
+ const instanceId = String(sessionInfo.instanceId || sessionInfo.sessionId || generateInstanceId()).trim();
25
49
 
26
50
  const sessionData = {
27
51
  profileId,
28
52
  pid: process.pid,
29
- startTime: Date.now(),
30
- lastSeen: Date.now(),
53
+ instanceId,
54
+ alias,
55
+ startTime: now,
56
+ lastSeen: now,
57
+ lastActivityAt: now,
31
58
  status: 'active',
32
59
  ...sessionInfo,
60
+ instanceId,
61
+ alias,
62
+ idleTimeoutMs,
33
63
  };
34
64
 
35
65
  fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
@@ -44,12 +74,30 @@ export function updateSession(profileId, updates = {}) {
44
74
 
45
75
  try {
46
76
  const existing = JSON.parse(fs.readFileSync(sessionFile, 'utf-8'));
77
+ const now = Date.now();
78
+ const mergedAlias = Object.prototype.hasOwnProperty.call(updates, 'alias')
79
+ ? normalizeAlias(updates.alias)
80
+ : normalizeAlias(existing.alias);
81
+ const mergedIdleTimeoutMs = Object.prototype.hasOwnProperty.call(updates, 'idleTimeoutMs')
82
+ ? normalizeTimeoutMs(updates.idleTimeoutMs)
83
+ : normalizeTimeoutMs(existing.idleTimeoutMs);
84
+ const touchActivity = updates.touchActivity === true;
85
+ const nextActivityAt = touchActivity
86
+ ? now
87
+ : (Object.prototype.hasOwnProperty.call(updates, 'lastActivityAt')
88
+ ? Number(updates.lastActivityAt) || now
89
+ : Number(existing.lastActivityAt) || now);
47
90
  const updated = {
48
91
  ...existing,
49
92
  ...updates,
50
- lastSeen: Date.now(),
93
+ instanceId: String(updates.instanceId || existing.instanceId || updates.sessionId || existing.sessionId || generateInstanceId()).trim(),
94
+ alias: mergedAlias,
95
+ idleTimeoutMs: mergedIdleTimeoutMs,
96
+ lastSeen: now,
97
+ lastActivityAt: nextActivityAt,
51
98
  profileId,
52
99
  };
100
+ delete updated.touchActivity;
53
101
  fs.writeFileSync(sessionFile, JSON.stringify(updated, null, 2));
54
102
  return updated;
55
103
  } catch {
@@ -93,6 +141,54 @@ export function listRegisteredSessions() {
93
141
  return sessions;
94
142
  }
95
143
 
144
+ export function findSessionByAlias(alias) {
145
+ const target = normalizeAlias(alias);
146
+ if (!target) return null;
147
+ return listRegisteredSessions().find((item) => normalizeAlias(item?.alias) === target) || null;
148
+ }
149
+
150
+ export function findSessionByInstanceId(instanceId) {
151
+ const target = String(instanceId || '').trim();
152
+ if (!target) return null;
153
+ return listRegisteredSessions().find((item) => String(item?.instanceId || '').trim() === target) || null;
154
+ }
155
+
156
+ export function resolveSessionTarget(target) {
157
+ const value = String(target || '').trim();
158
+ if (!value) return null;
159
+ const sessions = listRegisteredSessions();
160
+ const byProfile = sessions.find((item) => String(item?.profileId || '').trim() === value);
161
+ if (byProfile) return { profileId: byProfile.profileId, reason: 'profile', session: byProfile };
162
+ const byInstanceId = sessions.find((item) => String(item?.instanceId || '').trim() === value);
163
+ if (byInstanceId) return { profileId: byInstanceId.profileId, reason: 'instanceId', session: byInstanceId };
164
+ const byAlias = sessions.find((item) => normalizeAlias(item?.alias) === normalizeAlias(value));
165
+ if (byAlias) return { profileId: byAlias.profileId, reason: 'alias', session: byAlias };
166
+ return null;
167
+ }
168
+
169
+ export function isSessionAliasTaken(alias, exceptProfileId = '') {
170
+ const target = normalizeAlias(alias);
171
+ if (!target) return false;
172
+ const except = String(exceptProfileId || '').trim();
173
+ return listRegisteredSessions().some((item) => {
174
+ if (!item) return false;
175
+ if (except && String(item.profileId || '').trim() === except) return false;
176
+ if (String(item.status || '').trim() !== 'active') return false;
177
+ return normalizeAlias(item.alias) === target;
178
+ });
179
+ }
180
+
181
+ export function touchSessionActivity(profileId, updates = {}) {
182
+ const id = String(profileId || '').trim();
183
+ if (!id) return null;
184
+ const existing = getSessionInfo(id);
185
+ if (!existing) return null;
186
+ return updateSession(id, {
187
+ ...updates,
188
+ touchActivity: true,
189
+ });
190
+ }
191
+
96
192
  export function markSessionReconnecting(profileId) {
97
193
  return updateSession(profileId, { status: 'reconnecting', reconnectAttempt: Date.now() });
98
194
  }
@@ -9,6 +9,7 @@ import { releaseLock } from './lock.mjs';
9
9
  import { getSessionInfo, markSessionClosed } from './session-registry.mjs';
10
10
 
11
11
  const WATCHDOG_DIR = path.join(os.homedir(), '.webauto', 'run', 'camo-watchdogs');
12
+ const DEFAULT_HEADLESS_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
12
13
 
13
14
  function ensureWatchdogDir() {
14
15
  if (!fs.existsSync(WATCHDOG_DIR)) {
@@ -102,9 +103,11 @@ async function syncViewportWithWindow(profileId, tolerancePx = 3) {
102
103
  return true;
103
104
  }
104
105
 
105
- function shouldExitMonitor(profileId) {
106
- const info = getSessionInfo(profileId);
107
- return !info || info.status !== 'active';
106
+ function resolveIdleTimeoutMs(sessionInfo) {
107
+ if (!sessionInfo || sessionInfo.headless !== true) return 0;
108
+ const raw = Number(sessionInfo.idleTimeoutMs);
109
+ if (Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
110
+ return DEFAULT_HEADLESS_IDLE_TIMEOUT_MS;
108
111
  }
109
112
 
110
113
  async function cleanupSession(profileId) {
@@ -126,7 +129,18 @@ async function runMonitor(profileId, options = {}) {
126
129
  let blankOnlyStreak = 0;
127
130
 
128
131
  while (true) {
129
- if (shouldExitMonitor(profileId)) return;
132
+ const localInfo = getSessionInfo(profileId);
133
+ if (!localInfo || localInfo.status !== 'active') return;
134
+
135
+ const idleTimeoutMs = resolveIdleTimeoutMs(localInfo);
136
+ if (idleTimeoutMs > 0) {
137
+ const lastActivityAt = Number(localInfo.lastActivityAt || localInfo.lastSeen || localInfo.startTime || Date.now());
138
+ const idleMs = Date.now() - lastActivityAt;
139
+ if (idleMs >= idleTimeoutMs) {
140
+ await cleanupSession(profileId);
141
+ return;
142
+ }
143
+ }
130
144
 
131
145
  let sessions = [];
132
146
  try {
@@ -4,6 +4,14 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
6
  import { BROWSER_SERVICE_URL, loadConfig, setRepoRoot } from './config.mjs';
7
+ import { touchSessionActivity } from '../lifecycle/session-registry.mjs';
8
+
9
+ function shouldTrackSessionActivity(action, payload) {
10
+ const profileId = String(payload?.profileId || '').trim();
11
+ if (!profileId) return false;
12
+ if (action === 'getStatus' || action === 'service:shutdown' || action === 'stop') return false;
13
+ return true;
14
+ }
7
15
 
8
16
  export async function callAPI(action, payload = {}) {
9
17
  const r = await fetch(`${BROWSER_SERVICE_URL}/command`, {
@@ -21,6 +29,12 @@ export async function callAPI(action, payload = {}) {
21
29
  }
22
30
 
23
31
  if (!r.ok) throw new Error(body?.error || `HTTP ${r.status}`);
32
+ if (shouldTrackSessionActivity(action, payload)) {
33
+ touchSessionActivity(payload.profileId, {
34
+ lastAction: String(action || '').trim() || null,
35
+ lastActionAt: Date.now(),
36
+ });
37
+ }
24
38
  return body;
25
39
  }
26
40
 
@@ -24,12 +24,17 @@ CONFIG:
24
24
 
25
25
  BROWSER CONTROL:
26
26
  init Ensure camoufox + ensure browser-service daemon
27
- start [profileId] [--url <url>] [--headless] [--width <w> --height <h>]
27
+ start [profileId] [--url <url>] [--headless] [--alias <name>] [--idle-timeout <duration>] [--width <w> --height <h>]
28
28
  stop [profileId]
29
+ stop --id <instanceId> Stop by instance id
30
+ stop --alias <alias> Stop by alias
31
+ stop idle Stop all idle sessions
32
+ stop all Stop all sessions
29
33
  status [profileId]
30
34
  list Alias of status
31
35
 
32
36
  LIFECYCLE & CLEANUP:
37
+ instances List global camoufox instances (live + registered + idle state)
33
38
  sessions List active browser sessions
34
39
  cleanup [profileId] Cleanup session (release lock + stop)
35
40
  cleanup all Cleanup all active sessions
@@ -90,8 +95,13 @@ EXAMPLES:
90
95
  camo create fingerprint --os windows --region uk
91
96
  camo profile create myprofile
92
97
  camo profile default myprofile
93
- camo start --url https://example.com
98
+ camo start --url https://example.com --alias main
99
+ camo start worker-1 --headless --alias shard1 --idle-timeout 45m
94
100
  camo start myprofile --width 1920 --height 1020
101
+ camo stop --id inst_xxxxxxxx
102
+ camo stop --alias shard1
103
+ camo stop idle
104
+ camo close all
95
105
  camo goto https://www.xiaohongshu.com
96
106
  camo scroll --down --amount 500
97
107
  camo click "#search-input"
@@ -109,6 +119,7 @@ EXAMPLES:
109
119
  camo mouse wheel --deltay -300
110
120
  camo system display
111
121
  camo sessions
122
+ camo instances
112
123
  camo cleanup myprofile
113
124
  camo force-stop myprofile
114
125
  camo lock list