@parcha/agentrun-computer 0.1.0-beta.38 → 0.1.0-beta.40

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 (97) hide show
  1. package/README.md +126 -83
  2. package/box/Dockerfile +5 -54
  3. package/box/README.md +9 -3
  4. package/box/build-daytona.py +2 -2
  5. package/box/build-e2b.mjs +1 -1
  6. package/box/install.sh +87 -0
  7. package/box/recipe.d.mts +5 -0
  8. package/box/recipe.mjs +12 -10
  9. package/dist/agent37.d.ts +17 -4
  10. package/dist/agent37.js +98 -17
  11. package/dist/box-image.d.ts +14 -0
  12. package/dist/box-image.js +24 -0
  13. package/dist/computerd-linux-amd64 +0 -0
  14. package/dist/computerd-linux-arm64 +0 -0
  15. package/dist/computerd.json +2 -2
  16. package/dist/conformance/agent37.d.ts +9 -4
  17. package/dist/conformance/agent37.js +23 -11
  18. package/dist/conformance/browserbase.js +3 -3
  19. package/dist/conformance/cases/apps.d.ts +1 -1
  20. package/dist/conformance/cases/apps.js +1 -1
  21. package/dist/conformance/cases/isolation.d.ts +18 -3
  22. package/dist/conformance/cases/isolation.js +73 -6
  23. package/dist/conformance/cases/lifetime.js +30 -0
  24. package/dist/conformance/cases/mount.js +4 -2
  25. package/dist/conformance/cases/provider.js +88 -1
  26. package/dist/conformance/cli.js +29 -9
  27. package/dist/conformance/e2b.js +9 -4
  28. package/dist/conformance/exec-stream.d.ts +44 -7
  29. package/dist/conformance/exec-stream.js +347 -88
  30. package/dist/conformance/kernel.js +2 -2
  31. package/dist/conformance/modal.js +1 -1
  32. package/dist/conformance/orgo.js +2 -2
  33. package/dist/conformance/report.js +3 -0
  34. package/dist/conformance/runner.js +127 -9
  35. package/dist/conformance/types.d.ts +21 -0
  36. package/dist/daytona.d.ts +0 -5
  37. package/dist/daytona.js +19 -28
  38. package/dist/descriptor.d.ts +5 -3
  39. package/dist/descriptors/agent37.d.ts +3 -11
  40. package/dist/descriptors/agent37.js +9 -10
  41. package/dist/descriptors/daytona.d.ts +1 -1
  42. package/dist/descriptors/daytona.js +5 -2
  43. package/dist/descriptors/docker.d.ts +13 -1
  44. package/dist/descriptors/docker.js +3 -1
  45. package/dist/descriptors/e2b.d.ts +2 -9
  46. package/dist/descriptors/e2b.js +8 -8
  47. package/dist/descriptors/index.d.ts +21 -19
  48. package/dist/descriptors/index.js +1 -3
  49. package/dist/descriptors/modal.d.ts +2 -6
  50. package/dist/descriptors/modal.js +8 -6
  51. package/dist/descriptors/orgo.js +2 -1
  52. package/dist/docker/egress-main.js +23 -15
  53. package/dist/docker/egress.d.ts +6 -4
  54. package/dist/docker/egress.js +24 -16
  55. package/dist/docker/inspect.d.ts +2 -2
  56. package/dist/docker/inspect.js +5 -5
  57. package/dist/docker.d.ts +6 -5
  58. package/dist/docker.js +12 -11
  59. package/dist/e2b.d.ts +12 -2
  60. package/dist/e2b.js +42 -19
  61. package/dist/host.d.ts +113 -59
  62. package/dist/host.js +5 -0
  63. package/dist/hosted/framed-exec.d.ts +49 -0
  64. package/dist/hosted/framed-exec.js +185 -0
  65. package/dist/hosted/network.d.ts +23 -0
  66. package/dist/hosted/network.js +77 -0
  67. package/dist/hosted/process.d.ts +13 -5
  68. package/dist/hosted/process.js +35 -12
  69. package/dist/hosted/provider.d.ts +16 -9
  70. package/dist/hosted/provider.js +475 -170
  71. package/dist/hosted/rest.d.ts +20 -2
  72. package/dist/hosted/rest.js +24 -10
  73. package/dist/hosted/scripts.d.ts +27 -7
  74. package/dist/hosted/scripts.js +77 -18
  75. package/dist/{agent37-ssh.d.ts → hosted/ssh-exec.d.ts} +19 -9
  76. package/dist/{agent37-ssh.js → hosted/ssh-exec.js} +38 -19
  77. package/dist/hosted/values.d.ts +21 -0
  78. package/dist/hosted/values.js +55 -0
  79. package/dist/index.d.ts +1 -1
  80. package/dist/index.js +1 -1
  81. package/dist/isolation.d.ts +0 -2
  82. package/dist/isolation.js +3 -4
  83. package/dist/modal.d.ts +8 -2
  84. package/dist/modal.js +21 -15
  85. package/dist/mount-archil.d.ts +5 -4
  86. package/dist/mount-archil.js +5 -6
  87. package/dist/orgo.js +6 -4
  88. package/dist/providers.d.ts +4 -1
  89. package/dist/surface/api.d.ts +0 -9
  90. package/dist/surface/core.d.ts +7 -2
  91. package/dist/surface/core.js +12 -4
  92. package/dist/surface/index.d.ts +1 -1
  93. package/dist/surface/index.js +1 -1
  94. package/dist/surface/script.d.ts +4 -0
  95. package/dist/surface/script.js +9 -3
  96. package/package.json +1 -1
  97. package/box/build-agent37.mjs +0 -158
@@ -1,6 +1,9 @@
1
1
  import { type ComputerErrorCode, type Result } from "../result.js";
2
- /** A status as a code: 401 and 403 denied, 404 and 410 not found, 408 timeout, 402/429/507 limit, 400/409/422 invalid, else vendor. */
3
- export declare function httpCode(status: number): ComputerErrorCode;
2
+ /**
3
+ * A status as a code: 401 and 403 denied, 404 and 410 not found, 408 timeout, 402/429/507 limit, 400/409/422 invalid,
4
+ * else vendor; 409 is exists on a call that carries the machine's name (RestInit.named).
5
+ */
6
+ export declare function httpCode(status: number, named?: boolean): ComputerErrorCode;
4
7
  export interface RestAnswer {
5
8
  status: number;
6
9
  bytes: Uint8Array;
@@ -16,6 +19,11 @@ export interface RestInit {
16
19
  retry?: boolean | ((status: number, bytes: Uint8Array) => boolean);
17
20
  /** Whether an answer of this status is a value, with its status, not a failure (not retried). Default: a 2xx. */
18
21
  accept?: (status: number) => boolean;
22
+ /**
23
+ * The call carries the machine's name (a create by MachineRequest.name): its 409 is the vendor's word that a machine
24
+ * has that name, exists, which the adapter reads as the machine its listing by the name finds.
25
+ */
26
+ named?: boolean;
19
27
  }
20
28
  export interface RestOptions {
21
29
  /** The API's root; trailing slashes are cut. `rest.url(path)` joins it. */
@@ -45,11 +53,21 @@ export interface RestOptions {
45
53
  }
46
54
  /** The JSON a body holds; null for none or for text that is not JSON. */
47
55
  export declare function jsonOf(bytes: Uint8Array): unknown;
56
+ /** An accepted answer whose body is read as it comes: an event stream. */
57
+ export interface RestStream {
58
+ status: number;
59
+ body: AsyncIterable<Uint8Array>;
60
+ }
48
61
  export interface Rest {
49
62
  url(path: string): string;
50
63
  call(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<RestAnswer>>;
51
64
  /** call, with the body read as JSON (null for none). */
52
65
  json(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<unknown>>;
66
+ /**
67
+ * call, with an accepted answer's body handed back unread, as it comes (a process's events). The bound covers the
68
+ * answer's start alone: the body has none but the caller's signal, which ends it too.
69
+ */
70
+ stream(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<RestStream>>;
53
71
  }
54
72
  export declare function rest(options: RestOptions): Rest;
55
73
  /**
@@ -3,8 +3,11 @@
3
3
  // cursor-page loop are here too, so a REST vendor writes only its own words and its own retry rule.
4
4
  import { errorOf, fail, ok, vendorFail } from "../result.js";
5
5
  import { pause } from "./process.js";
6
- /** A status as a code: 401 and 403 denied, 404 and 410 not found, 408 timeout, 402/429/507 limit, 400/409/422 invalid, else vendor. */
7
- export function httpCode(status) {
6
+ /**
7
+ * A status as a code: 401 and 403 denied, 404 and 410 not found, 408 timeout, 402/429/507 limit, 400/409/422 invalid,
8
+ * else vendor; 409 is exists on a call that carries the machine's name (RestInit.named).
9
+ */
10
+ export function httpCode(status, named = false) {
8
11
  if (status === 401 || status === 403)
9
12
  return "denied";
10
13
  if (status === 404 || status === 410)
@@ -13,7 +16,9 @@ export function httpCode(status) {
13
16
  return "timeout";
14
17
  if (status === 402 || status === 429 || status === 507)
15
18
  return "limit";
16
- if (status === 400 || status === 409 || status === 422)
19
+ if (status === 409)
20
+ return named ? "exists" : "invalid";
21
+ if (status === 400 || status === 422)
17
22
  return "invalid";
18
23
  return "vendor";
19
24
  }
@@ -35,11 +40,13 @@ function redirected(cause) {
35
40
  const inner = cause?.cause;
36
41
  return /redirect/i.test(`${cause?.message ?? ""} ${inner?.message ?? ""}`);
37
42
  }
43
+ const NO_BODY = { async *[Symbol.asyncIterator]() { } };
38
44
  export function rest(options) {
39
45
  const base = options.base.replace(/\/+$/, "");
40
46
  const fetcher = options.fetch ?? fetch;
41
47
  const wait = options.retry?.pause ?? pause;
42
- async function call(method, url, init = {}, signal) {
48
+ /** One call, sent again as init.retry says; an accepted answer is what take makes of it, within the call's bound. */
49
+ async function exchange(method, url, init, signal, take) {
43
50
  const what = `${method} ${new URL(url).pathname}`;
44
51
  const attempts = init.retry === undefined || init.retry === false || options.retry === undefined ? 1 : options.retry.attempts;
45
52
  const timeoutMs = init.timeoutMs ?? options.timeoutMs;
@@ -47,7 +54,9 @@ export function rest(options) {
47
54
  for (let attempt = 1;; attempt++) {
48
55
  if (signal?.aborted)
49
56
  return fail("aborted", `${what} was aborted`);
50
- const timeout = AbortSignal.timeout(timeoutMs);
57
+ // A bound that lets go once the answer is taken, so a body read after it (a stream's) is never cut by it.
58
+ const timeout = new AbortController();
59
+ const timer = setTimeout(() => timeout.abort(), timeoutMs);
51
60
  let failure;
52
61
  let retryable;
53
62
  try {
@@ -58,34 +67,38 @@ export function rest(options) {
58
67
  headers,
59
68
  body: init.json === undefined ? init.form : JSON.stringify(init.json),
60
69
  redirect: "error",
61
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
70
+ signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
62
71
  });
63
- const bytes = new Uint8Array(await response.arrayBuffer());
64
72
  if (accepted(response.status))
65
- return ok({ status: response.status, bytes });
73
+ return ok(await take(response));
74
+ const bytes = new Uint8Array(await response.arrayBuffer());
66
75
  const own = typeof init.retry === "function";
67
76
  retryable = own ? init.retry(response.status, bytes) : init.retry === true && (response.status === 429 || response.status >= 500);
68
77
  const text = decoder.decode(bytes).replace(/\s+/g, " ").slice(0, 300);
69
78
  const said = options.explain?.({ status: response.status, bytes, text, what }) ?? {};
70
- failure = errorOf(said.code ?? httpCode(response.status), said.message ?? `${what}: ${response.status} ${text}`, options.vendor);
79
+ failure = errorOf(said.code ?? httpCode(response.status, init.named), said.message ?? `${what}: ${response.status} ${text}`, options.vendor);
71
80
  }
72
81
  catch (cause) {
73
82
  if (signal?.aborted)
74
83
  return fail("aborted", `${what} was aborted`);
75
84
  // No answer: the request may have reached the vendor, so only a call that may run twice is sent again.
76
85
  retryable = init.retry === true;
77
- if (timeout.aborted)
86
+ if (timeout.signal.aborted)
78
87
  failure = { code: "timeout", message: `${what} did not answer within ${timeoutMs / 1000} s` };
79
88
  else if (redirected(cause))
80
89
  return vendorFail(options.vendor, `${what}: the API answered with a redirect, which is never followed: it would carry the key`);
81
90
  else
82
91
  failure = { code: "vendor", vendor: options.vendor, message: `${what}: ${cause.message}` };
83
92
  }
93
+ finally {
94
+ clearTimeout(timer);
95
+ }
84
96
  if (!retryable || attempt >= attempts)
85
97
  return { ok: false, error: failure };
86
98
  await wait((options.retry?.baseMs ?? 0) * 2 ** (attempt - 1), signal);
87
99
  }
88
100
  }
101
+ const call = (method, url, init = {}, signal) => exchange(method, url, init, signal, async (response) => ({ status: response.status, bytes: new Uint8Array(await response.arrayBuffer()) }));
89
102
  return {
90
103
  url: (path) => `${base}${path}`,
91
104
  call,
@@ -93,6 +106,7 @@ export function rest(options) {
93
106
  const answer = await call(method, url, init, signal);
94
107
  return answer.ok ? ok(jsonOf(answer.value.bytes)) : answer;
95
108
  },
109
+ stream: (method, url, init = {}, signal) => exchange(method, url, init, signal, async (response) => ({ status: response.status, body: response.body ?? NO_BODY })),
96
110
  };
97
111
  }
98
112
  /**
@@ -8,8 +8,22 @@ export declare const shellCommand: (script: string, args: readonly string[]) =>
8
8
  export declare const shellLine: (argv: readonly string[]) => string;
9
9
  /** Where start leaves what init writes, root's alone: the words a create that never hears the daemon gives back. */
10
10
  export declare const INIT_LOG = "/run/agentrun-init.log";
11
+ /**
12
+ * The session buses a vendor's own processes leave in /tmp (Daytona's D-Bus, /tmp/dbus-Y8OW6E3FDx), which no network
13
+ * namespace cuts: every child host's create closes them to the computer's user before init starts. The window
14
+ * manager's bus is its own, at an abstract address, so closing these takes nothing from it.
15
+ */
16
+ export declare const SESSION_BUSES: readonly string[];
11
17
  /** The sockets the sockets script closed, from its `closed <path>` lines. */
12
18
  export declare function closedSocketsOf(output: string): string[];
19
+ /**
20
+ * Where a machine of a host that keeps no labels (HostFacts.labels "machine") holds its label map, as JSON. Under
21
+ * /var/lib, on the machine's disk, so it outlives a restart: /run is a tmpfs, and /run/agentrun is the daemon user's.
22
+ * In a directory root's alone (0700), so the computer's user can neither read nor change it.
23
+ */
24
+ export declare const LABEL_FILE = "/var/lib/agentrun/labels.json";
25
+ /** The label file's read, or given the byte length of the JSON on stdin, its write and then its read. */
26
+ export declare const labelsCommand: (bytes?: number) => string[];
13
27
  /**
14
28
  * Where a pid1 Archil computer's entrypoint waits for root's word that the run's folder is mounted: beside the daemon,
15
29
  * in the directory install makes root's alone before root makes the gate, so no other user can make it early. (A path
@@ -21,8 +35,10 @@ export interface HostedCommands {
21
35
  install: string[];
22
36
  /** child: init's start, detached; it answers once init is started. */
23
37
  start: string[];
24
- /** child: the vendor's sockets (HostFacts.vendorSockets) closed to others, run before start; none when it names none. */
25
- sockets?: string[];
38
+ /** child: the session buses in /tmp (SESSION_BUSES) closed to others, run before start. */
39
+ sockets: string[];
40
+ /** Write taken off every user but root on the host's rootOnly paths, run before the daemon's upload. */
41
+ rootOnly: string[];
26
42
  stdio: string[];
27
43
  log: string[];
28
44
  /** pid1: the machine's command. */
@@ -32,16 +48,18 @@ export interface HostedCommands {
32
48
  * The adapter's commands for one computer. Init's flags are the child's (childCommands) for both modes: --own-network
33
49
  * always, the display and the most deadline.extend may move the deadline to when given. waitS bounds a pid1 entrypoint's
34
50
  * wait for the daemon (and gate, for an Archil computer); with atomic, install moves the daemon into place last, and only
35
- * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for. vendorSockets
36
- * (HostFacts') gives a child its sockets command.
51
+ * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for. sockets are
52
+ * the patterns a child's sockets command closes (default SESSION_BUSES); rootOnly the paths its root-only command takes
53
+ * others' write off (default none).
37
54
  */
38
- export declare function hostedCommands({ staging, deadline, user, display, maxDeadline, atomic, waitS, gate, sha256, nonce, vendorSockets, }?: ChildCommandOptions & {
55
+ export declare function hostedCommands({ staging, deadline, user, display, maxDeadline, atomic, waitS, gate, sha256, nonce, sockets, rootOnly, network, }?: ChildCommandOptions & {
39
56
  atomic?: boolean;
40
57
  waitS?: number;
41
58
  gate?: string;
42
59
  sha256?: string;
43
60
  nonce?: string;
44
- vendorSockets?: readonly string[];
61
+ sockets?: readonly string[];
62
+ rootOnly?: readonly string[];
45
63
  }): HostedCommands;
46
64
  export interface ChildCommandOptions {
47
65
  /** Where the vendor's upload left the daemon. */
@@ -54,13 +72,15 @@ export interface ChildCommandOptions {
54
72
  display?: string;
55
73
  /** The most deadline.extend may move the deadline to, an ISO time; none, and the deadline cannot move. */
56
74
  maxDeadline?: string;
75
+ /** The network form init's egress proxy serves (./network.ts networkFormOf): open, or allow: and a list; none, no proxy. */
76
+ network?: string;
57
77
  }
58
78
  /**
59
79
  * The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
60
80
  * its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
61
81
  * every argument quoted.
62
82
  */
63
- export declare function childCommands({ staging, deadline, user, display, maxDeadline }?: ChildCommandOptions): {
83
+ export declare function childCommands({ staging, deadline, user, display, maxDeadline, network }?: ChildCommandOptions): {
64
84
  install: string;
65
85
  init: string;
66
86
  stdio: string;
@@ -60,15 +60,17 @@ export function installerOf(output) {
60
60
  * them (Daytona's toolbox, E2B's envd), which runs commands as root for whoever reaches it: a network of their own,
61
61
  * their loopback alone, no vsock, no other process of their uid (src/isolation.ts). Init holds every process and ends
62
62
  * them at the deadline. A display, when given, is init's DISPLAY, the X display its screen and input methods drive; a
63
- * maximum, when given, is the most deadline.extend may move the deadline to. */
63
+ * maximum, when given, is the most deadline.extend may move the deadline to; a network form, when given (open, or
64
+ * allow: and a list), has init start the egress proxy that serves it before it leaves the machine's network
65
+ * (./network.ts). */
64
66
  const INIT_SCRIPT = [
65
67
  "# agentrun-computer: init",
66
- // The display is v, not x: held() assigns x, and runs before the exec that reads it.
67
- "d=$1; t=$2; w=$3; h=$4; r=$5; v=${6-}; m=${7-}",
68
+ // The display is v, not x: held() assigns x, and runs before the exec that reads it. The network form is n.
69
+ "d=$1; t=$2; w=$3; h=$4; r=$5; v=${6-}; m=${7-}; n=${8-}",
68
70
  HELD,
69
71
  'held "$d" >&2 || exit 6',
70
72
  ROOT,
71
- `exec $p env -i PATH=${PATH} HOME="$h" AGENTRUN_COMPUTERD_SOCKET="$r/computerd.sock" \${v:+DISPLAY="$v"} sh -c 'cd "$HOME" && exec "$@"' sh "$d" init --deadline "$t" --user "$w" --own-network \${m:+--max-deadline "$m"}`,
73
+ `exec $p env -i PATH=${PATH} HOME="$h" AGENTRUN_COMPUTERD_SOCKET="$r/computerd.sock" \${v:+DISPLAY="$v"} sh -c 'cd "$HOME" && exec "$@"' sh "$d" init --deadline "$t" --user "$w" --own-network \${m:+--max-deadline "$m"} \${n:+--network "$n"}`,
72
74
  ].join("\n");
73
75
  /** The bridge one connection runs: stdin and stdout to init's socket. As root, to reach a socket in a directory that is
74
76
  * the daemon's user's alone; it only carries bytes, and the command's user is root or has passwordless sudo already.
@@ -89,8 +91,14 @@ export const INIT_LOG = `${SOCKET_DIR}-init.log`;
89
91
  */
90
92
  const START_SCRIPT = ["# agentrun-computer: start", "l=$1; shift", ROOT, `exec $p sh -c 'exec >"$0" 2>&1 </dev/null; setsid "$@" &' "$l" "$@"`].join("\n");
91
93
  /**
92
- * Takes others' access off every path unix socket the vendor's patterns ($@, each a shell pattern with no space) name,
93
- * as root: what init does itself under /run (daemon/internal/isolate CloseSystemSockets), for a vendor's socket
94
+ * The session buses a vendor's own processes leave in /tmp (Daytona's D-Bus, /tmp/dbus-Y8OW6E3FDx), which no network
95
+ * namespace cuts: every child host's create closes them to the computer's user before init starts. The window
96
+ * manager's bus is its own, at an abstract address, so closing these takes nothing from it.
97
+ */
98
+ export const SESSION_BUSES = ["/tmp/dbus-*"];
99
+ /**
100
+ * Takes others' access off every path unix socket the patterns ($@, each a shell pattern with no space) name, as
101
+ * root: what init does itself under /run (daemon/internal/isolate CloseSystemSockets), for a vendor's socket
94
102
  * elsewhere. The owner's and group's access stays, so the vendor's own service keeps its socket; the computer's user
95
103
  * is neither. A link is never followed. Prints `closed <path>` for each socket it closed and `failed <path>` for one
96
104
  * it could not; any failure fails the script, and create then refuses the computer.
@@ -107,12 +115,55 @@ const SOCKETS_SCRIPT = [
107
115
  "done",
108
116
  "exit $failed",
109
117
  ].join("\n");
118
+ /**
119
+ * Makes each path ($@) root's alone, as root, and for a directory everything under it (no link is followed): root owns
120
+ * every entry (a link itself, `chown -h`), and no group or other user may write one. Only the entries that need it are
121
+ * changed. Then it reads them back: an entry not root's alone fails the script, and create then refuses the computer.
122
+ * An owner who is not root could give write back with chmod, so the owner is made root as well as the mode. A path the
123
+ * image lacks is skipped. For a host whose image leaves places root runs or reads open to other users
124
+ * (HostFacts.rootOnly); it runs before the daemon's upload. Root is the user `$p` runs as, read by `id -u`.
125
+ */
126
+ const ROOT_ONLY_SCRIPT = [
127
+ "# agentrun-computer: root-only",
128
+ ROOT,
129
+ 'r=$($p id -u) || { echo "running a command as root failed"; exit 5; }',
130
+ 'for f in "$@"; do',
131
+ '\t[ -e "$f" ] || [ -L "$f" ] || continue',
132
+ '\t[ ! -L "$f" ] || { echo "$f is a symbolic link"; exit 6; }',
133
+ '\t$p find "$f" ! -user "$r" -exec chown -h "$r" {} + || { echo "making root the owner of $f failed"; exit 5; }',
134
+ '\t$p find "$f" ! -type l -perm /022 -exec chmod go-w {} + || { echo "taking write off $f failed"; exit 5; }',
135
+ '\tw=$($p find "$f" \\( ! -user "$r" -o ! -type l -perm /022 \\) -print 2>/dev/null | head -n 1)',
136
+ '\t[ -z "$w" ] || { echo "$w is not root\'s alone"; exit 5; }',
137
+ "done",
138
+ ].join("\n");
110
139
  /** The sockets the sockets script closed, from its `closed <path>` lines. */
111
140
  export function closedSocketsOf(output) {
112
141
  return output.split("\n").flatMap((line) => (line.startsWith("closed ") ? [line.slice("closed ".length).trim()] : []));
113
142
  }
114
143
  /** The last words init wrote to its log, as root; nothing when it wrote none. */
115
144
  const LOG_SCRIPT = ["# agentrun-computer: log", "l=$1", ROOT, '$p tail -c 2000 "$l" 2>/dev/null || true'].join("\n");
145
+ /**
146
+ * Where a machine of a host that keeps no labels (HostFacts.labels "machine") holds its label map, as JSON. Under
147
+ * /var/lib, on the machine's disk, so it outlives a restart: /run is a tmpfs, and /run/agentrun is the daemon user's.
148
+ * In a directory root's alone (0700), so the computer's user can neither read nor change it.
149
+ */
150
+ export const LABEL_FILE = "/var/lib/agentrun/labels.json";
151
+ /**
152
+ * The label file, as root. With write <bytes>, that many bytes of stdin replace it, read by length so no end of stdin
153
+ * is needed: written to a file of its own beside it (two writers never share one) and renamed in, 0600 in a 0700
154
+ * directory, both root's. Then it prints the file; exit 3 when there is none.
155
+ */
156
+ const LABELS_SCRIPT = [
157
+ "# agentrun-computer: labels",
158
+ "f=$1",
159
+ ROOT,
160
+ 'if [ "${2-}" = write ]; then',
161
+ `\t$p sh -c 'umask 077; d=\${0%/*}; mkdir -p "$d" && chown 0:0 "$d" && chmod 700 "$d" && t=$(mktemp "$0.XXXXXX") || exit 5; head -c "$1" >"$t" && [ "$(wc -c <"$t")" -eq "$1" ] && mv -f "$t" "$0" || { rm -f "$t"; exit 5; }' "$f" "$3" || exit 5`,
162
+ "fi",
163
+ `exec $p sh -c '[ -e "$0" ] || exit 3; exec cat "$0"' "$f"`,
164
+ ].join("\n");
165
+ /** The label file's read, or given the byte length of the JSON on stdin, its write and then its read. */
166
+ export const labelsCommand = (bytes) => argvOf(LABELS_SCRIPT, [LABEL_FILE, ...(bytes === undefined ? [] : ["write", String(bytes)])]);
116
167
  /**
117
168
  * A pid1 machine's main process: waits, bounded, for the daemon this create installed to be moved into place executable
118
169
  * (the marker beside it, `<daemon>.installed`, holds this create's nonce: a daemon the image had at the path, or one an
@@ -153,32 +204,40 @@ export const ARCHIL_GATE = `${DAEMON_IN_COMPUTER.slice(0, DAEMON_IN_COMPUTER.las
153
204
  * The adapter's commands for one computer. Init's flags are the child's (childCommands) for both modes: --own-network
154
205
  * always, the display and the most deadline.extend may move the deadline to when given. waitS bounds a pid1 entrypoint's
155
206
  * wait for the daemon (and gate, for an Archil computer); with atomic, install moves the daemon into place last, and only
156
- * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for. vendorSockets
157
- * (HostFacts') gives a child its sockets command.
207
+ * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for. sockets are
208
+ * the patterns a child's sockets command closes (default SESSION_BUSES); rootOnly the paths its root-only command takes
209
+ * others' write off (default none).
158
210
  */
159
- export function hostedCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "", atomic = false, waitS = 600, gate, sha256 = "", nonce = "", vendorSockets = [], } = {}) {
160
- const init = [DAEMON_IN_COMPUTER, deadline, user, WORK, SOCKET_DIR];
161
- if (display !== "" || maxDeadline !== "")
162
- init.push(display, maxDeadline);
163
- const initArgs = ["init", "--deadline", deadline, "--user", user, "--own-network", ...(maxDeadline === "" ? [] : ["--max-deadline", maxDeadline])];
211
+ export function hostedCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "", atomic = false, waitS = 600, gate, sha256 = "", nonce = "", sockets = SESSION_BUSES, rootOnly = [], network = "", } = {}) {
212
+ const init = initScriptArgs({ deadline, user, display, maxDeadline, network });
213
+ const initArgs = ["init", "--deadline", deadline, "--user", user, "--own-network", ...(maxDeadline === "" ? [] : ["--max-deadline", maxDeadline]), ...(network === "" ? [] : ["--network", network])];
164
214
  return {
165
215
  install: argvOf(INSTALL_SCRIPT, [staging, DAEMON_IN_COMPUTER, WORK, SOCKET_DIR, ...(atomic ? ["1", sha256, nonce] : [])]),
166
216
  start: argvOf(START_SCRIPT, [INIT_LOG, ...argvOf(INIT_SCRIPT, init)]),
167
217
  stdio: argvOf(STDIO_SCRIPT, [DAEMON_IN_COMPUTER, SOCKET_DIR]),
168
218
  log: argvOf(LOG_SCRIPT, [INIT_LOG]),
169
- ...(vendorSockets.length === 0 ? {} : { sockets: argvOf(SOCKETS_SCRIPT, vendorSockets) }),
219
+ sockets: argvOf(SOCKETS_SCRIPT, sockets),
220
+ rootOnly: argvOf(ROOT_ONLY_SCRIPT, rootOnly),
170
221
  entrypoint: argvOf(ENTRYPOINT_SCRIPT, [DAEMON_IN_COMPUTER, String(waitS), WORK, display, nonce, ...(gate === undefined ? [] : ["--gate", gate]), ...initArgs]),
171
222
  };
172
223
  }
224
+ /** The init script's arguments: the daemon, the deadline, the user, home and the socket's folder, then the display, the
225
+ * maximum and the network form, each empty when not given, where any of them is. */
226
+ function initScriptArgs({ deadline = "", user = TOOL_USER, display = "", maxDeadline = "", network = "" }) {
227
+ const init = [DAEMON_IN_COMPUTER, deadline, user, WORK, SOCKET_DIR];
228
+ if (network !== "")
229
+ init.push(display, maxDeadline, network);
230
+ else if (display !== "" || maxDeadline !== "")
231
+ init.push(display, maxDeadline);
232
+ return init;
233
+ }
173
234
  /**
174
235
  * The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
175
236
  * its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
176
237
  * every argument quoted.
177
238
  */
178
- export function childCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "" } = {}) {
179
- const init = [DAEMON_IN_COMPUTER, deadline, user, WORK, SOCKET_DIR];
180
- if (display !== "" || maxDeadline !== "")
181
- init.push(display, maxDeadline);
239
+ export function childCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "", network = "" } = {}) {
240
+ const init = initScriptArgs({ deadline, user, display, maxDeadline, network });
182
241
  return {
183
242
  install: shellCommand(INSTALL_SCRIPT, [staging, DAEMON_IN_COMPUTER, WORK, SOCKET_DIR]),
184
243
  init: shellCommand(INIT_SCRIPT, init),
@@ -1,5 +1,5 @@
1
1
  import { Duplex } from "node:stream";
2
- import type { HostCall, MachineProcess } from "./host.js";
2
+ import type { HostCall, MachineProcess } from "../host.js";
3
3
  /** A readable side of an ssh2 channel, as this provider uses it: piped, or drained. */
4
4
  export interface Ssh2Readable {
5
5
  pipe(destination: NodeJS.WritableStream): unknown;
@@ -23,8 +23,9 @@ export interface Ssh2Channel extends Ssh2Readable {
23
23
  /** The options of ssh2's Client.connect this provider gives (ssh2@1.17.0 lib/client.js). */
24
24
  export interface Ssh2ConnectConfig {
25
25
  sock: Duplex;
26
- username: "root";
27
- privateKey: string;
26
+ username: string;
27
+ privateKey?: string;
28
+ password?: string;
28
29
  readyTimeout: number;
29
30
  keepaliveInterval: number;
30
31
  keepaliveCountMax: number;
@@ -59,22 +60,31 @@ export interface SshTunnel {
59
60
  }
60
61
  /** How a vendor opens the stream to machine id's sshd: a fresh one per call, nothing started before it is used. */
61
62
  export type SshTunnelOf = (id: string) => SshTunnel;
63
+ /** How a host logs in to a machine's sshd: as root (MachineHost.exec's user), by a key or a password. */
64
+ export interface SshLogin {
65
+ username: string;
66
+ /** A private key in the PEM armor ssh2 reads (see pemOf). */
67
+ privateKey?: string;
68
+ password?: string;
69
+ /** What no error may carry, beside the key and the password, which never do: a key inside the username (Morph's). */
70
+ secrets?: readonly string[];
71
+ }
62
72
  export interface SshExecOptions {
63
73
  /** The host's own ssh2 package, or anything with the same slice. */
64
74
  ssh2: Ssh2Module;
65
- /** A private key in the PEM armor ssh2 reads (see pemOf). */
66
- privateKey: string;
75
+ /** The login to machine id. */
76
+ loginOf: (id: string) => SshLogin;
67
77
  tunnelOf: SshTunnelOf;
68
78
  }
69
- /** MachineHost.exec over SSH: argv as root, as channels on one connection per machine, shared by its execs. */
79
+ /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
70
80
  export declare class SshExec {
71
81
  #private;
72
- constructor({ ssh2, privateKey, tunnelOf }: SshExecOptions);
82
+ constructor({ ssh2, loginOf, tunnelOf }: SshExecOptions);
73
83
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
74
84
  closeAll(id: string): void;
75
85
  /**
76
- * argv as root over SSH, under WRAPPER, as one channel on the machine's shared connection (#start). stdout and
77
- * stderr are the channel's, piped; end sends end of file. wait answers once the channel closes, with the
86
+ * argv as the host's login over SSH, under WRAPPER, as one channel on the machine's shared connection (#start).
87
+ * stdout and stderr are the channel's, piped; end sends end of file. wait answers once the channel closes, with the
78
88
  * exit-status, or -1 for an exit by signal or none. kill ends the process group over a channel of its own (on a
79
89
  * connection with room), then closes the exec's channel, never a connection; if the close does not come, wait
80
90
  * answers -1 and the connection takes no new channel.
@@ -1,11 +1,12 @@
1
- // Agent37's SSH exec: its instances are reached over SSH (as root, one connection per process, under a wrapper that
2
- // names the process group), through the stream agent37.ts gives to each instance's sshd (its WebSocket tunnel), and
3
- // this is its MachineHost.exec. The host's own ssh2 package does the protocol; this package names only the slice it
4
- // uses (Ssh2Module) and imports nothing at load.
1
+ // MachineHost.exec over SSH, for a vendor whose machines run an sshd: one connection per machine shared by its execs,
2
+ // each process under a wrapper that names its process group, through the stream the host gives to the machine's sshd
3
+ // (Agent37's WebSocket tunnel) and as the login the host gives (Agent37's root and key). Every error it throws or
4
+ // rejects with is redacted of the login's secrets. The host's own ssh2 package does the protocol; this package names
5
+ // only the slice it uses (Ssh2Module) and imports nothing at load.
5
6
  import { randomBytes } from "node:crypto";
6
7
  import { PassThrough } from "node:stream";
7
- import { boundOf } from "./hosted/process.js";
8
- import { shellLine } from "./hosted/scripts.js";
8
+ import { boundOf, redact } from "./process.js";
9
+ import { shellLine } from "./scripts.js";
9
10
  /**
10
11
  * ssh2's keepalive, which also keeps the edge from seeing an idle tunnel (the CLI's ServerAliveInterval is 60 s, cli.js:32).
11
12
  * ssh2 pings every KEEPALIVE_MS and ends the connection at the tick after KEEPALIVE_COUNT_MAX pings went unanswered
@@ -66,19 +67,19 @@ const isBound = (error) => {
66
67
  const name = error?.name;
67
68
  return name === "TimeoutError" || name === "AbortError";
68
69
  };
69
- /** MachineHost.exec over SSH: argv as root, as channels on one connection per machine, shared by its execs. */
70
+ /** MachineHost.exec over SSH: argv as the host's login, as channels on one connection per machine, shared by its execs. */
70
71
  export class SshExec {
71
72
  #ssh2;
72
- #privateKey;
73
+ #loginOf;
73
74
  #tunnelOf;
74
75
  /**
75
76
  * The SSH connections to each machine, opening, open, or done and still held, until each ends: one, and a second
76
77
  * past CHANNELS_PER_CONNECTION channels. A done one takes no new channel; closeAll ends them all.
77
78
  */
78
79
  #links = new Map();
79
- constructor({ ssh2, privateKey, tunnelOf }) {
80
+ constructor({ ssh2, loginOf, tunnelOf }) {
80
81
  this.#ssh2 = ssh2;
81
- this.#privateKey = privateKey;
82
+ this.#loginOf = loginOf;
82
83
  this.#tunnelOf = tunnelOf;
83
84
  }
84
85
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
@@ -87,10 +88,11 @@ export class SshExec {
87
88
  this.#end(link);
88
89
  }
89
90
  /**
90
- * An SSH session as root over the instance's tunnel, its handshake within ctx. A tunnel that fails to open, or closes
91
- * before the SSH handshake, is opened again after a pause, TUNNEL_TRIES times in all within ctx: an instance fresh
92
- * from its create can refuse the first (seen live once in eight creates, the daemon's upload refused). Nothing has
93
- * run before a handshake, so a retry repeats nothing. A refused key or a handshake past its bound is not retried.
91
+ * An SSH session as the host's login over the machine's tunnel, its handshake within ctx. A tunnel that fails to
92
+ * open, or closes before the SSH handshake, is opened again after a pause, TUNNEL_TRIES times in all within ctx: an
93
+ * instance fresh from its create can refuse the first (seen live once in eight creates, the daemon's upload
94
+ * refused). Nothing has run before a handshake, so a retry repeats nothing. A refused key or a handshake past its
95
+ * bound is not retried.
94
96
  */
95
97
  async #ssh(id, ctx) {
96
98
  const bound = boundOf(ctx.timeoutMs, ctx.signal, `the SSH connection to ${id}`);
@@ -136,13 +138,14 @@ export class SshExec {
136
138
  quit(givenUp());
137
139
  };
138
140
  stop.addEventListener("abort", drop, { once: true });
141
+ const { username, privateKey, password } = this.#loginOf(id);
139
142
  try {
140
143
  await Promise.race([opened, quitted]);
141
144
  await Promise.race([
142
145
  new Promise((resolve, reject) => {
143
146
  client.once("ready", resolve);
144
147
  client.once("error", reject);
145
- client.connect({ sock: duplex, username: "root", privateKey: this.#privateKey, readyTimeout: timeoutMs, keepaliveInterval: KEEPALIVE_MS, keepaliveCountMax: KEEPALIVE_COUNT_MAX });
148
+ client.connect({ sock: duplex, username, privateKey, password, readyTimeout: timeoutMs, keepaliveInterval: KEEPALIVE_MS, keepaliveCountMax: KEEPALIVE_COUNT_MAX });
146
149
  }),
147
150
  quitted,
148
151
  ]);
@@ -333,15 +336,31 @@ export class SshExec {
333
336
  }
334
337
  }
335
338
  /**
336
- * argv as root over SSH, under WRAPPER, as one channel on the machine's shared connection (#start). stdout and
337
- * stderr are the channel's, piped; end sends end of file. wait answers once the channel closes, with the
339
+ * error with machine id's login secrets taken out of its message and stack, in place: its class, name and fields stay,
340
+ * which the adapter reads its code by. ssh2's words can carry the username, and a host's may hold a key.
341
+ */
342
+ #redacted(id, error) {
343
+ const { privateKey, password, secrets = [] } = this.#loginOf(id);
344
+ const hidden = [privateKey, password, ...secrets];
345
+ if (!(error instanceof Error))
346
+ return new Error(redact(String(error), hidden));
347
+ error.message = redact(error.message, hidden);
348
+ if (error.stack !== undefined)
349
+ error.stack = redact(error.stack, hidden);
350
+ return error;
351
+ }
352
+ /**
353
+ * argv as the host's login over SSH, under WRAPPER, as one channel on the machine's shared connection (#start).
354
+ * stdout and stderr are the channel's, piped; end sends end of file. wait answers once the channel closes, with the
338
355
  * exit-status, or -1 for an exit by signal or none. kill ends the process group over a channel of its own (on a
339
356
  * connection with room), then closes the exec's channel, never a connection; if the close does not come, wait
340
357
  * answers -1 and the connection takes no new channel.
341
358
  */
342
359
  async exec(id, argv, ctx) {
343
360
  const pidFile = `/tmp/.agentrun-exec-${randomBytes(8).toString("hex")}`;
344
- const opened = await this.#start(id, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx, `the exec in ${id}`);
361
+ const opened = await this.#start(id, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx, `the exec in ${id}`).catch((error) => {
362
+ throw this.#redacted(id, error);
363
+ });
345
364
  const { link: held, channel } = opened;
346
365
  const stdout = new PassThrough();
347
366
  const stderr = new PassThrough();
@@ -367,7 +386,7 @@ export class SshExec {
367
386
  write: (bytes) => new Promise((resolve, reject) => {
368
387
  if (ended || closed)
369
388
  return reject(new Error(ended ? "stdin was ended" : "the process has ended"));
370
- channel.write(bytes, (error) => (error ? reject(error) : resolve()));
389
+ channel.write(bytes, (error) => (error ? reject(this.#redacted(id, error)) : resolve()));
371
390
  }),
372
391
  end: async () => {
373
392
  if (ended || closed)
@@ -1,5 +1,26 @@
1
+ import type { HostFacts } from "../host.js";
2
+ import type { ComputerSpec, Refusal } from "../provider.js";
1
3
  /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
2
4
  export declare const DOMAIN: RegExp;
3
5
  export declare const isWhole: (value: unknown) => value is number;
6
+ /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
7
+ export declare function sizeRefusals(spec: Partial<ComputerSpec>, computer: string, image: string): Refusal[];
4
8
  /** A time the vendor reports: a Date, an ISO string, or a whole number of ms (or seconds); undefined when it is none of them. */
5
9
  export declare function dateOf(value: unknown, unit?: "ms" | "s"): Date | undefined;
10
+ /** The label a packed machine is listed by (packLabels): its value is the machine's name, MachineRequest.name. */
11
+ export declare const PACKED_NAME = "agentrun";
12
+ /**
13
+ * A machine's labels as a vendor whose labels can't hold them as they are stores them (facts.labels.packed): a cap of 5
14
+ * tags, Kubernetes' values, Cloudflare's 16-byte names, a list of strings. PACKED_NAME, the one label a host's list
15
+ * filters on, holds name; the whole map, as JSON, deflated and base64url, goes in parts of at most valueBytes. Every name
16
+ * is at most 11 bytes of [a-z0-9-], every value [A-Za-z0-9_-] with a letter or digit at each end, and no "=", so a
17
+ * host of a string list stores each as name=value. unpackLabels reads the map back exactly. A map that does not fit
18
+ * room (count, bytes and valueBytes, of the packed labels), or whose JSON is past PACKED_JSON_MAX, is refused in words.
19
+ */
20
+ export declare function packLabels(labels: Record<string, string>, name: string, room?: Exclude<HostFacts["labels"], "machine">): {
21
+ labels: Record<string, string>;
22
+ } | {
23
+ problem: string;
24
+ };
25
+ /** The labels packLabels packed in stored, exactly; undefined where stored holds no packed map (a machine not the adapter's). */
26
+ export declare function unpackLabels(stored: Record<string, string>): Record<string, string> | undefined;