@fungi.computer/computer 0.16.6 → 0.18.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 +21 -4
- package/container/computer-init.mjs +28 -0
- package/container/computer-start.sh +8 -1
- package/container/fungi-services +2 -0
- package/container/fungi-services.mjs +190 -0
- package/container/package.json +2 -1
- package/container/pnpm-lock.yaml +8 -0
- package/container/services-render.mjs +126 -0
- package/container/terminal-assets/global-tools.sh +4 -0
- package/container/terminal-server.mjs +55 -16
- package/container/tools/cli.mjs +55 -0
- package/container/tools/fungi-tools +14 -0
- package/container/tools/install.mjs +310 -0
- package/container/tools/manifest.mjs +111 -0
- package/container/tools/pi/package.json +8 -0
- package/container/tools/pi/pnpm-lock.yaml +1174 -0
- package/container/tools/pi/pnpm-workspace.yaml +4 -0
- package/dist/fleet/wire.d.ts +14 -0
- package/dist/fleet/wire.js +7 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +150 -25
- package/dist/port-failure.d.ts +10 -2
- package/dist/port-failure.js +25 -5
- package/dist/port-ownership.d.ts +16 -0
- package/dist/port-ownership.js +36 -0
- package/dist/preview-wait.d.ts +24 -0
- package/dist/preview-wait.js +47 -0
- package/dist/process-inventory.js +7 -21
- package/dist/services-apply.d.ts +54 -0
- package/dist/services-apply.js +66 -0
- package/dist/services-tools.d.ts +30 -0
- package/dist/services-tools.js +91 -0
- package/dist/services.d.ts +38 -0
- package/dist/services.js +123 -0
- package/dist/team-candidate-builder.mjs +29 -12
- package/package.json +17 -8
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=
|
|
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
|
|
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,190 @@
|
|
|
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
|
+
/**
|
|
52
|
+
* What went wrong, for the Hub to say in words. s6 reports its failures only as
|
|
53
|
+
* text, so this is the one place that reads it; callers get the kind.
|
|
54
|
+
*/
|
|
55
|
+
function failureOf(error) {
|
|
56
|
+
const text = `${error?.stderr ?? ""}\n${error?.message ?? String(error)}`;
|
|
57
|
+
const lines = text
|
|
58
|
+
.split("\n")
|
|
59
|
+
.map((line) => line.trim())
|
|
60
|
+
.filter((line) => line !== "");
|
|
61
|
+
const kind = /timed out|ETIMEDOUT/u.test(text)
|
|
62
|
+
? "timeout"
|
|
63
|
+
: /unable to control|supervisor not listening/u.test(text)
|
|
64
|
+
? "refused"
|
|
65
|
+
: /No such file|ENOENT/u.test(text)
|
|
66
|
+
? "missing"
|
|
67
|
+
: "other";
|
|
68
|
+
return { failure: kind, detail: (lines.at(-1) ?? "").slice(0, 300) };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function stopSupervisor(name) {
|
|
72
|
+
try {
|
|
73
|
+
await control(name, "-dx");
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error.code !== 111) throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function put(path, text, mode) {
|
|
80
|
+
const temporary = `${path}.new`;
|
|
81
|
+
await writeFile(temporary, text, { mode });
|
|
82
|
+
await rename(temporary, path);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// A stop is not done until the program is gone: wait for s6 to report the
|
|
86
|
+
// service down, so a caller that reads status next never sees a stopping one.
|
|
87
|
+
const stopWait = ["-wD", "-T", "10000"];
|
|
88
|
+
const controlFlags = {
|
|
89
|
+
"-u": ["-u"],
|
|
90
|
+
"-ut": ["-ut"],
|
|
91
|
+
"-t": ["-t"],
|
|
92
|
+
"-d": [...stopWait, "-d"],
|
|
93
|
+
"-dx": [...stopWait, "-dx"],
|
|
94
|
+
};
|
|
95
|
+
const control = (name, command) =>
|
|
96
|
+
run("s6-svc", [...controlFlags[command], join(scanDir, name)]);
|
|
97
|
+
|
|
98
|
+
async function apply(input) {
|
|
99
|
+
const logRoot = join(scanDir, ".logs");
|
|
100
|
+
await mkdir(logRoot, { recursive: true });
|
|
101
|
+
const plan = planApply(input, await existingServices(), {
|
|
102
|
+
workspace,
|
|
103
|
+
logRoot,
|
|
104
|
+
});
|
|
105
|
+
for (const name of plan.remove) {
|
|
106
|
+
// Stop the program and its supervisor before the directory goes.
|
|
107
|
+
await stopSupervisor(name);
|
|
108
|
+
// The exiting supervisor may still be writing its status files.
|
|
109
|
+
await rm(join(scanDir, name), {
|
|
110
|
+
recursive: true,
|
|
111
|
+
force: true,
|
|
112
|
+
maxRetries: 10,
|
|
113
|
+
retryDelay: 100,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
for (const file of plan.write) {
|
|
117
|
+
const directory = join(scanDir, file.name);
|
|
118
|
+
await mkdir(join(directory, "log"), { recursive: true });
|
|
119
|
+
await put(join(directory, "run"), file.run, 0o755);
|
|
120
|
+
await put(join(directory, "log", "run"), file.logRun, 0o755);
|
|
121
|
+
if (file.down === null) await rm(join(directory, "down"), { force: true });
|
|
122
|
+
else await writeFile(join(directory, "down"), file.down);
|
|
123
|
+
}
|
|
124
|
+
await run("s6-svscanctl", ["-an", scanDir]);
|
|
125
|
+
for (const { name, command } of plan.control) await control(name, command);
|
|
126
|
+
return plan;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Live state of every service s6 supervises, as JSON. */
|
|
130
|
+
async function status() {
|
|
131
|
+
const services = {};
|
|
132
|
+
for (const name of (await existingServices()).keys()) {
|
|
133
|
+
const { stdout } = await run("s6-svstat", [
|
|
134
|
+
"-o",
|
|
135
|
+
"up,wantedup,pid,updownfor",
|
|
136
|
+
join(scanDir, name),
|
|
137
|
+
]);
|
|
138
|
+
services[name] = parseSvstat(stdout);
|
|
139
|
+
}
|
|
140
|
+
return { services };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The retained tail of one service's log. */
|
|
144
|
+
async function logs(name, lines) {
|
|
145
|
+
const file = join(scanDir, ".logs", name, "current");
|
|
146
|
+
return {
|
|
147
|
+
name,
|
|
148
|
+
...tailLog(existsSync(file) ? await readFile(file, "utf8") : "", lines),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const [operation, ...extra] = process.argv.slice(2);
|
|
153
|
+
const usage =
|
|
154
|
+
"Usage: fungi-services apply < services.json | status | logs <name> <lines> | restart <name>\n";
|
|
155
|
+
const serviceName = /^[a-z][a-z0-9-]{0,31}$/u;
|
|
156
|
+
if (!(
|
|
157
|
+
((operation === "apply" || operation === "status") && extra.length === 0) ||
|
|
158
|
+
(operation === "logs" &&
|
|
159
|
+
extra.length === 2 &&
|
|
160
|
+
serviceName.test(extra[0]) &&
|
|
161
|
+
/^\d{1,4}$/u.test(extra[1])) ||
|
|
162
|
+
(operation === "restart" && extra.length === 1 && serviceName.test(extra[0]))
|
|
163
|
+
)) {
|
|
164
|
+
process.stderr.write(usage);
|
|
165
|
+
process.exit(2);
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
if (operation === "apply") {
|
|
169
|
+
const input = applyInputSchema.parse(JSON.parse(await readStdin()));
|
|
170
|
+
const plan = await apply(input);
|
|
171
|
+
process.stdout.write(
|
|
172
|
+
`${JSON.stringify({ applied: plan.write.map(({ name }) => name), removed: plan.remove })}\n`,
|
|
173
|
+
);
|
|
174
|
+
} else if (operation === "status")
|
|
175
|
+
process.stdout.write(`${JSON.stringify(await status())}\n`);
|
|
176
|
+
else if (operation === "logs")
|
|
177
|
+
process.stdout.write(
|
|
178
|
+
`${JSON.stringify(await logs(extra[0], Number(extra[1])))}\n`,
|
|
179
|
+
);
|
|
180
|
+
else {
|
|
181
|
+
// TERM ends the service and the supervisor, which wants it up, starts it again.
|
|
182
|
+
await control(extra[0], "-t");
|
|
183
|
+
process.stdout.write(`${JSON.stringify({ restarted: extra[0] })}\n`);
|
|
184
|
+
}
|
|
185
|
+
} catch (error) {
|
|
186
|
+
console.error("fungi-services:", error);
|
|
187
|
+
// The last line: the kind of failure, then the last line the command wrote.
|
|
188
|
+
console.error(JSON.stringify(failureOf(error)));
|
|
189
|
+
process.exit(1);
|
|
190
|
+
}
|
package/container/package.json
CHANGED
package/container/pnpm-lock.yaml
CHANGED
|
@@ -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
|
|
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(
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
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. */
|