@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/dist/index.js CHANGED
@@ -67,7 +67,7 @@ import { SystemTrustContainerBackend } from "./container-system-trust.js";
67
67
  import { computerTransportBackend } from "./transport-backend.js";
68
68
  import { PullPendingTracker } from "./pull-pending.js";
69
69
  import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, moveInputSchema, moveOutputSchema, ComputerFileMoveError, ComputerFileRemoveError, removeInputSchema, removeOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, processWaitInputSchema, processWaitOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
70
- import { createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
70
+ import { agentWorkspacePath, createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceRoot, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
71
71
  import { computerExecutionResult } from "./execution-result.js";
72
72
  import { ComputerOperationRecord } from "./operation-record.js";
73
73
  import { createComputerExecutionLifecycle } from "./execution-lifecycle.js";
@@ -262,6 +262,13 @@ export class ComputerBackendUnavailableError extends Error {
262
262
  this.name = "ComputerBackendUnavailableError";
263
263
  }
264
264
  }
265
+ /** SSH needs a guest sshd behind a host signer, which only an on-box VM has. */
266
+ export class ComputerSshUnavailableError extends Error {
267
+ constructor() {
268
+ super("SSH needs a hosted Computer");
269
+ this.name = "ComputerSshUnavailableError";
270
+ }
271
+ }
265
272
  class ComputerDurableObject extends DurableObject {
266
273
  get bindings() {
267
274
  return this.env;
@@ -271,9 +278,6 @@ class ComputerDurableObject extends DurableObject {
271
278
  }
272
279
  }
273
280
  const ContainerComputerBase = withWorkspaceContainer(ComputerDurableObject);
274
- /** One Workspace built for one attached-backend set. */
275
- /** The directory every Computer backend mounts as its guest workspace. */
276
- const workspaceMountRoot = "/workspace";
277
281
  /** A VM's container upgrade, rewritten by the verified on-box ingress door. */
278
282
  const vmUpgradePath = /^\/__vm\/([a-z0-9][a-z0-9-]{0,62})(\/ws)$/;
279
283
  /**
@@ -553,13 +557,22 @@ class ContainerComputer extends ContainerComputerBase {
553
557
  const workspace = this.workspace();
554
558
  await workspace.ready();
555
559
  if (!this.#rootedWorkspaces.has(workspace)) {
556
- await workspace.fs.mkdir(workspaceMountRoot, { recursive: true });
560
+ await workspace.fs.mkdir(workspaceRoot, { recursive: true });
557
561
  this.#rootedWorkspaces.add(workspace);
558
562
  }
559
563
  return workspace;
560
564
  }
565
+ /**
566
+ * A host's one-time work before the first Files operation reaches the
567
+ * Workspace. It runs outside the file queue, so an implementation may use
568
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
569
+ */
570
+ prepareFiles() {
571
+ return Promise.resolve();
572
+ }
561
573
  /** `getWorkspace(stub)` reaches the current generation through this door. */
562
574
  async __getWorkspaceStub() {
575
+ await this.prepareFiles();
563
576
  return (await this.readyWorkspace()).stub();
564
577
  }
565
578
  /**
@@ -948,6 +961,52 @@ export class ComputerDO extends ContainerComputer {
948
961
  console.error(`Computer Workspace ${direction} failed`, cause);
949
962
  }
950
963
  }
964
+ /**
965
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
966
+ * and say what it found. It runs in the file queue and first pulls every
967
+ * attached guest, so a guest that is ahead of the Workspace is seen before
968
+ * the copy and the next push cannot overwrite what the guest changed. A guest
969
+ * whose state cannot be read (a runtime whose pull fails, or an attached
970
+ * machine that is offline) makes the answer "unknown": nothing is copied.
971
+ */
972
+ async copyWorkspaceFileIfFree(from, to) {
973
+ return await this.#withBinaryFile(async () => {
974
+ const workspace = await this.readyWorkspace();
975
+ for (const backend of this.attachedBackends()) {
976
+ const id = attachedBackendId(backend);
977
+ try {
978
+ if (backend.kind === "local") {
979
+ if (!this.localConnections.online(id))
980
+ return "unknown";
981
+ }
982
+ else if (!(await this.containerRunning(backend)))
983
+ continue;
984
+ await workspace.pull(id);
985
+ }
986
+ catch (cause) {
987
+ if (cause instanceof ComputerContainersPausedError)
988
+ continue;
989
+ console.error(`Computer Workspace pull before a copy failed`, cause);
990
+ return "unknown";
991
+ }
992
+ }
993
+ const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
994
+ const outcome = this.state.storage.transactionSync(() => {
995
+ if (!workspaceFileExists(provider, from))
996
+ return "absent";
997
+ if (workspaceFileExists(provider, to))
998
+ return "conflict";
999
+ const stat = provider.statSync(from);
1000
+ if (!stat.isFile())
1001
+ return "absent";
1002
+ provider.writeFileSync(to, new Uint8Array(provider.readRangeSync(from, 0, stat.size)));
1003
+ return "copied";
1004
+ });
1005
+ if (outcome === "copied")
1006
+ await this.#syncRunningHosted("push");
1007
+ return outcome;
1008
+ });
1009
+ }
951
1010
  /** One loop per Computer while any terminal socket is attached. */
952
1011
  #startTerminalSync(backing) {
953
1012
  if (this.#terminalSync !== undefined)
@@ -990,6 +1049,7 @@ export class ComputerDO extends ContainerComputer {
990
1049
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
991
1050
  async readFileAfterAcceptance(input, accept, maximumBytes = maximumFileBytes) {
992
1051
  const { path, byteOffset = 0, byteLength, } = readBytesInputSchema.parse(input);
1052
+ await this.prepareFiles();
993
1053
  return await this.#withBinaryFile(async () => {
994
1054
  const workspace = await this.readyWorkspace();
995
1055
  accept();
@@ -1056,6 +1116,7 @@ export class ComputerDO extends ContainerComputer {
1056
1116
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
1057
1117
  async writeFileAfterAcceptance(input, content, accept) {
1058
1118
  const { path } = readInputSchema.parse(input);
1119
+ await this.prepareFiles();
1059
1120
  await this.#withBinaryFile(async () => {
1060
1121
  const workspace = await this.readyWorkspace();
1061
1122
  accept();
@@ -1065,6 +1126,7 @@ export class ComputerDO extends ContainerComputer {
1065
1126
  }
1066
1127
  /** Keep one Workspace lease around one authorized structured Files operation. */
1067
1128
  async withFilesAfterAcceptance(accept, operation) {
1129
+ await this.prepareFiles();
1068
1130
  const workspace = await this.readyWorkspace();
1069
1131
  accept();
1070
1132
  await this.#syncRunningHosted("pull");
@@ -1121,6 +1183,7 @@ export class ComputerDO extends ContainerComputer {
1121
1183
  case "wait_process":
1122
1184
  return await this.waitProcessAfterAcceptance(input, accept);
1123
1185
  }
1186
+ await this.prepareFiles();
1124
1187
  const workspace = await this.readyWorkspace();
1125
1188
  accept();
1126
1189
  switch (selected) {
@@ -1653,6 +1716,41 @@ export class ComputerDO extends ContainerComputer {
1653
1716
  if (!query.success) {
1654
1717
  return Response.json({ error: "invalid terminal options" }, { status: 400 });
1655
1718
  }
1719
+ return await this.#terminalServerUpgrade(request, accept, async () => {
1720
+ const target = new URL("http://localhost/pty");
1721
+ target.search = new URLSearchParams({
1722
+ ...(await this.terminalDisplayEnvironment()),
1723
+ session: await sha256(JSON.stringify([principalKey, query.data.session])),
1724
+ cols: String(query.data.cols),
1725
+ rows: String(query.data.rows),
1726
+ }).toString();
1727
+ return target;
1728
+ });
1729
+ }
1730
+ /**
1731
+ * Relay one authorized SSH transport to the guest terminal server's `/ssh`
1732
+ * upgrade, which runs one `sshd -i` per connection as the runtime user. The
1733
+ * SSH stream rides the WebSocket's binary frames; sshd authenticates it.
1734
+ */
1735
+ async sshAfterAcceptance(request, accept) {
1736
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket")
1737
+ return new Response("Expected WebSocket upgrade", { status: 426 });
1738
+ return await this.#terminalServerUpgrade(request, accept, () => Promise.resolve(new URL("http://localhost/ssh")));
1739
+ }
1740
+ /**
1741
+ * Ask this Computer's VM host to sign `publicKey` for its guest sshd. The
1742
+ * caller decided who may; the host names this VM as the only principal.
1743
+ */
1744
+ async sshCertificateAfterAcceptance(input, accept) {
1745
+ const hosted = this.hostedRoute();
1746
+ if (hosted?.backing.kind !== "on-box-vm")
1747
+ throw new ComputerSshUnavailableError();
1748
+ accept();
1749
+ const signed = await this.onBoxVmHost(hosted.backing.hostId).sshCertificate(input);
1750
+ return { ...signed, principal: this.state.id.toString() };
1751
+ }
1752
+ /** The hosted terminal server's upgrade, once the runtime answers a probe. */
1753
+ async #terminalServerUpgrade(request, accept, target) {
1656
1754
  const hosted = this.hostedRoute();
1657
1755
  if (hosted === undefined)
1658
1756
  return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
@@ -1685,16 +1783,10 @@ export class ComputerDO extends ContainerComputer {
1685
1783
  // Hub rechecks current Computer/operation authority at the dispatch seam.
1686
1784
  accept();
1687
1785
  try {
1688
- const target = new URL("http://localhost/pty");
1689
- target.search = new URLSearchParams({
1690
- ...(await this.terminalDisplayEnvironment()),
1691
- session: await sha256(JSON.stringify([principalKey, query.data.session])),
1692
- cols: String(query.data.cols),
1693
- rows: String(query.data.rows),
1694
- }).toString();
1786
+ const url = await target();
1695
1787
  const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1696
1788
  .port(computerTerminalPort)
1697
- .fetch(new Request(target, request)));
1789
+ .fetch(new Request(url, request)));
1698
1790
  if (response.status === 101)
1699
1791
  this.#startTerminalSync(hosted.backing);
1700
1792
  return response;
@@ -1720,6 +1812,7 @@ export class ComputerDO extends ContainerComputer {
1720
1812
  /** Stale-safe replacement with authority checked at the transaction boundary. */
1721
1813
  async replaceFileIfUnchangedAfterAcceptance(input, accept) {
1722
1814
  const replacement = replaceInputSchema.parse(input);
1815
+ await this.prepareFiles();
1723
1816
  const workspace = await this.readyWorkspace();
1724
1817
  await this.#syncRunningHosted("pull");
1725
1818
  const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
@@ -1774,7 +1867,10 @@ export function createComputerFilesPort(computer) {
1774
1867
  grep: (input) => withFiles((files) => files.grep(input)),
1775
1868
  replace: async (input, context) => {
1776
1869
  context.signal.throwIfAborted();
1777
- return await computer.replaceFileIfUnchanged(input);
1870
+ return await computer.replaceFileIfUnchanged({
1871
+ ...input,
1872
+ path: agentWorkspacePath(input.path),
1873
+ });
1778
1874
  },
1779
1875
  };
1780
1876
  }
@@ -44,7 +44,13 @@ export declare function onBoxVmPlacement(env: OnBoxVmEnv, hostId: string | undef
44
44
  export declare class OnBoxVmUnavailableError extends Error {
45
45
  readonly operation: string;
46
46
  readonly status: number;
47
- constructor(operation: string, status: number, detail?: string);
47
+ /** The host's own words, up to 200 characters. */
48
+ readonly detail: string;
49
+ /** The host's typed refusal, such as `scratch_capacity`; null when it names none. */
50
+ readonly hostCode: string | null;
51
+ constructor(operation: string, status: number,
52
+ /** The host's own words, up to 200 characters. */
53
+ detail?: string);
48
54
  }
49
55
  declare const vmStateSchema: z.ZodObject<{
50
56
  running: z.ZodBoolean;
@@ -72,7 +78,14 @@ declare const vmInventorySchema: z.ZodArray<z.ZodObject<{
72
78
  }>;
73
79
  }, z.core.$strict>>;
74
80
  export type OnBoxVmInventory = z.infer<typeof vmInventorySchema>;
75
- export type OnBoxVmOperation = "status" | "start" | "restart" | "destroy" | "intercept" | "inventory";
81
+ export type OnBoxVmOperation = "status" | "start" | "restart" | "destroy" | "intercept" | "inventory" | "ssh-certificate";
82
+ /** vmd's signed answer: a user certificate for this VM and its per-boot host key. */
83
+ declare const vmSshCertificateSchema: z.ZodObject<{
84
+ certificate: z.ZodString;
85
+ serial: z.ZodString;
86
+ hostKey: z.ZodString;
87
+ }, z.core.$strict>;
88
+ export type OnBoxVmSshCertificate = z.infer<typeof vmSshCertificateSchema>;
76
89
  declare const OnBoxVmTimeoutError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
77
90
  readonly _tag: "OnBoxVmTimeoutError";
78
91
  } & Readonly<A>;
@@ -120,6 +133,15 @@ export declare class OnBoxVmContainerHost implements IWorkspaceContainerAPI {
120
133
  running(): Promise<boolean>;
121
134
  interceptOutboundHttp(host: string, workspace: WorkspaceRef): Promise<void>;
122
135
  interceptAllOutboundHttp(workspace: WorkspaceRef, token: string): Promise<void>;
136
+ /**
137
+ * Ask the host to sign `publicKey` for this VM's guest sshd. The host signs
138
+ * only this signed control request, names this VM as the one principal and
139
+ * returns the VM's per-boot host key; who may ask is the caller's decision.
140
+ */
141
+ sshCertificate(input: {
142
+ publicKey: string;
143
+ keyId: string;
144
+ }): Promise<OnBoxVmSshCertificate>;
123
145
  fetchPort(port: number, input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
124
146
  /**
125
147
  * A guest port, reached through the host service: the VM has no address
package/dist/on-box-vm.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { computerSizeSchema } from "./computer-backends.js";
3
3
  import * as Data from "effect/Data";
4
+ import * as Option from "effect/Option";
5
+ import * as Schema from "effect/Schema";
4
6
  import { SeamReplayPartitions, importSeamSigner, importSeamVerifiers, seamBodyDigest, seamHeader, signSeamRequest, unsignedPayload, verifySeamRequest, } from "@fungi.computer/seam";
5
7
  function accessHeaders(env) {
6
8
  const id = env.COMPUTER_VM_ACCESS_CLIENT_ID;
@@ -43,11 +45,19 @@ export function onBoxVmPlacement(env, hostId) {
43
45
  export class OnBoxVmUnavailableError extends Error {
44
46
  operation;
45
47
  status;
46
- constructor(operation, status, detail = "") {
48
+ detail;
49
+ /** The host's typed refusal, such as `scratch_capacity`; null when it names none. */
50
+ hostCode;
51
+ constructor(operation, status,
52
+ /** The host's own words, up to 200 characters. */
53
+ detail = "") {
47
54
  super(`On-box Computer VM ${operation} failed with HTTP ${String(status)}${detail ? `: ${detail}` : ""}`);
48
55
  this.operation = operation;
49
56
  this.status = status;
57
+ this.detail = detail;
50
58
  this.name = "OnBoxVmUnavailableError";
59
+ const body = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({ code: Schema.String })))(detail);
60
+ this.hostCode = Option.isSome(body) ? body.value.code : null;
51
61
  }
52
62
  }
53
63
  const signers = new Map();
@@ -97,6 +107,12 @@ const vmInventorySchema = z.array(vmStateSchema.extend({
97
107
  const vmStartSchema = z.lazy(() => z.strictObject({
98
108
  runtimeId: z.string().min(1).max(128),
99
109
  }));
110
+ /** vmd's signed answer: a user certificate for this VM and its per-boot host key. */
111
+ const vmSshCertificateSchema = z.strictObject({
112
+ certificate: z.string().min(1).max(4_096),
113
+ serial: z.string().regex(/^\d{1,20}$/u),
114
+ hostKey: z.string().min(1).max(1_024),
115
+ });
100
116
  /**
101
117
  * vmd's own traffic timer is only a backstop at its maximum: ComputerDO owns
102
118
  * idle sleep, so a kept-awake VM is not stopped by the host while it is quiet.
@@ -159,7 +175,7 @@ export class OnBoxVmContainerHost {
159
175
  signal,
160
176
  });
161
177
  if (!response.ok) {
162
- const detail = (await response.text()).slice(0, 200);
178
+ const detail = (await response.text()).slice(0, 400);
163
179
  throw new OnBoxVmUnavailableError(operation, response.status, detail);
164
180
  }
165
181
  return schema.parse(await response.json());
@@ -226,6 +242,17 @@ export class OnBoxVmContainerHost {
226
242
  workspace,
227
243
  });
228
244
  }
245
+ /**
246
+ * Ask the host to sign `publicKey` for this VM's guest sshd. The host signs
247
+ * only this signed control request, names this VM as the one principal and
248
+ * returns the VM's per-boot host key; who may ask is the caller's decision.
249
+ */
250
+ sshCertificate(input) {
251
+ return this.#call("ssh-certificate", vmSshCertificateSchema, {
252
+ publicKey: input.publicKey,
253
+ keyId: input.keyId,
254
+ });
255
+ }
229
256
  fetchPort(port, input, init) {
230
257
  return this.port(port).fetch(input, init);
231
258
  }