@fungi.computer/computer 0.16.1 → 0.16.3

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
@@ -38,7 +38,8 @@ FROM node:24.20.0-trixie-slim@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b
38
38
 
39
39
  RUN apt-get update \
40
40
  && apt-get install -y --no-install-recommends \
41
- fuse3 libfuse2t64 ca-certificates curl git procps tini \
41
+ fuse3 libfuse2t64 ca-certificates curl git procps tini openssh-server \
42
+ && rm -f /etc/ssh/ssh_host_* \
42
43
  && rm -rf /var/lib/apt/lists/*
43
44
 
44
45
  RUN npm install --global --no-fund --no-audit pnpm@11.24.0 \
@@ -59,12 +60,15 @@ COPY dist/apply-patch/LICENSE.codex /opt/fungi/fungi-apply-patch.LICENSE
59
60
  COPY --from=terminal /opt/fungi/node_modules /opt/fungi/node_modules
60
61
  COPY container/runtime-privileges.mjs /opt/fungi/
61
62
  COPY --from=terminal /opt/fungi/runtime-privileges.node /opt/fungi/
62
- 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 /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/
63
64
  COPY container/terminal-assets/bashrc container/terminal-assets/git-prompt.sh container/terminal-assets/global-tools.sh /opt/fungi/terminal-assets/
64
65
  RUN chmod -R a+rX /opt/fungi \
65
66
  && printf '\n. /opt/fungi/terminal-assets/bashrc\n' >> /etc/bash.bashrc \
66
67
  && printf '. /opt/fungi/terminal-assets/global-tools.sh\n. /opt/fungi/terminal-assets/bashrc\n' > /etc/profile.d/fungi-terminal.sh
67
68
 
69
+ # openssh-server is installed only for `sshd -i`, which terminal-server.mjs runs
70
+ # as the runtime user for one admitted connection. No sshd service starts, and no
71
+ # host key ships in the image: vmd supplies each VM's key at boot.
68
72
  # No customer process can invoke a setuid/setgid helper, including fusermount.
69
73
  # FUSE is mounted while init is root, before either runtime listener opens.
70
74
  RUN find / -xdev -perm /6000 -exec chmod a-s {} +
package/README.md CHANGED
@@ -273,6 +273,7 @@ were saved in a hosted Computer. Do not copy its temporary output into source.
273
273
  checks native workspace operations and reconstruction.
274
274
  [Process proof](test/process-proof.mjs) checks retained process identity against
275
275
  the real container. [Terminal proof](test/terminal-container-proof.mjs),
276
+ [SSH proof](test/ssh-container-proof.mjs) (the guest `sshd -i` behind `/ssh`),
276
277
  [resource proof](test/container-resource-proof.mjs) and
277
278
  [backend tests](test/computer-backends.test.mjs) cover their separate
278
279
  boundaries. The declared nightly egress proof is separate from the ordinary
@@ -21,6 +21,19 @@ mkdir -p /workspace
21
21
  chown "$uid:$uid" /workspace
22
22
  ulimit -Su "$pids_max"
23
23
  ulimit -Hu "$pids_max"
24
+ # vmd's guest config carries this VM's SSH host key, user CA and principals. The
25
+ # unprivileged `sshd -i` reads them from files only the runtime user can read; a
26
+ # Computer without them has no SSH, and terminal-server refuses /ssh.
27
+ ssh_source=/run/fungi-vm/ssh
28
+ ssh_directory=/run/fungi-ssh
29
+ rm -rf "$ssh_directory"
30
+ if [[ -d "$ssh_source" ]]; then
31
+ install -d -m 0700 -o "$uid" -g "$uid" "$ssh_directory"
32
+ for name in host_ed25519 user_ca.pub principals; do
33
+ [[ -f "$ssh_source/$name" ]] || continue
34
+ install -m 0600 -o "$uid" -g "$uid" "$ssh_source/$name" "$ssh_directory/$name"
35
+ done
36
+ fi
24
37
  export HOME=/workspace
25
38
  # The image's npm and pnpm prefixes are root-owned. Global installs go into
26
39
  # user-owned folders in the persistent home; npm and pnpm create them on first
@@ -0,0 +1,38 @@
1
+ # The Computer's guest sshd, run only as `sshd -i` by terminal-server.mjs for one
2
+ # Hub-admitted WebSocket at a time, as the unprivileged runtime user. It has no
3
+ # listening socket. A user is admitted only by an OpenSSH certificate signed by
4
+ # the host's CA whose principal is this VM's id; there are no other credentials.
5
+ # vmd writes the files below into the guest at boot; computer-start.sh copies
6
+ # them to files the runtime user owns.
7
+ HostKey /run/fungi-ssh/host_ed25519
8
+ TrustedUserCAKeys /run/fungi-ssh/user_ca.pub
9
+ AuthorizedPrincipalsFile /run/fungi-ssh/principals
10
+
11
+ # Authentication
12
+ AuthorizedKeysFile none
13
+ AuthenticationMethods publickey
14
+ PubkeyAuthentication yes
15
+ PasswordAuthentication no
16
+ KbdInteractiveAuthentication no
17
+ PermitEmptyPasswords no
18
+ PermitRootLogin no
19
+ UsePAM no
20
+ StrictModes yes
21
+ AllowUsers fungi
22
+
23
+ # Forwarding: listeners stay on the guest's own loopback
24
+ GatewayPorts no
25
+ AllowAgentForwarding no
26
+ AllowStreamLocalForwarding no
27
+ PermitTunnel no
28
+ X11Forwarding no
29
+
30
+ # Nothing the user or the client can set changes the login
31
+ PermitUserRC no
32
+ PermitUserEnvironment no
33
+ PrintMotd no
34
+ PidFile none
35
+ LogLevel VERBOSE
36
+
37
+ # scp and sftp clients use the SFTP protocol
38
+ Subsystem sftp internal-sftp
@@ -4,15 +4,21 @@
4
4
  // `{"type":"resize","cols":N,"rows":N}` resizes, and the server sends
5
5
  // `{"type":"ready","information":{...}}` with display facts,
6
6
  // `{"type":"exit","code":N}` and `{"type":"error"}`.
7
+ //
8
+ // `/ssh` is a second door on the same port: each WebSocket carries one raw SSH
9
+ // stream (binary frames only) to a fixed `sshd -i`, run as this process's
10
+ // unprivileged user. It listens on nothing and counts as a session.
11
+ import { spawn } from "node:child_process";
7
12
  import { Buffer } from "node:buffer";
8
- import { existsSync } from "node:fs";
13
+ import console from "node:console";
14
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
9
15
  import { createServer } from "node:http";
10
16
  import process from "node:process";
11
- import { clearInterval, setInterval } from "node:timers";
17
+ import { clearInterval, setInterval, setTimeout } from "node:timers";
12
18
  import { URL } from "node:url";
13
19
  import pty from "node-pty";
14
20
  import manifest from "./package.json" with { type: "json" };
15
- import { WebSocketServer } from "ws";
21
+ import { createWebSocketStream, WebSocketServer } from "ws";
16
22
  import {
17
23
  boundedInteger,
18
24
  parseResize,
@@ -21,12 +27,88 @@ import {
21
27
  } from "./terminal-protocol.mjs";
22
28
 
23
29
  const terminalShell = "/bin/bash";
30
+ /** The guest's `sshd -i`, with fixed argv; nothing a client sends reaches it. */
31
+ const sshd = "/usr/sbin/sshd";
32
+ const sshdArguments = ["-i", "-e", "-f", "/opt/fungi/sshd_config"];
33
+ /** What vmd supplies at boot (computer-start.sh); without them there is no SSH. */
34
+ const sshFiles = [
35
+ "/run/fungi-ssh/host_ed25519",
36
+ "/run/fungi-ssh/user_ca.pub",
37
+ "/run/fungi-ssh/principals",
38
+ ];
39
+ /** How long a hung-up SSH session's processes get after SIGTERM before SIGKILL. */
40
+ const sshKillGraceMs = 2_000;
24
41
  const maximumSessions = 16;
25
42
  const detachedLifetimeMs = 30 * 60 * 1_000;
26
43
  /** A client that cannot drain this much output reconnects and replays. */
27
44
  const maximumBufferedBytes = 4 * 1_024 * 1_024;
28
45
  const sessionPattern = /^[A-Za-z0-9._:-]{1,160}$/;
29
46
 
47
+ /**
48
+ * Every process below `root`, from /proc. sshd puts a session's command in a
49
+ * session of its own and ignores SIGTERM when it has no PTY, so neither the
50
+ * process group nor sshd's death reaches it: the tree is read while sshd lives.
51
+ */
52
+ function descendants(root) {
53
+ const children = new Map();
54
+ for (const name of readdirSync("/proc")) {
55
+ if (!/^[0-9]+$/u.test(name)) continue;
56
+ let stat;
57
+ try {
58
+ stat = readFileSync(`/proc/${name}/stat`, "utf8");
59
+ } catch (cause) {
60
+ // The process exited while the table was read.
61
+ if (cause.code === "ENOENT" || cause.code === "ESRCH") continue;
62
+ throw cause;
63
+ }
64
+ // "pid (comm) state ppid ...": comm may hold spaces and parentheses.
65
+ const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
66
+ const siblings = children.get(parent) ?? [];
67
+ siblings.push(Number(name));
68
+ children.set(parent, siblings);
69
+ }
70
+ const found = [];
71
+ const pending = [root];
72
+ while (pending.length > 0) {
73
+ for (const child of children.get(pending.pop()) ?? []) {
74
+ found.push(child);
75
+ pending.push(child);
76
+ }
77
+ }
78
+ return found;
79
+ }
80
+
81
+ function signal(pid, name) {
82
+ try {
83
+ process.kill(pid, name);
84
+ } catch (cause) {
85
+ // A process that is already gone is what cleanup wants.
86
+ if (cause.code !== "ESRCH")
87
+ console.error(`ssh cleanup could not signal ${String(pid)}`, cause);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * End an sshd and all it started: SIGTERM, then SIGKILL after a short grace.
93
+ * When sshd itself has already exited its children cannot be found, so the
94
+ * tree walk is skipped; after the grace sshd's own pid and group are left
95
+ * alone once it is gone (the number may be reused), while a descendant that
96
+ * was alive when the walk ran is still killed.
97
+ */
98
+ function killSshd(child) {
99
+ const pid = child.pid;
100
+ if (pid === undefined) return;
101
+ const exited = () => child.exitCode !== null || child.signalCode !== null;
102
+ const doomed = exited() ? [] : [pid, ...descendants(pid)];
103
+ signal(-pid, "SIGTERM");
104
+ for (const target of doomed) signal(target, "SIGTERM");
105
+ setTimeout(() => {
106
+ if (!exited()) signal(-pid, "SIGKILL");
107
+ for (const target of doomed)
108
+ if (target !== pid || !exited()) signal(target, "SIGKILL");
109
+ }, sshKillGraceMs).unref();
110
+ }
111
+
30
112
  function send(socket, frame) {
31
113
  if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(frame));
32
114
  }
@@ -41,24 +123,30 @@ function shellEnvironment(labels) {
41
123
  return environment;
42
124
  }
43
125
 
44
- /** Owns every PTY session in this container; nothing else spawns shells. */
126
+ /**
127
+ * Owns every PTY session in this container, and every `sshd -i` that serves an
128
+ * attached SSH socket. Nothing else spawns shells or login daemons.
129
+ */
45
130
  class TerminalSessions {
46
131
  #sessions = new Map();
132
+ #ssh = new Set();
133
+ #spawnSshd;
47
134
  #spawn;
48
135
  #now;
49
136
 
50
- constructor(spawn, now) {
137
+ constructor(spawn, now, spawnSshd = spawnFixedSshd) {
51
138
  this.#spawn = spawn;
52
139
  this.#now = now;
140
+ this.#spawnSshd = spawnSshd;
53
141
  }
54
142
 
55
143
  get size() {
56
- return this.#sessions.size;
144
+ return this.#sessions.size + this.#ssh.size;
57
145
  }
58
146
 
59
147
  /** Sessions with a socket attached now; detached shells do not count. */
60
148
  get attached() {
61
- let attached = 0;
149
+ let attached = this.#ssh.size;
62
150
  for (const session of this.#sessions.values())
63
151
  if (session.socket !== null) attached += 1;
64
152
  return attached;
@@ -112,6 +200,39 @@ class TerminalSessions {
112
200
  });
113
201
  }
114
202
 
203
+ /**
204
+ * Serve one SSH stream: a fresh `sshd -i` whose stdin and stdout are this
205
+ * socket's binary frames. It ends with either side, and never outlives it.
206
+ */
207
+ attachSsh(socket) {
208
+ if (!this.#makeRoom()) {
209
+ send(socket, { type: "error", message: "terminal session limit" });
210
+ socket.close(1013, "terminal session limit");
211
+ return;
212
+ }
213
+ const child = this.#spawnSshd();
214
+ const session = { socket, child };
215
+ this.#ssh.add(session);
216
+ const stream = createWebSocketStream(socket);
217
+ const finish = () => {
218
+ if (!this.#ssh.delete(session)) return;
219
+ stream.destroy();
220
+ killSshd(child);
221
+ if (socket.readyState === socket.OPEN) socket.close(1000, "sshd exited");
222
+ };
223
+ child.once("exit", finish);
224
+ child.once("error", finish);
225
+ socket.once("close", finish);
226
+ stream.on("error", finish);
227
+ child.stdin.on("error", finish);
228
+ child.stdout.on("error", finish);
229
+ stream.pipe(child.stdin);
230
+ child.stdout.pipe(stream);
231
+ socket.on("error", () => {
232
+ socket.terminate();
233
+ });
234
+ }
235
+
115
236
  /** Hang up sessions nobody has attached to for the detached lifetime. */
116
237
  reap() {
117
238
  const now = this.#now();
@@ -125,6 +246,10 @@ class TerminalSessions {
125
246
  }
126
247
 
127
248
  closeAll() {
249
+ for (const session of this.#ssh) {
250
+ session.socket.close(1001, "Computer stopping");
251
+ killSshd(session.child);
252
+ }
128
253
  for (const session of this.#sessions.values()) {
129
254
  session.socket?.close(1001, "Computer stopping");
130
255
  session.pty.kill("SIGHUP");
@@ -132,7 +257,7 @@ class TerminalSessions {
132
257
  }
133
258
 
134
259
  #makeRoom() {
135
- if (this.#sessions.size < maximumSessions) return true;
260
+ if (this.size < maximumSessions) return true;
136
261
  let oldest = null;
137
262
  for (const session of this.#sessions.values()) {
138
263
  if (session.detachedAt === null) continue;
@@ -186,7 +311,19 @@ class TerminalSessions {
186
311
  }
187
312
  }
188
313
 
189
- /** Serve `/health` and the `/pty` upgrade on one private container port. */
314
+ function spawnFixedSshd() {
315
+ return spawn(sshd, sshdArguments, {
316
+ cwd: "/",
317
+ // Its own process group, so one signal reaches sshd and its helpers.
318
+ detached: true,
319
+ // sshd's own log (VERBOSE, with each certificate's key id) goes to this
320
+ // process's stderr, which the container runtime collects.
321
+ stdio: ["pipe", "pipe", "inherit"],
322
+ env: { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin" },
323
+ });
324
+ }
325
+
326
+ /** Serve `/health` and the `/pty` and `/ssh` upgrades on one private container port. */
190
327
  export function startTerminalServer(port) {
191
328
  const sessions = new TerminalSessions(pty.spawn, () => Date.now());
192
329
  const sockets = new WebSocketServer({
@@ -209,6 +346,17 @@ export function startTerminalServer(port) {
209
346
  });
210
347
  server.on("upgrade", (request, socket, head) => {
211
348
  const url = new URL(request.url ?? "/", "http://localhost");
349
+ if (url.pathname === "/ssh") {
350
+ // A Computer whose boot supplied no SSH files has no SSH to offer.
351
+ if (!sshFiles.every((file) => existsSync(file))) {
352
+ socket.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");
353
+ return;
354
+ }
355
+ sockets.handleUpgrade(request, socket, head, (client) => {
356
+ sessions.attachSsh(client);
357
+ });
358
+ return;
359
+ }
212
360
  const id = url.searchParams.get("session");
213
361
  if (url.pathname !== "/pty" || id === null || !sessionPattern.test(id)) {
214
362
  socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
@@ -52,10 +52,11 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
52
52
  });
53
53
  import { patchInputSchema, patchOutputSchema, } from "@fungi.computer/computer-contract";
54
54
  import { boundExecStream } from "./exec-output.js";
55
+ import { workspaceRoot } from "./files.js";
55
56
  /** The packaged, pinned Codex engine owns patch parsing and the Workspace jail. */
56
57
  const nativePatch = {
57
58
  executable: "/opt/fungi/fungi-apply-patch",
58
- cwd: "/workspace",
59
+ cwd: workspaceRoot,
59
60
  timeoutMs: 30_000,
60
61
  mismatchExitCode: 23,
61
62
  };
package/dist/files.d.ts CHANGED
@@ -3,6 +3,16 @@ import type { SQLiteWorkspaceProvider, WorkspaceClient } from "@fungi.computer/c
3
3
  export type WorkspaceFiles = Pick<WorkspaceClient, "fs">;
4
4
  import type { FilesPort } from "@fungi.computer/knapsack";
5
5
  import { type ComputerFileGlobInput, type ComputerFileGrepInput, type ComputerFileListInput, type ComputerFileReplacement, type ComputerFileReplacementResult } from "@fungi.computer/computer-contract";
6
+ /**
7
+ * The guest's mount of the Workspace filesystem, and the working directory of
8
+ * exec and apply_patch. It is the one root an Agent's relative path means.
9
+ */
10
+ export declare const workspaceRoot = "/workspace";
11
+ /**
12
+ * The Workspace path an Agent's Files path names: what a shell in
13
+ * {@link workspaceRoot} would resolve. Absolute paths pass through unchanged.
14
+ */
15
+ export declare function agentWorkspacePath(path: string): string;
6
16
  export type WorkspaceFilesOwner = Readonly<{
7
17
  replaceFileIfUnchanged: (input: ComputerFileReplacement) => Promise<ComputerFileReplacementResult>;
8
18
  }>;
package/dist/files.js CHANGED
@@ -4,6 +4,18 @@ import { SearchVisibility } from "@fungi.computer/knapsack/files-search";
4
4
  import { imageReadResult, imageSniffBytes, imageTooLargeMessage, maximumImageBytes, sniffImageMimeType, } from "@fungi.computer/knapsack/files-read";
5
5
  import { replaceOutputSchema, } from "@fungi.computer/computer-contract";
6
6
  const utf8 = new TextEncoder();
7
+ /**
8
+ * The guest's mount of the Workspace filesystem, and the working directory of
9
+ * exec and apply_patch. It is the one root an Agent's relative path means.
10
+ */
11
+ export const workspaceRoot = "/workspace";
12
+ /**
13
+ * The Workspace path an Agent's Files path names: what a shell in
14
+ * {@link workspaceRoot} would resolve. Absolute paths pass through unchanged.
15
+ */
16
+ export function agentWorkspacePath(path) {
17
+ return posix.resolve(workspaceRoot, path);
18
+ }
7
19
  function entryType(entry) {
8
20
  if (entry.isSymbolicLink)
9
21
  return "symlink";
@@ -70,7 +82,8 @@ export function readBoundedWorkspaceText(provider, path, maximumBytes) {
70
82
  export function createWorkspaceFilesPort(workspace, owner) {
71
83
  const port = {
72
84
  async read(input) {
73
- const stat = await workspace.fs.stat(input.path);
85
+ const target = agentWorkspacePath(input.path);
86
+ const stat = await workspace.fs.stat(target);
74
87
  if (!stat.isFile)
75
88
  throw new Error(`Files path is not a file: ${input.path}`);
76
89
  if (input.offset > stat.size) {
@@ -86,7 +99,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
86
99
  };
87
100
  }
88
101
  // The first read covers the sniff window whatever the caller's limit.
89
- const windowBytes = await readBytes(workspace, input.path, input.offset, Math.min(input.offset === 0
102
+ const windowBytes = await readBytes(workspace, target, input.offset, Math.min(input.offset === 0
90
103
  ? Math.max(input.limit, imageSniffBytes)
91
104
  : input.limit, stat.size - input.offset));
92
105
  if (windowBytes.byteLength === 0) {
@@ -98,7 +111,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
98
111
  throw new Error(imageTooLargeMessage(input.path, stat.size, maximumImageBytes));
99
112
  return imageReadResult(input.path, mimeType, windowBytes.byteLength === stat.size
100
113
  ? windowBytes
101
- : await readBytes(workspace, input.path, 0, stat.size));
114
+ : await readBytes(workspace, target, 0, stat.size));
102
115
  }
103
116
  const pageBytes = windowBytes.subarray(0, input.limit);
104
117
  const page = decodeUtf8Page(pageBytes, input.path, input.offset + pageBytes.byteLength < stat.size);
@@ -123,7 +136,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
123
136
  };
124
137
  },
125
138
  async glob(input, context) {
126
- const output = await visibleSearch(workspace, workspacePath(input.path), input.limit, (options) => workspace.fs.find(workspacePath(input.path), input.pattern, options), (entry) => entry.type === "dir", context?.signal);
139
+ const output = await visibleSearch(workspace, agentWorkspacePath(input.path), input.limit, (options) => workspace.fs.find(agentWorkspacePath(input.path), input.pattern, options), (entry) => entry.type === "dir", context?.signal);
127
140
  return {
128
141
  path: input.path,
129
142
  ...output,
@@ -141,7 +154,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
141
154
  };
142
155
  if (input.include !== undefined)
143
156
  options.include = input.include;
144
- const output = await visibleSearch(workspace, workspacePath(input.path), input.limit, (page) => workspace.fs.grep(input.pattern, workspacePath(input.path), {
157
+ const output = await visibleSearch(workspace, agentWorkspacePath(input.path), input.limit, (page) => workspace.fs.grep(input.pattern, agentWorkspacePath(input.path), {
145
158
  ...options,
146
159
  ...page,
147
160
  }), () => false, context?.signal);
@@ -156,7 +169,10 @@ export function createWorkspaceFilesPort(workspace, owner) {
156
169
  };
157
170
  },
158
171
  async replace(input) {
159
- return replaceOutputSchema.parse(await owner.replaceFileIfUnchanged(input));
172
+ return replaceOutputSchema.parse(await owner.replaceFileIfUnchanged({
173
+ ...input,
174
+ path: agentWorkspacePath(input.path),
175
+ }));
160
176
  },
161
177
  };
162
178
  return Object.freeze({
@@ -185,7 +201,7 @@ export function createWorkspaceFilesPort(workspace, owner) {
185
201
  });
186
202
  }
187
203
  function searchWorkspaceDirectory(workspace, input, signal) {
188
- const path = workspacePath(input.path);
204
+ const path = agentWorkspacePath(input.path);
189
205
  return visibleSearch(workspace, path, input.limit, async (options) => (await workspace.fs.readdir(path, options)).map((entry) => ({
190
206
  ...entry,
191
207
  path: childPath(path, entry.name),
@@ -209,12 +225,6 @@ export async function listWorkspaceFiles(workspace, input) {
209
225
  nextOffset: output.truncated === null ? null : input.offset + output.results.length,
210
226
  };
211
227
  }
212
- /** Computer wire paths are absolute within its Workspace, even for relative Files inputs. */
213
- function workspacePath(path) {
214
- if (path === ".")
215
- return "/";
216
- return path.startsWith("/") ? path : `/${path}`;
217
- }
218
228
  const missingSchema = z.object({ code: z.literal("ENOENT") });
219
229
  /** A regular file's stat, or null when the path is absent or not a file. */
220
230
  async function fileStat(workspace, path) {
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import type { FilesPort } from "@fungi.computer/knapsack";
9
9
  import { z } from "zod";
10
10
  import { type ComputerExecutionBudget, type ComputerExecutionHostHooks, type ComputerExecRequest, type ComputerOperationResult, type ComputerFileReadInput, type ComputerFileByteReadInput, type ComputerFileReplacement, type ComputerFileReplacementResult, type ComputerValue, writeInputSchema, writeOutputSchema, processLogsOutputSchema, processWaitOutputSchema, type ComputerProcess } from "@fungi.computer/computer-contract";
11
11
  import { createWorkspaceFilesPort } from "./files.js";
12
- import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement } from "./on-box-vm.js";
12
+ import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement, type OnBoxVmSshCertificate } from "./on-box-vm.js";
13
13
  import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ComputerSize, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
14
14
  import { LocalBackendConnections } from "./local-backend.js";
15
15
  /** Files needs only the native Workspace lease and its atomic replacement door. */
@@ -64,6 +64,10 @@ export declare class ComputerBackendUnavailableError extends Error {
64
64
  readonly code: "no_backend" | "backend_unavailable";
65
65
  constructor(code: "no_backend" | "backend_unavailable");
66
66
  }
67
+ /** SSH needs a guest sshd behind a host signer, which only an on-box VM has. */
68
+ export declare class ComputerSshUnavailableError extends Error {
69
+ constructor();
70
+ }
67
71
  declare class ComputerDurableObject extends DurableObject<ComputerEnv> {
68
72
  get bindings(): ComputerEnv;
69
73
  get state(): DurableObjectState;
@@ -145,6 +149,12 @@ declare class ContainerComputer extends ContainerComputerBase {
145
149
  * write there must not depend on a guest having booted first.
146
150
  */
147
151
  protected readyWorkspace(): Promise<Workspace>;
152
+ /**
153
+ * A host's one-time work before the first Files operation reaches the
154
+ * Workspace. It runs outside the file queue, so an implementation may use
155
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
156
+ */
157
+ protected prepareFiles(): Promise<void>;
148
158
  /** `getWorkspace(stub)` reaches the current generation through this door. */
149
159
  __getWorkspaceStub(): Promise<WorkspaceStub>;
150
160
  /**
@@ -227,6 +237,15 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
227
237
  * placeholder origin and a path/query with the Hub route prefix removed.
228
238
  */
229
239
  protected portPreviewAfterAcceptance(portInput: number, request: Request, accept: () => void): Promise<Response>;
240
+ /**
241
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
242
+ * and say what it found. It runs in the file queue and first pulls every
243
+ * attached guest, so a guest that is ahead of the Workspace is seen before
244
+ * the copy and the next push cannot overwrite what the guest changed. A guest
245
+ * whose state cannot be read (a runtime whose pull fails, or an attached
246
+ * machine that is offline) makes the answer "unknown": nothing is copied.
247
+ */
248
+ protected copyWorkspaceFileIfFree(from: string, to: string): Promise<"copied" | "absent" | "conflict" | "unknown">;
230
249
  getCapabilities(): Promise<{
231
250
  id: string;
232
251
  name: string;
@@ -332,6 +351,22 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
332
351
  * server, which keeps the PTY for `session` across socket reconnects.
333
352
  */
334
353
  protected terminalAfterAcceptance(request: Request, principalKey: string, accept: () => void): Promise<Response>;
354
+ /**
355
+ * Relay one authorized SSH transport to the guest terminal server's `/ssh`
356
+ * upgrade, which runs one `sshd -i` per connection as the runtime user. The
357
+ * SSH stream rides the WebSocket's binary frames; sshd authenticates it.
358
+ */
359
+ protected sshAfterAcceptance(request: Request, accept: () => void): Promise<Response>;
360
+ /**
361
+ * Ask this Computer's VM host to sign `publicKey` for its guest sshd. The
362
+ * caller decided who may; the host names this VM as the only principal.
363
+ */
364
+ protected sshCertificateAfterAcceptance(input: Readonly<{
365
+ publicKey: string;
366
+ keyId: string;
367
+ }>, accept: () => void): Promise<OnBoxVmSshCertificate & {
368
+ principal: string;
369
+ }>;
335
370
  protected withHostedResponse(_backing: HostedBacking, run: () => Promise<Response>): Promise<Response>;
336
371
  /** Host-owned display labels only; never credentials or provider URLs. */
337
372
  protected terminalDisplayEnvironment(): Promise<Record<string, string>>;
@@ -342,7 +377,7 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
342
377
  }
343
378
  export { WorkspaceProxy, WorkspaceServiceProxy };
344
379
  export { computerName, learnComputerName } from "./computer-name.js";
345
- export { OnBoxVmContainerHost, OnBoxVmTimeoutError, OnBoxVmUnavailableError, onBoxVmPlacement, onBoxVmIngress, type OnBoxVmEnv, type OnBoxVmOperation, type OnBoxVmState, } from "./on-box-vm.js";
380
+ export { OnBoxVmContainerHost, OnBoxVmTimeoutError, OnBoxVmUnavailableError, onBoxVmPlacement, onBoxVmIngress, type OnBoxVmEnv, type OnBoxVmOperation, type OnBoxVmSshCertificate, type OnBoxVmState, } from "./on-box-vm.js";
346
381
  export { computerContainerSleepAfterMs } from "./container-policy.js";
347
382
  export { isVaultExecutionContext, vaultExecutionContext, withVaultExecution, type VaultGrantPort, type VaultHolder, type VaultReferenceAdmission, type VaultSecretGrant, type VaultSubject, } from "./vault-references.js";
348
383
  export * from "./computer-backends.js";