@fungi.computer/computer 0.16.5 → 0.17.0

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.
package/Dockerfile CHANGED
@@ -11,7 +11,8 @@ RUN pnpm install --frozen-lockfile --prod --config.node-linker=hoisted \
11
11
  && mv build/Release/pty.node /tmp/pty.node \
12
12
  && rm -rf build deps third_party src scripts typings prebuilds node-addon-api \
13
13
  && mkdir -p build/Release \
14
- && mv /tmp/pty.node build/Release/pty.node
14
+ && mv /tmp/pty.node build/Release/pty.node \
15
+ && chmod -R a+rX /opt/fungi/node_modules
15
16
 
16
17
  COPY container/runtime-privileges.cc ./
17
18
  RUN g++ -shared -fPIC -I/usr/local/include/node runtime-privileges.cc -o runtime-privileges.node
@@ -33,12 +34,23 @@ RUN toolchain="$(node --input-type=module --eval "import { codexPatchPin } from
33
34
  COPY dist/apply-patch/ /source/
34
35
  RUN node /source/compile.mjs --out /out --scratch /scratch
35
36
 
37
+ # Only uv ships by default; fungi-tools installs optional pinned tools at first use.
38
+ FROM node:24.20.0-trixie-slim@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600 AS tools
39
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl xz-utils \
40
+ && rm -rf /var/lib/apt/lists/*
41
+ WORKDIR /tmp/downloads
42
+ RUN curl -fLSs https://github.com/astral-sh/uv/releases/download/0.13.8/uv-x86_64-unknown-linux-gnu.tar.gz -o uv.tar.gz \
43
+ && echo '5acfd9177cfecf0bf87578f059728215ccc884388988f55f7a65041b57387d91 uv.tar.gz' | sha256sum -c - \
44
+ && mkdir -p /opt/toolchains/uv && tar -xzf uv.tar.gz -C /opt/toolchains/uv --strip-components=1 \
45
+ && chmod -R a+rX /opt/toolchains
46
+
36
47
  # Match the repository toolchain on the same Linux x64 target as computerd.
37
48
  FROM node:24.20.0-trixie-slim@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600
38
49
 
39
50
  RUN apt-get update \
40
51
  && apt-get install -y --no-install-recommends \
41
- fuse3 libfuse2t64 ca-certificates curl git procps tini openssh-server \
52
+ fuse3 libfuse2t64 ca-certificates curl git procps s6 tini openssh-server \
53
+ python3 python3-venv gcc libc6-dev gh ripgrep xz-utils \
42
54
  && rm -f /etc/ssh/ssh_host_* \
43
55
  && rm -rf /var/lib/apt/lists/*
44
56
 
@@ -57,10 +69,15 @@ COPY dist/computerd.cjs dist/team-candidate-builder.mjs /opt/fungi/
57
69
  COPY --from=apply-patch --chmod=755 /out/fungi-apply-patch /opt/fungi/fungi-apply-patch
58
70
  COPY --from=apply-patch /out/build.json /opt/fungi/fungi-apply-patch.notices.json
59
71
  COPY dist/apply-patch/LICENSE.codex /opt/fungi/fungi-apply-patch.LICENSE
60
- COPY --from=terminal /opt/fungi/node_modules /opt/fungi/node_modules
72
+ COPY --from=tools /opt/toolchains /opt/toolchains
73
+ RUN ln -s /opt/toolchains/uv/uv /opt/toolchains/uv/uvx /usr/local/bin/
74
+ COPY container/tools/ /opt/fungi/tools/
75
+ COPY --chmod=755 container/tools/fungi-tools /usr/local/bin/fungi-tools
76
+ COPY --chmod=755 container/fungi-services /usr/local/bin/fungi-services
61
77
  COPY container/runtime-privileges.mjs /opt/fungi/
62
78
  COPY --from=terminal /opt/fungi/runtime-privileges.node /opt/fungi/
63
- COPY container/package.json container/computer-init.mjs container/computer-start.sh container/resource-bounds.mjs container/terminal-server.mjs container/terminal-runtime.mjs container/terminal-protocol.mjs container/sshd_config /opt/fungi/
79
+ COPY --from=terminal /opt/fungi/node_modules /opt/fungi/node_modules
80
+ COPY container/package.json container/computer-init.mjs container/computer-start.sh container/fungi-services.mjs container/services-render.mjs container/resource-bounds.mjs container/terminal-server.mjs container/terminal-runtime.mjs container/terminal-protocol.mjs container/sshd_config /opt/fungi/
64
81
  COPY container/terminal-assets/bashrc container/terminal-assets/git-prompt.sh container/terminal-assets/global-tools.sh /opt/fungi/terminal-assets/
65
82
  RUN chmod -R a+rX /opt/fungi \
66
83
  && printf '\n. /opt/fungi/terminal-assets/bashrc\n' >> /etc/bash.bashrc \
@@ -43,6 +43,7 @@ if (readRuntimePrivilegeMode() === "vm-sudo") {
43
43
  }
44
44
 
45
45
  let terminal;
46
+ let services;
46
47
  const daemon = spawn(process.execPath, [computerd], {
47
48
  stdio: ["ignore", "inherit", "inherit", "ipc"],
48
49
  env: {
@@ -55,6 +56,7 @@ const maximumRuntimeMs = boundedRuntimeMs(process.env.COMPUTER_MAX_RUNTIME_MS);
55
56
  setTimeout(() => {
56
57
  log("runtime deadline reached", { maximumRuntimeMs });
57
58
  stopping = true;
59
+ services?.kill("SIGTERM");
58
60
  terminal?.kill("SIGTERM");
59
61
  daemon.kill("SIGTERM");
60
62
  setTimeout(() => process.exit(0), 5_000).unref();
@@ -62,6 +64,7 @@ setTimeout(() => {
62
64
 
63
65
  daemon.once("exit", (code, signal) => {
64
66
  log("computerd exited", { code, signal, stopping });
67
+ services?.kill("SIGTERM");
65
68
  terminal?.kill("SIGTERM");
66
69
  // An unrequested exit is a failure even when computerd reports 0.
67
70
  process.exit(stopping ? (code ?? 0) : 1);
@@ -122,7 +125,31 @@ try {
122
125
  });
123
126
  });
124
127
  log("terminal listening", { port: terminalPort });
128
+ // The declared services' supervisor: a third fundamental child, like the
129
+ // terminal. s6 restarts each service; if s6-svscan itself dies, the runtime
130
+ // exits and the next one starts every enabled service again.
131
+ const servicesDir = process.env.COMPUTER_SERVICES_DIR;
132
+ if (servicesDir !== undefined) {
133
+ services = spawn("s6-svscan", [servicesDir], {
134
+ stdio: ["ignore", "inherit", "inherit"],
135
+ env: process.env,
136
+ });
137
+ services.once("error", (error) => {
138
+ log("s6-svscan failed to start", { error: error.message });
139
+ terminal?.kill("SIGTERM");
140
+ daemon.kill("SIGTERM");
141
+ process.exit(1);
142
+ });
143
+ services.once("exit", (code, signal) => {
144
+ log("s6-svscan exited", { code, signal, stopping });
145
+ terminal?.kill("SIGTERM");
146
+ daemon.kill("SIGTERM");
147
+ process.exit(stopping ? 0 : 1);
148
+ });
149
+ log("services supervisor started", { dir: servicesDir });
150
+ }
125
151
  } catch (error) {
152
+ services?.kill("SIGTERM");
126
153
  daemon.kill("SIGTERM");
127
154
  throw new Error("Computer terminal failed to listen", { cause: error });
128
155
  }
@@ -130,6 +157,7 @@ try {
130
157
  for (const signal of ["SIGTERM", "SIGINT"]) {
131
158
  process.on(signal, () => {
132
159
  stopping = true;
160
+ services?.kill("SIGTERM");
133
161
  terminal?.kill("SIGTERM");
134
162
  daemon.kill(signal);
135
163
  });
@@ -19,6 +19,13 @@ export COMPUTER_RUNTIME_UID="$uid"
19
19
  pids_max=$(node --input-type=module -e 'import { computerResourceBounds } from "/opt/fungi/resource-bounds.mjs"; process.stdout.write(String(computerResourceBounds.pidsMax))')
20
20
  mkdir -p /workspace
21
21
  chown "$uid:$uid" /workspace
22
+ # Agent CLIs installed by fungi-tools live here, outside the synced home: their
23
+ # binaries exceed the durable home's per-file bound. Nothing here survives a wake.
24
+ install -d -m 0700 -o "$uid" -g "$uid" /var/cache/fungi-tools
25
+ # The declared services' s6 scan directory and logs: scratch, rebuilt by
26
+ # `fungi-services apply` on every wake, never synced into the home.
27
+ export COMPUTER_SERVICES_DIR=/var/cache/fungi-services
28
+ install -d -m 0700 -o "$uid" -g "$uid" "$COMPUTER_SERVICES_DIR"
22
29
  ulimit -Su "$pids_max"
23
30
  ulimit -Hu "$pids_max"
24
31
  # vmd's guest config carries this VM's SSH host key, user CA and principals. The
@@ -43,5 +50,5 @@ export HOME=/workspace
43
50
  # /etc/profile resets PATH.
44
51
  export NPM_CONFIG_PREFIX="$HOME/.npm-global"
45
52
  export PNPM_HOME="$HOME/.local/share/pnpm"
46
- export PATH="$NPM_CONFIG_PREFIX/bin:$PNPM_HOME/bin:$PATH"
53
+ export PATH="$HOME/.local/bin:$NPM_CONFIG_PREFIX/bin:$PNPM_HOME/bin:$PATH"
47
54
  exec node /opt/fungi/computer-init.mjs
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ exec node /opt/fungi/fungi-services.mjs "$@"
@@ -0,0 +1,168 @@
1
+ // fungi-services apply: render the declared services (JSON on stdin) into the
2
+ // s6 scan directory and tell s6 to look again. The Computer's lifecycle runs it
3
+ // after every wake and every declaration change; s6 does the supervising.
4
+ import { Buffer } from "node:buffer";
5
+ import console from "node:console";
6
+ import { execFile } from "node:child_process";
7
+ import { existsSync } from "node:fs";
8
+ import {
9
+ mkdir,
10
+ readdir,
11
+ readFile,
12
+ rename,
13
+ rm,
14
+ writeFile,
15
+ } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ import process from "node:process";
18
+ import { promisify } from "node:util";
19
+ import {
20
+ applyInputSchema,
21
+ parseSvstat,
22
+ planApply,
23
+ tailLog,
24
+ } from "./services-render.mjs";
25
+
26
+ const run = promisify(execFile);
27
+
28
+ /** The scan directory is created by computer-start.sh for the Computer's UID. */
29
+ const scanDir =
30
+ process.env.COMPUTER_SERVICES_DIR ?? "/var/cache/fungi-services";
31
+ const workspace = process.env.MOUNT_POINT ?? "/workspace";
32
+
33
+ async function readStdin() {
34
+ const chunks = [];
35
+ for await (const chunk of process.stdin) chunks.push(chunk);
36
+ return Buffer.concat(chunks).toString("utf8");
37
+ }
38
+
39
+ /** Service directories now in the scan directory, with their current `run` text. */
40
+ async function existingServices() {
41
+ const found = new Map();
42
+ for (const entry of await readdir(scanDir, { withFileTypes: true })) {
43
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
44
+ const run = join(scanDir, entry.name, "run");
45
+ found.set(entry.name, existsSync(run) ? await readFile(run, "utf8") : "");
46
+ }
47
+ return found;
48
+ }
49
+
50
+ /** s6-svc exits 111 when no supervisor listens, which is true of a service that never started. */
51
+ async function stopSupervisor(name) {
52
+ try {
53
+ await control(name, "-dx");
54
+ } catch (error) {
55
+ if (error.code !== 111) throw error;
56
+ }
57
+ }
58
+
59
+ async function put(path, text, mode) {
60
+ const temporary = `${path}.new`;
61
+ await writeFile(temporary, text, { mode });
62
+ await rename(temporary, path);
63
+ }
64
+
65
+ // A stop is not done until the program is gone: wait for s6 to report the
66
+ // service down, so a caller that reads status next never sees a stopping one.
67
+ const stopWait = ["-wD", "-T", "10000"];
68
+ const controlFlags = {
69
+ "-u": ["-u"],
70
+ "-ut": ["-ut"],
71
+ "-t": ["-t"],
72
+ "-d": [...stopWait, "-d"],
73
+ "-dx": [...stopWait, "-dx"],
74
+ };
75
+ const control = (name, command) =>
76
+ run("s6-svc", [...controlFlags[command], join(scanDir, name)]);
77
+
78
+ async function apply(input) {
79
+ const logRoot = join(scanDir, ".logs");
80
+ await mkdir(logRoot, { recursive: true });
81
+ const plan = planApply(input, await existingServices(), {
82
+ workspace,
83
+ logRoot,
84
+ });
85
+ for (const name of plan.remove) {
86
+ // Stop the program and its supervisor before the directory goes.
87
+ await stopSupervisor(name);
88
+ // The exiting supervisor may still be writing its status files.
89
+ await rm(join(scanDir, name), {
90
+ recursive: true,
91
+ force: true,
92
+ maxRetries: 10,
93
+ retryDelay: 100,
94
+ });
95
+ }
96
+ for (const file of plan.write) {
97
+ const directory = join(scanDir, file.name);
98
+ await mkdir(join(directory, "log"), { recursive: true });
99
+ await put(join(directory, "run"), file.run, 0o755);
100
+ await put(join(directory, "log", "run"), file.logRun, 0o755);
101
+ if (file.down === null) await rm(join(directory, "down"), { force: true });
102
+ else await writeFile(join(directory, "down"), file.down);
103
+ }
104
+ await run("s6-svscanctl", ["-an", scanDir]);
105
+ for (const { name, command } of plan.control) await control(name, command);
106
+ return plan;
107
+ }
108
+
109
+ /** Live state of every service s6 supervises, as JSON. */
110
+ async function status() {
111
+ const services = {};
112
+ for (const name of (await existingServices()).keys()) {
113
+ const { stdout } = await run("s6-svstat", [
114
+ "-o",
115
+ "up,wantedup,pid,updownfor",
116
+ join(scanDir, name),
117
+ ]);
118
+ services[name] = parseSvstat(stdout);
119
+ }
120
+ return { services };
121
+ }
122
+
123
+ /** The retained tail of one service's log. */
124
+ async function logs(name, lines) {
125
+ const file = join(scanDir, ".logs", name, "current");
126
+ return {
127
+ name,
128
+ ...tailLog(existsSync(file) ? await readFile(file, "utf8") : "", lines),
129
+ };
130
+ }
131
+
132
+ const [operation, ...extra] = process.argv.slice(2);
133
+ const usage =
134
+ "Usage: fungi-services apply < services.json | status | logs <name> <lines> | restart <name>\n";
135
+ const serviceName = /^[a-z][a-z0-9-]{0,31}$/u;
136
+ if (!(
137
+ ((operation === "apply" || operation === "status") && extra.length === 0) ||
138
+ (operation === "logs" &&
139
+ extra.length === 2 &&
140
+ serviceName.test(extra[0]) &&
141
+ /^\d{1,4}$/u.test(extra[1])) ||
142
+ (operation === "restart" && extra.length === 1 && serviceName.test(extra[0]))
143
+ )) {
144
+ process.stderr.write(usage);
145
+ process.exit(2);
146
+ }
147
+ try {
148
+ if (operation === "apply") {
149
+ const input = applyInputSchema.parse(JSON.parse(await readStdin()));
150
+ const plan = await apply(input);
151
+ process.stdout.write(
152
+ `${JSON.stringify({ applied: plan.write.map(({ name }) => name), removed: plan.remove })}\n`,
153
+ );
154
+ } else if (operation === "status")
155
+ process.stdout.write(`${JSON.stringify(await status())}\n`);
156
+ else if (operation === "logs")
157
+ process.stdout.write(
158
+ `${JSON.stringify(await logs(extra[0], Number(extra[1])))}\n`,
159
+ );
160
+ else {
161
+ // TERM ends the service and the supervisor, which wants it up, starts it again.
162
+ await control(extra[0], "-t");
163
+ process.stdout.write(`${JSON.stringify({ restarted: extra[0] })}\n`);
164
+ }
165
+ } catch (error) {
166
+ console.error("fungi-services:", error);
167
+ process.exit(1);
168
+ }
@@ -8,7 +8,8 @@
8
8
  "node-pty": "1.1.0",
9
9
  "ws": "8.21.3",
10
10
  "fuse-native": "2.2.6",
11
- "esbuild": "0.28.2"
11
+ "esbuild": "0.28.2",
12
+ "zod": "4.4.3"
12
13
  },
13
14
  "license": "MIT"
14
15
  }
@@ -20,6 +20,9 @@ importers:
20
20
  ws:
21
21
  specifier: 8.21.3
22
22
  version: 8.21.3
23
+ zod:
24
+ specifier: 4.4.3
25
+ version: 4.4.3
23
26
 
24
27
  packages:
25
28
 
@@ -231,6 +234,9 @@ packages:
231
234
  utf-8-validate:
232
235
  optional: true
233
236
 
237
+ zod@4.4.3:
238
+ resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
239
+
234
240
  snapshots:
235
241
 
236
242
  '@esbuild/aix-ppc64@0.28.2':
@@ -376,3 +382,5 @@ snapshots:
376
382
  node-addon-api: 7.1.1
377
383
 
378
384
  ws@8.21.3: {}
385
+
386
+ zod@4.4.3: {}
@@ -0,0 +1,126 @@
1
+ // Renders declared services into s6 service directories. Pure: it decides the
2
+ // files and the supervisor commands, and touches neither the disk nor s6.
3
+ import { z } from "zod";
4
+
5
+ /** The JSON the Computer sends `fungi-services apply`; the contract's declaration, closed. */
6
+ export const applyInputSchema = z.strictObject({
7
+ services: z
8
+ .array(
9
+ z.strictObject({
10
+ name: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u),
11
+ command: z.string().min(1).max(16_384),
12
+ cwd: z
13
+ .string()
14
+ .min(1)
15
+ .max(4_096)
16
+ .startsWith("/")
17
+ .refine((path) => !path.includes("\0"))
18
+ .optional(),
19
+ env: z
20
+ .record(
21
+ z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/u),
22
+ z.string().max(4_096),
23
+ )
24
+ .refine((env) => Object.keys(env).length <= 32)
25
+ .optional(),
26
+ enabled: z.boolean(),
27
+ }),
28
+ )
29
+ .max(16),
30
+ });
31
+
32
+ /** One POSIX shell word: single-quoted, so `'`, `$`, backticks and newlines stay literal. */
33
+ export function shellWord(text) {
34
+ if (text.includes("\0"))
35
+ throw new Error("A shell word cannot hold a NUL byte");
36
+ return `'${text.replaceAll("'", `'\\''`)}'`;
37
+ }
38
+
39
+ /**
40
+ * The files of one service: its `run`, its logger's `run` and the `down`
41
+ * marker when stopped.
42
+ */
43
+ export function renderService(service, { workspace, logRoot }) {
44
+ const env = Object.entries(service.env ?? {}).map(
45
+ ([key, value]) => `export ${key}=${shellWord(value)}\n`,
46
+ );
47
+ const run = [
48
+ "#!/bin/sh\n",
49
+ "exec 2>&1\n",
50
+ `cd ${shellWord(service.cwd ?? workspace)} || exit 1\n`,
51
+ ...env,
52
+ // s6 signals only this script. The command runs beside it in the service's
53
+ // own process group, so a stop or restart ends everything it started, not
54
+ // just its shell.
55
+ `/bin/sh -c ${shellWord(service.command)} &\n`,
56
+ "child=$!\n",
57
+ "trap 'kill -TERM 0 2>/dev/null' TERM INT\n",
58
+ 'wait "$child"\n',
59
+ "status=$?\n",
60
+ 'while kill -0 "$child" 2>/dev/null; do wait "$child"; status=$?; done\n',
61
+ 'exit "$status"\n',
62
+ ].join("");
63
+ const logger = [
64
+ "#!/bin/sh\n",
65
+ // Five files of about a megabyte each, newest kept.
66
+ `exec s6-log n5 s1000000 ${shellWord(`${logRoot}/${service.name}`)}\n`,
67
+ ].join("");
68
+ return {
69
+ run,
70
+ logRun: logger,
71
+ down: service.enabled ? null : "",
72
+ };
73
+ }
74
+
75
+ /**
76
+ * What to do to reach the declared set. `existing` maps each service directory
77
+ * now in the scan directory to its current `run` text. A directory the supervisor
78
+ * has not seen yet starts itself (or stays down), so only a directory that
79
+ * already has a supervisor needs a control command: restart when its run file
80
+ * changed (up and TERM, which also starts a stopped one), up when it should run,
81
+ * down when it should not.
82
+ */
83
+ export function planApply(input, existing, options) {
84
+ const declared = new Map();
85
+ for (const service of input.services)
86
+ declared.set(service.name, {
87
+ service,
88
+ files: renderService(service, options),
89
+ });
90
+ const write = [];
91
+ const control = [];
92
+ const remove = [];
93
+ for (const [name, { service, files }] of declared) {
94
+ write.push({ name, ...files });
95
+ const current = existing.get(name);
96
+ if (current === undefined) continue;
97
+ if (!service.enabled) control.push({ name, command: "-d" });
98
+ else if (current !== files.run) control.push({ name, command: "-ut" });
99
+ else control.push({ name, command: "-u" });
100
+ }
101
+ for (const name of existing.keys())
102
+ if (!declared.has(name)) remove.push(name);
103
+ return { write, control, remove };
104
+ }
105
+
106
+ /**
107
+ * `s6-svstat -o up,wantedup,pid,updownfor` prints its values on one line,
108
+ * with no pid while the service is down. A service that is down but wanted up
109
+ * is between restarts; one that is down and not wanted is stopped.
110
+ */
111
+ export function parseSvstat(text) {
112
+ const values = text.trim().split(/\s+/u);
113
+ const seconds = Number(values.at(-1));
114
+ if (values[0] === "true" && values.length === 4)
115
+ return { state: "up", pid: Number(values[2]), seconds };
116
+ if (values[0] === "false" && values.length >= 3)
117
+ return { state: values[1] === "true" ? "restarting" : "down", seconds };
118
+ throw new Error(`Unreadable s6-svstat output: ${text.slice(0, 80)}`);
119
+ }
120
+
121
+ /** The last `lines` lines of s6-log's `current` file, and whether older lines were cut. */
122
+ export function tailLog(text, lines) {
123
+ const all = text.split("\n");
124
+ if (all.at(-1) === "") all.pop();
125
+ return { lines: all.slice(-lines), truncated: all.length > lines };
126
+ }
@@ -3,6 +3,10 @@
3
3
  # Restore them (idempotently) so `npm install -g` and `pnpm add -g` binaries
4
4
  # resolve in login shells too, interactive or not.
5
5
  [ -n "${NPM_CONFIG_PREFIX:-}" ] || return 0
6
+ case ":$PATH:" in
7
+ *":$HOME/.local/bin:"*) ;;
8
+ *) PATH="$HOME/.local/bin:$PATH" ;;
9
+ esac
6
10
  case ":$PATH:" in
7
11
  *":$NPM_CONFIG_PREFIX/bin:"*) ;;
8
12
  *) PATH="$NPM_CONFIG_PREFIX/bin:${PNPM_HOME:+$PNPM_HOME/bin:}$PATH" ;;
@@ -32,6 +32,13 @@ const terminalShell = "/bin/bash";
32
32
  /** The guest's `sshd -i`, with fixed argv; nothing a client sends reaches it. */
33
33
  const sshd = "/usr/sbin/sshd";
34
34
  const sshdArguments = ["-i", "-e", "-f", "/opt/fungi/sshd_config"];
35
+ /**
36
+ * Every process a connection starts carries this variable, set by sshd itself
37
+ * from a value this server numbers. It finds a command that outlived its sshd,
38
+ * which no process tree can: the command is reparented to init the moment sshd
39
+ * exits, and a client's own disconnect makes sshd exit first.
40
+ */
41
+ const sshSessionVariable = "FUNGI_SSH_SESSION";
35
42
  /** What vmd supplies at boot (computer-start.sh); without them there is no SSH. */
36
43
  const sshFiles = [
37
44
  "/run/fungi-ssh/host_ed25519",
@@ -79,6 +86,25 @@ function descendants(root) {
79
86
  return found;
80
87
  }
81
88
 
89
+ /** Processes marked with one connection's id, from /proc; never this server. */
90
+ function marked(id) {
91
+ const needle = Buffer.from(`${sshSessionVariable}=${id}\0`);
92
+ const found = [];
93
+ for (const name of readdirSync("/proc")) {
94
+ if (!/^[0-9]+$/u.test(name) || Number(name) === process.pid) continue;
95
+ try {
96
+ if (readFileSync(`/proc/${name}/environ`).includes(needle))
97
+ found.push(Number(name));
98
+ } catch (cause) {
99
+ // Exited while the table was read, or belongs to another user, so it
100
+ // cannot be one of this connection's.
101
+ if (["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(cause.code)) continue;
102
+ throw cause;
103
+ }
104
+ }
105
+ return found;
106
+ }
107
+
82
108
  function signal(pid, name) {
83
109
  try {
84
110
  process.kill(pid, name);
@@ -96,16 +122,17 @@ function signal(pid, name) {
96
122
  * alone once it is gone (the number may be reused), while a descendant that
97
123
  * was alive when the walk ran is still killed.
98
124
  */
99
- function killSshd(child) {
125
+ function killSshd(child, id) {
100
126
  const pid = child.pid;
101
127
  if (pid === undefined) return;
102
128
  const exited = () => child.exitCode !== null || child.signalCode !== null;
103
- const doomed = exited() ? [] : [pid, ...descendants(pid)];
129
+ const doomed = new Set(exited() ? [] : [pid, ...descendants(pid)]);
130
+ for (const target of marked(id)) doomed.add(target);
104
131
  signal(-pid, "SIGTERM");
105
132
  for (const target of doomed) signal(target, "SIGTERM");
106
133
  setTimeout(() => {
107
134
  if (!exited()) signal(-pid, "SIGKILL");
108
- for (const target of doomed)
135
+ for (const target of new Set([...doomed, ...marked(id)]))
109
136
  if (target !== pid || !exited()) signal(target, "SIGKILL");
110
137
  }, sshKillGraceMs).unref();
111
138
  }
@@ -131,6 +158,8 @@ function shellEnvironment(labels) {
131
158
  class TerminalSessions {
132
159
  #sessions = new Map();
133
160
  #ssh = new Set();
161
+ /** Numbers each SSH connection, so its marker is unique within this server. */
162
+ #connections = 0;
134
163
  #spawnSshd;
135
164
  #spawn;
136
165
  #now;
@@ -211,23 +240,29 @@ class TerminalSessions {
211
240
  socket.close(1013, "terminal session limit");
212
241
  return;
213
242
  }
214
- const child = this.#spawnSshd();
243
+ const id = `${String(process.pid)}-${String(this.#connections++)}`;
244
+ const child = this.#spawnSshd(id);
215
245
  const session = { socket, child };
216
246
  this.#ssh.add(session);
217
247
  const stream = createWebSocketStream(socket);
218
248
  const finish = () => {
219
249
  if (!this.#ssh.delete(session)) return;
250
+ killSshd(child, id);
220
251
  stream.destroy();
221
- killSshd(child);
222
252
  if (socket.readyState === socket.OPEN) socket.close(1000, "sshd exited");
223
253
  };
224
254
  child.once("exit", finish);
225
255
  child.once("error", finish);
256
+ // The client going away ends the stream before the socket's own close
257
+ // event. The pipe must not pass that end to sshd's stdin on its own: sshd
258
+ // exits on it, and a command it started is then out of reach of the tree
259
+ // walk. `finish` reads the tree first, then stops sshd.
260
+ stream.once("end", finish);
226
261
  socket.once("close", finish);
227
262
  stream.on("error", finish);
228
263
  child.stdin.on("error", finish);
229
264
  child.stdout.on("error", finish);
230
- stream.pipe(child.stdin);
265
+ stream.pipe(child.stdin, { end: false });
231
266
  child.stdout.pipe(stream);
232
267
  socket.on("error", () => {
233
268
  socket.terminate();
@@ -312,16 +347,20 @@ class TerminalSessions {
312
347
  }
313
348
  }
314
349
 
315
- function spawnFixedSshd() {
316
- return spawn(sshd, sshdArguments, {
317
- cwd: "/",
318
- // Its own process group, so one signal reaches sshd and its helpers.
319
- detached: true,
320
- // sshd's own log (VERBOSE, with each certificate's key id) goes to this
321
- // process's stderr, which the container runtime collects.
322
- stdio: ["pipe", "pipe", "inherit"],
323
- env: { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin" },
324
- });
350
+ function spawnFixedSshd(id) {
351
+ return spawn(
352
+ sshd,
353
+ [...sshdArguments, "-o", `SetEnv=${sshSessionVariable}=${id}`],
354
+ {
355
+ cwd: "/",
356
+ // Its own process group, so one signal reaches sshd and its helpers.
357
+ detached: true,
358
+ // sshd's own log (VERBOSE, with each certificate's key id) goes to this
359
+ // process's stderr, which the container runtime collects.
360
+ stdio: ["pipe", "pipe", "inherit"],
361
+ env: { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin" },
362
+ },
363
+ );
325
364
  }
326
365
 
327
366
  /** Serve `/health` and the `/pty` and `/ssh` upgrades on one private container port. */
@@ -0,0 +1,55 @@
1
+ import process from "node:process";
2
+ import { installTool, ToolsInstallError } from "./install.mjs";
3
+ import { toolCatalog } from "./manifest.mjs";
4
+
5
+ // Created per Computer by computer-start.sh outside the synced /workspace home.
6
+ // It survives nothing across a wake; Agent CLIs are reinstalled from pins.
7
+ const cache = "/var/cache/fungi-tools";
8
+
9
+ const controller = new globalThis.AbortController();
10
+ for (const signal of ["SIGTERM", "SIGINT"])
11
+ process.once(signal, () => controller.abort());
12
+
13
+ /** Run one install; resolve to the process exit status. */
14
+ async function main() {
15
+ try {
16
+ const [operation, tool, ...extra] = process.argv.slice(2);
17
+ if (operation !== "install" || !tool || extra.length !== 0)
18
+ throw new ToolsInstallError(
19
+ "unsupported",
20
+ `Usage: fungi-tools install <${Object.keys(toolCatalog).join("|")}>`,
21
+ );
22
+ if (process.platform !== "linux" || process.arch !== "x64")
23
+ throw new ToolsInstallError(
24
+ "unsupported",
25
+ "This image supports Linux x64 tools only",
26
+ );
27
+ if (!process.env.HOME || process.getuid() === 0)
28
+ throw new ToolsInstallError(
29
+ "unsupported",
30
+ "Run as the Computer user with its durable HOME, not root",
31
+ );
32
+ const result = await installTool(tool, {
33
+ home: process.env.HOME,
34
+ cache,
35
+ catalog: toolCatalog,
36
+ signal: controller.signal,
37
+ notify: (line) => process.stderr.write(`${line}\n`),
38
+ });
39
+ process.stdout.write(
40
+ `fungi-tools: ${result.tool} ${result.version}: ${result.status}\n`,
41
+ );
42
+ return { exitCode: 0 };
43
+ } catch (cause) {
44
+ const code =
45
+ cause instanceof ToolsInstallError ? cause.code : "storage_failed";
46
+ const message =
47
+ cause instanceof ToolsInstallError
48
+ ? cause.message
49
+ : "Installation could not finish; check writable home and free space, then retry";
50
+ process.stderr.write(`fungi-tools: ${code}: ${message}\n`);
51
+ return { failure: code, exitCode: 1 };
52
+ }
53
+ }
54
+
55
+ process.exitCode = (await main()).exitCode;