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

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