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

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 (107) hide show
  1. package/README.md +251 -46
  2. package/box/Dockerfile +3 -1
  3. package/box/agentrun-archil +59 -7
  4. package/box/build-daytona.py +20 -4
  5. package/dist/browser.d.ts +73 -23
  6. package/dist/browser.js +141 -17
  7. package/dist/browserbase.d.ts +48 -25
  8. package/dist/browserbase.js +176 -29
  9. package/dist/chrome.d.ts +3 -4
  10. package/dist/chrome.js +6 -11
  11. package/dist/computerd-linux-amd64 +0 -0
  12. package/dist/computerd-linux-arm64 +0 -0
  13. package/dist/conformance/browserbase.js +1 -1
  14. package/dist/conformance/cases/provider.js +78 -3
  15. package/dist/conformance/daytona.d.ts +4 -0
  16. package/dist/conformance/daytona.js +7 -1
  17. package/dist/conformance/e2b.js +2 -1
  18. package/dist/conformance/fixture.js +24 -2
  19. package/dist/conformance/kernel.js +1 -1
  20. package/dist/conformance/kind.js +2 -1
  21. package/dist/conformance/{local.d.ts → local-chrome.d.ts} +7 -7
  22. package/dist/conformance/{local.js → local-chrome.js} +11 -11
  23. package/dist/conformance/orgo.d.ts +11 -5
  24. package/dist/conformance/orgo.js +37 -8
  25. package/dist/conformance/phone-harness.js +2 -1
  26. package/dist/conformance/report.js +3 -2
  27. package/dist/conformance/runner.js +25 -7
  28. package/dist/conformance/types.d.ts +21 -8
  29. package/dist/conformance/types.js +10 -0
  30. package/dist/conformance/windows-fixture.d.ts +1 -0
  31. package/dist/conformance/windows-fixture.js +37 -0
  32. package/dist/daytona.d.ts +16 -35
  33. package/dist/daytona.js +87 -95
  34. package/dist/descriptor.d.ts +116 -0
  35. package/dist/descriptor.js +92 -0
  36. package/dist/descriptors/browserbase.d.ts +25 -0
  37. package/dist/descriptors/browserbase.js +20 -0
  38. package/dist/descriptors/daytona.d.ts +83 -0
  39. package/dist/descriptors/daytona.js +81 -0
  40. package/dist/descriptors/docker.d.ts +12 -0
  41. package/dist/descriptors/docker.js +17 -0
  42. package/dist/descriptors/e2b.d.ts +22 -0
  43. package/dist/descriptors/e2b.js +19 -0
  44. package/dist/descriptors/index.d.ts +256 -0
  45. package/dist/descriptors/index.js +19 -0
  46. package/dist/descriptors/kernel.d.ts +21 -0
  47. package/dist/descriptors/kernel.js +17 -0
  48. package/dist/descriptors/local-chrome.d.ts +17 -0
  49. package/dist/descriptors/local-chrome.js +21 -0
  50. package/dist/descriptors/modal.d.ts +54 -0
  51. package/dist/descriptors/modal.js +48 -0
  52. package/dist/descriptors/orgo.d.ts +99 -0
  53. package/dist/descriptors/orgo.js +49 -0
  54. package/dist/descriptors/phone-harness.d.ts +33 -0
  55. package/dist/descriptors/phone-harness.js +23 -0
  56. package/dist/descriptors/shared.d.ts +7 -0
  57. package/dist/descriptors/shared.js +6 -0
  58. package/dist/desktop.d.ts +4 -4
  59. package/dist/desktop.js +4 -4
  60. package/dist/docker/egress.d.ts +5 -4
  61. package/dist/docker/egress.js +7 -6
  62. package/dist/docker/image.js +17 -15
  63. package/dist/docker/inspect.d.ts +147 -0
  64. package/dist/docker/inspect.js +335 -0
  65. package/dist/docker.d.ts +6 -6
  66. package/dist/docker.js +53 -47
  67. package/dist/drift.d.ts +3 -145
  68. package/dist/drift.js +5 -334
  69. package/dist/e2b.d.ts +2 -8
  70. package/dist/e2b.js +17 -23
  71. package/dist/index.d.ts +9 -12
  72. package/dist/index.js +14 -12
  73. package/dist/isolation.js +2 -2
  74. package/dist/janitor.d.ts +20 -2
  75. package/dist/janitor.js +67 -19
  76. package/dist/kernel.d.ts +19 -29
  77. package/dist/kernel.js +110 -32
  78. package/dist/kinds.d.ts +59 -34
  79. package/dist/kinds.js +19 -117
  80. package/dist/labels.d.ts +20 -0
  81. package/dist/labels.js +62 -1
  82. package/dist/{local.d.ts → local-chrome.d.ts} +8 -9
  83. package/dist/{local.js → local-chrome.js} +26 -19
  84. package/dist/local-supervisor.d.ts +3 -3
  85. package/dist/local-supervisor.js +3 -3
  86. package/dist/modal.d.ts +6 -25
  87. package/dist/modal.js +86 -88
  88. package/dist/mount-archil.d.ts +25 -3
  89. package/dist/mount-archil.js +43 -12
  90. package/dist/orgo-channel.js +16 -13
  91. package/dist/orgo-desktop.d.ts +162 -0
  92. package/dist/orgo-desktop.js +1856 -0
  93. package/dist/orgo-names.d.ts +178 -0
  94. package/dist/orgo-names.js +287 -0
  95. package/dist/orgo.d.ts +34 -20
  96. package/dist/orgo.js +424 -173
  97. package/dist/phone-harness.d.ts +7 -12
  98. package/dist/phone-harness.js +70 -54
  99. package/dist/protocol.d.ts +5 -0
  100. package/dist/provider.d.ts +153 -10
  101. package/dist/provider.js +48 -1
  102. package/dist/providers.d.ts +23 -24
  103. package/dist/providers.js +14 -17
  104. package/dist/result.d.ts +11 -1
  105. package/dist/result.js +11 -0
  106. package/dist/test-connection.js +2 -2
  107. package/package.json +42 -2
package/dist/orgo.js CHANGED
@@ -16,43 +16,50 @@ import { readFileSync } from "node:fs";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { childCommands, daemonDrift } from "./child.js";
18
18
  import { DaemonClient } from "./client.js";
19
+ import { ORGO, ORGO_BASE_IMAGE } from "./descriptors/orgo.js";
19
20
  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_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
21
+ import { DAEMON_IN_COMPUTER, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, SOCKET_DIR, WORK } from "./drift.js";
22
+ import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
22
23
  import { checkMount } from "./mount.js";
23
24
  import { ORGO_API_URL, orgoRest, orgoTerminalChannel, START_LOG } from "./orgo-channel.js";
24
- import { checkGpu, checkLifetime, } from "./provider.js";
25
- import { fail, ok } from "./result.js";
25
+ import { OrgoDesktopProvider } from "./orgo-desktop.js";
26
+ import { COMPUTER_ID, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, claimProblem, andSettled, inTurn, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, withDeadline, } from "./orgo-names.js";
27
+ import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
28
+ import { failFor, ok, vendorFail } from "./result.js";
26
29
  import { daemonWatch } from "./screen-watch.js";
27
30
  import { listTested } from "./test-connection.js";
31
+ /** This module's failures: one with code vendor names Orgo. */
32
+ const fail = failFor("orgo");
28
33
  /** 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 network an Orgo desktop's programs get: none, a network of their own. */
31
- export const NETWORK = ["none"];
34
+ export const MOUNT = ORGO.mounts;
32
35
  /** The groups every Orgo computer offers: a Linux shell, files and processes, and the desktop's screen and input. */
33
36
  const GROUPS = ["exec", "files", "processes", ...DESKTOP_GROUPS];
34
- /** What a built provider declares, known without building one: one configuration, a Linux desktop (the registry's entry). */
35
- export const CAPABILITIES = [{ kind: "desktop", groups: [...GROUPS] }];
37
+ /**
38
+ * What a built provider declares, known without building one, per configuration (its descriptor's): the Linux desktop
39
+ * with computerd (the default), then the Windows and the macOS desktops Orgo's own API answers (options.os).
40
+ */
41
+ export const CAPABILITIES = ORGO.capabilities;
36
42
  /** The conformance CLI's module for Orgo: its live switch, the run's 1 h cap and the drifted twin. */
37
43
  export const conformance = () => import("./conformance/orgo.js");
38
44
  const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
39
45
  const HOUR = 3_600_000;
40
46
  /** Orgo's longest end: ends_in_hours is at most 720. */
41
47
  const MAX_LIFETIME_MS = 720 * HOUR;
48
+ /**
49
+ * The most init's deadline of an agent's own computer may move to: none in practice. Its deadline is maxLifetimeMs out
50
+ * from create, and each attach moves it maxLifetimeMs out again (deadline.extend), so only a desktop left detached for
51
+ * longer than that loses its daemon, which the next attach then installs again (#replaceDaemon).
52
+ */
53
+ const OWNED_MAX_DEADLINE = "9999-12-31T23:59:59.000Z";
42
54
  /** Orgo's RAM sizes, in GB, and the vCPUs each takes by default. */
43
55
  const RAM_GB = [4, 8, 16, 32];
44
56
  const CPU_FOR_RAM = { 4: 1, 8: 2, 16: 4, 32: 6 };
45
57
  /** The vCPUs a computer may ask for on its own (8 needs Orgo to set the account up). */
46
58
  const CPUS = [0.5, 1, 2, 4, 6];
47
- const NAME_MAX = 80;
48
- /** A name of this provider's making: computer-<12 hex>, the run label's hash, the epoch label, the deadline (base 36 s). */
49
- 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}))?$/;
50
59
  /** An Orgo template: namespace/name@version. */
51
60
  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}$/;
52
- /** Orgo's base desktop, no template: the image a spec names for a plain Linux desktop, and the default for kind desktop. */
53
- export const ORGO_BASE_IMAGE = "linux";
61
+ /** Orgo's base desktop, no template: the image a spec names for a plain Linux desktop, and its descriptor's default. */
54
62
  const BASE = ORGO_BASE_IMAGE;
55
- const COMPUTER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
56
63
  const WORKSPACE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
57
64
  const USER = /^(\d+):(\d+)$/;
58
65
  const DISPLAY = /^:(\d{1,5})(?:\.\d{1,5})?$/;
@@ -69,7 +76,7 @@ const DELETE_TRIES = 5;
69
76
  const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "labels", "gpu"]);
70
77
  /** The states in which a computer runs, or is on its way to. */
71
78
  const RUNNING = new Set(["running", "creating", "restarting", "updating", "resuming"]);
72
- /** Why a network other than "none" is refused (NETWORK is the forms it makes). */
79
+ /** Why a network other than "none" is refused: this configuration makes none alone. */
73
80
  const NETWORK_REFUSAL = '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';
74
81
  /** The scripts the provider runs as root, each marked on its first line, its arguments after it. */
75
82
  const X11_SCRIPT = ["# agentrun-computer: orgo-x11", "s=$1", '[ -S "$s" ] || { echo "no X socket at $s"; exit 1; }'].join("\n");
@@ -83,6 +90,31 @@ const STATUS_SCRIPT = [
83
90
  'if [ -S "$s" ]; then echo "socket present"; else echo "socket absent"; fi',
84
91
  "echo \"log $(tail -c 300 \"$l\" 2>/dev/null | tr '\\n' ' ')\"",
85
92
  ].join("\n");
93
+ /**
94
+ * Stops computerd init by its exact processes (pgrep anchored to init's own command line, so neither this script nor
95
+ * pgrep matches itself): SIGTERM to each PID, on which init ends its programs, then up to 10 s for each to be gone (a
96
+ * zombie counts as gone), then SIGKILL to those left. Prints `stopped <pids>`, or `no init running`; exits 1 when one
97
+ * outlives the SIGKILL.
98
+ */
99
+ const STOP_INIT_SCRIPT = [
100
+ "# agentrun-computer: orgo-stop-init",
101
+ "d=$1",
102
+ 'pids=$(pgrep -f "^$d init") || { echo "no init running"; exit 0; }',
103
+ "alive() { [ -e \"/proc/$1\" ] && [ \"$(awk '{ print $3 }' \"/proc/$1/stat\" 2>/dev/null)\" != Z ]; }",
104
+ "kill -TERM $pids 2>/dev/null",
105
+ "i=0",
106
+ "while [ $i -lt 100 ]; do",
107
+ "\tleft=",
108
+ '\tfor p in $pids; do alive "$p" && left="$left $p"; done',
109
+ '\t[ -n "$left" ] || { echo "stopped" $pids; exit 0; }',
110
+ "\tsleep 0.1",
111
+ "\ti=$((i + 1))",
112
+ "done",
113
+ "kill -KILL $left 2>/dev/null",
114
+ "sleep 1",
115
+ 'for p in $left; do alive "$p" && { echo "init $p outlived SIGKILL"; exit 1; }; done',
116
+ 'echo "stopped" $pids',
117
+ ].join("\n");
86
118
  /**
87
119
  * The TCP ports root listens on in Orgo's own network (its agent, its VNC, anything else of the image's), one decimal
88
120
  * port a line, from /proc/net/tcp and tcp6 (state 0A, LISTEN): no tool of the image's is relied on but awk.
@@ -127,7 +159,6 @@ export const LOCKDOWN_SCRIPT = [
127
159
  "EOF",
128
160
  "exit $failed",
129
161
  ].join("\n");
130
- const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
131
162
  const seconds = (ms) => `${ms / 1000} s`;
132
163
  const pause = (ms, signal) => new Promise((done) => {
133
164
  const timer = setTimeout(finish, ms);
@@ -141,77 +172,6 @@ const pause = (ms, signal) => new Promise((done) => {
141
172
  else
142
173
  signal?.addEventListener("abort", finish, { once: true });
143
174
  });
144
- /**
145
- * The name of a computer with these labels: computer-<hex>, then -r<the run label's hash> and -e<the epoch label> when
146
- * the labels carry a run and an epoch that is one, then -d<the deadline> when given: whole seconds since the epoch,
147
- * 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
148
- * value. Everything but the deadline is the name's stable part, which a rename on extend keeps.
149
- */
150
- export function orgoName(labels, hex, deadline) {
151
- const run = labels[RUN_LABEL];
152
- const epoch = labels[EPOCH_LABEL];
153
- 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}` : ""}`;
154
- return deadline === undefined ? stable : withDeadline(stable, deadline);
155
- }
156
- /** A name's stable part with this deadline. */
157
- function withDeadline(stable, deadline) {
158
- return `${stable}-d${Math.ceil(deadline.getTime() / 1000).toString(36)}`;
159
- }
160
- /** What a name of this provider's making says, or undefined for any other name: its stable part, and its deadline. */
161
- function nameParts(name) {
162
- const match = typeof name === "string" ? NAME.exec(name) : null;
163
- if (match === null)
164
- return undefined;
165
- const seconds = match[4] === undefined ? Number.NaN : Number.parseInt(match[4], 36);
166
- return {
167
- hex: match[1],
168
- ...(match[2] ? { run: match[2] } : {}),
169
- ...(match[3] !== undefined ? { epoch: match[3] } : {}),
170
- stable: name.replace(/-d[0-9a-z]+$/, ""),
171
- ...(Number.isSafeInteger(seconds) ? { deadline: new Date(seconds * 1000) } : {}),
172
- };
173
- }
174
- /** Whether two names are one computer's: their stable parts are the same (the deadline moves with extend). */
175
- const sameComputer = (a, b) => nameParts(a)?.stable !== undefined && nameParts(a)?.stable === nameParts(b)?.stable;
176
- function labelProblem(key, value) {
177
- if (typeof value !== "string")
178
- return `the label ${key} must be a string`;
179
- if (key === "" || key.includes("\0") || value.includes("\0"))
180
- return `the label ${JSON.stringify(key)} must be a non-empty name, and neither holds a NUL byte`;
181
- if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
182
- return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
183
- return undefined;
184
- }
185
- function filterProblem(labels) {
186
- if (typeof labels !== "object" || labels === null || Array.isArray(labels))
187
- return "labels must map names to strings";
188
- for (const [key, value] of Object.entries(labels)) {
189
- if (typeof value !== "string" || key === "" || key.includes("\0") || value.includes("\0"))
190
- return `the label ${JSON.stringify(key)} must be a non-empty name and a string, with no NUL byte`;
191
- }
192
- return undefined;
193
- }
194
- /** Why ref is not an Orgo computer's ref, or undefined. */
195
- function refProblem(ref) {
196
- if (typeof ref?.name !== "string" || nameParts(ref.name) === undefined)
197
- return `${String(ref?.name)} is not the name of an Orgo computer of this provider (computer-<12 hex digits>...)`;
198
- if (typeof ref.id !== "string" || !COMPUTER_ID.test(ref.id))
199
- return `${String(ref.id)} is not an Orgo computer id`;
200
- return undefined;
201
- }
202
- /** The labels file as written, or why it is not. */
203
- function labelsOf(text) {
204
- try {
205
- const value = JSON.parse(text);
206
- if (typeof value?.name === "string" && typeof value.labels === "object" && value.labels !== null && typeof value.deadline === "string" && typeof value.maxDeadline === "string" && typeof value.image === "string") {
207
- return value;
208
- }
209
- }
210
- catch {
211
- // Said below.
212
- }
213
- return `the labels file ${LABELS_FILE} is not the one create writes`;
214
- }
215
175
  /**
216
176
  * Orgo desktops: see the module's header. A spec's image is "linux" (Orgo's base desktop) or an Orgo template
217
177
  * (namespace/name@version); cpus and memoryMb are Orgo's sizes; the network is none.
@@ -230,9 +190,12 @@ export class OrgoProvider {
230
190
  #display;
231
191
  #timeouts;
232
192
  #probeTargets;
193
+ #ledger;
233
194
  /** Each computer's extend in flight, by id: the next waits for it, so two never read the same old deadline. */
234
195
  #extending = new Map();
235
- 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 }) {
196
+ /** Each agent's computer's attach or detach in flight, by id: the next waits for it, so two never overlap here. */
197
+ #owning = new Map();
198
+ 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, ledger = orgoMemoryLedger() }) {
236
199
  if (typeof apiKey !== "string" || apiKey === "")
237
200
  throw new Error("options.apiKey, an Orgo API key, is required");
238
201
  if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId))
@@ -275,19 +238,22 @@ export class OrgoProvider {
275
238
  this.#display = display;
276
239
  this.#timeouts = merged;
277
240
  this.#probeTargets = [...probeTargets];
241
+ this.#ledger = ledger;
278
242
  }
279
243
  /**
280
244
  * daemon child: Orgo's own agent is the VM's first process, and init is a command it ran. lifetime janitor: Orgo ends
281
245
  * a computer only in whole hours (ends_in_hours, the backstop), so the janitor deletes it at its exact deadline, which
282
246
  * its name carries (list() reads it with nothing run inside); init ends its programs at that deadline inside. network
283
- * none alone, read back by the probe from inside (Orgo reads no policy back). release delete alone: Orgo's stop
284
- * freezes a computer, which nothing here needs.
247
+ * none alone, read back by the probe from inside (Orgo reads no policy back). release delete, and detach for an
248
+ * agent's own computer: Orgo's suspend saves its memory and disk, so it resumes where it was (persistence resume),
249
+ * computerd init with it.
285
250
  */
286
251
  capabilities() {
287
252
  return {
288
253
  kind: "desktop",
289
254
  lifetime: "janitor",
290
- network: [...NETWORK],
255
+ // This configuration's form, one of Orgo's descriptor's: none (the Windows desktop's is open).
256
+ network: ["none"],
291
257
  networkReadBack: false,
292
258
  isolation: "vm",
293
259
  os: "linux",
@@ -298,16 +264,17 @@ export class OrgoProvider {
298
264
  mount: [...MOUNT],
299
265
  // Init starts with --own-network (childCommands): no tool reaches these, nor any port root listens on.
300
266
  vendorAgentPorts: [...ORGO_AGENT_PORTS],
267
+ persistence: { keepsState: true, resume: true },
301
268
  };
302
269
  }
303
270
  check(spec) {
304
271
  const refusals = [];
305
272
  const refuse = (field, message) => refusals.push({ field, message });
306
273
  const given = (typeof spec === "object" && spec !== null ? spec : {});
307
- const { image, lifetimeMs, network, cpus, memoryMb, labels, mount } = given;
274
+ const { image, network, cpus, memoryMb, labels, mount } = given;
308
275
  if (image !== BASE && !(typeof image === "string" && TEMPLATE.test(image)))
309
276
  refuse("image", `an image is "${BASE}" (Orgo's base desktop) or an Orgo template, namespace/name@version`);
310
- refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
277
+ refusals.push(...checkTenure(given, this.capabilities(), "Orgo"));
311
278
  if (network !== "none")
312
279
  refuse("network", NETWORK_REFUSAL);
313
280
  if (memoryMb !== undefined && !RAM_GB.some((gb) => gb * 1024 === memoryMb))
@@ -323,7 +290,7 @@ export class OrgoProvider {
323
290
  refusals.push(...checkMount(mount, MOUNT));
324
291
  refusals.push(...checkGpu(given.gpu, this.capabilities()));
325
292
  for (const [field, value] of Object.entries(given)) {
326
- if (SPEC_FIELDS.has(field) || field === "mount" || value === undefined)
293
+ if (SPEC_FIELDS.has(field) || field === "mount" || field === "owner" || value === undefined)
327
294
  continue;
328
295
  if (field === "user")
329
296
  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`);
@@ -349,12 +316,17 @@ export class OrgoProvider {
349
316
  }
350
317
  if (signal?.aborted)
351
318
  return fail("aborted", "create was aborted before Orgo was called");
352
- const labels = { ...spec.labels };
319
+ // An agent's own computer outlives the run: no janitor's deadline and no Orgo end, the owner in its name and labels.
320
+ // Init still takes one, maxLifetimeMs out, since it ends its programs at its deadline, with no most in practice:
321
+ // each attach moves it maxLifetimeMs out again (#ownedInit).
322
+ const owner = spec.owner;
323
+ const labels = { ...spec.labels, ...(owner === undefined ? {} : ownerLabels(owner)) };
353
324
  const now = Date.now();
354
- const deadline = new Date(now + spec.lifetimeMs).toISOString();
355
325
  const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
326
+ const deadline = owner === undefined ? new Date(now + runLifetimeMs(spec)).toISOString() : maxDeadline;
327
+ const init = owner === undefined ? { deadline, maxDeadline } : this.#ownedInit(now);
356
328
  // The janitor's deadline is in the name, so list() and the sweep read it with nothing run inside.
357
- const name = orgoName(labels, randomBytes(6).toString("hex"), new Date(deadline));
329
+ const name = orgoName(labels, randomBytes(6).toString("hex"), owner === undefined ? new Date(deadline) : undefined, owner);
358
330
  if (name.length > NAME_MAX || nameParts(name) === undefined)
359
331
  return fail("invalid", `the name ${name} is not one Orgo holds: at most ${NAME_MAX} of letters, digits and dashes`);
360
332
  const ram = spec.memoryMb === undefined ? 4 : spec.memoryMb / 1024;
@@ -366,7 +338,7 @@ export class OrgoProvider {
366
338
  ram,
367
339
  cpu,
368
340
  // Orgo's end, the vendor's backstop: whole hours, deleting the computer and its disk. init ends it on time.
369
- ends_in_hours: Math.max(1, Math.ceil(spec.lifetimeMs / HOUR)),
341
+ ...(owner === undefined ? { ends_in_hours: Math.max(1, Math.ceil(runLifetimeMs(spec) / HOUR)) } : {}),
370
342
  ...(spec.image === BASE ? {} : { template_ref: spec.image }),
371
343
  };
372
344
  const made = await this.#rest.request("POST", "/computers", { body, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
@@ -378,10 +350,16 @@ export class OrgoProvider {
378
350
  }
379
351
  const id = made.value?.id;
380
352
  if (typeof id !== "string" || !COMPUTER_ID.test(id))
381
- return fail("orgo", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
353
+ return vendorFail("orgo", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
382
354
  const ref = { id, name };
383
- const file = { name, labels, deadline, maxDeadline, image: spec.image, cpus: cpu, memoryMb: ram * 1024 };
384
- const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal);
355
+ // An agent's computer's labels go in the ledger at once, so list finds it as the agent's whatever happens next.
356
+ if (owner !== undefined) {
357
+ const kept = await this.#keep({ id, labels });
358
+ if (!kept.ok)
359
+ return this.#abandon(ref, kept.error);
360
+ }
361
+ const file = { name, labels, deadline: owner === undefined ? deadline : NO_DEADLINE, maxDeadline: owner === undefined ? maxDeadline : NO_DEADLINE, image: spec.image, cpus: cpu, memoryMb: ram * 1024 };
362
+ const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal, init);
385
363
  if (signal?.aborted)
386
364
  return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
387
365
  if (prepared.ok)
@@ -393,7 +371,7 @@ export class OrgoProvider {
393
371
  * installed (its sha256 read back), Orgo's X server's path socket there, the labels file, init started, its first
394
372
  * connection, then the daemon's report and the probe. Its value is the probe's notes.
395
373
  */
396
- async #prepare(ref, status, file, daemon, signal) {
374
+ async #prepare(ref, status, file, daemon, signal, init = file) {
397
375
  const { uploadMs, execMs } = this.#timeouts;
398
376
  const running = status === "running" ? ok(undefined) : await this.#untilRunning(ref, signal);
399
377
  if (!running.ok)
@@ -402,7 +380,7 @@ export class OrgoProvider {
402
380
  const uploaded = await this.#channel.upload(ref.id, staging, daemon, { timeoutMs: uploadMs, ...(signal ? { signal } : {}) });
403
381
  if (!uploaded.ok)
404
382
  return fail(uploaded.error.code, `the daemon's upload into ${ref.name} failed: ${uploaded.error.message}`);
405
- const commands = childCommands({ staging, deadline: file.deadline, user: `${this.#uid}:${this.#gid}`, display: this.#display, maxDeadline: file.maxDeadline });
383
+ const commands = childCommands({ staging, deadline: init.deadline, user: `${this.#uid}:${this.#gid}`, display: this.#display, maxDeadline: init.maxDeadline });
406
384
  const install = await this.#channel.run(ref.id, ["sh", "-c", commands.install], { timeoutMs: execMs, ...(signal ? { signal } : {}) });
407
385
  if (!install.ok)
408
386
  return install;
@@ -500,7 +478,7 @@ export class OrgoProvider {
500
478
  if (last === "running")
501
479
  return ok(undefined);
502
480
  if (!RUNNING.has(last))
503
- return fail("orgo", `Orgo read ${ref.name} ${last}, not running`);
481
+ return vendorFail("orgo", `Orgo read ${ref.name} ${last}, not running`);
504
482
  if (Date.now() >= until)
505
483
  return fail("timeout", `Orgo did not read ${ref.name} running within ${seconds(this.#timeouts.createMs)}; it last read ${last}`);
506
484
  await pause(this.#timeouts.pollMs, signal);
@@ -522,7 +500,7 @@ export class OrgoProvider {
522
500
  return read;
523
501
  if (read.value.exitCode !== 0)
524
502
  return fail("refused", `${ref.name} has no labels file ${LABELS_FILE} to read (exit ${read.value.exitCode})`);
525
- const file = labelsOf(read.value.output);
503
+ const file = labelsOf(read.value.output, LABELS_FILE);
526
504
  return typeof file === "string" ? fail("refused", `${ref.name}: ${file}`) : ok(file);
527
505
  }
528
506
  /**
@@ -539,6 +517,10 @@ export class OrgoProvider {
539
517
  const drift = [...found.value, ...probeNetworkDrift(probe.value)];
540
518
  return drift.length === 0 ? ok(probeNotes(probe.value, "none")) : fail("refused", `it did not match its spec: ${drift.join("; ")}`);
541
519
  }
520
+ /** Init's deadline and its most for an agent's own computer started at now: maxLifetimeMs out, and none in practice. */
521
+ #ownedInit(now) {
522
+ return { deadline: new Date(now + this.#maxLifetimeMs).toISOString(), maxDeadline: OWNED_MAX_DEADLINE };
523
+ }
542
524
  #daemonExpected() {
543
525
  const { kind, groups } = this.capabilities();
544
526
  return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: "amd64", kind, groups };
@@ -585,7 +567,7 @@ export class OrgoProvider {
585
567
  return fail("timeout", `the daemon in ${ref.name} did not answer hello within ${seconds(helloMs)}`);
586
568
  if (hello.error.code !== "gone")
587
569
  return hello;
588
- return { ...fail("orgo", `cannot reach the daemon in ${ref.name}: ${stream.said() || hello.error.message}`), notListening: true };
570
+ return { ...vendorFail("orgo", `cannot reach the daemon in ${ref.name}: ${stream.said() || hello.error.message}`), notListening: true };
589
571
  }
590
572
  return ok({ client, hello: hello.value, close });
591
573
  }
@@ -605,13 +587,18 @@ export class OrgoProvider {
605
587
  if (!read.ok)
606
588
  return read;
607
589
  if (typeof read.value?.name !== "string" || typeof read.value.status !== "string")
608
- return fail("orgo", `Orgo's record of ${id} has no name or status`);
590
+ return vendorFail("orgo", `Orgo's record of ${id} has no name or status`);
609
591
  return ok(read.value);
610
592
  }
611
593
  /** Whether Orgo's record is a computer of this provider: its name's shape, in this workspace. */
612
594
  #ours(record, name) {
613
595
  // A ref's name matches by its stable part: extend renames the computer with its new deadline.
614
- return nameParts(record.name) !== undefined && (record.workspace_id ?? record.project_id) === this.#workspaceId && (name === undefined || sameComputer(record.name, name)) && record.status !== "deleted";
596
+ // A Windows or macOS computer in the workspace is the desktop provider's (orgo-desktop.ts), where Orgo says its os.
597
+ return (nameParts(record.name) !== undefined &&
598
+ (record.workspace_id ?? record.project_id) === this.#workspaceId &&
599
+ (name === undefined || sameComputer(record.name, name)) &&
600
+ record.status !== "deleted" &&
601
+ (record.os === undefined || record.os === "linux"));
615
602
  }
616
603
  /** This provider's computer for ref, as Orgo reads it, or why not. */
617
604
  async #own(ref, signal) {
@@ -642,6 +629,54 @@ export class OrgoProvider {
642
629
  }
643
630
  return `; the computer named ${name}: ${said.join("; ")}`;
644
631
  }
632
+ /** An agent's computer's ledger entry, put; a ledger that fails is a failure in words. */
633
+ async #keep(entry) {
634
+ try {
635
+ await this.#ledger.put(entry);
636
+ return ok(undefined);
637
+ }
638
+ catch (error) {
639
+ return vendorFail("orgo", `the ledger of agents' computers could not be written: ${error instanceof Error ? error.message : String(error)}`);
640
+ }
641
+ }
642
+ /** Every agent's computer's ledger entry, by id. */
643
+ async #entries() {
644
+ try {
645
+ return ok(new Map((await this.#ledger.list()).map((entry) => [entry.id, entry])));
646
+ }
647
+ catch (error) {
648
+ return vendorFail("orgo", `the ledger of agents' computers could not be read: ${error instanceof Error ? error.message : String(error)}`);
649
+ }
650
+ }
651
+ /** A deleted computer's ledger entry, gone; best effort, since the computer is gone whatever the ledger says. */
652
+ async #forget(id) {
653
+ try {
654
+ await this.#ledger.remove(id);
655
+ }
656
+ catch {
657
+ // A stale entry names a computer Orgo no longer has: list never shows it.
658
+ }
659
+ }
660
+ /**
661
+ * An agent's computer deleted under `claim` (ReleaseContext): its entry taken first, only while it carries exactly the
662
+ * claim's run and epoch and no attach or detach holds it (takeEntry, only), so a claim that made it and lost it never
663
+ * deletes it from under a later claim. A delete Orgo refused lets the entry go again; one Orgo took forgot it already.
664
+ */
665
+ #claimedDelete(ref, name, claim, signal) {
666
+ const owner = nameParts(name)?.owner;
667
+ if (owner === undefined)
668
+ return Promise.resolve(fail("refused", `${ref.name} is a run's computer: a delete under a claim is an agent's own computer's alone, so it is left as it is`));
669
+ return inTurn(this.#owning, ref.id, async () => {
670
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being deleted", { only: true });
671
+ if (!taken.ok)
672
+ return taken;
673
+ const deleted = await this.#delete(ref, signal);
674
+ if (deleted.ok)
675
+ return deleted;
676
+ const left = await this.#entries();
677
+ return left.ok && !left.value.has(ref.id) ? deleted : andSettled(deleted, await settleEntry(this.#ledger, ref, taken.value));
678
+ });
679
+ }
645
680
  /** DELETE, tried again while Orgo answers 409 (waking), then the wait until Orgo no longer has the computer. */
646
681
  async #delete(ref, signal) {
647
682
  const { requestMs, pollMs, goneMs } = this.#timeouts;
@@ -654,6 +689,7 @@ export class OrgoProvider {
654
689
  return deleted;
655
690
  await pause(pollMs);
656
691
  }
692
+ await this.#forget(ref.id);
657
693
  const until = Date.now() + goneMs;
658
694
  let last = "unread";
659
695
  for (;;) {
@@ -679,7 +715,7 @@ export class OrgoProvider {
679
715
  return read;
680
716
  const desktops = read.value?.desktops;
681
717
  if (!Array.isArray(desktops))
682
- return fail("orgo", `Orgo's workspace ${this.#workspaceId} lists no computers array`);
718
+ return vendorFail("orgo", `Orgo's workspace ${this.#workspaceId} lists no computers array`);
683
719
  return ok(desktops.filter((one) => typeof one?.id === "string" && typeof one.name === "string").map((one) => ({ ...one, workspace_id: this.#workspaceId })));
684
720
  }
685
721
  /** The live view: screen.watch on a connection of the watch's own (daemonWatch), never Orgo's VNC (proxy only). */
@@ -705,7 +741,7 @@ export class OrgoProvider {
705
741
  await opened.value.close();
706
742
  return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drift.join("; ")}`);
707
743
  }
708
- async attach(ref, { signal } = {}) {
744
+ async attach(ref, { signal, claim } = {}) {
709
745
  const given = (typeof ref === "object" && ref !== null ? ref : {});
710
746
  if ((given.id === undefined) === (given.labels === undefined))
711
747
  return fail("invalid", "attach takes { id } or { labels }, one of them");
@@ -717,7 +753,7 @@ export class OrgoProvider {
717
753
  return read.error.code === "not_found" ? fail("not_found", `no Orgo computer has the id ${given.id}`) : read;
718
754
  if (!this.#ours(read.value))
719
755
  return fail("not_found", `no Orgo computer of this provider has the id ${given.id}`);
720
- return this.#attached(read.value, signal);
756
+ return this.#attached(read.value, signal, claim);
721
757
  }
722
758
  const problem = filterProblem(given.labels);
723
759
  if (problem)
@@ -736,58 +772,126 @@ export class OrgoProvider {
736
772
  const found = await this.#own(listed.value[0].ref, signal);
737
773
  if (!found.ok)
738
774
  return found;
739
- return this.#attached(found.value, signal);
775
+ return this.#attached(found.value, signal, claim);
740
776
  }
741
777
  /**
742
778
  * The drift check of a computer attach did not make: its labels file, the truth, held to its name, then its daemon
743
779
  * and the probe, as at create. One that drifts is refused and left as it is. A computer that does not run is
744
- * refused: reading it from inside would wake it.
780
+ * refused: reading it from inside would wake it. An agent's own computer is the exception: attaching it is asking
781
+ * for it. Its ledger entry is taken for the claim first, busy (takeEntry), before anything is done to the computer;
782
+ * one a detach suspended is then resumed (#wake), its memory and init with it; its daemon is moved on or installed
783
+ * again (#ownedInside); and it is marked held in the ledger last (settleEntry), by this attach alone, while the entry
784
+ * is still the one it holds. An attach that resumed it and then fails suspends it again, as it was found (#putBack).
785
+ * This process's attaches and detaches of one agent's computer are taken in turn; another process's are refused while
786
+ * this one holds the entry, so no attach or detach ends the programs or sleep of another's.
787
+ */
788
+ async #attached(record, signal, claim) {
789
+ const ref = { id: record.id, name: record.name };
790
+ const parts = nameParts(record.name);
791
+ if (parts.owner === undefined) {
792
+ if (claim !== undefined)
793
+ return fail("refused", claimProblem(ref.name, undefined, undefined, claim));
794
+ if (record.status !== "running")
795
+ return fail("refused", `${ref.name} is ${record.status}: its labels file and daemon are read from inside, and a read would wake it`);
796
+ return this.#checked(record, parts, signal);
797
+ }
798
+ const owner = parts.owner;
799
+ return inTurn(this.#owning, ref.id, async (waited) => {
800
+ // Read again after waiting: the attach or detach before this one may have resumed or suspended it.
801
+ const now = waited ? await this.#own(ref, signal) : ok(record);
802
+ if (!now.ok)
803
+ return now;
804
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being attached");
805
+ if (!taken.ok)
806
+ return taken;
807
+ const lease = taken.value;
808
+ const woke = now.value.status !== "running";
809
+ const attached = await this.#resumed(now.value, parts, lease, woke, signal, claim);
810
+ if (!attached.ok && woke)
811
+ return this.#putBack(ref, lease, attached.error);
812
+ // Marked held (no longer detached) once attached; a failed attach that woke nothing leaves it as it was.
813
+ return andSettled(attached, await settleEntry(this.#ledger, ref, lease, attached.ok ? ({ detachedAt: _held, ...held }) => held : undefined));
814
+ });
815
+ }
816
+ /**
817
+ * An agent's own computer, its entry taken: resumed when it was not running; under a claim, its labels file carries
818
+ * the claim's run and epoch from now on, as the ledger does; then checked.
819
+ */
820
+ async #resumed(record, parts, lease, woke, signal, claim) {
821
+ const ref = { id: record.id, name: record.name };
822
+ if (woke) {
823
+ const woken = await this.#wake(ref, record.status, signal);
824
+ if (!woken.ok)
825
+ return woken;
826
+ }
827
+ if (claim !== undefined) {
828
+ // Its labels file is written under the claim only while this attach still holds the entry, however long the wake took.
829
+ if (woke) {
830
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being attached");
831
+ if (!renewed.ok)
832
+ return renewed;
833
+ }
834
+ const read = await this.#readLabels(ref, signal);
835
+ if (!read.ok)
836
+ return read;
837
+ const written = await this.#writeLabels(ref, { ...read.value, labels: lease.entry.labels }, signal);
838
+ if (!written.ok)
839
+ return written;
840
+ }
841
+ return this.#checked(record, parts, signal, lease);
842
+ }
843
+ /**
844
+ * An agent's own computer this attach resumed, suspended again once the attach fails, best effort, as release detach
845
+ * suspends it, so it is left as it was found; its ledger entry still says when it was detached (takeEntry kept it).
846
+ * One another claim has taken since is that claim's, and runs on. Never signalled: it outlives an abort.
745
847
  */
746
- async #attached(record, signal) {
848
+ async #putBack(ref, lease, error) {
849
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being put back to sleep by an attach that failed");
850
+ if (!renewed.ok)
851
+ return fail(error.code, `${error.message}; ${ref.name} runs on, not suspended again: ${renewed.error.message}`);
852
+ const suspended = await this.#suspend(ref);
853
+ const failed = fail(error.code, `${error.message}; ${ref.name}, which this attach resumed, ${suspended.ok ? "was suspended again, as it was found" : `could not be suspended again (${suspended.error.message})`}`);
854
+ return andSettled(failed, await settleEntry(this.#ledger, ref, lease));
855
+ }
856
+ /** The labels file, the truth, held to the name, then the daemon and the probe: the drift check of #attached. `lease`:
857
+ * an agent's computer's ledger entry as this attach holds it, for its daemon's replacement. */
858
+ async #checked(record, parts, signal, lease) {
747
859
  const ref = { id: record.id, name: record.name };
748
- if (record.status !== "running")
749
- return fail("refused", `${ref.name} is ${record.status}: its labels file and daemon are read from inside, and a read would wake it`);
750
860
  const file = await this.#readLabels(ref, signal);
751
861
  if (!file.ok)
752
862
  return file;
753
863
  const found = [];
754
- const parts = nameParts(record.name);
755
864
  const { labels } = file.value;
756
865
  if (typeof file.value.name !== "string" || !sameComputer(file.value.name, record.name))
757
866
  found.push(`name: Orgo's is ${record.name}, the labels file's ${show(file.value.name)}`);
867
+ if ((parts.owner ?? "") !== ownerHashOfLabels(labels))
868
+ found.push(`owner: the name's owner hash ${show(parts.owner)} is not the labels file's owner ${show(labels[OWNER_LABEL])}`);
758
869
  const run = labels[RUN_LABEL];
759
- if ((parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
870
+ // An agent's own computer is no run's: its name carries no run or epoch, whatever run made it.
871
+ if (parts.owner === undefined && (parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
760
872
  found.push(`run: the name's run hash ${show(parts.run)} is not the labels file's run ${show(run)}`);
761
- if ((parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
873
+ if (parts.owner === undefined && (parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
762
874
  found.push(`epoch: the name says ${show(parts.epoch)}, the labels file ${show(labels[EPOCH_LABEL])}`);
763
- const deadline = new Date(file.value.deadline);
764
- if (Number.isNaN(deadline.getTime()))
875
+ const deadline = parts.owner === undefined ? new Date(file.value.deadline) : undefined;
876
+ if (deadline !== undefined && Number.isNaN(deadline.getTime()))
765
877
  found.push(`deadline: the labels file reads ${show(file.value.deadline)}, not a time`);
878
+ if (parts.owner !== undefined && file.value.deadline !== NO_DEADLINE)
879
+ found.push(`deadline: an agent's own computer has none, and the labels file reads ${show(file.value.deadline)}`);
766
880
  let notes = [];
767
- let kind;
768
881
  if (found.length === 0) {
769
- const ports = await this.#rootPorts(ref, signal);
770
- if (!ports.ok)
771
- return ports;
772
- const opened = await this.#open(ref, signal);
773
- if (!opened.ok)
774
- return opened;
775
- try {
776
- const inside = await this.#checkInside(opened.value, ref.name, ports.value, signal);
777
- if (!inside.ok && inside.error.code !== "refused")
778
- return inside;
779
- if (!inside.ok)
780
- found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
781
- else
782
- notes = inside.value;
783
- }
784
- finally {
785
- await opened.value.close();
786
- }
787
- kind = opened.value.hello.kind;
882
+ // lease is given for an agent's own computer alone (#resumed).
883
+ const inside = lease === undefined ? await this.#inside(ref, signal) : await this.#ownedInside(ref, file.value, lease, signal);
884
+ if (!inside.ok && inside.error.code !== "refused")
885
+ return inside;
886
+ if (!inside.ok)
887
+ found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
888
+ else
889
+ notes = inside.value;
788
890
  }
789
891
  if (found.length > 0)
790
892
  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("; ")}`);
893
+ // The daemon's hello passed the drift check, which holds its kind to this provider's.
894
+ const { kind } = this.capabilities();
791
895
  return ok({
792
896
  ...ref,
793
897
  spec: {
@@ -797,12 +901,110 @@ export class OrgoProvider {
797
901
  ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }),
798
902
  ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }),
799
903
  workdir: WORK,
800
- deadline,
801
- ...(kind === undefined ? {} : { kind }),
904
+ ...(deadline === undefined ? {} : { deadline }),
905
+ kind,
906
+ ...ownerReadBack(labels),
802
907
  },
803
908
  ...(notes.length > 0 ? { notes } : {}),
804
909
  });
805
910
  }
911
+ /** A run's computer's daemon and the probe, as at create: the probe's notes. */
912
+ async #inside(ref, signal) {
913
+ const ports = await this.#rootPorts(ref, signal);
914
+ if (!ports.ok)
915
+ return ports;
916
+ const opened = await this.#open(ref, signal);
917
+ if (!opened.ok)
918
+ return opened;
919
+ try {
920
+ return await this.#checkInside(opened.value, ref.name, ports.value, signal);
921
+ }
922
+ finally {
923
+ await opened.value.close();
924
+ }
925
+ }
926
+ /**
927
+ * An agent's own computer's daemon: init's deadline moved maxLifetimeMs out (deadline.extend), then checked as at
928
+ * create. One that does not answer (init ended at its deadline: the desktop was detached past maxLifetimeMs), answers
929
+ * as another version (the package was upgraded while it was detached), or whose deadline no longer moves (init is
930
+ * ending) is installed and started again over the same disk (#replaceDaemon). A run's computer is never replaced
931
+ * (#inside): its daemon is its run's, and one that drifts refuses the attach.
932
+ */
933
+ async #ownedInside(ref, file, lease, signal) {
934
+ const ports = await this.#rootPorts(ref, signal);
935
+ if (!ports.ok)
936
+ return ports;
937
+ const opened = await this.#open(ref, signal);
938
+ if (!opened.ok)
939
+ return opened.notListening ? this.#replaceDaemon(ref, file, lease, "its daemon did not answer (init had ended)", signal) : opened;
940
+ let stale;
941
+ try {
942
+ const { client, hello } = opened.value;
943
+ if (hello.version !== VERSION)
944
+ stale = `its daemon was version ${hello.version}, not this provider's ${VERSION}`;
945
+ else {
946
+ const at = new Date(Date.now() + this.#maxLifetimeMs).toISOString();
947
+ const extended = await client.call("deadline.extend", { at }, { signal: this.#bounded(this.#timeouts.helloMs, signal) });
948
+ // invalid: init's deadline is already later than at (maxLifetimeMs was lowered since), and it is kept.
949
+ if (!extended.ok && extended.error.code === "unsupported")
950
+ stale = `its init's deadline no longer moved (${extended.error.message})`;
951
+ else if (!extended.ok && extended.error.code !== "invalid")
952
+ return fail(extended.error.code, `init's deadline in ${ref.name} did not move to ${at}: ${extended.error.message}`);
953
+ else
954
+ return await this.#checkInside(opened.value, ref.name, ports.value, signal);
955
+ }
956
+ }
957
+ finally {
958
+ await opened.value.close();
959
+ }
960
+ return this.#replaceDaemon(ref, file, lease, stale, signal);
961
+ }
962
+ /**
963
+ * An agent's own computer's daemon installed and started again, its disk kept: the old init stopped by its exact
964
+ * processes, which ends its programs (STOP_INIT_SCRIPT), then every step create takes (#prepare: the upload, the
965
+ * install with its sha256 read back, the X socket, the labels file, root's ports, the lockdown, init, its first
966
+ * connection and the drift check). The attach's busy marker is renewed first (renewEntry), only while the ledger entry
967
+ * is still the one this attach holds (`lease`): an attach that lost it (its marker went stale and another took the
968
+ * computer) stops nothing, so an older attach never stops the init a newer one started. The probe's notes, after one
969
+ * that says the daemon was replaced and why.
970
+ */
971
+ async #replaceDaemon(ref, file, lease, why, signal) {
972
+ let daemon;
973
+ try {
974
+ daemon = readFileSync(this.#daemonPath);
975
+ }
976
+ catch {
977
+ return fail("not_found", `${ref.name}'s daemon needs replacing, since ${why}, and there is no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
978
+ }
979
+ const renewed = await renewEntry(this.#ledger, ref, lease, "its daemon being replaced by an attach");
980
+ if (!renewed.ok)
981
+ return fail(renewed.error.code, `${ref.name}'s daemon needs replacing, since ${why}, and is left as it is: ${renewed.error.message}`);
982
+ const stopped = await this.#channel.run(ref.id, ["sh", "-c", STOP_INIT_SCRIPT, "sh", DAEMON_IN_COMPUTER], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
983
+ if (!stopped.ok)
984
+ return stopped;
985
+ if (stopped.value.exitCode !== 0)
986
+ return fail("refused", `${ref.name}'s daemon needs replacing, since ${why}, and its old init could not be stopped (exit ${stopped.value.exitCode}): ${stopped.value.output.trim().slice(0, 200)}`);
987
+ const prepared = await this.#prepare(ref, "running", file, daemon, signal, this.#ownedInit(Date.now()));
988
+ if (!prepared.ok)
989
+ return fail(prepared.error.code, `replacing ${ref.name}'s daemon, since ${why}, failed: ${prepared.error.message}`);
990
+ return ok([`the daemon in ${ref.name} was replaced with this provider's ${VERSION}, its disk kept, since ${why}`, ...prepared.value]);
991
+ }
992
+ /**
993
+ * An agent's own computer that a detach suspended, resumed for its attach: Orgo's resume (its memory back, computerd
994
+ * init still running), then running. One stopped outside this provider comes back from its disk alone, with no init:
995
+ * Orgo's start, and the daemon is then installed again (#ownedInside).
996
+ */
997
+ async #wake(ref, status, signal) {
998
+ const how = status === "suspended" || status === "suspending" ? "resume" : status === "frozen" || status === "stopped" ? "start" : undefined;
999
+ if (how === undefined && !RUNNING.has(status))
1000
+ return fail("refused", `${ref.name} is ${status}: no resume or start brings it back`);
1001
+ if (how !== undefined) {
1002
+ const woken = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/${how}`, { body: {}, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
1003
+ if (!woken.ok)
1004
+ return fail(woken.error.code, `${ref.name} could not ${how} for its attach: ${woken.error.message}`);
1005
+ }
1006
+ return this.#untilRunning(ref, signal);
1007
+ }
806
1008
  /**
807
1009
  * Every computer of this provider in the workspace that carries all of these labels. The run and the epoch are read
808
1010
  * from the name, with nothing run in a computer, so a stopped one is listed too; any other label is read from the
@@ -816,25 +1018,42 @@ export class OrgoProvider {
816
1018
  if (!listed.ok)
817
1019
  return listed;
818
1020
  const others = Object.keys(labels).filter((key) => key !== RUN_LABEL && key !== EPOCH_LABEL);
1021
+ // An agent's computers' labels are the ledger's: read once, only when the workspace holds one.
1022
+ const owned = listed.value.some((record) => nameParts(record.name)?.owner !== undefined) ? await this.#entries() : ok(new Map());
1023
+ if (!owned.ok)
1024
+ return owned;
819
1025
  const infos = [];
820
1026
  for (const record of listed.value) {
821
1027
  const parts = nameParts(record.name);
822
- if (parts === undefined || record.status === "deleted")
1028
+ // Orgo's workspace listing names each desktop's os: a Windows or macOS one is the desktop provider's
1029
+ // (orgo-desktop.ts), never this one's to list or its janitor's to sweep.
1030
+ if (parts === undefined || record.status === "deleted" || (record.os !== undefined && record.os !== "linux"))
1031
+ continue;
1032
+ const ref = { id: record.id, name: record.name };
1033
+ const running = RUNNING.has(record.status);
1034
+ // An agent's computer: every label from its ledger entry, with nothing run inside, whatever its state; no deadline.
1035
+ if (parts.owner !== undefined) {
1036
+ const view = ownedListing(owned.value.get(record.id), labels);
1037
+ if (view === undefined)
1038
+ continue;
1039
+ infos.push({ ref, deadline: undefined, state: running ? "running" : "stopped", network: "none", ...view });
1040
+ continue;
1041
+ }
1042
+ if (labels[OWNER_LABEL] !== undefined || labels[OWNER_SERVER_LABEL] !== undefined)
823
1043
  continue;
824
1044
  if (labels[RUN_LABEL] !== undefined && parts.run !== runHash(labels[RUN_LABEL]))
825
1045
  continue;
826
1046
  if (labels[EPOCH_LABEL] !== undefined && parts.epoch !== labels[EPOCH_LABEL])
827
1047
  continue;
828
- const ref = { id: record.id, name: record.name };
829
- const running = RUNNING.has(record.status);
830
1048
  // The name keeps the run's hash, not the run: listed with no run to match, the hash is given, so a caller (serve's
831
1049
  // janitor) can still tell whose run a computer is.
832
1050
  let read = {
833
1051
  ...(labels[RUN_LABEL] !== undefined ? { [RUN_LABEL]: labels[RUN_LABEL] } : parts.run !== undefined ? { [RUN_HASH_LABEL]: parts.run } : {}),
834
1052
  ...(parts.epoch !== undefined ? { [EPOCH_LABEL]: parts.epoch } : {}),
835
1053
  };
836
- // The janitor's deadline is the name's; a name of an older make has none, and Orgo's end stands for it.
837
- let deadline = parts.deadline ?? (typeof record.ends_at === "string" ? new Date(record.ends_at) : undefined);
1054
+ // The janitor's deadline is the name's, which every name this provider makes carries. One with none is listed
1055
+ // with none, and the janitor ends it (a run's computer with no deadline it can read).
1056
+ const deadline = parts.deadline;
838
1057
  if (others.length > 0) {
839
1058
  if (record.status !== "running")
840
1059
  continue;
@@ -844,7 +1063,6 @@ export class OrgoProvider {
844
1063
  if (!others.every((key) => file.value.labels[key] === labels[key]))
845
1064
  continue;
846
1065
  read = { ...file.value.labels };
847
- deadline = parts.deadline ?? new Date(file.value.deadline);
848
1066
  }
849
1067
  infos.push({ ref, labels: read, deadline, state: running ? "running" : "stopped", network: "none" });
850
1068
  }
@@ -884,23 +1102,61 @@ export class OrgoProvider {
884
1102
  await opened.value.close();
885
1103
  }
886
1104
  }
887
- /** delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. No stop. */
888
- async release(ref, how, { signal } = {}) {
1105
+ /**
1106
+ * delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. detach, for an
1107
+ * agent's own computer alone: Orgo's suspend, its memory and disk saved, read back suspended. No stop: a run's
1108
+ * computer is deleted.
1109
+ */
1110
+ async release(ref, how, { signal, claim } = {}) {
889
1111
  const problem = refProblem(ref);
890
1112
  if (problem)
891
1113
  return fail("invalid", problem);
892
- if (how !== "stop" && how !== "delete")
893
- return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1114
+ if (how !== "stop" && how !== "delete" && how !== "detach")
1115
+ return fail("invalid", `release is "stop", "delete" or "detach", not ${String(how)}`);
894
1116
  if (how === "stop")
895
- return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete");
1117
+ return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete, or detach an agent's own");
896
1118
  const read = await this.#get(ref.id);
897
1119
  if (!read.ok)
898
- return read.error.code === "not_found" ? ok(undefined) : read;
1120
+ return read.error.code === "not_found" && how === "delete" ? ok(undefined) : read;
899
1121
  if (read.value.status === "deleted")
900
- return ok(undefined);
1122
+ return how === "delete" ? ok(undefined) : fail("not_found", `${ref.name} is deleted: there is nothing to detach`);
901
1123
  if (!this.#ours(read.value, ref.name))
902
1124
  return fail("not_found", `no Orgo computer of this provider is ${ref.name} (${ref.id}), so it is left as it is`);
903
- return this.#delete(ref, signal);
1125
+ if (how === "delete")
1126
+ return claim === undefined ? this.#delete(ref, signal) : this.#claimedDelete(ref, read.value.name, claim, signal);
1127
+ const owner = nameParts(read.value.name)?.owner;
1128
+ if (owner === undefined)
1129
+ return fail("refused", `${ref.name} is a run's computer, not an agent's own: it is deleted at its release, never detached`);
1130
+ // In turn with this process's attaches, and holding the ledger entry from before the suspend until it is marked
1131
+ // detached (takeEntry, settleEntry), so no attach resumes it meanwhile and an attach under way refuses this detach.
1132
+ return inTurn(this.#owning, ref.id, async (waited) => {
1133
+ const taken = await takeEntry(this.#ledger, ref, owner, undefined, "being detached");
1134
+ if (!taken.ok)
1135
+ return taken;
1136
+ const now = waited ? await this.#own(ref, signal) : ok(read.value);
1137
+ const suspended = !now.ok ? now : now.value.status === "suspended" ? ok(undefined) : await this.#suspend(ref, signal);
1138
+ return andSettled(suspended, await settleEntry(this.#ledger, ref, taken.value, suspended.ok ? (entry) => ({ ...entry, detachedAt: entry.detachedAt ?? new Date().toISOString() }) : undefined));
1139
+ });
1140
+ }
1141
+ /** Orgo's suspend, the computer's memory and disk saved, then the wait until Orgo reads it suspended. */
1142
+ async #suspend(ref, signal) {
1143
+ const suspended = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/suspend`, { timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
1144
+ if (!suspended.ok)
1145
+ return fail(suspended.error.code, `${ref.name} could not be suspended for its agent: ${suspended.error.message}`);
1146
+ // 202 suspending: its memory is still being saved. Read until Orgo says suspended.
1147
+ const until = Date.now() + this.#timeouts.goneMs;
1148
+ for (;;) {
1149
+ const now = await this.#get(ref.id, signal);
1150
+ if (!now.ok)
1151
+ return now;
1152
+ if (now.value.status === "suspended")
1153
+ return ok(undefined);
1154
+ if (Date.now() >= until)
1155
+ return fail("timeout", `${ref.name} was not suspended ${seconds(this.#timeouts.goneMs)} after its suspend; Orgo last read ${now.value.status}`);
1156
+ await pause(this.#timeouts.pollMs, signal);
1157
+ if (signal?.aborted)
1158
+ return fail("aborted", `the wait for ${ref.name} to be suspended was aborted`);
1159
+ }
904
1160
  }
905
1161
  /**
906
1162
  * Moves the deadline to now + ttlMs, never earlier and never past the most the labels file holds (create's time plus
@@ -910,16 +1166,7 @@ export class OrgoProvider {
910
1166
  * is refused as earlier, never renaming the computer back to an earlier deadline the janitor would trust.
911
1167
  */
912
1168
  extend(ref, ttlMs, context = {}) {
913
- const key = typeof ref?.id === "string" ? ref.id : "";
914
- const before = this.#extending.get(key) ?? Promise.resolve();
915
- const turn = before.then(() => this.#extend(ref, ttlMs, context));
916
- const settled = turn.then(() => undefined, () => undefined);
917
- this.#extending.set(key, settled);
918
- void settled.then(() => {
919
- if (this.#extending.get(key) === settled)
920
- this.#extending.delete(key);
921
- });
922
- return turn;
1169
+ return inTurn(this.#extending, typeof ref?.id === "string" ? ref.id : "", () => this.#extend(ref, ttlMs, context));
923
1170
  }
924
1171
  async #extend(ref, ttlMs, { signal } = {}) {
925
1172
  const problem = refProblem(ref);
@@ -930,6 +1177,8 @@ export class OrgoProvider {
930
1177
  const found = await this.#own(ref, signal);
931
1178
  if (!found.ok)
932
1179
  return found;
1180
+ if (nameParts(found.value.name)?.owner !== undefined)
1181
+ return fail("refused", `${ref.name} is an agent's own computer: it has no deadline to move`);
933
1182
  if (found.value.status !== "running")
934
1183
  return fail("refused", `${ref.name} is ${found.value.status}, not running`);
935
1184
  const file = await this.#readLabels(ref, signal);
@@ -984,10 +1233,12 @@ export class OrgoProvider {
984
1233
  return ok({ deadline: took });
985
1234
  }
986
1235
  }
987
- /**
988
- * An OrgoProvider from its options alone, its key included: it reads no environment. Serve passes apiKey from its
989
- * ORGO_API_KEY setting and its workspace; the conformance module reads COMPUTER_ORGO_* (settingsFromEnv).
990
- */
991
1236
  export function create(options) {
992
- return new OrgoProvider(options);
1237
+ const os = options?.os;
1238
+ if (os === "windows" || os === "macos")
1239
+ return new OrgoDesktopProvider(options);
1240
+ if (os !== undefined && os !== "linux")
1241
+ throw new Error(`os is "linux" (the default), "windows" or "macos", not ${JSON.stringify(os)}`);
1242
+ const { os: _os, ...linux } = options;
1243
+ return new OrgoProvider(linux);
993
1244
  }