@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
@@ -0,0 +1,1856 @@
1
+ var _a;
2
+ // Orgo's Windows and macOS desktops, daemon none: no computerd runs in them (CP-8, computerd for Windows and macOS, is
3
+ // deferred), so this provider answers the protocol's methods itself, in process, over Orgo's REST API, as the phone
4
+ // harness and Browserbase do. Every Orgo fact here is from docs.orgo.ai (read 2026-11-10; the pages are kept in the
5
+ // lane's vendor-docs/orgo/windows):
6
+ // - POST /computers takes os "windows" or "macos" on the same API as Linux. Windows needs Orgo's Scale plan or a Windows
7
+ // computer bought on the plan (403 WINDOWS_REQUIRES_SCALE otherwise) and is never billed by the hour. macOS takes ram
8
+ // 10 and nothing else (400 MACOS_RAM_FIXED), has no ends_in_hours (400 ENDS_NOT_SUPPORTED) and needs a Mac host
9
+ // serving the workspace (422 OS_UNAVAILABLE). A Mac Orgo manages may refuse a delete with 409.
10
+ // - GET /computers/{id}/screenshot?response_format=base64&format=png&scale=s answers { image, width, height } in PNG.
11
+ // - POST /computers/{id}/{click,mouse-move,drag,type,key,scroll} drive the screen. On Windows each answers { ok: true };
12
+ // click takes x, y, button and double (no modifiers, no repeat); drag takes start_x, start_y, end_x, end_y and button;
13
+ // type takes text alone, at most 20,000 bytes; key takes a key or a combination joined by "+", Windows key names
14
+ // (pageup, pagedown); scroll takes direction (up or down) and amount (1 to 50) alone, at the pointer.
15
+ // - POST /computers/{id}/bash runs PowerShell on Windows, from the user's Desktop folder, and answers stdout, stderr,
16
+ // exit_code and output; a command past its timeout answers exit_code 124 and error "timeout". The timeout is 1 to 300 s.
17
+ // - POST /files/upload with destPath drops a file into one folder of one computer (at most 10 MB).
18
+ // Nothing here runs in a computer Orgo does not read running: any action wakes a suspended one.
19
+ //
20
+ // What each desktop offers is what Orgo's API can answer: the screen, the pointer and the keys; exec, as PowerShell on
21
+ // Windows and the shell on macOS; and, on Windows, files, through PowerShell. No processes (Orgo runs a command and
22
+ // waits for it, nothing more), no network of its own (Orgo has no egress control: a program in the computer reaches the
23
+ // internet, so the network is "open", the one a provider that cannot hold a computer to none declares), and no mount.
24
+ // Orgo's API has no separate press and release: a down is held in the client and its up becomes one click (the pointer
25
+ // did not move) or one drag (from where it went down), so a press is seen on the screen only when it is released.
26
+ //
27
+ // The name carries the run, the epoch and the janitor's deadline, as the Linux desktop's does (orgo-names.ts). The rest
28
+ // of the labels is a file in the computer the provider writes at create (C:\ProgramData\agentrun\labels.json on Windows,
29
+ // /Users/Shared/agentrun/labels.json on macOS). Unlike Linux's root-owned file, a program in the computer can change it:
30
+ // the name, which only the provider's key can change, is what list, the janitor and the takeover trust.
31
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
32
+ import { readFileSync } from "node:fs";
33
+ import { checkActions } from "./actions.js";
34
+ import { readPng } from "./conformance/png.js";
35
+ import { MACOS_GROUPS, ORGO_MACOS_IMAGE, ORGO_WINDOWS_IMAGE, WINDOWS_GROUPS } from "./descriptors/orgo.js";
36
+ import { EPOCH_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerLabels, RUN_HASH_LABEL, RUN_LABEL, runHash } from "./labels.js";
37
+ import { checkMount } from "./mount.js";
38
+ import { ORGO_API_URL, orgoRest } from "./orgo-channel.js";
39
+ import { COMPUTER_ID, claimProblem, andSettled, inTurn, filterProblem, labelProblem, labelsOf, NAME_MAX, NO_DEADLINE, nameParts, orgoMemoryLedger, orgoName, ownedListing, ownerHashOfLabels, ownerReadBack, refProblem, sameComputer, settleEntry, show, renewEntry, takeEntry, withDeadline, } from "./orgo-names.js";
40
+ import { encodePng } from "./phone-harness.js";
41
+ import { MAX_CHUNK_BYTES, MAX_LIST_ENTRIES, MAX_OUTPUT_BYTES, PROTOCOL_VERSION, } from "./protocol.js";
42
+ import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
43
+ import { failFor, ok, vendorFail } from "./result.js";
44
+ import { daemonWatch } from "./screen-watch.js";
45
+ import { listTested } from "./test-connection.js";
46
+ /** This module's fail: a vendor failure names Orgo (CP-1's one vendor code). */
47
+ const fail = failFor("orgo");
48
+ const PROFILES = {
49
+ windows: {
50
+ os: "windows",
51
+ image: ORGO_WINDOWS_IMAGE,
52
+ groups: WINDOWS_GROUPS,
53
+ arch: "amd64",
54
+ labels: "C:\\ProgramData\\agentrun\\labels.json",
55
+ staging: "C:\\ProgramData\\agentrun\\staging",
56
+ ram: [4, 8, 16, 32],
57
+ ends: true,
58
+ cpus: true,
59
+ typeBytes: 20_000,
60
+ windowsInput: true,
61
+ },
62
+ macos: {
63
+ os: "macos",
64
+ image: ORGO_MACOS_IMAGE,
65
+ groups: MACOS_GROUPS,
66
+ arch: "arm64",
67
+ labels: "/Users/Shared/agentrun/labels.json",
68
+ ram: [10],
69
+ ends: false,
70
+ cpus: false,
71
+ // At Orgo's 12 ms a keystroke, about 2,500 characters fit the API's 30 s wait: a third of it, to be safe.
72
+ typeBytes: 800,
73
+ windowsInput: false,
74
+ },
75
+ };
76
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
77
+ const HOUR = 3_600_000;
78
+ const MAX_LIFETIME_MS = 720 * HOUR;
79
+ const CPU_FOR_RAM = { 4: 1, 8: 2, 16: 4, 32: 6 };
80
+ const CPUS = [0.5, 1, 2, 4, 6];
81
+ const WORKSPACE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
82
+ const DEFAULTS = { requestMs: 30_000, createMs: 600_000, execMs: 60_000, listMs: 60_000, goneMs: 120_000, pollMs: 2_000 };
83
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "labels", "gpu"]);
84
+ /** The states in which a computer runs, or is on its way to. */
85
+ const RUNNING = new Set(["running", "creating", "restarting", "updating", "resuming"]);
86
+ /** How often a delete that answers 409 (the computer waking) is tried again. */
87
+ const DELETE_TRIES = 5;
88
+ /** Orgo's bash call's longest timeout, in seconds, and how much longer its proxy waits. */
89
+ const BASH_MAX_S = 300;
90
+ const BASH_PROXY_MS = 30_000;
91
+ /** How often a waiting screen.watch reads the screen, as the phone's does. */
92
+ const WATCH_POLL_MS = 1_000;
93
+ /** How much of a file one files.read through PowerShell carries back: base64 of it stays well inside one answer. */
94
+ const READ_CHUNK_BYTES = 256 * 1024;
95
+ /** The most base64 a files.write puts inline in a PowerShell command; more goes through Orgo's upload first. */
96
+ const INLINE_WRITE_CHARS = 96 * 1024;
97
+ /** Orgo's scroll takes at most 50 wheel clicks a call. */
98
+ const SCROLL_MAX = 50;
99
+ const NETWORK = 'an Orgo Windows or macOS computer takes network "open" only: Orgo has no egress control, and no computerd runs in it to hold its programs to loopback';
100
+ const seconds = (ms) => `${ms / 1000} s`;
101
+ const pause = (ms, signal) => new Promise((done) => {
102
+ const timer = setTimeout(finish, ms);
103
+ function finish() {
104
+ clearTimeout(timer);
105
+ signal?.removeEventListener("abort", finish);
106
+ done();
107
+ }
108
+ if (signal?.aborted)
109
+ finish();
110
+ else
111
+ signal?.addEventListener("abort", finish, { once: true });
112
+ });
113
+ /** One word for PowerShell: single-quoted, with every quote PowerShell reads as a single quote doubled. */
114
+ export const psQuote = (word) => `'${word.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
115
+ /** One word for a POSIX shell: single-quoted. */
116
+ export const shQuote = (word) => `'${word.replaceAll("'", "'\\''")}'`;
117
+ /** An environment variable's name either shell takes as written. */
118
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
119
+ /** An absolute Windows path: a drive and a separator, or a UNC path. */
120
+ const WINDOWS_ABSOLUTE = /^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/])/;
121
+ /**
122
+ * The command that runs argv on this desktop, as Orgo's bash call takes it: on Windows a PowerShell call operator over
123
+ * quoted words, whose exit is the program's own ($LASTEXITCODE), or 0 and 1 for a cmdlet; on macOS the words quoted for
124
+ * the shell, through env for the variables. cwd and env are set first; argv is never a shell string. A cwd or variable
125
+ * that cannot be set runs nothing: the command exits 1 with the error on stderr, as the shell's `cd … &&` does on macOS.
126
+ */
127
+ export function commandOf(os, argv, { cwd, env } = {}) {
128
+ if (os === "windows") {
129
+ const setup = [
130
+ ...Object.entries(env ?? {}).map(([name, value]) => `Set-Item -LiteralPath ${psQuote(`Env:${name}`)} -Value ${psQuote(value)} -ErrorAction Stop`),
131
+ ...(cwd === undefined ? [] : [`Set-Location -LiteralPath ${psQuote(cwd)} -ErrorAction Stop`]),
132
+ ];
133
+ return [
134
+ "$ErrorActionPreference = 'Continue'",
135
+ ...(setup.length === 0 ? [] : ["try {", ...setup, "} catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }"]),
136
+ `& ${argv.map(psQuote).join(" ")}`,
137
+ "$agentrunOk = $?; $agentrunCode = $LASTEXITCODE",
138
+ "if ($null -ne $agentrunCode) { exit $agentrunCode } elseif ($agentrunOk) { exit 0 } else { exit 1 }",
139
+ ].join("\n");
140
+ }
141
+ const vars = Object.entries(env ?? {}).map(([name, value]) => shQuote(`${name}=${value}`));
142
+ const run = vars.length > 0 ? `env ${vars.join(" ")} ${argv.map(shQuote).join(" ")}` : argv.map(shQuote).join(" ");
143
+ return cwd === undefined ? run : `cd ${shQuote(cwd)} && ${run}`;
144
+ }
145
+ /** Why a files.write or files.mkdir that names a mode is refused on Windows, before anything is made or changed. */
146
+ const NO_MODES = "an Orgo Windows computer's files have no POSIX mode to set (its file system keeps ACLs): leave mode unset";
147
+ /**
148
+ * The files methods on Windows, as one PowerShell script: its request is base64 of JSON in place of the marker, so no
149
+ * value is ever quoted into the script, and its one line of output is JSON, the result or { error, message }.
150
+ */
151
+ const FILES_SCRIPT = [
152
+ "# agentrun-computer: orgo-windows-files",
153
+ "$ErrorActionPreference = 'Stop'",
154
+ "$p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('@@REQUEST@@')) | ConvertFrom-Json",
155
+ "function Say($o) { [Console]::Out.Write(($o | ConvertTo-Json -Compress -Depth 6)) }",
156
+ "# A refusal leaves nothing of the request behind: a write's uploaded copy goes with it.",
157
+ "function Refuse($kind, $words) { if ($p.staged) { Remove-Item -LiteralPath $p.staged -Force -ErrorAction SilentlyContinue }; Say @{ error = $kind; message = $words }; exit 2 }",
158
+ "function IsLink($i) { $i.LinkType -eq 'SymbolicLink' -or $i.LinkType -eq 'Junction' }",
159
+ "function StatOf($i) {",
160
+ " $t = if (IsLink $i) { 'symlink' } elseif ($i.PSIsContainer) { 'dir' } else { 'file' }",
161
+ " $m = if ($i.PSIsContainer) { 493 } elseif ($i.IsReadOnly) { 292 } else { 420 }",
162
+ " $s = if ($i.PSIsContainer) { 0 } else { [int64]$i.Length }",
163
+ " $at = [int64](($i.LastWriteTimeUtc - [datetime]'1970-01-01T00:00:00Z').TotalMilliseconds)",
164
+ " $o = @{ type = $t; size = $s; mode = $m; mtimeMs = $at; uid = 0; gid = 0 }",
165
+ " if ((IsLink $i) -and $i.Target) { $o.target = [string]@($i.Target)[0] }",
166
+ " $o",
167
+ "}",
168
+ "# What a link at $p.path points to, followed to the end as stat(2) does; one that points nowhere is not_found.",
169
+ "function Follow($i) {",
170
+ " $n = 0",
171
+ " while (IsLink $i) {",
172
+ " $n++; if ($n -gt 40) { Refuse 'invalid' \"$($p.path) is a chain of more than 40 links\" }",
173
+ " $t = [string]@($i.Target)[0]",
174
+ " if (-not $t) { Refuse 'invalid' \"$($i.FullName) is a link with no target\" }",
175
+ " if (-not [IO.Path]::IsPathRooted($t)) { $t = [IO.Path]::Combine([IO.Path]::GetDirectoryName($i.FullName), $t) }",
176
+ " if (-not (Test-Path -LiteralPath $t)) { Refuse 'not_found' \"$($p.path) links to $t, which is not there\" }",
177
+ " $i = Get-Item -LiteralPath $t -Force",
178
+ " }",
179
+ " $i",
180
+ "}",
181
+ "# Windows PowerShell 5.1's Split-Path takes -Parent with -Path alone, never a literal path: .NET's own instead.",
182
+ "function Parent($path) { [IO.Path]::GetDirectoryName($path) }",
183
+ "try {",
184
+ " switch ($p.op) {",
185
+ " 'read' {",
186
+ " if (Test-Path -LiteralPath $p.path -PathType Container) { Refuse 'is_dir' \"$($p.path) is a folder\" }",
187
+ " $f = [IO.File]::Open($p.path, 'Open', 'Read', 'ReadWrite')",
188
+ " try {",
189
+ " $size = $f.Length",
190
+ " if ($p.offset -gt $size) { $p.offset = $size }",
191
+ " [void]$f.Seek([int64]$p.offset, 'Begin')",
192
+ " $buf = New-Object byte[] ([int][Math]::Max(0, [Math]::Min([int64]$p.length, $size - [int64]$p.offset)))",
193
+ " $n = 0",
194
+ " while ($n -lt $buf.Length) { $r = $f.Read($buf, $n, $buf.Length - $n); if ($r -le 0) { break }; $n += $r }",
195
+ " } finally { $f.Close() }",
196
+ " Say @{ data = [Convert]::ToBase64String($buf, 0, $n); size = $size }",
197
+ " }",
198
+ " 'write' {",
199
+ " if (Test-Path -LiteralPath $p.path -PathType Container) { Refuse 'is_dir' \"$($p.path) is a folder\" }",
200
+ " $dir = Parent $p.path",
201
+ " if ($dir -and -not (Test-Path -LiteralPath $dir -PathType Container)) {",
202
+ " if ($p.parents) { [void](New-Item -ItemType Directory -Force -Path $dir) } else { Refuse 'not_found' \"no folder $dir\" }",
203
+ " }",
204
+ " # Assigned in each branch: an if expression's value is unrolled, so an empty byte array would come out $null.",
205
+ " if ($p.staged) { $bytes = [IO.File]::ReadAllBytes($p.staged) } else { $bytes = [Convert]::FromBase64String($p.data) }",
206
+ " if ($null -ne $p.offset -or $p.append) {",
207
+ " $f = [IO.File]::Open($p.path, 'OpenOrCreate', 'Write', 'Read')",
208
+ " try { if ($p.append) { [void]$f.Seek(0, 'End') } else { [void]$f.Seek([int64]$p.offset, 'Begin') }; $f.Write($bytes, 0, $bytes.Length); $size = $f.Length } finally { $f.Close() }",
209
+ " } else { [IO.File]::WriteAllBytes($p.path, $bytes); $size = $bytes.Length }",
210
+ " if ($p.staged) { Remove-Item -LiteralPath $p.staged -Force }",
211
+ " Say @{ size = [int64]$size }",
212
+ " }",
213
+ " 'stat' { $i = Get-Item -LiteralPath $p.path -Force; if ($p.follow) { $i = Follow $i }; Say (StatOf $i) }",
214
+ " 'list' {",
215
+ " if (-not (Test-Path -LiteralPath $p.path -PathType Container)) {",
216
+ " if (Test-Path -LiteralPath $p.path) { Refuse 'not_dir' \"$($p.path) is not a folder\" } else { Refuse 'not_found' \"no folder $($p.path)\" }",
217
+ " }",
218
+ " $all = New-Object System.Collections.ArrayList",
219
+ " $limit = [int]$p.offset + [int]$p.max + 1",
220
+ " function Walk($dir, $level) {",
221
+ " foreach ($i in (Get-ChildItem -LiteralPath $dir -Force | Sort-Object Name)) {",
222
+ " if ($all.Count -ge $limit) { return }",
223
+ " $o = StatOf $i; $o.path = $i.FullName; [void]$all.Add($o)",
224
+ " if ($i.PSIsContainer -and -not $i.LinkType -and $level -lt $p.depth) { Walk $i.FullName ($level + 1) }",
225
+ " }",
226
+ " }",
227
+ " Walk $p.path 1",
228
+ " $page = @($all | Select-Object -Skip ([int]$p.offset) -First ([int]$p.max))",
229
+ " Say @{ entries = $page; truncated = ($all.Count -gt [int]$p.offset + [int]$p.max) }",
230
+ " }",
231
+ " 'mkdir' {",
232
+ " if (Test-Path -LiteralPath $p.path) {",
233
+ " if ($p.parents -and (Test-Path -LiteralPath $p.path -PathType Container)) { Say @{}; break }",
234
+ " Refuse 'exists' \"$($p.path) is there already\"",
235
+ " }",
236
+ " $dir = Parent $p.path",
237
+ " if ($dir -and -not $p.parents -and -not (Test-Path -LiteralPath $dir -PathType Container)) { Refuse 'not_found' \"no folder $dir\" }",
238
+ " [void](New-Item -ItemType Directory -Force -Path $p.path)",
239
+ " Say @{}",
240
+ " }",
241
+ " 'move' {",
242
+ " if (-not (Test-Path -LiteralPath $p.from)) { Refuse 'not_found' \"no $($p.from)\" }",
243
+ " # As rename(2), from and to naming one file is no removal: the same path moves nothing, and a name that differs in",
244
+ " # case alone, on a folder that reads names without case (so no other entry has to's own name), is renamed by way",
245
+ " # of a name of its own, since Windows PowerShell refuses a move onto the same file.",
246
+ " $fromFull = [IO.Path]::GetFullPath($p.from); $toFull = [IO.Path]::GetFullPath($p.to)",
247
+ " if ($fromFull -ceq $toFull) { Say @{}; break }",
248
+ " if ($fromFull -ieq $toFull) {",
249
+ " $leaf = [IO.Path]::GetFileName($toFull)",
250
+ " if (@(Get-ChildItem -LiteralPath (Parent $toFull) -Force | Where-Object { $_.Name -ceq $leaf }).Count -eq 0) {",
251
+ " $via = \"$fromFull.agentrun-move-$([guid]::NewGuid().ToString('N'))\"",
252
+ " Move-Item -LiteralPath $p.from -Destination $via",
253
+ " Move-Item -LiteralPath $via -Destination $p.to",
254
+ " Say @{}; break",
255
+ " }",
256
+ " }",
257
+ " if (-not (Test-Path -LiteralPath $p.to)) { Move-Item -LiteralPath $p.from -Destination $p.to; Say @{}; break }",
258
+ " if (-not $p.overwrite) { Refuse 'exists' \"$($p.to) is there already\" }",
259
+ " # As rename(2): a file replaces a file, a folder an empty folder, at to itself. Move-Item onto a folder would move",
260
+ " # into it, so what is at to is checked, and set aside under a name of its own until the move is done: a move that",
261
+ " # fails (a source another program holds) puts it back, so a failed move leaves to as it was.",
262
+ " $s = Get-Item -LiteralPath $p.from -Force; $d = Get-Item -LiteralPath $p.to -Force",
263
+ " $sDir = $s.PSIsContainer -and -not $s.LinkType; $dDir = $d.PSIsContainer -and -not $d.LinkType",
264
+ " if ($dDir -and -not $sDir) { Refuse 'is_dir' \"$($p.to) is a folder\" }",
265
+ " if ($sDir -and -not $dDir) { Refuse 'not_dir' \"$($p.to) is not a folder\" }",
266
+ " if ($dDir -and @(Get-ChildItem -LiteralPath $p.to -Force).Count -gt 0) { Refuse 'exists' \"$($p.to) is a folder that is not empty\" }",
267
+ " $aside = \"$toFull.agentrun-replaced-$([guid]::NewGuid().ToString('N'))\"",
268
+ " Move-Item -LiteralPath $p.to -Destination $aside",
269
+ " try { Move-Item -LiteralPath $p.from -Destination $p.to }",
270
+ " catch { Move-Item -LiteralPath $aside -Destination $p.to; throw }",
271
+ " # The move is done; an old file another program still holds open stays under its aside name until it is let go.",
272
+ " Remove-Item -LiteralPath $aside -Force -Recurse -ErrorAction SilentlyContinue",
273
+ " Say @{}",
274
+ " }",
275
+ " 'remove' {",
276
+ " if (-not (Test-Path -LiteralPath $p.path)) { Refuse 'not_found' \"no $($p.path)\" }",
277
+ " $i = Get-Item -LiteralPath $p.path -Force",
278
+ " if ($i.PSIsContainer -and -not $i.LinkType -and -not $p.recursive -and @(Get-ChildItem -LiteralPath $p.path -Force).Count -gt 0) { Refuse 'invalid' \"$($p.path) is a folder that is not empty: remove it with recursive\" }",
279
+ " Remove-Item -LiteralPath $p.path -Force -Recurse:([bool]$p.recursive)",
280
+ " Say @{}",
281
+ " }",
282
+ " default { Refuse 'unsupported' \"$($p.op) is not a files method\" }",
283
+ " }",
284
+ "} catch {",
285
+ " $e = $_.Exception",
286
+ " # A .NET method's error (a file Open, WriteAllBytes) reaches here wrapped in PowerShell's MethodInvocationException:",
287
+ " # its code is the error inside.",
288
+ " while ($e.InnerException -and $e.GetType().Name -match 'MethodInvocation|TargetInvocation') { $e = $e.InnerException }",
289
+ " $kind = switch -regex ($e.GetType().Name) { 'NotFound' { 'not_found' } 'UnauthorizedAccess|Security' { 'denied' } 'PathTooLong' { 'limit' } default { 'invalid' } }",
290
+ " Refuse $kind $e.Message",
291
+ "}",
292
+ ].join("\n");
293
+ /** The labels file written, as each desktop's shell does it: its text base64 in the command, never quoted into it. */
294
+ function labelsWriteCommand(profile, text) {
295
+ const b64 = Buffer.from(text, "utf8").toString("base64");
296
+ if (profile.os === "windows") {
297
+ return [
298
+ `$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}'))`,
299
+ `$p = ${psQuote(profile.labels)}`,
300
+ "[void](New-Item -ItemType Directory -Force -Path ([IO.Path]::GetDirectoryName($p)))",
301
+ "[IO.File]::WriteAllText(\"$p.part\", $t); Move-Item -LiteralPath \"$p.part\" -Destination $p -Force",
302
+ ].join("\n");
303
+ }
304
+ const dir = profile.labels.slice(0, profile.labels.lastIndexOf("/"));
305
+ return `mkdir -p ${shQuote(dir)} && printf '%s' ${shQuote(text)} > ${shQuote(`${profile.labels}.part`)} && mv -f ${shQuote(`${profile.labels}.part`)} ${shQuote(profile.labels)}`;
306
+ }
307
+ /** The labels file read: its text, or exit 3 when there is none. */
308
+ function labelsReadCommand(profile) {
309
+ if (profile.os === "windows")
310
+ return `$p = ${psQuote(profile.labels)}; if (Test-Path -LiteralPath $p) { [Console]::Out.Write([IO.File]::ReadAllText($p)) } else { exit 3 }`;
311
+ return `[ -f ${shQuote(profile.labels)} ] && cat ${shQuote(profile.labels)} || exit 3`;
312
+ }
313
+ /**
314
+ * Who the computer's programs run as, as uid:gid: on Windows 0:0 for a member of the Administrators group (it can do
315
+ * anything a root can), else its account's relative id twice; on macOS what id says.
316
+ */
317
+ function userCommand(profile) {
318
+ if (profile.os === "windows") {
319
+ return [
320
+ "$i = [Security.Principal.WindowsIdentity]::GetCurrent()",
321
+ "$admin = ([Security.Principal.WindowsPrincipal]$i).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
322
+ "$rid = $i.User.Value.Split('-')[-1]",
323
+ "if ($admin) { [Console]::Out.Write('0:0') } else { [Console]::Out.Write(\"${rid}:${rid}\") }",
324
+ ].join("; ");
325
+ }
326
+ return 'printf "%s:%s" "$(id -u)" "$(id -g)"';
327
+ }
328
+ /**
329
+ * Orgo's Windows and macOS desktops: see the module's header. A spec's image is "windows" or "macos", the one this
330
+ * provider was built for; cpus and memoryMb are Orgo's sizes; the network is open.
331
+ */
332
+ export class OrgoDesktopProvider {
333
+ id = "orgo";
334
+ version = VERSION;
335
+ #rest;
336
+ #workspaceId;
337
+ #profile;
338
+ #maxLifetimeMs;
339
+ #timeouts;
340
+ #daemonVersion;
341
+ /**
342
+ * Where the pointer is on each computer, as far as this provider moved it, shared by every client of that computer:
343
+ * the run's input moves it, and the live view's own client (daemonWatch) draws the cursor there.
344
+ */
345
+ #pointers = new Map();
346
+ #ledger;
347
+ /** Each computer's extend in flight, by id: the next waits for it, so two never read the same old deadline. */
348
+ #extending = new Map();
349
+ /** Each agent's computer's attach or detach in flight, by id: the next waits for it, so two never overlap here. */
350
+ #owning = new Map();
351
+ constructor({ os, apiKey, workspaceId, apiUrl = ORGO_API_URL, fetch, maxLifetimeMs = MAX_LIFETIME_MS, timeouts = {}, daemonVersion = VERSION, ledger = orgoMemoryLedger() }) {
352
+ if (os !== "windows" && os !== "macos")
353
+ throw new Error(`os is "windows" or "macos" for an Orgo desktop Orgo's API answers, not ${JSON.stringify(os)}`);
354
+ if (typeof apiKey !== "string" || apiKey === "")
355
+ throw new Error("options.apiKey, an Orgo API key, is required");
356
+ if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId))
357
+ throw new Error("options.workspaceId, the Orgo workspace this deployment's computers live in, is required");
358
+ let url;
359
+ try {
360
+ url = new URL(apiUrl);
361
+ }
362
+ catch {
363
+ throw new Error("options.apiUrl is not a URL");
364
+ }
365
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "")
366
+ throw new Error("options.apiUrl must be https, with no credentials in it: the key goes to it");
367
+ if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > MAX_LIFETIME_MS)
368
+ throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 720 h (${MAX_LIFETIME_MS} ms)`);
369
+ const merged = { ...DEFAULTS, ...timeouts };
370
+ for (const [key, value] of Object.entries(merged)) {
371
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2 ** 31 - 1)
372
+ throw new Error(`timeouts.${key} must be a whole number of ms above 0`);
373
+ }
374
+ this.#rest = orgoRest({ apiKey, apiUrl: url.href, ...(fetch ? { fetch } : {}) });
375
+ this.#workspaceId = workspaceId;
376
+ this.#profile = PROFILES[os];
377
+ this.#maxLifetimeMs = maxLifetimeMs;
378
+ this.#timeouts = merged;
379
+ this.#daemonVersion = daemonVersion;
380
+ this.#ledger = ledger;
381
+ }
382
+ /** A client of the computer, opened: its screen read, its hello this provider's own version, or a refusal in words. */
383
+ async #open(ref, signal) {
384
+ let pointer = this.#pointers.get(ref.id);
385
+ if (pointer === undefined)
386
+ this.#pointers.set(ref.id, (pointer = {}));
387
+ const client = new OrgoDesktopClient(this.#rest, ref.id, this.#profile, this.#workspaceId, this.#timeouts.requestMs, pointer);
388
+ const hello = await client.open(this.#daemonVersion, signal);
389
+ if (!hello.ok) {
390
+ client.close();
391
+ return fail(hello.error.code, `the screen of ${ref.name} could not be read: ${hello.error.message}`);
392
+ }
393
+ if (hello.value.version !== this.version) {
394
+ client.close();
395
+ return fail("refused", `hello: the daemon reports version ${hello.value.version}, expected ${this.version}`);
396
+ }
397
+ return ok({ client, hello: hello.value });
398
+ }
399
+ /**
400
+ * daemon none: the provider answers every method over Orgo's API. lifetime janitor: the deadline is in the name, and
401
+ * on Windows Orgo's end (whole hours) is the backstop. network open alone, never read back from inside: Orgo has no
402
+ * egress control and no computerd runs here to probe from inside. release delete. persistence on Windows alone: an
403
+ * agent's computer detaches to its disk (Orgo's stop keeps files, apps and settings, not memory), so it does not
404
+ * resume where it was. A Mac takes no owner: Orgo stops none, so it cannot be detached.
405
+ */
406
+ capabilities() {
407
+ return {
408
+ kind: "desktop",
409
+ lifetime: "janitor",
410
+ network: ["open"],
411
+ networkReadBack: false,
412
+ isolation: "vm",
413
+ os: this.#profile.os,
414
+ daemon: "none",
415
+ groups: [...this.#profile.groups],
416
+ maxLifetimeMs: this.#maxLifetimeMs,
417
+ release: ["delete"],
418
+ ...(this.#profile.os === "windows" ? { persistence: { keepsState: true, resume: false } } : {}),
419
+ };
420
+ }
421
+ check(spec) {
422
+ const refusals = [];
423
+ const refuse = (field, message) => refusals.push({ field, message });
424
+ const given = (typeof spec === "object" && spec !== null ? spec : {});
425
+ const { image, network, cpus, memoryMb, labels, mount } = given;
426
+ const profile = this.#profile;
427
+ if (image !== profile.image)
428
+ refuse("image", `this Orgo provider makes ${profile.os} desktops: its image is ${JSON.stringify(profile.image)}`);
429
+ refusals.push(...checkTenure(given, this.capabilities(), `Orgo ${profile.os}`));
430
+ refusals.push(...checkGpu(given.gpu, this.capabilities()));
431
+ if (network !== "open")
432
+ refuse("network", NETWORK);
433
+ if (memoryMb !== undefined && !profile.ram.some((gb) => gb * 1024 === memoryMb))
434
+ refuse("memoryMb", `memoryMb is one of Orgo's ${profile.os} sizes: ${profile.ram.map((gb) => gb * 1024).join(", ")}`);
435
+ if (cpus !== undefined && !(profile.cpus && CPUS.includes(cpus)))
436
+ refuse("cpus", profile.cpus ? "cpus is one of Orgo's sizes: 0.5, 1, 2, 4 or 6" : `an Orgo ${profile.os} computer's cpus are its host's: leave cpus unset`);
437
+ if (labels !== undefined) {
438
+ const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
439
+ const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
440
+ if (bad)
441
+ refuse("labels", bad);
442
+ }
443
+ refusals.push(...checkMount(mount, []));
444
+ for (const [field, value] of Object.entries(given)) {
445
+ if (SPEC_FIELDS.has(field) || field === "mount" || field === "owner" || value === undefined)
446
+ continue;
447
+ if (field === "user")
448
+ refuse(field, `an Orgo ${profile.os} computer's programs run as Orgo's own user; a spec cannot name another`);
449
+ else if (field === "workdir")
450
+ refuse(field, `an Orgo ${profile.os} computer's programs start where Orgo starts them; a spec cannot name a folder`);
451
+ else if (field === "pids")
452
+ refuse(field, "Orgo offers no pids limit to set; leave pids unset");
453
+ else
454
+ refuse(field, `an Orgo ${profile.os} computer does not support ${field}`);
455
+ }
456
+ return refusals;
457
+ }
458
+ async create(spec, { signal } = {}) {
459
+ const refusals = this.check(spec);
460
+ if (refusals.length > 0)
461
+ return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
462
+ if (signal?.aborted)
463
+ return fail("aborted", "create was aborted before Orgo was called");
464
+ const profile = this.#profile;
465
+ // An agent's own computer outlives the run: no deadline, no Orgo end, the owner in its name and its labels.
466
+ const owner = spec.owner;
467
+ const labels = { ...spec.labels, ...(owner === undefined ? {} : ownerLabels(owner)) };
468
+ const now = Date.now();
469
+ const deadline = owner === undefined ? new Date(now + runLifetimeMs(spec)).toISOString() : NO_DEADLINE;
470
+ const maxDeadline = owner === undefined ? new Date(now + this.#maxLifetimeMs).toISOString() : NO_DEADLINE;
471
+ const name = orgoName(labels, randomBytes(6).toString("hex"), owner === undefined ? new Date(deadline) : undefined, owner);
472
+ if (name.length > NAME_MAX || nameParts(name) === undefined)
473
+ return fail("invalid", `the name ${name} is not one Orgo holds: at most ${NAME_MAX} of letters, digits and dashes`);
474
+ const ram = spec.memoryMb === undefined ? profile.ram[0] : spec.memoryMb / 1024;
475
+ const cpu = profile.cpus ? (spec.cpus ?? CPU_FOR_RAM[ram]) : undefined;
476
+ const body = {
477
+ workspace_id: this.#workspaceId,
478
+ name,
479
+ os: profile.os,
480
+ ram,
481
+ ...(cpu === undefined ? {} : { cpu }),
482
+ // Orgo's end, the vendor's backstop where it has one: whole hours, deleting the computer. The janitor ends it on time.
483
+ ...(profile.ends && owner === undefined ? { ends_in_hours: Math.max(1, Math.ceil(runLifetimeMs(spec) / HOUR)) } : {}),
484
+ };
485
+ const made = await this.#rest.request("POST", "/computers", { body, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
486
+ if (!made.ok) {
487
+ // A create Orgo refused (a 4xx) made nothing. One whose answer never came may have: it goes by its name.
488
+ if (["invalid", "denied", "limit", "not_found", "refused"].includes(made.error.code))
489
+ return made;
490
+ return fail(made.error.code, `${made.error.message}${await this.#deleteNamed(name)}`);
491
+ }
492
+ const id = made.value?.id;
493
+ if (typeof id !== "string" || !COMPUTER_ID.test(id))
494
+ return fail("vendor", `Orgo's create answered no computer id${await this.#deleteNamed(name)}`);
495
+ const ref = { id, name };
496
+ // An agent's computer's labels go in the ledger at once, so list finds it as the agent's whatever happens next.
497
+ if (owner !== undefined) {
498
+ const kept = await this.#keep({ id, labels });
499
+ if (!kept.ok)
500
+ return this.#abandon(ref, kept.error);
501
+ }
502
+ const file = { name, labels, deadline, maxDeadline, image: profile.image, ...(cpu === undefined ? {} : { cpus: cpu }), memoryMb: ram * 1024 };
503
+ const prepared = await this.#prepare(ref, made.value.status, file, signal);
504
+ if (signal?.aborted)
505
+ return this.#abandon(ref, { code: "aborted", message: "create was aborted" });
506
+ if (prepared.ok)
507
+ return ok(ref);
508
+ return this.#abandon(ref, prepared.error);
509
+ }
510
+ /** Running, answering a command, its labels file written, then its screen and the hello a connection answers. */
511
+ async #prepare(ref, status, file, signal) {
512
+ const running = status === "running" ? ok(undefined) : await this.#untilRunning(ref, signal);
513
+ if (!running.ok)
514
+ return running;
515
+ const until = Date.now() + this.#timeouts.createMs;
516
+ // A computer Orgo reads running may not take a command yet (503 "Computer not ready" while it boots): tried until it does.
517
+ for (;;) {
518
+ const written = await this.#shell(ref.id, labelsWriteCommand(this.#profile, JSON.stringify(file)), this.#timeouts.execMs, signal);
519
+ if (written.ok && written.value.exitCode === 0)
520
+ break;
521
+ if (signal?.aborted)
522
+ return fail("aborted", "create was aborted while the computer started");
523
+ if (written.ok)
524
+ return fail("refused", `writing the labels file ${this.#profile.labels} in ${ref.name} failed (exit ${written.value.exitCode}): ${(written.value.stderr || written.value.stdout).trim().slice(0, 300)}`);
525
+ if (Date.now() >= until)
526
+ return fail(written.error.code, `${ref.name} did not take a command within ${seconds(this.#timeouts.createMs)}: ${written.error.message}`);
527
+ await pause(this.#timeouts.pollMs, signal);
528
+ }
529
+ const opened = await this.#open(ref, signal);
530
+ if (!opened.ok)
531
+ return opened;
532
+ opened.value.client.close();
533
+ return ok(undefined);
534
+ }
535
+ /** Polls Orgo until it reads the computer running, within createMs. */
536
+ async #untilRunning(ref, signal) {
537
+ const until = Date.now() + this.#timeouts.createMs;
538
+ let last = "unread";
539
+ for (;;) {
540
+ const read = await this.#get(ref.id, signal);
541
+ if (!read.ok)
542
+ return read;
543
+ last = read.value.status;
544
+ if (last === "running")
545
+ return ok(undefined);
546
+ if (!RUNNING.has(last))
547
+ return fail("vendor", `Orgo read ${ref.name} ${last}, not running`);
548
+ if (Date.now() >= until)
549
+ return fail("timeout", `Orgo did not read ${ref.name} running within ${seconds(this.#timeouts.createMs)}; it last read ${last}`);
550
+ await pause(this.#timeouts.pollMs, signal);
551
+ if (signal?.aborted)
552
+ return fail("aborted", "create was aborted while Orgo made the computer");
553
+ }
554
+ }
555
+ /** One command of the provider's own through Orgo's bash call (PowerShell on Windows), read as Ran. */
556
+ #shell(id, command, timeoutMs, signal) {
557
+ return bashCall(this.#rest, id, command, timeoutMs, signal);
558
+ }
559
+ /** The labels file, read in the computer. */
560
+ async #readLabels(ref, signal) {
561
+ const read = await this.#shell(ref.id, labelsReadCommand(this.#profile), this.#timeouts.execMs, signal);
562
+ if (!read.ok)
563
+ return read;
564
+ if (read.value.exitCode !== 0)
565
+ return fail("refused", `${ref.name} has no labels file ${this.#profile.labels} to read (exit ${read.value.exitCode})`);
566
+ const file = labelsOf(read.value.stdout, this.#profile.labels);
567
+ return typeof file === "string" ? fail("refused", `${ref.name}: ${file}`) : ok(file);
568
+ }
569
+ async #writeLabels(ref, file, signal) {
570
+ const written = await this.#shell(ref.id, labelsWriteCommand(this.#profile, JSON.stringify(file)), this.#timeouts.execMs, signal);
571
+ if (!written.ok)
572
+ return written;
573
+ return written.value.exitCode === 0 ? ok(undefined) : fail("refused", `writing ${this.#profile.labels} in ${ref.name} failed (exit ${written.value.exitCode})`);
574
+ }
575
+ /** Orgo's record of a computer; not_found once Orgo no longer has it. */
576
+ async #get(id, signal) {
577
+ const read = await this.#rest.request("GET", `/computers/${encodeURIComponent(id)}`, { timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
578
+ if (!read.ok)
579
+ return read;
580
+ if (typeof read.value?.name !== "string" || typeof read.value.status !== "string")
581
+ return fail("vendor", `Orgo's record of ${id} has no name or status`);
582
+ return ok(read.value);
583
+ }
584
+ /**
585
+ * Whether Orgo's record is a computer of this provider: its name's shape, in this workspace, of this os where Orgo
586
+ * says it (a workspace's listing may not).
587
+ */
588
+ #ours(record, name) {
589
+ return (nameParts(record.name) !== undefined &&
590
+ (record.workspace_id ?? record.project_id) === this.#workspaceId &&
591
+ (name === undefined || sameComputer(record.name, name)) &&
592
+ record.status !== "deleted" &&
593
+ (record.os === undefined || record.os === this.#profile.os));
594
+ }
595
+ async #own(ref, signal) {
596
+ const read = await this.#get(ref.id, signal);
597
+ if (!read.ok)
598
+ return read.error.code === "not_found" ? fail("not_found", `no Orgo computer is ${ref.name} (${ref.id})`) : read;
599
+ if (!this.#ours(read.value, ref.name))
600
+ return fail("not_found", `no Orgo ${this.#profile.os} computer of this provider named ${ref.name} has the id ${ref.id}`);
601
+ return read;
602
+ }
603
+ /** Deletes a computer create gives up on, and waits until Orgo no longer has it. Never signalled: it outlives an abort. */
604
+ async #abandon(ref, error) {
605
+ const deleted = await this.#delete(ref);
606
+ return fail(error.code, `the computer ${ref.name} ${deleted.ok ? "was deleted" : `could not be deleted (${deleted.error.message})`}: ${error.message}`);
607
+ }
608
+ /** Every computer of this workspace with the name create gave: for a create whose answer never came. Best effort, in words. */
609
+ async #deleteNamed(name) {
610
+ const listed = await this.#desktops();
611
+ if (!listed.ok)
612
+ return `; a computer named ${name} may be left (${listed.error.message})`;
613
+ const found = listed.value.filter((one) => one.name === name);
614
+ if (found.length === 0)
615
+ return `; no computer named ${name} is in the workspace`;
616
+ const said = [];
617
+ for (const one of found) {
618
+ const deleted = await this.#delete({ id: one.id, name });
619
+ said.push(deleted.ok ? `${one.id} was deleted` : `${one.id} may be left (${deleted.error.message})`);
620
+ }
621
+ return `; the computer named ${name}: ${said.join("; ")}`;
622
+ }
623
+ /** An agent's computer's ledger entry, put; a ledger that fails is a failure in words. */
624
+ async #keep(entry) {
625
+ try {
626
+ await this.#ledger.put(entry);
627
+ return ok(undefined);
628
+ }
629
+ catch (error) {
630
+ return vendorFail("orgo", `the ledger of agents' computers could not be written: ${error instanceof Error ? error.message : String(error)}`);
631
+ }
632
+ }
633
+ /** Every agent's computer's ledger entry, by id. */
634
+ async #entries() {
635
+ try {
636
+ return ok(new Map((await this.#ledger.list()).map((entry) => [entry.id, entry])));
637
+ }
638
+ catch (error) {
639
+ return vendorFail("orgo", `the ledger of agents' computers could not be read: ${error instanceof Error ? error.message : String(error)}`);
640
+ }
641
+ }
642
+ /** A deleted computer's ledger entry, gone; best effort, since the computer is gone whatever the ledger says. */
643
+ async #forget(id) {
644
+ try {
645
+ await this.#ledger.remove(id);
646
+ }
647
+ catch {
648
+ // A stale entry names a computer Orgo no longer has: list never shows it.
649
+ }
650
+ }
651
+ /**
652
+ * An agent's computer deleted under `claim` (ReleaseContext): its entry taken first, only while it carries exactly the
653
+ * claim's run and epoch and no attach or detach holds it (takeEntry, only), so a claim that made it and lost it never
654
+ * deletes it from under a later claim. A delete Orgo refused lets the entry go again; one Orgo took forgot it already.
655
+ */
656
+ #claimedDelete(ref, name, claim, signal) {
657
+ const owner = nameParts(name)?.owner;
658
+ if (owner === undefined)
659
+ 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`));
660
+ return inTurn(this.#owning, ref.id, async () => {
661
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being deleted", { only: true });
662
+ if (!taken.ok)
663
+ return taken;
664
+ const deleted = await this.#delete(ref, signal);
665
+ if (deleted.ok)
666
+ return deleted;
667
+ const left = await this.#entries();
668
+ return left.ok && !left.value.has(ref.id) ? deleted : andSettled(deleted, await settleEntry(this.#ledger, ref, taken.value));
669
+ });
670
+ }
671
+ /** DELETE, tried again while Orgo answers 409 computer_waking, then the wait until Orgo no longer has the computer. */
672
+ async #delete(ref, signal) {
673
+ const { requestMs, pollMs, goneMs } = this.#timeouts;
674
+ for (let tries = 1;; tries++) {
675
+ const deleted = await this.#rest.request("DELETE", `/computers/${encodeURIComponent(ref.id)}`, { timeoutMs: requestMs });
676
+ if (deleted.ok || deleted.error.code === "not_found")
677
+ break;
678
+ const { status, orgoCode } = deleted;
679
+ // A Mac Orgo manages is given back, never deleted: said in Orgo's words, and left.
680
+ if (status !== 409 || orgoCode !== "computer_waking" || tries >= DELETE_TRIES)
681
+ return deleted;
682
+ await pause(pollMs);
683
+ }
684
+ await this.#forget(ref.id);
685
+ const until = Date.now() + goneMs;
686
+ let last = "unread";
687
+ for (;;) {
688
+ const read = await this.#get(ref.id, signal);
689
+ if (!read.ok && read.error.code === "not_found")
690
+ return ok(undefined);
691
+ if (read.ok && read.value.status === "deleted")
692
+ return ok(undefined);
693
+ if (!read.ok && read.error.code !== "timeout")
694
+ return fail(read.error.code, `release of ${ref.name}: reading it back failed (${read.error.message})`);
695
+ last = read.ok ? read.value.status : read.error.message;
696
+ if (Date.now() >= until)
697
+ return fail("timeout", `${ref.name} was still there ${seconds(goneMs)} after its delete; Orgo last read ${last}`);
698
+ await pause(pollMs, signal);
699
+ if (signal?.aborted)
700
+ return fail("aborted", `the wait for ${ref.name} to go was aborted; Orgo last read ${last}`);
701
+ }
702
+ }
703
+ /** The workspace's computers, as Orgo lists them. */
704
+ async #desktops(signal) {
705
+ const read = await this.#rest.request("GET", `/workspaces/${encodeURIComponent(this.#workspaceId)}`, { timeoutMs: this.#timeouts.listMs, ...(signal ? { signal } : {}) });
706
+ if (!read.ok)
707
+ return read;
708
+ const desktops = read.value?.desktops;
709
+ if (!Array.isArray(desktops))
710
+ return fail("vendor", `Orgo's workspace ${this.#workspaceId} lists no computers array`);
711
+ return ok(desktops.filter((one) => typeof one?.id === "string" && typeof one.name === "string").map((one) => ({ ...one, workspace_id: this.#workspaceId })));
712
+ }
713
+ /** The live view: screen.watch on a connection of the watch's own (daemonWatch), the client's polled screenshots. */
714
+ watch(ref, handlers, options) {
715
+ return daemonWatch(this, ref, handlers, options);
716
+ }
717
+ /**
718
+ * A connection to a computer Orgo reads running; one that is not is refused, never woken by a first call. Once open,
719
+ * the connection is the claim's own, on a computer its run holds: a call it makes reaches Orgo even if Orgo has since
720
+ * suspended the computer, and waking it for the run's own input is what the run asked. The no-wake rule is for what
721
+ * reads computers no run holds (list, the janitor, attach), which never wake one.
722
+ */
723
+ async connect(ref) {
724
+ const problem = refProblem(ref);
725
+ if (problem)
726
+ return fail("invalid", problem);
727
+ const found = await this.#own(ref);
728
+ if (!found.ok)
729
+ return found;
730
+ if (found.value.status !== "running")
731
+ return fail("refused", `${ref.name} is ${found.value.status}, not running: a connection's first call would wake it`);
732
+ const opened = await this.#open(ref);
733
+ if (!opened.ok)
734
+ return opened;
735
+ const { client, hello } = opened.value;
736
+ return ok({ client, hello, close: async () => client.close() });
737
+ }
738
+ async attach(ref, { signal, claim } = {}) {
739
+ const given = (typeof ref === "object" && ref !== null ? ref : {});
740
+ if ((given.id === undefined) === (given.labels === undefined))
741
+ return fail("invalid", "attach takes { id } or { labels }, one of them");
742
+ if (given.id !== undefined) {
743
+ if (typeof given.id !== "string" || !COMPUTER_ID.test(given.id))
744
+ return fail("invalid", `${String(given.id)} is not an Orgo computer id`);
745
+ const read = await this.#get(given.id, signal);
746
+ if (!read.ok)
747
+ return read.error.code === "not_found" ? fail("not_found", `no Orgo computer has the id ${given.id}`) : read;
748
+ if (!this.#ours(read.value))
749
+ return fail("not_found", `no Orgo ${this.#profile.os} computer of this provider has the id ${given.id}`);
750
+ return this.#attached(read.value, signal, claim);
751
+ }
752
+ const problem = filterProblem(given.labels);
753
+ if (problem)
754
+ return fail("invalid", problem);
755
+ const labels = given.labels;
756
+ if (Object.keys(labels).length === 0)
757
+ return fail("invalid", "attach by labels needs at least one label");
758
+ const listed = await this.list(labels, { signal });
759
+ if (!listed.ok)
760
+ return listed;
761
+ const words = JSON.stringify(labels);
762
+ if (listed.value.length === 0)
763
+ return fail("not_found", `no Orgo computer has the labels ${words}`);
764
+ if (listed.value.length > 1)
765
+ return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
766
+ const found = await this.#own(listed.value[0].ref, signal);
767
+ if (!found.ok)
768
+ return found;
769
+ return this.#attached(found.value, signal, claim);
770
+ }
771
+ /**
772
+ * The check of a computer attach did not make: its labels file held to its name, who its programs run as, and the
773
+ * hello its screen answers. A computer that does not run is refused: reading it would wake it. An agent's own computer
774
+ * is the exception: attaching it is asking for it. Its ledger entry is taken for the claim first, busy (takeEntry),
775
+ * before anything is done to the computer, so a claim of the same run below the epoch it carries is fenced however the
776
+ * two attaches interleave; one that was detached is then started (#wake); under a claim it carries the claim's run and
777
+ * epoch from then on; and it is marked held in the ledger last (settleEntry), by this attach alone, while the entry is
778
+ * still the one it holds. An attach that started it and then fails stops it again, as it was found (#putBack). This
779
+ * process's attaches and detaches of one agent's computer are taken in turn; another process's are refused while this
780
+ * one holds the entry, so no attach or detach stops another's computer under it.
781
+ */
782
+ async #attached(record, signal, claim) {
783
+ const ref = { id: record.id, name: record.name };
784
+ const parts = nameParts(record.name);
785
+ if (parts.owner === undefined) {
786
+ if (claim !== undefined)
787
+ return fail("refused", claimProblem(ref.name, undefined, undefined, claim));
788
+ if (record.status !== "running")
789
+ return fail("refused", `${ref.name} is ${record.status}: its labels file and screen are read from inside, and a read would wake it`);
790
+ return this.#checked(record, parts, signal);
791
+ }
792
+ const owner = parts.owner;
793
+ return inTurn(this.#owning, ref.id, async (waited) => {
794
+ // Read again after waiting: the attach or detach before this one may have started or stopped it.
795
+ const now = waited ? await this.#own(ref, signal) : ok(record);
796
+ if (!now.ok)
797
+ return now;
798
+ const taken = await takeEntry(this.#ledger, ref, owner, claim, "being attached");
799
+ if (!taken.ok)
800
+ return taken;
801
+ const lease = taken.value;
802
+ const woke = now.value.status !== "running";
803
+ const attached = await this.#started(now.value, parts, lease, woke, signal, claim);
804
+ if (!attached.ok && woke)
805
+ return this.#putBack(ref, lease, attached.error);
806
+ // Marked held (no longer detached) once attached; a failed attach that woke nothing leaves it as it was.
807
+ return andSettled(attached, await settleEntry(this.#ledger, ref, lease, attached.ok ? ({ detachedAt: _held, ...held }) => held : undefined));
808
+ });
809
+ }
810
+ /**
811
+ * An agent's own computer, its entry taken: started when it was not running; under a claim, its labels file carries
812
+ * the claim's run and epoch from now on, as the ledger does; then checked.
813
+ */
814
+ async #started(record, parts, lease, woke, signal, claim) {
815
+ const ref = { id: record.id, name: record.name };
816
+ if (woke) {
817
+ const woken = await this.#wake(ref, record.status, signal);
818
+ if (!woken.ok)
819
+ return woken;
820
+ }
821
+ if (claim !== undefined) {
822
+ // Its labels file is written under the claim only while this attach still holds the entry, however long the wake took.
823
+ if (woke) {
824
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being attached");
825
+ if (!renewed.ok)
826
+ return renewed;
827
+ }
828
+ const read = await this.#readLabels(ref, signal);
829
+ if (!read.ok)
830
+ return read;
831
+ const written = await this.#writeLabels(ref, { ...read.value, labels: lease.entry.labels }, signal);
832
+ if (!written.ok)
833
+ return written;
834
+ }
835
+ return this.#checked(record, parts, signal);
836
+ }
837
+ /**
838
+ * An agent's own computer this attach started, stopped again once the attach fails, best effort, as release detach
839
+ * stops it, so it is left as it was found; its ledger entry still says when it was detached (takeEntry kept it). One
840
+ * another claim has taken since is that claim's, and runs on. Never signalled: it outlives an abort.
841
+ */
842
+ async #putBack(ref, lease, error) {
843
+ const renewed = await renewEntry(this.#ledger, ref, lease, "being put back to sleep by an attach that failed");
844
+ if (!renewed.ok)
845
+ return fail(error.code, `${error.message}; ${ref.name} runs on, not stopped again: ${renewed.error.message}`);
846
+ const stopped = await this.#stop(ref);
847
+ const failed = fail(error.code, `${error.message}; ${ref.name}, which this attach started, ${stopped.ok ? "was stopped again, as it was found" : `could not be stopped again (${stopped.error.message})`}`);
848
+ return andSettled(failed, await settleEntry(this.#ledger, ref, lease));
849
+ }
850
+ /** The labels file held to the name, who its programs run as, and the hello its screen answers: #attached's check. */
851
+ async #checked(record, parts, signal) {
852
+ const ref = { id: record.id, name: record.name };
853
+ const file = await this.#readLabels(ref, signal);
854
+ if (!file.ok)
855
+ return file;
856
+ const found = [];
857
+ const { labels } = file.value;
858
+ if (typeof file.value.name !== "string" || !sameComputer(file.value.name, record.name))
859
+ found.push(`name: Orgo's is ${record.name}, the labels file's ${show(file.value.name)}`);
860
+ if ((parts.owner ?? "") !== ownerHashOfLabels(labels))
861
+ found.push(`owner: the name's owner hash ${show(parts.owner)} is not the labels file's owner ${show(labels[OWNER_LABEL])}`);
862
+ const run = labels[RUN_LABEL];
863
+ // An agent's own computer is no run's: its name carries no run or epoch, whatever run made it.
864
+ if (parts.owner === undefined && (parts.run ?? "") !== (typeof run === "string" && run !== "" ? runHash(run) : ""))
865
+ found.push(`run: the name's run hash ${show(parts.run)} is not the labels file's run ${show(run)}`);
866
+ if (parts.owner === undefined && (parts.epoch ?? "") !== (labels[EPOCH_LABEL] ?? ""))
867
+ found.push(`epoch: the name says ${show(parts.epoch)}, the labels file ${show(labels[EPOCH_LABEL])}`);
868
+ if (file.value.image !== this.#profile.image)
869
+ found.push(`image: the labels file says ${show(file.value.image)}, not ${this.#profile.image}`);
870
+ const deadline = parts.owner === undefined ? new Date(file.value.deadline) : undefined;
871
+ if (deadline !== undefined && Number.isNaN(deadline.getTime()))
872
+ found.push(`deadline: the labels file reads ${show(file.value.deadline)}, not a time`);
873
+ if (parts.owner !== undefined && file.value.deadline !== NO_DEADLINE)
874
+ found.push(`deadline: an agent's own computer has none, and the labels file reads ${show(file.value.deadline)}`);
875
+ if (found.length > 0)
876
+ 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("; ")}`);
877
+ const user = await this.#shell(ref.id, userCommand(this.#profile), this.#timeouts.execMs, signal);
878
+ if (!user.ok)
879
+ return user;
880
+ const ids = /^(\d+):(\d+)$/.exec(user.value.stdout.trim());
881
+ if (user.value.exitCode !== 0 || ids === null)
882
+ return fail("vendor", `who ${ref.name}'s programs run as could not be read (exit ${user.value.exitCode}): ${user.value.stdout.trim().slice(0, 100)}`);
883
+ const opened = await this.#open(ref, signal);
884
+ if (!opened.ok)
885
+ return opened;
886
+ opened.value.client.close();
887
+ return ok({
888
+ ...ref,
889
+ spec: {
890
+ image: file.value.image,
891
+ user: `${ids[1]}:${ids[2]}`,
892
+ network: "open",
893
+ ...(file.value.cpus === undefined ? {} : { cpus: file.value.cpus }),
894
+ ...(file.value.memoryMb === undefined ? {} : { memoryMb: file.value.memoryMb }),
895
+ ...(deadline === undefined ? {} : { deadline }),
896
+ kind: "desktop",
897
+ ...ownerReadBack(labels),
898
+ },
899
+ });
900
+ }
901
+ /**
902
+ * An agent's own computer that a detach stopped, started again for its attach: Orgo's start (a Windows computer comes
903
+ * back from its disk), then running, then taking a command. A status no start brings back is refused in words.
904
+ */
905
+ async #wake(ref, status, signal) {
906
+ if (status === "frozen" || status === "stopped") {
907
+ const started = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/start`, { body: {}, timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
908
+ if (!started.ok)
909
+ return fail(started.error.code, `${ref.name} could not be started for its attach: ${started.error.message}`);
910
+ }
911
+ else if (!RUNNING.has(status)) {
912
+ return fail("refused", `${ref.name} is ${status}: no start brings it back`);
913
+ }
914
+ const running = await this.#untilRunning(ref, signal);
915
+ if (!running.ok)
916
+ return running;
917
+ return this.#untilAnswering(ref, signal);
918
+ }
919
+ /** Orgo's bash call taking a command, tried within createMs: a computer Orgo reads running may still be booting. */
920
+ async #untilAnswering(ref, signal) {
921
+ const until = Date.now() + this.#timeouts.createMs;
922
+ for (;;) {
923
+ const ran = await this.#shell(ref.id, "exit 0", this.#timeouts.execMs, signal);
924
+ if (ran.ok)
925
+ return ok(undefined);
926
+ if (signal?.aborted)
927
+ return fail("aborted", `the wait for ${ref.name} to take a command was aborted`);
928
+ if (Date.now() >= until)
929
+ return fail(ran.error.code, `${ref.name} did not take a command within ${seconds(this.#timeouts.createMs)}: ${ran.error.message}`);
930
+ await pause(this.#timeouts.pollMs, signal);
931
+ }
932
+ }
933
+ /**
934
+ * Every computer of this provider in the workspace that carries all of these labels. The run and the epoch are read
935
+ * from the name, with nothing run in a computer, so a stopped one is listed too; any other label is read from the
936
+ * labels file of a running computer (a stopped one is not woken, so it proves no such label and is left out).
937
+ */
938
+ async list(labels, { signal } = {}) {
939
+ const problem = filterProblem(labels);
940
+ if (problem)
941
+ return fail("invalid", problem);
942
+ const listed = await this.#desktops(signal);
943
+ if (!listed.ok)
944
+ return listed;
945
+ const others = Object.keys(labels).filter((key) => key !== RUN_LABEL && key !== EPOCH_LABEL);
946
+ const ours = listed.value.filter((record) => nameParts(record.name) !== undefined && this.#ours(record));
947
+ // An agent's computers' labels are the ledger's: read once, only when the workspace holds one.
948
+ const owned = ours.some((record) => nameParts(record.name)?.owner !== undefined) ? await this.#entries() : ok(new Map());
949
+ if (!owned.ok)
950
+ return owned;
951
+ const infos = [];
952
+ for (const record of ours) {
953
+ const parts = nameParts(record.name);
954
+ const ref = { id: record.id, name: record.name };
955
+ const state = RUNNING.has(record.status) ? "running" : "stopped";
956
+ // An agent's computer: every label from its ledger entry, with nothing run inside, whatever its state; no deadline.
957
+ if (parts.owner !== undefined) {
958
+ const view = ownedListing(owned.value.get(record.id), labels);
959
+ if (view === undefined)
960
+ continue;
961
+ infos.push({ ref, deadline: undefined, state, network: "open", ...view });
962
+ continue;
963
+ }
964
+ if (labels[OWNER_LABEL] !== undefined || labels[OWNER_SERVER_LABEL] !== undefined)
965
+ continue;
966
+ if (labels[RUN_LABEL] !== undefined && parts.run !== runHash(labels[RUN_LABEL]))
967
+ continue;
968
+ if (labels[EPOCH_LABEL] !== undefined && parts.epoch !== labels[EPOCH_LABEL])
969
+ continue;
970
+ // The name keeps the run's hash, not the run: listed with no run to match, the hash is given, as the Linux
971
+ // desktop's list gives it, so a caller (serve's janitor) can still tell whose run a computer is.
972
+ let read = {
973
+ ...(labels[RUN_LABEL] !== undefined ? { [RUN_LABEL]: labels[RUN_LABEL] } : parts.run !== undefined ? { [RUN_HASH_LABEL]: parts.run } : {}),
974
+ ...(parts.epoch !== undefined ? { [EPOCH_LABEL]: parts.epoch } : {}),
975
+ };
976
+ // The janitor's deadline is the name's, which every name this provider makes carries.
977
+ const deadline = parts.deadline;
978
+ if (others.length > 0) {
979
+ if (record.status !== "running")
980
+ continue;
981
+ const file = await this.#readLabels(ref, signal);
982
+ if (!file.ok || !others.every((key) => file.value.labels[key] === labels[key]))
983
+ continue;
984
+ read = { ...file.value.labels };
985
+ }
986
+ infos.push({ ref, labels: read, deadline, state, network: "open" });
987
+ }
988
+ return ok(infos);
989
+ }
990
+ /** Settings' test: one read of the workspace's computers (list with no label to read from inside), which makes nothing. */
991
+ async testConnection(context = {}) {
992
+ return listTested("Orgo", await this.list({}, context));
993
+ }
994
+ /** open: what Orgo gives, the one network here; never read from inside, and a change is refused. */
995
+ async network(ref, policy, { signal } = {}) {
996
+ const problem = refProblem(ref);
997
+ if (problem)
998
+ return fail("invalid", problem);
999
+ if (policy !== undefined && policy !== "open")
1000
+ return fail("refused", NETWORK);
1001
+ const found = await this.#own(ref, signal);
1002
+ if (!found.ok)
1003
+ return found;
1004
+ return ok("open");
1005
+ }
1006
+ /**
1007
+ * delete: idempotent, a computer Orgo no longer has is done; it waits until Orgo no longer has it. detach, for an
1008
+ * agent's own Windows computer alone: Orgo's stop archives its disk, and it reads frozen. A Mac has no agent's
1009
+ * computer to detach (Orgo's stop takes none). No stop: a run's computer is deleted. Either forgets the pointer.
1010
+ */
1011
+ async release(ref, how, { signal, claim } = {}) {
1012
+ const problem = refProblem(ref);
1013
+ if (problem)
1014
+ return fail("invalid", problem);
1015
+ if (how !== "stop" && how !== "delete" && how !== "detach")
1016
+ return fail("invalid", `release is "stop", "delete" or "detach", not ${String(how)}`);
1017
+ if (how === "stop")
1018
+ return fail("unsupported", "an Orgo computer has no stop that this provider declares: release it with delete, or detach an agent's own");
1019
+ const read = await this.#get(ref.id);
1020
+ if (!read.ok)
1021
+ return read.error.code === "not_found" && how === "delete" ? ok(undefined) : read;
1022
+ if (read.value.status === "deleted")
1023
+ return how === "delete" ? ok(undefined) : fail("not_found", `${ref.name} is deleted: there is nothing to detach`);
1024
+ if (!this.#ours(read.value, ref.name))
1025
+ return fail("not_found", `no Orgo ${this.#profile.os} computer of this provider is ${ref.name} (${ref.id}), so it is left as it is`);
1026
+ if (how === "delete")
1027
+ return this.#dropPointer(ref, await (claim === undefined ? this.#delete(ref, signal) : this.#claimedDelete(ref, read.value.name, claim, signal)));
1028
+ const owner = nameParts(read.value.name)?.owner;
1029
+ if (owner === undefined)
1030
+ return fail("refused", `${ref.name} is a run's computer, not an agent's own: it is deleted at its release, never detached`);
1031
+ return this.#dropPointer(ref, await this.#detach(ref, owner, read.value.status, signal));
1032
+ }
1033
+ /** A released computer's pointer is no longer where any client moved it: the next client starts with none. */
1034
+ #dropPointer(ref, released) {
1035
+ if (released.ok)
1036
+ this.#pointers.delete(ref.id);
1037
+ return released;
1038
+ }
1039
+ /**
1040
+ * An agent's own Windows computer kept with its disk: stopped, read back frozen, and marked detached in the ledger. In
1041
+ * turn with this process's attaches, and holding the ledger entry from before the stop until it is marked detached
1042
+ * (takeEntry, settleEntry), so no attach starts it meanwhile and an attach under way refuses this detach. `status`:
1043
+ * Orgo's, read before the turn; `owner`: the name's owner hash.
1044
+ */
1045
+ async #detach(ref, owner, status, signal) {
1046
+ return inTurn(this.#owning, ref.id, async (waited) => {
1047
+ const taken = await takeEntry(this.#ledger, ref, owner, undefined, "being detached");
1048
+ if (!taken.ok)
1049
+ return taken;
1050
+ const now = waited ? await this.#own(ref, signal) : ok({ status });
1051
+ const stopped = !now.ok ? now : now.value.status === "frozen" ? ok(undefined) : await this.#stop(ref, signal);
1052
+ return andSettled(stopped, await settleEntry(this.#ledger, ref, taken.value, stopped.ok ? (entry) => ({ ...entry, detachedAt: entry.detachedAt ?? new Date().toISOString() }) : undefined));
1053
+ });
1054
+ }
1055
+ /** Orgo's stop, the computer's disk archived, then the wait until Orgo reads it frozen. */
1056
+ async #stop(ref, signal) {
1057
+ const stopped = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/stop`, { timeoutMs: this.#timeouts.createMs, ...(signal ? { signal } : {}) });
1058
+ if (!stopped.ok)
1059
+ return fail(stopped.error.code, `${ref.name} could not be stopped for its agent: ${stopped.error.message}`);
1060
+ const until = Date.now() + this.#timeouts.goneMs;
1061
+ for (;;) {
1062
+ const read = await this.#get(ref.id, signal);
1063
+ if (!read.ok)
1064
+ return read;
1065
+ if (read.value.status === "frozen")
1066
+ return ok(undefined);
1067
+ if (Date.now() >= until)
1068
+ return fail("timeout", `${ref.name} was not stopped ${seconds(this.#timeouts.goneMs)} after its stop; Orgo last read ${read.value.status}`);
1069
+ await pause(this.#timeouts.pollMs, signal);
1070
+ if (signal?.aborted)
1071
+ return fail("aborted", `the wait for ${ref.name} to stop was aborted`);
1072
+ }
1073
+ }
1074
+ /**
1075
+ * Moves the deadline to now + ttlMs, never earlier and never past the most the labels file holds: Orgo's end first
1076
+ * where there is one, in whole hours with an Idempotency-Key, then the name's, then the labels file. A computer's
1077
+ * extends are taken in turn.
1078
+ */
1079
+ extend(ref, ttlMs, context = {}) {
1080
+ return inTurn(this.#extending, typeof ref?.id === "string" ? ref.id : "", () => this.#extend(ref, ttlMs, context));
1081
+ }
1082
+ async #extend(ref, ttlMs, { signal } = {}) {
1083
+ const problem = refProblem(ref);
1084
+ if (problem)
1085
+ return fail("invalid", problem);
1086
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0)
1087
+ return fail("invalid", "extend takes ttlMs, a whole number of milliseconds above 0");
1088
+ const found = await this.#own(ref, signal);
1089
+ if (!found.ok)
1090
+ return found;
1091
+ if (nameParts(found.value.name)?.owner !== undefined)
1092
+ return fail("refused", `${ref.name} is an agent's own computer: it has no deadline to move`);
1093
+ if (found.value.status !== "running")
1094
+ return fail("refused", `${ref.name} is ${found.value.status}, not running`);
1095
+ const file = await this.#readLabels(ref, signal);
1096
+ if (!file.ok)
1097
+ return file;
1098
+ // The most it may live is read off Orgo's own record, its creation time and this provider's longest lifetime: a
1099
+ // program in a Windows or macOS desktop can write the labels file, so its maxDeadline may lower that, never raise it.
1100
+ const created = typeof found.value.created_at === "string" ? Date.parse(found.value.created_at) : Number.NaN;
1101
+ if (Number.isNaN(created))
1102
+ return fail("vendor", `Orgo's record of ${ref.name} says no creation time (created_at ${show(found.value.created_at)}), so the most it may live is not known; nothing moved`);
1103
+ const filed = Date.parse(file.value.maxDeadline);
1104
+ const most = Number.isNaN(filed) ? created + this.#maxLifetimeMs : Math.min(created + this.#maxLifetimeMs, filed);
1105
+ const current = Date.parse(file.value.deadline);
1106
+ const target = Date.now() + ttlMs;
1107
+ if (target > most)
1108
+ return fail("limit", `${new Date(target).toISOString()} is past ${new Date(most).toISOString()}, the most this computer may live`);
1109
+ if (target < current)
1110
+ return fail("refused", `${new Date(target).toISOString()} is earlier than ${ref.name}'s deadline ${file.value.deadline}: an extend never moves it earlier; nothing moved`);
1111
+ if (target === current)
1112
+ return ok({ deadline: new Date(current) });
1113
+ const end = typeof found.value.ends_at === "string" ? Date.parse(found.value.ends_at) : Number.NaN;
1114
+ if (this.#profile.ends && !Number.isNaN(end) && end < target) {
1115
+ const hours = Math.ceil((target - end) / HOUR);
1116
+ const moved = await this.#rest.request("POST", `/computers/${encodeURIComponent(ref.id)}/extend`, { body: { hours }, headers: { "idempotency-key": randomUUID() }, timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
1117
+ if (!moved.ok)
1118
+ return fail(moved.error.code, `Orgo's end did not move, so nothing did: ${moved.error.message}`);
1119
+ }
1120
+ const took = new Date(Math.ceil(target / 1000) * 1000);
1121
+ const parts = nameParts(found.value.name);
1122
+ const name = parts.deadline !== undefined && parts.deadline.getTime() >= took.getTime() ? found.value.name : withDeadline(parts.stable, took);
1123
+ if (name !== found.value.name) {
1124
+ const renamed = await this.#rest.request("PATCH", `/computers/${encodeURIComponent(ref.id)}`, { body: { name }, timeoutMs: this.#timeouts.requestMs, ...(signal ? { signal } : {}) });
1125
+ if (!renamed.ok)
1126
+ return fail(renamed.error.code, `the deadline in ${found.value.name} did not move: ${renamed.error.message}`);
1127
+ }
1128
+ const written = await this.#writeLabels(ref, { ...file.value, name, deadline: took.toISOString() }, signal);
1129
+ if (!written.ok)
1130
+ return fail(written.error.code, `the janitor's deadline moved to ${took.toISOString()}, and the labels file did not: ${written.error.message}`);
1131
+ return ok({ deadline: took });
1132
+ }
1133
+ }
1134
+ /** Orgo's bash call (PowerShell on Windows), bounded, read as Ran whichever shape it answers. */
1135
+ async function bashCall(rest, id, command, timeoutMs, signal) {
1136
+ const timeout = Math.min(BASH_MAX_S, Math.max(1, Math.ceil(timeoutMs / 1000)));
1137
+ const ran = await rest.request("POST", `/computers/${encodeURIComponent(id)}/bash`, {
1138
+ body: { command, timeout },
1139
+ timeoutMs: timeout * 1000 + BASH_PROXY_MS,
1140
+ ...(signal ? { signal } : {}),
1141
+ });
1142
+ if (!ran.ok)
1143
+ return ran;
1144
+ const { exit_code: exitCode, output, stdout, stderr, error } = ran.value ?? {};
1145
+ if (typeof exitCode !== "number")
1146
+ return fail("vendor", `Orgo's bash call answered no exit code (${JSON.stringify(ran.value)?.slice(0, 200)})`);
1147
+ const split = typeof stdout === "string" || typeof stderr === "string";
1148
+ // Windows says a timeout in words (exit 124, error "timeout"); Linux, and by the same agent macOS, with exit -1.
1149
+ const timedOut = error === "timeout" || exitCode === -1;
1150
+ return ok({
1151
+ exitCode: timedOut ? null : exitCode,
1152
+ stdout: split ? (typeof stdout === "string" ? stdout : "") : typeof output === "string" ? output : "",
1153
+ stderr: split && typeof stderr === "string" ? stderr : "",
1154
+ timedOut,
1155
+ });
1156
+ }
1157
+ const refuse = (code, message) => fail(code, message);
1158
+ const DAEMON_KINDS = new Set(["not_found", "invalid", "timeout", "aborted", "denied", "limit", "unsupported", "exists", "not_dir", "is_dir"]);
1159
+ /** The key names of Orgo's key call, from the protocol's (KEYS): Linux's X keysyms, which Windows reads as written but for pageup and pagedown. */
1160
+ function orgoKey(key, os) {
1161
+ const named = {
1162
+ enter: "Return",
1163
+ tab: "Tab",
1164
+ space: "space",
1165
+ backspace: "BackSpace",
1166
+ delete: "Delete",
1167
+ escape: "Escape",
1168
+ insert: "Insert",
1169
+ up: "Up",
1170
+ down: "Down",
1171
+ left: "Left",
1172
+ right: "Right",
1173
+ home: "Home",
1174
+ end: "End",
1175
+ pageup: os === "windows" ? "pageup" : "Page_Up",
1176
+ pagedown: os === "windows" ? "pagedown" : "Page_Down",
1177
+ shift: "shift",
1178
+ ctrl: "ctrl",
1179
+ alt: "alt",
1180
+ super: "super",
1181
+ capslock: os === "windows" ? "capslock" : "Caps_Lock",
1182
+ };
1183
+ if (Object.hasOwn(named, key))
1184
+ return named[key];
1185
+ if (/^f([1-9]|1[0-2])$/.test(key))
1186
+ return key.toUpperCase();
1187
+ // "+" joins a combination in Orgo's key call, so it cannot be one of its keys.
1188
+ if (key.length === 1 && key !== "+")
1189
+ return key;
1190
+ return undefined;
1191
+ }
1192
+ /**
1193
+ * The in-process client of one Orgo Windows or macOS desktop: each protocol method is one or more calls to Orgo's API.
1194
+ * Input batches run one at a time; a cancel stops a batch at the action it is on.
1195
+ */
1196
+ export class OrgoDesktopClient {
1197
+ rest;
1198
+ computer;
1199
+ profile;
1200
+ workspaceId;
1201
+ requestMs;
1202
+ pointer;
1203
+ #closed = false;
1204
+ #hello;
1205
+ /** The screen's size, the input space. */
1206
+ #size = [0, 0];
1207
+ /**
1208
+ * Where the pointer is, as far as the provider moved it; undefined until it has. The computer's, shared with every
1209
+ * other client of it (the provider's #pointers): the live view's client draws the cursor where the run's moved it.
1210
+ */
1211
+ get #pointer() {
1212
+ return this.pointer.at;
1213
+ }
1214
+ set #pointer(at) {
1215
+ this.pointer.at = at;
1216
+ }
1217
+ #held;
1218
+ #watchHeld;
1219
+ #watch = {
1220
+ seq: 0,
1221
+ digest: "",
1222
+ read: Number.NEGATIVE_INFINITY,
1223
+ };
1224
+ /** A press down asked for and not yet released: Orgo has no separate press, so up makes it one click or drag. */
1225
+ #pressed;
1226
+ #watching = Promise.resolve();
1227
+ #inputs = Promise.resolve();
1228
+ #closing = new AbortController();
1229
+ constructor(rest, computer, profile, workspaceId, requestMs, pointer = {}) {
1230
+ this.rest = rest;
1231
+ this.computer = computer;
1232
+ this.profile = profile;
1233
+ this.workspaceId = workspaceId;
1234
+ this.requestMs = requestMs;
1235
+ this.pointer = pointer;
1236
+ }
1237
+ /** The screen's size from a first screenshot, then the hello this client answers. */
1238
+ async open(version, signal) {
1239
+ const shot = await this.#screenshot(1, signal);
1240
+ if (!shot.ok)
1241
+ return shot;
1242
+ this.#size = [shot.value.width, shot.value.height];
1243
+ this.#hello = { protocol: PROTOCOL_VERSION, version, os: this.profile.os, kind: "desktop", arch: this.profile.arch, groups: [...this.profile.groups] };
1244
+ return ok(this.#hello);
1245
+ }
1246
+ close() {
1247
+ if (this.#closed)
1248
+ return;
1249
+ this.#closed = true;
1250
+ this.#held = undefined;
1251
+ this.#watchHeld = undefined;
1252
+ this.#closing.abort();
1253
+ }
1254
+ #either(signal) {
1255
+ return signal ? AbortSignal.any([signal, this.#closing.signal]) : this.#closing.signal;
1256
+ }
1257
+ async call(method, params, options = {}) {
1258
+ if (this.#closed)
1259
+ return fail("gone", "the connection to the computer is closed");
1260
+ if (options.signal?.aborted)
1261
+ return fail("aborted", `${method} was aborted`);
1262
+ return (await this.#answer(method, (params ?? {}), this.#either(options.signal)));
1263
+ }
1264
+ async #answer(method, params, signal) {
1265
+ switch (method) {
1266
+ case "hello":
1267
+ return ok(this.#hello);
1268
+ case "ping":
1269
+ return ok({});
1270
+ case "screen.shot":
1271
+ return this.#shot(params.region, signal);
1272
+ case "screen.read":
1273
+ return this.#read(params.id, params.offset);
1274
+ case "screen.watch": {
1275
+ const turn = this.#watching.then(() => this.#screenWatch(params, signal));
1276
+ this.#watching = turn.catch(() => undefined);
1277
+ return turn;
1278
+ }
1279
+ case "input.actions":
1280
+ return this.#inTurn(params.actions, signal);
1281
+ case "exec.run":
1282
+ return this.#exec(params, signal);
1283
+ }
1284
+ const group = method.split(".")[0];
1285
+ if (group === "files" && this.profile.groups.includes("files"))
1286
+ return this.#files(method.slice("files.".length), params, signal);
1287
+ if (["files", "tar"].includes(group))
1288
+ return refuse("unsupported", `${method}: an Orgo ${this.profile.os} computer offers ${this.profile.groups.includes("files") ? "files.read, write, stat, list, mkdir, move and remove, and no tar" : "no files methods: use exec"}`);
1289
+ if (group === "process")
1290
+ return refuse("unsupported", `${method}: Orgo runs a command and waits for it, so an Orgo ${this.profile.os} computer offers no processes`);
1291
+ if (method === "deadline.extend")
1292
+ return refuse("unsupported", "deadline.extend: no computerd runs in an Orgo Windows or macOS computer; extend it through the provider");
1293
+ return refuse("unsupported", `${method} is not a method an Orgo ${this.profile.os} computer answers`);
1294
+ }
1295
+ // --- screen --------------------------------------------------------------------------------------------------
1296
+ /** One screenshot, PNG, at scale (0 to 1]: its bytes and its size. */
1297
+ async #screenshot(scale, signal) {
1298
+ const query = `response_format=base64&format=png${scale < 1 ? `&scale=${scale.toFixed(4)}` : ""}`;
1299
+ const shot = await this.rest.request("GET", `/computers/${encodeURIComponent(this.computer)}/screenshot?${query}`, {
1300
+ timeoutMs: this.requestMs,
1301
+ ...(signal ? { signal } : {}),
1302
+ });
1303
+ if (!shot.ok)
1304
+ return shot;
1305
+ const { image, width, height } = shot.value ?? {};
1306
+ if (typeof image !== "string" || image === "")
1307
+ return fail("vendor", "Orgo's screenshot answered no image");
1308
+ const bytes = Buffer.from(image.replace(/^data:[^,]*,/, ""), "base64");
1309
+ if (Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0)
1310
+ return ok({ bytes, width: width, height: height });
1311
+ try {
1312
+ const png = readPng(bytes);
1313
+ return ok({ bytes, width: png.width, height: png.height });
1314
+ }
1315
+ catch (error) {
1316
+ return fail("vendor", `Orgo's screenshot is not a PNG this client reads: ${error instanceof Error ? error.message : String(error)}`);
1317
+ }
1318
+ }
1319
+ async #shot(region, signal) {
1320
+ const shot = await this.#screenshot(1, signal);
1321
+ if (!shot.ok)
1322
+ return shot;
1323
+ const { width, height } = shot.value;
1324
+ this.#size = [width, height];
1325
+ let bytes = shot.value.bytes;
1326
+ let rect = [0, 0, width, height];
1327
+ if (region !== undefined) {
1328
+ const r = region;
1329
+ if (!(Array.isArray(r) && r.length === 4 && r.every((v) => Number.isSafeInteger(v)) && r[0] >= 0 && r[1] >= 0 && r[2] > 0 && r[3] > 0 && r[0] + r[2] <= width && r[1] + r[3] <= height)) {
1330
+ return refuse("invalid", `region ${show(region)} is not [x, y, w, h] inside the ${width}x${height} screen`);
1331
+ }
1332
+ rect = r;
1333
+ const png = readPng(bytes);
1334
+ const rgba = Buffer.alloc(width * height * 4);
1335
+ for (let y = rect[1]; y < rect[1] + rect[3]; y++) {
1336
+ for (let x = rect[0]; x < rect[0] + rect[2]; x++) {
1337
+ const [red, green, blue] = png.rgb(x, y);
1338
+ rgba.set([red, green, blue, 255], (y * width + x) * 4);
1339
+ }
1340
+ }
1341
+ bytes = await encodePng(rgba, width, rect);
1342
+ // close() may have run while the region was deflating: hold nothing for a closed connection.
1343
+ if (this.#closed)
1344
+ return fail("gone", "the connection to the computer is closed");
1345
+ }
1346
+ const id = randomBytes(6).toString("hex");
1347
+ this.#held = { id, bytes };
1348
+ const data = bytes.subarray(0, MAX_CHUNK_BYTES);
1349
+ return ok({ id, size: bytes.length, data: data.toString("base64"), eof: data.length === bytes.length, width: rect[2], height: rect[3], scale: 1, ...(this.#pointer ? { cursor: [...this.#pointer] } : {}) });
1350
+ }
1351
+ /**
1352
+ * screen.watch: the live view's frames, PNG, read about once a second at most (WATCH_POLL_MS), scaled by Orgo to
1353
+ * maxWidth; width and height stay the screen's, the input space. An older ack gets the newest frame at once, one at
1354
+ * the newest waits for a change until waitMs passes.
1355
+ */
1356
+ async #screenWatch(params, signal) {
1357
+ const { after, waitMs = 2_000, maxWidth = 1_280, quality = 60 } = params;
1358
+ const whole = (v, lo, hi) => Number.isSafeInteger(v) && v >= lo && v <= hi;
1359
+ if (!whole(after, 0, Number.MAX_SAFE_INTEGER))
1360
+ return refuse("invalid", "screen.watch takes after: the seq of the last frame the caller has, 0 for none");
1361
+ if (!whole(waitMs, 0, 10_000))
1362
+ return refuse("invalid", `waitMs ${show(waitMs)} is outside 0 to 10000`);
1363
+ if (!whole(maxWidth, 1, 16_384))
1364
+ return refuse("invalid", `maxWidth ${show(maxWidth)} is outside 1 to 16384`);
1365
+ if (!whole(quality, 1, 100))
1366
+ return refuse("invalid", `quality ${show(quality)} is outside 1 to 100`);
1367
+ const watch = this.#watch;
1368
+ if (after > watch.seq)
1369
+ return refuse("invalid", `after ${after} is past the newest frame, ${watch.seq}`);
1370
+ if (after < watch.seq && watch.frame)
1371
+ return ok(this.#frameAnswer());
1372
+ const aborted = () => refuse("aborted", "screen.watch was aborted");
1373
+ const deadline = Date.now() + waitMs;
1374
+ for (;;) {
1375
+ const wait = watch.read + WATCH_POLL_MS - Date.now();
1376
+ if (wait > 0)
1377
+ await pause(wait, signal);
1378
+ if (signal.aborted || this.#closed)
1379
+ return aborted();
1380
+ watch.read = Date.now();
1381
+ const [width, height] = this.#size;
1382
+ const scale = width > maxWidth ? maxWidth / width : 1;
1383
+ const shot = await this.#screenshot(scale, signal);
1384
+ if (signal.aborted || this.#closed)
1385
+ return aborted();
1386
+ if (!shot.ok)
1387
+ return shot;
1388
+ // The cursor is part of what a frame shows: where this client moved the pointer is in the digest, so a move is a
1389
+ // new frame even when Orgo's screenshot leaves the cursor out.
1390
+ const cursor = this.#pointer === undefined ? undefined : [...this.#pointer];
1391
+ const digest = createHash("sha256").update(shot.value.bytes).update(`|${cursor?.join(",") ?? ""}`).digest("hex");
1392
+ if (watch.seq === 0 || digest !== watch.digest) {
1393
+ watch.seq += 1;
1394
+ watch.digest = digest;
1395
+ const full = scale < 1 ? [width, height] : [shot.value.width, shot.value.height];
1396
+ if (scale >= 1)
1397
+ this.#size = full;
1398
+ watch.frame = { bytes: shot.value.bytes, frameWidth: shot.value.width, frameHeight: shot.value.height, width: full[0], height: full[1], ...(cursor ? { cursor } : {}) };
1399
+ return ok(this.#frameAnswer());
1400
+ }
1401
+ const left = deadline - Date.now();
1402
+ if (left < WATCH_POLL_MS) {
1403
+ if (left > 0)
1404
+ await pause(left, signal);
1405
+ if (signal.aborted || this.#closed)
1406
+ return aborted();
1407
+ return ok({ seq: watch.seq, changed: false, width: this.#size[0], height: this.#size[1] });
1408
+ }
1409
+ }
1410
+ }
1411
+ #frameAnswer() {
1412
+ const { seq, frame } = this.#watch;
1413
+ const { bytes, frameWidth, frameHeight, width, height, cursor } = frame;
1414
+ const data = bytes.subarray(0, MAX_CHUNK_BYTES);
1415
+ const eof = data.length === bytes.length;
1416
+ const id = randomBytes(6).toString("hex");
1417
+ if (!eof)
1418
+ this.#watchHeld = { id, bytes };
1419
+ return { seq, changed: true, ...(eof ? {} : { id }), size: bytes.length, data: data.toString("base64"), eof, format: "png", frameWidth, frameHeight, width, height, ...(cursor ? { cursor } : {}) };
1420
+ }
1421
+ #read(id, offset) {
1422
+ const frame = this.#watchHeld !== undefined && this.#watchHeld.id === id;
1423
+ const held = frame ? this.#watchHeld : this.#held;
1424
+ if (held === undefined || held.id !== id)
1425
+ return refuse("not_found", `no shot ${show(id)} is held: take one with screen.shot`);
1426
+ if (!(Number.isSafeInteger(offset) && offset >= 0 && offset <= held.bytes.length))
1427
+ return refuse("invalid", `offset ${show(offset)} is not inside the shot's ${held.bytes.length} bytes`);
1428
+ const data = held.bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
1429
+ const eof = offset + data.length >= held.bytes.length;
1430
+ if (eof && frame)
1431
+ this.#watchHeld = undefined;
1432
+ else if (eof)
1433
+ this.#held = undefined;
1434
+ return ok({ data: data.toString("base64"), eof });
1435
+ }
1436
+ // --- input ---------------------------------------------------------------------------------------------------
1437
+ /**
1438
+ * The Orgo calls of one action with the pointer where it is, or why this desktop cannot do it: "unsupported" whatever
1439
+ * the pointer, so a batch is refused whole before any of it runs. down and up are the batch loop's (#actions).
1440
+ */
1441
+ #steps(action, pointer) {
1442
+ const windows = this.profile.windowsInput;
1443
+ const os = this.profile.os;
1444
+ const at = (point) => ({ x: Math.round(point[0]), y: Math.round(point[1]) });
1445
+ const modifiers = (keys) => {
1446
+ if (keys === undefined || keys.length === 0)
1447
+ return [];
1448
+ if (windows)
1449
+ return { kind: "unsupported", message: "Orgo's Windows click takes no keys held down" };
1450
+ const names = { ctrl: "ctrl", alt: "alt", shift: "shift", super: "super" };
1451
+ const bad = keys.find((key) => !Object.hasOwn(names, key));
1452
+ return bad === undefined ? keys.map((key) => names[key]) : { kind: "unsupported", message: `${show(bad)} is not a key Orgo's click holds down: ctrl, alt, shift or super` };
1453
+ };
1454
+ switch (action.type) {
1455
+ case "move":
1456
+ return [{ path: "mouse-move", body: at(action.at) }];
1457
+ case "click": {
1458
+ const point = action.at ?? pointer;
1459
+ if (point === undefined)
1460
+ return { kind: "invalid", message: "a click without at needs the pointer's place, and this connection has not moved it yet" };
1461
+ const button = action.button ?? "left";
1462
+ const count = action.count ?? 1;
1463
+ const held = modifiers(action.keys);
1464
+ if (!Array.isArray(held))
1465
+ return held;
1466
+ if (windows) {
1467
+ if (count === 3)
1468
+ return { kind: "unsupported", message: "Orgo's Windows click has no triple click" };
1469
+ return [{ path: "click", body: { ...at(point), button, ...(count === 2 ? { double: true } : {}) } }];
1470
+ }
1471
+ if (count === 2 && button !== "left")
1472
+ return { kind: "unsupported", message: "Orgo's double click is always the left button's" };
1473
+ if (held.length > 0 && count > 1)
1474
+ return { kind: "unsupported", message: "Orgo's click takes keys held down only on a single click" };
1475
+ return [{ path: "click", body: { ...at(point), button, ...(count === 2 ? { double: true } : count === 3 ? { repeat: 3 } : {}), ...(held.length > 0 ? { modifiers: held } : {}) } }];
1476
+ }
1477
+ case "drag": {
1478
+ if (action.path.length !== 2)
1479
+ return { kind: "unsupported", message: "Orgo's drag goes straight from one point to another: a path of 2 points" };
1480
+ if ((action.keys ?? []).length > 0)
1481
+ return { kind: "unsupported", message: "Orgo's drag takes no keys held down" };
1482
+ const button = action.button ?? "left";
1483
+ if (!windows && button !== "left")
1484
+ return { kind: "unsupported", message: `Orgo's drag on ${os} is always the left button's` };
1485
+ const [from, to] = action.path;
1486
+ return [{ path: "drag", body: { start_x: Math.round(from[0]), start_y: Math.round(from[1]), end_x: Math.round(to[0]), end_y: Math.round(to[1]), ...(windows ? { button } : {}) } }];
1487
+ }
1488
+ case "scroll": {
1489
+ if ((action.dx ?? 0) !== 0)
1490
+ return { kind: "unsupported", message: "Orgo scrolls up and down only, not sideways" };
1491
+ if ((action.keys ?? []).length > 0)
1492
+ return { kind: "unsupported", message: "Orgo's scroll takes no keys held down" };
1493
+ const dy = Math.round(action.dy ?? 0);
1494
+ if (dy === 0)
1495
+ return [];
1496
+ const point = action.at ?? pointer;
1497
+ const direction = dy > 0 ? "down" : "up";
1498
+ const steps = [];
1499
+ if (windows) {
1500
+ // Windows scrolls at the pointer, and takes no coordinates: the pointer goes there first.
1501
+ if (action.at !== undefined)
1502
+ steps.push({ path: "mouse-move", body: at(action.at) });
1503
+ for (let left = Math.abs(dy); left > 0; left -= SCROLL_MAX)
1504
+ steps.push({ path: "scroll", body: { direction, amount: Math.min(SCROLL_MAX, left) } });
1505
+ return steps;
1506
+ }
1507
+ if (point === undefined)
1508
+ return { kind: "invalid", message: "a scroll without at needs the pointer's place, and this connection has not moved it yet" };
1509
+ for (let left = Math.abs(dy); left > 0; left -= SCROLL_MAX)
1510
+ steps.push({ path: "scroll", body: { ...at(point), direction, amount: Math.min(SCROLL_MAX, left) } });
1511
+ return steps;
1512
+ }
1513
+ case "key": {
1514
+ const names = action.keys.map((key) => orgoKey(key, os));
1515
+ const bad = names.findIndex((name) => name === undefined);
1516
+ if (bad !== -1)
1517
+ return { kind: "unsupported", message: `${show(action.keys[bad])} is not a key Orgo's key call can press: "+" joins a combination there` };
1518
+ return Array.from({ length: action.repeat ?? 1 }, () => ({ path: "key", body: { key: names.join("+") } }));
1519
+ }
1520
+ case "type": {
1521
+ const steps = [];
1522
+ let chunk = "";
1523
+ for (const character of action.text) {
1524
+ if (Buffer.byteLength(chunk + character, "utf8") > this.profile.typeBytes) {
1525
+ steps.push({ path: "type", body: { text: chunk } });
1526
+ chunk = "";
1527
+ }
1528
+ chunk += character;
1529
+ }
1530
+ if (chunk !== "")
1531
+ steps.push({ path: "type", body: { text: chunk } });
1532
+ return steps;
1533
+ }
1534
+ case "wait":
1535
+ return [{ waitMs: action.ms }];
1536
+ case "down":
1537
+ if (!windows && (action.button ?? "left") !== "left")
1538
+ return { kind: "unsupported", message: `Orgo's drag on ${os}, which a down and its up become, is always the left button's` };
1539
+ return [];
1540
+ case "up":
1541
+ return [];
1542
+ case "hold":
1543
+ return { kind: "unsupported", message: "hold: Orgo's key call cannot keep a key down" };
1544
+ default:
1545
+ return { kind: "unsupported", message: `${action.type} is not an action an Orgo desktop takes` };
1546
+ }
1547
+ }
1548
+ /** The points an action names, to check against the screen before any runs. */
1549
+ static #pointsOf(action) {
1550
+ if ((action.type === "move" || action.type === "click" || action.type === "scroll") && action.at !== undefined)
1551
+ return [action.at];
1552
+ if (action.type === "drag")
1553
+ return action.path;
1554
+ return [];
1555
+ }
1556
+ /** A batch in its turn: batches run one at a time; a cancel while it waits answers at once with none of it run. */
1557
+ #inTurn(actions, signal) {
1558
+ const waitedOut = () => ok({ done: 0, failed: { index: 0, kind: "aborted", message: "action 0: the batch was aborted while it waited for the batch before it; none of it ran" } });
1559
+ let started = false;
1560
+ const turn = this.#inputs.then(() => {
1561
+ started = true;
1562
+ return signal.aborted ? waitedOut() : this.#actions(actions, signal);
1563
+ });
1564
+ this.#inputs = turn.catch(() => undefined);
1565
+ return new Promise((resolve, reject) => {
1566
+ const stop = () => {
1567
+ if (!started)
1568
+ resolve(waitedOut());
1569
+ };
1570
+ signal.addEventListener("abort", stop, { once: true });
1571
+ if (signal.aborted)
1572
+ stop();
1573
+ turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
1574
+ });
1575
+ }
1576
+ /** One call to Orgo's input API, bounded and cancelled with the batch. */
1577
+ #send(step, signal) {
1578
+ return this.rest.request("POST", `/computers/${encodeURIComponent(this.computer)}/${step.path}`, { body: step.body, timeoutMs: this.requestMs, signal });
1579
+ }
1580
+ /**
1581
+ * The press down asked for, released where the pointer is now: one click there when it has not moved, else one drag
1582
+ * from where it went down. Orgo has no separate press and release, so this is when the button goes down and up.
1583
+ */
1584
+ async #release(signal) {
1585
+ const pressed = this.#pressed;
1586
+ if (pressed === undefined)
1587
+ return ok(undefined);
1588
+ this.#pressed = undefined;
1589
+ const to = this.#pointer ?? pressed.at;
1590
+ const windows = this.profile.windowsInput;
1591
+ const [x, y] = [Math.round(to[0]), Math.round(to[1])];
1592
+ if (to[0] === pressed.at[0] && to[1] === pressed.at[1])
1593
+ return this.#send({ path: "click", body: { x, y, button: pressed.button } }, signal);
1594
+ return this.#send({ path: "drag", body: { start_x: Math.round(pressed.at[0]), start_y: Math.round(pressed.at[1]), end_x: x, end_y: y, ...(windows ? { button: pressed.button } : {}) } }, signal);
1595
+ }
1596
+ /**
1597
+ * The batch: checked whole first (its shape, keys and groups, then what Orgo's API cannot do), so a refused batch runs
1598
+ * nothing; then each action in order, its points held to the screen as it comes, so a batch that fails at action n
1599
+ * has done n. A press down is held in the client until its up (#release), across batches as the protocol says, and a
1600
+ * batch that fails releases it where the pointer is.
1601
+ */
1602
+ async #actions(actions, signal) {
1603
+ const refused = checkActions(actions, this.profile.groups, { pixelScroll: false });
1604
+ if (refused !== undefined)
1605
+ return ok({ done: 0, failed: refused });
1606
+ const list = actions;
1607
+ for (const [index, action] of list.entries()) {
1608
+ const steps = this.#steps(action, [0, 0]);
1609
+ if (!Array.isArray(steps) && steps.kind === "unsupported")
1610
+ return ok({ done: 0, failed: { index, kind: steps.kind, message: `action ${index}: ${steps.message}` } });
1611
+ }
1612
+ const failed = async (index, kind, message) => {
1613
+ if (this.#pressed !== undefined && !signal.aborted)
1614
+ await this.#release(signal);
1615
+ return ok({ done: index, failed: { index, kind, message: `action ${index}: ${message}` } });
1616
+ };
1617
+ // A cancelled batch lets go of a press it held: nothing is sent (the batch is aborted), and the next batch's up or
1618
+ // click never turns it into a click or drag the cancelled one asked for.
1619
+ const cancelled = (index) => {
1620
+ this.#pressed = undefined;
1621
+ return ok({ done: index, failed: { index, kind: "aborted", message: `action ${index}: the batch was aborted; actions ${index} on did not run` } });
1622
+ };
1623
+ const sendOrFail = async (index, step) => {
1624
+ const sent = await this.#send(step, signal);
1625
+ if (sent.ok)
1626
+ return undefined;
1627
+ if (signal.aborted)
1628
+ return cancelled(index);
1629
+ return failed(index, (DAEMON_KINDS.has(sent.error.code) ? sent.error.code : "invalid"), sent.error.message);
1630
+ };
1631
+ for (const [index, action] of list.entries()) {
1632
+ if (signal.aborted)
1633
+ return cancelled(index);
1634
+ const off = _a.#pointsOf(action).find((point) => point[0] < 0 || point[1] < 0 || point[0] >= this.#size[0] || point[1] >= this.#size[1]);
1635
+ if (off !== undefined)
1636
+ return failed(index, "invalid", `${show(off)} is off the ${this.#size[0]}x${this.#size[1]} screen`);
1637
+ if (action.type === "down" || action.type === "up" || (action.type === "move" && this.#pressed !== undefined)) {
1638
+ if (action.type === "move")
1639
+ this.#pointer = [...action.at];
1640
+ else if (action.type === "up") {
1641
+ const released = await this.#release(signal);
1642
+ if (!released.ok)
1643
+ return signal.aborted ? cancelled(index) : failed(index, (DAEMON_KINDS.has(released.error.code) ? released.error.code : "invalid"), released.error.message);
1644
+ }
1645
+ else {
1646
+ if (this.#pointer === undefined)
1647
+ return failed(index, "invalid", "a down needs the pointer's place, and this connection has not moved it yet");
1648
+ // A press still held is released first, as the up's: one cancelled on the way says so, never bad input.
1649
+ if (this.#pressed !== undefined) {
1650
+ const released = await this.#release(signal);
1651
+ if (!released.ok)
1652
+ return signal.aborted ? cancelled(index) : failed(index, (DAEMON_KINDS.has(released.error.code) ? released.error.code : "invalid"), released.error.message);
1653
+ }
1654
+ this.#pressed = { button: action.button ?? "left", at: [...this.#pointer] };
1655
+ }
1656
+ continue;
1657
+ }
1658
+ // Anything else presses or moves on its own: a press held down is released first, where the pointer is.
1659
+ if (this.#pressed !== undefined && action.type !== "wait" && action.type !== "key" && action.type !== "type") {
1660
+ const released = await this.#release(signal);
1661
+ if (!released.ok)
1662
+ return signal.aborted ? cancelled(index) : failed(index, "invalid", released.error.message);
1663
+ }
1664
+ const steps = this.#steps(action, this.#pointer);
1665
+ if (!Array.isArray(steps))
1666
+ return failed(index, steps.kind, steps.message);
1667
+ for (const step of steps) {
1668
+ if (signal.aborted)
1669
+ return cancelled(index);
1670
+ if ("waitMs" in step) {
1671
+ await pause(step.waitMs, signal);
1672
+ if (signal.aborted)
1673
+ return cancelled(index);
1674
+ continue;
1675
+ }
1676
+ const stopped = await sendOrFail(index, step);
1677
+ if (stopped !== undefined)
1678
+ return stopped;
1679
+ }
1680
+ if (action.type === "move" || ((action.type === "click" || action.type === "scroll") && action.at !== undefined))
1681
+ this.#pointer = [...action.at];
1682
+ else if (action.type === "drag")
1683
+ this.#pointer = [...action.path.at(-1)];
1684
+ }
1685
+ return ok({ done: list.length });
1686
+ }
1687
+ // --- exec ----------------------------------------------------------------------------------------------------
1688
+ /**
1689
+ * exec.run through Orgo's bash call: PowerShell on Windows, the shell on macOS, argv quoted word by word (never a
1690
+ * shell string). Orgo bounds a command in whole seconds, 1 to 300; a longer timeoutMs is refused as limit. No user
1691
+ * switch: denied. maxOutput keeps that many bytes of each stream.
1692
+ */
1693
+ async #exec(params, signal) {
1694
+ const { argv, cwd, env, user, timeoutMs, maxOutput = MAX_OUTPUT_BYTES } = params;
1695
+ if (!Array.isArray(argv) || argv.length === 0 || !argv.every((word) => typeof word === "string" && !word.includes("\0")) || argv[0] === "")
1696
+ return refuse("invalid", "argv is a program and its arguments: a list of strings, the first not empty, none holding a NUL");
1697
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
1698
+ return refuse("invalid", "timeoutMs is a whole number of milliseconds above 0");
1699
+ if (timeoutMs > BASH_MAX_S * 1000)
1700
+ return refuse("limit", `timeoutMs ${timeoutMs} is past Orgo's longest command, ${BASH_MAX_S} s`);
1701
+ if (!Number.isSafeInteger(maxOutput) || maxOutput < 0 || maxOutput > MAX_OUTPUT_BYTES)
1702
+ return refuse("invalid", `maxOutput is 0 to ${MAX_OUTPUT_BYTES} bytes`);
1703
+ if (user !== undefined)
1704
+ return refuse("denied", `an Orgo ${this.profile.os} computer runs every program as Orgo's own user; it cannot switch to ${show(user)}`);
1705
+ if (cwd !== undefined && (typeof cwd !== "string" || cwd === "" || cwd.includes("\0")))
1706
+ return refuse("invalid", "cwd is a folder's path");
1707
+ if (env !== undefined) {
1708
+ if (typeof env !== "object" || env === null || Array.isArray(env))
1709
+ return refuse("invalid", "env maps names to strings");
1710
+ const bad = Object.entries(env).find(([name, value]) => !ENV_NAME.test(name) || typeof value !== "string" || value.includes("\0"));
1711
+ if (bad)
1712
+ return refuse("invalid", `env ${show(bad[0])}: a name of letters, digits and _, not starting with a digit, and a string with no NUL`);
1713
+ }
1714
+ const command = commandOf(this.profile.os, argv, { ...(cwd === undefined ? {} : { cwd: cwd }), ...(env === undefined ? {} : { env: env }) });
1715
+ const ran = await bashCall(this.rest, this.computer, command, timeoutMs, signal);
1716
+ if (!ran.ok)
1717
+ return signal.aborted ? refuse("aborted", "exec.run was aborted; the command may still run in the computer until its timeout") : ran;
1718
+ const keep = (text) => {
1719
+ const bytes = Buffer.from(text, "utf8");
1720
+ return { data: bytes.subarray(0, maxOutput).toString("base64"), cut: bytes.length > maxOutput };
1721
+ };
1722
+ const out = keep(ran.value.stdout);
1723
+ const err = keep(ran.value.stderr);
1724
+ return ok({ exitCode: ran.value.exitCode, stdout: out.data, stderr: err.data, timedOut: ran.value.timedOut, truncated: out.cut || err.cut });
1725
+ }
1726
+ // --- files (Windows) -----------------------------------------------------------------------------------------
1727
+ /** One files method through FILES_SCRIPT, its request base64 in the script; a large write is uploaded first. */
1728
+ async #files(op, params, signal) {
1729
+ const path = (value) => (typeof value === "string" && WINDOWS_ABSOLUTE.test(value) && !value.includes("\0") ? value : undefined);
1730
+ const absolute = (field) => refuse("invalid", `${field} is an absolute Windows path, such as C:\\Users\\Public\\notes.txt`);
1731
+ let request;
1732
+ switch (op) {
1733
+ case "read": {
1734
+ if (path(params.path) === undefined)
1735
+ return absolute("path");
1736
+ const { offset = 0, length = MAX_CHUNK_BYTES } = params;
1737
+ if (!Number.isSafeInteger(offset) || offset < 0)
1738
+ return refuse("invalid", "offset is a whole number of bytes, 0 or more");
1739
+ if (!Number.isSafeInteger(length) || length < 0)
1740
+ return refuse("invalid", "length is a whole number of bytes, 0 or more");
1741
+ if (length > MAX_CHUNK_BYTES)
1742
+ return refuse("limit", `length is at most ${MAX_CHUNK_BYTES} bytes`);
1743
+ request = { op, path: params.path, offset, length: Math.min(length, READ_CHUNK_BYTES) };
1744
+ break;
1745
+ }
1746
+ case "write": {
1747
+ if (path(params.path) === undefined)
1748
+ return absolute("path");
1749
+ if (typeof params.data !== "string")
1750
+ return refuse("invalid", "data is base64");
1751
+ if (params.offset !== undefined && params.append)
1752
+ return refuse("invalid", "offset and append are one or the other");
1753
+ if (params.offset !== undefined && !(Number.isSafeInteger(params.offset) && params.offset >= 0))
1754
+ return refuse("invalid", "offset is a whole number of bytes, 0 or more");
1755
+ if (params.mode !== undefined)
1756
+ return refuse("unsupported", NO_MODES);
1757
+ request = { op, path: params.path, ...(params.offset === undefined ? {} : { offset: params.offset }), append: params.append === true, parents: params.parents === true };
1758
+ if (params.data.length <= INLINE_WRITE_CHARS)
1759
+ request.data = params.data;
1760
+ else {
1761
+ const staged = await this.#stage(Buffer.from(params.data, "base64"), signal);
1762
+ if (!staged.ok)
1763
+ return staged;
1764
+ request.staged = staged.value;
1765
+ }
1766
+ break;
1767
+ }
1768
+ case "stat":
1769
+ if (path(params.path) === undefined)
1770
+ return absolute("path");
1771
+ request = { op, path: params.path, follow: params.follow === true };
1772
+ break;
1773
+ case "list": {
1774
+ if (path(params.path) === undefined)
1775
+ return absolute("path");
1776
+ const { depth = 1, offset = 0 } = params;
1777
+ if (!Number.isSafeInteger(depth) || depth < 1 || depth > 16)
1778
+ return refuse("invalid", "depth is 1 to 16");
1779
+ if (!Number.isSafeInteger(offset) || offset < 0)
1780
+ return refuse("invalid", "offset is a whole number, 0 or more");
1781
+ request = { op, path: params.path, depth, offset, max: MAX_LIST_ENTRIES };
1782
+ break;
1783
+ }
1784
+ case "mkdir":
1785
+ case "remove":
1786
+ if (path(params.path) === undefined)
1787
+ return absolute("path");
1788
+ if (op === "mkdir" && params.mode !== undefined)
1789
+ return refuse("unsupported", NO_MODES);
1790
+ request = { op, path: params.path, parents: params.parents === true, recursive: params.recursive === true };
1791
+ break;
1792
+ case "move":
1793
+ if (path(params.from) === undefined)
1794
+ return absolute("from");
1795
+ if (path(params.to) === undefined)
1796
+ return absolute("to");
1797
+ request = { op, from: params.from, to: params.to, overwrite: params.overwrite === true };
1798
+ break;
1799
+ default:
1800
+ return refuse("unsupported", `files.${op} is not a files method`);
1801
+ }
1802
+ const script = FILES_SCRIPT.replace("@@REQUEST@@", Buffer.from(JSON.stringify(request), "utf8").toString("base64"));
1803
+ const ran = await bashCall(this.rest, this.computer, script, 120_000, signal);
1804
+ if (!ran.ok || ran.value.timedOut) {
1805
+ // The script that removes an uploaded copy did not run (or was cut off, or hit Orgo's time limit): it is removed here, once, unbounded by the
1806
+ // call's own signal, which may be the abort itself.
1807
+ if (typeof request.staged === "string")
1808
+ await bashCall(this.rest, this.computer, `Remove-Item -LiteralPath ${psQuote(request.staged)} -Force -ErrorAction SilentlyContinue`, 30_000).catch(() => undefined);
1809
+ if (!ran.ok)
1810
+ return signal.aborted ? refuse("aborted", `files.${op} was aborted`) : ran;
1811
+ }
1812
+ let answer;
1813
+ try {
1814
+ answer = JSON.parse(ran.value.stdout.trim() || "null");
1815
+ }
1816
+ catch {
1817
+ answer = {};
1818
+ }
1819
+ if (typeof answer?.error === "string") {
1820
+ const kind = DAEMON_KINDS.has(answer.error) ? answer.error : "invalid";
1821
+ return refuse(kind, `files.${op}: ${String(answer.message ?? "refused").trim().slice(0, 300)}`);
1822
+ }
1823
+ if (ran.value.exitCode !== 0 || answer === null || typeof answer !== "object")
1824
+ return refuse("invalid", `files.${op} failed in the computer (exit ${ran.value.exitCode}): ${(ran.value.stderr || ran.value.stdout).trim().slice(0, 300)}`);
1825
+ switch (op) {
1826
+ case "read": {
1827
+ const data = Buffer.from(String(answer.data ?? ""), "base64");
1828
+ const size = Number(answer.size);
1829
+ return ok({ data: data.toString("base64"), eof: request.offset + data.length >= size, size });
1830
+ }
1831
+ case "write":
1832
+ return ok({ size: Number(answer.size) });
1833
+ case "stat":
1834
+ return ok(answer);
1835
+ case "list":
1836
+ return ok({ entries: Array.isArray(answer.entries) ? answer.entries : answer.entries === undefined || answer.entries === null ? [] : [answer.entries], truncated: answer.truncated === true });
1837
+ default:
1838
+ return ok({});
1839
+ }
1840
+ }
1841
+ /** bytes put in the staging folder through Orgo's upload, under a fresh name: the path PowerShell then reads. */
1842
+ async #stage(bytes, signal) {
1843
+ const folder = this.profile.staging;
1844
+ const name = `agentrun-${randomBytes(8).toString("hex")}`;
1845
+ const form = new FormData();
1846
+ form.set("file", new Blob([new Uint8Array(bytes)]), name);
1847
+ form.set("workspaceId", this.workspaceId);
1848
+ form.set("desktopId", this.computer);
1849
+ form.set("destPath", folder);
1850
+ const sent = await this.rest.request("POST", "/files/upload", { form, timeoutMs: 120_000, signal });
1851
+ if (!sent.ok)
1852
+ return fail(sent.error.code, `the write's upload to ${folder} failed: ${sent.error.message}`);
1853
+ return ok(`${folder}\\${name}`);
1854
+ }
1855
+ }
1856
+ _a = OrgoDesktopClient;