@nexum-hub/browser 0.0.0-stage → 0.0.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.
- package/README.md +22 -2
- package/browser-extension/assets.js +654 -0
- package/browser-extension/build.mjs +111 -0
- package/browser-extension/clipboard.js +397 -0
- package/browser-extension/connection.js +880 -0
- package/browser-extension/dist/development/assets.js +654 -0
- package/browser-extension/dist/development/clipboard.js +397 -0
- package/browser-extension/dist/development/connection.js +880 -0
- package/browser-extension/dist/development/errors.js +106 -0
- package/browser-extension/dist/development/evaluate.js +160 -0
- package/browser-extension/dist/development/frames.js +256 -0
- package/browser-extension/dist/development/keyboard.js +167 -0
- package/browser-extension/dist/development/manifest.json +35 -0
- package/browser-extension/dist/development/native-node.js +85 -0
- package/browser-extension/dist/development/page-data.js +497 -0
- package/browser-extension/dist/development/page.js +772 -0
- package/browser-extension/dist/development/profile.js +2 -0
- package/browser-extension/dist/development/router.js +5961 -0
- package/browser-extension/dist/development/site-source.js +149 -0
- package/browser-extension/dist/development/transport.js +405 -0
- package/browser-extension/dist/development/visual.js +976 -0
- package/browser-extension/dist/development/worker.js +24 -0
- package/browser-extension/dist/production/assets.js +654 -0
- package/browser-extension/dist/production/clipboard.js +397 -0
- package/browser-extension/dist/production/connection.js +880 -0
- package/browser-extension/dist/production/errors.js +106 -0
- package/browser-extension/dist/production/evaluate.js +160 -0
- package/browser-extension/dist/production/frames.js +256 -0
- package/browser-extension/dist/production/keyboard.js +167 -0
- package/browser-extension/dist/production/manifest.json +35 -0
- package/browser-extension/dist/production/native-node.js +85 -0
- package/browser-extension/dist/production/page-data.js +497 -0
- package/browser-extension/dist/production/page.js +772 -0
- package/browser-extension/dist/production/profile.js +2 -0
- package/browser-extension/dist/production/router.js +5961 -0
- package/browser-extension/dist/production/site-source.js +149 -0
- package/browser-extension/dist/production/transport.js +405 -0
- package/browser-extension/dist/production/visual.js +976 -0
- package/browser-extension/dist/production/worker.js +24 -0
- package/browser-extension/errors.js +106 -0
- package/browser-extension/evaluate.js +160 -0
- package/browser-extension/frames.js +256 -0
- package/browser-extension/keyboard.js +167 -0
- package/browser-extension/native-node.js +85 -0
- package/browser-extension/page-data.js +497 -0
- package/browser-extension/page.js +772 -0
- package/browser-extension/release-info.json +21 -0
- package/browser-extension/route-manifest.json +807 -0
- package/browser-extension/router.js +5961 -0
- package/browser-extension/site-source.js +149 -0
- package/browser-extension/transport.js +405 -0
- package/browser-extension/visual.js +976 -0
- package/browser-extension/worker.js +24 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +894 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/routes.d.ts +6 -0
- package/dist/client/routes.js +777 -0
- package/dist/client/routes.js.map +1 -0
- package/dist/client/serialize.d.ts +16 -0
- package/dist/client/serialize.js +355 -0
- package/dist/client/serialize.js.map +1 -0
- package/dist/client/types.d.ts +1342 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/extension/artifacts.d.ts +60 -0
- package/dist/extension/artifacts.js +493 -0
- package/dist/extension/artifacts.js.map +1 -0
- package/dist/extension/assets.d.ts +10 -0
- package/dist/extension/assets.js +90 -0
- package/dist/extension/assets.js.map +1 -0
- package/dist/extension/batch.d.ts +6 -0
- package/dist/extension/batch.js +138 -0
- package/dist/extension/batch.js.map +1 -0
- package/dist/extension/files.d.ts +16 -0
- package/dist/extension/files.js +594 -0
- package/dist/extension/files.js.map +1 -0
- package/dist/extension/index.d.ts +3 -0
- package/dist/extension/index.js +623 -0
- package/dist/extension/index.js.map +1 -0
- package/dist/extension/protocol.d.ts +81 -0
- package/dist/extension/protocol.js +475 -0
- package/dist/extension/protocol.js.map +1 -0
- package/dist/extension/scope.d.ts +55 -0
- package/dist/extension/scope.js +563 -0
- package/dist/extension/scope.js.map +1 -0
- package/dist/extension/service.d.ts +113 -0
- package/dist/extension/service.js +905 -0
- package/dist/extension/service.js.map +1 -0
- package/docs/README.md +10 -0
- package/docs/api.md +1375 -0
- package/docs/connection.md +9 -0
- package/docs/lifecycle.md +17 -0
- package/docs/usage.md +75 -0
- package/implementation.json +2352 -0
- package/instructions/README.md +8 -0
- package/package.json +80 -4
- package/scripts/discover.js +12 -0
- package/scripts/screenshot.js +9 -0
- package/skills/browser-control/SKILL.md +12 -0
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
import { EventEmitter, once } from "node:events";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { readFile, writeFile, rename, mkdir, lstat, unlink, } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { setImmediate as yieldTurn, setTimeout as delay, } from "node:timers/promises";
|
|
7
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
8
|
+
import { BinaryInbox, check, control, data, failure, frames, identifier, limits, pack, parseControl, record, socketPath, unpack, } from "./protocol.js";
|
|
9
|
+
/** Cold, package-owned native listener. Only explicit start performs filesystem/network I/O. */
|
|
10
|
+
export class BrowserService extends EventEmitter {
|
|
11
|
+
options;
|
|
12
|
+
bootId = randomUUID();
|
|
13
|
+
closed;
|
|
14
|
+
#closed = Promise.withResolvers();
|
|
15
|
+
#stop = new AbortController();
|
|
16
|
+
#server;
|
|
17
|
+
#wss;
|
|
18
|
+
#start;
|
|
19
|
+
#disposing;
|
|
20
|
+
#started = false;
|
|
21
|
+
#stopping = false;
|
|
22
|
+
#timer;
|
|
23
|
+
#wakeTimer;
|
|
24
|
+
#port;
|
|
25
|
+
#sockets = new Set();
|
|
26
|
+
#peers = new Map();
|
|
27
|
+
#profiles = new Map();
|
|
28
|
+
#generations = new Map();
|
|
29
|
+
#identities = new Map();
|
|
30
|
+
#claims = new Map();
|
|
31
|
+
#leases = new Map();
|
|
32
|
+
#tasks = new Set();
|
|
33
|
+
#persist = Promise.resolve();
|
|
34
|
+
constructor(options) {
|
|
35
|
+
super();
|
|
36
|
+
this.options = options;
|
|
37
|
+
this.setMaxListeners(0);
|
|
38
|
+
this.closed = this.#closed.promise;
|
|
39
|
+
this.#port = options.port;
|
|
40
|
+
check(["production", "development"].includes(options.profile) &&
|
|
41
|
+
Number.isInteger(options.port) &&
|
|
42
|
+
options.port >= 0 &&
|
|
43
|
+
options.port <= 65535 &&
|
|
44
|
+
path.isAbsolute(options.work) &&
|
|
45
|
+
/^[a-p]{32}$/.test(options.extensionId) &&
|
|
46
|
+
identifier(options.extensionVersion), "INVALID_ARGUMENT", "Browser service requires one explicit profile, port and matching extension identity.");
|
|
47
|
+
}
|
|
48
|
+
get address() {
|
|
49
|
+
return this.#started && !this.#stopping
|
|
50
|
+
? { host: "127.0.0.1", port: this.#port, path: socketPath }
|
|
51
|
+
: null;
|
|
52
|
+
}
|
|
53
|
+
#track(task) {
|
|
54
|
+
this.#tasks.add(task);
|
|
55
|
+
void task.finally(() => this.#tasks.delete(task)).catch(() => { });
|
|
56
|
+
return task;
|
|
57
|
+
}
|
|
58
|
+
#wakeActiveActions() {
|
|
59
|
+
if (this.#wakeTimer || this.#stopping)
|
|
60
|
+
return;
|
|
61
|
+
// Some MV3 workers defer their own timers while a controlled page is
|
|
62
|
+
// active. Existing bound heartbeat messages provide a Node-timed wakeup;
|
|
63
|
+
// they neither repeat an action nor change its deadline.
|
|
64
|
+
this.#wakeTimer = setInterval(() => {
|
|
65
|
+
for (const peer of this.#peers.values()) {
|
|
66
|
+
if (!peer.pending.size || peer.socket.readyState !== WebSocket.OPEN)
|
|
67
|
+
continue;
|
|
68
|
+
try {
|
|
69
|
+
void this.#send(peer, { v: 1, type: "ping", at: Date.now() }).catch(() => { });
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// The peer may close or its existing write budget may be full.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
this.#stopWakeIfIdle();
|
|
76
|
+
}, 100);
|
|
77
|
+
this.#wakeTimer.unref();
|
|
78
|
+
}
|
|
79
|
+
#stopWakeIfIdle() {
|
|
80
|
+
if ([...this.#peers.values()].some((peer) => peer.pending.size))
|
|
81
|
+
return;
|
|
82
|
+
if (this.#wakeTimer)
|
|
83
|
+
clearInterval(this.#wakeTimer);
|
|
84
|
+
this.#wakeTimer = undefined;
|
|
85
|
+
}
|
|
86
|
+
start(signal) {
|
|
87
|
+
check(!this.#stopping, "EXTENSION_OFFLINE", "The browser service is stopping.");
|
|
88
|
+
if (this.#start)
|
|
89
|
+
return this.#start;
|
|
90
|
+
const task = this.#startNative(signal);
|
|
91
|
+
this.#start = task;
|
|
92
|
+
void task.catch(() => { });
|
|
93
|
+
return task;
|
|
94
|
+
}
|
|
95
|
+
async #startNative(signal) {
|
|
96
|
+
const combined = AbortSignal.any([signal, this.#stop.signal]);
|
|
97
|
+
combined.throwIfAborted();
|
|
98
|
+
const directory = path.join(this.options.work, ".nexum-browser");
|
|
99
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
100
|
+
check(!(await lstat(directory)).isSymbolicLink(), "PERMISSION_DENIED", "Browser state cannot use a symbolic-link directory.");
|
|
101
|
+
try {
|
|
102
|
+
const body = await readFile(path.join(directory, "profiles.json"));
|
|
103
|
+
check(body.length <= 1024 * 1024, "OUTPUT_TOO_LARGE", "The browser profile map is too large.");
|
|
104
|
+
const value = JSON.parse(body.toString("utf8"));
|
|
105
|
+
check(value && typeof value === "object" && !Array.isArray(value), "PROTOCOL_MISMATCH", "The stored browser profile map is invalid.");
|
|
106
|
+
for (const [key, id] of Object.entries(value)) {
|
|
107
|
+
check(identifier(key) && identifier(id) && this.#identities.size < 1000, "PROTOCOL_MISMATCH", "The stored browser profile map is invalid.");
|
|
108
|
+
this.#identities.set(key, id);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch (cause) {
|
|
112
|
+
if (cause.code !== "ENOENT")
|
|
113
|
+
throw cause;
|
|
114
|
+
}
|
|
115
|
+
combined.throwIfAborted();
|
|
116
|
+
const server = createServer({ maxHeaderSize: 16384 }, (_request, response) => {
|
|
117
|
+
response.writeHead(404);
|
|
118
|
+
response.end();
|
|
119
|
+
});
|
|
120
|
+
this.#server = server;
|
|
121
|
+
server.maxHeadersCount = 64;
|
|
122
|
+
const wss = new WebSocketServer({
|
|
123
|
+
noServer: true,
|
|
124
|
+
perMessageDeflate: false,
|
|
125
|
+
maxPayload: limits.controlBytes,
|
|
126
|
+
maxFragments: 32,
|
|
127
|
+
maxBufferedChunks: 256,
|
|
128
|
+
});
|
|
129
|
+
this.#wss = wss;
|
|
130
|
+
server.on("upgrade", (request, socket, head) => {
|
|
131
|
+
const invalid = this.#stopping ||
|
|
132
|
+
!["127.0.0.1", "::ffff:127.0.0.1"].includes(socket.remoteAddress ?? "") ||
|
|
133
|
+
request.method !== "GET" ||
|
|
134
|
+
request.url !== socketPath ||
|
|
135
|
+
request.headers.host !== `127.0.0.1:${this.#port}` ||
|
|
136
|
+
request.headers.origin !==
|
|
137
|
+
`chrome-extension://${this.options.extensionId}` ||
|
|
138
|
+
Object.keys(request.headers).some((name) => name === "forwarded" ||
|
|
139
|
+
name.startsWith("x-forwarded-") ||
|
|
140
|
+
name === "x-original-url") ||
|
|
141
|
+
this.#sockets.size >= 64;
|
|
142
|
+
if (invalid) {
|
|
143
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
wss.handleUpgrade(request, socket, head, (ws) => this.#connection(ws));
|
|
147
|
+
});
|
|
148
|
+
server.on("error", () => { });
|
|
149
|
+
try {
|
|
150
|
+
server.listen(this.options.port, "127.0.0.1");
|
|
151
|
+
await once(server, "listening", { signal: combined });
|
|
152
|
+
}
|
|
153
|
+
catch (cause) {
|
|
154
|
+
throw cause.code === "EADDRINUSE"
|
|
155
|
+
? failure("PORT_IN_USE", "The configured browser extension port is already in use.")
|
|
156
|
+
: cause;
|
|
157
|
+
}
|
|
158
|
+
const address = server.address();
|
|
159
|
+
check(address && typeof address === "object", "EXTENSION_OFFLINE", "Browser service did not become ready.");
|
|
160
|
+
this.#port = address.port;
|
|
161
|
+
combined.throwIfAborted();
|
|
162
|
+
this.#started = true;
|
|
163
|
+
this.#timer = setInterval(() => {
|
|
164
|
+
const now = Date.now();
|
|
165
|
+
for (const socket of this.#sockets) {
|
|
166
|
+
const peer = [...this.#peers.values()].find((value) => value.socket === socket);
|
|
167
|
+
if (peer && now - peer.lastSeen > 60000) {
|
|
168
|
+
socket.terminate();
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (peer && socket.readyState === WebSocket.OPEN)
|
|
172
|
+
socket.send(control({
|
|
173
|
+
v: 1,
|
|
174
|
+
type: "ping",
|
|
175
|
+
at: now,
|
|
176
|
+
connectionId: peer.connectionId,
|
|
177
|
+
generation: peer.generation,
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
}, 20000);
|
|
181
|
+
}
|
|
182
|
+
#connection(socket) {
|
|
183
|
+
this.#sockets.add(socket);
|
|
184
|
+
let peer;
|
|
185
|
+
const handshake = setTimeout(() => {
|
|
186
|
+
if (!peer)
|
|
187
|
+
socket.terminate();
|
|
188
|
+
}, 5000);
|
|
189
|
+
socket.on("error", () => { });
|
|
190
|
+
socket.on("message", (raw, binary) => {
|
|
191
|
+
const task = (async () => {
|
|
192
|
+
const body = Buffer.isBuffer(raw)
|
|
193
|
+
? raw
|
|
194
|
+
: Array.isArray(raw)
|
|
195
|
+
? Buffer.concat(raw)
|
|
196
|
+
: Buffer.from(raw);
|
|
197
|
+
if (binary) {
|
|
198
|
+
check(peer && this.#peers.get(peer.id) === peer, "PROTOCOL_MISMATCH", "Binary data arrived before a current handshake.");
|
|
199
|
+
peer.inbox.push(body);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const message = parseControl(body);
|
|
203
|
+
if (!peer) {
|
|
204
|
+
check(message.type === "hello", "PROTOCOL_MISMATCH", "Browser hello must be the first message.");
|
|
205
|
+
peer = await this.#hello(socket, message);
|
|
206
|
+
clearTimeout(handshake);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
check(this.#peers.get(peer.id) === peer &&
|
|
210
|
+
message.generation === peer.generation &&
|
|
211
|
+
message.connectionId === peer.connectionId, "PROTOCOL_MISMATCH", "Message belongs to a stale browser connection.");
|
|
212
|
+
peer.lastSeen = Date.now();
|
|
213
|
+
this.#message(peer, message);
|
|
214
|
+
})();
|
|
215
|
+
void this.#track(task).catch((cause) => {
|
|
216
|
+
this.#diagnose("protocol_rejected", peer, identifier(cause?.code)
|
|
217
|
+
? cause.code
|
|
218
|
+
: "PROTOCOL_MISMATCH", null);
|
|
219
|
+
if (socket.readyState === WebSocket.OPEN)
|
|
220
|
+
socket.send(control({
|
|
221
|
+
v: 1,
|
|
222
|
+
type: "error",
|
|
223
|
+
code: identifier(cause?.code)
|
|
224
|
+
? cause.code
|
|
225
|
+
: "PROTOCOL_MISMATCH",
|
|
226
|
+
message: "The browser connection could not accept this message.",
|
|
227
|
+
}), () => socket.close(1008, "Invalid browser protocol"));
|
|
228
|
+
else
|
|
229
|
+
socket.terminate();
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
socket.once("close", (code) => {
|
|
233
|
+
clearTimeout(handshake);
|
|
234
|
+
this.#sockets.delete(socket);
|
|
235
|
+
this.#diagnose("closed", peer, null, code);
|
|
236
|
+
if (peer)
|
|
237
|
+
this.#offline(peer);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
#diagnose(event, peer, code, closeCode) {
|
|
241
|
+
const diagnostic = {
|
|
242
|
+
event,
|
|
243
|
+
browserId: peer?.id ?? null,
|
|
244
|
+
generation: peer?.generation ?? null,
|
|
245
|
+
code,
|
|
246
|
+
closeCode,
|
|
247
|
+
operationIds: [...(peer?.pending.values() ?? [])]
|
|
248
|
+
.slice(0, 8)
|
|
249
|
+
.map((pending) => pending.operationId),
|
|
250
|
+
};
|
|
251
|
+
this.emit("diagnostic", diagnostic);
|
|
252
|
+
}
|
|
253
|
+
async #hello(socket, value) {
|
|
254
|
+
check(value.profile === this.options.profile &&
|
|
255
|
+
value.extensionId === this.options.extensionId &&
|
|
256
|
+
value.extensionVersion === this.options.extensionVersion &&
|
|
257
|
+
value.protocol &&
|
|
258
|
+
typeof value.protocol === "object" &&
|
|
259
|
+
value.protocol.min === 1 &&
|
|
260
|
+
value.protocol.max === 1 &&
|
|
261
|
+
identifier(value.browserProfileId) &&
|
|
262
|
+
identifier(value.browserSessionId) &&
|
|
263
|
+
identifier(value.clientInstanceId) &&
|
|
264
|
+
Number.isSafeInteger(value.attemptSequence) &&
|
|
265
|
+
Number(value.attemptSequence) > 0, "PROFILE_MISMATCH", "The browser hello does not match this profile and plugin build.");
|
|
266
|
+
const profileId = value.browserProfileId, claim = {};
|
|
267
|
+
let old = this.#profiles.get(profileId);
|
|
268
|
+
if (old && Date.now() - old.lastSeen > 60000) {
|
|
269
|
+
this.#offline(old);
|
|
270
|
+
old.socket.terminate();
|
|
271
|
+
old = undefined;
|
|
272
|
+
}
|
|
273
|
+
check(!this.#claims.has(profileId), "PROFILE_CONFLICT", "Another handshake already owns this browser profile.");
|
|
274
|
+
check(!old ||
|
|
275
|
+
(old.clientInstanceId === value.clientInstanceId &&
|
|
276
|
+
Number(value.attemptSequence) > old.attemptSequence), "PROFILE_CONFLICT", "Another healthy browser worker owns this profile identity.");
|
|
277
|
+
this.#claims.set(profileId, claim);
|
|
278
|
+
try {
|
|
279
|
+
let id = this.#identities.get(profileId);
|
|
280
|
+
if (!id) {
|
|
281
|
+
const candidate = randomUUID(), directory = path.join(this.options.work, ".nexum-browser");
|
|
282
|
+
// Build from the last durable map inside the serial write, then publish it.
|
|
283
|
+
// A failed write never installs a nondurable identity in the live map.
|
|
284
|
+
const persist = this.#persist
|
|
285
|
+
.catch(() => { })
|
|
286
|
+
.then(async () => {
|
|
287
|
+
check(this.#identities.size < 1000, "QUEUE_FULL", "The browser profile map is full.");
|
|
288
|
+
const next = new Map(this.#identities);
|
|
289
|
+
next.set(profileId, candidate);
|
|
290
|
+
const temporary = path.join(directory, `.profiles-${randomUUID()}.tmp`);
|
|
291
|
+
try {
|
|
292
|
+
await writeFile(temporary, JSON.stringify(Object.fromEntries(next)), { flag: "wx", mode: 0o600 });
|
|
293
|
+
await rename(temporary, path.join(directory, "profiles.json"));
|
|
294
|
+
this.#identities = next;
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
await unlink(temporary).catch((cause) => {
|
|
298
|
+
if (cause.code !== "ENOENT")
|
|
299
|
+
throw cause;
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
this.#persist = persist;
|
|
304
|
+
await persist;
|
|
305
|
+
id = candidate;
|
|
306
|
+
}
|
|
307
|
+
check(!this.#stopping &&
|
|
308
|
+
socket.readyState === WebSocket.OPEN &&
|
|
309
|
+
this.#claims.get(profileId) === claim, "EXTENSION_OFFLINE", "The browser handshake ended before acceptance.");
|
|
310
|
+
if (old) {
|
|
311
|
+
this.#offline(old);
|
|
312
|
+
old.socket.close(1000, "Newer connection attempt");
|
|
313
|
+
}
|
|
314
|
+
const generation = (this.#generations.get(id) ?? 0) + 1;
|
|
315
|
+
this.#generations.set(id, generation);
|
|
316
|
+
const metadata = data(value.metadata ?? {}, 16384);
|
|
317
|
+
const info = {
|
|
318
|
+
id,
|
|
319
|
+
name: typeof metadata.name === "string" ? metadata.name : "Chromium",
|
|
320
|
+
type: "extension",
|
|
321
|
+
status: "online",
|
|
322
|
+
generation,
|
|
323
|
+
bootId: this.bootId,
|
|
324
|
+
browserSessionId: value.browserSessionId,
|
|
325
|
+
metadata: {
|
|
326
|
+
extensionVersion: this.options.extensionVersion,
|
|
327
|
+
versionSource: ["clientHints", "userAgent", "unknown"].includes(String(metadata.versionSource))
|
|
328
|
+
? metadata.versionSource
|
|
329
|
+
: "unknown",
|
|
330
|
+
...(typeof metadata.browserVersion === "string"
|
|
331
|
+
? { browserVersion: metadata.browserVersion }
|
|
332
|
+
: {}),
|
|
333
|
+
},
|
|
334
|
+
...(typeof metadata.profileName === "string"
|
|
335
|
+
? { profileName: metadata.profileName }
|
|
336
|
+
: {}),
|
|
337
|
+
...(typeof metadata.family === "string"
|
|
338
|
+
? { family: metadata.family }
|
|
339
|
+
: {}),
|
|
340
|
+
};
|
|
341
|
+
const peer = {
|
|
342
|
+
id,
|
|
343
|
+
generation,
|
|
344
|
+
browserSessionId: value.browserSessionId,
|
|
345
|
+
clientInstanceId: value.clientInstanceId,
|
|
346
|
+
attemptSequence: Number(value.attemptSequence),
|
|
347
|
+
profileId,
|
|
348
|
+
socket,
|
|
349
|
+
connectionId: randomUUID(),
|
|
350
|
+
inbox: new BinaryInbox(),
|
|
351
|
+
info,
|
|
352
|
+
tabs: new Map(),
|
|
353
|
+
capabilities: [],
|
|
354
|
+
lastSeen: Date.now(),
|
|
355
|
+
sequence: 0,
|
|
356
|
+
snapshots: new Map(),
|
|
357
|
+
tabsReady: false,
|
|
358
|
+
capabilitiesReady: false,
|
|
359
|
+
pending: new Map(),
|
|
360
|
+
completed: new Map(),
|
|
361
|
+
};
|
|
362
|
+
this.#peers.set(id, peer);
|
|
363
|
+
this.#profiles.set(profileId, peer);
|
|
364
|
+
for (const [leaseId, lease] of this.#leases)
|
|
365
|
+
if (lease.peer.id === id &&
|
|
366
|
+
lease.peer.browserSessionId !== peer.browserSessionId) {
|
|
367
|
+
lease.onClosed?.();
|
|
368
|
+
this.#leases.delete(leaseId);
|
|
369
|
+
}
|
|
370
|
+
await this.#send(peer, {
|
|
371
|
+
v: 1,
|
|
372
|
+
type: "ready",
|
|
373
|
+
profile: this.options.profile,
|
|
374
|
+
bootId: this.bootId,
|
|
375
|
+
connectionId: peer.connectionId,
|
|
376
|
+
browserId: id,
|
|
377
|
+
browserSessionId: peer.browserSessionId,
|
|
378
|
+
generation,
|
|
379
|
+
protocolVersion: 1,
|
|
380
|
+
limits,
|
|
381
|
+
});
|
|
382
|
+
this.emit("online", info);
|
|
383
|
+
return peer;
|
|
384
|
+
}
|
|
385
|
+
finally {
|
|
386
|
+
if (this.#claims.get(profileId) === claim)
|
|
387
|
+
this.#claims.delete(profileId);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
#message(peer, message) {
|
|
391
|
+
if (message.type === "pong" || message.type === "ping") {
|
|
392
|
+
if (message.type === "ping")
|
|
393
|
+
void this.#send(peer, { v: 1, type: "pong", at: Date.now() }).catch(() => { });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
if (message.type === "tabs" || message.type === "capabilities") {
|
|
397
|
+
check(identifier(message.snapshotId) &&
|
|
398
|
+
Number.isSafeInteger(message.index) &&
|
|
399
|
+
Number.isSafeInteger(message.total) &&
|
|
400
|
+
Number(message.total) > 0 &&
|
|
401
|
+
Number(message.total) <= 128 &&
|
|
402
|
+
Number(message.index) >= 0 &&
|
|
403
|
+
Number(message.index) < Number(message.total) &&
|
|
404
|
+
Array.isArray(message.items), "PROTOCOL_MISMATCH", "Invalid browser snapshot partition.");
|
|
405
|
+
let snapshot = peer.snapshots.get(message.type);
|
|
406
|
+
if (!snapshot || snapshot.id !== message.snapshotId) {
|
|
407
|
+
snapshot = {
|
|
408
|
+
id: message.snapshotId,
|
|
409
|
+
total: Number(message.total),
|
|
410
|
+
parts: new Map(),
|
|
411
|
+
bytes: 0,
|
|
412
|
+
created: Date.now(),
|
|
413
|
+
};
|
|
414
|
+
peer.snapshots.set(message.type, snapshot);
|
|
415
|
+
}
|
|
416
|
+
check(snapshot.total === message.total &&
|
|
417
|
+
!snapshot.parts.has(Number(message.index)) &&
|
|
418
|
+
Date.now() - snapshot.created <= 30000, "PROTOCOL_MISMATCH", "Browser snapshot partitions conflict.");
|
|
419
|
+
snapshot.bytes += Buffer.byteLength(JSON.stringify(message.items));
|
|
420
|
+
check(snapshot.bytes <= limits.snapshotBytes &&
|
|
421
|
+
[...snapshot.parts.values()].reduce((n, items) => n + items.length, 0) +
|
|
422
|
+
message.items.length <=
|
|
423
|
+
limits.snapshotItems, "OUTPUT_TOO_LARGE", "The browser snapshot exceeds its negotiated budget.");
|
|
424
|
+
snapshot.parts.set(Number(message.index), message.items);
|
|
425
|
+
if (snapshot.parts.size === snapshot.total) {
|
|
426
|
+
const items = [...Array(snapshot.total).keys()].flatMap((index) => snapshot.parts.get(index));
|
|
427
|
+
if (message.type === "tabs") {
|
|
428
|
+
const next = new Map();
|
|
429
|
+
for (const item of items) {
|
|
430
|
+
const value = data(item, 16384);
|
|
431
|
+
check(identifier(value.id) && !next.has(value.id), "PROTOCOL_MISMATCH", "Browser tab snapshot has duplicate or invalid IDs.");
|
|
432
|
+
next.set(value.id, value);
|
|
433
|
+
}
|
|
434
|
+
peer.tabs = next;
|
|
435
|
+
peer.tabsReady = true;
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
peer.capabilities = items.map((item) => data(item, 16384));
|
|
439
|
+
peer.capabilitiesReady = true;
|
|
440
|
+
}
|
|
441
|
+
peer.snapshots.delete(message.type);
|
|
442
|
+
this.emit("snapshot", peer.info, message.type);
|
|
443
|
+
}
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (message.type === "binary_start") {
|
|
447
|
+
const late = typeof message.actionId === "string" &&
|
|
448
|
+
!peer.pending.has(message.actionId) &&
|
|
449
|
+
peer.completed.get(message.actionId)?.operationId ===
|
|
450
|
+
message.operationId;
|
|
451
|
+
peer.inbox.begin(message, (binding) => {
|
|
452
|
+
const known = peer.pending.get(binding.actionId) ??
|
|
453
|
+
peer.completed.get(binding.actionId);
|
|
454
|
+
return (!!known &&
|
|
455
|
+
known.operationId === binding.operationId &&
|
|
456
|
+
binding.generation === peer.generation);
|
|
457
|
+
}, late);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (message.type === "binary_end") {
|
|
461
|
+
peer.inbox.end(message);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (message.type === "action_result") {
|
|
465
|
+
check(identifier(message.actionId) && identifier(message.operationId), "PROTOCOL_MISMATCH", "Browser action result has no correlation.");
|
|
466
|
+
const pending = peer.pending.get(message.actionId);
|
|
467
|
+
if (!pending &&
|
|
468
|
+
peer.completed.get(message.actionId)?.operationId ===
|
|
469
|
+
message.operationId) {
|
|
470
|
+
peer.inbox.discard(message.actionId);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
check(pending && pending.operationId === message.operationId, "PROTOCOL_MISMATCH", "Browser result belongs to an unknown action.");
|
|
474
|
+
try {
|
|
475
|
+
if (message.ok === true)
|
|
476
|
+
pending.resolve(unpack(message.value, message.attachments, message.valueStream, peer.inbox, pending));
|
|
477
|
+
else
|
|
478
|
+
pending.reject(failure(identifier(message.code) ? message.code : "UNKNOWN_RESULT", typeof message.message === "string"
|
|
479
|
+
? message.message.slice(0, 1024)
|
|
480
|
+
: "The browser operation failed.", {
|
|
481
|
+
dispatched: message.dispatched !== false,
|
|
482
|
+
effect: message.effect === "none"
|
|
483
|
+
? "none"
|
|
484
|
+
: message.effect === "confirmed"
|
|
485
|
+
? "confirmed"
|
|
486
|
+
: "unknown",
|
|
487
|
+
operationId: pending.operationId,
|
|
488
|
+
}));
|
|
489
|
+
}
|
|
490
|
+
catch (cause) {
|
|
491
|
+
pending.reject(cause);
|
|
492
|
+
throw cause;
|
|
493
|
+
}
|
|
494
|
+
finally {
|
|
495
|
+
pending.cleanup();
|
|
496
|
+
peer.inbox.discard(pending.actionId);
|
|
497
|
+
}
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (message.type === "lease_opened" || message.type === "lease_closed") {
|
|
501
|
+
check(identifier(message.leaseId), "PROTOCOL_MISMATCH", "A browser lease reply has no identity.");
|
|
502
|
+
const lease = this.#leases.get(message.leaseId);
|
|
503
|
+
if (!lease && message.type === "lease_closed")
|
|
504
|
+
return;
|
|
505
|
+
check(lease &&
|
|
506
|
+
peer.id === lease.peer.id &&
|
|
507
|
+
peer.browserSessionId === lease.peer.browserSessionId &&
|
|
508
|
+
message.runId === lease.runId &&
|
|
509
|
+
(message.originalGeneration ?? message.generation) ===
|
|
510
|
+
lease.generation, "PROTOCOL_MISMATCH", "Browser lease evidence belongs to another run or connection.");
|
|
511
|
+
if (message.type === "lease_opened") {
|
|
512
|
+
check(lease.peer === peer, "PROTOCOL_MISMATCH", "A new connection cannot open an old lease.");
|
|
513
|
+
lease.opened = true;
|
|
514
|
+
lease.resolve();
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
if (!lease.opened)
|
|
518
|
+
lease.reject(failure(identifier(message.code) ? message.code : "INVALID_TARGET", typeof message.message === "string"
|
|
519
|
+
? message.message.slice(0, 1024)
|
|
520
|
+
: "The browser closed this lease before control was ready."));
|
|
521
|
+
lease.onClosed?.({
|
|
522
|
+
unconfirmedControls: message.unconfirmedControls === true,
|
|
523
|
+
});
|
|
524
|
+
this.#leases.delete(message.leaseId);
|
|
525
|
+
}
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (message.type === "event") {
|
|
529
|
+
check(Number.isSafeInteger(message.sequence) &&
|
|
530
|
+
Number(message.sequence) > peer.sequence, "PROTOCOL_MISMATCH", "Browser event sequence is stale.");
|
|
531
|
+
const event = data(message, limits.controlBytes);
|
|
532
|
+
peer.sequence = Number(message.sequence);
|
|
533
|
+
if (message.event === "tab_closed" &&
|
|
534
|
+
message.target &&
|
|
535
|
+
typeof message.target === "object" &&
|
|
536
|
+
identifier(message.target.tabId))
|
|
537
|
+
peer.tabs.delete(message.target.tabId);
|
|
538
|
+
if (message.event === "visual_degraded" && identifier(message.leaseId)) {
|
|
539
|
+
const lease = this.#leases.get(message.leaseId);
|
|
540
|
+
if (lease?.opened &&
|
|
541
|
+
lease.peer === peer &&
|
|
542
|
+
lease.generation === peer.generation &&
|
|
543
|
+
lease.runId === message.runId) {
|
|
544
|
+
const target = record(message.target) ? message.target : undefined;
|
|
545
|
+
const pending = [...peer.pending.values()].find((item) => item.leaseId === message.leaseId &&
|
|
546
|
+
item.runId === lease.runId &&
|
|
547
|
+
item.operationId === message.operationId &&
|
|
548
|
+
target?.bootId === item.target.bootId &&
|
|
549
|
+
target.browserId === item.target.browserId &&
|
|
550
|
+
target.browserSessionId === item.target.browserSessionId &&
|
|
551
|
+
target.generation === item.target.generation &&
|
|
552
|
+
target.tabId === item.target.tabId);
|
|
553
|
+
const reasons = [
|
|
554
|
+
"VISUAL_BUSY",
|
|
555
|
+
"VISUAL_CANCELLED",
|
|
556
|
+
"VISUAL_GROUP_UNAVAILABLE",
|
|
557
|
+
"VISUAL_MOVE_SUPERSEDED",
|
|
558
|
+
"VISUAL_TARGET_RELEASED",
|
|
559
|
+
"VISUAL_TIMEOUT",
|
|
560
|
+
"VISUAL_UNAVAILABLE",
|
|
561
|
+
];
|
|
562
|
+
const diagnostic = {
|
|
563
|
+
browserId: peer.id,
|
|
564
|
+
generation: peer.generation,
|
|
565
|
+
runId: lease.runId,
|
|
566
|
+
operationId: pending?.operationId ?? null,
|
|
567
|
+
tabId: pending?.target.tabId && /^\d{1,20}$/.test(pending.target.tabId)
|
|
568
|
+
? pending.target.tabId
|
|
569
|
+
: null,
|
|
570
|
+
reason: typeof message.reason === "string" &&
|
|
571
|
+
reasons.includes(message.reason)
|
|
572
|
+
? message.reason
|
|
573
|
+
: "VISUAL_UNAVAILABLE",
|
|
574
|
+
};
|
|
575
|
+
try {
|
|
576
|
+
this.emit("visual-diagnostic", diagnostic);
|
|
577
|
+
}
|
|
578
|
+
catch {
|
|
579
|
+
// Diagnostics never change the outcome of the actual browser action.
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
this.emit("browser-event", peer, event);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
check(message.type === "metadata", "PROTOCOL_MISMATCH", "Unknown browser protocol message.");
|
|
587
|
+
}
|
|
588
|
+
#offline(peer) {
|
|
589
|
+
if (this.#peers.get(peer.id) !== peer)
|
|
590
|
+
return;
|
|
591
|
+
this.#peers.delete(peer.id);
|
|
592
|
+
if (this.#profiles.get(peer.profileId) === peer)
|
|
593
|
+
this.#profiles.delete(peer.profileId);
|
|
594
|
+
peer.tabs.clear();
|
|
595
|
+
peer.capabilities = [];
|
|
596
|
+
peer.snapshots.clear();
|
|
597
|
+
for (const lease of this.#leases.values())
|
|
598
|
+
if (lease.peer === peer && !lease.opened)
|
|
599
|
+
lease.reject(failure("EXTENSION_OFFLINE", "The browser disconnected before its control lease was ready."));
|
|
600
|
+
for (const pending of [...peer.pending.values()]) {
|
|
601
|
+
pending.reject(failure("UNKNOWN_RESULT", "The browser connection ended before the operation outcome was confirmed.", {
|
|
602
|
+
dispatched: pending.dispatched,
|
|
603
|
+
effect: pending.dispatched ? "unknown" : "none",
|
|
604
|
+
operationId: pending.operationId,
|
|
605
|
+
}));
|
|
606
|
+
pending.cleanup();
|
|
607
|
+
}
|
|
608
|
+
peer.inbox.discard();
|
|
609
|
+
this.emit("offline", peer.info);
|
|
610
|
+
}
|
|
611
|
+
list() {
|
|
612
|
+
return [...this.#peers.values()]
|
|
613
|
+
.sort((a, b) => a.id.localeCompare(b.id))
|
|
614
|
+
.map((peer) => JSON.parse(JSON.stringify(peer.info)));
|
|
615
|
+
}
|
|
616
|
+
get(id) {
|
|
617
|
+
const peer = this.#peers.get(id);
|
|
618
|
+
check(peer && !this.#stopping, "EXTENSION_OFFLINE", "The selected browser is offline.");
|
|
619
|
+
return peer;
|
|
620
|
+
}
|
|
621
|
+
target(target) {
|
|
622
|
+
check(target.bootId === this.bootId, "INVALID_TARGET", "The browser target belongs to an old Agent boot.");
|
|
623
|
+
const peer = this.get(target.browserId);
|
|
624
|
+
check(peer.generation === target.generation &&
|
|
625
|
+
peer.browserSessionId === target.browserSessionId, "INVALID_TARGET", "The browser target belongs to a stale connection.");
|
|
626
|
+
if (target.tabId)
|
|
627
|
+
check(peer.tabs.has(target.tabId), "TARGET_GONE", "The selected browser tab is no longer available.");
|
|
628
|
+
return peer;
|
|
629
|
+
}
|
|
630
|
+
async waitSnapshot(peer, kind, signal, budgetMs = 30000) {
|
|
631
|
+
signal.throwIfAborted();
|
|
632
|
+
if (kind === "tabs" ? peer.tabsReady : peer.capabilitiesReady)
|
|
633
|
+
return;
|
|
634
|
+
await new Promise((resolve, reject) => {
|
|
635
|
+
const done = (info, type) => {
|
|
636
|
+
if (info.id === peer.id && type === kind) {
|
|
637
|
+
cleanup();
|
|
638
|
+
resolve();
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
const offline = (info) => {
|
|
642
|
+
if (info.id === peer.id) {
|
|
643
|
+
cleanup();
|
|
644
|
+
reject(failure("EXTENSION_OFFLINE", "The browser disconnected before its complete snapshot was ready."));
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
const abort = () => {
|
|
648
|
+
cleanup();
|
|
649
|
+
reject(signal.reason);
|
|
650
|
+
};
|
|
651
|
+
const timer = setTimeout(() => {
|
|
652
|
+
cleanup();
|
|
653
|
+
reject(failure("TIMEOUT", "The browser did not publish a complete discovery snapshot."));
|
|
654
|
+
}, Math.max(1, Math.min(budgetMs, 30000)));
|
|
655
|
+
const cleanup = () => {
|
|
656
|
+
clearTimeout(timer);
|
|
657
|
+
this.removeListener("snapshot", done);
|
|
658
|
+
this.removeListener("offline", offline);
|
|
659
|
+
signal.removeEventListener("abort", abort);
|
|
660
|
+
};
|
|
661
|
+
this.on("snapshot", done);
|
|
662
|
+
this.on("offline", offline);
|
|
663
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
664
|
+
if (signal.aborted)
|
|
665
|
+
abort();
|
|
666
|
+
else if (this.#peers.get(peer.id) !== peer)
|
|
667
|
+
offline(peer.info);
|
|
668
|
+
else if (kind === "tabs" ? peer.tabsReady : peer.capabilitiesReady)
|
|
669
|
+
done(peer.info, kind);
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
#send(peer, value, binding = true) {
|
|
673
|
+
check(peer.socket.readyState === WebSocket.OPEN &&
|
|
674
|
+
(!this.#stopping ||
|
|
675
|
+
value.type === "lease_end" ||
|
|
676
|
+
value.type === "cancel_action"), "EXTENSION_OFFLINE", "The browser connection is closed.");
|
|
677
|
+
const body = control(binding
|
|
678
|
+
? {
|
|
679
|
+
...value,
|
|
680
|
+
connectionId: peer.connectionId,
|
|
681
|
+
generation: peer.generation,
|
|
682
|
+
}
|
|
683
|
+
: value);
|
|
684
|
+
check(value.type === "lease_end" ||
|
|
685
|
+
value.type === "cancel_action" ||
|
|
686
|
+
peer.socket.bufferedAmount + Buffer.byteLength(body) <=
|
|
687
|
+
2 * limits.controlBytes, "QUEUE_FULL", "The browser connection write buffer is full.");
|
|
688
|
+
return new Promise((resolve, reject) => peer.socket.send(body, (cause) => (cause ? reject(cause) : resolve())));
|
|
689
|
+
}
|
|
690
|
+
async #binary(peer, prepared, signal) {
|
|
691
|
+
for (const stream of prepared.streams) {
|
|
692
|
+
signal.throwIfAborted();
|
|
693
|
+
await this.#send(peer, { v: 1, type: "binary_start", ...stream.meta });
|
|
694
|
+
for (const frame of frames(stream.meta, stream.bytes)) {
|
|
695
|
+
while (peer.socket.bufferedAmount > 1024 * 1024) {
|
|
696
|
+
signal.throwIfAborted();
|
|
697
|
+
await delay(4, undefined, { signal });
|
|
698
|
+
}
|
|
699
|
+
signal.throwIfAborted();
|
|
700
|
+
await new Promise((resolve, reject) => peer.socket.send(frame, { binary: true }, (cause) => cause ? reject(cause) : resolve()));
|
|
701
|
+
await yieldTurn(undefined, { signal });
|
|
702
|
+
}
|
|
703
|
+
await this.#send(peer, { v: 1, type: "binary_end", ...stream.meta });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
action(peer, input) {
|
|
707
|
+
input.signal.throwIfAborted();
|
|
708
|
+
check(Number.isFinite(input.budgetMs) &&
|
|
709
|
+
input.budgetMs > 0 &&
|
|
710
|
+
input.budgetMs <= 2147483647, "INVALID_ARGUMENT", "The browser action deadline is invalid.");
|
|
711
|
+
this.target(input.target);
|
|
712
|
+
check(peer.pending.size < limits.inFlight, "QUEUE_FULL", "This browser has too many in-flight actions.");
|
|
713
|
+
const actionId = randomUUID(), binding = {
|
|
714
|
+
actionId,
|
|
715
|
+
operationId: input.operationId,
|
|
716
|
+
generation: peer.generation,
|
|
717
|
+
}, packed = pack(input.args, binding), result = Promise.withResolvers();
|
|
718
|
+
void result.promise.catch(() => { });
|
|
719
|
+
const timer = setTimeout(() => stop(failure("TIMEOUT", "The browser action exceeded its remaining deadline.", {
|
|
720
|
+
dispatched: pending.dispatched,
|
|
721
|
+
effect: pending.dispatched ? "unknown" : "none",
|
|
722
|
+
operationId: input.operationId,
|
|
723
|
+
})), input.budgetMs);
|
|
724
|
+
const stop = (cause) => {
|
|
725
|
+
void this.#send(peer, {
|
|
726
|
+
v: 1,
|
|
727
|
+
type: "cancel_action",
|
|
728
|
+
actionId,
|
|
729
|
+
operationId: input.operationId,
|
|
730
|
+
leaseId: input.leaseId,
|
|
731
|
+
reason: "cancelled",
|
|
732
|
+
}).catch(() => { });
|
|
733
|
+
result.reject(cause);
|
|
734
|
+
pending.cleanup();
|
|
735
|
+
peer.inbox.discard(actionId);
|
|
736
|
+
};
|
|
737
|
+
const aborted = () => stop(failure("UNKNOWN_RESULT", "The browser action was cancelled before its effect was confirmed.", {
|
|
738
|
+
dispatched: pending.dispatched,
|
|
739
|
+
effect: pending.dispatched ? "unknown" : "none",
|
|
740
|
+
operationId: input.operationId,
|
|
741
|
+
}));
|
|
742
|
+
const pending = {
|
|
743
|
+
...binding,
|
|
744
|
+
runId: input.runId,
|
|
745
|
+
leaseId: input.leaseId,
|
|
746
|
+
target: { ...input.target },
|
|
747
|
+
resolve: result.resolve,
|
|
748
|
+
reject: result.reject,
|
|
749
|
+
dispatched: false,
|
|
750
|
+
cleanup: () => {
|
|
751
|
+
clearTimeout(timer);
|
|
752
|
+
input.signal.removeEventListener("abort", aborted);
|
|
753
|
+
peer.pending.delete(actionId);
|
|
754
|
+
this.#stopWakeIfIdle();
|
|
755
|
+
peer.completed.set(actionId, {
|
|
756
|
+
operationId: input.operationId,
|
|
757
|
+
at: Date.now(),
|
|
758
|
+
});
|
|
759
|
+
for (const [id, item] of peer.completed)
|
|
760
|
+
if (Date.now() - item.at > 300000 || peer.completed.size > 1024)
|
|
761
|
+
peer.completed.delete(id);
|
|
762
|
+
},
|
|
763
|
+
};
|
|
764
|
+
peer.pending.set(actionId, pending);
|
|
765
|
+
this.#wakeActiveActions();
|
|
766
|
+
input.signal.addEventListener("abort", aborted, { once: true });
|
|
767
|
+
const send = (async () => {
|
|
768
|
+
input.signal.throwIfAborted();
|
|
769
|
+
const dispatched = this.#send(peer, {
|
|
770
|
+
v: 1,
|
|
771
|
+
type: "action",
|
|
772
|
+
actionId,
|
|
773
|
+
runId: input.runId,
|
|
774
|
+
operationId: input.operationId,
|
|
775
|
+
leaseId: input.leaseId,
|
|
776
|
+
target: input.target,
|
|
777
|
+
method: input.method,
|
|
778
|
+
args: packed.value,
|
|
779
|
+
...(packed.valueStream ? { argsStream: packed.valueStream } : {}),
|
|
780
|
+
attachments: packed.attachments,
|
|
781
|
+
budgetMs: input.budgetMs,
|
|
782
|
+
});
|
|
783
|
+
pending.dispatched = true;
|
|
784
|
+
input.onDispatched?.();
|
|
785
|
+
await dispatched;
|
|
786
|
+
await this.#binary(peer, packed, input.signal);
|
|
787
|
+
})();
|
|
788
|
+
void this.#track(send).catch((cause) => stop(cause));
|
|
789
|
+
return result.promise;
|
|
790
|
+
}
|
|
791
|
+
async openLease(peer, input) {
|
|
792
|
+
const ready = Promise.withResolvers();
|
|
793
|
+
void ready.promise.catch(() => { });
|
|
794
|
+
const lease = {
|
|
795
|
+
peer,
|
|
796
|
+
generation: peer.generation,
|
|
797
|
+
runId: input.runId,
|
|
798
|
+
operationId: input.operationId,
|
|
799
|
+
resolve: ready.resolve,
|
|
800
|
+
reject: ready.reject,
|
|
801
|
+
opened: false,
|
|
802
|
+
onClosed: input.onClosed,
|
|
803
|
+
};
|
|
804
|
+
check(!this.#leases.has(input.id), "INVALID_ARGUMENT", "The browser lease identity is already used.");
|
|
805
|
+
this.#leases.set(input.id, lease);
|
|
806
|
+
let dispatched;
|
|
807
|
+
try {
|
|
808
|
+
dispatched = this.#send(peer, {
|
|
809
|
+
v: 1,
|
|
810
|
+
type: "lease_open",
|
|
811
|
+
leaseId: input.id,
|
|
812
|
+
runId: input.runId,
|
|
813
|
+
operationId: input.operationId,
|
|
814
|
+
target: input.target,
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
catch (cause) {
|
|
818
|
+
this.#leases.delete(input.id);
|
|
819
|
+
input.onClosed();
|
|
820
|
+
throw cause;
|
|
821
|
+
}
|
|
822
|
+
// A native send failure can be ambiguous. Only a synchronous admission
|
|
823
|
+
// rejection above proves that the remote lease was never sent.
|
|
824
|
+
await dispatched;
|
|
825
|
+
const timer = setTimeout(() => ready.reject(failure("TIMEOUT", "The browser did not confirm control readiness.")), 30000);
|
|
826
|
+
const aborted = () => ready.reject(input.signal.reason);
|
|
827
|
+
input.signal.addEventListener("abort", aborted, { once: true });
|
|
828
|
+
try {
|
|
829
|
+
input.signal.throwIfAborted();
|
|
830
|
+
await ready.promise;
|
|
831
|
+
}
|
|
832
|
+
finally {
|
|
833
|
+
clearTimeout(timer);
|
|
834
|
+
input.signal.removeEventListener("abort", aborted);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
async endLease(id) {
|
|
838
|
+
const lease = this.#leases.get(id);
|
|
839
|
+
if (!lease)
|
|
840
|
+
return;
|
|
841
|
+
const peer = this.#peers.get(lease.peer.id);
|
|
842
|
+
if (!peer || peer.browserSessionId !== lease.peer.browserSessionId)
|
|
843
|
+
return;
|
|
844
|
+
try {
|
|
845
|
+
await this.#send(peer, {
|
|
846
|
+
v: 1,
|
|
847
|
+
type: "lease_end",
|
|
848
|
+
leaseId: id,
|
|
849
|
+
runId: lease.runId,
|
|
850
|
+
operationId: lease.operationId,
|
|
851
|
+
originalGeneration: lease.generation,
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
catch {
|
|
855
|
+
// A failed send does not establish that the browser released control.
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
dispose() {
|
|
859
|
+
if (this.#disposing)
|
|
860
|
+
return this.#disposing;
|
|
861
|
+
this.#stopping = true;
|
|
862
|
+
this.#stop.abort(failure("EXTENSION_OFFLINE", "The browser service is stopping."));
|
|
863
|
+
if (this.#timer)
|
|
864
|
+
clearInterval(this.#timer);
|
|
865
|
+
if (this.#wakeTimer)
|
|
866
|
+
clearInterval(this.#wakeTimer);
|
|
867
|
+
this.#wakeTimer = undefined;
|
|
868
|
+
const task = (async () => {
|
|
869
|
+
await this.#start?.catch(() => { });
|
|
870
|
+
for (const id of this.#leases.keys())
|
|
871
|
+
await this.endLease(id);
|
|
872
|
+
for (const peer of this.#peers.values())
|
|
873
|
+
this.#offline(peer);
|
|
874
|
+
for (const socket of this.#sockets)
|
|
875
|
+
socket.close(1001, "Browser service stopped");
|
|
876
|
+
const grace = setTimeout(() => {
|
|
877
|
+
for (const socket of this.#sockets)
|
|
878
|
+
socket.terminate();
|
|
879
|
+
}, 5000);
|
|
880
|
+
try {
|
|
881
|
+
if (this.#wss)
|
|
882
|
+
await new Promise((resolve) => this.#wss.close(() => resolve()));
|
|
883
|
+
if (this.#server)
|
|
884
|
+
await new Promise((resolve, reject) => this.#server.close((cause) => cause &&
|
|
885
|
+
cause.code !== "ERR_SERVER_NOT_RUNNING"
|
|
886
|
+
? reject(cause)
|
|
887
|
+
: resolve()));
|
|
888
|
+
await Promise.allSettled([...this.#tasks]);
|
|
889
|
+
await this.#persist.catch(() => { });
|
|
890
|
+
this.#started = false;
|
|
891
|
+
this.#closed.resolve();
|
|
892
|
+
}
|
|
893
|
+
finally {
|
|
894
|
+
clearTimeout(grace);
|
|
895
|
+
}
|
|
896
|
+
})();
|
|
897
|
+
this.#disposing = task;
|
|
898
|
+
void task.catch(() => {
|
|
899
|
+
if (this.#disposing === task)
|
|
900
|
+
this.#disposing = undefined;
|
|
901
|
+
});
|
|
902
|
+
return task;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
//# sourceMappingURL=service.js.map
|