@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,441 @@
1
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+ import { isUuid } from "../frame.js";
3
+ export const JSON_LIMIT = 256 * 1024;
4
+ export const PNG_LIMIT = 8 * 1024 * 1024;
5
+ const DIMENSION_LIMIT = 2048;
6
+ const PIXEL_LIMIT = 2048 * 1536;
7
+ const VALUE_LIMIT = 16_384;
8
+ const PNG_IHDR = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");
9
+ const wireErrorCodes = [
10
+ "invalid_frame",
11
+ "frame_limit",
12
+ "invalid_request",
13
+ "unsupported_version",
14
+ "method_unavailable",
15
+ "authentication_failed",
16
+ "auth_required",
17
+ "auth_failed",
18
+ "consent_denied",
19
+ "consent_expired",
20
+ "cancelled",
21
+ "needs_system_permission",
22
+ "permissions_expired",
23
+ "key_store_unavailable",
24
+ "trusted_key_limit",
25
+ "key_revoked",
26
+ "connection_closed",
27
+ "desktop_disabled",
28
+ "console_unavailable",
29
+ "accessibility_permission_required",
30
+ "screen_recording_permission_required",
31
+ "session_stopped",
32
+ "cancel_requested",
33
+ "busy",
34
+ "window_unavailable",
35
+ "window_already_bound",
36
+ "window_coordinate_out_of_bounds",
37
+ "window_focus_unavailable",
38
+ "window_occluded",
39
+ "process_identity_changed",
40
+ "binding_unavailable",
41
+ "binding_not_found",
42
+ "element_unavailable",
43
+ "key_unavailable",
44
+ "action_unavailable",
45
+ "invalid_value",
46
+ "action_rejected",
47
+ "action_outcome_unknown",
48
+ "capture_failed",
49
+ "capture_limit",
50
+ "internal_error",
51
+ ];
52
+ const wireErrors = new Set(wireErrorCodes);
53
+ export class ComputerUseError extends Error {
54
+ code;
55
+ constructor(code, options) {
56
+ super(code, options);
57
+ this.code = code;
58
+ this.name = "ComputerUseError";
59
+ }
60
+ get retryable() {
61
+ return this.code === "busy" || this.code === "request_timeout";
62
+ }
63
+ get actionOutcomeUnknown() {
64
+ return this.code === "action_outcome_unknown";
65
+ }
66
+ }
67
+ const actions = ["press", "set_value", "increment", "decrement"];
68
+ const actionNames = new Set(actions);
69
+ export function isObject(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
72
+ function isString(value) {
73
+ return typeof value === "string" && !/[\uD800-\uDFFF]/u.test(value);
74
+ }
75
+ function isNonemptyString(value) {
76
+ return isString(value) && value.length > 0;
77
+ }
78
+ function isId(value) {
79
+ return isNonemptyString(value) && Buffer.byteLength(value) <= 64;
80
+ }
81
+ function isNumber(value) {
82
+ return typeof value === "number" && Number.isFinite(value);
83
+ }
84
+ function isPositiveInteger(value, max = Number.MAX_SAFE_INTEGER) {
85
+ return isNumber(value) && Number.isInteger(value) && value >= 1 && value <= max;
86
+ }
87
+ function isPid(value) {
88
+ return isPositiveInteger(value, 0x7fffffff);
89
+ }
90
+ function isWindowId(value) {
91
+ return isPositiveInteger(value, 0xffffffff);
92
+ }
93
+ function isValue(value) {
94
+ return ((isString(value) && Buffer.byteLength(value) <= VALUE_LIMIT) ||
95
+ typeof value === "boolean" ||
96
+ isNumber(value));
97
+ }
98
+ function hasOnlyKeys(value, ...keys) {
99
+ return Object.keys(value).every((key) => keys.includes(key));
100
+ }
101
+ function decodeBase64(value, size = 32) {
102
+ if (!isString(value) || value.length !== Math.ceil(size / 3) * 4)
103
+ return;
104
+ const bytes = Buffer.from(value, "base64");
105
+ if (bytes.length === size && bytes.toString("base64") === value)
106
+ return bytes;
107
+ }
108
+ const locales = new Set(["en", "ja", "zh-Hans", "zh-Hant"]);
109
+ const consentModes = new Set(["session_only", "persistent_only", "session_or_persistent"]);
110
+ function isScope(value) {
111
+ return value === "remote" || value === "local";
112
+ }
113
+ function isFingerprint(value) {
114
+ return isString(value) && /^[A-F0-9]{4}(?:-[A-F0-9]{4}){7}$/.test(value);
115
+ }
116
+ const smallOrderY = new Set([
117
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
118
+ "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
119
+ "JuiVj8KyJ7BFw/SJ8u+Y8NXfrAXTxjM5sTgCiG1T/AU=",
120
+ "xxdqcD1N2E+6PAt2DRBnDyogU/osOczGTsf9d5KsA3o=",
121
+ ]);
122
+ const fieldModulusMinusOne = Buffer.from("7P///////////////////////////////////////38=", "base64").reverse();
123
+ function isControllerKey(value) {
124
+ const y = decodeBase64(value);
125
+ if (!y)
126
+ return false;
127
+ y[31] &= 0x7f;
128
+ return !smallOrderY.has(y.toString("base64")) && y.reverse().compare(fieldModulusMinusOne) < 0;
129
+ }
130
+ function isController(value) {
131
+ return (isObject(value) &&
132
+ hasOnlyKeys(value, "publicKey", "label", "scope") &&
133
+ isControllerKey(value.publicKey) &&
134
+ isLabel(value.label) &&
135
+ isScope(value.scope));
136
+ }
137
+ function isLabel(value) {
138
+ return (isString(value) &&
139
+ /[^\p{White_Space}\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{M}]/u.test(value));
140
+ }
141
+ const buttons = new Set(["left", "right", "middle"]);
142
+ const modifiers = new Set(["command", "control", "option", "shift"]);
143
+ const namedKeys = /^(?:return|enter|tab|escape|backspace|delete|space|up|down|left|right|home|end|page_up|page_down|f(?:[1-9]|1[0-2]))$/i;
144
+ const graphemes = new Intl.Segmenter();
145
+ function isKey(value) {
146
+ return (isNonemptyString(value) &&
147
+ (namedKeys.test(value) || (value.length <= 16 && [...graphemes.segment(value)].length === 1)));
148
+ }
149
+ function isDelta(value) {
150
+ return isNumber(value) && Math.abs(value) <= 2000;
151
+ }
152
+ function isAct(value) {
153
+ if (!isObject(value) || !isUuid(value.binding))
154
+ return false;
155
+ const { action, element, x, y, button, clickCount, toX, toY, steps, deltaX, deltaY, key, text } = value;
156
+ if (actionNames.has(action)) {
157
+ return (hasOnlyKeys(value, "binding", "action", "element", "value") &&
158
+ isNonemptyString(element) &&
159
+ (action === "set_value" ? isValue(value.value) : value.value === undefined));
160
+ }
161
+ if (action === "type_text") {
162
+ return (hasOnlyKeys(value, "binding", "action", "text") &&
163
+ isNonemptyString(text) &&
164
+ Buffer.byteLength(text) <= VALUE_LIMIT);
165
+ }
166
+ const names = value.modifiers;
167
+ if (names !== undefined &&
168
+ (!Array.isArray(names) ||
169
+ names.length > 4 ||
170
+ !names.every((name) => modifiers.has(name)) ||
171
+ new Set(names).size !== names.length))
172
+ return false;
173
+ const keys = ["binding", "action", "modifiers"];
174
+ if (action === "key_press")
175
+ return hasOnlyKeys(value, ...keys, "key") && isKey(key);
176
+ if (!isNumber(x) || !isNumber(y))
177
+ return false;
178
+ keys.push("x", "y");
179
+ switch (action) {
180
+ case "move":
181
+ return hasOnlyKeys(value, ...keys);
182
+ case "click":
183
+ return (hasOnlyKeys(value, ...keys, "button", "clickCount") &&
184
+ (button === undefined || buttons.has(button)) &&
185
+ (clickCount === undefined || isPositiveInteger(clickCount, 3)));
186
+ case "drag":
187
+ return (hasOnlyKeys(value, ...keys, "toX", "toY", "button", "steps") &&
188
+ isNumber(toX) &&
189
+ isNumber(toY) &&
190
+ (button === undefined || buttons.has(button)) &&
191
+ (steps === undefined || isPositiveInteger(steps, 60)));
192
+ case "scroll":
193
+ return (hasOnlyKeys(value, ...keys, "deltaX", "deltaY") &&
194
+ isDelta(deltaX) &&
195
+ isDelta(deltaY) &&
196
+ (Math.abs(deltaX) >= 0.5 || Math.abs(deltaY) >= 0.5));
197
+ default:
198
+ return false;
199
+ }
200
+ }
201
+ function isWindow(value) {
202
+ if (!isObject(value))
203
+ return false;
204
+ const { window, appName, bundleName, bundleId, title, bounds } = value;
205
+ return (isWindowId(window) &&
206
+ [appName, bundleName, bundleId, title].every(isString) &&
207
+ Array.isArray(bounds) &&
208
+ bounds.length === 4 &&
209
+ bounds.every(isNumber) &&
210
+ bounds[2] > 0 &&
211
+ bounds[3] > 0);
212
+ }
213
+ function isTree(value) {
214
+ const nodes = [value];
215
+ while (nodes.length) {
216
+ const node = nodes.pop();
217
+ if (!isObject(node) ||
218
+ !isNonemptyString(node.ref) ||
219
+ !isNonemptyString(node.role) ||
220
+ !Array.isArray(node.actions) ||
221
+ !node.actions.every((action) => actionNames.has(action)) ||
222
+ !Array.isArray(node.children) ||
223
+ (node.title !== undefined && !isString(node.title)) ||
224
+ (node.description !== undefined && !isString(node.description)) ||
225
+ (node.value !== undefined && !isValue(node.value)) ||
226
+ (node.valueTruncated !== undefined && (node.valueTruncated !== true || !isString(node.value))))
227
+ return false;
228
+ for (const child of node.children)
229
+ nodes.push(child);
230
+ }
231
+ return true;
232
+ }
233
+ function isStopped(result) {
234
+ return ((result.stop === "cancel_requested" || result.stop === "stop_confirmed") &&
235
+ wireErrors.has(result.reason));
236
+ }
237
+ function isScreenshot(value) {
238
+ if (!isObject(value))
239
+ return false;
240
+ const { mimeType, width, height, bytes } = value;
241
+ return (mimeType === "image/png" &&
242
+ isPositiveInteger(width, DIMENSION_LIMIT) &&
243
+ isPositiveInteger(height, DIMENSION_LIMIT) &&
244
+ width * height <= PIXEL_LIMIT &&
245
+ isPositiveInteger(bytes, PNG_LIMIT) &&
246
+ bytes >= 33);
247
+ }
248
+ function isHelperAccess(result) {
249
+ if (!isObject(result))
250
+ return false;
251
+ if (!isPositiveInteger(result.revision))
252
+ return false;
253
+ if (result.status === "authorized")
254
+ return hasOnlyKeys(result, "revision", "status");
255
+ const { missing } = result;
256
+ return (result.status === "needs_system_permission" &&
257
+ hasOnlyKeys(result, "revision", "status", "missing", "guideOpened") &&
258
+ typeof result.guideOpened === "boolean" &&
259
+ Array.isArray(missing) &&
260
+ missing.length > 0 &&
261
+ missing.length <= 2 &&
262
+ new Set(missing).size === missing.length &&
263
+ missing.every((pane) => pane === "accessibility" || pane === "screen_recording"));
264
+ }
265
+ const resultValidators = {
266
+ hello: (result) => {
267
+ const { instance, helperPid, helperProof, locale, auth, status, challenge, fingerprint } = result;
268
+ if (!isUuid(instance) ||
269
+ !isPid(helperPid) ||
270
+ !decodeBase64(helperProof) ||
271
+ !locales.has(locale))
272
+ return false;
273
+ const keys = ["instance", "helperPid", "helperProof", "locale"];
274
+ return status === "challenge_required"
275
+ ? hasOnlyKeys(result, ...keys, "status", "challenge", "fingerprint") &&
276
+ !!decodeBase64(challenge) &&
277
+ isFingerprint(fingerprint)
278
+ : hasOnlyKeys(result, ...keys, "auth", "access") &&
279
+ auth === "session" &&
280
+ (result.access === undefined || isHelperAccess(result.access));
281
+ },
282
+ authorize: (result) => {
283
+ const { auth, locale, fingerprint, enrolled, label, scope } = result;
284
+ return (hasOnlyKeys(result, "auth", "locale", "fingerprint", "enrolled", "label", "scope", "access") &&
285
+ (result.access === undefined || isHelperAccess(result.access)) &&
286
+ (auth === "session" || auth === "persistent") &&
287
+ locales.has(locale) &&
288
+ isFingerprint(fingerprint) &&
289
+ typeof enrolled === "boolean" &&
290
+ (auth === "persistent" || !enrolled) &&
291
+ isLabel(label) &&
292
+ isScope(scope));
293
+ },
294
+ access_status: isHelperAccess,
295
+ open_permission_guide: isHelperAccess,
296
+ status: (result) => isUuid(result.instance) &&
297
+ (result.stop === "running" ? result.reason === undefined : isStopped(result)),
298
+ windows: ({ windows }) => Array.isArray(windows) && windows.every(isWindow),
299
+ bind: ({ binding, window }) => isUuid(binding) && isWindow(window),
300
+ unbind: ({ binding, released }) => isUuid(binding) && released === true,
301
+ observe: ({ binding, tree, truncated, refTTLms, screenshot }) => isUuid(binding) &&
302
+ isTree(tree) &&
303
+ typeof truncated === "boolean" &&
304
+ isPositiveInteger(refTTLms) &&
305
+ (screenshot === undefined || isScreenshot(screenshot)),
306
+ act: ({ binding, dispatched }) => isUuid(binding) && dispatched === true,
307
+ cancel: isStopped,
308
+ stop: isStopped,
309
+ };
310
+ const paramsValidators = {
311
+ hello: (params) => isObject(params) &&
312
+ hasOnlyKeys(params, "nonce", "proof", "locale", "consentMode", "controller", "consentTimeoutMs", "includeAccess") &&
313
+ !!decodeBase64(params.nonce) &&
314
+ !!decodeBase64(params.proof) &&
315
+ (params.locale === undefined || isString(params.locale)) &&
316
+ (params.includeAccess === undefined || typeof params.includeAccess === "boolean") &&
317
+ (params.consentTimeoutMs === undefined ||
318
+ isPositiveInteger(params.consentTimeoutMs, 180_000)) &&
319
+ (params.consentMode === undefined || consentModes.has(params.consentMode)) &&
320
+ (params.controller === undefined
321
+ ? params.consentMode === undefined || params.consentMode === "session_only"
322
+ : isController(params.controller)),
323
+ authorize: (params) => isObject(params) && hasOnlyKeys(params, "signature") && !!decodeBase64(params.signature, 64),
324
+ access_status: (params) => params === undefined ||
325
+ (isObject(params) &&
326
+ hasOnlyKeys(params, "afterRevision") &&
327
+ isPositiveInteger(params.afterRevision)),
328
+ open_permission_guide: (params) => params === undefined,
329
+ status: (params) => params === undefined,
330
+ windows: (params) => params === undefined ||
331
+ (isObject(params) &&
332
+ hasOnlyKeys(params, "application") &&
333
+ (params.application === undefined || isString(params.application))),
334
+ bind: (params) => isObject(params) && hasOnlyKeys(params, "window") && isWindowId(params.window),
335
+ unbind: (params) => isObject(params) && hasOnlyKeys(params, "binding") && isUuid(params.binding),
336
+ observe: (params) => isObject(params) &&
337
+ hasOnlyKeys(params, "binding", "element", "screenshot") &&
338
+ isUuid(params.binding) &&
339
+ (params.element === undefined || isNonemptyString(params.element)) &&
340
+ (params.screenshot === undefined || typeof params.screenshot === "boolean"),
341
+ act: isAct,
342
+ cancel: (params) => params === undefined,
343
+ stop: (params) => params === undefined,
344
+ };
345
+ export function requestParams(method, params) {
346
+ if (!Object.hasOwn(paramsValidators, method) || !paramsValidators[method](params)) {
347
+ throw new ComputerUseError("invalid_request");
348
+ }
349
+ return params;
350
+ }
351
+ export function makeRequest(id, method, params) {
352
+ if (!isId(id)) {
353
+ throw new ComputerUseError("invalid_request");
354
+ }
355
+ requestParams(method, params);
356
+ return params === undefined ? { v: 1, id, method } : { v: 1, id, method, params };
357
+ }
358
+ export function parseResponse(message, method) {
359
+ const { v, id, ok, result, error } = message;
360
+ if (v === 1 &&
361
+ ok === false &&
362
+ (isId(id) || id === null) &&
363
+ hasOnlyKeys(message, "v", "id", "ok", "error") &&
364
+ isObject(error) &&
365
+ hasOnlyKeys(error, "code") &&
366
+ wireErrors.has(error.code)) {
367
+ return message;
368
+ }
369
+ if (v === 1 &&
370
+ ok === true &&
371
+ isId(id) &&
372
+ method &&
373
+ hasOnlyKeys(message, "v", "id", "ok", "result") &&
374
+ isObject(result) &&
375
+ (method === "observe" || !Object.hasOwn(result, "screenshot")) &&
376
+ resultValidators[method](result)) {
377
+ return message;
378
+ }
379
+ throw new ComputerUseError("invalid_frame");
380
+ }
381
+ export function screenshotFor(message, binaryLength) {
382
+ if (message.ok === true &&
383
+ isObject(message.result) &&
384
+ Object.hasOwn(message.result, "screenshot")) {
385
+ const screenshot = message.result.screenshot;
386
+ if (message.v === 1 &&
387
+ isId(message.id) &&
388
+ hasOnlyKeys(message, "v", "id", "ok", "result") &&
389
+ isScreenshot(screenshot) &&
390
+ screenshot.bytes === binaryLength)
391
+ return screenshot;
392
+ throw new ComputerUseError("invalid_frame");
393
+ }
394
+ if (binaryLength !== 0)
395
+ throw new ComputerUseError("invalid_frame");
396
+ }
397
+ export function checkPng(bytes, { width, height }) {
398
+ if (!bytes.subarray(0, PNG_IHDR.length).equals(PNG_IHDR) ||
399
+ bytes.readUInt32BE(16) !== width ||
400
+ bytes.readUInt32BE(20) !== height) {
401
+ throw new ComputerUseError("invalid_frame");
402
+ }
403
+ }
404
+ export function createProof(context, ...role) {
405
+ const { secret, nonce, hostPid } = context;
406
+ const [name, helperPid, instance] = role;
407
+ if (secret.length !== 32 ||
408
+ nonce.length !== 32 ||
409
+ !isPid(hostPid) ||
410
+ (name === "helper" && (!isPid(helperPid) || !isUuid(instance)))) {
411
+ throw new ComputerUseError("authentication_failed");
412
+ }
413
+ const fields = ["rome-computer-use-v1", name, hostPid];
414
+ const encodedNonce = nonce.toString("base64");
415
+ if (name === "host")
416
+ fields.push(encodedNonce);
417
+ else
418
+ fields.push(helperPid, encodedNonce, instance);
419
+ return createHmac("sha256", secret).update(fields.join("\n")).digest("base64");
420
+ }
421
+ export function verifyProof(proof, context, ...role) {
422
+ const actual = decodeBase64(proof);
423
+ return (actual !== undefined &&
424
+ timingSafeEqual(actual, Buffer.from(createProof(context, ...role), "base64")));
425
+ }
426
+ export function controllerFingerprint(publicKey) {
427
+ const hex = createHash("sha256").update(Buffer.from(publicKey, "base64")).digest("hex");
428
+ return hex.slice(0, 32).toUpperCase().match(/.{4}/g).join("-");
429
+ }
430
+ export function authorizationPayload(hello, hostPid, controller, mode = "session_only") {
431
+ return Buffer.from([
432
+ "rome-computer-use-auth-v1",
433
+ hello.instance,
434
+ hello.helperPid,
435
+ hostPid,
436
+ hello.challenge,
437
+ controller.publicKey,
438
+ controller.scope,
439
+ mode,
440
+ ].join("\n"));
441
+ }
package/dist/connect.d.ts CHANGED
@@ -1,29 +1,15 @@
1
- import type { DeviceSession } from "./login.js";
2
- import type { CredentialStore } from "./storage.js";
1
+ import type { EnsureComputerUseHelper } from "./computer-use/host.js";
2
+ import type { HelperPermissionCache } from "./computer-use/launch.js";
3
3
  import { type HostAudit } from "./executor.js";
4
- export type HostCredential = DeviceSession & {
5
- name: string;
6
- };
7
- export type HostEvent = {
8
- type: "authorization_required";
9
- } | {
10
- type: "retrying";
11
- } | {
12
- type: "device";
13
- name: string;
14
- deviceId: string;
15
- } | {
16
- type: "connection";
17
- status: import("./client.js").ConnectionStatus;
18
- };
19
- export interface HostOptions {
20
- cloudUrl: string;
21
- name: string;
22
- signal: AbortSignal;
23
- credentials: CredentialStore<HostCredential>;
24
- authorize(cloudUrl: string, name: string, signal: AbortSignal): Promise<DeviceSession>;
25
- onEvent?(event: HostEvent): void;
4
+ import { type HostConnectionOptions, type HostCredential, type HostEvent } from "./host-connection.js";
5
+ export type { HostCredential, HostEvent };
6
+ export interface HostOptions extends HostConnectionOptions {
26
7
  audit: HostAudit;
8
+ computerUseHelperPath?: string;
9
+ computerUseLocale?: () => string | undefined;
10
+ ensureComputerUseHelper?: EnsureComputerUseHelper;
11
+ strictBundledAppPath?: boolean;
12
+ permissionCache?: HelperPermissionCache;
27
13
  }
28
14
  export declare function connectHost(options: HostOptions): Promise<void>;
29
15
  export declare const defaultDeviceName: () => string;
package/dist/connect.js CHANGED
@@ -1,117 +1,13 @@
1
1
  import { hostname } from "node:os";
2
- import { setTimeout as delay } from "node:timers/promises";
3
- import { isRecord } from "./actions.js";
4
- import { cloudOrigin, cloudRequest, CloudError, gatewayConfig } from "./cloud.js";
5
- import { connectGateway } from "./client.js";
6
- import { createNodeSocket } from "./socket.js";
7
2
  import { createExecutor } from "./executor.js";
8
- import { validId } from "./protocol.js";
9
- export async function connectHost(options) {
10
- const { name, signal, credentials } = options;
11
- if (signal.aborted)
12
- return;
13
- const cloudUrl = cloudOrigin(options.cloudUrl);
14
- const stored = await credentials.load();
15
- let session = isRecord(stored) &&
16
- stored.cloudUrl === cloudUrl &&
17
- typeof stored.token === "string" &&
18
- /^(?:romedev|romemob)_[A-Za-z0-9_-]{43}$/.test(stored.token) &&
19
- validId(stored.deviceId) &&
20
- typeof stored.name === "string"
21
- ? { cloudUrl, token: stored.token, deviceId: stored.deviceId, name: stored.name }
22
- : null;
23
- let gatewayUrl = "";
24
- let attempt = 0;
25
- while (!signal.aborted) {
26
- if (!session) {
27
- options.onEvent?.({ type: "authorization_required" });
28
- session = { ...(await options.authorize(cloudUrl, name, signal)), name };
29
- await credentials.save(session);
30
- }
31
- try {
32
- gatewayUrl = await gatewayConfig(cloudUrl, session.token);
33
- break;
34
- }
35
- catch (error) {
36
- if (error instanceof CloudError && error.code === "invalid_device_session") {
37
- await credentials.clear();
38
- session = null;
39
- continue;
40
- }
41
- options.onEvent?.({ type: "retrying" });
42
- await delay(Math.min(60_000, 1000 * 2 ** Math.min(attempt++, 6)), undefined, {
43
- signal,
44
- }).catch(() => { });
45
- }
46
- }
47
- if (signal.aborted || !session)
48
- return;
49
- const devices = await cloudRequest(cloudUrl, "/api/account/devices", session.token).catch(() => null);
50
- if (isRecord(devices) && Array.isArray(devices.items)) {
51
- const device = devices.items.find((item) => isRecord(item) && item.id === session?.deviceId);
52
- if (isRecord(device) && typeof device.device_name === "string") {
53
- session.name = device.device_name;
54
- await credentials.save(session);
55
- }
56
- }
57
- if (signal.aborted)
58
- return;
59
- const active = session;
60
- options.onEvent?.({ type: "device", name: active.name, deviceId: active.deviceId });
61
- await new Promise((resolve, reject) => {
62
- const executor = createExecutor(active.name, options.audit, (message) => connection.send(message), [active.token], (frame) => connection.sendFrame(frame));
63
- let finished = false;
64
- const finish = (error) => {
65
- if (finished)
66
- return;
67
- finished = true;
68
- signal.removeEventListener("abort", abort);
69
- executor.disconnect();
70
- connection.stop();
71
- void Promise.race([executor.idle(), delay(3000, undefined, { ref: false })]).then(() => error ? reject(error) : resolve());
72
- };
73
- const abort = () => finish();
74
- const connection = connectGateway({
75
- gatewayUrl,
76
- getToken: () => active.token,
77
- createSocket: createNodeSocket,
78
- beforeConnect: async () => {
79
- try {
80
- return await gatewayConfig(cloudUrl, active.token);
81
- }
82
- catch (error) {
83
- if (error instanceof CloudError && error.code === "invalid_device_session")
84
- return null;
85
- throw error;
86
- }
87
- },
88
- onMessage: (message) => {
89
- if ("from" in message)
90
- void executor.receive(message);
91
- },
92
- onFrame: (frame) => void executor.receiveFrame(frame),
93
- onStatus: (status) => {
94
- options.audit.host({
95
- event: "connection",
96
- status,
97
- deviceId: active.deviceId,
98
- name: active.name,
99
- cloudOrigin: cloudUrl,
100
- }, [active.token]);
101
- options.onEvent?.({ type: "connection", status });
102
- if (status !== "online" && status !== "connecting")
103
- executor.disconnect();
104
- if (status === "revoked" || status === "superseded") {
105
- queueMicrotask(() => finish(new Error(status === "revoked"
106
- ? "Authorization revoked. Explicit authorization is required."
107
- : "Another connection replaced this device. This process has stopped.")));
108
- }
109
- },
110
- });
111
- signal.addEventListener("abort", abort, { once: true });
112
- if (signal.aborted)
113
- abort();
114
- });
3
+ import { runHostConnection, } from "./host-connection.js";
4
+ export function connectHost(options) {
5
+ return runHostConnection(options, (session, send, sendFrame, secrets) => createExecutor(session.name, options.audit, send, secrets, sendFrame, options.computerUseHelperPath, {
6
+ ensureHelper: options.ensureComputerUseHelper,
7
+ computerUseLocale: options.computerUseLocale,
8
+ strictBundledAppPath: options.strictBundledAppPath,
9
+ permissionCache: options.permissionCache,
10
+ }));
115
11
  }
116
12
  export const defaultDeviceName = () => hostname()
117
13
  .replace(/[\u0000-\u001f\u007f]/g, "")
@@ -289,7 +289,7 @@ export function createNodeClient(config, options = {}) {
289
289
  typeof device.id === "string" &&
290
290
  typeof device.name === "string" &&
291
291
  (device.platform === null || typeof device.platform === "string") &&
292
- ["connected", "not_connected", "unknown", "revoked"].includes(String(device.status))))
292
+ ["connected", "not_connected", "unknown"].includes(String(device.status))))
293
293
  throw new Error("Invalid devices status response.");
294
294
  return body;
295
295
  },
package/dist/daemon.js CHANGED
@@ -4,6 +4,7 @@ import { createRequire } from "node:module";
4
4
  import { join } from "node:path";
5
5
  import WebSocket, { WebSocketServer } from "ws";
6
6
  import { actionError, isRecord } from "./actions.js";
7
+ import { computerUseAuditFields } from "./computer-use/audit-fields.js";
7
8
  import { ObserveStore, QueryError } from "./observe.js";
8
9
  import { CloudError } from "./cloud.js";
9
10
  import { DeviceConnector } from "./connector.js";
@@ -34,9 +35,16 @@ function byteCount(value) {
34
35
  return typeof value === "string" ? Buffer.byteLength(value) : 0;
35
36
  }
36
37
  function actionStart(deviceId, action, args, mode, stdinBytes = 0) {
38
+ if (action === "computer.status" || (action === "system.info" && mode === "json"))
39
+ return null;
37
40
  const exec = action === "exec" && isRecord(args) && typeof args.command === "string";
38
41
  let text = null;
39
- if (!exec)
42
+ if (action.startsWith("computer.")) {
43
+ const metadata = computerUseAuditFields(action, args);
44
+ if (metadata.actionId)
45
+ text = JSON.stringify(metadata);
46
+ }
47
+ else if (!exec)
40
48
  try {
41
49
  text = JSON.stringify(args ?? {});
42
50
  }
@@ -56,7 +64,11 @@ function actionEnd(response, stdoutBytes) {
56
64
  if (!response.ok) {
57
65
  const code = response.error.code;
58
66
  return {
59
- outcome: code === "unknown_outcome" ? "unknown_outcome" : code === "canceled" ? "aborted" : "error",
67
+ outcome: code === "unknown_outcome" || code === "action_outcome_unknown"
68
+ ? "unknown_outcome"
69
+ : code === "canceled"
70
+ ? "aborted"
71
+ : "error",
60
72
  errorCode: code,
61
73
  };
62
74
  }
@@ -393,7 +405,7 @@ export async function serveDaemon(config, signal) {
393
405
  {
394
406
  const { deviceId, action } = params;
395
407
  const args = params.args ?? {};
396
- result = await observed(action === "system.info" ? null : actionStart(deviceId, action, args, "json"), () => connector.run(deviceId, action, args), (response) => actionEnd(response));
408
+ result = await observed(actionStart(deviceId, action, args, "json"), () => connector.run(deviceId, action, args), (response) => actionEnd(response));
397
409
  }
398
410
  break;
399
411
  case "devices.runBinary": {
@@ -4,7 +4,7 @@ export interface DeviceStatus {
4
4
  id: string;
5
5
  name: string;
6
6
  platform: string | null;
7
- status: "connected" | "not_connected" | "unknown" | "revoked";
7
+ status: "connected" | "not_connected" | "unknown";
8
8
  audit?: {
9
9
  state: "ok" | "unavailable";
10
10
  code?: string;
@@ -24,5 +24,6 @@ export declare class DeviceStatusReader {
24
24
  constructor(connector: Pick<DeviceConnector, "list" | "run" | "getStatus">);
25
25
  invalidate(): void;
26
26
  read(): Promise<DevicesStatus>;
27
+ private refresh;
27
28
  private check;
28
29
  }