@rome-os/node-core 0.1.7 → 0.1.10

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 (41) hide show
  1. package/README.md +4 -5
  2. package/dist/actions.d.ts +2 -1
  3. package/dist/actions.js +3 -3
  4. package/dist/audit.d.ts +6 -0
  5. package/dist/audit.js +11 -0
  6. package/dist/client.d.ts +2 -1
  7. package/dist/client.js +12 -3
  8. package/dist/cloud.js +1 -2
  9. package/dist/computer-use/audit-fields.d.ts +5 -0
  10. package/dist/computer-use/audit-fields.js +17 -0
  11. package/dist/computer-use/bridge.d.ts +53 -0
  12. package/dist/computer-use/bridge.js +361 -0
  13. package/dist/computer-use/discovery.d.ts +14 -0
  14. package/dist/computer-use/discovery.js +117 -0
  15. package/dist/computer-use/frames.d.ts +9 -0
  16. package/dist/computer-use/frames.js +100 -0
  17. package/dist/computer-use/host.d.ts +90 -0
  18. package/dist/computer-use/host.js +765 -0
  19. package/dist/computer-use/launch.d.ts +55 -0
  20. package/dist/computer-use/launch.js +375 -0
  21. package/dist/computer-use/protocol.d.ts +238 -0
  22. package/dist/computer-use/protocol.js +441 -0
  23. package/dist/connect.d.ts +10 -24
  24. package/dist/connect.js +8 -112
  25. package/dist/daemon-client.js +1 -1
  26. package/dist/daemon.js +15 -3
  27. package/dist/devices-status.d.ts +2 -1
  28. package/dist/devices-status.js +16 -10
  29. package/dist/executor.d.ts +2 -1
  30. package/dist/executor.js +124 -134
  31. package/dist/host-connection.d.ts +37 -0
  32. package/dist/host-connection.js +114 -0
  33. package/dist/host.d.ts +6 -1
  34. package/dist/host.js +3 -0
  35. package/dist/limited-host.d.ts +3 -0
  36. package/dist/limited-host.js +5 -0
  37. package/dist/limited.d.ts +10 -0
  38. package/dist/limited.js +43 -0
  39. package/dist/protocol.d.ts +13 -0
  40. package/dist/protocol.js +29 -0
  41. package/package.json +5 -1
@@ -0,0 +1,765 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { actionError, isRecord } from "../actions.js";
4
+ import { isUuid } from "../frame.js";
5
+ import { ComputerUseBridge } from "./bridge.js";
6
+ import { discoverHelper } from "./discovery.js";
7
+ import { createHelperPermissionCache, probeHelperPermissions, } from "./launch.js";
8
+ import { ComputerUseError, JSON_LIMIT, PNG_LIMIT, requestParams, } from "./protocol.js";
9
+ const CONSENT_TTL_MS = 180_000;
10
+ const CONSENT_REPLY_GRACE_MS = 10_000;
11
+ const SYSTEM_PERMISSION_TTL_MS = 300_000;
12
+ const TERMINAL_TTL_MS = 600_000;
13
+ const MAX_TERMINALS_PER_PEER = 64;
14
+ const SESSION_TTL_MS = 5 * 60_000;
15
+ const MAX_PEERS = 8;
16
+ const MAX_BINDINGS = 8;
17
+ const MAX_ACTION_IDS = 1024;
18
+ const STOP_TIMEOUT_MS = 1000;
19
+ const empty = new Uint8Array();
20
+ function success(result, body = empty) {
21
+ return { response: { type: "response", ok: true, result }, body };
22
+ }
23
+ function failure(code, detail = code) {
24
+ return { response: actionError(code, detail), body: empty };
25
+ }
26
+ function validAccessArgs(args) {
27
+ return args === undefined || (isRecord(args) && !Object.keys(args).length);
28
+ }
29
+ function errorCode(cause) {
30
+ return cause instanceof ComputerUseError ? cause.code : "internal_error";
31
+ }
32
+ const errorMessages = {
33
+ computer_use_unsupported_platform: "The Computer Use Helper requires macOS.",
34
+ computer_use_helper_missing: "The Computer Use Helper is missing from this Mac.",
35
+ action_outcome_unknown: "The Helper did not confirm the input outcome. Do not retry with a new action ID.",
36
+ window_focus_unavailable: "Keyboard input requires the bound window to have focus within its app. Focus that window before sending keys, or use an Accessibility action such as set_value or press.",
37
+ };
38
+ const stopRequested = { stop: "cancel_requested", reason: "session_stopped" };
39
+ const stopConfirmed = { stop: "stop_confirmed", reason: "session_stopped" };
40
+ export class ComputerUseHost {
41
+ sessions = new Map();
42
+ history = new Map();
43
+ windows = new Map();
44
+ deps;
45
+ permissionCache;
46
+ discovering;
47
+ ensuring;
48
+ constructor(deps = {}) {
49
+ this.deps = {
50
+ discover: discoverHelper,
51
+ probePermissions: probeHelperPermissions,
52
+ launch: (options) => ComputerUseBridge.launch(options),
53
+ consentTtlMs: CONSENT_TTL_MS,
54
+ permissionTtlMs: SYSTEM_PERMISSION_TTL_MS,
55
+ terminalTtlMs: TERMINAL_TTL_MS,
56
+ sessionTtlMs: SESSION_TTL_MS,
57
+ now: () => performance.now(),
58
+ isProcessAlive: (pid) => {
59
+ if (!Number.isInteger(pid) || pid <= 0)
60
+ return false;
61
+ try {
62
+ process.kill(pid, 0);
63
+ return true;
64
+ }
65
+ catch (cause) {
66
+ return cause.code === "EPERM";
67
+ }
68
+ },
69
+ stopPollMs: 200,
70
+ ...deps,
71
+ };
72
+ this.permissionCache =
73
+ deps.permissionCache ??
74
+ createHelperPermissionCache({ probe: this.deps.probePermissions, now: this.deps.now });
75
+ }
76
+ operations = {
77
+ "computer.request_access": {
78
+ usage: "No arguments. Request local approval and return the request ID and current state.",
79
+ run: async (session) => {
80
+ if (!session)
81
+ throw new ComputerUseError("busy");
82
+ if (!session.phase) {
83
+ if ((this.history.get(session.peer)?.size ?? 0) >= MAX_TERMINALS_PER_PEER)
84
+ throw new ComputerUseError("busy");
85
+ const appPath = await this.findHelper();
86
+ this.check(session);
87
+ if (!session.phase) {
88
+ session.phase = { status: "pending_consent" };
89
+ this.deadline(session, this.deps.consentTtlMs + CONSENT_REPLY_GRACE_MS);
90
+ void this.start(session, appPath);
91
+ }
92
+ }
93
+ else if (session.phase.status === "needs_system_permission" && !session.refocusing) {
94
+ session.refocusing = session
95
+ .bridge.openPermissionGuide()
96
+ .then((access) => {
97
+ if (session.phase?.status === "needs_system_permission")
98
+ this.updateAccess(session, access);
99
+ }, () => { })
100
+ .finally(() => {
101
+ session.refocusing = undefined;
102
+ });
103
+ }
104
+ return success(this.snapshot(session));
105
+ },
106
+ },
107
+ "computer.status": {
108
+ usage: "{requestId?}. Read the active request or a retained outcome for this peer.",
109
+ run: async (_session, input, _binary, peer) => {
110
+ if (input !== undefined &&
111
+ (!isRecord(input) ||
112
+ Object.keys(input).some((key) => key !== "requestId") ||
113
+ (input.requestId !== undefined && typeof input.requestId !== "string")))
114
+ throw new ComputerUseError("invalid_request");
115
+ const requestId = isRecord(input) ? input.requestId : undefined;
116
+ const active = this.sessions.get(peer);
117
+ if (active?.phase && (requestId === undefined || requestId === active.requestId)) {
118
+ if (this.deps.now() < active.expiresAt)
119
+ return success(this.snapshot(active));
120
+ if (requestId !== undefined)
121
+ return success(this.outcome(active, this.expiry(active)));
122
+ }
123
+ return success(requestId === undefined
124
+ ? { status: "idle" }
125
+ : (this.history.get(peer)?.get(requestId) ?? { status: "not_found", requestId }));
126
+ },
127
+ },
128
+ "computer.windows": {
129
+ usage: "{application?}. List windows, optionally filtered by application.",
130
+ run: async (session, input) => {
131
+ const args = requestParams("windows", input);
132
+ const active = this.requireSession(session);
133
+ return this.work(active, async (bridge) => {
134
+ const result = await bridge.windows(args?.application);
135
+ this.check(active);
136
+ return success(result);
137
+ });
138
+ },
139
+ },
140
+ "computer.bind": {
141
+ usage: "{window}. Bind a window by its numeric ID.",
142
+ run: async (session, input) => {
143
+ const { window } = requestParams("bind", input);
144
+ return this.bind(this.requireSession(session), window);
145
+ },
146
+ },
147
+ "computer.unbind": {
148
+ usage: "{binding}. Release the binding.",
149
+ run: async (session, input) => {
150
+ const { binding: id } = requestParams("unbind", input);
151
+ const { active, binding, bridge } = this.bound(session, id);
152
+ return this.work(active, async () => {
153
+ await this.changeBinding(active, () => bridge.unbind(binding.nativeId));
154
+ this.check(active);
155
+ this.releaseBinding(active, id);
156
+ return success({ binding: id, released: true });
157
+ });
158
+ },
159
+ },
160
+ "computer.observe": {
161
+ usage: "{binding, element?, screenshot?}. Read the AX tree, optionally rooted at an element ref. " +
162
+ "screenshot: true requires a binary request frame and returns raw PNG bytes in the response body.",
163
+ run: async (session, input, binary) => {
164
+ const { binding: id, element, screenshot } = requestParams("observe", input);
165
+ if (screenshot && !binary)
166
+ return failure("screenshot_requires_binary", "Use binary output for screenshots.");
167
+ const { active, binding, bridge } = this.bound(session, id);
168
+ return this.work(active, async () => {
169
+ const { screenshot: capture, ...observation } = await bridge.observe(binding.nativeId, {
170
+ element,
171
+ screenshot,
172
+ });
173
+ this.check(active);
174
+ if (!capture)
175
+ return success({ ...observation, binding: id });
176
+ const { png, ...descriptor } = capture;
177
+ if (png.byteLength > PNG_LIMIT)
178
+ return failure("output_too_large");
179
+ return success({ ...observation, binding: id, screenshot: descriptor }, png);
180
+ });
181
+ },
182
+ },
183
+ "computer.act": {
184
+ usage: "{binding, actionId, action, ...}. Use a new UUID actionId per intended action. " +
185
+ "For AX, use {element, action: press|increment|decrement} or {element, action: set_value, value}. " +
186
+ "Use an element ref from observe. value is a string, number, or boolean. " +
187
+ "Input fields by action are click {x, y, button?, clickCount?}, move {x, y}, " +
188
+ "drag {x, y, toX, toY, button?, steps?}, scroll {x, y, deltaX, deltaY}, key_press {key}, " +
189
+ "and type_text {text}. Pointer coordinates use points from the window's top-left corner. " +
190
+ "button is left, right, or middle. clickCount is 1 to 3 and steps is 1 to 60. " +
191
+ "key is a named key such as Enter or a single grapheme. Each input action except type_text " +
192
+ "accepts an optional modifiers array of distinct names (command, control, option, shift).",
193
+ run: async (session, input) => {
194
+ if (!isRecord(input))
195
+ throw new ComputerUseError("invalid_request");
196
+ const { actionId, ...args } = input;
197
+ if (!isUuid(actionId))
198
+ throw new ComputerUseError("invalid_request");
199
+ const { binding: id, ...action } = requestParams("act", args);
200
+ const { active, binding, bridge } = this.bound(session, id);
201
+ const key = actionId.toLowerCase();
202
+ let pending = binding.actions.get(key);
203
+ if (!pending) {
204
+ if (active.working || binding.actions.size >= MAX_ACTION_IDS)
205
+ throw new ComputerUseError("busy");
206
+ pending = this.work(active, () => bridge.act({ binding: binding.nativeId, ...action }));
207
+ binding.actions.set(key, pending);
208
+ }
209
+ await pending;
210
+ this.check(active);
211
+ return success({ binding: id, actionId: key, dispatched: true });
212
+ },
213
+ },
214
+ "computer.cancel": {
215
+ usage: "No arguments. Stop input for this peer and return the stop status.",
216
+ urgent: true,
217
+ run: async (session) => success(await this.cancel(session)),
218
+ },
219
+ };
220
+ async info(peer) {
221
+ if (isUuid(peer))
222
+ peer = peer.toLowerCase();
223
+ const appPath = await this.findHelper().catch(() => undefined);
224
+ const permitted = appPath && !this.sessions.get(peer)?.stop
225
+ ? await this.permissionCache.check(appPath)
226
+ : undefined;
227
+ const session = this.sessions.get(peer);
228
+ const stopped = Boolean(session?.stop);
229
+ const live = session?.phase?.status === "authorized" && !session.bridge?.closed;
230
+ const installed = Boolean(appPath) || (!this.deps.ensureHelper && live);
231
+ const state = stopped || !installed ? "off" : (permitted ?? live) ? "on" : "needs_permission";
232
+ const operations = Object.entries(this.operations);
233
+ const advertised = installed
234
+ ? operations.filter(([name, operation]) => !stopped ||
235
+ operation.urgent ||
236
+ name === "computer.request_access" ||
237
+ name === "computer.status")
238
+ : [];
239
+ return {
240
+ capability: {
241
+ id: "computer_use",
242
+ prefix: "computer",
243
+ title: "Window Control",
244
+ state,
245
+ personal: true,
246
+ actions: Object.keys(this.operations),
247
+ },
248
+ actions: advertised.map(([action]) => action),
249
+ usage: Object.fromEntries(advertised.map(([action, { usage }]) => [action, usage])),
250
+ };
251
+ }
252
+ prepare(action, peer, args, body) {
253
+ if (!Object.hasOwn(this.operations, action))
254
+ return;
255
+ const operation = this.operations[action];
256
+ if (isUuid(peer))
257
+ peer = peer.toLowerCase();
258
+ let session = action === "computer.status" ? undefined : this.sessions.get(peer);
259
+ if (session?.phase && this.deps.now() >= session.expiresAt) {
260
+ this.expire(session);
261
+ session = undefined;
262
+ }
263
+ const requesting = action === "computer.request_access";
264
+ const restarting = requesting && session?.stop ? session : undefined;
265
+ const cancelRevision = restarting?.cancelRevision;
266
+ if (restarting)
267
+ session = undefined;
268
+ else if (!session &&
269
+ ((requesting && !body?.byteLength && validAccessArgs(args)) || operation.urgent))
270
+ session = this.reserve(peer, !!operation.urgent);
271
+ const gate = action === "computer.windows" || action === "computer.bind"
272
+ ? this.refusal(session)
273
+ : undefined;
274
+ if (session)
275
+ session.pending++;
276
+ const stopping = operation.urgent
277
+ ? operation.run(session, args, body !== undefined, peer)
278
+ : undefined;
279
+ const run = async (refusal) => {
280
+ try {
281
+ if (stopping)
282
+ return await stopping;
283
+ if (session?.bridge && this.deps.ensureHelper) {
284
+ await this.ensureReady(this.deps.ensureHelper);
285
+ this.check(session);
286
+ }
287
+ if (refusal)
288
+ return { response: refusal, body: empty };
289
+ if (body?.byteLength)
290
+ return failure("invalid_request", "Computer Use takes no binary input.");
291
+ if (requesting && !validAccessArgs(args))
292
+ return failure("invalid_request");
293
+ if (gate)
294
+ return gate;
295
+ if (restarting) {
296
+ if (restarting.cancelRevision !== cancelRevision)
297
+ throw new ComputerUseError("session_stopped");
298
+ const current = this.sessions.get(peer);
299
+ if (current === restarting) {
300
+ if (current.stopped?.stop !== "stop_confirmed")
301
+ throw new ComputerUseError("session_stopped");
302
+ session = this.reserve(peer, false, current);
303
+ }
304
+ else if (current?.replaces === restarting.requestId) {
305
+ session = current;
306
+ }
307
+ else
308
+ throw new ComputerUseError("connection_closed");
309
+ if (session)
310
+ session.pending++;
311
+ }
312
+ if (session)
313
+ this.check(session);
314
+ const result = await operation.run(session, args, body !== undefined, peer);
315
+ if (Buffer.byteLength(JSON.stringify(result.response)) > JSON_LIMIT)
316
+ return failure("output_too_large");
317
+ return result;
318
+ }
319
+ catch (cause) {
320
+ const code = errorCode(cause);
321
+ if (session?.appPath &&
322
+ (code === "accessibility_permission_required" ||
323
+ code === "screen_recording_permission_required"))
324
+ this.permissionCache.invalidate(session.appPath);
325
+ if (session?.bridge && code === "session_stopped" && !session.stop)
326
+ void this.cancel(session);
327
+ if (session &&
328
+ (code === "binding_not_found" || code === "binding_unavailable") &&
329
+ isRecord(args) &&
330
+ isUuid(args.binding)) {
331
+ this.releaseBinding(session, args.binding);
332
+ }
333
+ return code === "capture_limit"
334
+ ? failure("output_too_large")
335
+ : failure(code, errorMessages[code]);
336
+ }
337
+ };
338
+ return {
339
+ run,
340
+ release: () => {
341
+ if (!session || --session.pending || session.phase || session.stop)
342
+ return;
343
+ this.remove(session);
344
+ },
345
+ };
346
+ }
347
+ disconnect() {
348
+ this.permissionCache.invalidate();
349
+ for (const session of this.sessions.values())
350
+ this.remove(session);
351
+ }
352
+ reserve(peer, urgent, previous) {
353
+ const occupied = urgent
354
+ ? this.sessions.size
355
+ : [...this.sessions.values()].filter((s) => !s.stopped).length;
356
+ if (occupied >= MAX_PEERS)
357
+ return;
358
+ if (previous)
359
+ this.remove(previous);
360
+ const session = {
361
+ peer,
362
+ requestId: randomUUID(),
363
+ replaces: previous?.requestId,
364
+ revision: 1,
365
+ cancelRevision: 0,
366
+ launch: new AbortController(),
367
+ bindings: new Map(),
368
+ pending: 0,
369
+ working: false,
370
+ expiresAt: Infinity,
371
+ };
372
+ this.sessions.set(peer, session);
373
+ return session;
374
+ }
375
+ findHelper() {
376
+ this.discovering ??= this.resolveHelper().finally(() => {
377
+ this.discovering = undefined;
378
+ });
379
+ return this.discovering;
380
+ }
381
+ ensureReady(ensureHelper, force = false) {
382
+ if (this.ensuring && !force)
383
+ return this.ensuring;
384
+ const previous = this.ensuring?.catch(() => { }) ?? Promise.resolve();
385
+ const pending = previous
386
+ .then(() => (force ? ensureHelper({ force: true }) : ensureHelper()))
387
+ .catch(() => false)
388
+ .then((ready) => {
389
+ if (!ready) {
390
+ this.permissionCache.invalidate();
391
+ throw new ComputerUseError("computer_use_helper_missing");
392
+ }
393
+ })
394
+ .finally(() => {
395
+ if (this.ensuring === pending)
396
+ this.ensuring = undefined;
397
+ });
398
+ this.ensuring = pending;
399
+ return pending;
400
+ }
401
+ async resolveHelper() {
402
+ const { discover, bundledAppPath, strictBundledAppPath, ensureHelper } = this.deps;
403
+ const options = { bundledAppPath, strictBundledAppPath };
404
+ if (ensureHelper)
405
+ await this.ensureReady(ensureHelper);
406
+ try {
407
+ return await discover(options);
408
+ }
409
+ catch (cause) {
410
+ if (!ensureHelper || errorCode(cause) !== "computer_use_helper_missing")
411
+ throw cause;
412
+ this.permissionCache.invalidate();
413
+ await this.ensureReady(ensureHelper, true);
414
+ return discover(options);
415
+ }
416
+ }
417
+ requireSession(session) {
418
+ if (!session || session.phase?.status !== "authorized")
419
+ throw new ComputerUseError("consent_required");
420
+ return session;
421
+ }
422
+ check(session) {
423
+ if (session.stop)
424
+ throw new ComputerUseError("session_stopped");
425
+ if (this.sessions.get(session.peer) !== session)
426
+ throw new ComputerUseError("connection_closed");
427
+ if (this.deps.now() >= session.expiresAt) {
428
+ this.expire(session);
429
+ throw new ComputerUseError("binding_not_found");
430
+ }
431
+ }
432
+ async work(session, run) {
433
+ this.check(session);
434
+ const bridge = session.bridge;
435
+ if (session.phase?.status !== "authorized" || !bridge || bridge.closed)
436
+ throw new ComputerUseError("consent_required");
437
+ if (session.working)
438
+ throw new ComputerUseError("busy");
439
+ session.working = true;
440
+ try {
441
+ return await run(bridge);
442
+ }
443
+ finally {
444
+ session.working = false;
445
+ }
446
+ }
447
+ snapshot(session) {
448
+ const phase = session.phase;
449
+ const displayExpiresAt = phase.status === "pending_consent"
450
+ ? session.expiresAt - CONSENT_REPLY_GRACE_MS
451
+ : session.expiresAt;
452
+ return {
453
+ ...phase,
454
+ requestId: session.requestId,
455
+ revision: session.revision,
456
+ expiresInMs: Math.max(0, Math.ceil(displayExpiresAt - this.deps.now())),
457
+ };
458
+ }
459
+ refusal(session) {
460
+ if (!session?.phase)
461
+ return failure("consent_required");
462
+ if (session.phase.status === "authorized")
463
+ return;
464
+ const { status, ...details } = this.snapshot(session);
465
+ return { response: actionError(status, status, details), body: empty };
466
+ }
467
+ deadline(session, ms) {
468
+ clearTimeout(session.timer);
469
+ session.expiresAt = this.deps.now() + ms;
470
+ session.timer = setTimeout(() => this.expire(session), ms).unref();
471
+ }
472
+ expiry(session) {
473
+ switch (session.phase?.status) {
474
+ case "pending_consent":
475
+ return "consent_expired";
476
+ case "needs_system_permission":
477
+ return "permissions_expired";
478
+ default:
479
+ return "cancelled";
480
+ }
481
+ }
482
+ expire(session) {
483
+ this.remove(session, this.expiry(session));
484
+ }
485
+ async start(session, appPath) {
486
+ try {
487
+ session.appPath = appPath;
488
+ this.permissionCache.invalidate(appPath);
489
+ const bridge = await this.deps.launch({
490
+ appPath,
491
+ signal: session.launch.signal,
492
+ startupTimeoutMs: 8000,
493
+ locale: this.deps.computerUseLocale?.(),
494
+ consentMode: "session_only",
495
+ includeAccess: true,
496
+ consentTimeoutMs: this.deps.consentTtlMs + 15_000,
497
+ consentDialogTimeoutMs: this.deps.consentTtlMs,
498
+ });
499
+ if (!this.current(session)) {
500
+ bridge.close();
501
+ return;
502
+ }
503
+ session.bridge = bridge;
504
+ bridge.onDisconnect((cause) => {
505
+ this.permissionCache.invalidate(appPath);
506
+ if (session.stop)
507
+ this.finishStop(session, bridge, cause.code === "session_stopped" ? stopConfirmed : stopRequested);
508
+ else
509
+ this.failed(session, cause);
510
+ });
511
+ bridge.onCancelRequested(() => {
512
+ if (!this.current(session))
513
+ return;
514
+ this.seal(session);
515
+ session.stop = Promise.resolve(stopRequested);
516
+ });
517
+ let access = bridge.initialAccess;
518
+ if (!access)
519
+ throw new ComputerUseError("method_unavailable");
520
+ while (this.current(session)) {
521
+ this.updateAccess(session, access);
522
+ if (!this.current(session))
523
+ return;
524
+ const next = await bridge.accessStatus(access.revision, {
525
+ timeoutMs: Math.ceil(session.expiresAt - this.deps.now()) + 15_000,
526
+ signal: session.launch.signal,
527
+ });
528
+ if (next.revision <= access.revision)
529
+ throw new ComputerUseError("invalid_frame");
530
+ access = next;
531
+ }
532
+ }
533
+ catch (cause) {
534
+ this.failed(session, cause);
535
+ }
536
+ }
537
+ current(session) {
538
+ return this.sessions.get(session.peer) === session && !session.stop && !!session.phase;
539
+ }
540
+ updateAccess(session, access) {
541
+ if (!this.current(session))
542
+ return;
543
+ if (this.deps.now() >= session.expiresAt) {
544
+ this.expire(session);
545
+ return;
546
+ }
547
+ const previous = session.phase;
548
+ if (previous.status !== "pending_consent" && access.revision <= previous.revision)
549
+ return;
550
+ session.phase = access;
551
+ session.revision++;
552
+ if (session.appPath)
553
+ this.permissionCache.invalidate(session.appPath);
554
+ if (access.status !== previous.status)
555
+ this.deadline(session, access.status === "authorized" ? this.deps.sessionTtlMs : this.deps.permissionTtlMs);
556
+ }
557
+ failed(session, cause) {
558
+ if (!this.current(session))
559
+ return;
560
+ const code = errorCode(cause);
561
+ if (code === "session_stopped") {
562
+ this.record(session, "cancelled");
563
+ session.stop = Promise.resolve(stopConfirmed);
564
+ session.stopped = stopConfirmed;
565
+ session.bindings.clear();
566
+ session.launch.abort();
567
+ session.bridge?.close();
568
+ this.releaseWindows(session);
569
+ this.scheduleStopCleanup(session);
570
+ return;
571
+ }
572
+ this.remove(session, code === "consent_denied" ||
573
+ code === "consent_expired" ||
574
+ (code === "permissions_expired" && session.phase?.status === "needs_system_permission")
575
+ ? code
576
+ : "cancelled", code === "cancelled" || code === "request_aborted" ? undefined : code);
577
+ }
578
+ async bind(session, window) {
579
+ return this.work(session, async (bridge) => {
580
+ if (this.windows.has(window))
581
+ throw new ComputerUseError("window_already_bound");
582
+ if (session.bindings.size >= MAX_BINDINGS)
583
+ throw new ComputerUseError("busy");
584
+ this.windows.set(window, session);
585
+ try {
586
+ const result = await this.changeBinding(session, () => bridge.bind(window));
587
+ this.check(session);
588
+ const id = randomUUID();
589
+ session.bindings.set(id, {
590
+ nativeId: result.binding,
591
+ window,
592
+ instance: bridge.instanceId,
593
+ actions: new Map(),
594
+ });
595
+ return success({
596
+ binding: id,
597
+ window: result.window,
598
+ bindingTTLms: Math.max(0, Math.floor(session.expiresAt - this.deps.now())),
599
+ });
600
+ }
601
+ catch (cause) {
602
+ if (!session.stop && this.windows.get(window) === session)
603
+ this.windows.delete(window);
604
+ throw cause;
605
+ }
606
+ });
607
+ }
608
+ bound(session, id) {
609
+ const binding = session?.bindings.get(id);
610
+ const bridge = session?.bridge;
611
+ if (!session || !bridge || !binding || binding.instance !== bridge.instanceId)
612
+ throw new ComputerUseError("binding_not_found");
613
+ this.check(session);
614
+ return { active: session, binding, bridge };
615
+ }
616
+ async changeBinding(session, run) {
617
+ try {
618
+ return await run();
619
+ }
620
+ catch (cause) {
621
+ if (!session.stop && errorCode(cause) === "request_timeout")
622
+ this.remove(session);
623
+ throw cause;
624
+ }
625
+ }
626
+ cancel(session) {
627
+ if (!session)
628
+ return Promise.resolve(stopConfirmed);
629
+ session.cancelRevision++;
630
+ if (session.stopped)
631
+ return Promise.resolve(session.stopped);
632
+ if (session.stop)
633
+ return session.stop;
634
+ const waiting = session.phase?.status !== "authorized";
635
+ const bridge = session.bridge;
636
+ this.seal(session);
637
+ session.stop =
638
+ bridge && !waiting ? this.stopHelper(session, bridge) : Promise.resolve(stopConfirmed);
639
+ if (!bridge || waiting) {
640
+ bridge?.close();
641
+ session.stopped = stopConfirmed;
642
+ session.launch.abort();
643
+ this.releaseWindows(session);
644
+ this.scheduleStopCleanup(session);
645
+ }
646
+ return session.stop;
647
+ }
648
+ seal(session) {
649
+ if (session.appPath)
650
+ this.permissionCache.invalidate(session.appPath);
651
+ this.record(session, "cancelled");
652
+ session.bindings.clear();
653
+ clearTimeout(session.timer);
654
+ session.timer = undefined;
655
+ }
656
+ scheduleStopCleanup(session) {
657
+ clearTimeout(session.timer);
658
+ session.timer = setTimeout(() => this.remove(session), this.deps.sessionTtlMs).unref();
659
+ }
660
+ async stopHelper(session, bridge) {
661
+ try {
662
+ const result = await bridge.cancel({ timeoutMs: STOP_TIMEOUT_MS });
663
+ if (result.stop === "cancel_requested")
664
+ void this.confirmStop(session, bridge, result);
665
+ else
666
+ this.finishStop(session, bridge, result);
667
+ return result;
668
+ }
669
+ catch {
670
+ this.finishStop(session, bridge, stopRequested);
671
+ return stopRequested;
672
+ }
673
+ }
674
+ async confirmStop(session, bridge, requested) {
675
+ const signal = AbortSignal.any([AbortSignal.timeout(STOP_TIMEOUT_MS), session.launch.signal]);
676
+ try {
677
+ while (!signal.aborted) {
678
+ await delay(50, undefined, { signal, ref: false });
679
+ const status = await bridge.status({ signal });
680
+ if (status.stop === "stop_confirmed") {
681
+ this.finishStop(session, bridge, { stop: status.stop, reason: status.reason });
682
+ return;
683
+ }
684
+ }
685
+ }
686
+ catch { }
687
+ this.finishStop(session, bridge, requested);
688
+ }
689
+ finishStop(session, bridge, result) {
690
+ if (this.sessions.get(session.peer) !== session || session.stopped?.stop === "stop_confirmed")
691
+ return;
692
+ session.stopped = result;
693
+ bridge.close();
694
+ if (result.stop === "stop_confirmed") {
695
+ this.releaseWindows(session);
696
+ this.scheduleStopCleanup(session);
697
+ }
698
+ else {
699
+ this.watchHelperExit(session, bridge);
700
+ }
701
+ }
702
+ watchHelperExit(session, bridge) {
703
+ if (session.timer)
704
+ return;
705
+ session.timer = setTimeout(() => {
706
+ session.timer = undefined;
707
+ if (this.sessions.get(session.peer) !== session || session.stopped?.stop === "stop_confirmed")
708
+ return;
709
+ if (bridge.helperPid > 0 && this.deps.isProcessAlive(bridge.helperPid))
710
+ this.watchHelperExit(session, bridge);
711
+ else
712
+ this.finishStop(session, bridge, stopConfirmed);
713
+ }, this.deps.stopPollMs).unref();
714
+ }
715
+ releaseBinding(session, id) {
716
+ const binding = session.bindings.get(id);
717
+ if (!binding)
718
+ return;
719
+ session.bindings.delete(id);
720
+ this.windows.delete(binding.window);
721
+ }
722
+ releaseWindows(session) {
723
+ for (const [window, owner] of this.windows)
724
+ if (owner === session)
725
+ this.windows.delete(window);
726
+ }
727
+ outcome(session, status) {
728
+ return {
729
+ status,
730
+ revision: session.revision + 1,
731
+ requestId: session.requestId,
732
+ ...(status === "permissions_expired" &&
733
+ session.phase?.status === "needs_system_permission" && { missing: session.phase.missing }),
734
+ };
735
+ }
736
+ record(session, status, reason) {
737
+ if (!session.phase)
738
+ return;
739
+ const record = this.outcome(session, this.deps.now() >= session.expiresAt ? this.expiry(session) : status);
740
+ session.revision = record.revision;
741
+ if (reason && record.status === "cancelled")
742
+ record.reason = reason;
743
+ session.phase = undefined;
744
+ const records = this.history.get(session.peer) ?? new Map();
745
+ this.history.set(session.peer, records);
746
+ records.set(record.requestId, record);
747
+ const peer = session.peer;
748
+ setTimeout(() => {
749
+ records.delete(record.requestId);
750
+ if (!records.size)
751
+ this.history.delete(peer);
752
+ }, this.deps.terminalTtlMs).unref();
753
+ }
754
+ remove(session, outcome = "cancelled", reason) {
755
+ if (this.sessions.get(session.peer) !== session)
756
+ return;
757
+ this.record(session, outcome, reason);
758
+ this.sessions.delete(session.peer);
759
+ clearTimeout(session.timer);
760
+ session.bindings.clear();
761
+ session.launch.abort();
762
+ session.bridge?.close();
763
+ this.releaseWindows(session);
764
+ }
765
+ }