@parcha/agentrun-computer 0.1.0-beta.37 → 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 (124) hide show
  1. package/README.md +341 -260
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +14 -0
  4. package/box/build-daytona.py +2 -2
  5. package/box/build-e2b.mjs +41 -18
  6. package/box/recipe.d.mts +5 -0
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37.d.ts +18 -66
  9. package/dist/agent37.js +187 -464
  10. package/dist/box-image.d.ts +14 -0
  11. package/dist/box-image.js +24 -0
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/agent37.d.ts +9 -4
  20. package/dist/conformance/agent37.js +23 -11
  21. package/dist/conformance/browserbase.js +3 -3
  22. package/dist/conformance/cases/apps.d.ts +6 -0
  23. package/dist/conformance/cases/apps.js +18 -5
  24. package/dist/conformance/cases/isolation.d.ts +22 -5
  25. package/dist/conformance/cases/isolation.js +97 -16
  26. package/dist/conformance/cases/mount.js +5 -3
  27. package/dist/conformance/cases/provider.js +41 -0
  28. package/dist/conformance/cli.js +72 -11
  29. package/dist/conformance/daytona.d.ts +9 -20
  30. package/dist/conformance/daytona.js +12 -21
  31. package/dist/conformance/e2b.js +9 -4
  32. package/dist/conformance/exec-stream.d.ts +52 -0
  33. package/dist/conformance/exec-stream.js +493 -0
  34. package/dist/conformance/kernel.js +2 -2
  35. package/dist/conformance/modal.js +1 -1
  36. package/dist/conformance/orgo.js +2 -2
  37. package/dist/conformance/sweep.js +8 -8
  38. package/dist/conformance/types.d.ts +2 -2
  39. package/dist/create-requests.d.ts +1 -1
  40. package/dist/daytona.d.ts +17 -133
  41. package/dist/daytona.js +396 -1452
  42. package/dist/descriptor.d.ts +11 -4
  43. package/dist/descriptor.js +7 -0
  44. package/dist/descriptors/agent37.d.ts +3 -11
  45. package/dist/descriptors/agent37.js +9 -10
  46. package/dist/descriptors/daytona.d.ts +7 -6
  47. package/dist/descriptors/daytona.js +14 -7
  48. package/dist/descriptors/docker.d.ts +13 -1
  49. package/dist/descriptors/docker.js +3 -1
  50. package/dist/descriptors/e2b.d.ts +2 -9
  51. package/dist/descriptors/e2b.js +8 -8
  52. package/dist/descriptors/index.d.ts +25 -24
  53. package/dist/descriptors/index.js +1 -3
  54. package/dist/descriptors/modal.d.ts +2 -6
  55. package/dist/descriptors/modal.js +8 -6
  56. package/dist/descriptors/orgo.js +2 -1
  57. package/dist/descriptors/shared.d.ts +1 -1
  58. package/dist/descriptors/shared.js +2 -2
  59. package/dist/desktop.d.ts +18 -4
  60. package/dist/desktop.js +89 -9
  61. package/dist/docker/egress-main.js +23 -15
  62. package/dist/docker/egress.d.ts +6 -4
  63. package/dist/docker/egress.js +24 -16
  64. package/dist/docker/inspect.d.ts +2 -2
  65. package/dist/docker/inspect.js +5 -5
  66. package/dist/docker.d.ts +6 -11
  67. package/dist/docker.js +13 -16
  68. package/dist/drift.js +4 -4
  69. package/dist/e2b.d.ts +22 -130
  70. package/dist/e2b.js +163 -243
  71. package/dist/host.d.ts +136 -104
  72. package/dist/host.js +8 -1
  73. package/dist/hosted/network.d.ts +23 -0
  74. package/dist/hosted/network.js +77 -0
  75. package/dist/hosted/process.d.ts +24 -8
  76. package/dist/hosted/process.js +80 -44
  77. package/dist/hosted/provider.d.ts +38 -22
  78. package/dist/hosted/provider.js +500 -341
  79. package/dist/hosted/rest.d.ts +74 -0
  80. package/dist/hosted/rest.js +126 -0
  81. package/dist/hosted/scripts.d.ts +21 -3
  82. package/dist/hosted/scripts.js +76 -14
  83. package/dist/hosted/ssh-exec.d.ts +99 -0
  84. package/dist/hosted/ssh-exec.js +464 -0
  85. package/dist/hosted/values.d.ts +26 -0
  86. package/dist/hosted/values.js +63 -0
  87. package/dist/index.d.ts +2 -2
  88. package/dist/index.js +2 -2
  89. package/dist/isolation.d.ts +0 -2
  90. package/dist/isolation.js +3 -4
  91. package/dist/kernel.d.ts +0 -6
  92. package/dist/kernel.js +1 -5
  93. package/dist/kinds.d.ts +3 -1
  94. package/dist/local-chrome.d.ts +0 -6
  95. package/dist/local-chrome.js +1 -5
  96. package/dist/modal.d.ts +15 -86
  97. package/dist/modal.js +67 -185
  98. package/dist/mount-archil.d.ts +13 -8
  99. package/dist/mount-archil.js +27 -17
  100. package/dist/mount.d.ts +10 -4
  101. package/dist/mount.js +8 -4
  102. package/dist/orgo.d.ts +0 -9
  103. package/dist/orgo.js +8 -13
  104. package/dist/phone-harness.d.ts +0 -6
  105. package/dist/phone-harness.js +0 -4
  106. package/dist/protocol.d.ts +4 -1
  107. package/dist/protocol.js +1 -0
  108. package/dist/provider.d.ts +2 -2
  109. package/dist/providers.d.ts +15 -13
  110. package/dist/screen-watch.js +34 -6
  111. package/dist/surface/api.d.ts +14 -11
  112. package/dist/surface/core.d.ts +23 -5
  113. package/dist/surface/core.js +105 -15
  114. package/dist/surface/index.d.ts +1 -1
  115. package/dist/surface/index.js +1 -1
  116. package/dist/surface/outline.d.ts +2 -0
  117. package/dist/surface/outline.js +2 -1
  118. package/dist/surface/script.d.ts +4 -0
  119. package/dist/surface/script.js +11 -3
  120. package/dist/ui-engine.js +19 -3
  121. package/package.json +2 -3
  122. package/box/build-agent37.mjs +0 -177
  123. package/dist/conformance/daytona-sweep.d.ts +0 -18
  124. package/dist/conformance/daytona-sweep.js +0 -126
@@ -1,6 +1,6 @@
1
1
  import { MAX_CHUNK_BYTES } from "../protocol.js";
2
- import { outlineOf } from "./outline.js";
3
- export const SURFACE_OPS = ["observe", "act", "screenshot", "input.act", "apps.list", "apps.open", "shell.run", "files.read", "files.write", "files.list", "files.stat"];
2
+ import { outlineOf, quoted } from "./outline.js";
3
+ export const SURFACE_OPS = ["observe", "act", "screenshot", "input.act", "apps.list", "apps.open", "shell.run", "processes.start", "files.read", "files.write", "files.list", "files.stat"];
4
4
  /** A call the computer refused or failed: `kind` is the protocol's error kind (stale, unsupported, ...) or the
5
5
  * connection's (gone, timeout). */
6
6
  export class SurfaceError extends Error {
@@ -50,6 +50,7 @@ export function opsOf(groups) {
50
50
  "apps.list": has("apps"),
51
51
  "apps.open": has("apps"),
52
52
  "shell.run": has("exec"),
53
+ "processes.start": has("processes"),
53
54
  "files.read": has("files"),
54
55
  "files.write": has("files"),
55
56
  "files.list": has("files"),
@@ -65,8 +66,29 @@ function jsonText(value) {
65
66
  }
66
67
  /** The name of a step: its first key ("press", "click", ...). */
67
68
  export const stepName = (step) => Object.keys(step)[0] ?? "step";
68
- /** An act's answer as lines: one per step (named by `names`), then the expect, then whether it changed and the new
69
- * state, then the new observation's outline when there is one. */
69
+ /** The element a step acts on, by its ref: press's, set's, perform's, and click's or scroll's when they name one, or
70
+ * type's `into`. None for a step at a point or with no element. */
71
+ function stepRef(step) {
72
+ const at = "type" in step ? step.into : "press" in step ? step.press : "set" in step ? step.set : "perform" in step ? step.perform : "click" in step ? step.click : "scroll" in step ? step.scroll : undefined;
73
+ return typeof at === "string" ? at : undefined;
74
+ }
75
+ /** The most elements a surface remembers the names of, past which the oldest seen go first. */
76
+ const MAX_NAMED = 4000;
77
+ /** A step as its line in an act's answer names it: its name, then the element it acted on as the outline names it
78
+ * (`press @e3 button "Save"`, `type into @e4 textbox "PIN" [secure]`), where that element was seen in an observation;
79
+ * `[secure]` is that element's own flag. A type with no element names none: where the focus is when it runs (which
80
+ * app, which field, after what the steps before it, a person, or the system did) is not known here, so no reader of
81
+ * its line can tell it went to an ordinary field, and none shows what was typed. */
82
+ export function stepWords(step, named) {
83
+ const ref = stepRef(step);
84
+ const node = ref === undefined ? undefined : named(ref);
85
+ if (ref === undefined || node === undefined)
86
+ return stepName(step);
87
+ const target = [ref, node.role, ...(node.name ? [quoted(node.name)] : []), ...(node.secure ? ["[secure]"] : [])].join(" ");
88
+ return `${stepName(step)}${"type" in step ? " into" : ""} ${target}`;
89
+ }
90
+ /** An act's answer as lines: one per step (named by `names`, stepWords), then the expect, then whether it changed and
91
+ * the new state, then the new observation's outline when there is one. */
70
92
  export function actText(names, result) {
71
93
  const lines = result.steps.map((outcome, index) => {
72
94
  const name = names[index] ?? "step";
@@ -91,8 +113,11 @@ export function actText(names, result) {
91
113
  }
92
114
  /** A chord's keys: "ctrl+shift+t" is ctrl, shift, t; a trailing "+" is the plus key ("ctrl++"). */
93
115
  export const chordKeys = (chord) => chord.split(/\+(?=.)/).filter((key) => key !== "");
94
- /** The surface of one computer, over its connection. */
95
- 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 } = {}) {
96
121
  const card = cardOf(hello);
97
122
  const has = (group) => card.groups.includes(group);
98
123
  const ops = opsOf(card.groups);
@@ -102,6 +127,34 @@ export function createSurface(client, hello) {
102
127
  let lastApp;
103
128
  /** The app each observed state belongs to: an act that names a state and no app was run on that state's app. */
104
129
  const appOfState = new Map();
130
+ /** Every element observed, by ref, as an act's step line names it (stepWords): a ref stays good across states. */
131
+ const named = new Map();
132
+ /** Remembers an observation's elements. One with no name of its own (an Android row, a container whose text is in
133
+ * its children) takes its first named element's within a few levels, as a person reading the row would say it. */
134
+ function remember(nodes) {
135
+ const parentOf = new Map();
136
+ for (const node of nodes) {
137
+ parentOf.set(node.ref, node.parent);
138
+ named.delete(node.ref);
139
+ named.set(node.ref, { role: node.role, ...(node.name ? { name: node.name } : {}), secure: node.flags?.includes("secure") === true });
140
+ }
141
+ for (const node of nodes) {
142
+ if (!node.name)
143
+ continue;
144
+ let up = node.parent;
145
+ for (let level = 0; up !== undefined && level < 3; level += 1, up = parentOf.get(up)) {
146
+ const above = named.get(up);
147
+ if (above === undefined || above.name !== undefined)
148
+ break;
149
+ above.name = node.name;
150
+ }
151
+ }
152
+ for (const ref of named.keys()) {
153
+ if (named.size <= MAX_NAMED)
154
+ break;
155
+ named.delete(ref);
156
+ }
157
+ }
105
158
  async function call(method, params, signal) {
106
159
  const result = await client.call(method, params, { signal });
107
160
  if (!result.ok)
@@ -131,6 +184,7 @@ export function createSurface(client, hello) {
131
184
  lastState.set(result.app.id, result.state);
132
185
  appOfState.set(result.state, result.app.id);
133
186
  lastApp = result.app.id;
187
+ remember(result.nodes);
134
188
  const outline = outlineOf(head, result.nodes, result.truncated, result.empty);
135
189
  const imageNote = result.image ? `\nimage: ${result.image.width}×${result.image.height} px of the window's ${window.bounds[2]}×${window.bounds[3]} points` : "";
136
190
  return {
@@ -143,16 +197,27 @@ export function createSurface(client, hello) {
143
197
  ...(result.image ? { image: imageOf(result.image) } : {}),
144
198
  };
145
199
  }
146
- /** The screen as a state, for a computer with no ui group: its image, no elements. */
200
+ /** On a computer with no ui group, input goes to what is in front: an app a look or an act names is opened, or brought
201
+ * in front, first (apps.launch), so the per-step tools open an app as a script's computer.apps.open does. */
202
+ async function inFront(app, signal) {
203
+ if (app && has("apps"))
204
+ await call("apps.launch", { id: app }, signal);
205
+ }
206
+ /** The screen as a state, for a computer with no ui group: its image, no elements. With nothing in front, the head
207
+ * lists the apps to name. */
147
208
  async function screenState(signal) {
148
209
  const image = await shot(undefined, signal);
149
- const app = has("apps") ? ((await call("apps.list", {}, signal)).foreground ?? "") : "";
150
- const head = `screen ${image.width}×${image.height} px${app ? ` · ${app} in front` : ""} · this computer has no ui group: no elements; act at points of this image`;
210
+ const listed = has("apps") ? await call("apps.list", {}, signal) : undefined;
211
+ const app = listed?.foreground ?? "";
212
+ const front = app ? ` · ${app} in front` : listed ? ` · no app in front; name one as app to open it: ${listed.apps.map((one) => one.id).join(", ")}` : "";
213
+ const head = `screen ${image.width}×${image.height} px${front} · this computer has no ui group: no elements; act at points of this image`;
151
214
  return { id: "screen", app: { id: app, name: "" }, window: { id: "screen", bounds: [0, 0, image.width, image.height] }, elements: [], truncated: false, outline: head, image };
152
215
  }
153
216
  async function observe(args, signal) {
154
- if (!has("ui"))
217
+ if (!has("ui")) {
218
+ await inFront(args.app, signal);
155
219
  return screenState(signal);
220
+ }
156
221
  const imageInUi = args.image === true && card.features["ui.image"] === true;
157
222
  const result = await call("ui.observe", { ...(args.app ? { target: { app: args.app } } : {}), ...(imageInUi ? { image: true } : {}), ...(args.full ? { full: true } : {}) }, signal);
158
223
  const state = stateOf(result);
@@ -224,7 +289,12 @@ export function createSurface(client, hello) {
224
289
  if (!has("ui")) {
225
290
  if (args.expect)
226
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");
227
- return runInput(inputActionsOf(steps), Boolean(args.observe), signal);
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.
296
+ await inFront(args.app, signal);
297
+ return runInput(actions, Boolean(args.observe), signal);
228
298
  }
229
299
  const app = args.app;
230
300
  const state = args.state ?? (hasPoint(steps) ? lastState.get(app ?? lastApp ?? "") : undefined);
@@ -284,13 +354,24 @@ export function createSurface(client, hello) {
284
354
  }
285
355
  return entries.map((entry) => infoOf(entry.path, entry));
286
356
  }
287
- async function run(args, signal) {
288
- const command = args.command;
357
+ /** A command's argv: a string in the shell (cmd on Windows), a list as given. */
358
+ function argvOf(command) {
289
359
  const argv = typeof command === "string" ? (card.os === "windows" ? ["cmd.exe", "/d", "/s", "/c", command] : ["sh", "-c", command]) : Array.isArray(command) && command.every((part) => typeof part === "string") ? command : undefined;
290
360
  if (!argv || argv.length === 0)
291
361
  throw new SurfaceError("invalid", "command is a string (run by the shell) or a list: the program and its arguments");
362
+ return argv;
363
+ }
364
+ /** A program's env: on a desktop with an X display, its DISPLAY (the daemon gives its programs none: protocol.ts
365
+ * ExecRunParams), so an app opens where the screen is; the call's own variables over it. */
366
+ function envOf(given) {
367
+ const env = { ...(hello.display ? { DISPLAY: hello.display } : {}), ...(given ?? {}) };
368
+ return Object.keys(env).length > 0 ? { env } : {};
369
+ }
370
+ async function run(args, signal) {
371
+ const argv = argvOf(args.command);
292
372
  const timeoutMs = Math.min(Math.max(1, args.timeoutMs ?? DEFAULT_RUN_MS), MAX_RUN_MS);
293
- const result = await call("exec.run", { argv, timeoutMs, ...(args.cwd ? { cwd: args.cwd } : {}), ...(args.env ? { env: 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);
294
375
  return {
295
376
  stdout: Buffer.from(result.stdout, "base64").toString("utf8"),
296
377
  stderr: Buffer.from(result.stderr, "base64").toString("utf8"),
@@ -309,8 +390,10 @@ export function createSurface(client, hello) {
309
390
  case "observe":
310
391
  return observeAnswer(await observe(args, signal));
311
392
  case "act": {
393
+ // Each step named as its element was before the act: what it pressed, not what the press made of it.
394
+ const given = args.steps;
395
+ const names = Array.isArray(given) ? given.map((step) => stepWords(step, (ref) => named.get(ref))) : [];
312
396
  const result = await act(args, signal);
313
- const names = (args.steps ?? []).map(stepName);
314
397
  return { value: result, text: actText(names, result), images: result.after?.image ? [result.after.image] : [] };
315
398
  }
316
399
  case "input.act": {
@@ -340,6 +423,13 @@ export function createSurface(client, hello) {
340
423
  const value = await run(args, signal);
341
424
  return { value, text: jsonText(value), images: [] };
342
425
  }
426
+ case "processes.start": {
427
+ const argv = argvOf(args.command);
428
+ // orphans "keep": what the program starts (a launcher that forks its app and exits) runs on too.
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);
431
+ return { value: { pid: started.pid }, text: `started ${argv.join(" ")} (pid ${started.pid})`, images: [] };
432
+ }
343
433
  case "files.read": {
344
434
  const value = await readFile(pathOf(args), args.encoding, signal);
345
435
  return { value, text: value.length > MAX_TEXT_CHARS ? `${value.slice(0, MAX_TEXT_CHARS)}… (${value.length - MAX_TEXT_CHARS} more characters)` : value, images: [] };
@@ -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";
@@ -1,6 +1,8 @@
1
1
  import type { UiNode } from "../protocol.js";
2
2
  /** The most characters an outline takes: past it, the last line counts the elements left out. */
3
3
  export declare const OUTLINE_MAX_CHARS = 12000;
4
+ /** A name or value as the outline shows it: on one line, cut, in JSON's quotes. */
5
+ export declare const quoted: (text: string) => string;
4
6
  /** One element's line: `@e4 button "Save" = "value" ("what else it says") [focused]`. */
5
7
  export declare function lineOf(node: UiNode): string;
6
8
  /** The outline of an observation: `head`, then the elements within OUTLINE_MAX_CHARS, each indented under its parent,
@@ -5,7 +5,8 @@ const TEXT_CHARS = 80;
5
5
  /** The deepest indent, in levels: deeper elements line up at it. */
6
6
  const MAX_INDENT = 8;
7
7
  const clip = (text) => (text.length > TEXT_CHARS ? `${text.slice(0, TEXT_CHARS - 1)}…` : text);
8
- const quoted = (text) => JSON.stringify(clip(text.replace(/\s+/g, " ").trim()));
8
+ /** A name or value as the outline shows it: on one line, cut, in JSON's quotes. */
9
+ export const quoted = (text) => JSON.stringify(clip(text.replace(/\s+/g, " ").trim()));
9
10
  /** One element's line: `@e4 button "Save" = "value" ("what else it says") [focused]`. */
10
11
  export function lineOf(node) {
11
12
  const parts = [node.ref, node.role];
@@ -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)
@@ -72,6 +72,8 @@ export function bindComputer(call, card) {
72
72
  computer.input = freeze({ act: (actions) => call("input.act", { actions }) });
73
73
  if (has("exec"))
74
74
  computer.shell = freeze({ run: (command, options = {}) => call("shell.run", { ...options, command }) });
75
+ if (has("processes"))
76
+ computer.processes = freeze({ start: (command, options = {}) => call("processes.start", { ...options, command }) });
75
77
  if (has("files"))
76
78
  computer.files = freeze({
77
79
  read: (path, options = {}) => call("files.read", { ...options, path }),
@@ -85,8 +87,14 @@ export function bindComputer(call, card) {
85
87
  }
86
88
  /** The global a script's isolate holds the host's call under. */
87
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
+ }
88
96
  /** One line that binds `computer` in a script, over the global COMPUTER_CALL_GLOBAL: put it before the script's first
89
97
  * line (as `${scriptPrelude(card)} ${code}`) and the script's line numbers stay its own. */
90
98
  export function scriptPrelude(card) {
91
- return `const computer = (0, eval)(${JSON.stringify(`(${String(bindComputer)})`)})(${COMPUTER_CALL_GLOBAL}, ${JSON.stringify(card)});`;
99
+ return `const computer = ${computerOver(card, COMPUTER_CALL_GLOBAL)};`;
92
100
  }
package/dist/ui-engine.js CHANGED
@@ -286,9 +286,22 @@ const looksOf = (element) => JSON.stringify([element.role, element.name, valueOf
286
286
  * What a person would see of a view, for the settle and an act's changed: the window, and its elements when it has
287
287
  * any. The frame (a hash of its pixels) counts only with no elements (ui.tree off, or a window with none): a blinking
288
288
  * caret or a spinner redraws the frame under the same tree, which held each settle to maxSettleMs (Notes on a Mac: 13.5 s
289
- * against 1.9 s on the tree) and counted as a step's effect. A state keeps its frame, for a point with no element.
289
+ * against 1.9 s on the tree) and counted as a step's effect. A state keeps its frame, for a point with no element. Only
290
+ * what is on the window counts, with its bounds held inside it as ui.observe shows them: System Settings rebuilds its
291
+ * sidebar rows scrolled out of view each time its tree is read (so the list's content is a new height each time), and
292
+ * Finder's status bar below the window counts the free disk space, which held every settle there to maxSettleMs too.
293
+ * Nor which element each is (its key): a person sees none of that, and System Settings makes its sidebar's row at the
294
+ * window's edge anew on every read, the same words in the same place.
290
295
  */
291
- const fingerprint = (view) => JSON.stringify([view.window.id, view.window.bounds, view.elements.length > 0 ? view.elements.map((element) => [element.key, looksOf(element)]) : view.frame]);
296
+ const fingerprint = (view) => JSON.stringify([
297
+ view.window.id,
298
+ view.window.bounds,
299
+ view.elements.length > 0
300
+ ? view.elements.filter((element) => onWindow(view, element.bounds)).map((element) => looksOf({ ...element, bounds: insideWindow(element.bounds, view.window.bounds[2], view.window.bounds[3]) }))
301
+ : view.frame,
302
+ ]);
303
+ /** The bounds (window points) reach into the window. */
304
+ const onWindow = (view, [x, y, w, h]) => x < view.window.bounds[2] && 0 < x + w && y < view.window.bounds[3] && 0 < y + h;
292
305
  /** Whether an element says text, in its name, value or desc. */
293
306
  const holdsText = (element, text) => [element.name, valueOf(element), element.desc].some((said) => said?.includes(text) ?? false);
294
307
  /** An element's key scoped to its window: what a ref stands for. */
@@ -638,7 +651,10 @@ export class UiEngine {
638
651
  return "set" in step && result !== undefined && !("error" in result) && result.verified ? [index] : [];
639
652
  });
640
653
  if (sets.length > 0) {
641
- await sleep(SET_HOLD_MS, signal);
654
+ // Waited out on the clock: a timer may fire a millisecond early, and the hold is a floor.
655
+ const heldUntil = Date.now() + SET_HOLD_MS;
656
+ for (let left = SET_HOLD_MS; left > 0 && !signal.aborted; left = heldUntil - Date.now())
657
+ await sleep(left, signal);
642
658
  if (signal.aborted)
643
659
  return aborted("ui.act");
644
660
  read = await final();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.37",
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",
@@ -101,8 +101,7 @@
101
101
  "test:daytona": "node --test --test-timeout=1800000 test/daytona/*.test.mjs",
102
102
  "test:modal": "node --test --test-timeout=1800000 test/modal/*.test.mjs",
103
103
  "test:e2b": "node --test --test-timeout=1800000 test/e2b/*.test.mjs",
104
- "conformance": "node dist/conformance/cli.js",
105
- "daytona:sweep": "node dist/conformance/daytona-sweep.js"
104
+ "conformance": "node dist/conformance/cli.js"
106
105
  },
107
106
  "repository": {
108
107
  "type": "git",
@@ -1,177 +0,0 @@
1
- // Build the box image (this folder's Dockerfile, plus Xvfb for a desktop) 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 (the Dockerfile, the files it copies and DESKTOP below) 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 { createHash } from "node:crypto";
19
- import { readFileSync } from "node:fs";
20
- import { dirname, join } from "node:path";
21
- import { fileURLToPath } from "node:url";
22
- import { gzipSync } from "node:zlib";
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 besides DESKTOP: the Dockerfile and what it copies, as build-e2b.mjs hashes them. */
28
- export const RECIPE = ["Dockerfile", "agentrun-archil"];
29
- /**
30
- * What a desktop adds to box/Dockerfile: Xvfb, which the provider starts through computerd as the tool user on :0
31
- * (src/desktop.ts). Nothing starts it here, and no window manager, VNC server or sudo comes with it.
32
- */
33
- export const DESKTOP = `
34
- # A desktop (build-agent37.mjs): Xvfb, which the provider starts through computerd as the tool user on :0.
35
- RUN set -eu; \\
36
- apt-get update -qq; \\
37
- DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends xvfb >/dev/null; \\
38
- rm -rf /var/lib/apt/lists/*; \\
39
- command -v Xvfb >/dev/null || { echo "the image has no Xvfb" >&2; exit 1; }; \\
40
- ! command -v sudo >/dev/null 2>&1 || { echo "the image has sudo" >&2; exit 1; }
41
- `;
42
- /** How often a build's log is read, and the longest a build is waited for: Agent37's 45 minutes, and some. */
43
- const POLL_MS = 5_000;
44
- const BUILD_MS = 50 * 60_000;
45
-
46
- const here = dirname(fileURLToPath(import.meta.url));
47
-
48
- /** The recipe's files, read from dir, with the context's Dockerfile (box/Dockerfile and DESKTOP), and its 12-hex hash. */
49
- export function recipeOf(dir = here) {
50
- const files = Object.fromEntries(RECIPE.map((name) => [name, readFileSync(join(dir, name))]));
51
- const dockerfile = Buffer.concat([files.Dockerfile, Buffer.from(DESKTOP)]);
52
- const hash = createHash("sha256")
53
- .update(Buffer.concat([...RECIPE.map((name) => files[name]), Buffer.from(DESKTOP)]))
54
- .digest("hex")
55
- .slice(0, 12);
56
- return { hash, files: { ...files, Dockerfile: dockerfile } };
57
- }
58
-
59
- /** The template's description: the recipe's hash is how a later build knows this one is current. */
60
- export const descriptionOf = (hash) => `AgentRun's box image (Archil client and helper, tool user, Xvfb), recipe ${hash}`;
61
-
62
- /** One ustar header block: a file at the archive's root, owned by root. */
63
- function header(name, mode, size) {
64
- const block = Buffer.alloc(512);
65
- const octal = (value, width) => `${value.toString(8).padStart(width - 1, "0")}\0`;
66
- block.write(name, 0, 100);
67
- block.write(octal(mode, 8), 100);
68
- block.write(octal(0, 8), 108);
69
- block.write(octal(0, 8), 116);
70
- block.write(octal(size, 12), 124);
71
- block.write(octal(0, 12), 136);
72
- block.write(" ", 148);
73
- block.write("0", 156);
74
- block.write("ustar\0", 257);
75
- block.write("00", 263);
76
- let sum = 0;
77
- for (const byte of block) sum += byte;
78
- block.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148);
79
- return block;
80
- }
81
-
82
- /** The build's context: a gzipped tar of the Dockerfile (0644) and the helper (0755), at its root. */
83
- export function contextOf({ files }) {
84
- const parts = [];
85
- for (const [name, mode] of [
86
- ["Dockerfile", 0o644],
87
- ["agentrun-archil", 0o755],
88
- ]) {
89
- const body = files[name];
90
- parts.push(header(name, mode, body.length), body, Buffer.alloc((512 - (body.length % 512)) % 512));
91
- }
92
- parts.push(Buffer.alloc(1024));
93
- return gzipSync(Buffer.concat(parts));
94
- }
95
-
96
- /** An answer that is not a success, in Agent37's words (its envelope's code and message), never with the key. */
97
- async function failure(what, response) {
98
- const text = await response.text().catch(() => "");
99
- let error;
100
- try {
101
- error = JSON.parse(text)?.error;
102
- } catch {
103
- // Not JSON: its status alone.
104
- }
105
- const code = typeof error === "string" ? error : error?.code;
106
- const message = typeof error === "object" ? error?.message : undefined;
107
- return new Error(`${what} answered ${response.status}${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}`);
108
- }
109
-
110
- /**
111
- * Builds the recipe as the template NAME unless the workspace's template already names its hash, and answers the
112
- * template's name, revision and digest (revision and digest undefined when nothing was built). log gets the build's
113
- * log as it comes.
114
- */
115
- 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 }) {
116
- if (typeof apiKey !== "string" || apiKey === "") throw new Error("set AGENT37_API_KEY to the workspace's Agent37 API key, for this one command");
117
- const auth = { Authorization: `Bearer ${apiKey}`, Accept: "application/json" };
118
- const rest = async (method, path, body) => {
119
- const response = await fetch(`${apiUrl}${path}`, {
120
- method,
121
- headers: { ...auth, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
122
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
123
- signal: AbortSignal.timeout(60_000),
124
- });
125
- if (!response.ok) throw await failure(`${method} ${path}`, response);
126
- return response.json();
127
- };
128
- const recipe = recipeOf(dir);
129
- const description = descriptionOf(recipe.hash);
130
- log(`build-agent37: template ${NAME}, recipe ${recipe.hash}\n`);
131
-
132
- const current = await fetch(`${apiUrl}/v1/templates/${NAME}`, { headers: auth, signal: AbortSignal.timeout(60_000) });
133
- if (current.ok) {
134
- const template = await current.json();
135
- if (template?.description === description) {
136
- log(`build-agent37: ${NAME} revision ${template.revision} is this recipe already; nothing built\n`);
137
- return { name: NAME, revision: template.revision, digest: template.image_digest };
138
- }
139
- } else if (current.status !== 404) {
140
- throw await failure(`GET /v1/templates/${NAME}`, current);
141
- }
142
-
143
- const context = contextOf(recipe);
144
- const made = await rest("POST", "/v1/template-builds", { name: NAME, size_bytes: context.length, description });
145
- if (typeof made?.id !== "string" || typeof made?.upload_url !== "string") throw new Error("POST /v1/template-builds answered no id or upload_url");
146
- log(`build-agent37: build ${made.id}, context ${context.length} bytes\n`);
147
- // The presigned URL takes no Agent37 key, and fetch sends no Expect header.
148
- const uploaded = await fetch(made.upload_url, { method: "PUT", body: context, headers: { "Content-Type": "application/gzip" }, signal: AbortSignal.timeout(300_000) });
149
- if (!uploaded.ok) throw await failure("the context's upload", uploaded);
150
- await rest("POST", `/v1/template-builds/${made.id}/start`, {});
151
-
152
- const end = Date.now() + buildMs;
153
- let offset = 0;
154
- for (;;) {
155
- const read = await rest("GET", `/v1/template-builds/${made.id}/logs?offset=${offset}`);
156
- if (typeof read?.data === "string" && read.data !== "") log(read.data);
157
- if (Number.isSafeInteger(read?.offset)) offset = read.offset;
158
- if (read?.status === "succeeded") {
159
- const { name = NAME, revision, image_digest: digest } = read.template ?? {};
160
- log(`\nbuild-agent37: ${name} revision ${revision}, ${digest}\n`);
161
- return { name, revision, digest };
162
- }
163
- if (read?.status === "failed") throw new Error(`build ${made.id} failed: ${read.error?.code ?? "no code"}${read.error?.message ? `: ${read.error.message}` : ""}`);
164
- 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`);
165
- await new Promise((resolve) => setTimeout(resolve, pollMs));
166
- }
167
- }
168
-
169
- if (import.meta.main) {
170
- try {
171
- const { name } = await build({ apiKey: process.env.AGENT37_API_KEY });
172
- console.log(`template=${name}`);
173
- } catch (error) {
174
- console.error(`build-agent37: ${error.message}`);
175
- process.exit(1);
176
- }
177
- }
@@ -1,18 +0,0 @@
1
- import type { DaytonaProviderOptions } from "../daytona.js";
2
- /** A stream as main writes to it: done is called once the text is handed on. */
3
- export interface Writer {
4
- write(text: string, done?: (error?: Error | null) => void): unknown;
5
- }
6
- export interface SweepIo {
7
- /** Where the settings are read; default process.env. */
8
- env?: Record<string, string | undefined>;
9
- fetch?: DaytonaProviderOptions["fetch"];
10
- webSocket?: DaytonaProviderOptions["webSocket"];
11
- stdout?: Writer;
12
- stderr?: Writer;
13
- /** How long --after reads one deleted sandbox back before it counts as still there; default 60 s. */
14
- waitMs?: number;
15
- /** The pause between two reads of one sandbox; default 2 s. */
16
- pollMs?: number;
17
- }
18
- export declare function main(argv: string[], io?: SweepIo): Promise<number>;