@fungi.computer/computer 0.16.1 → 0.16.2

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.
@@ -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
@@ -145,6 +145,12 @@ declare class ContainerComputer extends ContainerComputerBase {
145
145
  * write there must not depend on a guest having booted first.
146
146
  */
147
147
  protected readyWorkspace(): Promise<Workspace>;
148
+ /**
149
+ * A host's one-time work before the first Files operation reaches the
150
+ * Workspace. It runs outside the file queue, so an implementation may use
151
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
152
+ */
153
+ protected prepareFiles(): Promise<void>;
148
154
  /** `getWorkspace(stub)` reaches the current generation through this door. */
149
155
  __getWorkspaceStub(): Promise<WorkspaceStub>;
150
156
  /**
@@ -227,6 +233,15 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
227
233
  * placeholder origin and a path/query with the Hub route prefix removed.
228
234
  */
229
235
  protected portPreviewAfterAcceptance(portInput: number, request: Request, accept: () => void): Promise<Response>;
236
+ /**
237
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
238
+ * and say what it found. It runs in the file queue and first pulls every
239
+ * attached guest, so a guest that is ahead of the Workspace is seen before
240
+ * the copy and the next push cannot overwrite what the guest changed. A guest
241
+ * whose state cannot be read (a runtime whose pull fails, or an attached
242
+ * machine that is offline) makes the answer "unknown": nothing is copied.
243
+ */
244
+ protected copyWorkspaceFileIfFree(from: string, to: string): Promise<"copied" | "absent" | "conflict" | "unknown">;
230
245
  getCapabilities(): Promise<{
231
246
  id: string;
232
247
  name: string;
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";
@@ -271,9 +271,6 @@ class ComputerDurableObject extends DurableObject {
271
271
  }
272
272
  }
273
273
  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
274
  /** A VM's container upgrade, rewritten by the verified on-box ingress door. */
278
275
  const vmUpgradePath = /^\/__vm\/([a-z0-9][a-z0-9-]{0,62})(\/ws)$/;
279
276
  /**
@@ -553,13 +550,22 @@ class ContainerComputer extends ContainerComputerBase {
553
550
  const workspace = this.workspace();
554
551
  await workspace.ready();
555
552
  if (!this.#rootedWorkspaces.has(workspace)) {
556
- await workspace.fs.mkdir(workspaceMountRoot, { recursive: true });
553
+ await workspace.fs.mkdir(workspaceRoot, { recursive: true });
557
554
  this.#rootedWorkspaces.add(workspace);
558
555
  }
559
556
  return workspace;
560
557
  }
558
+ /**
559
+ * A host's one-time work before the first Files operation reaches the
560
+ * Workspace. It runs outside the file queue, so an implementation may use
561
+ * {@link copyWorkspaceFileIfFree}. It must never throw.
562
+ */
563
+ prepareFiles() {
564
+ return Promise.resolve();
565
+ }
561
566
  /** `getWorkspace(stub)` reaches the current generation through this door. */
562
567
  async __getWorkspaceStub() {
568
+ await this.prepareFiles();
563
569
  return (await this.readyWorkspace()).stub();
564
570
  }
565
571
  /**
@@ -948,6 +954,52 @@ export class ComputerDO extends ContainerComputer {
948
954
  console.error(`Computer Workspace ${direction} failed`, cause);
949
955
  }
950
956
  }
957
+ /**
958
+ * Copy one Workspace file to a path nothing occupies, keeping the original,
959
+ * and say what it found. It runs in the file queue and first pulls every
960
+ * attached guest, so a guest that is ahead of the Workspace is seen before
961
+ * the copy and the next push cannot overwrite what the guest changed. A guest
962
+ * whose state cannot be read (a runtime whose pull fails, or an attached
963
+ * machine that is offline) makes the answer "unknown": nothing is copied.
964
+ */
965
+ async copyWorkspaceFileIfFree(from, to) {
966
+ return await this.#withBinaryFile(async () => {
967
+ const workspace = await this.readyWorkspace();
968
+ for (const backend of this.attachedBackends()) {
969
+ const id = attachedBackendId(backend);
970
+ try {
971
+ if (backend.kind === "local") {
972
+ if (!this.localConnections.online(id))
973
+ return "unknown";
974
+ }
975
+ else if (!(await this.containerRunning(backend)))
976
+ continue;
977
+ await workspace.pull(id);
978
+ }
979
+ catch (cause) {
980
+ if (cause instanceof ComputerContainersPausedError)
981
+ continue;
982
+ console.error(`Computer Workspace pull before a copy failed`, cause);
983
+ return "unknown";
984
+ }
985
+ }
986
+ const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
987
+ const outcome = this.state.storage.transactionSync(() => {
988
+ if (!workspaceFileExists(provider, from))
989
+ return "absent";
990
+ if (workspaceFileExists(provider, to))
991
+ return "conflict";
992
+ const stat = provider.statSync(from);
993
+ if (!stat.isFile())
994
+ return "absent";
995
+ provider.writeFileSync(to, new Uint8Array(provider.readRangeSync(from, 0, stat.size)));
996
+ return "copied";
997
+ });
998
+ if (outcome === "copied")
999
+ await this.#syncRunningHosted("push");
1000
+ return outcome;
1001
+ });
1002
+ }
951
1003
  /** One loop per Computer while any terminal socket is attached. */
952
1004
  #startTerminalSync(backing) {
953
1005
  if (this.#terminalSync !== undefined)
@@ -990,6 +1042,7 @@ export class ComputerDO extends ContainerComputer {
990
1042
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
991
1043
  async readFileAfterAcceptance(input, accept, maximumBytes = maximumFileBytes) {
992
1044
  const { path, byteOffset = 0, byteLength, } = readBytesInputSchema.parse(input);
1045
+ await this.prepareFiles();
993
1046
  return await this.#withBinaryFile(async () => {
994
1047
  const workspace = await this.readyWorkspace();
995
1048
  accept();
@@ -1056,6 +1109,7 @@ export class ComputerDO extends ContainerComputer {
1056
1109
  /** Resource hosts may accept authority after the file queue and Workspace are ready. */
1057
1110
  async writeFileAfterAcceptance(input, content, accept) {
1058
1111
  const { path } = readInputSchema.parse(input);
1112
+ await this.prepareFiles();
1059
1113
  await this.#withBinaryFile(async () => {
1060
1114
  const workspace = await this.readyWorkspace();
1061
1115
  accept();
@@ -1065,6 +1119,7 @@ export class ComputerDO extends ContainerComputer {
1065
1119
  }
1066
1120
  /** Keep one Workspace lease around one authorized structured Files operation. */
1067
1121
  async withFilesAfterAcceptance(accept, operation) {
1122
+ await this.prepareFiles();
1068
1123
  const workspace = await this.readyWorkspace();
1069
1124
  accept();
1070
1125
  await this.#syncRunningHosted("pull");
@@ -1121,6 +1176,7 @@ export class ComputerDO extends ContainerComputer {
1121
1176
  case "wait_process":
1122
1177
  return await this.waitProcessAfterAcceptance(input, accept);
1123
1178
  }
1179
+ await this.prepareFiles();
1124
1180
  const workspace = await this.readyWorkspace();
1125
1181
  accept();
1126
1182
  switch (selected) {
@@ -1720,6 +1776,7 @@ export class ComputerDO extends ContainerComputer {
1720
1776
  /** Stale-safe replacement with authority checked at the transaction boundary. */
1721
1777
  async replaceFileIfUnchangedAfterAcceptance(input, accept) {
1722
1778
  const replacement = replaceInputSchema.parse(input);
1779
+ await this.prepareFiles();
1723
1780
  const workspace = await this.readyWorkspace();
1724
1781
  await this.#syncRunningHosted("pull");
1725
1782
  const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
@@ -1774,7 +1831,10 @@ export function createComputerFilesPort(computer) {
1774
1831
  grep: (input) => withFiles((files) => files.grep(input)),
1775
1832
  replace: async (input, context) => {
1776
1833
  context.signal.throwIfAborted();
1777
- return await computer.replaceFileIfUnchanged(input);
1834
+ return await computer.replaceFileIfUnchanged({
1835
+ ...input,
1836
+ path: agentWorkspacePath(input.path),
1837
+ });
1778
1838
  },
1779
1839
  };
1780
1840
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",