@web-auto/camo 0.1.26 → 0.2.1

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 (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +586 -586
  3. package/bin/browser-service.mjs +11 -11
  4. package/bin/camo.mjs +22 -22
  5. package/package.json +48 -48
  6. package/scripts/build.mjs +19 -19
  7. package/scripts/bump-version.mjs +34 -34
  8. package/scripts/check-file-size.mjs +80 -80
  9. package/scripts/file-size-policy.json +12 -2
  10. package/scripts/install.mjs +76 -76
  11. package/scripts/release.sh +54 -54
  12. package/src/autoscript/action-providers/index.mjs +6 -6
  13. package/src/autoscript/impact-engine.mjs +78 -78
  14. package/src/autoscript/runtime.mjs +1017 -1017
  15. package/src/autoscript/schema.mjs +376 -376
  16. package/src/cli.mjs +405 -405
  17. package/src/commands/attach.mjs +141 -141
  18. package/src/commands/autoscript.mjs +1011 -1011
  19. package/src/commands/browser.mjs +1255 -1257
  20. package/src/commands/container.mjs +401 -401
  21. package/src/commands/cookies.mjs +69 -69
  22. package/src/commands/create.mjs +98 -98
  23. package/src/commands/devtools.mjs +349 -349
  24. package/src/commands/events.mjs +152 -152
  25. package/src/commands/highlight-mode.mjs +24 -24
  26. package/src/commands/init.mjs +68 -68
  27. package/src/commands/lifecycle.mjs +275 -275
  28. package/src/commands/mouse.mjs +45 -45
  29. package/src/commands/profile.mjs +46 -46
  30. package/src/commands/record.mjs +115 -115
  31. package/src/commands/system.mjs +14 -14
  32. package/src/commands/window.mjs +123 -123
  33. package/src/container/change-notifier.mjs +362 -362
  34. package/src/container/element-filter.mjs +143 -143
  35. package/src/container/index.mjs +3 -3
  36. package/src/container/runtime-core/checkpoint.mjs +209 -209
  37. package/src/container/runtime-core/index.mjs +21 -21
  38. package/src/container/runtime-core/operations/index.mjs +774 -774
  39. package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
  40. package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
  41. package/src/container/runtime-core/operations/viewport.mjs +189 -189
  42. package/src/container/runtime-core/search.mjs +190 -190
  43. package/src/container/runtime-core/subscription.mjs +224 -224
  44. package/src/container/runtime-core/utils.mjs +94 -94
  45. package/src/container/runtime-core/validation.mjs +127 -184
  46. package/src/container/runtime-core.mjs +1 -1
  47. package/src/container/subscription-registry.mjs +459 -459
  48. package/src/core/actions.mjs +561 -561
  49. package/src/core/browser.mjs +266 -266
  50. package/src/core/index.mjs +52 -52
  51. package/src/core/utils.mjs +91 -91
  52. package/src/events/daemon-entry.mjs +33 -33
  53. package/src/events/daemon.mjs +80 -80
  54. package/src/events/progress-log.mjs +109 -109
  55. package/src/events/ws-server.mjs +239 -239
  56. package/src/lib/client.mjs +200 -200
  57. package/src/lifecycle/cleanup.mjs +83 -83
  58. package/src/lifecycle/lock.mjs +126 -126
  59. package/src/lifecycle/session-registry.mjs +279 -279
  60. package/src/lifecycle/session-view.mjs +76 -76
  61. package/src/lifecycle/session-watchdog.mjs +281 -281
  62. package/src/services/browser-service/index.js +671 -674
  63. package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
  64. package/src/services/browser-service/internal/BrowserSession.js +325 -336
  65. package/src/services/browser-service/internal/ElementRegistry.js +60 -60
  66. package/src/services/browser-service/internal/ProfileLock.js +84 -84
  67. package/src/services/browser-service/internal/SessionManager.js +184 -184
  68. package/src/services/browser-service/internal/SessionManager.test.js +39 -39
  69. package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
  70. package/src/services/browser-service/internal/browser-session/input-ops.js +222 -219
  71. package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
  72. package/src/services/browser-service/internal/browser-session/logging.js +46 -46
  73. package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
  74. package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
  75. package/src/services/browser-service/internal/browser-session/page-management.js +302 -336
  76. package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
  77. package/src/services/browser-service/internal/browser-session/recording.js +198 -198
  78. package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
  79. package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
  80. package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
  81. package/src/services/browser-service/internal/browser-session/types.js +14 -14
  82. package/src/services/browser-service/internal/browser-session/utils.js +95 -95
  83. package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
  84. package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
  85. package/src/services/browser-service/internal/container-matcher.js +851 -851
  86. package/src/services/browser-service/internal/container-registry.js +182 -182
  87. package/src/services/browser-service/internal/engine-manager.js +259 -259
  88. package/src/services/browser-service/internal/fingerprint.js +203 -203
  89. package/src/services/browser-service/internal/heartbeat.js +137 -137
  90. package/src/services/browser-service/internal/logging.js +46 -46
  91. package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
  92. package/src/services/browser-service/internal/pageRuntime.js +28 -28
  93. package/src/services/browser-service/internal/runtimeInjector.js +31 -31
  94. package/src/services/browser-service/internal/service-process-logger.js +140 -140
  95. package/src/services/browser-service/internal/state-bus.js +45 -45
  96. package/src/services/browser-service/internal/storage-paths.js +42 -42
  97. package/src/services/browser-service/internal/ws-server.js +1194 -1194
  98. package/src/services/browser-service/internal/ws-server.test.js +58 -58
  99. package/src/services/browser-service/server.mjs +6 -6
  100. package/src/services/controller/cli-bridge.js +93 -93
  101. package/src/services/controller/container-index.js +50 -50
  102. package/src/services/controller/container-storage.js +36 -36
  103. package/src/services/controller/controller-actions.js +207 -207
  104. package/src/services/controller/controller.js +1138 -1138
  105. package/src/services/controller/selectors.js +54 -54
  106. package/src/services/controller/transport.js +125 -125
  107. package/src/utils/args.mjs +26 -26
  108. package/src/utils/browser-service.mjs +544 -544
  109. package/src/utils/command-log.mjs +64 -64
  110. package/src/utils/config.mjs +214 -214
  111. package/src/utils/fingerprint.mjs +181 -181
  112. package/src/utils/help.mjs +216 -216
  113. package/src/utils/js-policy.mjs +13 -13
  114. package/src/utils/ws-client.mjs +30 -30
  115. package/src/container/runtime-core/operations/tab-pool.mjs.bak +0 -762
  116. package/src/container/runtime-core/operations/tab-pool.mjs.syntax-error +0 -762
  117. package/src/services/browser-service/index.js.bak +0 -671
@@ -1,279 +1,279 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Session registry - persistent session state management
4
- * Stores session metadata locally for recovery/reconnection
5
- */
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
- import crypto from 'node:crypto';
9
- import { CONFIG_DIR } from '../utils/config.mjs';
10
-
11
- const SESSION_DIR = path.join(CONFIG_DIR, 'sessions');
12
-
13
- function ensureSessionDir() {
14
- if (!fs.existsSync(SESSION_DIR)) {
15
- fs.mkdirSync(SESSION_DIR, { recursive: true });
16
- }
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 isAliasProtectedStatus(status) {
29
- const normalized = String(status || '').trim().toLowerCase();
30
- return normalized === 'active' || normalized === 'reconnecting';
31
- }
32
-
33
- function normalizeTimeoutMs(value) {
34
- const ms = Number(value);
35
- if (!Number.isFinite(ms) || ms < 0) return null;
36
- return Math.floor(ms);
37
- }
38
-
39
- function generateInstanceId() {
40
- return `inst_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
41
- }
42
-
43
- export function getSessionFile(profileId) {
44
- return path.join(SESSION_DIR, `${profileId}.json`);
45
- }
46
-
47
- export function registerSession(profileId, sessionInfo = {}) {
48
- ensureSessionDir();
49
- const sessionFile = getSessionFile(profileId);
50
- const now = Date.now();
51
- const alias = normalizeAlias(sessionInfo.alias);
52
- const idleTimeoutMs = normalizeTimeoutMs(sessionInfo.idleTimeoutMs);
53
- const instanceId = String(sessionInfo.instanceId || sessionInfo.sessionId || generateInstanceId()).trim();
54
-
55
- const sessionData = {
56
- profileId,
57
- pid: process.pid,
58
- instanceId,
59
- alias,
60
- startTime: now,
61
- lastSeen: now,
62
- lastActivityAt: now,
63
- status: 'active',
64
- ...sessionInfo,
65
- instanceId,
66
- alias,
67
- idleTimeoutMs,
68
- };
69
-
70
- fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
71
- return sessionData;
72
- }
73
-
74
- export function updateSession(profileId, updates = {}) {
75
- const sessionFile = getSessionFile(profileId);
76
- if (!fs.existsSync(sessionFile)) {
77
- return registerSession(profileId, updates);
78
- }
79
-
80
- try {
81
- const existing = JSON.parse(fs.readFileSync(sessionFile, 'utf-8'));
82
- const now = Date.now();
83
- const mergedAlias = Object.prototype.hasOwnProperty.call(updates, 'alias')
84
- ? normalizeAlias(updates.alias)
85
- : normalizeAlias(existing.alias);
86
- const mergedIdleTimeoutMs = Object.prototype.hasOwnProperty.call(updates, 'idleTimeoutMs')
87
- ? normalizeTimeoutMs(updates.idleTimeoutMs)
88
- : normalizeTimeoutMs(existing.idleTimeoutMs);
89
- const touchActivity = updates.touchActivity === true;
90
- const nextActivityAt = touchActivity
91
- ? now
92
- : (Object.prototype.hasOwnProperty.call(updates, 'lastActivityAt')
93
- ? Number(updates.lastActivityAt) || now
94
- : Number(existing.lastActivityAt) || now);
95
- const updated = {
96
- ...existing,
97
- ...updates,
98
- instanceId: String(updates.instanceId || existing.instanceId || updates.sessionId || existing.sessionId || generateInstanceId()).trim(),
99
- alias: mergedAlias,
100
- idleTimeoutMs: mergedIdleTimeoutMs,
101
- lastSeen: now,
102
- lastActivityAt: nextActivityAt,
103
- profileId,
104
- };
105
- delete updated.touchActivity;
106
- fs.writeFileSync(sessionFile, JSON.stringify(updated, null, 2));
107
- return updated;
108
- } catch {
109
- return registerSession(profileId, updates);
110
- }
111
- }
112
-
113
- export function getSessionInfo(profileId) {
114
- const sessionFile = getSessionFile(profileId);
115
- if (!fs.existsSync(sessionFile)) return null;
116
-
117
- try {
118
- const content = fs.readFileSync(sessionFile, 'utf-8');
119
- return JSON.parse(content);
120
- } catch {
121
- return null;
122
- }
123
- }
124
-
125
- export function unregisterSession(profileId) {
126
- const sessionFile = getSessionFile(profileId);
127
- if (fs.existsSync(sessionFile)) {
128
- fs.unlinkSync(sessionFile);
129
- return true;
130
- }
131
- return false;
132
- }
133
-
134
- export function listRegisteredSessions() {
135
- ensureSessionDir();
136
- const files = fs.readdirSync(SESSION_DIR);
137
- const sessions = [];
138
-
139
- for (const file of files) {
140
- if (!file.endsWith('.json')) continue;
141
- const profileId = file.replace('.json', '');
142
- const info = getSessionInfo(profileId);
143
- if (info) sessions.push(info);
144
- }
145
-
146
- return sessions;
147
- }
148
-
149
- export function findSessionByAlias(alias) {
150
- const target = normalizeAlias(alias);
151
- if (!target) return null;
152
- return listRegisteredSessions().find((item) => normalizeAlias(item?.alias) === target) || null;
153
- }
154
-
155
- export function findSessionByInstanceId(instanceId) {
156
- const target = String(instanceId || '').trim();
157
- if (!target) return null;
158
- return listRegisteredSessions().find((item) => String(item?.instanceId || '').trim() === target) || null;
159
- }
160
-
161
- export function resolveSessionTarget(target) {
162
- const value = String(target || '').trim();
163
- if (!value) return null;
164
- const sessions = listRegisteredSessions();
165
- const byProfile = sessions.find((item) => String(item?.profileId || '').trim() === value);
166
- if (byProfile) return { profileId: byProfile.profileId, reason: 'profile', session: byProfile };
167
- const byInstanceId = sessions.filter((item) => String(item?.instanceId || '').trim() === value);
168
- if (byInstanceId.length > 1) {
169
- throw new Error(`Ambiguous instance id target: ${value}`);
170
- }
171
- if (byInstanceId.length === 1) {
172
- return { profileId: byInstanceId[0].profileId, reason: 'instanceId', session: byInstanceId[0] };
173
- }
174
- const normalizedAlias = normalizeAlias(value);
175
- const byAlias = sessions.filter((item) => normalizeAlias(item?.alias) === normalizedAlias && isAliasProtectedStatus(item?.status));
176
- if (byAlias.length > 1) {
177
- throw new Error(`Ambiguous alias target: ${value}`);
178
- }
179
- if (byAlias.length === 1) {
180
- return { profileId: byAlias[0].profileId, reason: 'alias', session: byAlias[0] };
181
- }
182
- return null;
183
- }
184
-
185
- export function isSessionAliasTaken(alias, exceptProfileId = '') {
186
- const target = normalizeAlias(alias);
187
- if (!target) return false;
188
- const except = String(exceptProfileId || '').trim();
189
- return listRegisteredSessions().some((item) => {
190
- if (!item) return false;
191
- if (except && String(item.profileId || '').trim() === except) return false;
192
- if (!isAliasProtectedStatus(item.status)) return false;
193
- return normalizeAlias(item.alias) === target;
194
- });
195
- }
196
-
197
- export function touchSessionActivity(profileId, updates = {}) {
198
- const id = String(profileId || '').trim();
199
- if (!id) return null;
200
- const existing = getSessionInfo(id);
201
- if (!existing) return null;
202
- return updateSession(id, {
203
- ...updates,
204
- touchActivity: true,
205
- });
206
- }
207
-
208
- export function markSessionReconnecting(profileId) {
209
- return updateSession(profileId, { status: 'reconnecting', reconnectAttempt: Date.now() });
210
- }
211
-
212
- export function markSessionActive(profileId, updates = {}) {
213
- return updateSession(profileId, { status: 'active', ...updates });
214
-
215
- }
216
-
217
- export function markSessionClosed(profileId) {
218
- const sessionFile = getSessionFile(profileId);
219
- if (fs.existsSync(sessionFile)) {
220
- try {
221
- const existing = JSON.parse(fs.readFileSync(sessionFile, 'utf-8'));
222
- existing.status = 'closed';
223
- existing.closedAt = Date.now();
224
- fs.writeFileSync(sessionFile, JSON.stringify(existing, null, 2));
225
- } catch {
226
- // Best-effort close: continue with removal even for corrupted metadata.
227
- }
228
- }
229
- return unregisterSession(profileId);
230
- }
231
-
232
- export function cleanupStaleSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
233
- ensureSessionDir();
234
- const files = fs.readdirSync(SESSION_DIR);
235
- const now = Date.now();
236
- let cleaned = 0;
237
-
238
- for (const file of files) {
239
- if (!file.endsWith('.json')) continue;
240
-
241
- const sessionFile = path.join(SESSION_DIR, file);
242
- try {
243
- const content = fs.readFileSync(sessionFile, 'utf-8');
244
- const session = JSON.parse(content);
245
-
246
- // Clean if session is too old or marked as closed
247
- if (session.status === 'closed' || (session.lastSeen && (now - session.lastSeen) > maxAgeMs)) {
248
- fs.unlinkSync(sessionFile);
249
- cleaned++;
250
- }
251
- } catch {
252
- // Remove corrupted session files
253
- try {
254
- fs.unlinkSync(sessionFile);
255
- cleaned++;
256
- } catch {}
257
- }
258
- }
259
-
260
- return cleaned;
261
- }
262
-
263
- export async function recoverSession(profileId, checkHealthFn) {
264
- const info = getSessionInfo(profileId);
265
- if (!info) return null;
266
-
267
- // Check if browser service is still running
268
- const isHealthy = await checkHealthFn();
269
-
270
- if (!isHealthy) {
271
- // Service is down, mark as needing recovery
272
- markSessionReconnecting(profileId);
273
- return { status: 'needs_recovery', info };
274
- }
275
-
276
- // Service is up, check if session is still active
277
- markSessionActive(profileId, { recoveredAt: Date.now() });
278
- return { status: 'recovered', info };
279
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Session registry - persistent session state management
4
+ * Stores session metadata locally for recovery/reconnection
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import { CONFIG_DIR } from '../utils/config.mjs';
10
+
11
+ const SESSION_DIR = path.join(CONFIG_DIR, 'sessions');
12
+
13
+ function ensureSessionDir() {
14
+ if (!fs.existsSync(SESSION_DIR)) {
15
+ fs.mkdirSync(SESSION_DIR, { recursive: true });
16
+ }
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 isAliasProtectedStatus(status) {
29
+ const normalized = String(status || '').trim().toLowerCase();
30
+ return normalized === 'active' || normalized === 'reconnecting';
31
+ }
32
+
33
+ function normalizeTimeoutMs(value) {
34
+ const ms = Number(value);
35
+ if (!Number.isFinite(ms) || ms < 0) return null;
36
+ return Math.floor(ms);
37
+ }
38
+
39
+ function generateInstanceId() {
40
+ return `inst_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
41
+ }
42
+
43
+ export function getSessionFile(profileId) {
44
+ return path.join(SESSION_DIR, `${profileId}.json`);
45
+ }
46
+
47
+ export function registerSession(profileId, sessionInfo = {}) {
48
+ ensureSessionDir();
49
+ const sessionFile = getSessionFile(profileId);
50
+ const now = Date.now();
51
+ const alias = normalizeAlias(sessionInfo.alias);
52
+ const idleTimeoutMs = normalizeTimeoutMs(sessionInfo.idleTimeoutMs);
53
+ const instanceId = String(sessionInfo.instanceId || sessionInfo.sessionId || generateInstanceId()).trim();
54
+
55
+ const sessionData = {
56
+ profileId,
57
+ pid: process.pid,
58
+ instanceId,
59
+ alias,
60
+ startTime: now,
61
+ lastSeen: now,
62
+ lastActivityAt: now,
63
+ status: 'active',
64
+ ...sessionInfo,
65
+ instanceId,
66
+ alias,
67
+ idleTimeoutMs,
68
+ };
69
+
70
+ fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
71
+ return sessionData;
72
+ }
73
+
74
+ export function updateSession(profileId, updates = {}) {
75
+ const sessionFile = getSessionFile(profileId);
76
+ if (!fs.existsSync(sessionFile)) {
77
+ return registerSession(profileId, updates);
78
+ }
79
+
80
+ try {
81
+ const existing = JSON.parse(fs.readFileSync(sessionFile, 'utf-8'));
82
+ const now = Date.now();
83
+ const mergedAlias = Object.prototype.hasOwnProperty.call(updates, 'alias')
84
+ ? normalizeAlias(updates.alias)
85
+ : normalizeAlias(existing.alias);
86
+ const mergedIdleTimeoutMs = Object.prototype.hasOwnProperty.call(updates, 'idleTimeoutMs')
87
+ ? normalizeTimeoutMs(updates.idleTimeoutMs)
88
+ : normalizeTimeoutMs(existing.idleTimeoutMs);
89
+ const touchActivity = updates.touchActivity === true;
90
+ const nextActivityAt = touchActivity
91
+ ? now
92
+ : (Object.prototype.hasOwnProperty.call(updates, 'lastActivityAt')
93
+ ? Number(updates.lastActivityAt) || now
94
+ : Number(existing.lastActivityAt) || now);
95
+ const updated = {
96
+ ...existing,
97
+ ...updates,
98
+ instanceId: String(updates.instanceId || existing.instanceId || updates.sessionId || existing.sessionId || generateInstanceId()).trim(),
99
+ alias: mergedAlias,
100
+ idleTimeoutMs: mergedIdleTimeoutMs,
101
+ lastSeen: now,
102
+ lastActivityAt: nextActivityAt,
103
+ profileId,
104
+ };
105
+ delete updated.touchActivity;
106
+ fs.writeFileSync(sessionFile, JSON.stringify(updated, null, 2));
107
+ return updated;
108
+ } catch {
109
+ return registerSession(profileId, updates);
110
+ }
111
+ }
112
+
113
+ export function getSessionInfo(profileId) {
114
+ const sessionFile = getSessionFile(profileId);
115
+ if (!fs.existsSync(sessionFile)) return null;
116
+
117
+ try {
118
+ const content = fs.readFileSync(sessionFile, 'utf-8');
119
+ return JSON.parse(content);
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ export function unregisterSession(profileId) {
126
+ const sessionFile = getSessionFile(profileId);
127
+ if (fs.existsSync(sessionFile)) {
128
+ fs.unlinkSync(sessionFile);
129
+ return true;
130
+ }
131
+ return false;
132
+ }
133
+
134
+ export function listRegisteredSessions() {
135
+ ensureSessionDir();
136
+ const files = fs.readdirSync(SESSION_DIR);
137
+ const sessions = [];
138
+
139
+ for (const file of files) {
140
+ if (!file.endsWith('.json')) continue;
141
+ const profileId = file.replace('.json', '');
142
+ const info = getSessionInfo(profileId);
143
+ if (info) sessions.push(info);
144
+ }
145
+
146
+ return sessions;
147
+ }
148
+
149
+ export function findSessionByAlias(alias) {
150
+ const target = normalizeAlias(alias);
151
+ if (!target) return null;
152
+ return listRegisteredSessions().find((item) => normalizeAlias(item?.alias) === target) || null;
153
+ }
154
+
155
+ export function findSessionByInstanceId(instanceId) {
156
+ const target = String(instanceId || '').trim();
157
+ if (!target) return null;
158
+ return listRegisteredSessions().find((item) => String(item?.instanceId || '').trim() === target) || null;
159
+ }
160
+
161
+ export function resolveSessionTarget(target) {
162
+ const value = String(target || '').trim();
163
+ if (!value) return null;
164
+ const sessions = listRegisteredSessions();
165
+ const byProfile = sessions.find((item) => String(item?.profileId || '').trim() === value);
166
+ if (byProfile) return { profileId: byProfile.profileId, reason: 'profile', session: byProfile };
167
+ const byInstanceId = sessions.filter((item) => String(item?.instanceId || '').trim() === value);
168
+ if (byInstanceId.length > 1) {
169
+ throw new Error(`Ambiguous instance id target: ${value}`);
170
+ }
171
+ if (byInstanceId.length === 1) {
172
+ return { profileId: byInstanceId[0].profileId, reason: 'instanceId', session: byInstanceId[0] };
173
+ }
174
+ const normalizedAlias = normalizeAlias(value);
175
+ const byAlias = sessions.filter((item) => normalizeAlias(item?.alias) === normalizedAlias && isAliasProtectedStatus(item?.status));
176
+ if (byAlias.length > 1) {
177
+ throw new Error(`Ambiguous alias target: ${value}`);
178
+ }
179
+ if (byAlias.length === 1) {
180
+ return { profileId: byAlias[0].profileId, reason: 'alias', session: byAlias[0] };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ export function isSessionAliasTaken(alias, exceptProfileId = '') {
186
+ const target = normalizeAlias(alias);
187
+ if (!target) return false;
188
+ const except = String(exceptProfileId || '').trim();
189
+ return listRegisteredSessions().some((item) => {
190
+ if (!item) return false;
191
+ if (except && String(item.profileId || '').trim() === except) return false;
192
+ if (!isAliasProtectedStatus(item.status)) return false;
193
+ return normalizeAlias(item.alias) === target;
194
+ });
195
+ }
196
+
197
+ export function touchSessionActivity(profileId, updates = {}) {
198
+ const id = String(profileId || '').trim();
199
+ if (!id) return null;
200
+ const existing = getSessionInfo(id);
201
+ if (!existing) return null;
202
+ return updateSession(id, {
203
+ ...updates,
204
+ touchActivity: true,
205
+ });
206
+ }
207
+
208
+ export function markSessionReconnecting(profileId) {
209
+ return updateSession(profileId, { status: 'reconnecting', reconnectAttempt: Date.now() });
210
+ }
211
+
212
+ export function markSessionActive(profileId, updates = {}) {
213
+ return updateSession(profileId, { status: 'active', ...updates });
214
+
215
+ }
216
+
217
+ export function markSessionClosed(profileId) {
218
+ const sessionFile = getSessionFile(profileId);
219
+ if (fs.existsSync(sessionFile)) {
220
+ try {
221
+ const existing = JSON.parse(fs.readFileSync(sessionFile, 'utf-8'));
222
+ existing.status = 'closed';
223
+ existing.closedAt = Date.now();
224
+ fs.writeFileSync(sessionFile, JSON.stringify(existing, null, 2));
225
+ } catch {
226
+ // Best-effort close: continue with removal even for corrupted metadata.
227
+ }
228
+ }
229
+ return unregisterSession(profileId);
230
+ }
231
+
232
+ export function cleanupStaleSessions(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
233
+ ensureSessionDir();
234
+ const files = fs.readdirSync(SESSION_DIR);
235
+ const now = Date.now();
236
+ let cleaned = 0;
237
+
238
+ for (const file of files) {
239
+ if (!file.endsWith('.json')) continue;
240
+
241
+ const sessionFile = path.join(SESSION_DIR, file);
242
+ try {
243
+ const content = fs.readFileSync(sessionFile, 'utf-8');
244
+ const session = JSON.parse(content);
245
+
246
+ // Clean if session is too old or marked as closed
247
+ if (session.status === 'closed' || (session.lastSeen && (now - session.lastSeen) > maxAgeMs)) {
248
+ fs.unlinkSync(sessionFile);
249
+ cleaned++;
250
+ }
251
+ } catch {
252
+ // Remove corrupted session files
253
+ try {
254
+ fs.unlinkSync(sessionFile);
255
+ cleaned++;
256
+ } catch {}
257
+ }
258
+ }
259
+
260
+ return cleaned;
261
+ }
262
+
263
+ export async function recoverSession(profileId, checkHealthFn) {
264
+ const info = getSessionInfo(profileId);
265
+ if (!info) return null;
266
+
267
+ // Check if browser service is still running
268
+ const isHealthy = await checkHealthFn();
269
+
270
+ if (!isHealthy) {
271
+ // Service is down, mark as needing recovery
272
+ markSessionReconnecting(profileId);
273
+ return { status: 'needs_recovery', info };
274
+ }
275
+
276
+ // Service is up, check if session is still active
277
+ markSessionActive(profileId, { recoveredAt: Date.now() });
278
+ return { status: 'recovered', info };
279
+ }