@parcha/agentrun-computer 0.0.0-stage → 0.1.0-beta.33

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 (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +2411 -2
  4. package/box/Dockerfile +69 -0
  5. package/box/agentrun-archil +168 -0
  6. package/box/build-daytona.py +26 -0
  7. package/box/build-e2b.mjs +32 -0
  8. package/box/build-modal.py +17 -0
  9. package/dist/actions.d.ts +18 -0
  10. package/dist/actions.js +139 -0
  11. package/dist/browser.d.ts +151 -0
  12. package/dist/browser.js +305 -0
  13. package/dist/browserbase.d.ts +139 -0
  14. package/dist/browserbase.js +408 -0
  15. package/dist/child.d.ts +40 -0
  16. package/dist/child.js +127 -0
  17. package/dist/client.d.ts +22 -0
  18. package/dist/client.js +136 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/archil.d.ts +68 -0
  22. package/dist/conformance/archil.js +152 -0
  23. package/dist/conformance/browserbase.d.ts +35 -0
  24. package/dist/conformance/browserbase.js +45 -0
  25. package/dist/conformance/cases/apps.d.ts +2 -0
  26. package/dist/conformance/cases/apps.js +155 -0
  27. package/dist/conformance/cases/browser.d.ts +4 -0
  28. package/dist/conformance/cases/browser.js +105 -0
  29. package/dist/conformance/cases/drift.d.ts +2 -0
  30. package/dist/conformance/cases/drift.js +64 -0
  31. package/dist/conformance/cases/exec.d.ts +2 -0
  32. package/dist/conformance/cases/exec.js +125 -0
  33. package/dist/conformance/cases/files.d.ts +2 -0
  34. package/dist/conformance/cases/files.js +294 -0
  35. package/dist/conformance/cases/health.d.ts +2 -0
  36. package/dist/conformance/cases/health.js +71 -0
  37. package/dist/conformance/cases/index.d.ts +9 -0
  38. package/dist/conformance/cases/index.js +37 -0
  39. package/dist/conformance/cases/input.d.ts +12 -0
  40. package/dist/conformance/cases/input.js +109 -0
  41. package/dist/conformance/cases/isolation.d.ts +21 -0
  42. package/dist/conformance/cases/isolation.js +98 -0
  43. package/dist/conformance/cases/lifetime.d.ts +2 -0
  44. package/dist/conformance/cases/lifetime.js +64 -0
  45. package/dist/conformance/cases/mount.d.ts +2 -0
  46. package/dist/conformance/cases/mount.js +252 -0
  47. package/dist/conformance/cases/process.d.ts +2 -0
  48. package/dist/conformance/cases/process.js +240 -0
  49. package/dist/conformance/cases/provider.d.ts +2 -0
  50. package/dist/conformance/cases/provider.js +302 -0
  51. package/dist/conformance/cases/screen.d.ts +9 -0
  52. package/dist/conformance/cases/screen.js +230 -0
  53. package/dist/conformance/cases/settings.d.ts +57 -0
  54. package/dist/conformance/cases/settings.js +142 -0
  55. package/dist/conformance/cases/touch.d.ts +2 -0
  56. package/dist/conformance/cases/touch.js +117 -0
  57. package/dist/conformance/cases/util.d.ts +7 -0
  58. package/dist/conformance/cases/util.js +8 -0
  59. package/dist/conformance/cdp.d.ts +13 -0
  60. package/dist/conformance/cdp.js +88 -0
  61. package/dist/conformance/cli.d.ts +29 -0
  62. package/dist/conformance/cli.js +231 -0
  63. package/dist/conformance/daytona-sweep.d.ts +18 -0
  64. package/dist/conformance/daytona-sweep.js +126 -0
  65. package/dist/conformance/daytona.d.ts +83 -0
  66. package/dist/conformance/daytona.js +107 -0
  67. package/dist/conformance/docker.d.ts +38 -0
  68. package/dist/conformance/docker.js +70 -0
  69. package/dist/conformance/drift-daemon.d.ts +8 -0
  70. package/dist/conformance/drift-daemon.js +41 -0
  71. package/dist/conformance/e2b-diagnose.d.ts +16 -0
  72. package/dist/conformance/e2b-diagnose.js +61 -0
  73. package/dist/conformance/e2b-sweep.d.ts +18 -0
  74. package/dist/conformance/e2b-sweep.js +132 -0
  75. package/dist/conformance/e2b.d.ts +74 -0
  76. package/dist/conformance/e2b.js +111 -0
  77. package/dist/conformance/fixture.d.ts +65 -0
  78. package/dist/conformance/fixture.js +98 -0
  79. package/dist/conformance/index.d.ts +8 -0
  80. package/dist/conformance/index.js +8 -0
  81. package/dist/conformance/kernel.d.ts +31 -0
  82. package/dist/conformance/kernel.js +40 -0
  83. package/dist/conformance/kind.d.ts +23 -0
  84. package/dist/conformance/kind.js +58 -0
  85. package/dist/conformance/modal-sweep.d.ts +22 -0
  86. package/dist/conformance/modal-sweep.js +213 -0
  87. package/dist/conformance/modal.d.ts +69 -0
  88. package/dist/conformance/modal.js +76 -0
  89. package/dist/conformance/orgo.d.ts +41 -0
  90. package/dist/conformance/orgo.js +69 -0
  91. package/dist/conformance/phone-harness.d.ts +61 -0
  92. package/dist/conformance/phone-harness.js +241 -0
  93. package/dist/conformance/png.d.ts +16 -0
  94. package/dist/conformance/png.js +132 -0
  95. package/dist/conformance/report.d.ts +2 -0
  96. package/dist/conformance/report.js +86 -0
  97. package/dist/conformance/runner.d.ts +11 -0
  98. package/dist/conformance/runner.js +585 -0
  99. package/dist/conformance/tar.d.ts +13 -0
  100. package/dist/conformance/tar.js +105 -0
  101. package/dist/conformance/types.d.ts +257 -0
  102. package/dist/conformance/types.js +24 -0
  103. package/dist/daemon-copy.d.ts +40 -0
  104. package/dist/daemon-copy.js +259 -0
  105. package/dist/daytona.d.ts +180 -0
  106. package/dist/daytona.js +1498 -0
  107. package/dist/desktop.d.ts +24 -0
  108. package/dist/desktop.js +68 -0
  109. package/dist/docker/egress-main.d.ts +1 -0
  110. package/dist/docker/egress-main.js +68 -0
  111. package/dist/docker/egress-proxy.d.ts +53 -0
  112. package/dist/docker/egress-proxy.js +450 -0
  113. package/dist/docker/egress-table.d.ts +39 -0
  114. package/dist/docker/egress-table.js +197 -0
  115. package/dist/docker/egress.d.ts +109 -0
  116. package/dist/docker/egress.js +318 -0
  117. package/dist/docker/image.d.ts +49 -0
  118. package/dist/docker/image.js +302 -0
  119. package/dist/docker/stage.d.ts +21 -0
  120. package/dist/docker/stage.js +290 -0
  121. package/dist/docker/volume.d.ts +24 -0
  122. package/dist/docker/volume.js +67 -0
  123. package/dist/docker.d.ts +156 -0
  124. package/dist/docker.js +1277 -0
  125. package/dist/drift.d.ts +200 -0
  126. package/dist/drift.js +416 -0
  127. package/dist/e2b.d.ts +337 -0
  128. package/dist/e2b.js +1516 -0
  129. package/dist/entry.d.ts +2 -0
  130. package/dist/entry.js +24 -0
  131. package/dist/files.d.ts +50 -0
  132. package/dist/files.js +208 -0
  133. package/dist/index.d.ts +27 -0
  134. package/dist/index.js +26 -0
  135. package/dist/isolation.d.ts +29 -0
  136. package/dist/isolation.js +71 -0
  137. package/dist/janitor.d.ts +50 -0
  138. package/dist/janitor.js +135 -0
  139. package/dist/kernel.d.ts +113 -0
  140. package/dist/kernel.js +358 -0
  141. package/dist/kinds.d.ts +79 -0
  142. package/dist/kinds.js +133 -0
  143. package/dist/labels.d.ts +23 -0
  144. package/dist/labels.js +50 -0
  145. package/dist/modal.d.ts +302 -0
  146. package/dist/modal.js +1374 -0
  147. package/dist/mount-archil.d.ts +164 -0
  148. package/dist/mount-archil.js +471 -0
  149. package/dist/mount.d.ts +57 -0
  150. package/dist/mount.js +104 -0
  151. package/dist/orgo-channel.d.ts +96 -0
  152. package/dist/orgo-channel.js +391 -0
  153. package/dist/orgo.d.ts +139 -0
  154. package/dist/orgo.js +1006 -0
  155. package/dist/phone-harness.d.ts +185 -0
  156. package/dist/phone-harness.js +1420 -0
  157. package/dist/processes.d.ts +24 -0
  158. package/dist/processes.js +40 -0
  159. package/dist/protocol.d.ts +729 -0
  160. package/dist/protocol.js +54 -0
  161. package/dist/provider.d.ts +245 -0
  162. package/dist/provider.js +37 -0
  163. package/dist/providers.d.ts +68 -0
  164. package/dist/providers.js +25 -0
  165. package/dist/result.d.ts +15 -0
  166. package/dist/result.js +2 -0
  167. package/dist/screen-watch.d.ts +150 -0
  168. package/dist/screen-watch.js +490 -0
  169. package/dist/test-connection.d.ts +17 -0
  170. package/dist/test-connection.js +26 -0
  171. package/dist/wait.d.ts +23 -0
  172. package/dist/wait.js +65 -0
  173. package/package.json +62 -4
package/dist/orgo.js ADDED
@@ -0,0 +1,1006 @@
1
+ // The Orgo provisioner: desktops on Orgo (orgo.ai), a Linux VM with a screen, for the desktop kind. computerd runs in the
2
+ // VM as everywhere (design: "computerd in every computer"), so a desktop is the same wire as every computer: it is
3
+ // uploaded, installed and started as a child of Orgo's own agent, on Orgo's own X display (:99), with its tools as
4
+ // 2510:2510 in init's own network namespace. Orgo's screenshot and input API is not used. Everything inside a computer
5
+ // goes through an OrgoChannel (orgo-channel.ts): Orgo's bash and upload calls and its root terminal, by default.
6
+ //
7
+ // Orgo has no labels and no list of computers but a workspace's: the computers of a deployment live in one workspace
8
+ // (the workspaceId option), and a computer's name carries what list needs with nothing run inside it: computer-<12 hex>,
9
+ // then -r<the run label's hash> and -e<the epoch label>. Every label, the deadline and its most are in a root-owned file
10
+ // in the computer, /opt/agentrun/labels.json, the truth attach reads. Every Orgo fact is cited in orgo-channel.ts and
11
+ // the plan: POST /computers takes workspace_id, name (≤ 80), os, ram, cpu, template_ref and ends_in_hours (1 to 720,
12
+ // after which Orgo deletes the computer); DELETE /computers/{id} answers 404 computer_not_found once it is gone and 409
13
+ // computer_waking while it wakes; POST /computers/{id}/extend { hours } with an Idempotency-Key lengthens Orgo's end.
14
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
15
+ import { readFileSync } from "node:fs";
16
+ import { fileURLToPath } from "node:url";
17
+ import { childCommands, daemonDrift } from "./child.js";
18
+ import { DaemonClient } from "./client.js";
19
+ import { DESKTOP_GROUPS } from "./desktop.js";
20
+ import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, SOCKET_DIR, WORK } from "./drift.js";
21
+ import { EPOCH_LABEL, RUN_LABEL } from "./labels.js";
22
+ import { checkMount } from "./mount.js";
23
+ import { ORGO_API_URL, orgoRest, orgoTerminalChannel, START_LOG } from "./orgo-channel.js";
24
+ import { checkLifetime, } from "./provider.js";
25
+ import { fail, ok } from "./result.js";
26
+ import { daemonWatch } from "./screen-watch.js";
27
+ import { listTested } from "./test-connection.js";
28
+ /** The mount kinds an Orgo computer takes: none yet (an Archil mount needs an Orgo template that bakes the helper). */
29
+ export const MOUNT = [];
30
+ /** The groups every Orgo computer offers: a Linux shell, files and processes, and the desktop's screen and input. */
31
+ const GROUPS = ["exec", "files", "processes", ...DESKTOP_GROUPS];
32
+ /** What a built provider declares, known without building one: one configuration, a Linux desktop (the registry's entry). */
33
+ export const CAPABILITIES = [{ kind: "desktop", groups: [...GROUPS] }];
34
+ /** The conformance CLI's module for Orgo: its live switch, the run's 1 h cap and the drifted twin. */
35
+ export const conformance = () => import("./conformance/orgo.js");
36
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
37
+ const HOUR = 3_600_000;
38
+ /** Orgo's longest end: ends_in_hours is at most 720. */
39
+ const MAX_LIFETIME_MS = 720 * HOUR;
40
+ /** Orgo's RAM sizes, in GB, and the vCPUs each takes by default. */
41
+ const RAM_GB = [4, 8, 16, 32];
42
+ const CPU_FOR_RAM = { 4: 1, 8: 2, 16: 4, 32: 6 };
43
+ /** The vCPUs a computer may ask for on its own (8 needs Orgo to set the account up). */
44
+ const CPUS = [0.5, 1, 2, 4, 6];
45
+ const NAME_MAX = 80;
46
+ /** A name of this provider's making: computer-<12 hex>, the run label's hash, the epoch label, the deadline (base 36 s). */
47
+ const NAME = /^computer-([0-9a-f]{12})(?:-r([a-z2-7]{16}))?(?:-e(0|[1-9][0-9]{0,15}))?(?:-d([0-9a-z]{1,11}))?$/;
48
+ /** An Orgo template: namespace/name@version. */
49
+ const TEMPLATE = /^[a-z0-9][a-z0-9_.-]{0,63}\/[a-z0-9][a-z0-9_.-]{0,63}@[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;
50
+ /** Orgo's base desktop, no template: the image a spec names for a plain Linux desktop, and the default for kind desktop. */
51
+ export const ORGO_BASE_IMAGE = "linux";
52
+ const BASE = ORGO_BASE_IMAGE;
53
+ const COMPUTER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
54
+ const WORKSPACE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
55
+ const USER = /^(\d+):(\d+)$/;
56
+ const DISPLAY = /^:(\d{1,5})(?:\.\d{1,5})?$/;
57
+ const TARGET = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):[0-9]{1,5}(?:\/udp)?$/;
58
+ const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1111]:443", "1.1.1.1:53/udp", "[2606:4700:4700::1111]:53/udp"];
59
+ const DEFAULTS = { requestMs: 30_000, createMs: 300_000, uploadMs: 120_000, execMs: 60_000, helloMs: 30_000, probeMs: 30_000, listMs: 60_000, goneMs: 120_000, pollMs: 1_000 };
60
+ const DEFAULT_DAEMON_PATH = fileURLToPath(new URL("./computerd-linux-amd64", import.meta.url));
61
+ /** The labels file: every label, the deadline and its most, the image and sizes, root's, readable by all. */
62
+ export const LABELS_FILE = "/opt/agentrun/labels.json";
63
+ const STAGING = "/tmp/agentrun-computerd-";
64
+ const LISTEN_RETRY_MS = 250;
65
+ /** How often a delete that answers 409 (the computer waking) is tried again. */
66
+ const DELETE_TRIES = 5;
67
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "labels"]);
68
+ /** The states in which a computer runs, or is on its way to. */
69
+ const RUNNING = new Set(["running", "creating", "restarting", "updating", "resuming"]);
70
+ const NETWORK = 'an Orgo computer takes network "none" only: Orgo has no egress control, so its tools have no network of their own (init\'s namespace holds them to loopback), and open or an allowlist waits for the proxy-backed feature';
71
+ /** The scripts the provider runs as root, each marked on its first line, its arguments after it. */
72
+ const X11_SCRIPT = ["# agentrun-computer: orgo-x11", "s=$1", '[ -S "$s" ] || { echo "no X socket at $s"; exit 1; }'].join("\n");
73
+ const LABELS_SCRIPT = ["# agentrun-computer: orgo-labels", 'p=$1; t=$2; d=${p%/*}', 'mkdir -p "$d" && printf \'%s\' "$t" > "$p.part" && chmod 0644 "$p.part" && mv -f "$p.part" "$p"'].join("\n");
74
+ const LABELS_READ_SCRIPT = ["# agentrun-computer: orgo-labels-read", 'cat "$1"'].join("\n");
75
+ /** What the computer holds when its daemon does not answer: init running (anchored, so this script never matches itself), its socket, its log's tail. */
76
+ const STATUS_SCRIPT = [
77
+ "# agentrun-computer: orgo-status",
78
+ "d=$1; s=$2; l=$3",
79
+ 'if pgrep -f "^$d init" >/dev/null 2>&1; then echo "init running"; else echo "init not running"; fi',
80
+ 'if [ -S "$s" ]; then echo "socket present"; else echo "socket absent"; fi',
81
+ "echo \"log $(tail -c 300 \"$l\" 2>/dev/null | tr '\\n' ' ')\"",
82
+ ].join("\n");
83
+ /**
84
+ * The TCP ports root listens on in Orgo's own network (its agent, its VNC, anything else of the image's), one decimal
85
+ * port a line, from /proc/net/tcp and tcp6 (state 0A, LISTEN): no tool of the image's is relied on but awk.
86
+ */
87
+ const PORTS_SCRIPT = [
88
+ "# agentrun-computer: orgo-ports",
89
+ "for f in /proc/net/tcp /proc/net/tcp6; do [ -r \"$f\" ] && awk 'NR > 1 && $4 == \"0A\" { n = split($2, a, \":\"); print a[n] }' \"$f\"; done | sort -u | while read -r h; do printf '%d\\n' \"0x$h\"; done",
90
+ ].join("\n");
91
+ /**
92
+ * The ports Orgo's own agent listens on in a computer, which its tools must never reach: its VNC (5999), websockify
93
+ * (6080) and desktop API (8080), as live run 4's notes read them (Orgo documents only the host's side). create reads
94
+ * every port root listens on beside these and holds the tools to none of them either.
95
+ */
96
+ const ORGO_AGENT_PORTS = [5999, 6080, 8080];
97
+ /**
98
+ * Every path unix socket of Orgo's desktop made root's alone (owner root, mode 0600), but the display's own ($1) and
99
+ * computerd's, before any tool runs: the tools reach the X server through that one and nothing else (live run 4 found
100
+ * root's D-Bus buses connectable by the tool user). Prints `locked <path>` for each, and `failed <path>` for one it
101
+ * could not lock. Any failure fails the script: the scan, the sort, or one socket's chown or chmod (a later socket that
102
+ * locks hides none), and create then refuses the computer. Plain sh (no pipefail): the scan and the sort are each
103
+ * checked, and the loop reads a here-document, so its failed flag is the script's own. Orgo's desktop runs as root, so
104
+ * nothing of its own loses a socket.
105
+ */
106
+ export const LOCKDOWN_SCRIPT = [
107
+ "# agentrun-computer: orgo-lockdown",
108
+ "x=$1",
109
+ "set --",
110
+ 'for d in /tmp /run /var/run /dev/shm; do [ -d "$d" ] && set -- "$@" "$d"; done',
111
+ "[ $# -gt 0 ] || exit 0",
112
+ // GNU find's -ignore_readdir_race: a socket gone between listing and reading is no failure. Used only where find has it.
113
+ "r=",
114
+ "find / -maxdepth 0 -ignore_readdir_race >/dev/null 2>&1 && r=-ignore_readdir_race",
115
+ 'found=$(find "$@" $r -type s) || { echo "scanning for sockets failed"; exit 1; }',
116
+ "sorted=$(printf '%s\\n' \"$found\" | sort -u) || { echo \"sorting the sockets failed\"; exit 1; }",
117
+ "failed=0",
118
+ "while IFS= read -r s; do",
119
+ '\t[ -n "$s" ] || continue',
120
+ '\tcase "$s" in "$x" | /run/agentrun/* | /run/agentrun-archil/*) continue ;; esac',
121
+ '\tif chown 0:0 "$s" && chmod 0600 "$s"; then echo "locked $s"; else echo "failed $s"; failed=1; fi',
122
+ "done <<EOF",
123
+ "$sorted",
124
+ "EOF",
125
+ "exit $failed",
126
+ ].join("\n");
127
+ const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
128
+ const seconds = (ms) => `${ms / 1000} s`;
129
+ const pause = (ms, signal) => new Promise((done) => {
130
+ const timer = setTimeout(finish, ms);
131
+ function finish() {
132
+ clearTimeout(timer);
133
+ signal?.removeEventListener("abort", finish);
134
+ done();
135
+ }
136
+ if (signal?.aborted)
137
+ finish();
138
+ else
139
+ signal?.addEventListener("abort", finish, { once: true });
140
+ });
141
+ /** The run label's hash, as a name carries it: base32 of its sha256, lower case, 16 letters. */
142
+ function runHash(run) {
143
+ const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
144
+ const bytes = createHash("sha256").update(run, "utf8").digest();
145
+ let bits = 0;
146
+ let value = 0;
147
+ let out = "";
148
+ for (const byte of bytes) {
149
+ value = (value << 8) | byte;
150
+ bits += 8;
151
+ while (bits >= 5 && out.length < 16) {
152
+ out += alphabet[(value >>> (bits - 5)) & 31];
153
+ bits -= 5;
154
+ }
155
+ if (out.length >= 16)
156
+ break;
157
+ }
158
+ return out;
159
+ }
160
+ /**
161
+ * The name of a computer with these labels: computer-<hex>, then -r<the run label's hash> and -e<the epoch label> when
162
+ * the labels carry a run and an epoch that is one, then -d<the deadline> when given: whole seconds since the epoch,
163
+ * rounded up (never before init's own), in base 36, the janitor's deadline. Only those: a name is no place for a label's
164
+ * value. Everything but the deadline is the name's stable part, which a rename on extend keeps.
165
+ */
166
+ export function orgoName(labels, hex, deadline) {
167
+ const run = labels[RUN_LABEL];
168
+ const epoch = labels[EPOCH_LABEL];
169
+ const stable = `computer-${hex}${typeof run === "string" && run !== "" ? `-r${runHash(run)}` : ""}${typeof epoch === "string" && /^(?:0|[1-9][0-9]{0,15})$/.test(epoch) ? `-e${epoch}` : ""}`;
170
+ return deadline === undefined ? stable : withDeadline(stable, deadline);
171
+ }
172
+ /** A name's stable part with this deadline. */
173
+ function withDeadline(stable, deadline) {
174
+ return `${stable}-d${Math.ceil(deadline.getTime() / 1000).toString(36)}`;
175
+ }
176
+ /** What a name of this provider's making says, or undefined for any other name: its stable part, and its deadline. */
177
+ function nameParts(name) {
178
+ const match = typeof name === "string" ? NAME.exec(name) : null;
179
+ if (match === null)
180
+ return undefined;
181
+ const seconds = match[4] === undefined ? Number.NaN : Number.parseInt(match[4], 36);
182
+ return {
183
+ hex: match[1],
184
+ ...(match[2] ? { run: match[2] } : {}),
185
+ ...(match[3] !== undefined ? { epoch: match[3] } : {}),
186
+ stable: name.replace(/-d[0-9a-z]+$/, ""),
187
+ ...(Number.isSafeInteger(seconds) ? { deadline: new Date(seconds * 1000) } : {}),
188
+ };
189
+ }
190
+ /** Whether two names are one computer's: their stable parts are the same (the deadline moves with extend). */
191
+ const sameComputer = (a, b) => nameParts(a)?.stable !== undefined && nameParts(a)?.stable === nameParts(b)?.stable;
192
+ function labelProblem(key, value) {
193
+ if (typeof value !== "string")
194
+ return `the label ${key} must be a string`;
195
+ if (key === "" || key.includes("\0") || value.includes("\0"))
196
+ return `the label ${JSON.stringify(key)} must be a non-empty name, and neither holds a NUL byte`;
197
+ if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
198
+ return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
199
+ return undefined;
200
+ }
201
+ function filterProblem(labels) {
202
+ if (typeof labels !== "object" || labels === null || Array.isArray(labels))
203
+ return "labels must map names to strings";
204
+ for (const [key, value] of Object.entries(labels)) {
205
+ if (typeof value !== "string" || key === "" || key.includes("\0") || value.includes("\0"))
206
+ return `the label ${JSON.stringify(key)} must be a non-empty name and a string, with no NUL byte`;
207
+ }
208
+ return undefined;
209
+ }
210
+ /** Why ref is not an Orgo computer's ref, or undefined. */
211
+ function refProblem(ref) {
212
+ if (typeof ref?.name !== "string" || nameParts(ref.name) === undefined)
213
+ return `${String(ref?.name)} is not the name of an Orgo computer of this provider (computer-<12 hex digits>...)`;
214
+ if (typeof ref.id !== "string" || !COMPUTER_ID.test(ref.id))
215
+ return `${String(ref.id)} is not an Orgo computer id`;
216
+ return undefined;
217
+ }
218
+ /** The labels file as written, or why it is not. */
219
+ function labelsOf(text) {
220
+ try {
221
+ const value = JSON.parse(text);
222
+ if (typeof value?.name === "string" && typeof value.labels === "object" && value.labels !== null && typeof value.deadline === "string" && typeof value.maxDeadline === "string" && typeof value.image === "string") {
223
+ return value;
224
+ }
225
+ }
226
+ catch {
227
+ // Said below.
228
+ }
229
+ return `the labels file ${LABELS_FILE} is not the one create writes`;
230
+ }
231
+ /**
232
+ * Orgo desktops: see the module's header. A spec's image is "linux" (Orgo's base desktop) or an Orgo template
233
+ * (namespace/name@version); cpus and memoryMb are Orgo's sizes; the network is none.
234
+ */
235
+ export class OrgoProvider {
236
+ id = "orgo";
237
+ version = VERSION;
238
+ #rest;
239
+ #channel;
240
+ #workspaceId;
241
+ #daemonPath;
242
+ #maxLifetimeMs;
243
+ #uid;
244
+ #gid;
245
+ #start;
246
+ #display;
247
+ #timeouts;
248
+ #probeTargets;
249
+ /** Each computer's extend in flight, by id: the next waits for it, so two never read the same old deadline. */
250
+ #extending = new Map();
251
+ constructor({ apiKey, workspaceId, apiUrl = ORGO_API_URL, fetch, webSocket, channel, daemonPath = DEFAULT_DAEMON_PATH, maxLifetimeMs = MAX_LIFETIME_MS, user = "2510:2510", start = "bash", display = ":99", timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS }) {
252
+ if (typeof apiKey !== "string" || apiKey === "")
253
+ throw new Error("options.apiKey, an Orgo API key, is required");
254
+ if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId))
255
+ throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is required");
256
+ let url;
257
+ try {
258
+ url = new URL(apiUrl);
259
+ }
260
+ catch {
261
+ throw new Error("options.apiUrl is not a URL");
262
+ }
263
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "")
264
+ throw new Error("options.apiUrl must be https, with no credentials in it: the key goes to it");
265
+ if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
266
+ throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most Orgo's 720 h (${MAX_LIFETIME_MS} ms)`);
267
+ const ids = USER.exec(user);
268
+ if (ids === null)
269
+ throw new Error(`the user ${JSON.stringify(user)} must be uid:gid in numbers, such as 2510:2510`);
270
+ if (Number(ids[1]) === 0 || Number(ids[2]) === 0)
271
+ throw new Error(`the user ${user} is root or in root's group: an Orgo computer's tools run as neither`);
272
+ if (start !== "bash" && start !== "session")
273
+ throw new Error(`start is "bash" or "session", not ${JSON.stringify(start)}`);
274
+ if (!DISPLAY.test(display))
275
+ throw new Error(`display ${JSON.stringify(display)} must be a local X display, such as :99`);
276
+ const merged = { ...DEFAULTS, ...timeouts };
277
+ for (const [key, value] of Object.entries(merged)) {
278
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2 ** 31 - 1)
279
+ throw new Error(`timeouts.${key} must be a whole number of ms above 0`);
280
+ }
281
+ if (!Array.isArray(probeTargets) || probeTargets.length === 0 || probeTargets.some((target) => typeof target !== "string" || !TARGET.test(target))) {
282
+ throw new Error("probeTargets must name at least one address for the probe, each host:port or host:port/udp");
283
+ }
284
+ this.#rest = orgoRest({ apiKey, apiUrl: url.href, ...(fetch ? { fetch } : {}) });
285
+ this.#channel = channel ?? orgoTerminalChannel({ rest: this.#rest, workspaceId, ...(webSocket ? { webSocket } : {}) });
286
+ this.#workspaceId = workspaceId;
287
+ this.#daemonPath = daemonPath;
288
+ this.#maxLifetimeMs = maxLifetimeMs;
289
+ [this.#uid, this.#gid] = [String(Number(ids[1])), String(Number(ids[2]))];
290
+ this.#start = start;
291
+ this.#display = display;
292
+ this.#timeouts = merged;
293
+ this.#probeTargets = [...probeTargets];
294
+ }
295
+ /**
296
+ * daemon child: Orgo's own agent is the VM's first process, and init is a command it ran. lifetime janitor: Orgo ends
297
+ * a computer only in whole hours (ends_in_hours, the backstop), so the janitor deletes it at its exact deadline, which
298
+ * its name carries (list() reads it with nothing run inside); init ends its programs at that deadline inside. network
299
+ * none alone, read back by the probe from inside (Orgo reads no policy back). release delete alone: Orgo's stop
300
+ * freezes a computer, which nothing here needs.
301
+ */
302
+ capabilities() {
303
+ return {
304
+ kind: "desktop",
305
+ lifetime: "janitor",
306
+ network: ["none"],
307
+ networkReadBack: false,
308
+ isolation: "vm",
309
+ os: "linux",
310
+ daemon: "child",
311
+ groups: [...GROUPS],
312
+ maxLifetimeMs: this.#maxLifetimeMs,
313
+ release: ["delete"],
314
+ mount: [...MOUNT],
315
+ // Init starts with --own-network (childCommands): no tool reaches these, nor any port root listens on.
316
+ vendorAgentPorts: [...ORGO_AGENT_PORTS],
317
+ };
318
+ }
319
+ check(spec) {
320
+ const refusals = [];
321
+ const refuse = (field, message) => refusals.push({ field, message });
322
+ const given = (typeof spec === "object" && spec !== null ? spec : {});
323
+ const { image, lifetimeMs, network, cpus, memoryMb, labels, mount } = given;
324
+ if (image !== BASE && !(typeof image === "string" && TEMPLATE.test(image)))
325
+ refuse("image", `an image is "${BASE}" (Orgo's base desktop) or an Orgo template, namespace/name@version`);
326
+ refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
327
+ if (network !== "none")
328
+ refuse("network", NETWORK);
329
+ if (memoryMb !== undefined && !RAM_GB.some((gb) => gb * 1024 === memoryMb))
330
+ refuse("memoryMb", "memoryMb is one of Orgo's sizes: 4096, 8192, 16384 or 32768");
331
+ if (cpus !== undefined && !CPUS.includes(cpus))
332
+ refuse("cpus", "cpus is one of Orgo's sizes: 0.5, 1, 2, 4 or 6");
333
+ if (labels !== undefined) {
334
+ const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
335
+ const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
336
+ if (bad)
337
+ refuse("labels", bad);
338
+ }
339
+ refusals.push(...checkMount(mount, MOUNT));
340
+ for (const [field, value] of Object.entries(given)) {
341
+ if (SPEC_FIELDS.has(field) || field === "mount" || value === undefined)
342
+ continue;
343
+ if (field === "user")
344
+ refuse(field, `an Orgo computer's tools run as the provider's user (${this.#uid}:${this.#gid}, the remote tool user), never as one a spec names`);
345
+ else if (field === "workdir")
346
+ refuse(field, `an Orgo computer works in ${WORK}, its home; a spec cannot name another`);
347
+ else if (field === "pids")
348
+ refuse(field, "Orgo offers no pids limit to set; leave pids unset");
349
+ else
350
+ refuse(field, `an Orgo computer does not support ${field}`);
351
+ }
352
+ return refusals;
353
+ }
354
+ async create(spec, { signal } = {}) {
355
+ const refusals = this.check(spec);
356
+ if (refusals.length > 0)
357
+ return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
358
+ let daemon;
359
+ try {
360
+ daemon = readFileSync(this.#daemonPath);
361
+ }
362
+ catch {
363
+ return fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
364
+ }
365
+ if (signal?.aborted)
366
+ return fail("aborted", "create was aborted before Orgo was called");
367
+ const labels = { ...spec.labels };
368
+ const now = Date.now();
369
+ const deadline = new Date(now + spec.lifetimeMs).toISOString();
370
+ const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
371
+ // The janitor's deadline is in the name, so list() and the sweep read it with nothing run inside.
372
+ const name = orgoName(labels, randomBytes(6).toString("hex"), new Date(deadline));
373
+ if (name.length > NAME_MAX || nameParts(name) === undefined)
374
+ return fail("invalid", `the name ${name} is not one Orgo holds: at most ${NAME_MAX} of letters, digits and dashes`);
375
+ const ram = spec.memoryMb === undefined ? 4 : spec.memoryMb / 1024;
376
+ const cpu = spec.cpus ?? CPU_FOR_RAM[ram];
377
+ const body = {
378
+ workspace_id: this.#workspaceId,
379
+ name,
380
+ os: "linux",
381
+ ram,
382
+ cpu,
383
+ // Orgo's end, the vendor's backstop: whole hours, deleting the computer and its disk. init ends it on time.
384
+ ends_in_hours: Math.max(1, Math.ceil(spec.lifetimeMs / HOUR)),
385
+ ...(spec.image === BASE ? {} : { template_ref: spec.image }),
386
+ };
387
+ const made = await this.#rest.request("POST", "/computers", { body, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
388
+ if (!made.ok) {
389
+ // A create Orgo refused (a 4xx) made nothing. One whose answer never came may have: it goes by its name.
390
+ if (["invalid", "denied", "limit", "not_found", "refused"].includes(made.error.code))
391
+ return made;
392
+ return fail(made.error.code, `${made.error.message}${await this.#deleteNamed(name)}`);
393
+ }
394
+ const id = made.value?.id;
395
+ if (typeof id !== "string" || !COMPUTER_ID.test(id))
396
+ return fail("orgo", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
397
+ const ref = { id, name };
398
+ const file = { name, labels, deadline, maxDeadline, image: spec.image, cpus: cpu, memoryMb: ram * 1024 };
399
+ const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal);
400
+ if (signal?.aborted)
401
+ return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
402
+ if (prepared.ok)
403
+ return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
404
+ return this.#abandon(ref, prepared.error);
405
+ }
406
+ /**
407
+ * Everything between Orgo's answer and a computer that passed the drift check: running, computerd uploaded and
408
+ * installed (its sha256 read back), Orgo's X server's path socket there, the labels file, init started, its first
409
+ * connection, then the daemon's report and the probe. Its value is the probe's notes.
410
+ */
411
+ async #prepare(ref, status, file, daemon, signal) {
412
+ const { uploadMs, execMs } = this.#timeouts;
413
+ const running = status === "running" ? ok(undefined) : await this.#untilRunning(ref, signal);
414
+ if (!running.ok)
415
+ return running;
416
+ const staging = `${STAGING}${randomBytes(8).toString("hex")}`;
417
+ const uploaded = await this.#channel.upload(ref.id, staging, daemon, { timeoutMs: uploadMs, ...(signal ? { signal } : {}) });
418
+ if (!uploaded.ok)
419
+ return fail(uploaded.error.code, `the daemon's upload into ${ref.name} failed: ${uploaded.error.message}`);
420
+ const commands = childCommands({ staging, deadline: file.deadline, user: `${this.#uid}:${this.#gid}`, display: this.#display, maxDeadline: file.maxDeadline });
421
+ const install = await this.#channel.run(ref.id, ["sh", "-c", commands.install], { timeoutMs: execMs, ...(signal ? { signal } : {}) });
422
+ if (!install.ok)
423
+ return install;
424
+ if (install.value.exitCode !== 0)
425
+ return fail("refused", `installing the daemon failed (exit ${install.value.exitCode}): ${install.value.output.trim().slice(0, 500)}`);
426
+ const sha256 = createHash("sha256").update(daemon).digest("hex");
427
+ const read = /^sha256 ([0-9a-f]{64})$/m.exec(install.value.output)?.[1];
428
+ if (read !== sha256)
429
+ return fail("refused", `it did not match its spec: daemon: uploaded sha256 ${sha256}, the installed binary reads back ${show(read)}`);
430
+ // The tools live in init's own network namespace, which cuts the X server's abstract socket: they reach it through
431
+ // its path socket alone, so a display with none is no desktop here.
432
+ const socket = `/tmp/.X11-unix/X${DISPLAY.exec(this.#display)[1]}`;
433
+ const x11 = await this.#channel.run(ref.id, ["sh", "-c", X11_SCRIPT, "sh", socket], { timeoutMs: execMs, ...(signal ? { signal } : {}) });
434
+ if (!x11.ok)
435
+ return x11;
436
+ if (x11.value.exitCode !== 0) {
437
+ return fail("refused", `Orgo's X server for ${this.#display} has no socket at ${socket}: the tools reach it only through that path, since init's own network namespace cuts the abstract one (${x11.value.output.trim().slice(0, 200)})`);
438
+ }
439
+ const written = await this.#writeLabels(ref, file, signal);
440
+ if (!written.ok)
441
+ return written;
442
+ // Every port root listens on in Orgo's own network, read before init starts in a network of its own.
443
+ const ports = await this.#rootPorts(ref, signal);
444
+ if (!ports.ok)
445
+ return ports;
446
+ // Every path socket of Orgo's desktop root's alone but the display's own, before any tool runs.
447
+ const locked = await this.#lockDown(ref, socket, signal);
448
+ if (!locked.ok)
449
+ return locked;
450
+ const started = await this.#channel.start(ref.id, ["sh", "-c", commands.init], { how: this.#start, timeoutMs: execMs, ...(signal ? { signal } : {}) });
451
+ if (!started.ok)
452
+ return fail(started.error.code, `starting the daemon in ${ref.name} failed: ${started.error.message}`);
453
+ const opened = await this.#openWhenListening(ref, signal);
454
+ if (!opened.ok) {
455
+ if (opened.error.code === "aborted")
456
+ return opened;
457
+ return fail(opened.error.code, `the daemon did not answer: ${opened.error.message}; in the computer: ${await this.#status(ref, signal)}`);
458
+ }
459
+ try {
460
+ const inside = await this.#checkInside(opened.value, ref.name, ports.value, signal);
461
+ if (!inside.ok)
462
+ return inside;
463
+ return ok([
464
+ ...inside.value,
465
+ `Orgo's own network listens on ${ports.value.join(", ") || "no TCP port"} (TCP, as root reads it); the tools' probe was refused at each and at ${ORGO_AGENT_PORTS.join(", ")}, on both loopbacks`,
466
+ `Orgo's desktop sockets made root's alone: ${locked.value.join(", ") || "none"} (the display's own, ${socket}, left to the tools)`,
467
+ ]);
468
+ }
469
+ finally {
470
+ await opened.value.close();
471
+ }
472
+ }
473
+ /** Every path socket of Orgo's desktop made root's alone but the display's own (LOCKDOWN_SCRIPT): the paths it locked. */
474
+ async #lockDown(ref, display, signal) {
475
+ const ran = await this.#channel.run(ref.id, ["sh", "-c", LOCKDOWN_SCRIPT, "sh", display], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
476
+ if (!ran.ok)
477
+ return ran;
478
+ if (ran.value.exitCode !== 0)
479
+ return fail("refused", `making Orgo's desktop sockets root's alone in ${ref.name} failed (exit ${ran.value.exitCode}): ${ran.value.output.trim().slice(0, 200)}`);
480
+ return ok(ran.value.output.split("\n").flatMap((line) => (line.startsWith("locked ") ? [line.slice("locked ".length).trim()] : [])));
481
+ }
482
+ /** The TCP ports root listens on in Orgo's own network, sorted, read through the channel. */
483
+ async #rootPorts(ref, signal) {
484
+ const read = await this.#channel.run(ref.id, ["sh", "-c", PORTS_SCRIPT], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
485
+ if (!read.ok)
486
+ return read;
487
+ if (read.value.exitCode !== 0)
488
+ return fail("refused", `reading the ports root listens on in ${ref.name} failed (exit ${read.value.exitCode}): ${read.value.output.trim().slice(0, 200)}`);
489
+ const ports = read.value.output
490
+ .split("\n")
491
+ .map((line) => Number(line.trim()))
492
+ .filter((port) => Number.isSafeInteger(port) && port > 0 && port < 65536);
493
+ return ok([...new Set(ports)].sort((a, b) => a - b));
494
+ }
495
+ /** The probe's targets on the computer's own loopbacks: every port given and every declared agent port, on 127.0.0.1 and ::1. */
496
+ #agentTargets(ports) {
497
+ return [...new Set([...ports, ...ORGO_AGENT_PORTS])].sort((a, b) => a - b).flatMap((port) => [`127.0.0.1:${port}`, `[::1]:${port}`]); // key-gate: loopback-rule the computer's own loopbacks, where Orgo's agent listens and its tools must be refused
498
+ }
499
+ /** What the computer holds, in words, for a daemon that does not answer: init running or not, its socket, its log's tail. */
500
+ async #status(ref, signal) {
501
+ const read = await this.#channel.run(ref.id, ["sh", "-c", STATUS_SCRIPT, "sh", DAEMON_IN_COMPUTER, `${SOCKET_DIR}/computerd.sock`, START_LOG], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
502
+ if (!read.ok)
503
+ return `its status could not be read (${read.error.message})`;
504
+ return read.value.output.trim().split("\n").map((line) => line.trim()).join("; ").slice(0, 600);
505
+ }
506
+ /** Polls Orgo until it reads the computer running, within createMs. */
507
+ async #untilRunning(ref, signal) {
508
+ const until = Date.now() + this.#timeouts.createMs;
509
+ let last = "unread";
510
+ for (;;) {
511
+ const read = await this.#get(ref.id, signal);
512
+ if (!read.ok)
513
+ return read;
514
+ last = read.value.status;
515
+ if (last === "running")
516
+ return ok(undefined);
517
+ if (!RUNNING.has(last))
518
+ return fail("orgo", `Orgo read ${ref.name} ${last}, not running`);
519
+ if (Date.now() >= until)
520
+ return fail("timeout", `Orgo did not read ${ref.name} running within ${seconds(this.#timeouts.createMs)}; it last read ${last}`);
521
+ await pause(this.#timeouts.pollMs, signal);
522
+ if (signal?.aborted)
523
+ return fail("aborted", "create was aborted while Orgo made the computer");
524
+ }
525
+ }
526
+ /** The labels file written as root, readable by all, writable by root alone. */
527
+ async #writeLabels(ref, file, signal) {
528
+ const written = await this.#channel.run(ref.id, ["sh", "-c", LABELS_SCRIPT, "sh", LABELS_FILE, JSON.stringify(file)], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
529
+ if (!written.ok)
530
+ return written;
531
+ return written.value.exitCode === 0 ? ok(undefined) : fail("refused", `writing ${LABELS_FILE} in ${ref.name} failed (exit ${written.value.exitCode}): ${written.value.output.trim().slice(0, 300)}`);
532
+ }
533
+ /** The labels file, read through the channel. */
534
+ async #readLabels(ref, signal) {
535
+ const read = await this.#channel.run(ref.id, ["sh", "-c", LABELS_READ_SCRIPT, "sh", LABELS_FILE], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
536
+ if (!read.ok)
537
+ return read;
538
+ if (read.value.exitCode !== 0)
539
+ return fail("refused", `${ref.name} has no labels file ${LABELS_FILE} to read (exit ${read.value.exitCode})`);
540
+ const file = labelsOf(read.value.output);
541
+ return typeof file === "string" ? fail("refused", `${ref.name}: ${file}`) : ok(file);
542
+ }
543
+ /**
544
+ * The daemon's report (hello with the desktop groups, its credentials, home and binary) and the probe, which refuses
545
+ * on an answer from any target and records a silent accept in the notes it returns.
546
+ */
547
+ async #checkInside(connection, name, ports, signal) {
548
+ const found = await daemonDrift(connection, this.#daemonExpected(), this.#timeouts.helloMs, signal);
549
+ if (!found.ok)
550
+ return found;
551
+ const probe = await this.#probe(connection, name, ports, signal);
552
+ if (!probe.ok)
553
+ return probe;
554
+ const drift = [...found.value, ...probeNetworkDrift(probe.value)];
555
+ return drift.length === 0 ? ok(probeNotes(probe.value, "none")) : fail("refused", `it did not match its spec: ${drift.join("; ")}`);
556
+ }
557
+ #daemonExpected() {
558
+ const { kind, groups } = this.capabilities();
559
+ return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: "amd64", kind, groups };
560
+ }
561
+ #bounded(ms, signal) {
562
+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
563
+ }
564
+ /** `computerd probe` through the daemon, as the tool user: the outside targets, and Orgo's agent's ports (ports and the declared ones) on both loopbacks. */
565
+ async #probe(connection, name, ports, signal) {
566
+ const { probeMs } = this.#timeouts;
567
+ const argv = [DAEMON_IN_COMPUTER, "probe", ...[...this.#probeTargets, ...this.#agentTargets(ports)].flatMap((target) => ["--connect", target])];
568
+ const ran = await connection.client.call("exec.run", { argv, timeoutMs: probeMs }, { signal: this.#bounded(probeMs + 5_000, signal) });
569
+ if (!ran.ok) {
570
+ if (signal?.aborted)
571
+ return fail("aborted", `the probe in ${name} was aborted`);
572
+ return fail(ran.error.code === "aborted" ? "timeout" : ran.error.code, `the probe in ${name} failed: ${ran.error.message}`);
573
+ }
574
+ const { exitCode, stdout, stderr, timedOut } = ran.value;
575
+ if (timedOut)
576
+ return fail("timeout", `the probe in ${name} did not end within ${seconds(probeMs)}`);
577
+ if (exitCode !== 0)
578
+ return fail("refused", `the probe in ${name} exited with ${exitCode}: ${Buffer.from(stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
579
+ const report = probeReportOf(stdout);
580
+ return "not" in report ? fail("refused", `the probe in ${name} ${report.not}`) : ok(report);
581
+ }
582
+ /** One connection to the daemon through the channel's stdio bridge, after hello, unchecked. */
583
+ async #open(ref, signal, helloMs = this.#timeouts.helloMs) {
584
+ const bridge = await this.#channel.stdio(ref.id, ["sh", "-c", childCommands().stdio], { timeoutMs: helloMs, ...(signal ? { signal } : {}) });
585
+ if (!bridge.ok)
586
+ return bridge;
587
+ const stream = bridge.value;
588
+ const client = new DaemonClient({ readable: stream.readable, writable: stream.writable });
589
+ let closed;
590
+ const close = () => (closed ??= (async () => {
591
+ client.close();
592
+ await stream.close();
593
+ })());
594
+ const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: this.#bounded(helloMs, signal) });
595
+ if (!hello.ok) {
596
+ await close();
597
+ if (signal?.aborted)
598
+ return fail("aborted", `hello to the daemon in ${ref.name} was aborted`);
599
+ if (hello.error.code === "aborted")
600
+ return fail("timeout", `the daemon in ${ref.name} did not answer hello within ${seconds(helloMs)}`);
601
+ if (hello.error.code !== "gone")
602
+ return hello;
603
+ return { ...fail("orgo", `cannot reach the daemon in ${ref.name}: ${stream.said() || hello.error.message}`), notListening: true };
604
+ }
605
+ return ok({ client, hello: hello.value, close });
606
+ }
607
+ /** #open, tried again while the bridge finds no daemon listening, until hello or helloMs in all. */
608
+ async #openWhenListening(ref, signal) {
609
+ const until = Date.now() + this.#timeouts.helloMs;
610
+ for (;;) {
611
+ const opened = await this.#open(ref, signal, Math.max(1, until - Date.now()));
612
+ if (opened.ok || !opened.notListening || signal?.aborted || Date.now() + LISTEN_RETRY_MS >= until)
613
+ return opened;
614
+ await pause(LISTEN_RETRY_MS, signal);
615
+ }
616
+ }
617
+ /** Orgo's record of a computer; not_found once Orgo no longer has it. */
618
+ async #get(id, signal) {
619
+ const read = await this.#rest.request("GET", `/computers/${encodeURIComponent(id)}`, { timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
620
+ if (!read.ok)
621
+ return read;
622
+ if (typeof read.value?.name !== "string" || typeof read.value.status !== "string")
623
+ return fail("orgo", `Orgo's record of ${id} has no name or status`);
624
+ return ok(read.value);
625
+ }
626
+ /** Whether Orgo's record is a computer of this provider: its name's shape, in this workspace. */
627
+ #ours(record, name) {
628
+ // A ref's name matches by its stable part: extend renames the computer with its new deadline.
629
+ return nameParts(record.name) !== undefined && (record.workspace_id ?? record.project_id) === this.#workspaceId && (name === undefined || sameComputer(record.name, name)) && record.status !== "deleted";
630
+ }
631
+ /** This provider's computer for ref, as Orgo reads it, or why not. */
632
+ async #own(ref, signal) {
633
+ const read = await this.#get(ref.id, signal);
634
+ if (!read.ok)
635
+ return read.error.code === "not_found" ? fail("not_found", `no Orgo computer is ${ref.name} (${ref.id})`) : read;
636
+ if (!this.#ours(read.value, ref.name))
637
+ return fail("not_found", `no Orgo computer of this provider named ${ref.name} has the id ${ref.id}`);
638
+ return read;
639
+ }
640
+ /** Deletes a computer create gives up on, and waits until Orgo no longer has it. Never signalled: it outlives an abort. */
641
+ async #abandon(ref, error) {
642
+ const deleted = await this.#delete(ref);
643
+ return fail(error.code, `the computer ${ref.name} ${deleted.ok ? "was deleted" : `could not be deleted (${deleted.error.message}); Orgo ends it at its end`}: ${error.message}`);
644
+ }
645
+ /** Every computer of this workspace with the name create gave: for a create whose answer never came. Best effort, in words. */
646
+ async #deleteNamed(name) {
647
+ const listed = await this.#desktops();
648
+ if (!listed.ok)
649
+ return `; a computer named ${name} may be left (${listed.error.message}), which Orgo ends at its end`;
650
+ const found = listed.value.filter((one) => one.name === name);
651
+ if (found.length === 0)
652
+ return `; no computer named ${name} is in the workspace`;
653
+ const said = [];
654
+ for (const one of found) {
655
+ const deleted = await this.#delete({ id: one.id, name });
656
+ said.push(deleted.ok ? `${one.id} was deleted` : `${one.id} may be left (${deleted.error.message})`);
657
+ }
658
+ return `; the computer named ${name}: ${said.join("; ")}`;
659
+ }
660
+ /** DELETE, tried again while Orgo answers 409 (waking), then the wait until Orgo no longer has the computer. */
661
+ async #delete(ref, signal) {
662
+ const { requestMs, pollMs, goneMs } = this.#timeouts;
663
+ for (let tries = 1;; tries++) {
664
+ const deleted = await this.#rest.request("DELETE", `/computers/${encodeURIComponent(ref.id)}`, { timeoutMs: requestMs });
665
+ if (deleted.ok || deleted.error.code === "not_found")
666
+ break;
667
+ const status = deleted.status;
668
+ if (status !== 409 || tries >= DELETE_TRIES)
669
+ return deleted;
670
+ await pause(pollMs);
671
+ }
672
+ const until = Date.now() + goneMs;
673
+ let last = "unread";
674
+ for (;;) {
675
+ const read = await this.#get(ref.id, signal);
676
+ if (!read.ok && read.error.code === "not_found")
677
+ return ok(undefined);
678
+ if (read.ok && read.value.status === "deleted")
679
+ return ok(undefined);
680
+ if (!read.ok && read.error.code !== "timeout")
681
+ return fail(read.error.code, `release of ${ref.name}: reading it back failed (${read.error.message})`);
682
+ last = read.ok ? read.value.status : read.error.message;
683
+ if (Date.now() >= until)
684
+ return fail("timeout", `${ref.name} was still there ${seconds(goneMs)} after its delete; Orgo last read ${last}`);
685
+ await pause(pollMs, signal);
686
+ if (signal?.aborted)
687
+ return fail("aborted", `the wait for ${ref.name} to go was aborted; Orgo last read ${last}`);
688
+ }
689
+ }
690
+ /** The workspace's computers, as Orgo lists them. */
691
+ async #desktops(signal) {
692
+ const read = await this.#rest.request("GET", `/workspaces/${encodeURIComponent(this.#workspaceId)}`, { timeoutMs: this.#timeouts.listMs, ...(signal ? { signal } : {}) });
693
+ if (!read.ok)
694
+ return read;
695
+ const desktops = read.value?.desktops;
696
+ if (!Array.isArray(desktops))
697
+ return fail("orgo", `Orgo's workspace ${this.#workspaceId} lists no computers array`);
698
+ return ok(desktops.filter((one) => typeof one?.id === "string" && typeof one.name === "string").map((one) => ({ ...one, workspace_id: this.#workspaceId })));
699
+ }
700
+ /** The live view: screen.watch on a connection of the watch's own (daemonWatch), never Orgo's VNC (proxy only). */
701
+ watch(ref, handlers, options) {
702
+ return daemonWatch(this, ref, handlers, options);
703
+ }
704
+ async connect(ref) {
705
+ const problem = refProblem(ref);
706
+ if (problem)
707
+ return fail("invalid", problem);
708
+ const found = await this.#own(ref);
709
+ if (!found.ok)
710
+ return found;
711
+ if (found.value.status !== "running")
712
+ return fail("refused", `${ref.name} is ${found.value.status}, not running: its daemon does not run`);
713
+ const opened = await this.#open(ref);
714
+ if (!opened.ok)
715
+ return opened;
716
+ const { kind, groups } = this.capabilities();
717
+ const drift = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: "amd64" });
718
+ if (drift.length === 0)
719
+ return opened;
720
+ await opened.value.close();
721
+ return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drift.join("; ")}`);
722
+ }
723
+ async attach(ref, { signal } = {}) {
724
+ const given = (typeof ref === "object" && ref !== null ? ref : {});
725
+ if ((given.id === undefined) === (given.labels === undefined))
726
+ return fail("invalid", "attach takes { id } or { labels }, one of them");
727
+ if (given.id !== undefined) {
728
+ if (typeof given.id !== "string" || !COMPUTER_ID.test(given.id))
729
+ return fail("invalid", `${String(given.id)} is not an Orgo computer id`);
730
+ const read = await this.#get(given.id, signal);
731
+ if (!read.ok)
732
+ return read.error.code === "not_found" ? fail("not_found", `no Orgo computer has the id ${given.id}`) : read;
733
+ if (!this.#ours(read.value))
734
+ return fail("not_found", `no Orgo computer of this provider has the id ${given.id}`);
735
+ return this.#attached(read.value, signal);
736
+ }
737
+ const problem = filterProblem(given.labels);
738
+ if (problem)
739
+ return fail("invalid", problem);
740
+ const labels = given.labels;
741
+ if (Object.keys(labels).length === 0)
742
+ return fail("invalid", "attach by labels needs at least one label");
743
+ const listed = await this.list(labels, { signal });
744
+ if (!listed.ok)
745
+ return listed;
746
+ const words = JSON.stringify(labels);
747
+ if (listed.value.length === 0)
748
+ return fail("not_found", `no Orgo computer has the labels ${words}`);
749
+ if (listed.value.length > 1)
750
+ return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
751
+ const found = await this.#own(listed.value[0].ref, signal);
752
+ if (!found.ok)
753
+ return found;
754
+ return this.#attached(found.value, signal);
755
+ }
756
+ /**
757
+ * The drift check of a computer attach did not make: its labels file, the truth, held to its name, then its daemon
758
+ * and the probe, as at create. One that drifts is refused and left as it is. A computer that does not run is
759
+ * refused: reading it from inside would wake it.
760
+ */
761
+ async #attached(record, signal) {
762
+ const ref = { id: record.id, name: record.name };
763
+ if (record.status !== "running")
764
+ return fail("refused", `${ref.name} is ${record.status}: its labels file and daemon are read from inside, and a read would wake it`);
765
+ const file = await this.#readLabels(ref, signal);
766
+ if (!file.ok)
767
+ return file;
768
+ const found = [];
769
+ const parts = nameParts(record.name);
770
+ const { labels } = file.value;
771
+ if (typeof file.value.name !== "string" || !sameComputer(file.value.name, record.name))
772
+ found.push(`name: Orgo's is ${record.name}, the labels file's ${show(file.value.name)}`);
773
+ const run = labels[RUN_LABEL];
774
+ if ((parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
775
+ found.push(`run: the name's run hash ${show(parts.run)} is not the labels file's run ${show(run)}`);
776
+ if ((parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
777
+ found.push(`epoch: the name says ${show(parts.epoch)}, the labels file ${show(labels[EPOCH_LABEL])}`);
778
+ const deadline = new Date(file.value.deadline);
779
+ if (Number.isNaN(deadline.getTime()))
780
+ found.push(`deadline: the labels file reads ${show(file.value.deadline)}, not a time`);
781
+ let notes = [];
782
+ let kind;
783
+ if (found.length === 0) {
784
+ const ports = await this.#rootPorts(ref, signal);
785
+ if (!ports.ok)
786
+ return ports;
787
+ const opened = await this.#open(ref, signal);
788
+ if (!opened.ok)
789
+ return opened;
790
+ try {
791
+ const inside = await this.#checkInside(opened.value, ref.name, ports.value, signal);
792
+ if (!inside.ok && inside.error.code !== "refused")
793
+ return inside;
794
+ if (!inside.ok)
795
+ found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
796
+ else
797
+ notes = inside.value;
798
+ }
799
+ finally {
800
+ await opened.value.close();
801
+ }
802
+ kind = opened.value.hello.kind;
803
+ }
804
+ if (found.length > 0)
805
+ return fail("refused", `the computer ${ref.name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
806
+ return ok({
807
+ ...ref,
808
+ spec: {
809
+ image: file.value.image,
810
+ user: `${this.#uid}:${this.#gid}`,
811
+ network: "none",
812
+ ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }),
813
+ ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }),
814
+ workdir: WORK,
815
+ deadline,
816
+ ...(kind === undefined ? {} : { kind }),
817
+ },
818
+ ...(notes.length > 0 ? { notes } : {}),
819
+ });
820
+ }
821
+ /**
822
+ * Every computer of this provider in the workspace that carries all of these labels. The run and the epoch are read
823
+ * from the name, with nothing run in a computer, so a stopped one is listed too; any other label is read from the
824
+ * labels file of a running computer (a stopped one is not woken, so it proves no such label and is left out).
825
+ */
826
+ async list(labels, { signal } = {}) {
827
+ const problem = filterProblem(labels);
828
+ if (problem)
829
+ return fail("invalid", problem);
830
+ const listed = await this.#desktops(signal);
831
+ if (!listed.ok)
832
+ return listed;
833
+ const others = Object.keys(labels).filter((key) => key !== RUN_LABEL && key !== EPOCH_LABEL);
834
+ const infos = [];
835
+ for (const record of listed.value) {
836
+ const parts = nameParts(record.name);
837
+ if (parts === undefined || record.status === "deleted")
838
+ continue;
839
+ if (labels[RUN_LABEL] !== undefined && parts.run !== runHash(labels[RUN_LABEL]))
840
+ continue;
841
+ if (labels[EPOCH_LABEL] !== undefined && parts.epoch !== labels[EPOCH_LABEL])
842
+ continue;
843
+ const ref = { id: record.id, name: record.name };
844
+ const running = RUNNING.has(record.status);
845
+ let read = {
846
+ ...(labels[RUN_LABEL] !== undefined ? { [RUN_LABEL]: labels[RUN_LABEL] } : {}),
847
+ ...(parts.epoch !== undefined ? { [EPOCH_LABEL]: parts.epoch } : {}),
848
+ };
849
+ // The janitor's deadline is the name's; a name of an older make has none, and Orgo's end stands for it.
850
+ let deadline = parts.deadline ?? (typeof record.ends_at === "string" ? new Date(record.ends_at) : undefined);
851
+ if (others.length > 0) {
852
+ if (record.status !== "running")
853
+ continue;
854
+ const file = await this.#readLabels(ref, signal);
855
+ if (!file.ok)
856
+ continue;
857
+ if (!others.every((key) => file.value.labels[key] === labels[key]))
858
+ continue;
859
+ read = { ...file.value.labels };
860
+ deadline = parts.deadline ?? new Date(file.value.deadline);
861
+ }
862
+ infos.push({ ref, labels: read, deadline, state: running ? "running" : "stopped", network: "none" });
863
+ }
864
+ return ok(infos);
865
+ }
866
+ /** none, read back by the probe from inside, as the tool user; a change is refused: none is the one network here. */
867
+ /** Settings' test: one read of the workspace's computers (list with no label to read from inside), which makes nothing. */
868
+ async testConnection(context = {}) {
869
+ return listTested("Orgo", await this.list({}, context));
870
+ }
871
+ async network(ref, policy, { signal } = {}) {
872
+ const problem = refProblem(ref);
873
+ if (problem)
874
+ return fail("invalid", problem);
875
+ if (policy !== undefined && policy !== "none")
876
+ return fail("refused", NETWORK);
877
+ const found = await this.#own(ref, signal);
878
+ if (!found.ok)
879
+ return found;
880
+ if (found.value.status !== "running")
881
+ return fail("refused", `${ref.name} is ${found.value.status}: its network is read from inside, and a read would wake it`);
882
+ const ports = await this.#rootPorts(ref, signal);
883
+ if (!ports.ok)
884
+ return ports;
885
+ const opened = await this.#open(ref, signal);
886
+ if (!opened.ok)
887
+ return opened;
888
+ try {
889
+ const probe = await this.#probe(opened.value, ref.name, ports.value, signal);
890
+ if (!probe.ok)
891
+ return probe;
892
+ if (probe.value.reached.length > 0)
893
+ return ok({ other: `created with network none, yet from inside an answer came back from ${probe.value.reached.join(", ")}` });
894
+ return ok("none");
895
+ }
896
+ finally {
897
+ await opened.value.close();
898
+ }
899
+ }
900
+ /** delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. No stop. */
901
+ async release(ref, how, { signal } = {}) {
902
+ const problem = refProblem(ref);
903
+ if (problem)
904
+ return fail("invalid", problem);
905
+ if (how !== "stop" && how !== "delete")
906
+ return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
907
+ if (how === "stop")
908
+ return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete");
909
+ const read = await this.#get(ref.id);
910
+ if (!read.ok)
911
+ return read.error.code === "not_found" ? ok(undefined) : read;
912
+ if (read.value.status === "deleted")
913
+ return ok(undefined);
914
+ if (!this.#ours(read.value, ref.name))
915
+ return fail("not_found", `no Orgo computer of this provider is ${ref.name} (${ref.id}), so it is left as it is`);
916
+ return this.#delete(ref, signal);
917
+ }
918
+ /**
919
+ * Moves the deadline to now + ttlMs, never earlier and never past the most the labels file holds (create's time plus
920
+ * the cap): Orgo's end first, in whole hours with an Idempotency-Key, so it never ends the computer before init does;
921
+ * then init's deadline; then the name's, from the time init took; then the labels file. The result is the deadline
922
+ * init took. A computer's extends are taken in turn: each reads the deadline the one before it left, so a shorter one
923
+ * is refused as earlier, never renaming the computer back to an earlier deadline the janitor would trust.
924
+ */
925
+ extend(ref, ttlMs, context = {}) {
926
+ const key = typeof ref?.id === "string" ? ref.id : "";
927
+ const before = this.#extending.get(key) ?? Promise.resolve();
928
+ const turn = before.then(() => this.#extend(ref, ttlMs, context));
929
+ const settled = turn.then(() => undefined, () => undefined);
930
+ this.#extending.set(key, settled);
931
+ void settled.then(() => {
932
+ if (this.#extending.get(key) === settled)
933
+ this.#extending.delete(key);
934
+ });
935
+ return turn;
936
+ }
937
+ async #extend(ref, ttlMs, { signal } = {}) {
938
+ const problem = refProblem(ref);
939
+ if (problem)
940
+ return fail("invalid", problem);
941
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0)
942
+ return fail("invalid", "extend takes ttlMs, a whole number of milliseconds above 0");
943
+ const found = await this.#own(ref, signal);
944
+ if (!found.ok)
945
+ return found;
946
+ if (found.value.status !== "running")
947
+ return fail("refused", `${ref.name} is ${found.value.status}, not running`);
948
+ const file = await this.#readLabels(ref, signal);
949
+ if (!file.ok)
950
+ return file;
951
+ const most = Date.parse(file.value.maxDeadline);
952
+ const current = Date.parse(file.value.deadline);
953
+ const target = Date.now() + ttlMs;
954
+ if (Number.isNaN(most) || target > most)
955
+ return fail("limit", `${new Date(target).toISOString()} is past ${file.value.maxDeadline}, the most this computer may live`);
956
+ // An extend never shortens a computer's life: one that would is refused in words, and nothing moves.
957
+ if (target < current)
958
+ return fail("refused", `${new Date(target).toISOString()} is earlier than ${ref.name}'s deadline ${file.value.deadline}: an extend never moves it earlier; nothing moved`);
959
+ if (target === current)
960
+ return ok({ deadline: new Date(current) });
961
+ const end = typeof found.value.ends_at === "string" ? Date.parse(found.value.ends_at) : Number.NaN;
962
+ if (!Number.isNaN(end) && end < target) {
963
+ const hours = Math.ceil((target - end) / HOUR);
964
+ const moved = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/extend`, { body: { hours }, headers: { "idempotency-key": randomUUID() }, timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
965
+ if (!moved.ok)
966
+ return fail(moved.error.code, `Orgo's end did not move, so nothing did: ${moved.error.message}`);
967
+ }
968
+ // Init's deadline next, then the janitor's, in the name (a rename, its stable part kept), from the time init took:
969
+ // the name, init and the labels file then agree. A step that fails leaves the janitor ending the computer no later
970
+ // than init, never after it.
971
+ const opened = await this.#open(ref, signal);
972
+ if (!opened.ok)
973
+ return fail(opened.error.code, `Orgo's end moved, and init's deadline did not: ${opened.error.message}`);
974
+ let took;
975
+ try {
976
+ const at = new Date(target).toISOString();
977
+ const extended = await opened.value.client.call("deadline.extend", { at }, { signal: this.#bounded(this.#timeouts.helloMs, signal) });
978
+ if (!extended.ok)
979
+ return fail(extended.error.code, `Orgo's end moved, and init's deadline did not: ${extended.error.message}`);
980
+ const answered = Date.parse(extended.value.at);
981
+ took = new Date(Number.isNaN(answered) ? at : answered);
982
+ }
983
+ finally {
984
+ await opened.value.close();
985
+ }
986
+ // The name's deadline never moves back: a name that already holds this deadline or a later one is kept.
987
+ const parts = nameParts(found.value.name);
988
+ const name = parts.deadline !== undefined && parts.deadline.getTime() >= Math.ceil(took.getTime() / 1000) * 1000 ? found.value.name : withDeadline(parts.stable, took);
989
+ if (name !== found.value.name) {
990
+ const renamed = await this.#rest.request("PATCH", `/computers/${encodeURIComponent(ref.id)}`, { body: { name }, timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
991
+ if (!renamed.ok)
992
+ return fail(renamed.error.code, `init's deadline moved to ${took.toISOString()}, and the deadline in ${found.value.name} did not: ${renamed.error.message}`);
993
+ }
994
+ const written = await this.#writeLabels(ref, { ...file.value, name, deadline: took.toISOString() }, signal);
995
+ if (!written.ok)
996
+ return fail(written.error.code, `init's deadline moved to ${took.toISOString()}, and the labels file did not: ${written.error.message}`);
997
+ return ok({ deadline: took });
998
+ }
999
+ }
1000
+ /**
1001
+ * An OrgoProvider from its options alone, its key included: it reads no environment. Serve passes apiKey from its
1002
+ * ORGO_API_KEY setting and its workspace; the conformance module reads COMPUTER_ORGO_* (settingsFromEnv).
1003
+ */
1004
+ export function create(options) {
1005
+ return new OrgoProvider(options);
1006
+ }