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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +423 -323
  3. package/box/Dockerfile +3 -1
  4. package/box/agentrun-archil +59 -7
  5. package/box/build-agent37.mjs +177 -0
  6. package/box/build-daytona.py +20 -4
  7. package/dist/agent37.d.ts +165 -0
  8. package/dist/agent37.js +759 -0
  9. package/dist/attach.d.ts +146 -0
  10. package/dist/attach.js +469 -0
  11. package/dist/browser.d.ts +61 -10
  12. package/dist/browser.js +125 -3
  13. package/dist/browserbase.d.ts +46 -23
  14. package/dist/browserbase.js +162 -17
  15. package/dist/chrome.d.ts +3 -4
  16. package/dist/chrome.js +6 -11
  17. package/dist/client.d.ts +33 -1
  18. package/dist/client.js +53 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/agent37.d.ts +96 -0
  22. package/dist/conformance/agent37.js +154 -0
  23. package/dist/conformance/cases/apps.d.ts +5 -0
  24. package/dist/conformance/cases/apps.js +160 -73
  25. package/dist/conformance/cases/health.js +14 -0
  26. package/dist/conformance/cases/index.js +2 -0
  27. package/dist/conformance/cases/provider.js +27 -1
  28. package/dist/conformance/cases/screen.d.ts +3 -0
  29. package/dist/conformance/cases/screen.js +18 -0
  30. package/dist/conformance/cases/settings.d.ts +29 -23
  31. package/dist/conformance/cases/settings.js +76 -58
  32. package/dist/conformance/cases/touch.js +19 -17
  33. package/dist/conformance/cases/ui.d.ts +2 -0
  34. package/dist/conformance/cases/ui.js +475 -0
  35. package/dist/conformance/cli.d.ts +9 -0
  36. package/dist/conformance/cli.js +28 -3
  37. package/dist/conformance/daytona.d.ts +4 -0
  38. package/dist/conformance/daytona.js +5 -0
  39. package/dist/conformance/e2b.d.ts +6 -0
  40. package/dist/conformance/e2b.js +9 -2
  41. package/dist/conformance/fixture.d.ts +1 -1
  42. package/dist/conformance/fixture.js +25 -1
  43. package/dist/conformance/modal.d.ts +17 -13
  44. package/dist/conformance/modal.js +18 -9
  45. package/dist/conformance/orgo.d.ts +3 -3
  46. package/dist/conformance/orgo.js +6 -8
  47. package/dist/conformance/phone-harness.d.ts +6 -2
  48. package/dist/conformance/phone-harness.js +21 -4
  49. package/dist/conformance/report.js +1 -1
  50. package/dist/conformance/runner.js +23 -4
  51. package/dist/conformance/sweep.d.ts +50 -0
  52. package/dist/conformance/sweep.js +187 -0
  53. package/dist/conformance/types.d.ts +11 -3
  54. package/dist/conformance/ui-fixture.d.ts +56 -0
  55. package/dist/conformance/ui-fixture.js +43 -0
  56. package/dist/create-requests.d.ts +51 -0
  57. package/dist/create-requests.js +121 -0
  58. package/dist/daytona.d.ts +15 -5
  59. package/dist/daytona.js +58 -38
  60. package/dist/descriptor.d.ts +29 -2
  61. package/dist/descriptor.js +13 -0
  62. package/dist/descriptors/agent37.d.ts +41 -0
  63. package/dist/descriptors/agent37.js +28 -0
  64. package/dist/descriptors/browserbase.d.ts +1 -0
  65. package/dist/descriptors/browserbase.js +2 -0
  66. package/dist/descriptors/daytona.d.ts +23 -2
  67. package/dist/descriptors/daytona.js +34 -2
  68. package/dist/descriptors/index.d.ts +66 -3
  69. package/dist/descriptors/index.js +5 -3
  70. package/dist/descriptors/kernel.d.ts +1 -0
  71. package/dist/descriptors/kernel.js +2 -0
  72. package/dist/descriptors/modal.d.ts +4 -0
  73. package/dist/descriptors/modal.js +11 -1
  74. package/dist/descriptors/orgo.d.ts +13 -1
  75. package/dist/descriptors/orgo.js +9 -3
  76. package/dist/descriptors/phone-harness.d.ts +6 -1
  77. package/dist/descriptors/phone-harness.js +5 -2
  78. package/dist/docker/egress.d.ts +4 -3
  79. package/dist/docker/egress.js +7 -6
  80. package/dist/docker.d.ts +7 -4
  81. package/dist/docker.js +278 -34
  82. package/dist/e2b.d.ts +9 -165
  83. package/dist/e2b.js +282 -1342
  84. package/dist/fake-ui-driver.d.ts +97 -0
  85. package/dist/fake-ui-driver.js +717 -0
  86. package/dist/host.d.ts +182 -0
  87. package/dist/host.js +1 -0
  88. package/dist/hosted/process.d.ts +67 -0
  89. package/dist/hosted/process.js +228 -0
  90. package/dist/hosted/provider.d.ts +146 -0
  91. package/dist/hosted/provider.js +1364 -0
  92. package/dist/hosted/scripts.d.ts +76 -0
  93. package/dist/{child.js → hosted/scripts.js} +93 -12
  94. package/dist/index.d.ts +11 -7
  95. package/dist/index.js +10 -7
  96. package/dist/janitor.d.ts +5 -4
  97. package/dist/janitor.js +1 -1
  98. package/dist/kernel.d.ts +17 -27
  99. package/dist/kernel.js +94 -18
  100. package/dist/kinds.d.ts +17 -5
  101. package/dist/kinds.js +20 -4
  102. package/dist/labels.d.ts +10 -2
  103. package/dist/labels.js +30 -7
  104. package/dist/local-chrome.d.ts +5 -5
  105. package/dist/local-chrome.js +10 -5
  106. package/dist/modal.d.ts +23 -181
  107. package/dist/modal.js +273 -1232
  108. package/dist/mount-archil.d.ts +25 -3
  109. package/dist/mount-archil.js +39 -8
  110. package/dist/orgo-channel.d.ts +3 -2
  111. package/dist/orgo-channel.js +5 -2
  112. package/dist/orgo-desktop.d.ts +23 -9
  113. package/dist/orgo-desktop.js +328 -66
  114. package/dist/orgo-names.d.ts +129 -3
  115. package/dist/orgo-names.js +211 -8
  116. package/dist/orgo-workspaces.d.ts +47 -0
  117. package/dist/orgo-workspaces.js +94 -0
  118. package/dist/orgo.d.ts +27 -10
  119. package/dist/orgo.js +411 -81
  120. package/dist/phone-harness.d.ts +31 -21
  121. package/dist/phone-harness.js +510 -681
  122. package/dist/png.d.ts +4 -0
  123. package/dist/png.js +27 -0
  124. package/dist/protocol.d.ts +338 -30
  125. package/dist/protocol.js +96 -3
  126. package/dist/provider.d.ts +97 -7
  127. package/dist/provider.js +24 -3
  128. package/dist/result.d.ts +1 -1
  129. package/dist/surface/api.d.ts +248 -0
  130. package/dist/surface/api.js +1 -0
  131. package/dist/surface/core.d.ts +42 -0
  132. package/dist/surface/core.js +393 -0
  133. package/dist/surface/index.d.ts +5 -0
  134. package/dist/surface/index.js +3 -0
  135. package/dist/surface/outline.d.ts +8 -0
  136. package/dist/surface/outline.js +50 -0
  137. package/dist/surface/script.d.ts +10 -0
  138. package/dist/surface/script.js +92 -0
  139. package/dist/ui-engine.d.ts +114 -0
  140. package/dist/ui-engine.js +798 -0
  141. package/package.json +17 -1
  142. package/dist/child.d.ts +0 -42
  143. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  144. package/dist/conformance/e2b-diagnose.js +0 -61
  145. package/dist/conformance/e2b-sweep.d.ts +0 -18
  146. package/dist/conformance/e2b-sweep.js +0 -132
  147. package/dist/conformance/modal-sweep.d.ts +0 -22
  148. package/dist/conformance/modal-sweep.js +0 -213
package/dist/orgo.js CHANGED
@@ -14,16 +14,17 @@
14
14
  import { createHash, randomBytes, randomUUID } from "node:crypto";
15
15
  import { readFileSync } from "node:fs";
16
16
  import { fileURLToPath } from "node:url";
17
- import { childCommands, daemonDrift } from "./child.js";
17
+ import { childCommands, daemonDrift } from "./hosted/scripts.js";
18
18
  import { DaemonClient } from "./client.js";
19
19
  import { ORGO, ORGO_BASE_IMAGE } from "./descriptors/orgo.js";
20
20
  import { DESKTOP_GROUPS } from "./desktop.js";
21
21
  import { DAEMON_IN_COMPUTER, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, SOCKET_DIR, WORK } from "./drift.js";
22
- import { EPOCH_LABEL, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
22
+ import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
23
23
  import { checkMount } from "./mount.js";
24
24
  import { ORGO_API_URL, orgoRest, orgoTerminalChannel, START_LOG } from "./orgo-channel.js";
25
25
  import { OrgoDesktopProvider } from "./orgo-desktop.js";
26
- import { COMPUTER_ID, filterProblem, labelProblem, labelsOf, NAME_MAX, nameParts, orgoName, refProblem, sameComputer, show, withDeadline, } from "./orgo-names.js";
26
+ import { workspaceChoices, workspaceHolder } from "./orgo-workspaces.js";
27
+ 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
28
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
28
29
  import { failFor, ok, vendorFail } from "./result.js";
29
30
  import { daemonWatch } from "./screen-watch.js";
@@ -45,6 +46,12 @@ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.u
45
46
  const HOUR = 3_600_000;
46
47
  /** Orgo's longest end: ends_in_hours is at most 720. */
47
48
  const MAX_LIFETIME_MS = 720 * HOUR;
49
+ /**
50
+ * The most init's deadline of an agent's own computer may move to: none in practice. Its deadline is maxLifetimeMs out
51
+ * from create, and each attach moves it maxLifetimeMs out again (deadline.extend), so only a desktop left detached for
52
+ * longer than that loses its daemon, which the next attach then installs again (#replaceDaemon).
53
+ */
54
+ const OWNED_MAX_DEADLINE = "9999-12-31T23:59:59.000Z";
48
55
  /** Orgo's RAM sizes, in GB, and the vCPUs each takes by default. */
49
56
  const RAM_GB = [4, 8, 16, 32];
50
57
  const CPU_FOR_RAM = { 4: 1, 8: 2, 16: 4, 32: 6 };
@@ -84,6 +91,31 @@ const STATUS_SCRIPT = [
84
91
  'if [ -S "$s" ]; then echo "socket present"; else echo "socket absent"; fi',
85
92
  "echo \"log $(tail -c 300 \"$l\" 2>/dev/null | tr '\\n' ' ')\"",
86
93
  ].join("\n");
94
+ /**
95
+ * Stops computerd init by its exact processes (pgrep anchored to init's own command line, so neither this script nor
96
+ * pgrep matches itself): SIGTERM to each PID, on which init ends its programs, then up to 10 s for each to be gone (a
97
+ * zombie counts as gone), then SIGKILL to those left. Prints `stopped <pids>`, or `no init running`; exits 1 when one
98
+ * outlives the SIGKILL.
99
+ */
100
+ const STOP_INIT_SCRIPT = [
101
+ "# agentrun-computer: orgo-stop-init",
102
+ "d=$1",
103
+ 'pids=$(pgrep -f "^$d init") || { echo "no init running"; exit 0; }',
104
+ "alive() { [ -e \"/proc/$1\" ] && [ \"$(awk '{ print $3 }' \"/proc/$1/stat\" 2>/dev/null)\" != Z ]; }",
105
+ "kill -TERM $pids 2>/dev/null",
106
+ "i=0",
107
+ "while [ $i -lt 100 ]; do",
108
+ "\tleft=",
109
+ '\tfor p in $pids; do alive "$p" && left="$left $p"; done',
110
+ '\t[ -n "$left" ] || { echo "stopped" $pids; exit 0; }',
111
+ "\tsleep 0.1",
112
+ "\ti=$((i + 1))",
113
+ "done",
114
+ "kill -KILL $left 2>/dev/null",
115
+ "sleep 1",
116
+ 'for p in $left; do alive "$p" && { echo "init $p outlived SIGKILL"; exit 1; }; done',
117
+ 'echo "stopped" $pids',
118
+ ].join("\n");
87
119
  /**
88
120
  * The TCP ports root listens on in Orgo's own network (its agent, its VNC, anything else of the image's), one decimal
89
121
  * port a line, from /proc/net/tcp and tcp6 (state 0A, LISTEN): no tool of the image's is relied on but awk.
@@ -150,7 +182,7 @@ export class OrgoProvider {
150
182
  version = VERSION;
151
183
  #rest;
152
184
  #channel;
153
- #workspaceId;
185
+ #workspace;
154
186
  #daemonPath;
155
187
  #maxLifetimeMs;
156
188
  #uid;
@@ -159,13 +191,16 @@ export class OrgoProvider {
159
191
  #display;
160
192
  #timeouts;
161
193
  #probeTargets;
194
+ #ledger;
162
195
  /** Each computer's extend in flight, by id: the next waits for it, so two never read the same old deadline. */
163
196
  #extending = new Map();
164
- 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 }) {
197
+ /** Each agent's computer's attach or detach in flight, by id: the next waits for it, so two never overlap here. */
198
+ #owning = new Map();
199
+ 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() }) {
165
200
  if (typeof apiKey !== "string" || apiKey === "")
166
201
  throw new Error("options.apiKey, an Orgo API key, is required");
167
- if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId))
168
- throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is required");
202
+ if (workspaceId !== undefined && (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId)))
203
+ throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is an Orgo workspace id when given");
169
204
  let url;
170
205
  try {
171
206
  url = new URL(apiUrl);
@@ -195,8 +230,8 @@ export class OrgoProvider {
195
230
  throw new Error("probeTargets must name at least one address for the probe, each host:port or host:port/udp");
196
231
  }
197
232
  this.#rest = orgoRest({ apiKey, apiUrl: url.href, ...(fetch ? { fetch } : {}) });
198
- this.#channel = channel ?? orgoTerminalChannel({ rest: this.#rest, workspaceId, ...(webSocket ? { webSocket } : {}) });
199
- this.#workspaceId = workspaceId;
233
+ this.#workspace = workspaceHolder(workspaceId, this.#rest, merged.requestMs);
234
+ this.#channel = channel ?? orgoTerminalChannel({ rest: this.#rest, workspace: (signal) => this.#workspace.read(signal), ...(webSocket ? { webSocket } : {}) });
200
235
  this.#daemonPath = daemonPath;
201
236
  this.#maxLifetimeMs = maxLifetimeMs;
202
237
  [this.#uid, this.#gid] = [String(Number(ids[1])), String(Number(ids[2]))];
@@ -204,13 +239,15 @@ export class OrgoProvider {
204
239
  this.#display = display;
205
240
  this.#timeouts = merged;
206
241
  this.#probeTargets = [...probeTargets];
242
+ this.#ledger = ledger;
207
243
  }
208
244
  /**
209
245
  * daemon child: Orgo's own agent is the VM's first process, and init is a command it ran. lifetime janitor: Orgo ends
210
246
  * a computer only in whole hours (ends_in_hours, the backstop), so the janitor deletes it at its exact deadline, which
211
247
  * its name carries (list() reads it with nothing run inside); init ends its programs at that deadline inside. network
212
- * none alone, read back by the probe from inside (Orgo reads no policy back). release delete alone: Orgo's stop
213
- * freezes a computer, which nothing here needs.
248
+ * none alone, read back by the probe from inside (Orgo reads no policy back). release delete, and detach for an
249
+ * agent's own computer: Orgo's suspend saves its memory and disk, so it resumes where it was (persistence resume),
250
+ * computerd init with it.
214
251
  */
215
252
  capabilities() {
216
253
  return {
@@ -228,13 +265,14 @@ export class OrgoProvider {
228
265
  mount: [...MOUNT],
229
266
  // Init starts with --own-network (childCommands): no tool reaches these, nor any port root listens on.
230
267
  vendorAgentPorts: [...ORGO_AGENT_PORTS],
268
+ persistence: { keepsState: true, resume: true },
231
269
  };
232
270
  }
233
271
  check(spec) {
234
272
  const refusals = [];
235
273
  const refuse = (field, message) => refusals.push({ field, message });
236
274
  const given = (typeof spec === "object" && spec !== null ? spec : {});
237
- const { image, lifetimeMs, network, cpus, memoryMb, labels, mount } = given;
275
+ const { image, network, cpus, memoryMb, labels, mount } = given;
238
276
  if (image !== BASE && !(typeof image === "string" && TEMPLATE.test(image)))
239
277
  refuse("image", `an image is "${BASE}" (Orgo's base desktop) or an Orgo template, namespace/name@version`);
240
278
  refusals.push(...checkTenure(given, this.capabilities(), "Orgo"));
@@ -253,7 +291,7 @@ export class OrgoProvider {
253
291
  refusals.push(...checkMount(mount, MOUNT));
254
292
  refusals.push(...checkGpu(given.gpu, this.capabilities()));
255
293
  for (const [field, value] of Object.entries(given)) {
256
- if (SPEC_FIELDS.has(field) || field === "mount" || value === undefined)
294
+ if (SPEC_FIELDS.has(field) || field === "mount" || field === "owner" || value === undefined)
257
295
  continue;
258
296
  if (field === "user")
259
297
  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`);
@@ -266,7 +304,8 @@ export class OrgoProvider {
266
304
  }
267
305
  return refusals;
268
306
  }
269
- async create(spec, { signal } = {}) {
307
+ async create(spec, context) {
308
+ const signal = context?.signal;
270
309
  const refusals = this.check(spec);
271
310
  if (refusals.length > 0)
272
311
  return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
@@ -279,24 +318,32 @@ export class OrgoProvider {
279
318
  }
280
319
  if (signal?.aborted)
281
320
  return fail("aborted", "create was aborted before Orgo was called");
282
- const labels = { ...spec.labels };
321
+ const workspace = await this.#workspace.read(signal);
322
+ if (!workspace.ok)
323
+ return workspace;
324
+ // An agent's own computer outlives the run: no janitor's deadline and no Orgo end, the owner in its name and labels.
325
+ // Init still takes one, maxLifetimeMs out, since it ends its programs at its deadline, with no most in practice:
326
+ // each attach moves it maxLifetimeMs out again (#ownedInit).
327
+ const owner = spec.owner;
328
+ const labels = { ...spec.labels, ...(owner === undefined ? {} : ownerLabels(owner)) };
283
329
  const now = Date.now();
284
- const deadline = new Date(now + runLifetimeMs(spec)).toISOString();
285
330
  const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
331
+ const deadline = owner === undefined ? new Date(now + runLifetimeMs(spec)).toISOString() : maxDeadline;
332
+ const init = owner === undefined ? { deadline, maxDeadline } : this.#ownedInit(now);
286
333
  // The janitor's deadline is in the name, so list() and the sweep read it with nothing run inside.
287
- const name = orgoName(labels, randomBytes(6).toString("hex"), new Date(deadline));
334
+ const name = orgoName(labels, randomBytes(6).toString("hex"), owner === undefined ? new Date(deadline) : undefined, owner);
288
335
  if (name.length > NAME_MAX || nameParts(name) === undefined)
289
336
  return fail("invalid", `the name ${name} is not one Orgo holds: at most ${NAME_MAX} of letters, digits and dashes`);
290
337
  const ram = spec.memoryMb === undefined ? 4 : spec.memoryMb / 1024;
291
338
  const cpu = spec.cpus ?? CPU_FOR_RAM[ram];
292
339
  const body = {
293
- workspace_id: this.#workspaceId,
340
+ workspace_id: workspace.value,
294
341
  name,
295
342
  os: "linux",
296
343
  ram,
297
344
  cpu,
298
345
  // Orgo's end, the vendor's backstop: whole hours, deleting the computer and its disk. init ends it on time.
299
- ends_in_hours: Math.max(1, Math.ceil(runLifetimeMs(spec) / HOUR)),
346
+ ...(owner === undefined ? { ends_in_hours: Math.max(1, Math.ceil(runLifetimeMs(spec) / HOUR)) } : {}),
300
347
  ...(spec.image === BASE ? {} : { template_ref: spec.image }),
301
348
  };
302
349
  const made = await this.#rest.request("POST", "/computers", { body, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
@@ -310,8 +357,14 @@ export class OrgoProvider {
310
357
  if (typeof id !== "string" || !COMPUTER_ID.test(id))
311
358
  return vendorFail("orgo", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
312
359
  const ref = { id, name };
313
- const file = { name, labels, deadline, maxDeadline, image: spec.image, cpus: cpu, memoryMb: ram * 1024 };
314
- const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal);
360
+ // An agent's computer's labels go in the ledger at once, so list finds it as the agent's whatever happens next.
361
+ if (owner !== undefined) {
362
+ const kept = await this.#keep({ id, labels });
363
+ if (!kept.ok)
364
+ return this.#abandon(ref, kept.error);
365
+ }
366
+ const file = { name, labels, deadline: owner === undefined ? deadline : NO_DEADLINE, maxDeadline: owner === undefined ? maxDeadline : NO_DEADLINE, image: spec.image, cpus: cpu, memoryMb: ram * 1024 };
367
+ const prepared = await this.#prepare(ref, made.value.status, file, daemon, signal, init);
315
368
  if (signal?.aborted)
316
369
  return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
317
370
  if (prepared.ok)
@@ -323,7 +376,7 @@ export class OrgoProvider {
323
376
  * installed (its sha256 read back), Orgo's X server's path socket there, the labels file, init started, its first
324
377
  * connection, then the daemon's report and the probe. Its value is the probe's notes.
325
378
  */
326
- async #prepare(ref, status, file, daemon, signal) {
379
+ async #prepare(ref, status, file, daemon, signal, init = file) {
327
380
  const { uploadMs, execMs } = this.#timeouts;
328
381
  const running = status === "running" ? ok(undefined) : await this.#untilRunning(ref, signal);
329
382
  if (!running.ok)
@@ -332,7 +385,7 @@ export class OrgoProvider {
332
385
  const uploaded = await this.#channel.upload(ref.id, staging, daemon, { timeoutMs: uploadMs, ...(signal ? { signal } : {}) });
333
386
  if (!uploaded.ok)
334
387
  return fail(uploaded.error.code, `the daemon's upload into ${ref.name} failed: ${uploaded.error.message}`);
335
- const commands = childCommands({ staging, deadline: file.deadline, user: `${this.#uid}:${this.#gid}`, display: this.#display, maxDeadline: file.maxDeadline });
388
+ const commands = childCommands({ staging, deadline: init.deadline, user: `${this.#uid}:${this.#gid}`, display: this.#display, maxDeadline: init.maxDeadline });
336
389
  const install = await this.#channel.run(ref.id, ["sh", "-c", commands.install], { timeoutMs: execMs, ...(signal ? { signal } : {}) });
337
390
  if (!install.ok)
338
391
  return install;
@@ -469,6 +522,10 @@ export class OrgoProvider {
469
522
  const drift = [...found.value, ...probeNetworkDrift(probe.value)];
470
523
  return drift.length === 0 ? ok(probeNotes(probe.value, "none")) : fail("refused", `it did not match its spec: ${drift.join("; ")}`);
471
524
  }
525
+ /** Init's deadline and its most for an agent's own computer started at now: maxLifetimeMs out, and none in practice. */
526
+ #ownedInit(now) {
527
+ return { deadline: new Date(now + this.#maxLifetimeMs).toISOString(), maxDeadline: OWNED_MAX_DEADLINE };
528
+ }
472
529
  #daemonExpected() {
473
530
  const { kind, groups } = this.capabilities();
474
531
  return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: "amd64", kind, groups };
@@ -530,7 +587,11 @@ export class OrgoProvider {
530
587
  }
531
588
  }
532
589
  /** Orgo's record of a computer; not_found once Orgo no longer has it. */
590
+ /** Orgo's record of a computer. The workspace is read first, so #ours knows it for every record read. */
533
591
  async #get(id, signal) {
592
+ const workspace = await this.#workspace.read(signal);
593
+ if (!workspace.ok)
594
+ return workspace;
534
595
  const read = await this.#rest.request("GET", `/computers/${encodeURIComponent(id)}`, { timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
535
596
  if (!read.ok)
536
597
  return read;
@@ -543,7 +604,8 @@ export class OrgoProvider {
543
604
  // A ref's name matches by its stable part: extend renames the computer with its new deadline.
544
605
  // A Windows or macOS computer in the workspace is the desktop provider's (orgo-desktop.ts), where Orgo says its os.
545
606
  return (nameParts(record.name) !== undefined &&
546
- (record.workspace_id ?? record.project_id) === this.#workspaceId &&
607
+ this.#workspace.id !== undefined &&
608
+ (record.workspace_id ?? record.project_id) === this.#workspace.id &&
547
609
  (name === undefined || sameComputer(record.name, name)) &&
548
610
  record.status !== "deleted" &&
549
611
  (record.os === undefined || record.os === "linux"));
@@ -577,6 +639,54 @@ export class OrgoProvider {
577
639
  }
578
640
  return `; the computer named ${name}: ${said.join("; ")}`;
579
641
  }
642
+ /** An agent's computer's ledger entry, put; a ledger that fails is a failure in words. */
643
+ async #keep(entry) {
644
+ try {
645
+ await this.#ledger.put(entry);
646
+ return ok(undefined);
647
+ }
648
+ catch (error) {
649
+ return vendorFail("orgo", `the ledger of agents' computers could not be written: ${error instanceof Error ? error.message : String(error)}`);
650
+ }
651
+ }
652
+ /** Every agent's computer's ledger entry, by id. */
653
+ async #entries() {
654
+ try {
655
+ return ok(new Map((await this.#ledger.list()).map((entry) => [entry.id, entry])));
656
+ }
657
+ catch (error) {
658
+ return vendorFail("orgo", `the ledger of agents' computers could not be read: ${error instanceof Error ? error.message : String(error)}`);
659
+ }
660
+ }
661
+ /** A deleted computer's ledger entry, gone; best effort, since the computer is gone whatever the ledger says. */
662
+ async #forget(id) {
663
+ try {
664
+ await this.#ledger.remove(id);
665
+ }
666
+ catch {
667
+ // A stale entry names a computer Orgo no longer has: list never shows it.
668
+ }
669
+ }
670
+ /**
671
+ * An agent's computer deleted under `claim` (ReleaseContext): its entry taken first, only while it carries exactly the
672
+ * claim's run and epoch and no attach or detach holds it (takeEntry, only), so a claim that made it and lost it never
673
+ * deletes it from under a later claim. A delete Orgo refused lets the entry go again; one Orgo took forgot it already.
674
+ */
675
+ #claimedDelete(ref, name, claim, signal) {
676
+ const owner = nameParts(name)?.owner;
677
+ if (owner === undefined)
678
+ 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`));
679
+ return inTurn(this.#owning, ref.id, async () => {
680
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being deleted", { only: true });
681
+ if (!taken.ok)
682
+ return taken;
683
+ const deleted = await this.#delete(ref, signal);
684
+ if (deleted.ok)
685
+ return deleted;
686
+ const left = await this.#entries();
687
+ return left.ok && !left.value.has(ref.id) ? deleted : andSettled(deleted, await settleEntry(this.#ledger, ref, taken.value));
688
+ });
689
+ }
580
690
  /** DELETE, tried again while Orgo answers 409 (waking), then the wait until Orgo no longer has the computer. */
581
691
  async #delete(ref, signal) {
582
692
  const { requestMs, pollMs, goneMs } = this.#timeouts;
@@ -589,6 +699,7 @@ export class OrgoProvider {
589
699
  return deleted;
590
700
  await pause(pollMs);
591
701
  }
702
+ await this.#forget(ref.id);
592
703
  const until = Date.now() + goneMs;
593
704
  let last = "unread";
594
705
  for (;;) {
@@ -609,13 +720,17 @@ export class OrgoProvider {
609
720
  }
610
721
  /** The workspace's computers, as Orgo lists them. */
611
722
  async #desktops(signal) {
612
- const read = await this.#rest.request("GET", `/workspaces/${encodeURIComponent(this.#workspaceId)}`, { timeoutMs: this.#timeouts.listMs, ...(signal ? { signal } : {}) });
723
+ const workspace = await this.#workspace.read(signal);
724
+ if (!workspace.ok)
725
+ return workspace;
726
+ const id = workspace.value;
727
+ const read = await this.#rest.request("GET", `/workspaces/${encodeURIComponent(id)}`, { timeoutMs: this.#timeouts.listMs, ...(signal ? { signal } : {}) });
613
728
  if (!read.ok)
614
729
  return read;
615
730
  const desktops = read.value?.desktops;
616
731
  if (!Array.isArray(desktops))
617
- return vendorFail("orgo", `Orgo's workspace ${this.#workspaceId} lists no computers array`);
618
- return ok(desktops.filter((one) => typeof one?.id === "string" && typeof one.name === "string").map((one) => ({ ...one, workspace_id: this.#workspaceId })));
732
+ return vendorFail("orgo", `Orgo's workspace ${id} lists no computers array`);
733
+ return ok(desktops.filter((one) => typeof one?.id === "string" && typeof one.name === "string").map((one) => ({ ...one, workspace_id: id })));
619
734
  }
620
735
  /** The live view: screen.watch on a connection of the watch's own (daemonWatch), never Orgo's VNC (proxy only). */
621
736
  watch(ref, handlers, options) {
@@ -640,7 +755,7 @@ export class OrgoProvider {
640
755
  await opened.value.close();
641
756
  return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drift.join("; ")}`);
642
757
  }
643
- async attach(ref, { signal } = {}) {
758
+ async attach(ref, { signal, claim } = {}) {
644
759
  const given = (typeof ref === "object" && ref !== null ? ref : {});
645
760
  if ((given.id === undefined) === (given.labels === undefined))
646
761
  return fail("invalid", "attach takes { id } or { labels }, one of them");
@@ -652,7 +767,7 @@ export class OrgoProvider {
652
767
  return read.error.code === "not_found" ? fail("not_found", `no Orgo computer has the id ${given.id}`) : read;
653
768
  if (!this.#ours(read.value))
654
769
  return fail("not_found", `no Orgo computer of this provider has the id ${given.id}`);
655
- return this.#attached(read.value, signal);
770
+ return this.#attached(read.value, signal, claim);
656
771
  }
657
772
  const problem = filterProblem(given.labels);
658
773
  if (problem)
@@ -671,58 +786,126 @@ export class OrgoProvider {
671
786
  const found = await this.#own(listed.value[0].ref, signal);
672
787
  if (!found.ok)
673
788
  return found;
674
- return this.#attached(found.value, signal);
789
+ return this.#attached(found.value, signal, claim);
675
790
  }
676
791
  /**
677
792
  * The drift check of a computer attach did not make: its labels file, the truth, held to its name, then its daemon
678
793
  * and the probe, as at create. One that drifts is refused and left as it is. A computer that does not run is
679
- * refused: reading it from inside would wake it.
794
+ * refused: reading it from inside would wake it. An agent's own computer is the exception: attaching it is asking
795
+ * for it. Its ledger entry is taken for the claim first, busy (takeEntry), before anything is done to the computer;
796
+ * one a detach suspended is then resumed (#wake), its memory and init with it; its daemon is moved on or installed
797
+ * again (#ownedInside); and it is marked held in the ledger last (settleEntry), by this attach alone, while the entry
798
+ * is still the one it holds. An attach that resumed it and then fails suspends it again, as it was found (#putBack).
799
+ * This process's attaches and detaches of one agent's computer are taken in turn; another process's are refused while
800
+ * this one holds the entry, so no attach or detach ends the programs or sleep of another's.
801
+ */
802
+ async #attached(record, signal, claim) {
803
+ const ref = { id: record.id, name: record.name };
804
+ const parts = nameParts(record.name);
805
+ if (parts.owner === undefined) {
806
+ if (claim !== undefined)
807
+ return fail("refused", claimProblem(ref.name, undefined, undefined, claim));
808
+ if (record.status !== "running")
809
+ return fail("refused", `${ref.name} is ${record.status}: its labels file and daemon are read from inside, and a read would wake it`);
810
+ return this.#checked(record, parts, signal);
811
+ }
812
+ const owner = parts.owner;
813
+ return inTurn(this.#owning, ref.id, async (waited) => {
814
+ // Read again after waiting: the attach or detach before this one may have resumed or suspended it.
815
+ const now = waited ? await this.#own(ref, signal) : ok(record);
816
+ if (!now.ok)
817
+ return now;
818
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being attached");
819
+ if (!taken.ok)
820
+ return taken;
821
+ const lease = taken.value;
822
+ const woke = now.value.status !== "running";
823
+ const attached = await this.#resumed(now.value, parts, lease, woke, signal, claim);
824
+ if (!attached.ok && woke)
825
+ return this.#putBack(ref, lease, attached.error);
826
+ // Marked held (no longer detached) once attached; a failed attach that woke nothing leaves it as it was.
827
+ return andSettled(attached, await settleEntry(this.#ledger, ref, lease, attached.ok ? ({ detachedAt: _held, ...held }) => held : undefined));
828
+ });
829
+ }
830
+ /**
831
+ * An agent's own computer, its entry taken: resumed when it was not running; under a claim, its labels file carries
832
+ * the claim's run and epoch from now on, as the ledger does; then checked.
833
+ */
834
+ async #resumed(record, parts, lease, woke, signal, claim) {
835
+ const ref = { id: record.id, name: record.name };
836
+ if (woke) {
837
+ const woken = await this.#wake(ref, record.status, signal);
838
+ if (!woken.ok)
839
+ return woken;
840
+ }
841
+ if (claim !== undefined) {
842
+ // Its labels file is written under the claim only while this attach still holds the entry, however long the wake took.
843
+ if (woke) {
844
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being attached");
845
+ if (!renewed.ok)
846
+ return renewed;
847
+ }
848
+ const read = await this.#readLabels(ref, signal);
849
+ if (!read.ok)
850
+ return read;
851
+ const written = await this.#writeLabels(ref, { ...read.value, labels: lease.entry.labels }, signal);
852
+ if (!written.ok)
853
+ return written;
854
+ }
855
+ return this.#checked(record, parts, signal, lease);
856
+ }
857
+ /**
858
+ * An agent's own computer this attach resumed, suspended again once the attach fails, best effort, as release detach
859
+ * suspends it, so it is left as it was found; its ledger entry still says when it was detached (takeEntry kept it).
860
+ * One another claim has taken since is that claim's, and runs on. Never signalled: it outlives an abort.
680
861
  */
681
- async #attached(record, signal) {
862
+ async #putBack(ref, lease, error) {
863
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being put back to sleep by an attach that failed");
864
+ if (!renewed.ok)
865
+ return fail(error.code, `${error.message}; ${ref.name} runs on, not suspended again: ${renewed.error.message}`);
866
+ const suspended = await this.#suspend(ref);
867
+ 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})`}`);
868
+ return andSettled(failed, await settleEntry(this.#ledger, ref, lease));
869
+ }
870
+ /** The labels file, the truth, held to the name, then the daemon and the probe: the drift check of #attached. `lease`:
871
+ * an agent's computer's ledger entry as this attach holds it, for its daemon's replacement. */
872
+ async #checked(record, parts, signal, lease) {
682
873
  const ref = { id: record.id, name: record.name };
683
- if (record.status !== "running")
684
- return fail("refused", `${ref.name} is ${record.status}: its labels file and daemon are read from inside, and a read would wake it`);
685
874
  const file = await this.#readLabels(ref, signal);
686
875
  if (!file.ok)
687
876
  return file;
688
877
  const found = [];
689
- const parts = nameParts(record.name);
690
878
  const { labels } = file.value;
691
879
  if (typeof file.value.name !== "string" || !sameComputer(file.value.name, record.name))
692
880
  found.push(`name: Orgo's is ${record.name}, the labels file's ${show(file.value.name)}`);
881
+ if ((parts.owner ?? "") !== ownerHashOfLabels(labels))
882
+ found.push(`owner: the name's owner hash ${show(parts.owner)} is not the labels file's owner ${show(labels[OWNER_LABEL])}`);
693
883
  const run = labels[RUN_LABEL];
694
- if ((parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
884
+ // An agent's own computer is no run's: its name carries no run or epoch, whatever run made it.
885
+ if (parts.owner === undefined && (parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
695
886
  found.push(`run: the name's run hash ${show(parts.run)} is not the labels file's run ${show(run)}`);
696
- if ((parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
887
+ if (parts.owner === undefined && (parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
697
888
  found.push(`epoch: the name says ${show(parts.epoch)}, the labels file ${show(labels[EPOCH_LABEL])}`);
698
- const deadline = new Date(file.value.deadline);
699
- if (Number.isNaN(deadline.getTime()))
889
+ const deadline = parts.owner === undefined ? new Date(file.value.deadline) : undefined;
890
+ if (deadline !== undefined && Number.isNaN(deadline.getTime()))
700
891
  found.push(`deadline: the labels file reads ${show(file.value.deadline)}, not a time`);
892
+ if (parts.owner !== undefined && file.value.deadline !== NO_DEADLINE)
893
+ found.push(`deadline: an agent's own computer has none, and the labels file reads ${show(file.value.deadline)}`);
701
894
  let notes = [];
702
- let kind;
703
895
  if (found.length === 0) {
704
- const ports = await this.#rootPorts(ref, signal);
705
- if (!ports.ok)
706
- return ports;
707
- const opened = await this.#open(ref, signal);
708
- if (!opened.ok)
709
- return opened;
710
- try {
711
- const inside = await this.#checkInside(opened.value, ref.name, ports.value, signal);
712
- if (!inside.ok && inside.error.code !== "refused")
713
- return inside;
714
- if (!inside.ok)
715
- found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
716
- else
717
- notes = inside.value;
718
- }
719
- finally {
720
- await opened.value.close();
721
- }
722
- kind = opened.value.hello.kind;
896
+ // lease is given for an agent's own computer alone (#resumed).
897
+ const inside = lease === undefined ? await this.#inside(ref, signal) : await this.#ownedInside(ref, file.value, lease, signal);
898
+ if (!inside.ok && inside.error.code !== "refused")
899
+ return inside;
900
+ if (!inside.ok)
901
+ found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
902
+ else
903
+ notes = inside.value;
723
904
  }
724
905
  if (found.length > 0)
725
906
  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("; ")}`);
907
+ // The daemon's hello passed the drift check, which holds its kind to this provider's.
908
+ const { kind } = this.capabilities();
726
909
  return ok({
727
910
  ...ref,
728
911
  spec: {
@@ -732,12 +915,110 @@ export class OrgoProvider {
732
915
  ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }),
733
916
  ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }),
734
917
  workdir: WORK,
735
- deadline,
736
- ...(kind === undefined ? {} : { kind }),
918
+ ...(deadline === undefined ? {} : { deadline }),
919
+ kind,
920
+ ...ownerReadBack(labels),
737
921
  },
738
922
  ...(notes.length > 0 ? { notes } : {}),
739
923
  });
740
924
  }
925
+ /** A run's computer's daemon and the probe, as at create: the probe's notes. */
926
+ async #inside(ref, signal) {
927
+ const ports = await this.#rootPorts(ref, signal);
928
+ if (!ports.ok)
929
+ return ports;
930
+ const opened = await this.#open(ref, signal);
931
+ if (!opened.ok)
932
+ return opened;
933
+ try {
934
+ return await this.#checkInside(opened.value, ref.name, ports.value, signal);
935
+ }
936
+ finally {
937
+ await opened.value.close();
938
+ }
939
+ }
940
+ /**
941
+ * An agent's own computer's daemon: init's deadline moved maxLifetimeMs out (deadline.extend), then checked as at
942
+ * create. One that does not answer (init ended at its deadline: the desktop was detached past maxLifetimeMs), answers
943
+ * as another version (the package was upgraded while it was detached), or whose deadline no longer moves (init is
944
+ * ending) is installed and started again over the same disk (#replaceDaemon). A run's computer is never replaced
945
+ * (#inside): its daemon is its run's, and one that drifts refuses the attach.
946
+ */
947
+ async #ownedInside(ref, file, lease, signal) {
948
+ const ports = await this.#rootPorts(ref, signal);
949
+ if (!ports.ok)
950
+ return ports;
951
+ const opened = await this.#open(ref, signal);
952
+ if (!opened.ok)
953
+ return opened.notListening ? this.#replaceDaemon(ref, file, lease, "its daemon did not answer (init had ended)", signal) : opened;
954
+ let stale;
955
+ try {
956
+ const { client, hello } = opened.value;
957
+ if (hello.version !== VERSION)
958
+ stale = `its daemon was version ${hello.version}, not this provider's ${VERSION}`;
959
+ else {
960
+ const at = new Date(Date.now() + this.#maxLifetimeMs).toISOString();
961
+ const extended = await client.call("deadline.extend", { at }, { signal: this.#bounded(this.#timeouts.helloMs, signal) });
962
+ // invalid: init's deadline is already later than at (maxLifetimeMs was lowered since), and it is kept.
963
+ if (!extended.ok && extended.error.code === "unsupported")
964
+ stale = `its init's deadline no longer moved (${extended.error.message})`;
965
+ else if (!extended.ok && extended.error.code !== "invalid")
966
+ return fail(extended.error.code, `init's deadline in ${ref.name} did not move to ${at}: ${extended.error.message}`);
967
+ else
968
+ return await this.#checkInside(opened.value, ref.name, ports.value, signal);
969
+ }
970
+ }
971
+ finally {
972
+ await opened.value.close();
973
+ }
974
+ return this.#replaceDaemon(ref, file, lease, stale, signal);
975
+ }
976
+ /**
977
+ * An agent's own computer's daemon installed and started again, its disk kept: the old init stopped by its exact
978
+ * processes, which ends its programs (STOP_INIT_SCRIPT), then every step create takes (#prepare: the upload, the
979
+ * install with its sha256 read back, the X socket, the labels file, root's ports, the lockdown, init, its first
980
+ * connection and the drift check). The attach's busy marker is renewed first (renewEntry), only while the ledger entry
981
+ * is still the one this attach holds (`lease`): an attach that lost it (its marker went stale and another took the
982
+ * computer) stops nothing, so an older attach never stops the init a newer one started. The probe's notes, after one
983
+ * that says the daemon was replaced and why.
984
+ */
985
+ async #replaceDaemon(ref, file, lease, why, signal) {
986
+ let daemon;
987
+ try {
988
+ daemon = readFileSync(this.#daemonPath);
989
+ }
990
+ catch {
991
+ 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`);
992
+ }
993
+ const renewed = await renewEntry(this.#ledger, ref, lease, "its daemon being replaced by an attach");
994
+ if (!renewed.ok)
995
+ return fail(renewed.error.code, `${ref.name}'s daemon needs replacing, since ${why}, and is left as it is: ${renewed.error.message}`);
996
+ const stopped = await this.#channel.run(ref.id, ["sh", "-c", STOP_INIT_SCRIPT, "sh", DAEMON_IN_COMPUTER], { timeoutMs: this.#timeouts.execMs, ...(signal ? { signal } : {}) });
997
+ if (!stopped.ok)
998
+ return stopped;
999
+ if (stopped.value.exitCode !== 0)
1000
+ 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)}`);
1001
+ const prepared = await this.#prepare(ref, "running", file, daemon, signal, this.#ownedInit(Date.now()));
1002
+ if (!prepared.ok)
1003
+ return fail(prepared.error.code, `replacing ${ref.name}'s daemon, since ${why}, failed: ${prepared.error.message}`);
1004
+ return ok([`the daemon in ${ref.name} was replaced with this provider's ${VERSION}, its disk kept, since ${why}`, ...prepared.value]);
1005
+ }
1006
+ /**
1007
+ * An agent's own computer that a detach suspended, resumed for its attach: Orgo's resume (its memory back, computerd
1008
+ * init still running), then running. One stopped outside this provider comes back from its disk alone, with no init:
1009
+ * Orgo's start, and the daemon is then installed again (#ownedInside).
1010
+ */
1011
+ async #wake(ref, status, signal) {
1012
+ const how = status === "suspended" || status === "suspending" ? "resume" : status === "frozen" || status === "stopped" ? "start" : undefined;
1013
+ if (how === undefined && !RUNNING.has(status))
1014
+ return fail("refused", `${ref.name} is ${status}: no resume or start brings it back`);
1015
+ if (how !== undefined) {
1016
+ const woken = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/${how}`, { body: {}, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
1017
+ if (!woken.ok)
1018
+ return fail(woken.error.code, `${ref.name} could not ${how} for its attach: ${woken.error.message}`);
1019
+ }
1020
+ return this.#untilRunning(ref, signal);
1021
+ }
741
1022
  /**
742
1023
  * Every computer of this provider in the workspace that carries all of these labels. The run and the epoch are read
743
1024
  * from the name, with nothing run in a computer, so a stopped one is listed too; any other label is read from the
@@ -751,6 +1032,10 @@ export class OrgoProvider {
751
1032
  if (!listed.ok)
752
1033
  return listed;
753
1034
  const others = Object.keys(labels).filter((key) => key !== RUN_LABEL && key !== EPOCH_LABEL);
1035
+ // An agent's computers' labels are the ledger's: read once, only when the workspace holds one.
1036
+ const owned = listed.value.some((record) => nameParts(record.name)?.owner !== undefined) ? await this.#entries() : ok(new Map());
1037
+ if (!owned.ok)
1038
+ return owned;
754
1039
  const infos = [];
755
1040
  for (const record of listed.value) {
756
1041
  const parts = nameParts(record.name);
@@ -758,12 +1043,22 @@ export class OrgoProvider {
758
1043
  // (orgo-desktop.ts), never this one's to list or its janitor's to sweep.
759
1044
  if (parts === undefined || record.status === "deleted" || (record.os !== undefined && record.os !== "linux"))
760
1045
  continue;
1046
+ const ref = { id: record.id, name: record.name };
1047
+ const running = RUNNING.has(record.status);
1048
+ // An agent's computer: every label from its ledger entry, with nothing run inside, whatever its state; no deadline.
1049
+ if (parts.owner !== undefined) {
1050
+ const view = ownedListing(owned.value.get(record.id), labels);
1051
+ if (view === undefined)
1052
+ continue;
1053
+ infos.push({ ref, deadline: undefined, state: running ? "running" : "stopped", network: "none", ...view });
1054
+ continue;
1055
+ }
1056
+ if (labels[OWNER_LABEL] !== undefined || labels[OWNER_SERVER_LABEL] !== undefined)
1057
+ continue;
761
1058
  if (labels[RUN_LABEL] !== undefined && parts.run !== runHash(labels[RUN_LABEL]))
762
1059
  continue;
763
1060
  if (labels[EPOCH_LABEL] !== undefined && parts.epoch !== labels[EPOCH_LABEL])
764
1061
  continue;
765
- const ref = { id: record.id, name: record.name };
766
- const running = RUNNING.has(record.status);
767
1062
  // 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
768
1063
  // janitor) can still tell whose run a computer is.
769
1064
  let read = {
@@ -792,6 +1087,10 @@ export class OrgoProvider {
792
1087
  async testConnection(context = {}) {
793
1088
  return listTested("Orgo", await this.list({}, context));
794
1089
  }
1090
+ /** Settings' pick of ORGO_WORKSPACE_ID (workspaceId): every workspace the key's account sees, by name. Makes nothing. */
1091
+ keyChoices(option, { signal } = {}) {
1092
+ return workspaceChoices(this.#rest, option, { timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
1093
+ }
795
1094
  async network(ref, policy, { signal } = {}) {
796
1095
  const problem = refProblem(ref);
797
1096
  if (problem)
@@ -821,23 +1120,61 @@ export class OrgoProvider {
821
1120
  await opened.value.close();
822
1121
  }
823
1122
  }
824
- /** delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. No stop. */
825
- async release(ref, how, { signal } = {}) {
1123
+ /**
1124
+ * delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. detach, for an
1125
+ * agent's own computer alone: Orgo's suspend, its memory and disk saved, read back suspended. No stop: a run's
1126
+ * computer is deleted.
1127
+ */
1128
+ async release(ref, how, { signal, claim } = {}) {
826
1129
  const problem = refProblem(ref);
827
1130
  if (problem)
828
1131
  return fail("invalid", problem);
829
- if (how !== "stop" && how !== "delete")
830
- return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1132
+ if (how !== "stop" && how !== "delete" && how !== "detach")
1133
+ return fail("invalid", `release is "stop", "delete" or "detach", not ${String(how)}`);
831
1134
  if (how === "stop")
832
- return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete");
1135
+ return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete, or detach an agent's own");
833
1136
  const read = await this.#get(ref.id);
834
1137
  if (!read.ok)
835
- return read.error.code === "not_found" ? ok(undefined) : read;
1138
+ return read.error.code === "not_found" && how === "delete" ? ok(undefined) : read;
836
1139
  if (read.value.status === "deleted")
837
- return ok(undefined);
1140
+ return how === "delete" ? ok(undefined) : fail("not_found", `${ref.name} is deleted: there is nothing to detach`);
838
1141
  if (!this.#ours(read.value, ref.name))
839
1142
  return fail("not_found", `no Orgo computer of this provider is ${ref.name} (${ref.id}), so it is left as it is`);
840
- return this.#delete(ref, signal);
1143
+ if (how === "delete")
1144
+ return claim === undefined ? this.#delete(ref, signal) : this.#claimedDelete(ref, read.value.name, claim, signal);
1145
+ const owner = nameParts(read.value.name)?.owner;
1146
+ if (owner === undefined)
1147
+ return fail("refused", `${ref.name} is a run's computer, not an agent's own: it is deleted at its release, never detached`);
1148
+ // In turn with this process's attaches, and holding the ledger entry from before the suspend until it is marked
1149
+ // detached (takeEntry, settleEntry), so no attach resumes it meanwhile and an attach under way refuses this detach.
1150
+ return inTurn(this.#owning, ref.id, async (waited) => {
1151
+ const taken = await takeEntry(this.#ledger, ref, owner, undefined, "being detached");
1152
+ if (!taken.ok)
1153
+ return taken;
1154
+ const now = waited ? await this.#own(ref, signal) : ok(read.value);
1155
+ const suspended = !now.ok ? now : now.value.status === "suspended" ? ok(undefined) : await this.#suspend(ref, signal);
1156
+ return andSettled(suspended, await settleEntry(this.#ledger, ref, taken.value, suspended.ok ? (entry) => ({ ...entry, detachedAt: entry.detachedAt ?? new Date().toISOString() }) : undefined));
1157
+ });
1158
+ }
1159
+ /** Orgo's suspend, the computer's memory and disk saved, then the wait until Orgo reads it suspended. */
1160
+ async #suspend(ref, signal) {
1161
+ const suspended = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/suspend`, { timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
1162
+ if (!suspended.ok)
1163
+ return fail(suspended.error.code, `${ref.name} could not be suspended for its agent: ${suspended.error.message}`);
1164
+ // 202 suspending: its memory is still being saved. Read until Orgo says suspended.
1165
+ const until = Date.now() + this.#timeouts.goneMs;
1166
+ for (;;) {
1167
+ const now = await this.#get(ref.id, signal);
1168
+ if (!now.ok)
1169
+ return now;
1170
+ if (now.value.status === "suspended")
1171
+ return ok(undefined);
1172
+ if (Date.now() >= until)
1173
+ return fail("timeout", `${ref.name} was not suspended ${seconds(this.#timeouts.goneMs)} after its suspend; Orgo last read ${now.value.status}`);
1174
+ await pause(this.#timeouts.pollMs, signal);
1175
+ if (signal?.aborted)
1176
+ return fail("aborted", `the wait for ${ref.name} to be suspended was aborted`);
1177
+ }
841
1178
  }
842
1179
  /**
843
1180
  * Moves the deadline to now + ttlMs, never earlier and never past the most the labels file holds (create's time plus
@@ -847,16 +1184,7 @@ export class OrgoProvider {
847
1184
  * is refused as earlier, never renaming the computer back to an earlier deadline the janitor would trust.
848
1185
  */
849
1186
  extend(ref, ttlMs, context = {}) {
850
- const key = typeof ref?.id === "string" ? ref.id : "";
851
- const before = this.#extending.get(key) ?? Promise.resolve();
852
- const turn = before.then(() => this.#extend(ref, ttlMs, context));
853
- const settled = turn.then(() => undefined, () => undefined);
854
- this.#extending.set(key, settled);
855
- void settled.then(() => {
856
- if (this.#extending.get(key) === settled)
857
- this.#extending.delete(key);
858
- });
859
- return turn;
1187
+ return inTurn(this.#extending, typeof ref?.id === "string" ? ref.id : "", () => this.#extend(ref, ttlMs, context));
860
1188
  }
861
1189
  async #extend(ref, ttlMs, { signal } = {}) {
862
1190
  const problem = refProblem(ref);
@@ -867,6 +1195,8 @@ export class OrgoProvider {
867
1195
  const found = await this.#own(ref, signal);
868
1196
  if (!found.ok)
869
1197
  return found;
1198
+ if (nameParts(found.value.name)?.owner !== undefined)
1199
+ return fail("refused", `${ref.name} is an agent's own computer: it has no deadline to move`);
870
1200
  if (found.value.status !== "running")
871
1201
  return fail("refused", `${ref.name} is ${found.value.status}, not running`);
872
1202
  const file = await this.#readLabels(ref, signal);