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

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 (96) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +285 -28
  3. package/box/Dockerfile +6 -4
  4. package/box/README.md +10 -2
  5. package/box/build-daytona.py +3 -1
  6. package/box/build-e2b.mjs +1 -1
  7. package/box/install.sh +68 -7
  8. package/dist/attach.d.ts +46 -1
  9. package/dist/attach.js +48 -4
  10. package/dist/box-image.d.ts +1 -1
  11. package/dist/box-image.js +1 -1
  12. package/dist/boxd.d.ts +126 -0
  13. package/dist/boxd.js +418 -0
  14. package/dist/cloudflare.d.ts +32 -0
  15. package/dist/cloudflare.js +179 -0
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +2 -2
  19. package/dist/conformance/boxd.d.ts +77 -0
  20. package/dist/conformance/boxd.js +113 -0
  21. package/dist/conformance/cases/isolation.js +1 -17
  22. package/dist/conformance/cases/provider.js +42 -26
  23. package/dist/conformance/cli.js +4 -1
  24. package/dist/conformance/cloudflare.d.ts +42 -0
  25. package/dist/conformance/cloudflare.js +54 -0
  26. package/dist/conformance/daytona.d.ts +25 -0
  27. package/dist/conformance/daytona.js +26 -1
  28. package/dist/conformance/dial-only.d.ts +6 -0
  29. package/dist/conformance/dial-only.js +9 -0
  30. package/dist/conformance/e2b.d.ts +12 -3
  31. package/dist/conformance/e2b.js +21 -4
  32. package/dist/conformance/exec-stream.js +14 -6
  33. package/dist/conformance/fly.d.ts +52 -0
  34. package/dist/conformance/fly.js +52 -0
  35. package/dist/conformance/modal.d.ts +15 -2
  36. package/dist/conformance/modal.js +36 -3
  37. package/dist/conformance/morph.d.ts +59 -0
  38. package/dist/conformance/morph.js +95 -0
  39. package/dist/conformance/phone-harness.js +2 -2
  40. package/dist/conformance/runner.js +5 -1
  41. package/dist/conformance/sweep.d.ts +1 -1
  42. package/dist/conformance/sweep.js +1 -1
  43. package/dist/conformance/types.d.ts +21 -0
  44. package/dist/daytona.d.ts +8 -1
  45. package/dist/daytona.js +124 -101
  46. package/dist/descriptor.d.ts +22 -1
  47. package/dist/descriptor.js +18 -0
  48. package/dist/descriptors/boxd.d.ts +52 -0
  49. package/dist/descriptors/boxd.js +29 -0
  50. package/dist/descriptors/cloudflare.d.ts +21 -0
  51. package/dist/descriptors/cloudflare.js +29 -0
  52. package/dist/descriptors/daytona.d.ts +12 -3
  53. package/dist/descriptors/daytona.js +15 -7
  54. package/dist/descriptors/e2b.d.ts +4 -0
  55. package/dist/descriptors/e2b.js +3 -0
  56. package/dist/descriptors/fly.d.ts +19 -0
  57. package/dist/descriptors/fly.js +28 -0
  58. package/dist/descriptors/index.d.ts +121 -2
  59. package/dist/descriptors/index.js +7 -2
  60. package/dist/descriptors/modal.d.ts +3 -0
  61. package/dist/descriptors/modal.js +7 -2
  62. package/dist/descriptors/morph.d.ts +15 -0
  63. package/dist/descriptors/morph.js +21 -0
  64. package/dist/descriptors/phone-harness.d.ts +1 -0
  65. package/dist/descriptors/phone-harness.js +2 -0
  66. package/dist/e2b.d.ts +7 -1
  67. package/dist/e2b.js +87 -44
  68. package/dist/fly.d.ts +43 -0
  69. package/dist/fly.js +245 -0
  70. package/dist/host.d.ts +52 -48
  71. package/dist/hosted/framed-exec.d.ts +8 -19
  72. package/dist/hosted/framed-exec.js +21 -87
  73. package/dist/hosted/process.d.ts +21 -0
  74. package/dist/hosted/process.js +37 -2
  75. package/dist/hosted/provider.d.ts +32 -6
  76. package/dist/hosted/provider.js +239 -236
  77. package/dist/hosted/rest.d.ts +19 -0
  78. package/dist/hosted/rest.js +76 -0
  79. package/dist/hosted/scripts.d.ts +52 -8
  80. package/dist/hosted/scripts.js +118 -23
  81. package/dist/hosted/ssh-exec.d.ts +9 -7
  82. package/dist/hosted/ssh-exec.js +93 -54
  83. package/dist/hosted/values.d.ts +5 -0
  84. package/dist/hosted/values.js +9 -0
  85. package/dist/index.d.ts +3 -3
  86. package/dist/index.js +4 -4
  87. package/dist/kinds.d.ts +2 -0
  88. package/dist/modal.d.ts +6 -0
  89. package/dist/modal.js +40 -17
  90. package/dist/morph.d.ts +65 -0
  91. package/dist/morph.js +495 -0
  92. package/dist/phone-harness.d.ts +15 -5
  93. package/dist/phone-harness.js +50 -15
  94. package/dist/providers.d.ts +4 -2
  95. package/dist/screen-watch.js +2 -2
  96. package/package.json +20 -2
@@ -70,6 +70,25 @@ export interface Rest {
70
70
  stream(method: string, url: string, init?: RestInit, signal?: AbortSignal): Promise<Result<RestStream>>;
71
71
  }
72
72
  export declare function rest(options: RestOptions): Rest;
73
+ /** The JSON value of each line of a body of newline-delimited JSON, as the lines come; a line that is not JSON throws. */
74
+ export declare function ndjson(body: AsyncIterable<Uint8Array>): AsyncIterable<unknown>;
75
+ /** One event of a text/event-stream body: its type, its data, and the last id and retry the stream had set by then. */
76
+ export interface SseEvent {
77
+ /** "message" unless an `event:` field named it. */
78
+ event: string;
79
+ /** Its `data:` fields, joined by "\n". */
80
+ data: string;
81
+ /** The last `id:` so far ("" for none): what a host that resumes a dropped stream asks from. */
82
+ id: string;
83
+ /** The last `retry:` so far, the ms the vendor asks a reconnect to wait. */
84
+ retry?: number;
85
+ }
86
+ /**
87
+ * The events of a body of server-sent events (text/event-stream), as they come, read as the HTML standard's event
88
+ * stream says: lines end at \r\n, \n or \r; a line that starts with ":" is a comment (a vendor's keep-alive); a blank
89
+ * line ends an event, and one with no data is none. An event the body ends inside is dropped.
90
+ */
91
+ export declare function sse(body: AsyncIterable<Uint8Array>): AsyncGenerator<SseEvent, void, undefined>;
73
92
  /**
74
93
  * Every item of a paged listing. next gets the cursor of the page to read (none for the first) and answers its items and
75
94
  * the cursor of the page after it, or nothing at the end. A cursor that comes back twice, or a listing past max pages,
@@ -109,6 +109,82 @@ export function rest(options) {
109
109
  stream: (method, url, init = {}, signal) => exchange(method, url, init, signal, async (response) => ({ status: response.status, body: response.body ?? NO_BODY })),
110
110
  };
111
111
  }
112
+ /** The JSON value of each line of a body of newline-delimited JSON, as the lines come; a line that is not JSON throws. */
113
+ export async function* ndjson(body) {
114
+ const decoder = new TextDecoder();
115
+ let rest = "";
116
+ for await (const chunk of body) {
117
+ rest += decoder.decode(chunk, { stream: true });
118
+ let at = rest.indexOf("\n");
119
+ while (at >= 0) {
120
+ const line = rest.slice(0, at).trim();
121
+ rest = rest.slice(at + 1);
122
+ if (line !== "")
123
+ yield JSON.parse(line);
124
+ at = rest.indexOf("\n");
125
+ }
126
+ }
127
+ rest += decoder.decode();
128
+ if (rest.trim() !== "")
129
+ yield JSON.parse(rest);
130
+ }
131
+ /**
132
+ * The events of a body of server-sent events (text/event-stream), as they come, read as the HTML standard's event
133
+ * stream says: lines end at \r\n, \n or \r; a line that starts with ":" is a comment (a vendor's keep-alive); a blank
134
+ * line ends an event, and one with no data is none. An event the body ends inside is dropped.
135
+ */
136
+ export async function* sse(body) {
137
+ // Not ignoreBOM: the standard drops a U+FEFF that starts the stream.
138
+ const decoder = new TextDecoder();
139
+ let rest = "";
140
+ let data = [];
141
+ let event = "";
142
+ let id = "";
143
+ let retry;
144
+ // The last line ended at a \r that ended what came: a \n that starts what comes next is that \r's, no line of its own.
145
+ let halfCrLf = false;
146
+ const eol = /\r\n|\r|\n/g;
147
+ function* lines(text) {
148
+ if (halfCrLf && text !== "") {
149
+ if (text.startsWith("\n"))
150
+ text = text.slice(1);
151
+ halfCrLf = false;
152
+ }
153
+ // What is left from before holds no line end: the search starts at what came.
154
+ eol.lastIndex = rest.length;
155
+ rest += text;
156
+ let from = 0;
157
+ for (let end = eol.exec(rest); end !== null; end = eol.exec(rest)) {
158
+ const line = rest.slice(from, end.index);
159
+ from = eol.lastIndex;
160
+ halfCrLf = end[0] === "\r" && from === rest.length;
161
+ if (line === "") {
162
+ if (data.length > 0)
163
+ yield { event: event || "message", data: data.join("\n"), id, ...(retry === undefined ? {} : { retry }) };
164
+ data = [];
165
+ event = "";
166
+ continue;
167
+ }
168
+ if (line.startsWith(":"))
169
+ continue;
170
+ const colon = line.indexOf(":");
171
+ const field = colon < 0 ? line : line.slice(0, colon);
172
+ const value = colon < 0 ? "" : line.slice(line[colon + 1] === " " ? colon + 2 : colon + 1);
173
+ if (field === "data")
174
+ data.push(value);
175
+ else if (field === "event")
176
+ event = value;
177
+ else if (field === "id" && !value.includes("\0"))
178
+ id = value;
179
+ else if (field === "retry" && /^[0-9]+$/.test(value))
180
+ retry = Number(value);
181
+ }
182
+ rest = rest.slice(from);
183
+ }
184
+ for await (const chunk of body)
185
+ yield* lines(decoder.decode(chunk, { stream: true }));
186
+ yield* lines(decoder.decode());
187
+ }
112
188
  /**
113
189
  * Every item of a paged listing. next gets the cursor of the page to read (none for the first) and answers its items and
114
190
  * the cursor of the page after it, or nothing at the end. A cursor that comes back twice, or a listing past max pages,
@@ -1,3 +1,4 @@
1
+ import { PassThrough } from "node:stream";
1
2
  import type { ComputerCapabilities, ComputerConnection } from "../provider.js";
2
3
  import { type Result } from "../result.js";
3
4
  /** Who ran install, from its output's `installer <uid> <name>[ sudo]` line, in words; undefined when it has none. */
@@ -6,6 +7,8 @@ export declare function installerOf(output: string): string | undefined;
6
7
  export declare const shellCommand: (script: string, args: readonly string[]) => string;
7
8
  /** One argv as one shell line, every word but a plain one ("sh", "-c") single-quoted: for a vendor whose exec takes a line. */
8
9
  export declare const shellLine: (argv: readonly string[]) => string;
10
+ /** The box image's agentrun-dial (box/install.sh): what a dial machine runs first, from MachineRequest.boot.env. */
11
+ export declare const AGENTRUN_DIAL = "/usr/local/bin/agentrun-dial";
9
12
  /** Where start leaves what init writes, root's alone: the words a create that never hears the daemon gives back. */
10
13
  export declare const INIT_LOG = "/run/agentrun-init.log";
11
14
  /**
@@ -16,14 +19,6 @@ export declare const INIT_LOG = "/run/agentrun-init.log";
16
19
  export declare const SESSION_BUSES: readonly string[];
17
20
  /** The sockets the sockets script closed, from its `closed <path>` lines. */
18
21
  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[];
27
22
  /**
28
23
  * Where a pid1 Archil computer's entrypoint waits for root's word that the run's folder is mounted: beside the daemon,
29
24
  * in the directory install makes root's alone before root makes the gate, so no other user can make it early. (A path
@@ -75,6 +70,12 @@ export interface ChildCommandOptions {
75
70
  /** The network form init's egress proxy serves (./network.ts networkFormOf): open, or allow: and a list; none, no proxy. */
76
71
  network?: string;
77
72
  }
73
+ /**
74
+ * init's flags, as start and a pid1 entrypoint give them: the deadline, the user, --own-network, and the most
75
+ * deadline.extend may move it to and the network form where given. A dial machine's AGENTRUN_INIT_ARGS, space-separated:
76
+ * no value holds a space.
77
+ */
78
+ export declare function initFlags({ deadline, user, maxDeadline, network }: Omit<ChildCommandOptions, "staging" | "display">): string[];
78
79
  /**
79
80
  * The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
80
81
  * its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
@@ -100,3 +101,46 @@ export interface DaemonExpected {
100
101
  * working directory and binary. Each read is bounded by timeoutMs and the caller's signal.
101
102
  */
102
103
  export declare function daemonDrift(connection: ComputerConnection, expected: DaemonExpected, timeoutMs: number, signal?: AbortSignal): Promise<Result<string[]>>;
104
+ /**
105
+ * The sh a process starts under where the vendor has no kill that ends it (framedExec with no kill, SSH, Modal): one
106
+ * line on stderr, its pid and its start time (field 22 of /proc/<pid>/stat, counted past the command's name in
107
+ * parentheses, which may hold spaces), then the command in its place, which keeps both. pidLine takes the line off.
108
+ */
109
+ export declare const PID_WRAPPER: string[];
110
+ /**
111
+ * The sh pidKill starts, given the pid and start time: a pid whose process has ended, and may be another's now, is let
112
+ * be. Otherwise it kills the process and every process under it (an upload's head and base64 would wait on the open
113
+ * stdin, and hold stderr open, past their sh; a child that left the process group too): each is stopped as it is found,
114
+ * so none forks away, by its parent pid (field 4 of its stat) until a pass over /proc finds no more, and then all are
115
+ * killed. When the pid leads its own process group (field 5), as a command an sshd starts does, every process in that
116
+ * group is taken too: a background job whose parent exited is under no process the walk finds, but still in the group.
117
+ * A pid that leads no group of its own is let be past its tree, so a kill never reaches what it didn't start.
118
+ */
119
+ export declare const PID_KILL: string;
120
+ /** A process's pid and start time, from PID_WRAPPER's line. */
121
+ export interface PidOf {
122
+ pid: string;
123
+ start: string;
124
+ }
125
+ /** The argv that kills a process started under PID_WRAPPER, and every process under it, while its pid has that start time. */
126
+ export declare const pidKill: ({ pid, start }: PidOf) => string[];
127
+ /** What pidLine and pidStderr answer: the pid and start time once the line ends, waited for at most ms. */
128
+ export type PidWithin = (ms: number) => Promise<PidOf | undefined>;
129
+ /**
130
+ * PID_WRAPPER's line taken off a process's stderr: take() is given each piece of stderr and answers what of it is the
131
+ * process's own (nothing while the line has not ended). pid answers once the line ends; undefined for a line that is
132
+ * no pid and start time, once end() came first (the stream ended), or past ms.
133
+ */
134
+ export declare function pidLine(): {
135
+ take(bytes: Uint8Array): Buffer;
136
+ end(): void;
137
+ pid: PidWithin;
138
+ };
139
+ /**
140
+ * A stream's stderr with PID_WRAPPER's line taken off (pidLine), read from its start whether or not anyone reads what
141
+ * it passes on, so the pid comes; the rest waits for its reader.
142
+ */
143
+ export declare function pidStderr(source: AsyncIterable<Uint8Array>): {
144
+ stderr: PassThrough;
145
+ pid: PidWithin;
146
+ };
@@ -4,6 +4,7 @@
4
4
  // a pid1 host's machine runs the entrypoint as its main process, which waits for the daemon and becomes init. Every
5
5
  // connection runs stdio. Each is one argv, `sh -c '<script>' sh <args>`; shellCommand gives it as one string for a
6
6
  // vendor whose exec takes a shell line.
7
+ import { PassThrough } from "node:stream";
7
8
  import { DAEMON_IN_COMPUTER, helloDrift, SOCKET_DIR, WORK } from "../drift.js";
8
9
  import { readOwnNetwork, TOOL_USER } from "../isolation.js";
9
10
  import { fail, ok } from "../result.js";
@@ -83,6 +84,8 @@ export const shellCommand = (script, args) => ["sh", "-c", quote(script), "sh",
83
84
  /** One argv as one shell line, every word but a plain one ("sh", "-c") single-quoted: for a vendor whose exec takes a line. */
84
85
  export const shellLine = (argv) => argv.map((word) => (/^[A-Za-z0-9_./:=@%+-]+$/.test(word) ? word : quote(word))).join(" ");
85
86
  const argvOf = (script, args) => ["sh", "-c", script, "sh", ...args];
87
+ /** The box image's agentrun-dial (box/install.sh): what a dial machine runs first, from MachineRequest.boot.env. */
88
+ export const AGENTRUN_DIAL = "/usr/local/bin/agentrun-dial";
86
89
  /** Where start leaves what init writes, root's alone: the words a create that never hears the daemon gives back. */
87
90
  export const INIT_LOG = `${SOCKET_DIR}-init.log`;
88
91
  /**
@@ -142,28 +145,6 @@ export function closedSocketsOf(output) {
142
145
  }
143
146
  /** The last words init wrote to its log, as root; nothing when it wrote none. */
144
147
  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)])]);
167
148
  /**
168
149
  * A pid1 machine's main process: waits, bounded, for the daemon this create installed to be moved into place executable
169
150
  * (the marker beside it, `<daemon>.installed`, holds this create's nonce: a daemon the image had at the path, or one an
@@ -210,7 +191,7 @@ export const ARCHIL_GATE = `${DAEMON_IN_COMPUTER.slice(0, DAEMON_IN_COMPUTER.las
210
191
  */
211
192
  export function hostedCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "", atomic = false, waitS = 600, gate, sha256 = "", nonce = "", sockets = SESSION_BUSES, rootOnly = [], network = "", } = {}) {
212
193
  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])];
194
+ const initArgs = ["init", ...initFlags({ deadline, user, maxDeadline, network })];
214
195
  return {
215
196
  install: argvOf(INSTALL_SCRIPT, [staging, DAEMON_IN_COMPUTER, WORK, SOCKET_DIR, ...(atomic ? ["1", sha256, nonce] : [])]),
216
197
  start: argvOf(START_SCRIPT, [INIT_LOG, ...argvOf(INIT_SCRIPT, init)]),
@@ -221,6 +202,14 @@ export function hostedCommands({ staging = "", deadline = "", user = TOOL_USER,
221
202
  entrypoint: argvOf(ENTRYPOINT_SCRIPT, [DAEMON_IN_COMPUTER, String(waitS), WORK, display, nonce, ...(gate === undefined ? [] : ["--gate", gate]), ...initArgs]),
222
203
  };
223
204
  }
205
+ /**
206
+ * init's flags, as start and a pid1 entrypoint give them: the deadline, the user, --own-network, and the most
207
+ * deadline.extend may move it to and the network form where given. A dial machine's AGENTRUN_INIT_ARGS, space-separated:
208
+ * no value holds a space.
209
+ */
210
+ export function initFlags({ deadline = "", user = TOOL_USER, maxDeadline = "", network = "" }) {
211
+ return ["--deadline", deadline, "--user", user, "--own-network", ...(maxDeadline === "" ? [] : ["--max-deadline", maxDeadline]), ...(network === "" ? [] : ["--network", network])];
212
+ }
224
213
  /** The init script's arguments: the daemon, the deadline, the user, home and the socket's folder, then the display, the
225
214
  * maximum and the network form, each empty when not given, where any of them is. */
226
215
  function initScriptArgs({ deadline = "", user = TOOL_USER, display = "", maxDeadline = "", network = "" }) {
@@ -301,3 +290,109 @@ export async function daemonDrift(connection, expected, timeoutMs, signal) {
301
290
  }
302
291
  return ok(found);
303
292
  }
293
+ /**
294
+ * The sh a process starts under where the vendor has no kill that ends it (framedExec with no kill, SSH, Modal): one
295
+ * line on stderr, its pid and its start time (field 22 of /proc/<pid>/stat, counted past the command's name in
296
+ * parentheses, which may hold spaces), then the command in its place, which keeps both. pidLine takes the line off.
297
+ */
298
+ export const PID_WRAPPER = ["sh", "-c", 'echo "$$ $(s=$(cat /proc/$$/stat) && set -- ${s##*") "} && echo "${20}")" >&2; exec "$@"', "sh"];
299
+ /**
300
+ * The sh pidKill starts, given the pid and start time: a pid whose process has ended, and may be another's now, is let
301
+ * be. Otherwise it kills the process and every process under it (an upload's head and base64 would wait on the open
302
+ * stdin, and hold stderr open, past their sh; a child that left the process group too): each is stopped as it is found,
303
+ * so none forks away, by its parent pid (field 4 of its stat) until a pass over /proc finds no more, and then all are
304
+ * killed. When the pid leads its own process group (field 5), as a command an sshd starts does, every process in that
305
+ * group is taken too: a background job whose parent exited is under no process the walk finds, but still in the group.
306
+ * A pid that leads no group of its own is let be past its tree, so a kill never reaches what it didn't start.
307
+ */
308
+ export const PID_KILL = [
309
+ "pid=$1 start=$2",
310
+ 'read -r s 2>/dev/null <"/proc/$pid/stat" || exit 0',
311
+ 'set -- ${s##*") "}',
312
+ '[ "${20}" = "$start" ] || exit 0',
313
+ 'group=; [ "$3" = "$pid" ] && group=$pid',
314
+ 'kill -STOP "$pid" 2>/dev/null',
315
+ 'all=" $pid " new=$pid',
316
+ 'while [ -n "$new" ]; do',
317
+ "\tnew=",
318
+ "\tfor f in /proc/[0-9]*/stat; do",
319
+ '\t\tread -r s 2>/dev/null <"$f" || continue',
320
+ "\t\tp=${s%% *}",
321
+ '\t\tset -- ${s##*") "}',
322
+ '\t\tcase "$all" in *" $p "*) continue ;; esac',
323
+ '\t\tcase "$all" in *" $2 "*) ;; *) [ -n "$group" ] && [ "$3" = "$group" ] || continue ;; esac',
324
+ '\t\tall="$all$p " new="$new $p"; kill -STOP "$p" 2>/dev/null',
325
+ "\tdone",
326
+ "done",
327
+ "kill -KILL $all 2>/dev/null",
328
+ "exit 0",
329
+ ].join("\n");
330
+ /** The argv that kills a process started under PID_WRAPPER, and every process under it, while its pid has that start time. */
331
+ export const pidKill = ({ pid, start }) => ["sh", "-c", PID_KILL, "sh", pid, start];
332
+ /**
333
+ * PID_WRAPPER's line taken off a process's stderr: take() is given each piece of stderr and answers what of it is the
334
+ * process's own (nothing while the line has not ended). pid answers once the line ends; undefined for a line that is
335
+ * no pid and start time, once end() came first (the stream ended), or past ms.
336
+ */
337
+ export function pidLine() {
338
+ let held = Buffer.alloc(0);
339
+ let got = () => { };
340
+ const found = new Promise((done) => (got = done));
341
+ return {
342
+ take(bytes) {
343
+ const piece = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
344
+ if (held === undefined)
345
+ return piece;
346
+ held = Buffer.concat([held, piece]);
347
+ const at = held.indexOf(0x0a);
348
+ if (at < 0)
349
+ return Buffer.alloc(0);
350
+ const line = /^([1-9][0-9]*) ([0-9]+)$/.exec(held.subarray(0, at).toString("latin1").trim());
351
+ got(line ? { pid: line[1], start: line[2] } : undefined);
352
+ const rest = held.subarray(at + 1);
353
+ held = undefined;
354
+ return rest;
355
+ },
356
+ end: () => got(undefined),
357
+ pid: async (ms) => {
358
+ let timer;
359
+ const late = new Promise((done) => (timer = setTimeout(() => done(undefined), ms)));
360
+ try {
361
+ return await Promise.race([found, late]);
362
+ }
363
+ finally {
364
+ clearTimeout(timer);
365
+ }
366
+ },
367
+ };
368
+ }
369
+ /**
370
+ * A stream's stderr with PID_WRAPPER's line taken off (pidLine), read from its start whether or not anyone reads what
371
+ * it passes on, so the pid comes; the rest waits for its reader.
372
+ */
373
+ export function pidStderr(source) {
374
+ const line = pidLine();
375
+ const stderr = new PassThrough().on("error", () => { });
376
+ const drained = () => new Promise((done) => {
377
+ const go = () => {
378
+ stderr.off("drain", go).off("close", go);
379
+ done();
380
+ };
381
+ stderr.on("drain", go).on("close", go);
382
+ });
383
+ void (async () => {
384
+ try {
385
+ for await (const bytes of source) {
386
+ const own = line.take(bytes);
387
+ if (own.length > 0 && !stderr.destroyed && !stderr.write(own))
388
+ await drained();
389
+ }
390
+ }
391
+ catch {
392
+ // A stream that broke ends here, as one that ended.
393
+ }
394
+ line.end();
395
+ stderr.end();
396
+ })();
397
+ return { stderr, pid: line.pid };
398
+ }
@@ -7,7 +7,7 @@ export interface Ssh2Readable {
7
7
  }
8
8
  /**
9
9
  * The slice of an ssh2 channel this provider uses (ssh2@1.17.0 lib/Channel.js): the channel is stdout. No signal
10
- * request: ssh2 sends one only while stdin is open (Channel.js:237-246), so a kill goes by the process group instead.
10
+ * request: ssh2 sends one only while stdin is open (Channel.js:237-246), so a kill goes by the pid instead (pidKill).
11
11
  */
12
12
  export interface Ssh2Channel extends Ssh2Readable {
13
13
  readonly stderr: Ssh2Readable;
@@ -83,17 +83,19 @@ export declare class SshExec {
83
83
  /** Ends every connection to machine id, channels and all: the vendor calls it once the machine is deleted. */
84
84
  closeAll(id: string): void;
85
85
  /**
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
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
89
- * connection with room), then closes the exec's channel, never a connection; if the close does not come, wait
90
- * answers -1 and the connection takes no new channel.
86
+ * argv as the host's login over SSH, under PID_WRAPPER (./scripts.ts), as one channel on the machine's shared
87
+ * connection (#start). stdout and stderr are the channel's, piped, the wrapper's line taken off stderr; end sends end
88
+ * of file. wait answers once the channel closes, with the exit-status, or -1 for an exit by signal or none. kill
89
+ * starts pidKill over a channel of its own (on a connection with room), which ends the process and every process
90
+ * under it, then closes the exec's channel, never a connection; if the close does not come, wait answers -1 and the
91
+ * connection takes no new channel.
91
92
  */
92
93
  exec(id: string, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
93
94
  }
94
95
  /**
95
96
  * A private key in the PEM armor ssh2 reads (its parser wants the BEGIN and END lines on lines of their own), or
96
97
  * undefined when text is not one. A key pasted into Settings → Computers comes back on one line, since a password
97
- * field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it.
98
+ * field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it. A PKCS#8 key
99
+ * (the PEM label "PRIVATE KEY", Morph's GET /instance/{id}/ssh/key) is converted (fromPkcs8).
98
100
  */
99
101
  export declare function pemOf(text: string): string | undefined;
@@ -1,12 +1,12 @@
1
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
2
+ // each process under the wrapper that names its pid (./scripts.ts, PID_WRAPPER), through the stream the host gives to
3
+ // the machine's sshd (Agent37's WebSocket tunnel) and as the login the host gives (Agent37's root and key). Every error it throws or
4
4
  // rejects with is redacted of the login's secrets. The host's own ssh2 package does the protocol; this package names
5
5
  // only the slice it uses (Ssh2Module) and imports nothing at load.
6
- import { randomBytes } from "node:crypto";
6
+ import { createPrivateKey, randomBytes } from "node:crypto";
7
7
  import { PassThrough } from "node:stream";
8
8
  import { boundOf, redact } from "./process.js";
9
- import { shellLine } from "./scripts.js";
9
+ import { PID_WRAPPER, pidKill, pidStderr, shellLine } from "./scripts.js";
10
10
  /**
11
11
  * ssh2's keepalive, which also keeps the edge from seeing an idle tunnel (the CLI's ServerAliveInterval is 60 s, cli.js:32).
12
12
  * ssh2 pings every KEEPALIVE_MS and ends the connection at the tick after KEEPALIVE_COUNT_MAX pings went unanswered
@@ -35,26 +35,6 @@ const CHANNELS_PER_CONNECTION = 10;
35
35
  * socket are both referenced), so the wait is short: a process that is done with its computers exits at most this late.
36
36
  */
37
37
  const IDLE_MS = 2_000;
38
- /**
39
- * Every command runs under this sh, which writes its pid to $0 first and removes the file when the command ends. The
40
- * instance's sshd starts each command as a session and group leader (seen live: sh's PID, PGID and SID are one), so
41
- * the pid names the group a kill ends; ssh2 sends no signal once stdin has ended, and a signal ends one process only.
42
- */
43
- const WRAPPER = '{ echo $$ > "$0"; } 2>/dev/null; "$@"; c=$?; rm -f "$0"; exit $c';
44
- /**
45
- * The kill: waits up to a second for the pid file, then kills the group when the pid leads one (the process alone
46
- * otherwise, so a kill never reaches past what it started) and removes the file.
47
- */
48
- const KILL_SCRIPT = [
49
- "i=0",
50
- 'while [ ! -s "$0" ] && [ $i -lt 10 ]; do sleep 0.1; i=$((i+1)); done',
51
- 'p=$(cat "$0" 2>/dev/null); rm -f "$0"',
52
- '[ -n "$p" ] || exit 0',
53
- 'g=$(cut -d" " -f5 "/proc/$p/stat" 2>/dev/null)',
54
- // No "--": dash's kill reads it as a pid (seen live: "Illegal number: -").
55
- 'if [ "$g" = "$p" ]; then kill -KILL "-$p"; else kill -KILL "$p"; fi 2>/dev/null',
56
- "exit 0",
57
- ].join("\n");
58
38
  /** A tunnel failed before its SSH handshake, or while it carried the stream: the one failure a retry may repeat. */
59
39
  export class SshTunnelError extends Error {
60
40
  name = "SshTunnelError";
@@ -350,22 +330,23 @@ export class SshExec {
350
330
  return error;
351
331
  }
352
332
  /**
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
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
356
- * connection with room), then closes the exec's channel, never a connection; if the close does not come, wait
357
- * answers -1 and the connection takes no new channel.
333
+ * argv as the host's login over SSH, under PID_WRAPPER (./scripts.ts), as one channel on the machine's shared
334
+ * connection (#start). stdout and stderr are the channel's, piped, the wrapper's line taken off stderr; end sends end
335
+ * of file. wait answers once the channel closes, with the exit-status, or -1 for an exit by signal or none. kill
336
+ * starts pidKill over a channel of its own (on a connection with room), which ends the process and every process
337
+ * under it, then closes the exec's channel, never a connection; if the close does not come, wait answers -1 and the
338
+ * connection takes no new channel.
358
339
  */
359
340
  async exec(id, argv, ctx) {
360
- const pidFile = `/tmp/.agentrun-exec-${randomBytes(8).toString("hex")}`;
361
- const opened = await this.#start(id, shellLine(["sh", "-c", WRAPPER, pidFile, ...argv]), ctx, `the exec in ${id}`).catch((error) => {
341
+ const opened = await this.#start(id, shellLine([...PID_WRAPPER, ...argv]), ctx, `the exec in ${id}`).catch((error) => {
362
342
  throw this.#redacted(id, error);
363
343
  });
364
344
  const { link: held, channel } = opened;
365
345
  const stdout = new PassThrough();
366
- const stderr = new PassThrough();
346
+ const raw = new PassThrough();
367
347
  channel.pipe(stdout);
368
- channel.stderr.pipe(stderr);
348
+ channel.stderr.pipe(raw);
349
+ const { stderr, pid } = pidStderr(raw);
369
350
  let ended = false;
370
351
  let closed = false;
371
352
  // ssh2 closes every channel when the connection goes (utils.js, ChannelManager.cleanup), so the close is enough.
@@ -398,32 +379,35 @@ export class SshExec {
398
379
  kill: async () => {
399
380
  if (closed)
400
381
  return;
401
- // The pid file is the machine's, so the kill's channel goes on any connection with room, counted like an exec's.
402
- try {
403
- const killer = await this.#start(id, shellLine(["sh", "-c", KILL_SCRIPT, pidFile]), { timeoutMs: KILL_GRACE_MS }, `the kill in ${id}`);
404
- killer.channel.resume();
405
- killer.channel.stderr.resume();
406
- killer.channel.eof();
407
- const grace = boundOf(KILL_GRACE_MS, undefined, `the kill in ${id}`);
382
+ // The pid is the machine's, so the kill's channel goes on any connection with room, counted like an exec's. No
383
+ // pid line within the grace (or the process ended meanwhile): closing the channel below is what is left.
384
+ const target = await pid(KILL_GRACE_MS);
385
+ if (target !== undefined && !closed)
408
386
  try {
409
- await Promise.race([killer.closed, grace.promise]);
410
- }
411
- catch {
387
+ const killer = await this.#start(id, shellLine(pidKill(target)), { timeoutMs: KILL_GRACE_MS }, `the kill in ${id}`);
388
+ killer.channel.resume();
389
+ killer.channel.stderr.resume();
390
+ killer.channel.eof();
391
+ const grace = boundOf(KILL_GRACE_MS, undefined, `the kill in ${id}`);
412
392
  try {
413
- killer.channel.close();
393
+ await Promise.race([killer.closed, grace.promise]);
414
394
  }
415
395
  catch {
416
- // Closed already.
396
+ try {
397
+ killer.channel.close();
398
+ }
399
+ catch {
400
+ // Closed already.
401
+ }
402
+ }
403
+ finally {
404
+ grace.clear();
405
+ this.#letGo(killer.link);
417
406
  }
418
407
  }
419
- finally {
420
- grace.clear();
421
- this.#letGo(killer.link);
408
+ catch {
409
+ // No connection took the kill in time: closing the channel below is what is left.
422
410
  }
423
- }
424
- catch {
425
- // No connection took the kill in time: closing the channel below is what is left.
426
- }
427
411
  try {
428
412
  channel.close();
429
413
  }
@@ -446,7 +430,8 @@ export class SshExec {
446
430
  /**
447
431
  * A private key in the PEM armor ssh2 reads (its parser wants the BEGIN and END lines on lines of their own), or
448
432
  * undefined when text is not one. A key pasted into Settings → Computers comes back on one line, since a password
449
- * field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it.
433
+ * field drops line breaks: its body is wrapped again at 70 characters, as ssh-keygen writes it. A PKCS#8 key
434
+ * (the PEM label "PRIVATE KEY", Morph's GET /instance/{id}/ssh/key) is converted (fromPkcs8).
450
435
  */
451
436
  export function pemOf(text) {
452
437
  const armor = /^-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----([\s\S]*?)-----END \1-----$/.exec(text.replace(/\r/g, "").trim());
@@ -460,5 +445,59 @@ export function pemOf(text) {
460
445
  const body = lines.join("").replace(/\s+/g, "");
461
446
  if (body === "" || !/^[A-Za-z0-9+/=]+$/.test(body))
462
447
  return undefined;
463
- return `-----BEGIN ${label}-----\n${body.match(/.{1,70}/g)?.join("\n")}\n-----END ${label}-----\n`;
448
+ const pem = armored(label, Buffer.from(body, "base64"));
449
+ return label === "PRIVATE KEY" ? fromPkcs8(pem) : pem;
450
+ }
451
+ /** bytes as base64 between BEGIN and END lines of label, 70 characters a line. */
452
+ function armored(label, bytes) {
453
+ return `-----BEGIN ${label}-----\n${bytes.toString("base64").match(/.{1,70}/g)?.join("\n")}\n-----END ${label}-----\n`;
454
+ }
455
+ /**
456
+ * A PKCS#8 key as the same key in a form ssh2 reads, or undefined for a body node:crypto can't read or a type SSH has
457
+ * no use for here. ssh2 reads OpenSSH's own form, PKCS#1 RSA, SEC1 EC, DSA and PuTTY's, never PKCS#8 (ssh2@1.17.0
458
+ * lib/protocol/keyParser.js parseKey: no parser matches, "Unsupported key format"). node:crypto writes RSA as PKCS#1 and
459
+ * EC as SEC1; Ed25519 it writes only as PKCS#8, and ssh2 reads Ed25519 only in OpenSSH's form, so openSshEd25519 writes it.
460
+ */
461
+ function fromPkcs8(pem) {
462
+ let key;
463
+ try {
464
+ key = createPrivateKey(pem);
465
+ }
466
+ catch {
467
+ return undefined;
468
+ }
469
+ if (key.asymmetricKeyType === "rsa")
470
+ return key.export({ type: "pkcs1", format: "pem" });
471
+ if (key.asymmetricKeyType === "ec")
472
+ return key.export({ type: "sec1", format: "pem" });
473
+ if (key.asymmetricKeyType === "ed25519")
474
+ return openSshEd25519(key);
475
+ return undefined;
476
+ }
477
+ /** An SSH string (RFC 4251 §5): its uint32 length, then its bytes. */
478
+ const sshString = (bytes) => {
479
+ const body = Buffer.from(bytes);
480
+ const length = Buffer.alloc(4);
481
+ length.writeUInt32BE(body.length);
482
+ return Buffer.concat([length, body]);
483
+ };
484
+ /**
485
+ * An Ed25519 private key in OpenSSH's own format, unencrypted (openssh-portable PROTOCOL.key; sshkey.c writes it so):
486
+ * "openssh-key-v1\0", cipher "none", KDF "none", empty KDF options, the key count 1, the public key blob (RFC 8709 §4:
487
+ * "ssh-ed25519", the 32-byte public key), then the private section as one string: two equal random check words, the
488
+ * key type, the public key, the 64-byte private key (the 32-byte seed, then the public key), an empty comment, and
489
+ * the padding bytes 1, 2, 3, ... to a multiple of 8, the block size of cipher "none".
490
+ */
491
+ function openSshEd25519(key) {
492
+ const { d, x } = key.export({ format: "jwk" });
493
+ const seed = Buffer.from(d ?? "", "base64url");
494
+ const publicKey = Buffer.from(x ?? "", "base64url");
495
+ const blob = Buffer.concat([sshString("ssh-ed25519"), sshString(publicKey)]);
496
+ const check = randomBytes(4);
497
+ const section = Buffer.concat([check, check, blob, sshString(Buffer.concat([seed, publicKey])), sshString("")]);
498
+ const padding = Buffer.from(Array.from({ length: (8 - (section.length % 8)) % 8 }, (_, index) => index + 1));
499
+ const count = Buffer.alloc(4);
500
+ count.writeUInt32BE(1);
501
+ const body = Buffer.concat([Buffer.from("openssh-key-v1\0", "latin1"), sshString("none"), sshString("none"), sshString(""), count, sshString(blob), sshString(Buffer.concat([section, padding]))]);
502
+ return armored("OPENSSH PRIVATE KEY", body);
464
503
  }
@@ -3,6 +3,11 @@ import type { ComputerSpec, Refusal } from "../provider.js";
3
3
  /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
4
4
  export declare const DOMAIN: RegExp;
5
5
  export declare const isWhole: (value: unknown) => value is number;
6
+ /**
7
+ * How a provider that can do both reaches its machines (its descriptor's connect setting): exec (the default), a bridge
8
+ * through the vendor's exec for each connection; dial, the machine's computerd dials the server (HostFacts.connect).
9
+ */
10
+ export declare function connectOf(value: unknown, label: string): "exec" | "dial";
6
11
  /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
7
12
  export declare function sizeRefusals(spec: Partial<ComputerSpec>, computer: string, image: string): Refusal[];
8
13
  /** 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. */