@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.37

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 (121) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +321 -308
  3. package/box/build-agent37.mjs +177 -0
  4. package/dist/agent37.d.ts +165 -0
  5. package/dist/agent37.js +759 -0
  6. package/dist/attach.d.ts +146 -0
  7. package/dist/attach.js +469 -0
  8. package/dist/browserbase.d.ts +2 -4
  9. package/dist/browserbase.js +2 -1
  10. package/dist/client.d.ts +33 -1
  11. package/dist/client.js +53 -0
  12. package/dist/computerd-linux-amd64 +0 -0
  13. package/dist/computerd-linux-arm64 +0 -0
  14. package/dist/conformance/agent37.d.ts +96 -0
  15. package/dist/conformance/agent37.js +154 -0
  16. package/dist/conformance/cases/apps.d.ts +5 -0
  17. package/dist/conformance/cases/apps.js +160 -73
  18. package/dist/conformance/cases/health.js +14 -0
  19. package/dist/conformance/cases/index.js +2 -0
  20. package/dist/conformance/cases/provider.js +27 -1
  21. package/dist/conformance/cases/screen.d.ts +3 -0
  22. package/dist/conformance/cases/screen.js +18 -0
  23. package/dist/conformance/cases/settings.d.ts +29 -23
  24. package/dist/conformance/cases/settings.js +76 -58
  25. package/dist/conformance/cases/touch.js +19 -17
  26. package/dist/conformance/cases/ui.d.ts +2 -0
  27. package/dist/conformance/cases/ui.js +475 -0
  28. package/dist/conformance/cli.d.ts +9 -0
  29. package/dist/conformance/cli.js +28 -3
  30. package/dist/conformance/e2b.d.ts +6 -0
  31. package/dist/conformance/e2b.js +9 -2
  32. package/dist/conformance/fixture.d.ts +1 -1
  33. package/dist/conformance/fixture.js +25 -1
  34. package/dist/conformance/modal.d.ts +17 -13
  35. package/dist/conformance/modal.js +18 -9
  36. package/dist/conformance/orgo.d.ts +3 -3
  37. package/dist/conformance/orgo.js +6 -8
  38. package/dist/conformance/phone-harness.d.ts +6 -2
  39. package/dist/conformance/phone-harness.js +21 -4
  40. package/dist/conformance/report.js +1 -1
  41. package/dist/conformance/runner.js +23 -4
  42. package/dist/conformance/sweep.d.ts +50 -0
  43. package/dist/conformance/sweep.js +187 -0
  44. package/dist/conformance/types.d.ts +11 -3
  45. package/dist/conformance/ui-fixture.d.ts +56 -0
  46. package/dist/conformance/ui-fixture.js +43 -0
  47. package/dist/create-requests.d.ts +51 -0
  48. package/dist/create-requests.js +121 -0
  49. package/dist/daytona.d.ts +2 -4
  50. package/dist/daytona.js +3 -2
  51. package/dist/descriptor.d.ts +5 -0
  52. package/dist/descriptor.js +2 -0
  53. package/dist/descriptors/agent37.d.ts +41 -0
  54. package/dist/descriptors/agent37.js +28 -0
  55. package/dist/descriptors/index.d.ts +38 -2
  56. package/dist/descriptors/index.js +4 -2
  57. package/dist/descriptors/orgo.d.ts +2 -1
  58. package/dist/descriptors/orgo.js +3 -2
  59. package/dist/descriptors/phone-harness.d.ts +1 -1
  60. package/dist/descriptors/phone-harness.js +2 -2
  61. package/dist/docker.d.ts +7 -4
  62. package/dist/docker.js +271 -29
  63. package/dist/e2b.d.ts +9 -165
  64. package/dist/e2b.js +282 -1342
  65. package/dist/fake-ui-driver.d.ts +97 -0
  66. package/dist/fake-ui-driver.js +717 -0
  67. package/dist/host.d.ts +182 -0
  68. package/dist/host.js +1 -0
  69. package/dist/hosted/process.d.ts +67 -0
  70. package/dist/hosted/process.js +228 -0
  71. package/dist/hosted/provider.d.ts +146 -0
  72. package/dist/hosted/provider.js +1364 -0
  73. package/dist/hosted/scripts.d.ts +76 -0
  74. package/dist/{child.js → hosted/scripts.js} +93 -12
  75. package/dist/index.d.ts +7 -3
  76. package/dist/index.js +7 -4
  77. package/dist/kernel.d.ts +2 -4
  78. package/dist/kernel.js +2 -1
  79. package/dist/kinds.d.ts +8 -1
  80. package/dist/kinds.js +20 -4
  81. package/dist/local-chrome.d.ts +2 -4
  82. package/dist/local-chrome.js +2 -1
  83. package/dist/modal.d.ts +23 -181
  84. package/dist/modal.js +271 -1244
  85. package/dist/orgo-channel.d.ts +3 -2
  86. package/dist/orgo-channel.js +5 -2
  87. package/dist/orgo-desktop.d.ts +9 -4
  88. package/dist/orgo-desktop.js +33 -13
  89. package/dist/orgo-workspaces.d.ts +47 -0
  90. package/dist/orgo-workspaces.js +94 -0
  91. package/dist/orgo.d.ts +10 -4
  92. package/dist/orgo.js +30 -12
  93. package/dist/phone-harness.d.ts +31 -22
  94. package/dist/phone-harness.js +510 -698
  95. package/dist/png.d.ts +4 -0
  96. package/dist/png.js +27 -0
  97. package/dist/protocol.d.ts +335 -32
  98. package/dist/protocol.js +96 -3
  99. package/dist/provider.d.ts +34 -6
  100. package/dist/provider.js +16 -0
  101. package/dist/result.d.ts +1 -1
  102. package/dist/surface/api.d.ts +248 -0
  103. package/dist/surface/api.js +1 -0
  104. package/dist/surface/core.d.ts +42 -0
  105. package/dist/surface/core.js +393 -0
  106. package/dist/surface/index.d.ts +5 -0
  107. package/dist/surface/index.js +3 -0
  108. package/dist/surface/outline.d.ts +8 -0
  109. package/dist/surface/outline.js +50 -0
  110. package/dist/surface/script.d.ts +10 -0
  111. package/dist/surface/script.js +92 -0
  112. package/dist/ui-engine.d.ts +114 -0
  113. package/dist/ui-engine.js +798 -0
  114. package/package.json +17 -1
  115. package/dist/child.d.ts +0 -42
  116. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  117. package/dist/conformance/e2b-diagnose.js +0 -61
  118. package/dist/conformance/e2b-sweep.d.ts +0 -18
  119. package/dist/conformance/e2b-sweep.js +0 -132
  120. package/dist/conformance/modal-sweep.d.ts +0 -22
  121. package/dist/conformance/modal-sweep.js +0 -213
@@ -0,0 +1,146 @@
1
+ import { type Readable, Writable } from "node:stream";
2
+ import { type HelloResult } from "./protocol.js";
3
+ import { type ComputerConnection, type ComputerProvider } from "./provider.js";
4
+ import { type Result } from "./result.js";
5
+ export declare const ATTACH_PATH = "/v2/computers/attach";
6
+ /** The WebSocket subprotocol a driver asks for: the protocol version it speaks. Serve answers with it or refuses. */
7
+ export declare const ATTACH_SUBPROTOCOL = "agentrun.computer.0.2";
8
+ /** Each side pings this often (WebSocket ping frames, not JSON-RPC), so a NAT keeps the path open. */
9
+ export declare const ATTACH_HEARTBEAT_MS = 20000;
10
+ /** A side that hears nothing, not even a pong, for this long closes the socket with ATTACH_CLOSE.idle. */
11
+ export declare const ATTACH_IDLE_MS = 60000;
12
+ /** Serve waits this long for a new socket's hello answer; a socket whose driver pings but never answers is closed idle. */
13
+ export declare const ATTACH_HELLO_MS = 10000;
14
+ /** A pairing code lives this long, and is good once. */
15
+ export declare const PAIRING_CODE_TTL_MS: number;
16
+ /** Eight characters a person reads off a screen and types, with no 0, O, 1 or I: "K7PD-W3QX". */
17
+ export declare const PAIRING_CODE_PATTERN: RegExp;
18
+ /** The longest a driver waits between two dials. */
19
+ export declare const ATTACH_REDIAL_MAX_MS = 60000;
20
+ /** Why a socket closed, as its close code. A driver dials again after any code but the four that need a person. */
21
+ export declare const ATTACH_CLOSE: {
22
+ readonly normal: 1000;
23
+ /** Serve is restarting or the driver is quitting. */
24
+ readonly going: 1001;
25
+ /** A binary frame: the binding is text frames only. */
26
+ readonly binary: 1003;
27
+ /** A frame over maxLineBytes. */
28
+ readonly tooBig: 1009;
29
+ /** The computer's hello is not what it paired as (another kind or os): pair again. */
30
+ readonly mismatch: 4400;
31
+ /** The token is unknown or was revoked: pair again. */
32
+ readonly unauthorized: 4401;
33
+ /** Nothing heard for ATTACH_IDLE_MS, or no answer to serve's hello within ATTACH_HELLO_MS. */
34
+ readonly idle: 4408;
35
+ /** The same computer dialed again; the older socket is closed. */
36
+ readonly replaced: 4409;
37
+ /** The driver speaks another protocol version, or its hello lacks a group its kind needs (kindServed): update it. */
38
+ readonly protocol: 4426;
39
+ };
40
+ /** Whether a driver dials again after a close with this code; false means a person must act (pair, update). */
41
+ export declare const redials: (code: number) => boolean;
42
+ /** How long a driver waits before its redial number `attempt` (from 0): 1 s doubling to ATTACH_REDIAL_MAX_MS, less up to a fifth at random. */
43
+ export declare function redialDelay(attempt: number, random?: () => number): number;
44
+ /** What a driver sends to trade a pairing code for its computer's token: POST /v2/computers/pair. */
45
+ export interface PairRequest {
46
+ code: string;
47
+ /** What the person calls the machine: "Ada's MacBook". */
48
+ name: string;
49
+ /** The driver's hello, so serve knows what it pairs: kind, os, groups and features. */
50
+ hello: HelloResult;
51
+ }
52
+ /** Serve's answer: the computer's id and its token, a secret the driver keeps in the OS's keychain. */
53
+ export interface PairResult {
54
+ computer: string;
55
+ token: string;
56
+ }
57
+ /**
58
+ * One WebSocket as serve holds it, whatever the library: text frames in and out, and its close. The implementation
59
+ * answers pings and sends its own every ATTACH_HEARTBEAT_MS, closes with ATTACH_CLOSE.idle after ATTACH_IDLE_MS of
60
+ * silence, closes a binary frame with ATTACH_CLOSE.binary and one over maxLineBytes with ATTACH_CLOSE.tooBig.
61
+ */
62
+ export interface AttachSocket {
63
+ send(text: string): void;
64
+ close(code: number, reason: string): void;
65
+ onText(listener: (text: string) => void): void;
66
+ /** Called once, when the socket closed, by either side or by a drop. */
67
+ onClose(listener: (code: number, reason: string) => void): void;
68
+ }
69
+ /**
70
+ * A socket as the byte streams of the stdio binding: each frame in becomes a line, each line out a frame. Both serve's
71
+ * client and a driver written in TypeScript (the fake ui driver) speak through it, so the binding adds nothing to the
72
+ * wire. A raw newline in a frame can only be whitespace between JSON tokens, so it is read as a space.
73
+ */
74
+ export declare function socketStreams(socket: AttachSocket): {
75
+ readable: Readable;
76
+ writable: Writable;
77
+ };
78
+ /** A paired computer, as serve's store keeps it. Its token is not here: serve keeps only the token's hash. */
79
+ export interface PairedComputer {
80
+ id: string;
81
+ name: string;
82
+ /** What it paired as: its hello at pairing. A later hello of another kind or os is refused (ATTACH_CLOSE.mismatch). */
83
+ hello: HelloResult;
84
+ labels: Record<string, string>;
85
+ }
86
+ /**
87
+ * Why a hello may not stand for a paired computer, or undefined. The protocol version must be the server's; the
88
+ * driver's own version may be any: a person's installed app updates on its own schedule, and the server cannot
89
+ * replace it the way a provider replaces a copied daemon.
90
+ */
91
+ export declare function helloMismatch(paired: PairedComputer, hello: HelloResult): {
92
+ code: number;
93
+ message: string;
94
+ } | undefined;
95
+ /**
96
+ * Serve's attached computers in one process: the live connection of each, by its id. Serve's attach route checks the
97
+ * token, finds the paired computer and hands the socket to accept. A computer has one connection, serve's, which every
98
+ * caller shares (one run holds the computer at a time); a new socket from the same computer replaces the old one.
99
+ */
100
+ export declare class AttachHub {
101
+ #private;
102
+ constructor({ helloMs }?: {
103
+ helloMs?: number;
104
+ });
105
+ /**
106
+ * Takes a computer's new socket: calls hello on it, and keeps it when the hello is what the computer paired as. The
107
+ * newest dial wins whichever hello answers first: a socket whose hello ends after a newer one went live is closed,
108
+ * never put in its place.
109
+ */
110
+ accept(paired: PairedComputer, socket: AttachSocket): Promise<Result<HelloResult>>;
111
+ /** Whether the computer is attached now. */
112
+ online(id: string): boolean;
113
+ /** The hello of the computer's live connection: its driver's version and groups now, which an update may change. */
114
+ hello(id: string): HelloResult | undefined;
115
+ /**
116
+ * A connection over the computer's one socket: closing it leaves the socket open, cancels its calls still running and
117
+ * refuses its later ones, and the run's release closes every connection it was given, so a run done with the computer
118
+ * cannot reach it once another run holds it. Undefined while it is not attached.
119
+ */
120
+ connection(id: string): ComputerConnection | undefined;
121
+ /**
122
+ * Holds the computer for a run, with the run's labels, until its deadline (an agent's hold has none): there the hold
123
+ * ends as a release does, closing the run's connections, and the person's machine runs on. False when another run
124
+ * holds it. The hold's token names this hold and no later one: unclaim with it never ends another run's.
125
+ */
126
+ claim(id: string, labels: Record<string, string>, deadline?: Date): string | undefined;
127
+ /** The labels of the run that holds the computer, or undefined. */
128
+ claimed(id: string): Record<string, string> | undefined;
129
+ /** The token of the hold on the computer now, or undefined. */
130
+ hold(id: string): string | undefined;
131
+ /** The deadline of the run that holds the computer, or undefined (no hold, or an agent's). */
132
+ deadline(id: string): Date | undefined;
133
+ /**
134
+ * Ends the hold named by its token, and closes the connections it was given. A token of a hold already ended (a late
135
+ * release, after the deadline gave the computer to another run) ends nothing: false.
136
+ */
137
+ unclaim(id: string, hold: string): boolean;
138
+ /** Ends a computer's attachment: its token was revoked, or the computer was removed. */
139
+ revoke(id: string, why: string): void;
140
+ }
141
+ /**
142
+ * One paired computer as a provider, id "attached": its capabilities are what it paired as. create claims it for a
143
+ * run (refused while it is offline or another run holds it) and release ends the claim; a person's machine is never
144
+ * made, stopped or deleted by a run. It has no init of ours, so its daemon mode is none.
145
+ */
146
+ export declare function attachedProvider(paired: PairedComputer, hub: AttachHub): ComputerProvider;
package/dist/attach.js ADDED
@@ -0,0 +1,469 @@
1
+ // The attach binding (spec/computer/attach.md), serve's side, written against a socket interface so it runs with any
2
+ // WebSocket library and in tests with none. A driver on a person's own machine dials wss://<serve>/v2/computers/attach
3
+ // with the token it got by pairing, and the same JSON-RPC messages travel as text frames, one message per frame. Serve
4
+ // is the caller: it sends hello first, then the run's calls. The AttachHub keeps one live connection per paired
5
+ // computer; attachedProvider hands that computer to a run as a provider, one run at a time.
6
+ import { randomUUID } from "node:crypto";
7
+ import { PassThrough, Writable } from "node:stream";
8
+ import { DaemonClient } from "./client.js";
9
+ import { kindServed } from "./kinds.js";
10
+ import { PROTOCOL_VERSION } from "./protocol.js";
11
+ import { checkLifetime, kindRefusals, runLifetimeMs } from "./provider.js";
12
+ import { fail, ok } from "./result.js";
13
+ export const ATTACH_PATH = "/v2/computers/attach";
14
+ /** The WebSocket subprotocol a driver asks for: the protocol version it speaks. Serve answers with it or refuses. */
15
+ export const ATTACH_SUBPROTOCOL = `agentrun.computer.${PROTOCOL_VERSION}`;
16
+ /** Each side pings this often (WebSocket ping frames, not JSON-RPC), so a NAT keeps the path open. */
17
+ export const ATTACH_HEARTBEAT_MS = 20_000;
18
+ /** A side that hears nothing, not even a pong, for this long closes the socket with ATTACH_CLOSE.idle. */
19
+ export const ATTACH_IDLE_MS = 60_000;
20
+ /** Serve waits this long for a new socket's hello answer; a socket whose driver pings but never answers is closed idle. */
21
+ export const ATTACH_HELLO_MS = 10_000;
22
+ /** A pairing code lives this long, and is good once. */
23
+ export const PAIRING_CODE_TTL_MS = 10 * 60_000;
24
+ /** Eight characters a person reads off a screen and types, with no 0, O, 1 or I: "K7PD-W3QX". */
25
+ export const PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/;
26
+ /** The longest a driver waits between two dials. */
27
+ export const ATTACH_REDIAL_MAX_MS = 60_000;
28
+ /** Why a socket closed, as its close code. A driver dials again after any code but the four that need a person. */
29
+ export const ATTACH_CLOSE = {
30
+ normal: 1000,
31
+ /** Serve is restarting or the driver is quitting. */
32
+ going: 1001,
33
+ /** A binary frame: the binding is text frames only. */
34
+ binary: 1003,
35
+ /** A frame over maxLineBytes. */
36
+ tooBig: 1009,
37
+ /** The computer's hello is not what it paired as (another kind or os): pair again. */
38
+ mismatch: 4400,
39
+ /** The token is unknown or was revoked: pair again. */
40
+ unauthorized: 4401,
41
+ /** Nothing heard for ATTACH_IDLE_MS, or no answer to serve's hello within ATTACH_HELLO_MS. */
42
+ idle: 4408,
43
+ /** The same computer dialed again; the older socket is closed. */
44
+ replaced: 4409,
45
+ /** The driver speaks another protocol version, or its hello lacks a group its kind needs (kindServed): update it. */
46
+ protocol: 4426,
47
+ };
48
+ const STOPS = new Set([ATTACH_CLOSE.mismatch, ATTACH_CLOSE.unauthorized, ATTACH_CLOSE.protocol]);
49
+ /** Whether a driver dials again after a close with this code; false means a person must act (pair, update). */
50
+ export const redials = (code) => !STOPS.has(code);
51
+ /** How long a driver waits before its redial number `attempt` (from 0): 1 s doubling to ATTACH_REDIAL_MAX_MS, less up to a fifth at random. */
52
+ export function redialDelay(attempt, random = Math.random) {
53
+ const base = Math.min(ATTACH_REDIAL_MAX_MS, 1000 * 2 ** Math.max(0, Math.min(attempt, 16)));
54
+ return Math.round(base * (1 - random() / 5));
55
+ }
56
+ /**
57
+ * A socket as the byte streams of the stdio binding: each frame in becomes a line, each line out a frame. Both serve's
58
+ * client and a driver written in TypeScript (the fake ui driver) speak through it, so the binding adds nothing to the
59
+ * wire. A raw newline in a frame can only be whitespace between JSON tokens, so it is read as a space.
60
+ */
61
+ export function socketStreams(socket) {
62
+ const readable = new PassThrough();
63
+ let pending = "";
64
+ let open = true;
65
+ socket.onText((text) => {
66
+ if (open)
67
+ readable.write(`${text.replace(/\r?\n/g, " ")}\n`);
68
+ });
69
+ socket.onClose(() => {
70
+ open = false;
71
+ readable.end();
72
+ });
73
+ const writable = new Writable({
74
+ write(chunk, _encoding, done) {
75
+ pending += chunk.toString();
76
+ for (let at = pending.indexOf("\n"); at >= 0; at = pending.indexOf("\n")) {
77
+ const line = pending.slice(0, at);
78
+ pending = pending.slice(at + 1);
79
+ if (open && line.trim() !== "")
80
+ socket.send(line);
81
+ }
82
+ done();
83
+ },
84
+ final(done) {
85
+ if (open)
86
+ socket.close(ATTACH_CLOSE.normal, "the connection was closed");
87
+ done();
88
+ },
89
+ });
90
+ return { readable, writable };
91
+ }
92
+ /** Whether protocol version a ("0.3") comes after b ("0.2"), part by part as numbers. */
93
+ function laterProtocol(a, b) {
94
+ const [x, y] = [a, b].map((version) => version.split(".").map((part) => Number.parseInt(part, 10) || 0));
95
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
96
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
97
+ return (x[i] ?? 0) > (y[i] ?? 0);
98
+ return false;
99
+ }
100
+ /**
101
+ * Why a hello may not stand for a paired computer, or undefined. The protocol version must be the server's; the
102
+ * driver's own version may be any: a person's installed app updates on its own schedule, and the server cannot
103
+ * replace it the way a provider replaces a copied daemon.
104
+ */
105
+ export function helloMismatch(paired, hello) {
106
+ // Serve names no OS and no driver app: one way to update, in the same words for every computer.
107
+ const update = `update the driver on ${paired.name} (the download is on the console's Computers page)`;
108
+ const said = hello;
109
+ if (typeof said !== "object" || said === null || typeof said.protocol !== "string" || typeof said.version !== "string") {
110
+ return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver answered hello without its protocol and version: ${update}` };
111
+ }
112
+ if (hello.protocol !== PROTOCOL_VERSION) {
113
+ const newer = laterProtocol(hello.protocol, PROTOCOL_VERSION) ? "the server is older: it is updated by whoever runs it" : update;
114
+ return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver ${hello.version} speaks protocol ${hello.protocol}, and this server ${PROTOCOL_VERSION}: ${newer}` };
115
+ }
116
+ // Every field serve reads off a live hello (the provider's capabilities, the kind check): one missing is refused
117
+ // here, never met later as a throw.
118
+ const missing = [
119
+ ...(typeof said.os === "string" ? [] : ["os"]),
120
+ ...(typeof said.kind === "string" ? [] : ["kind"]),
121
+ ...(typeof said.arch === "string" ? [] : ["arch"]),
122
+ ...(Array.isArray(said.groups) && said.groups.every((group) => typeof group === "string") ? [] : ["groups"]),
123
+ ];
124
+ if (missing.length > 0) {
125
+ return { code: ATTACH_CLOSE.protocol, message: `${paired.name}'s driver ${hello.version} answered a protocol ${PROTOCOL_VERSION} hello without ${missing.join(", ")}: ${update}` };
126
+ }
127
+ if (hello.kind !== paired.hello.kind || hello.os !== paired.hello.os) {
128
+ return { code: ATTACH_CLOSE.mismatch, message: `${paired.name} paired as a ${paired.hello.os} ${paired.hello.kind} and now says ${hello.os} ${hello.kind}: pair it again` };
129
+ }
130
+ // A computer that lacks a group its kind needs can't be given to an agent: refused at connect, in the hello's own
131
+ // words for what it is, never at a run's first call.
132
+ const lacks = kindServed(hello);
133
+ if (lacks.length > 0) {
134
+ return { code: ATTACH_CLOSE.protocol, message: `${paired.name} says it is a ${hello.os} ${hello.kind} but declares no ${lacks.join(", ")}: ${update}` };
135
+ }
136
+ return undefined;
137
+ }
138
+ /**
139
+ * Serve's attached computers in one process: the live connection of each, by its id. Serve's attach route checks the
140
+ * token, finds the paired computer and hands the socket to accept. A computer has one connection, serve's, which every
141
+ * caller shares (one run holds the computer at a time); a new socket from the same computer replaces the old one.
142
+ */
143
+ export class AttachHub {
144
+ #live = new Map();
145
+ /** The run holding each computer: the hold's own token, its labels, and its deadline with the timer that ends it. */
146
+ #claims = new Map();
147
+ /** The sockets still saying hello, by computer: a revoke closes them too, so none comes back after it. */
148
+ #pending = new Map();
149
+ /** Each computer's connections given out, by the function that closes one. */
150
+ #given = new Map();
151
+ /** The dials taken so far, in order, across every computer: a dial's number is taken before its hello is awaited. */
152
+ #dials = 0;
153
+ /** How long a new socket's hello may take (ATTACH_HELLO_MS; shorter in tests). */
154
+ #helloMs;
155
+ constructor({ helloMs = ATTACH_HELLO_MS } = {}) {
156
+ this.#helloMs = helloMs;
157
+ }
158
+ /**
159
+ * Takes a computer's new socket: calls hello on it, and keeps it when the hello is what the computer paired as. The
160
+ * newest dial wins whichever hello answers first: a socket whose hello ends after a newer one went live is closed,
161
+ * never put in its place.
162
+ */
163
+ async accept(paired, socket) {
164
+ const dial = ++this.#dials;
165
+ const pending = this.#pending.get(paired.id) ?? new Set();
166
+ this.#pending.set(paired.id, pending);
167
+ pending.add(socket);
168
+ const client = new DaemonClient(socketStreams(socket));
169
+ // Listened for before the hello is awaited, so a close in that wait is never missed: it keeps the socket out of
170
+ // #live, or takes it out once in.
171
+ let closed = false;
172
+ let mine;
173
+ socket.onClose(() => {
174
+ closed = true;
175
+ if (mine !== undefined && this.#live.get(paired.id) === mine)
176
+ this.#live.delete(paired.id);
177
+ });
178
+ // Bounded: a driver that answers pings but never hello would otherwise hold a socket open forever.
179
+ const hello = await client.call("hello", { client: "agentrun-serve" }, { signal: AbortSignal.timeout(this.#helloMs) });
180
+ const revoked = !pending.delete(socket);
181
+ if (pending.size === 0 && this.#pending.get(paired.id) === pending)
182
+ this.#pending.delete(paired.id);
183
+ if (revoked) {
184
+ const why = `${paired.name} was removed while it said hello`;
185
+ socket.close(ATTACH_CLOSE.unauthorized, why);
186
+ return fail("refused", why);
187
+ }
188
+ if (!hello.ok && hello.error.code === "aborted") {
189
+ const why = `${paired.name}'s driver did not answer hello within ${this.#helloMs / 1000} s`;
190
+ socket.close(ATTACH_CLOSE.idle, why);
191
+ return fail("timeout", why);
192
+ }
193
+ if (!hello.ok) {
194
+ socket.close(ATTACH_CLOSE.going, `hello failed: ${hello.error.message}`);
195
+ return hello;
196
+ }
197
+ const wrong = helloMismatch(paired, hello.value);
198
+ if (wrong !== undefined) {
199
+ socket.close(wrong.code, wrong.message);
200
+ return fail("refused", wrong.message);
201
+ }
202
+ const older = this.#live.get(paired.id);
203
+ if (older !== undefined && older.dial > dial) {
204
+ const why = `${paired.name} dialed again while this socket said hello, and the newer one is live`;
205
+ socket.close(ATTACH_CLOSE.replaced, why);
206
+ return fail("refused", why);
207
+ }
208
+ if (closed)
209
+ return fail("gone", `${paired.name}'s socket closed while it said hello`);
210
+ mine = { socket, client, hello: hello.value, dial };
211
+ this.#live.set(paired.id, mine);
212
+ older?.socket.close(ATTACH_CLOSE.replaced, "the computer dialed again");
213
+ return hello;
214
+ }
215
+ /** Whether the computer is attached now. */
216
+ online(id) {
217
+ return this.#live.has(id);
218
+ }
219
+ /** The hello of the computer's live connection: its driver's version and groups now, which an update may change. */
220
+ hello(id) {
221
+ return this.#live.get(id)?.hello;
222
+ }
223
+ /**
224
+ * A connection over the computer's one socket: closing it leaves the socket open, cancels its calls still running and
225
+ * refuses its later ones, and the run's release closes every connection it was given, so a run done with the computer
226
+ * cannot reach it once another run holds it. Undefined while it is not attached.
227
+ */
228
+ connection(id) {
229
+ const live = this.#live.get(id);
230
+ if (live === undefined)
231
+ return undefined;
232
+ const stop = new AbortController();
233
+ const given = this.#given.get(id) ?? new Set();
234
+ this.#given.set(id, given);
235
+ const end = () => {
236
+ given.delete(end);
237
+ stop.abort();
238
+ };
239
+ given.add(end);
240
+ // Every caller's calls go over the computer's live socket, looked up per call: a drop fails the calls in flight
241
+ // with gone. A new socket is a new session whose refs, states and handles are its own, and an old one could name
242
+ // something else there: the first call after a redial is refused gone, saying so, and the calls after it go over
243
+ // the new socket.
244
+ let using = live;
245
+ const shared = {
246
+ call: (method, params, options) => {
247
+ if (stop.signal.aborted)
248
+ return Promise.resolve(fail("gone", "this connection to the computer was closed: connect again"));
249
+ const now = this.#live.get(id);
250
+ if (now === undefined)
251
+ return Promise.resolve(fail("gone", "the computer is not attached now: it dials back on its own, so try again shortly"));
252
+ if (now !== using) {
253
+ using = now;
254
+ return Promise.resolve(fail("gone", "the computer dialed back since the last call: its refs, states and handles from before are void, so observe again (this call did not run)"));
255
+ }
256
+ return now.client.call(method, params, { ...options, signal: options?.signal === undefined ? stop.signal : AbortSignal.any([options.signal, stop.signal]) });
257
+ },
258
+ close: end,
259
+ };
260
+ return { client: shared, hello: live.hello, close: async () => end() };
261
+ }
262
+ /** Closes every connection given out for the computer. */
263
+ #closeGiven(id) {
264
+ for (const end of [...(this.#given.get(id) ?? [])])
265
+ end();
266
+ this.#given.delete(id);
267
+ }
268
+ /**
269
+ * Holds the computer for a run, with the run's labels, until its deadline (an agent's hold has none): there the hold
270
+ * ends as a release does, closing the run's connections, and the person's machine runs on. False when another run
271
+ * holds it. The hold's token names this hold and no later one: unclaim with it never ends another run's.
272
+ */
273
+ claim(id, labels, deadline) {
274
+ this.#expire(id);
275
+ if (this.#claims.has(id))
276
+ return undefined;
277
+ const hold = randomUUID().replaceAll("-", "").slice(0, 16);
278
+ const timer = deadline === undefined ? undefined : setTimeout(() => this.unclaim(id, hold), Math.max(0, deadline.getTime() - Date.now()));
279
+ timer?.unref?.();
280
+ this.#claims.set(id, { hold, labels: { ...labels }, ...(deadline === undefined ? {} : { deadline, timer }) });
281
+ return hold;
282
+ }
283
+ /** The labels of the run that holds the computer, or undefined. */
284
+ claimed(id) {
285
+ this.#expire(id);
286
+ return this.#claims.get(id)?.labels;
287
+ }
288
+ /** The token of the hold on the computer now, or undefined. */
289
+ hold(id) {
290
+ this.#expire(id);
291
+ return this.#claims.get(id)?.hold;
292
+ }
293
+ /** The deadline of the run that holds the computer, or undefined (no hold, or an agent's). */
294
+ deadline(id) {
295
+ this.#expire(id);
296
+ return this.#claims.get(id)?.deadline;
297
+ }
298
+ /**
299
+ * Ends the hold named by its token, and closes the connections it was given. A token of a hold already ended (a late
300
+ * release, after the deadline gave the computer to another run) ends nothing: false.
301
+ */
302
+ unclaim(id, hold) {
303
+ const held = this.#claims.get(id);
304
+ if (held === undefined || held.hold !== hold)
305
+ return false;
306
+ clearTimeout(held.timer);
307
+ this.#claims.delete(id);
308
+ this.#closeGiven(id);
309
+ return true;
310
+ }
311
+ /** A hold past its deadline ends at once, whether or not its timer has run yet. */
312
+ #expire(id) {
313
+ const held = this.#claims.get(id);
314
+ if (held?.deadline !== undefined && held.deadline.getTime() <= Date.now())
315
+ this.unclaim(id, held.hold);
316
+ }
317
+ /** Ends a computer's attachment: its token was revoked, or the computer was removed. */
318
+ revoke(id, why) {
319
+ const pending = this.#pending.get(id);
320
+ this.#pending.delete(id);
321
+ for (const socket of pending ?? [])
322
+ socket.close(ATTACH_CLOSE.unauthorized, why);
323
+ pending?.clear();
324
+ this.#closeGiven(id);
325
+ this.#live.get(id)?.socket.close(ATTACH_CLOSE.unauthorized, why);
326
+ this.#live.delete(id);
327
+ clearTimeout(this.#claims.get(id)?.timer);
328
+ this.#claims.delete(id);
329
+ }
330
+ }
331
+ const ATTACHED_NOTE = "an attached computer is a person's own machine: release ends the run's hold on it, and deletes nothing";
332
+ /**
333
+ * One paired computer as a provider, id "attached": its capabilities are what it paired as. create claims it for a
334
+ * run (refused while it is offline or another run holds it) and release ends the claim; a person's machine is never
335
+ * made, stopped or deleted by a run. It has no init of ours, so its daemon mode is none.
336
+ */
337
+ export function attachedProvider(paired, hub) {
338
+ /** What the computer says now: its live hello while attached (an update may add groups), else what it paired as. */
339
+ const now = () => hub.hello(paired.id) ?? paired.hello;
340
+ const capabilities = () => ({
341
+ kind: paired.hello.kind,
342
+ lifetime: "vendor",
343
+ network: ["open"],
344
+ isolation: "machine",
345
+ os: paired.hello.os,
346
+ daemon: "none",
347
+ groups: [...now().groups],
348
+ maxLifetimeMs: 24 * 60 * 60_000,
349
+ release: ["delete"],
350
+ });
351
+ const ref = { id: paired.id, name: paired.name };
352
+ // A run's ref names its hold, `<computer id>.<hold token>`, so a call under a hold that ended (released, or at its
353
+ // deadline) never acts on the next run's: release ends only its own hold, connect and attach refuse a stale one.
354
+ const holdRef = (hold) => ({ id: `${paired.id}.${hold}`, name: paired.name });
355
+ const heldRef = () => {
356
+ const hold = hub.hold(paired.id);
357
+ return hold === undefined ? ref : holdRef(hold);
358
+ };
359
+ /** The computer itself, a hold (with whether it is the hold now), or undefined for another provider's id. */
360
+ const named = (asked) => {
361
+ if (asked.id === paired.id)
362
+ return { current: true };
363
+ if (!asked.id.startsWith(`${paired.id}.`))
364
+ return undefined;
365
+ const hold = asked.id.slice(paired.id.length + 1);
366
+ return { hold, current: hub.hold(paired.id) === hold };
367
+ };
368
+ const mine = (asked) => named(asked) !== undefined;
369
+ /** The hold each create request made: a request id makes one hold, ever. */
370
+ const holdsBy = new Map();
371
+ const ended = () => fail("gone", `this run's hold on ${paired.name} has ended (released, or at its deadline): another run may hold it now`);
372
+ const unknown = (id) => fail("not_found", `no attached computer ${id}: this provider is ${paired.name}'s (${paired.id})`);
373
+ const offline = () => fail("gone", `${paired.name} is not attached now: open its driver, which dials this server`);
374
+ const holds = (labels, wanted) => Object.entries(wanted).every(([key, value]) => labels[key] === value);
375
+ /** Why a network other than open is refused: a run never narrows a person's own machine's network. */
376
+ const networkRefusal = (asked) => `${paired.name} is a person's own machine on its own network, which a run cannot block or limit: network ${JSON.stringify(asked)} is refused; ask for network "open"`;
377
+ return {
378
+ id: "attached",
379
+ // The driver's version is the computer's, whatever it is: the provider never refuses a newer or older build of one
380
+ // protocol, because it cannot replace a person's app the way it replaces a copied daemon.
381
+ get version() {
382
+ return now().version;
383
+ },
384
+ capabilities,
385
+ check: (spec) => [
386
+ ...kindRefusals(capabilities()),
387
+ ...(spec.owner === undefined ? checkLifetime(spec.lifetimeMs, capabilities()) : []),
388
+ ...(spec.network === "open" ? [] : [{ field: "network", message: networkRefusal(spec.network) }]),
389
+ ],
390
+ async create(spec, context) {
391
+ const refusals = this.check(spec);
392
+ if (refusals.length > 0)
393
+ return fail("refused", refusals.map((refusal) => refusal.message).join("; "));
394
+ if (typeof context?.requestId !== "string" || context.requestId === "")
395
+ return fail("invalid", "create needs a request id (CreateContext.requestId): pass the same one to retry the same request");
396
+ // One hold per request id (provider.md, Idempotent create): a retry while it holds answers it, and after it ended
397
+ // is refused, so a retry never takes the machine from the run that holds it next.
398
+ const before = holdsBy.get(context.requestId);
399
+ if (before !== undefined) {
400
+ if (hub.hold(paired.id) !== before)
401
+ return fail("exists", `${paired.name}'s hold ${before} was made for this request and has ended: create with a new request id`);
402
+ // The hold carries the labels of the request that made it: a retry that asks for other labels is another request.
403
+ const claimed = hub.claimed(paired.id) ?? {};
404
+ const asked = spec.labels ?? {};
405
+ const same = Object.keys(asked).length === Object.keys(claimed).length && holds(claimed, asked);
406
+ if (!same)
407
+ return fail("exists", `${paired.name}'s hold ${before} was made for this request with other labels: create with a new request id`);
408
+ return ok({ ...holdRef(before), notes: [ATTACHED_NOTE] });
409
+ }
410
+ if (!hub.online(paired.id))
411
+ return offline();
412
+ // A run's hold ends at its lifetime, released or not: a run that never releases cannot keep the machine from the next.
413
+ const deadline = spec.owner === undefined ? new Date(Date.now() + runLifetimeMs(spec)) : undefined;
414
+ const hold = hub.claim(paired.id, spec.labels ?? {}, deadline);
415
+ if (hold === undefined)
416
+ return fail("refused", `${paired.name} is held by another run: one run at a time`);
417
+ holdsBy.set(context.requestId, hold);
418
+ return ok({ ...holdRef(hold), notes: [ATTACHED_NOTE] });
419
+ },
420
+ async attach(asked) {
421
+ if ("id" in asked) {
422
+ const which = named(asked);
423
+ if (which === undefined)
424
+ return unknown(asked.id);
425
+ if (!which.current)
426
+ return ended();
427
+ }
428
+ else if (!holds({ ...paired.labels, ...hub.claimed(paired.id) }, asked.labels))
429
+ return unknown(JSON.stringify(asked.labels));
430
+ const deadline = hub.deadline(paired.id);
431
+ const found = "id" in asked ? { id: asked.id, name: paired.name } : heldRef();
432
+ return ok({ ...found, spec: { image: "attached", user: "the person's own", network: { other: "the machine's own network" }, kind: paired.hello.kind, ...(deadline === undefined ? {} : { deadline }) } });
433
+ },
434
+ async list(labels) {
435
+ const have = { ...paired.labels, ...hub.claimed(paired.id) };
436
+ if (!holds(have, labels))
437
+ return ok([]);
438
+ return ok([{ ref: heldRef(), labels: have, deadline: hub.deadline(paired.id), state: hub.online(paired.id) ? "running" : "stopped", network: { other: "the machine's own network" } }]);
439
+ },
440
+ async network(asked, policy) {
441
+ if (!mine(asked))
442
+ return unknown(asked.id);
443
+ if (policy !== undefined && policy !== "open")
444
+ return fail("refused", networkRefusal(policy));
445
+ return ok({ other: "the machine's own network" });
446
+ },
447
+ async connect(asked) {
448
+ const which = named(asked);
449
+ if (which === undefined)
450
+ return unknown(asked.id);
451
+ if (!which.current)
452
+ return ended();
453
+ const connection = hub.connection(paired.id);
454
+ return connection === undefined ? offline() : ok(connection);
455
+ },
456
+ async release(asked, how) {
457
+ const which = named(asked);
458
+ if (which === undefined)
459
+ return unknown(asked.id);
460
+ if (how === "stop")
461
+ return fail("unsupported", `${paired.name} is a person's own machine: a run releases its hold, and never stops it`);
462
+ if (which.hold === undefined)
463
+ return fail("invalid", `release names the run's hold on ${paired.name}, the ref create gave (${paired.id}.<hold>), never the computer itself`);
464
+ // A hold already ended is released already: the hold on the computer now, if any, is another run's and stays.
465
+ hub.unclaim(paired.id, which.hold);
466
+ return ok(undefined);
467
+ },
468
+ };
469
+ }
@@ -1,7 +1,7 @@
1
1
  import { type BrowserComputerProvider, type BrowserDownloads, type BrowserProfiles, type BrowserStream, type ReleaseConfirm } from "./browser.js";
2
2
  import type { KindCapabilities } from "./kinds.js";
3
3
  import type { MountKind } from "./mount.js";
4
- import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
4
+ import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreateContext, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
5
5
  import { type Result } from "./result.js";
6
6
  export declare const BROWSERBASE_API_URL = "https://api.browserbase.com";
7
7
  /** The domain a Browserbase CDP URL is on (wss://connect.browserbase.com, read live 11-08): cdpUrlProblem holds it there. */
@@ -125,9 +125,7 @@ export declare class BrowserbaseProvider implements ComputerProvider, BrowserCom
125
125
  * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
126
126
  * unless declared.
127
127
  */
128
- create(spec: ComputerSpec, { signal }?: {
129
- signal?: AbortSignal;
130
- }): Promise<Result<CreatedComputer>>;
128
+ create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
131
129
  /**
132
130
  * Settings' test: one read of the project's running sessions (GET /v1/sessions?status=RUNNING), which makes nothing.
133
131
  * A refused key is unauthorized and a Browserbase not reached unreachable; the words name the call, never the key.
@@ -228,7 +228,8 @@ export class BrowserbaseProvider {
228
228
  * whole seconds, and the labels as its userMetadata. spec.browser is the session's own options, each refused by check()
229
229
  * unless declared.
230
230
  */
231
- async create(spec, { signal } = {}) {
231
+ async create(spec, context) {
232
+ const signal = context?.signal;
232
233
  const refusals = this.check(spec);
233
234
  if (refusals.length > 0)
234
235
  return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));