@parcha/agentrun-computer 0.1.0-beta.38 → 0.1.0-beta.39

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.
Files changed (85) hide show
  1. package/README.md +101 -76
  2. package/box/README.md +2 -1
  3. package/box/recipe.d.mts +5 -0
  4. package/dist/agent37.d.ts +17 -4
  5. package/dist/agent37.js +96 -16
  6. package/dist/box-image.d.ts +14 -0
  7. package/dist/box-image.js +24 -0
  8. package/dist/computerd-linux-amd64 +0 -0
  9. package/dist/computerd-linux-arm64 +0 -0
  10. package/dist/computerd.json +2 -2
  11. package/dist/conformance/agent37.d.ts +9 -4
  12. package/dist/conformance/agent37.js +23 -11
  13. package/dist/conformance/browserbase.js +3 -3
  14. package/dist/conformance/cases/apps.d.ts +1 -1
  15. package/dist/conformance/cases/apps.js +1 -1
  16. package/dist/conformance/cases/isolation.d.ts +18 -3
  17. package/dist/conformance/cases/isolation.js +57 -6
  18. package/dist/conformance/cases/mount.js +4 -2
  19. package/dist/conformance/cases/provider.js +41 -0
  20. package/dist/conformance/cli.js +6 -5
  21. package/dist/conformance/e2b.js +9 -4
  22. package/dist/conformance/exec-stream.d.ts +7 -0
  23. package/dist/conformance/exec-stream.js +8 -1
  24. package/dist/conformance/kernel.js +2 -2
  25. package/dist/conformance/modal.js +1 -1
  26. package/dist/conformance/orgo.js +2 -2
  27. package/dist/daytona.d.ts +0 -5
  28. package/dist/daytona.js +16 -27
  29. package/dist/descriptor.d.ts +5 -3
  30. package/dist/descriptors/agent37.d.ts +3 -11
  31. package/dist/descriptors/agent37.js +9 -10
  32. package/dist/descriptors/daytona.d.ts +1 -1
  33. package/dist/descriptors/daytona.js +5 -2
  34. package/dist/descriptors/docker.d.ts +13 -1
  35. package/dist/descriptors/docker.js +3 -1
  36. package/dist/descriptors/e2b.d.ts +2 -9
  37. package/dist/descriptors/e2b.js +8 -8
  38. package/dist/descriptors/index.d.ts +21 -19
  39. package/dist/descriptors/index.js +1 -3
  40. package/dist/descriptors/modal.d.ts +2 -6
  41. package/dist/descriptors/modal.js +8 -6
  42. package/dist/descriptors/orgo.js +2 -1
  43. package/dist/docker/egress-main.js +23 -15
  44. package/dist/docker/egress.d.ts +6 -4
  45. package/dist/docker/egress.js +24 -16
  46. package/dist/docker/inspect.d.ts +2 -2
  47. package/dist/docker/inspect.js +5 -5
  48. package/dist/docker.d.ts +6 -5
  49. package/dist/docker.js +12 -11
  50. package/dist/e2b.d.ts +12 -2
  51. package/dist/e2b.js +42 -19
  52. package/dist/host.d.ts +54 -41
  53. package/dist/hosted/network.d.ts +23 -0
  54. package/dist/hosted/network.js +77 -0
  55. package/dist/hosted/process.d.ts +2 -0
  56. package/dist/hosted/process.js +5 -0
  57. package/dist/hosted/provider.d.ts +6 -4
  58. package/dist/hosted/provider.js +244 -136
  59. package/dist/hosted/rest.d.ts +10 -2
  60. package/dist/hosted/rest.js +9 -4
  61. package/dist/hosted/scripts.d.ts +19 -7
  62. package/dist/hosted/scripts.js +55 -18
  63. package/dist/{agent37-ssh.d.ts → hosted/ssh-exec.d.ts} +19 -9
  64. package/dist/{agent37-ssh.js → hosted/ssh-exec.js} +38 -19
  65. package/dist/hosted/values.d.ts +21 -0
  66. package/dist/hosted/values.js +55 -0
  67. package/dist/index.d.ts +1 -1
  68. package/dist/index.js +1 -1
  69. package/dist/isolation.d.ts +0 -2
  70. package/dist/isolation.js +3 -4
  71. package/dist/modal.d.ts +8 -2
  72. package/dist/modal.js +21 -15
  73. package/dist/mount-archil.d.ts +5 -4
  74. package/dist/mount-archil.js +5 -6
  75. package/dist/orgo.js +6 -4
  76. package/dist/providers.d.ts +4 -1
  77. package/dist/surface/api.d.ts +0 -9
  78. package/dist/surface/core.d.ts +7 -2
  79. package/dist/surface/core.js +12 -4
  80. package/dist/surface/index.d.ts +1 -1
  81. package/dist/surface/index.js +1 -1
  82. package/dist/surface/script.d.ts +4 -0
  83. package/dist/surface/script.js +9 -3
  84. package/package.json +1 -1
  85. package/box/build-agent37.mjs +0 -158
package/dist/modal.js CHANGED
@@ -1,8 +1,10 @@
1
- import { MODAL, MODAL_DEFAULT_IMAGE, MODAL_GPU } from "./descriptors/modal.js";
1
+ import { boxImageRef } from "./box-image.js";
2
+ import { MODAL } from "./descriptors/modal.js";
2
3
  import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, WORK } from "./drift.js";
3
4
  import { HostError } from "./host.js";
4
5
  import { HostedProvider } from "./hosted/provider.js";
5
6
  import { isWhole } from "./hosted/values.js";
7
+ import { ok } from "./result.js";
6
8
  /** A GPU as the SDK takes it: the type, then :count past one ("T4", "H100:8"). */
7
9
  const modalGpu = ({ type, count }) => (count === 1 ? type : `${type}:${count}`);
8
10
  /** The SDK's default server (modal-client@64880502:js/src/config.ts:143). */
@@ -123,7 +125,7 @@ class ModalHost {
123
125
  // The sandbox's command is the entrypoint, which becomes init: Modal finishes the sandbox when that main process
124
126
  // exits (sandbox.ts:384-388), so init's exit ends the computer.
125
127
  daemon: "pid1",
126
- // A GPU computer runs on gVisor, Modal's one GPU runtime (gpu.isolation): vm is every other computer's.
128
+ // A GPU computer runs on gVisor, Modal's one GPU runtime (its descriptor's gpu.isolation): vm is every other computer's.
127
129
  isolation: "vm",
128
130
  lifetime: "vendor",
129
131
  maxLifetimeMs: MAX_LIFETIME_MS,
@@ -131,13 +133,9 @@ class ModalHost {
131
133
  arch: "amd64",
132
134
  // No listener of Modal's own inside a sandbox is documented, so none is declared.
133
135
  vendorAgentPorts: [],
134
- // capabilities() reads a copy, so no caller can change the descriptor's own.
135
- gpu: MODAL_GPU,
136
136
  // Never root: each connection is Modal's exec of the stdio bridge, as Modal's root, outside the daemon.
137
137
  user: ["uid"],
138
- specFields: ["cpus", "memoryMb", "user"],
139
- labelRules: { max: MAX_TAGS, maxBytes: MAX_TAG_BYTES, measure: "pairs" },
140
- runtime: (req) => (req.gpu === undefined ? "vm" : "gvisor"),
138
+ labels: { count: MAX_TAGS, bytes: MAX_TAG_BYTES },
141
139
  };
142
140
  }
143
141
  errorCode(error) {
@@ -163,14 +161,14 @@ class ModalHost {
163
161
  }
164
162
  /**
165
163
  * Modal's own rules of a spec, over the adapter's: an image Modal can pull or holds (no option, no space), sizes in
166
- * the units Modal takes. No call; the adapter holds the tags to Modal's 512 bytes (labelRules).
164
+ * the units Modal takes. No call; the adapter holds the tags to Modal's 10 and 512 bytes (facts.labels).
167
165
  */
168
166
  check(spec) {
169
167
  const refusals = [];
170
168
  const refuse = (field, message) => refusals.push({ field, message });
171
169
  const { image, cpus, memoryMb } = spec;
172
170
  if (typeof image === "string" && (image.startsWith("-") || /\s/.test(image))) {
173
- refuse("image", `an image is a registry tag for linux/amd64 that Modal can pull, such as ${MODAL_DEFAULT_IMAGE}, or an image Modal holds by its id (im-...)`);
171
+ refuse("image", "an image is a registry tag for linux/amd64 that Modal can pull, such as debian:bookworm-slim, or an image Modal holds by its id (im-...)");
174
172
  }
175
173
  if (cpus !== undefined && !(isNumber(cpus) && cpus >= CPU_REQUEST * CPUS_PER_CORE)) {
176
174
  refuse("cpus", `cpus must be a number of CPUs of at least ${CPU_REQUEST * CPUS_PER_CORE}: Modal counts physical cores, 2 CPUs each, and requests ${CPU_REQUEST} of one by default`);
@@ -182,8 +180,8 @@ class ModalHost {
182
180
  /**
183
181
  * sandboxes.create in the app: the request's image (an im- id opened by fromId, else a registry tag) with HOME and the
184
182
  * workdir the computer's home, the entrypoint as its command, the lifetime as its timeout in the whole seconds the
185
- * SDK takes, the spec's sizes as limits over Modal's small default request, no network unless the adapter asks open
186
- * (an Archil computer's root, to reach Archil), and the labels as its tags.
183
+ * SDK takes, the spec's sizes as limits over Modal's small default request, no network unless the adapter asks egress
184
+ * (an Archil computer's root, to reach Archil, or the egress proxy of a network open or a list), and the labels as its tags, on gVisor for a GPU computer.
187
185
  */
188
186
  async create(req, ctx) {
189
187
  void ctx;
@@ -202,16 +200,15 @@ class ModalHost {
202
200
  const memoryMb = req.memoryMb ?? DEFAULT_MEMORY_MB;
203
201
  const cpuLimit = cpus / CPUS_PER_CORE;
204
202
  const params = {
205
- runtime: this.facts.runtime?.(req) ?? "vm",
206
- ...(req.gpu === undefined ? {} : { gpu: modalGpu(req.gpu) }),
203
+ ...(req.gpu === undefined ? { runtime: "vm" } : { runtime: "gvisor", gpu: modalGpu(req.gpu) }),
207
204
  command: [...req.command],
208
- timeoutMs: Math.ceil((req.lifetimeMs ?? 0) / 1000) * 1000,
205
+ timeoutMs: Math.ceil(req.lifetimeMs / 1000) * 1000,
209
206
  workdir: WORK,
210
207
  cpu: Math.min(CPU_REQUEST, cpuLimit),
211
208
  cpuLimit,
212
209
  memoryMiB: Math.min(MEMORY_REQUEST_MIB, memoryMb),
213
210
  memoryLimitMiB: memoryMb,
214
- ...(req.network === "none" ? { blockNetwork: true } : {}),
211
+ ...(req.egress ? {} : { blockNetwork: true }),
215
212
  tags: req.labels,
216
213
  };
217
214
  const image = base.dockerfileCommands([`ENV HOME=${WORK}`, `WORKDIR ${WORK}`]);
@@ -316,6 +313,15 @@ class ModalHost {
316
313
  * memoryMb) and name the uid its programs run as, never root.
317
314
  */
318
315
  export class ModalProvider extends HostedProvider {
316
+ /**
317
+ * The provider contract's prepareImage (its descriptor declares it): the box image the release publishes, by its
318
+ * public registry tag (box-image.ts), which has the Archil client and its root helper. No call: Modal pulls a
319
+ * registry tag at the first create from it in a workspace (images.fromRegistry), so there is nothing to pull ahead of
320
+ * it, and onWait is never told (the claim's wait is the create's). A sandbox with GPUs starts from the same image.
321
+ */
322
+ async prepareImage() {
323
+ return ok(boxImageRef());
324
+ }
319
325
  constructor(options) {
320
326
  const { app, timeouts = {}, ...rest } = options ?? {};
321
327
  const sdk = options?.sdk;
@@ -50,10 +50,11 @@ export type ProviderNote = (note: {
50
50
  */
51
51
  export declare const ARCHIL_REGION = "[a-z0-9]+-[a-z0-9][a-z0-9-]{0,62}";
52
52
  /**
53
- * The Archil rule every provider's check() adds to checkMount's, with no vendor call: network "none" (the tools have no
54
- * network: init's own namespace, loopback alone), the run's agentrun.run and agentrun.epoch labels (the claim the mount is made
55
- * under), a disk, region and folder of the helper's shapes, the folder of the labelled run, and a token of a disk
56
- * token's shape. No word holds a value of the mount but the folder's run, and only once the folder has the folder's shape.
53
+ * The Archil rule every provider's check() adds to checkMount's, with no vendor call: the run's agentrun.run and
54
+ * agentrun.epoch labels (the claim the mount is made under), a disk, region and folder of the helper's shapes, the folder
55
+ * of the labelled run, and a token of a disk token's shape. No word holds a value of the mount but the folder's run, and
56
+ * only once the folder has the folder's shape. The tools' network is the provider's descriptor's to take (none, or open
57
+ * and a list through init's egress proxy): the mount is root's, outside their network either way.
57
58
  */
58
59
  export declare function archilRefusals(spec: ComputerSpec): Refusal[];
59
60
  /** The sha256 of the helper this package ships (box/agentrun-archil): the one an image must have. */
@@ -37,10 +37,11 @@ const REGION = new RegExp(`^${ARCHIL_REGION}$`);
37
37
  const FOLDER = /^agents\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})\/runs\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})\/work$/;
38
38
  const TOKEN = /^[A-Za-z0-9._~+/=-]{16,4096}$/;
39
39
  /**
40
- * The Archil rule every provider's check() adds to checkMount's, with no vendor call: network "none" (the tools have no
41
- * network: init's own namespace, loopback alone), the run's agentrun.run and agentrun.epoch labels (the claim the mount is made
42
- * under), a disk, region and folder of the helper's shapes, the folder of the labelled run, and a token of a disk
43
- * token's shape. No word holds a value of the mount but the folder's run, and only once the folder has the folder's shape.
40
+ * The Archil rule every provider's check() adds to checkMount's, with no vendor call: the run's agentrun.run and
41
+ * agentrun.epoch labels (the claim the mount is made under), a disk, region and folder of the helper's shapes, the folder
42
+ * of the labelled run, and a token of a disk token's shape. No word holds a value of the mount but the folder's run, and
43
+ * only once the folder has the folder's shape. The tools' network is the provider's descriptor's to take (none, or open
44
+ * and a list through init's egress proxy): the mount is root's, outside their network either way.
44
45
  */
45
46
  export function archilRefusals(spec) {
46
47
  const mount = spec.mount;
@@ -48,8 +49,6 @@ export function archilRefusals(spec) {
48
49
  return [];
49
50
  const found = [];
50
51
  const refuse = (field, message) => found.push({ field, message });
51
- if (spec.network !== "none")
52
- refuse("network", 'a computer with an Archil mount takes network "none": its tools have no network, only loopback in init\'s own namespace');
53
52
  const labels = spec.labels ?? {};
54
53
  const run = labels[RUN_LABEL];
55
54
  const runWrong = runProblem(run);
package/dist/orgo.js CHANGED
@@ -14,6 +14,7 @@
14
14
  import { createHash, randomBytes, randomUUID } from "node:crypto";
15
15
  import { readFileSync } from "node:fs";
16
16
  import { fileURLToPath } from "node:url";
17
+ import { networkRefusal } from "./hosted/network.js";
17
18
  import { childCommands, daemonDrift } from "./hosted/scripts.js";
18
19
  import { DaemonClient } from "./client.js";
19
20
  import { ORGO, ORGO_BASE_IMAGE } from "./descriptors/orgo.js";
@@ -70,8 +71,9 @@ const DELETE_TRIES = 5;
70
71
  const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "labels", "gpu"]);
71
72
  /** The states in which a computer runs, or is on its way to. */
72
73
  const RUNNING = new Set(["running", "creating", "restarting", "updating", "resuming"]);
73
- /** Why a network other than "none" is refused: this configuration makes none alone. */
74
- const NETWORK_REFUSAL = 'an Orgo computer takes network "none" only: Orgo has no egress control, so its tools have no network of their own (init\'s namespace holds them to loopback), and open or an allowlist waits for the proxy-backed feature';
74
+ /** Why a network other than "none" is refused, in the words every hosted provider uses (hosted/network.ts), and why:
75
+ * this configuration makes none alone. */
76
+ const networkRefused = (network) => `${networkRefusal("Orgo", ORGO.network, network)}: an Orgo computer's tools have no network of their own (init's namespace holds them to loopback), and Orgo's adapter, unlike the shared hosted one, starts no egress proxy out of it`;
75
77
  /** The scripts the provider runs as root, each marked on its first line, its arguments after it. */
76
78
  const X11_SCRIPT = ["# agentrun-computer: orgo-x11", "s=$1", '[ -S "$s" ] || { echo "no X socket at $s"; exit 1; }'].join("\n");
77
79
  const LABELS_SCRIPT = ["# agentrun-computer: orgo-labels", 'p=$1; t=$2; d=${p%/*}', 'mkdir -p "$d" && printf \'%s\' "$t" > "$p.part" && chmod 0644 "$p.part" && mv -f "$p.part" "$p"'].join("\n");
@@ -270,7 +272,7 @@ export class OrgoProvider {
270
272
  refuse("image", `an image is "${BASE}" (Orgo's base desktop) or an Orgo template, namespace/name@version`);
271
273
  refusals.push(...checkTenure(given, this.capabilities(), "Orgo"));
272
274
  if (network !== "none")
273
- refuse("network", NETWORK_REFUSAL);
275
+ refuse("network", networkRefused(network));
274
276
  if (memoryMb !== undefined && !RAM_GB.some((gb) => gb * 1024 === memoryMb))
275
277
  refuse("memoryMb", "memoryMb is one of Orgo's sizes: 4096, 8192, 16384 or 32768");
276
278
  if (cpus !== undefined && !CPUS.includes(cpus))
@@ -1089,7 +1091,7 @@ export class OrgoProvider {
1089
1091
  if (problem)
1090
1092
  return fail("invalid", problem);
1091
1093
  if (policy !== undefined && policy !== "none")
1092
- return fail("refused", NETWORK_REFUSAL);
1094
+ return fail("refused", networkRefused(policy));
1093
1095
  const found = await this.#own(ref, signal);
1094
1096
  if (!found.ok)
1095
1097
  return found;
@@ -18,7 +18,10 @@ export interface ConformanceModule {
18
18
  createDriftedProvider?(options?: object): ComputerProvider | Promise<ComputerProvider>;
19
19
  /** A fresh run folder for a mount kind the provider declares, with its outside; undefined for a kind it cannot make. */
20
20
  mountFor?(kind: MountKind, options?: object): RunFolder | undefined | Promise<RunFolder | undefined>;
21
- conformanceImage?(options?: object): string | Promise<string>;
21
+ /** The run's image when --image names none; `signal` is the run's own (Ctrl-C), for one that makes or registers it. */
22
+ conformanceImage?(options?: object, context?: {
23
+ signal?: AbortSignal;
24
+ }): string | Promise<string>;
22
25
  conformanceNotes?: string[];
23
26
  /**
24
27
  * A provider on the shared adapter: its MachineHost from the same settings, with no live switch, since it makes
@@ -249,12 +249,3 @@ export interface ScreenshotArgs {
249
249
  /** [x, y, w, h] in screen pixels. */
250
250
  region?: Rect;
251
251
  }
252
- /** computer_script: run JavaScript against the `computer` object. */
253
- export interface ScriptArgs {
254
- /** An async function's body; `return` what you need. */
255
- code: string;
256
- /** For the run's timeline. */
257
- title?: string;
258
- /** Default 120000, at most 600000. */
259
- timeoutMs?: number;
260
- }
@@ -48,8 +48,13 @@ export declare function stepWords(step: UiStep, named: (ref: string) => Named |
48
48
  export declare function actText(names: readonly string[], result: ActResult): string;
49
49
  /** A chord's keys: "ctrl+shift+t" is ctrl, shift, t; a trailing "+" is the plus key ("ctrl++"). */
50
50
  export declare const chordKeys: (chord: string) => string[];
51
- /** The surface of one computer, over its connection. */
52
- export declare function createSurface(client: ComputerClient, hello: HelloResult): Surface;
51
+ /**
52
+ * The surface of one computer, over its connection. `cwd`: where shell.run and processes.start start a program whose
53
+ * call names no folder (the run's folder, where the computer mounts it); absent, where the computer starts it.
54
+ */
55
+ export declare function createSurface(client: ComputerClient, hello: HelloResult, { cwd }?: {
56
+ readonly cwd?: string;
57
+ }): Surface;
53
58
  /** A value with its images' data left out: the structured half of an answer whose images travel beside it. */
54
59
  export declare function withoutImageData(value: unknown): unknown;
55
60
  export {};
@@ -113,8 +113,11 @@ export function actText(names, result) {
113
113
  }
114
114
  /** A chord's keys: "ctrl+shift+t" is ctrl, shift, t; a trailing "+" is the plus key ("ctrl++"). */
115
115
  export const chordKeys = (chord) => chord.split(/\+(?=.)/).filter((key) => key !== "");
116
- /** The surface of one computer, over its connection. */
117
- export function createSurface(client, hello) {
116
+ /**
117
+ * The surface of one computer, over its connection. `cwd`: where shell.run and processes.start start a program whose
118
+ * call names no folder (the run's folder, where the computer mounts it); absent, where the computer starts it.
119
+ */
120
+ export function createSurface(client, hello, { cwd } = {}) {
118
121
  const card = cardOf(hello);
119
122
  const has = (group) => card.groups.includes(group);
120
123
  const ops = opsOf(card.groups);
@@ -287,6 +290,9 @@ export function createSurface(client, hello) {
287
290
  if (args.expect)
288
291
  throw new SurfaceError("unsupported", "this computer has no ui group, so it can't check an expect: take a screenshot to see the effect");
289
292
  const actions = inputActionsOf(steps);
293
+ // Kept on every act that names an app, never skipped for the app this surface last brought in front: raw input
294
+ // goes to whatever has focus, and focus can move where the surface never sees it (a person's take-over, a window a
295
+ // program the agent started opens, a dialog), so typing could land in another app. An act that names none makes no call.
290
296
  await inFront(args.app, signal);
291
297
  return runInput(actions, Boolean(args.observe), signal);
292
298
  }
@@ -364,7 +370,8 @@ export function createSurface(client, hello) {
364
370
  async function run(args, signal) {
365
371
  const argv = argvOf(args.command);
366
372
  const timeoutMs = Math.min(Math.max(1, args.timeoutMs ?? DEFAULT_RUN_MS), MAX_RUN_MS);
367
- const result = await call("exec.run", { argv, timeoutMs, ...(args.cwd ? { cwd: args.cwd } : {}), ...envOf(args.env) }, signal);
373
+ const folder = args.cwd || cwd;
374
+ const result = await call("exec.run", { argv, timeoutMs, ...(folder ? { cwd: folder } : {}), ...envOf(args.env) }, signal);
368
375
  return {
369
376
  stdout: Buffer.from(result.stdout, "base64").toString("utf8"),
370
377
  stderr: Buffer.from(result.stderr, "base64").toString("utf8"),
@@ -419,7 +426,8 @@ export function createSurface(client, hello) {
419
426
  case "processes.start": {
420
427
  const argv = argvOf(args.command);
421
428
  // orphans "keep": what the program starts (a launcher that forks its app and exits) runs on too.
422
- const started = await call("process.start", { argv, ...(typeof args.cwd === "string" && args.cwd ? { cwd: args.cwd } : {}), ...envOf(args.env), orphans: "keep" }, signal);
429
+ const folder = (typeof args.cwd === "string" && args.cwd) || cwd;
430
+ const started = await call("process.start", { argv, ...(folder ? { cwd: folder } : {}), ...envOf(args.env), orphans: "keep" }, signal);
423
431
  return { value: { pid: started.pid }, text: `started ${argv.join(" ")} (pid ${started.pid})`, images: [] };
424
432
  }
425
433
  case "files.read": {
@@ -2,4 +2,4 @@ export type * from "./api.js";
2
2
  export { actText, cardOf, chordKeys, createSurface, MAX_READ_BYTES, opsOf, stepName, SURFACE_OPS, SurfaceError, withoutImageData } from "./core.js";
3
3
  export type { Surface, SurfaceAnswer, SurfaceOp } from "./core.js";
4
4
  export { lineOf, OUTLINE_MAX_CHARS, outlineOf } from "./outline.js";
5
- export { bindComputer, COMPUTER_CALL_GLOBAL, scriptPrelude } from "./script.js";
5
+ export { bindComputer, COMPUTER_CALL_GLOBAL, computerOver, scriptPrelude } from "./script.js";
@@ -1,3 +1,3 @@
1
1
  export { actText, cardOf, chordKeys, createSurface, MAX_READ_BYTES, opsOf, stepName, SURFACE_OPS, SurfaceError, withoutImageData } from "./core.js";
2
2
  export { lineOf, OUTLINE_MAX_CHARS, outlineOf } from "./outline.js";
3
- export { bindComputer, COMPUTER_CALL_GLOBAL, scriptPrelude } from "./script.js";
3
+ export { bindComputer, COMPUTER_CALL_GLOBAL, computerOver, scriptPrelude } from "./script.js";
@@ -4,6 +4,10 @@ type Call = (op: string, args: unknown) => Promise<unknown>;
4
4
  export declare function bindComputer(call: Call, card: Card): Computer;
5
5
  /** The global a script's isolate holds the host's call under. */
6
6
  export declare const COMPUTER_CALL_GLOBAL = "__computerCall";
7
+ /** One expression, on one line, that is the `computer` object for a computer that is `card`, over `call`: the source of
8
+ * the isolate's `(op, args) => Promise` the object's calls go through (the host's codemode passes one that calls the
9
+ * run's tools, each a nested call of its own). */
10
+ export declare function computerOver(card: Card, call: string): string;
7
11
  /** One line that binds `computer` in a script, over the global COMPUTER_CALL_GLOBAL: put it before the script's first
8
12
  * line (as `${scriptPrelude(card)} ${code}`) and the script's line numbers stay its own. */
9
13
  export declare function scriptPrelude(card: Card): string;
@@ -21,8 +21,8 @@ export function bindComputer(call, card) {
21
21
  const result = (await call("act", args));
22
22
  if (result.after)
23
23
  last = result.after;
24
- // A refused step is the last one run (api.ts ActResult): the script stops there, as computer_script's words say, so
25
- // no later action lands on a screen it did not expect.
24
+ // A refused step is the last one run (api.ts ActResult): the script stops there, as its words say ("a refused step
25
+ // throws"), so no later action lands on a screen it did not expect.
26
26
  for (let index = 0; index < result.steps.length; index += 1) {
27
27
  const step = result.steps[index];
28
28
  if (step.error)
@@ -87,8 +87,14 @@ export function bindComputer(call, card) {
87
87
  }
88
88
  /** The global a script's isolate holds the host's call under. */
89
89
  export const COMPUTER_CALL_GLOBAL = "__computerCall";
90
+ /** One expression, on one line, that is the `computer` object for a computer that is `card`, over `call`: the source of
91
+ * the isolate's `(op, args) => Promise` the object's calls go through (the host's codemode passes one that calls the
92
+ * run's tools, each a nested call of its own). */
93
+ export function computerOver(card, call) {
94
+ return `(0, eval)(${JSON.stringify(`(${String(bindComputer)})`)})(${call}, ${JSON.stringify(card)})`;
95
+ }
90
96
  /** One line that binds `computer` in a script, over the global COMPUTER_CALL_GLOBAL: put it before the script's first
91
97
  * line (as `${scriptPrelude(card)} ${code}`) and the script's line numbers stay its own. */
92
98
  export function scriptPrelude(card) {
93
- return `const computer = (0, eval)(${JSON.stringify(`(${String(bindComputer)})`)})(${COMPUTER_CALL_GLOBAL}, ${JSON.stringify(card)});`;
99
+ return `const computer = ${computerOver(card, COMPUTER_CALL_GLOBAL)};`;
94
100
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.38",
3
+ "version": "0.1.0-beta.39",
4
4
  "description": "The open platform's computer protocol: a daemon in every computer, and one provisioner per vendor, starting with Docker.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -1,158 +0,0 @@
1
- // Build the box image (this folder's Dockerfile, its desktop included) as a template of an Agent37 workspace, through
2
- // Agent37's cloud build, with the workspace's key in AGENT37_API_KEY, and print the template's name: an Agent37 desktop
3
- // starts from it (src/descriptors/agent37.ts AGENT37_BOX_TEMPLATE), and so can an Archil computer.
4
- //
5
- // Agent37 keeps a template's revisions under one name (docs: agents-api/templates), so the name is fixed, agentrun-box,
6
- // and the recipe's hash (recipe.mjs: the Dockerfile and the files it copies) goes in the template's description: a
7
- // workspace whose template already names this hash is built nothing, and a changed recipe publishes a new revision,
8
- // which every instance made after it starts from. Builds are free, at most three at once per workspace and 45 minutes
9
- // each. The calls, in order (docs: templates, "Build an image in the cloud"):
10
- //
11
- // GET /v1/templates/agentrun-box its description, or 404
12
- // POST /v1/template-builds { name, size_bytes, description } -> { id, upload_url }
13
- // PUT <upload_url> the gzipped context, Dockerfile at its root, no Agent37 key
14
- // POST /v1/template-builds/{id}/start
15
- // GET /v1/template-builds/{id}/logs?offset=N until status succeeded or failed (a poll registers the template)
16
- //
17
- // AGENT37_API_KEY=... node packages/computer/box/build-agent37.mjs
18
- import { readFileSync } from "node:fs";
19
- import { dirname, join } from "node:path";
20
- import { fileURLToPath } from "node:url";
21
- import { gzipSync } from "node:zlib";
22
- import { RECIPE, recipeHash } from "./recipe.mjs";
23
-
24
- /** The template's name in every workspace: AGENT37_BOX_TEMPLATE. */
25
- export const NAME = "agentrun-box";
26
- export const API_URL = "https://api.agent37.com";
27
- /** Every file the image is made of: the Dockerfile (its desktop included) and what it copies (recipe.mjs). */
28
- export { RECIPE };
29
- /** How often a build's log is read, and the longest a build is waited for: Agent37's 45 minutes, and some. */
30
- const POLL_MS = 5_000;
31
- const BUILD_MS = 50 * 60_000;
32
-
33
- const here = dirname(fileURLToPath(import.meta.url));
34
-
35
- /** The recipe's files, read from dir, and its 12-hex hash: recipe.mjs's, the one every build and the published image carry. */
36
- export function recipeOf(dir = here) {
37
- return { hash: recipeHash(dir), files: Object.fromEntries(RECIPE.map((name) => [name, readFileSync(join(dir, name))])) };
38
- }
39
-
40
- /** The template's description: the recipe's hash is how a later build knows this one is current. */
41
- export const descriptionOf = (hash) => `AgentRun's box image (Archil client and helper, tool user, Xvfb, xfwm4 and apps), recipe ${hash}`;
42
-
43
- /** One ustar header block: a file at the archive's root, owned by root. */
44
- function header(name, mode, size) {
45
- const block = Buffer.alloc(512);
46
- const octal = (value, width) => `${value.toString(8).padStart(width - 1, "0")}\0`;
47
- block.write(name, 0, 100);
48
- block.write(octal(mode, 8), 100);
49
- block.write(octal(0, 8), 108);
50
- block.write(octal(0, 8), 116);
51
- block.write(octal(size, 12), 124);
52
- block.write(octal(0, 12), 136);
53
- block.write(" ", 148);
54
- block.write("0", 156);
55
- block.write("ustar\0", 257);
56
- block.write("00", 263);
57
- let sum = 0;
58
- for (const byte of block) sum += byte;
59
- block.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148);
60
- return block;
61
- }
62
-
63
- /** The build's context: a gzipped tar of the Dockerfile (0644) and the helper (0755), at its root. */
64
- export function contextOf({ files }) {
65
- const parts = [];
66
- for (const [name, mode] of [
67
- ["Dockerfile", 0o644],
68
- ["agentrun-archil", 0o755],
69
- ]) {
70
- const body = files[name];
71
- parts.push(header(name, mode, body.length), body, Buffer.alloc((512 - (body.length % 512)) % 512));
72
- }
73
- parts.push(Buffer.alloc(1024));
74
- return gzipSync(Buffer.concat(parts));
75
- }
76
-
77
- /** An answer that is not a success, in Agent37's words (its envelope's code and message), never with the key. */
78
- async function failure(what, response) {
79
- const text = await response.text().catch(() => "");
80
- let error;
81
- try {
82
- error = JSON.parse(text)?.error;
83
- } catch {
84
- // Not JSON: its status alone.
85
- }
86
- const code = typeof error === "string" ? error : error?.code;
87
- const message = typeof error === "object" ? error?.message : undefined;
88
- return new Error(`${what} answered ${response.status}${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}`);
89
- }
90
-
91
- /**
92
- * Builds the recipe as the template NAME unless the workspace's template already names its hash, and answers the
93
- * template's name, revision and digest (revision and digest undefined when nothing was built). log gets the build's
94
- * log as it comes.
95
- */
96
- export async function build({ apiKey, fetch = globalThis.fetch, apiUrl = API_URL, dir = here, log = (text) => process.stderr.write(text), pollMs = POLL_MS, buildMs = BUILD_MS }) {
97
- if (typeof apiKey !== "string" || apiKey === "") throw new Error("set AGENT37_API_KEY to the workspace's Agent37 API key, for this one command");
98
- const auth = { Authorization: `Bearer ${apiKey}`, Accept: "application/json" };
99
- const rest = async (method, path, body) => {
100
- const response = await fetch(`${apiUrl}${path}`, {
101
- method,
102
- headers: { ...auth, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
103
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
104
- signal: AbortSignal.timeout(60_000),
105
- });
106
- if (!response.ok) throw await failure(`${method} ${path}`, response);
107
- return response.json();
108
- };
109
- const recipe = recipeOf(dir);
110
- const description = descriptionOf(recipe.hash);
111
- log(`build-agent37: template ${NAME}, recipe ${recipe.hash}\n`);
112
-
113
- const current = await fetch(`${apiUrl}/v1/templates/${NAME}`, { headers: auth, signal: AbortSignal.timeout(60_000) });
114
- if (current.ok) {
115
- const template = await current.json();
116
- if (template?.description === description) {
117
- log(`build-agent37: ${NAME} revision ${template.revision} is this recipe already; nothing built\n`);
118
- return { name: NAME, revision: template.revision, digest: template.image_digest };
119
- }
120
- } else if (current.status !== 404) {
121
- throw await failure(`GET /v1/templates/${NAME}`, current);
122
- }
123
-
124
- const context = contextOf(recipe);
125
- const made = await rest("POST", "/v1/template-builds", { name: NAME, size_bytes: context.length, description });
126
- if (typeof made?.id !== "string" || typeof made?.upload_url !== "string") throw new Error("POST /v1/template-builds answered no id or upload_url");
127
- log(`build-agent37: build ${made.id}, context ${context.length} bytes\n`);
128
- // The presigned URL takes no Agent37 key, and fetch sends no Expect header.
129
- const uploaded = await fetch(made.upload_url, { method: "PUT", body: context, headers: { "Content-Type": "application/gzip" }, signal: AbortSignal.timeout(300_000) });
130
- if (!uploaded.ok) throw await failure("the context's upload", uploaded);
131
- await rest("POST", `/v1/template-builds/${made.id}/start`, {});
132
-
133
- const end = Date.now() + buildMs;
134
- let offset = 0;
135
- for (;;) {
136
- const read = await rest("GET", `/v1/template-builds/${made.id}/logs?offset=${offset}`);
137
- if (typeof read?.data === "string" && read.data !== "") log(read.data);
138
- if (Number.isSafeInteger(read?.offset)) offset = read.offset;
139
- if (read?.status === "succeeded") {
140
- const { name = NAME, revision, image_digest: digest } = read.template ?? {};
141
- log(`\nbuild-agent37: ${name} revision ${revision}, ${digest}\n`);
142
- return { name, revision, digest };
143
- }
144
- if (read?.status === "failed") throw new Error(`build ${made.id} failed: ${read.error?.code ?? "no code"}${read.error?.message ? `: ${read.error.message}` : ""}`);
145
- if (Date.now() > end) throw new Error(`build ${made.id} was not done within ${buildMs / 60_000} minutes (status ${read?.status}); Agent37 ends a build at 45`);
146
- await new Promise((resolve) => setTimeout(resolve, pollMs));
147
- }
148
- }
149
-
150
- if (import.meta.main) {
151
- try {
152
- const { name } = await build({ apiKey: process.env.AGENT37_API_KEY });
153
- console.log(`template=${name}`);
154
- } catch (error) {
155
- console.error(`build-agent37: ${error.message}`);
156
- process.exit(1);
157
- }
158
- }