@parcha/agentrun-computer 0.1.0-beta.35 → 0.1.0-beta.37

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 (148) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +423 -323
  3. package/box/Dockerfile +3 -1
  4. package/box/agentrun-archil +59 -7
  5. package/box/build-agent37.mjs +177 -0
  6. package/box/build-daytona.py +20 -4
  7. package/dist/agent37.d.ts +165 -0
  8. package/dist/agent37.js +759 -0
  9. package/dist/attach.d.ts +146 -0
  10. package/dist/attach.js +469 -0
  11. package/dist/browser.d.ts +61 -10
  12. package/dist/browser.js +125 -3
  13. package/dist/browserbase.d.ts +46 -23
  14. package/dist/browserbase.js +162 -17
  15. package/dist/chrome.d.ts +3 -4
  16. package/dist/chrome.js +6 -11
  17. package/dist/client.d.ts +33 -1
  18. package/dist/client.js +53 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/agent37.d.ts +96 -0
  22. package/dist/conformance/agent37.js +154 -0
  23. package/dist/conformance/cases/apps.d.ts +5 -0
  24. package/dist/conformance/cases/apps.js +160 -73
  25. package/dist/conformance/cases/health.js +14 -0
  26. package/dist/conformance/cases/index.js +2 -0
  27. package/dist/conformance/cases/provider.js +27 -1
  28. package/dist/conformance/cases/screen.d.ts +3 -0
  29. package/dist/conformance/cases/screen.js +18 -0
  30. package/dist/conformance/cases/settings.d.ts +29 -23
  31. package/dist/conformance/cases/settings.js +76 -58
  32. package/dist/conformance/cases/touch.js +19 -17
  33. package/dist/conformance/cases/ui.d.ts +2 -0
  34. package/dist/conformance/cases/ui.js +475 -0
  35. package/dist/conformance/cli.d.ts +9 -0
  36. package/dist/conformance/cli.js +28 -3
  37. package/dist/conformance/daytona.d.ts +4 -0
  38. package/dist/conformance/daytona.js +5 -0
  39. package/dist/conformance/e2b.d.ts +6 -0
  40. package/dist/conformance/e2b.js +9 -2
  41. package/dist/conformance/fixture.d.ts +1 -1
  42. package/dist/conformance/fixture.js +25 -1
  43. package/dist/conformance/modal.d.ts +17 -13
  44. package/dist/conformance/modal.js +18 -9
  45. package/dist/conformance/orgo.d.ts +3 -3
  46. package/dist/conformance/orgo.js +6 -8
  47. package/dist/conformance/phone-harness.d.ts +6 -2
  48. package/dist/conformance/phone-harness.js +21 -4
  49. package/dist/conformance/report.js +1 -1
  50. package/dist/conformance/runner.js +23 -4
  51. package/dist/conformance/sweep.d.ts +50 -0
  52. package/dist/conformance/sweep.js +187 -0
  53. package/dist/conformance/types.d.ts +11 -3
  54. package/dist/conformance/ui-fixture.d.ts +56 -0
  55. package/dist/conformance/ui-fixture.js +43 -0
  56. package/dist/create-requests.d.ts +51 -0
  57. package/dist/create-requests.js +121 -0
  58. package/dist/daytona.d.ts +15 -5
  59. package/dist/daytona.js +58 -38
  60. package/dist/descriptor.d.ts +29 -2
  61. package/dist/descriptor.js +13 -0
  62. package/dist/descriptors/agent37.d.ts +41 -0
  63. package/dist/descriptors/agent37.js +28 -0
  64. package/dist/descriptors/browserbase.d.ts +1 -0
  65. package/dist/descriptors/browserbase.js +2 -0
  66. package/dist/descriptors/daytona.d.ts +23 -2
  67. package/dist/descriptors/daytona.js +34 -2
  68. package/dist/descriptors/index.d.ts +66 -3
  69. package/dist/descriptors/index.js +5 -3
  70. package/dist/descriptors/kernel.d.ts +1 -0
  71. package/dist/descriptors/kernel.js +2 -0
  72. package/dist/descriptors/modal.d.ts +4 -0
  73. package/dist/descriptors/modal.js +11 -1
  74. package/dist/descriptors/orgo.d.ts +13 -1
  75. package/dist/descriptors/orgo.js +9 -3
  76. package/dist/descriptors/phone-harness.d.ts +6 -1
  77. package/dist/descriptors/phone-harness.js +5 -2
  78. package/dist/docker/egress.d.ts +4 -3
  79. package/dist/docker/egress.js +7 -6
  80. package/dist/docker.d.ts +7 -4
  81. package/dist/docker.js +278 -34
  82. package/dist/e2b.d.ts +9 -165
  83. package/dist/e2b.js +282 -1342
  84. package/dist/fake-ui-driver.d.ts +97 -0
  85. package/dist/fake-ui-driver.js +717 -0
  86. package/dist/host.d.ts +182 -0
  87. package/dist/host.js +1 -0
  88. package/dist/hosted/process.d.ts +67 -0
  89. package/dist/hosted/process.js +228 -0
  90. package/dist/hosted/provider.d.ts +146 -0
  91. package/dist/hosted/provider.js +1364 -0
  92. package/dist/hosted/scripts.d.ts +76 -0
  93. package/dist/{child.js → hosted/scripts.js} +93 -12
  94. package/dist/index.d.ts +11 -7
  95. package/dist/index.js +10 -7
  96. package/dist/janitor.d.ts +5 -4
  97. package/dist/janitor.js +1 -1
  98. package/dist/kernel.d.ts +17 -27
  99. package/dist/kernel.js +94 -18
  100. package/dist/kinds.d.ts +17 -5
  101. package/dist/kinds.js +20 -4
  102. package/dist/labels.d.ts +10 -2
  103. package/dist/labels.js +30 -7
  104. package/dist/local-chrome.d.ts +5 -5
  105. package/dist/local-chrome.js +10 -5
  106. package/dist/modal.d.ts +23 -181
  107. package/dist/modal.js +273 -1232
  108. package/dist/mount-archil.d.ts +25 -3
  109. package/dist/mount-archil.js +39 -8
  110. package/dist/orgo-channel.d.ts +3 -2
  111. package/dist/orgo-channel.js +5 -2
  112. package/dist/orgo-desktop.d.ts +23 -9
  113. package/dist/orgo-desktop.js +328 -66
  114. package/dist/orgo-names.d.ts +129 -3
  115. package/dist/orgo-names.js +211 -8
  116. package/dist/orgo-workspaces.d.ts +47 -0
  117. package/dist/orgo-workspaces.js +94 -0
  118. package/dist/orgo.d.ts +27 -10
  119. package/dist/orgo.js +411 -81
  120. package/dist/phone-harness.d.ts +31 -21
  121. package/dist/phone-harness.js +510 -681
  122. package/dist/png.d.ts +4 -0
  123. package/dist/png.js +27 -0
  124. package/dist/protocol.d.ts +338 -30
  125. package/dist/protocol.js +96 -3
  126. package/dist/provider.d.ts +97 -7
  127. package/dist/provider.js +24 -3
  128. package/dist/result.d.ts +1 -1
  129. package/dist/surface/api.d.ts +248 -0
  130. package/dist/surface/api.js +1 -0
  131. package/dist/surface/core.d.ts +42 -0
  132. package/dist/surface/core.js +393 -0
  133. package/dist/surface/index.d.ts +5 -0
  134. package/dist/surface/index.js +3 -0
  135. package/dist/surface/outline.d.ts +8 -0
  136. package/dist/surface/outline.js +50 -0
  137. package/dist/surface/script.d.ts +10 -0
  138. package/dist/surface/script.js +92 -0
  139. package/dist/ui-engine.d.ts +114 -0
  140. package/dist/ui-engine.js +798 -0
  141. package/package.json +17 -1
  142. package/dist/child.d.ts +0 -42
  143. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  144. package/dist/conformance/e2b-diagnose.js +0 -61
  145. package/dist/conformance/e2b-sweep.d.ts +0 -18
  146. package/dist/conformance/e2b-sweep.js +0 -132
  147. package/dist/conformance/modal-sweep.d.ts +0 -22
  148. package/dist/conformance/modal-sweep.js +0 -213
package/box/Dockerfile CHANGED
@@ -8,6 +8,8 @@
8
8
  # - FUSE (fuse3, and the client's own FUSE library). No firewall: init and every tool run in a network namespace of
9
9
  # their own with loopback alone (computerd init --own-network), while the archil client and serve, as root, stay in
10
10
  # the computer's, which reaches Archil;
11
+ # - nftables, for the helper's mount with an egress gateway alone: it redirects root's TCP to Archil's 8100 and 32050
12
+ # to computerd's archil relay on the computer's loopback;
11
13
  # - /workspace, empty and root's, where the helper mounts the run's folder.
12
14
  #
13
15
  # No sudo and no sudoers file: the image's user is root, so the provider's own exec (Daytona's toolbox, Modal's exec,
@@ -35,7 +37,7 @@ RUN set -eu; \
35
37
  case "$sum" in unpinned) echo "archil ${ARCHIL_VERSION} for $arch has no pinned sha256 yet: set ARCHIL_SHA256_$(echo "$arch" | tr a-z A-Z) to the package's sum" >&2; exit 1 ;; esac; \
36
38
  apt-get update -qq; \
37
39
  DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
38
- git curl ca-certificates nodejs npm ripgrep fuse3 >/dev/null; \
40
+ git curl ca-certificates nodejs npm ripgrep fuse3 nftables >/dev/null; \
39
41
  curl -fsSL -o /tmp/archil.deb "https://s3.amazonaws.com/archil-client/pkg/archil_${ARCHIL_VERSION}_${arch}.deb"; \
40
42
  echo "$sum /tmp/archil.deb" | sha256sum -c -; \
41
43
  DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends /tmp/archil.deb >/dev/null; \
@@ -3,8 +3,8 @@
3
3
  # at /workspace. It does four things and nothing else, each with fixed arguments to the archil client, to find and chown,
4
4
  # or to computerd:
5
5
  #
6
- # mount <disk> <region> agents/<agent>/runs/<run>/work the disk token as one line on fd 0
7
- # revoke <disk> <region> agents/<agent>/runs/<run>/work the disk token as one line on fd 0
6
+ # mount <disk> <region> agents/<agent>/runs/<run>/work [egress=<gateway>:<mount lane>:<data lane>] the token on fd 0
7
+ # revoke <disk> <region> agents/<agent>/runs/<run>/work [egress=<gateway>:<mount lane>:<data lane>] the token on fd 0
8
8
  # serve
9
9
  # checkin
10
10
  #
@@ -12,6 +12,15 @@
12
12
  # then every path of the mounted tree that is not agentrun-tool's is given to it (the links themselves, never
13
13
  # followed, and never past the mount): the disk's object API makes files root's, 644, and while a computer holds
14
14
  # the folder no outside write lands (Archil refuses it), so what the object API made is all there at the mount.
15
+ # With egress=<gateway>:<mount lane>:<data lane> (an IPv4 address and two ports, neither 8100 nor 32050), the
16
+ # archil client reaches Archil through that egress gateway alone, set up before it runs: `computerd archil-relay`
17
+ # listens on the computer's loopback (127.0.0.1:3129), and an nftables table of the helper's own (inet
18
+ # agentrun_archil, replaced whole) redirects root's TCP to 8100 (the mount endpoint) and 32050 (the file servers)
19
+ # to it and resets every other TCP to those ports. The relay carries each connection to the gateway's lane for
20
+ # its port with a PROXY v2 header naming the original destination, and the gateway admits it only to a
21
+ # destination that proves, by certificate, the Archil name the client asked for. A relay or a table that cannot
22
+ # be set up exits 4 and runs nothing; a relay that cannot reach the gateway later closes the connection, so the
23
+ # client reaches nothing. Both stay as long as the computer. With no egress, nothing of this is set.
15
24
  # revoke the same with --force: takes the folder back from a computer that is gone and left its delegation behind.
16
25
  # serve becomes `computerd sync-serve`, resident, holding no token: on its socket it takes one fixed byte and answers
17
26
  # the exit code of `archil sync /workspace` (every write so far durable), coalesced; it exits when the mount
@@ -20,7 +29,7 @@
20
29
  #
21
30
  # The archil client and serve run as root in the computer's own network namespace, which reaches Archil; init and every
22
31
  # tool run in a namespace of their own with loopback alone (computerd init --own-network), so the tools have no network
23
- # and reach no daemon of the provider's. This helper sets no firewall.
32
+ # and reach no daemon of the provider's. Without egress this helper sets no firewall.
24
33
  #
25
34
  # Install it root:root 0755 at /usr/local/sbin/agentrun-archil. The provider runs it as root through its own exec (the
26
35
  # image's user is root), never through sudo: the image has none. The run's tools run as agentrun-tool, through
@@ -29,12 +38,13 @@
29
38
  # The token is read from fd 0 and handed to archil only in the environment of its exec (archil reads it nowhere else),
30
39
  # never as an argument and never in a file. Every argument is checked here, whoever calls: a caller that is not root, a
31
40
  # wrong verb or count, a newline, a disk, region or folder of any other shape (an absolute path, `.` or `..`, an empty
32
- # or extra segment), a mountpoint that is a link or not empty, or a token of any other shape exits 2 and runs nothing.
41
+ # or extra segment), an egress of any other shape, a mountpoint that is a link or not empty, or a token of any other
42
+ # shape exits 2 and runs nothing.
33
43
  # A serve or checkin with nothing mounted exits 3 and runs nothing. A mount or revoke in a computer whose /proc lets a
34
44
  # user see another's processes (no hidepid=2 or invisible) exits 4 and runs nothing; each first remounts /proc with
35
45
  # hidepid=2, which a computer whose root may not remount leaves as it was. A mount the client refuses answers the
36
46
  # client's exit code; a mount whose tree cannot then be given to agentrun-tool exits 4. A serve whose computerd is not
37
- # root's alone exits 4.
47
+ # root's alone exits 4, and so does a mount or revoke with egress whose computerd is not.
38
48
  set -eu
39
49
  umask 077
40
50
  PATH=/usr/sbin:/usr/bin:/sbin:/bin
@@ -53,6 +63,7 @@ FIND=/usr/bin/find
53
63
  TOOL=agentrun-tool
54
64
  TOOL_UID=2510
55
65
  COMPUTERD=/opt/agentrun/computerd
66
+ NFT=/usr/sbin/nft
56
67
  SOCK=/run/agentrun-archil/archil.sock
57
68
  ROOT_UID=0
58
69
  HELD_TOP=/
@@ -76,12 +87,25 @@ matches() { printf '%s\n' "$1" | grep -Eqx -- "$2"; }
76
87
  # Whether $MP is in the mount table, as an archil mount (fuse.archil) or as anything (any).
77
88
  listed() { awk -v m="$MP" -v t="$1" '$2 == m && (t == "any" || $3 == t) { f = 1 } END { exit !f }' "$MOUNTS"; }
78
89
 
90
+ # The relay's port on the computer's loopback (computerd's archilrelay.Address) and Archil's two ports.
91
+ RELAY_PORT=3129
92
+ ARCHIL_PORTS='8100, 32050'
93
+
79
94
  take() {
80
- [ "$#" -eq 3 ] || refuse "$verb takes <disk> <region> agents/<agent>/runs/<run>/work"
81
- disk=$1 region=$2 folder=$3
95
+ [ "$#" -eq 3 ] || [ "$#" -eq 4 ] || refuse "$verb takes <disk> <region> agents/<agent>/runs/<run>/work and at most egress=<gateway>:<mount lane>:<data lane>"
96
+ disk=$1 region=$2 folder=$3 egress=${4-}
82
97
  matches "$disk" 'dsk-[0-9a-f]{16}|[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}/[A-Za-z0-9][A-Za-z0-9._-]{0,127}' || refuse "the disk is a disk id (dsk-...) or owner/name"
83
98
  matches "$region" '[a-z0-9]+-[a-z0-9][a-z0-9-]{0,62}' || refuse "the region is a provider, a dash and its region, lowercase letters, digits and dashes"
84
99
  matches "$folder" 'agents/[A-Za-z0-9][A-Za-z0-9_-]{0,127}/runs/[A-Za-z0-9][A-Za-z0-9_-]{0,127}/work' || refuse "the folder is agents/<agent>/runs/<run>/work, nothing else"
100
+ if [ "$#" -eq 4 ]; then
101
+ # egress=<IPv4>:<port>:<port>, as mount-archil.ts checks it; computerd archil-relay checks the same again.
102
+ port='([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])'
103
+ matches "$egress" "egress=((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]):$port:$port" || refuse "egress is egress=<gateway>:<mount lane>:<data lane>, an IPv4 address and two ports"
104
+ lanes=${egress#egress=}
105
+ gateway=${lanes%%:*} lanes=${lanes#*:}
106
+ mount_lane=${lanes%%:*} data_lane=${lanes#*:}
107
+ [ "$mount_lane" != "$data_lane" ] && [ "$mount_lane" != 8100 ] && [ "$mount_lane" != 32050 ] && [ "$data_lane" != 8100 ] && [ "$data_lane" != 32050 ] || refuse "egress's two lanes differ, and neither is 8100 or 32050, which the computer redirects to the relay"
108
+ fi
85
109
  # The computer's /proc (its last mount there) must hide each user's processes from the others, hidepid=2 or invisible
86
110
  # as newer kernels name it: else the run's tools could see this root archil client's. No image sets it, so it is
87
111
  # remounted so first, as root may where it holds CAP_SYS_ADMIN; a computer where that fails is refused by the check.
@@ -104,6 +128,8 @@ take() {
104
128
  IFS= read -r token || [ -n "$token" ] || refuse "no token on fd 0"
105
129
  [ "${#token}" -ge 16 ] && [ "${#token}" -le 4096 ] || refuse "the token is not a disk token"
106
130
  case "$token" in *[!A-Za-z0-9._~+/=-]*) refuse "the token is not a disk token" ;; esac
131
+ # Every argument and the token checked: the way out is set right before the client that takes it.
132
+ [ -z "$egress" ] || route
107
133
  # In the environment of archil's command alone (an assignment before the command, never exported to this shell's own,
108
134
  # which was fixed at its start), and archil runs as root, so no other user reads it there.
109
135
  rc=0
@@ -119,6 +145,32 @@ take() {
119
145
  }
120
146
  }
121
147
 
148
+ # The archil client's way out through the egress gateway: the relay first, so every redirected connection meets it, then
149
+ # the table, whole (made, dropped and made again in one transaction, so a mount found again replaces its own).
150
+ route() {
151
+ rootsalone || { printf 'agentrun-archil: computerd at %s is not root'"'"'s alone, so no relay runs and nothing is mounted\n' "$COMPUTERD" >&2; exit 4; }
152
+ "$COMPUTERD" archil-relay --gateway "$gateway" --mount-lane "$mount_lane" --data-lane "$data_lane" </dev/null || {
153
+ printf 'agentrun-archil: the archil relay to %s did not start, so nothing is mounted\n' "$gateway" >&2
154
+ exit 4
155
+ }
156
+ printf '%s\n' \
157
+ 'table inet agentrun_archil' \
158
+ 'delete table inet agentrun_archil' \
159
+ 'table inet agentrun_archil {' \
160
+ ' chain out_redirect {' \
161
+ ' type nat hook output priority -100; policy accept;' \
162
+ " meta skuid 0 meta nfproto ipv4 tcp dport { $ARCHIL_PORTS } redirect to :$RELAY_PORT" \
163
+ ' }' \
164
+ ' chain out_fence {' \
165
+ ' type filter hook output priority 0; policy accept;' \
166
+ " tcp dport { $ARCHIL_PORTS } reject with tcp reset" \
167
+ ' }' \
168
+ '}' | "$NFT" -f - || {
169
+ printf 'agentrun-archil: the redirect to the archil relay could not be set, so nothing is mounted\n' >&2
170
+ exit 4
171
+ }
172
+ }
173
+
122
174
  # serve and checkin act on the archil mount at $MP; with none there (a computer whose mount went), nothing is held, and
123
175
  # they say so with exit 3.
124
176
  held() {
@@ -0,0 +1,177 @@
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
+ }
@@ -4,22 +4,38 @@
4
4
  # a new snapshot, and the same recipe is the one built before: Daytona then refuses the name, and the printed name is
5
5
  # the one to use. Its size is 2 CPUs, 4 GB of memory and a 10 GB disk.
6
6
  #
7
- # python3 packages/computer/box/build-daytona.py
7
+ # With --gpu H100, the same image as a GPU snapshot: a snapshot carries its own resources, the GPU among them, so its
8
+ # sandboxes have one H100 (and daytona-gpu's 16 CPUs, 100 GB of memory and a 400 GB disk), in region earth, Daytona's
9
+ # GPU region. Its name is agentrun-archil-gpu-h100-<the recipe's hash>: the provider's gpuSnapshot option takes it, and
10
+ # reads the GPU from it. Another type is another snapshot.
11
+ #
12
+ # python3 packages/computer/box/build-daytona.py [--gpu H100]
8
13
  import hashlib
9
14
  import os
10
15
  import sys
11
16
 
12
- from daytona import CreateSnapshotParams, Daytona, Image, Resources
17
+ from daytona import CreateSnapshotParams, Daytona, GpuType, Image, Resources
18
+
19
+ GPUS = {"H100": GpuType.H100}
20
+
21
+ args = sys.argv[1:]
22
+ gpu = None
23
+ if args:
24
+ if len(args) != 2 or args[0] != "--gpu" or args[1] not in GPUS:
25
+ sys.exit(f"usage: build-daytona.py [--gpu {'|'.join(GPUS)}]")
26
+ gpu = args[1]
13
27
 
14
28
  here = os.path.dirname(os.path.abspath(__file__))
15
29
  recipe = b"".join(open(os.path.join(here, name), "rb").read() for name in ("Dockerfile", "agentrun-archil"))
16
- name = "agentrun-archil-" + hashlib.sha256(recipe).hexdigest()[:12]
30
+ digest = hashlib.sha256(recipe).hexdigest()[:12]
31
+ name = f"agentrun-archil-gpu-{gpu.lower()}-{digest}" if gpu else f"agentrun-archil-{digest}"
17
32
  print(f"build-daytona: snapshot {name}", file=sys.stderr)
18
33
  Daytona().snapshot.create(
19
34
  CreateSnapshotParams(
20
35
  name=name,
21
36
  image=Image.from_dockerfile(os.path.join(here, "Dockerfile")),
22
- resources=Resources(cpu=2, memory=4, disk=10),
37
+ resources=Resources(cpu=16, memory=100, disk=400, gpu=1, gpu_type=GPUS[gpu]) if gpu else Resources(cpu=2, memory=4, disk=10),
38
+ **({"region_id": "earth"} if gpu else {}),
23
39
  ),
24
40
  on_logs=lambda line: print(line, file=sys.stderr),
25
41
  )
@@ -0,0 +1,165 @@
1
+ import { Duplex } from "node:stream";
2
+ import { HostedProvider, type HostedOptions, type HostedTimeouts } from "./hosted/provider.js";
3
+ import type { KindCapabilities } from "./kinds.js";
4
+ import type { MountKind } from "./mount.js";
5
+ /** A readable side of an ssh2 channel, as this provider uses it: piped, or drained. */
6
+ export interface Ssh2Readable {
7
+ pipe(destination: NodeJS.WritableStream): unknown;
8
+ resume(): unknown;
9
+ }
10
+ /**
11
+ * The slice of an ssh2 channel this provider uses (ssh2@1.17.0 lib/Channel.js): the channel is stdout. No signal
12
+ * request: ssh2 sends one only while stdin is open (Channel.js:237-246), so a kill goes by the process group instead.
13
+ */
14
+ export interface Ssh2Channel extends Ssh2Readable {
15
+ readonly stderr: Ssh2Readable;
16
+ write(data: Uint8Array, callback?: (error?: Error | null) => void): boolean;
17
+ /** Sends end of file on stdin and keeps the channel open (Channel.js:200-205). */
18
+ eof(): void;
19
+ close(): void;
20
+ /** exit-status, or exit-signal with a null code (client.js:666-678). */
21
+ on(event: "exit", listener: (code: number | null, signal?: string) => void): unknown;
22
+ on(event: "close", listener: () => void): unknown;
23
+ on(event: "error", listener: (error: Error) => void): unknown;
24
+ }
25
+ /** The options of ssh2's Client.connect this provider gives (ssh2@1.17.0 lib/client.js). */
26
+ export interface Ssh2ConnectConfig {
27
+ sock: Duplex;
28
+ username: "root";
29
+ privateKey: string;
30
+ readyTimeout: number;
31
+ keepaliveInterval: number;
32
+ }
33
+ /** The slice of an ssh2 Client this provider uses. */
34
+ export interface Ssh2Client {
35
+ connect(config: Ssh2ConnectConfig): unknown;
36
+ exec(command: string, callback: (error: Error | undefined, channel: Ssh2Channel) => void): unknown;
37
+ end(): unknown;
38
+ destroy(): unknown;
39
+ once(event: "ready", listener: () => void): unknown;
40
+ once(event: "error", listener: (error: Error) => void): unknown;
41
+ on(event: "error", listener: (error: Error) => void): unknown;
42
+ on(event: "close", listener: () => void): unknown;
43
+ removeListener(event: "error", listener: (error: Error) => void): unknown;
44
+ }
45
+ /** The ssh2 package as this provider uses it: its Client class. The host's own, or anything with the same slice. */
46
+ export interface Ssh2Module {
47
+ Client: new () => Ssh2Client;
48
+ }
49
+ /** A WebSocket as this provider uses one: Node's global WebSocket (undici), which takes headers, or the same slice. */
50
+ export interface WebSocketLike {
51
+ binaryType: string;
52
+ readonly readyState: number;
53
+ readonly bufferedAmount: number;
54
+ send(data: Uint8Array): void;
55
+ close(code?: number, reason?: string): void;
56
+ addEventListener(type: "open" | "close" | "error", listener: (event: {
57
+ code?: number;
58
+ reason?: string;
59
+ message?: string;
60
+ }) => void): void;
61
+ addEventListener(type: "message", listener: (event: {
62
+ data: unknown;
63
+ }) => void): void;
64
+ }
65
+ export type WebSocketClass = new (url: string, init: {
66
+ headers: Record<string, string>;
67
+ }) => WebSocketLike;
68
+ /** One Agent37 instance as the REST API answers it (docs: agents-api/instances/object), as far as this provider reads it. */
69
+ export interface Agent37Instance {
70
+ id: string;
71
+ status: string;
72
+ status_reason?: {
73
+ code?: string;
74
+ message?: string;
75
+ } | null;
76
+ template?: string;
77
+ image_digest?: string | null;
78
+ type?: string;
79
+ region?: string;
80
+ resources?: {
81
+ cpu?: number;
82
+ memory?: number;
83
+ disk?: number;
84
+ };
85
+ public_ports?: unknown[];
86
+ name?: string | null;
87
+ metadata?: Record<string, string> | null;
88
+ auto_sleep?: boolean;
89
+ network?: unknown;
90
+ created?: number;
91
+ }
92
+ /** What Agent37 runs an instance on: a VM with its own kernel, or a gVisor sandbox (docs: agents-api/vm-instances). */
93
+ export type Agent37Type = "vm" | "default";
94
+ /** Where an instance runs (docs: agents-api/instances/create, region). */
95
+ export type Agent37Region = "us" | "eu" | "ap-south";
96
+ /** The Agent37 provider's options: the key, the SSH key and ssh2, then the shared adapter's (HostedOptions). */
97
+ export interface Agent37ProviderOptions extends Omit<HostedOptions, "label" | "maxLifetimeMs"> {
98
+ /** The workspace's API key (sk_live_...). The caller passes it; this provider never reads it from the environment. */
99
+ apiKey: string;
100
+ /**
101
+ * The private half of an SSH key registered on the same workspace (POST /v1/ssh-keys), in OpenSSH or PEM form: its
102
+ * contents, never a path. Every command reaches an instance over SSH as root with it.
103
+ */
104
+ sshKey: string;
105
+ /** The ssh2 package: the host's own, or anything with the same slice. */
106
+ ssh2: Ssh2Module;
107
+ /** The fetch every REST call goes through; default the global one. */
108
+ fetch?: typeof fetch;
109
+ /** The WebSocket the SSH stream rides; default Node's global one. */
110
+ WebSocket?: WebSocketClass;
111
+ /** Agent37's REST API; default https://api.agent37.com. */
112
+ apiUrl?: string;
113
+ /** The domain an instance's ports answer under, {id}-{port}.<domain>; default agent37.app. */
114
+ proxyDomain?: string;
115
+ /** vm (default): a whole VM with its own kernel; default: Agent37's gVisor sandbox. */
116
+ type?: Agent37Type;
117
+ /** us (default), eu or ap-south; outside us, type vm alone. */
118
+ region?: Agent37Region;
119
+ /**
120
+ * linux (default): no screen; desktop: an X server started through the daemon (Xvfb on :0 unless options.desktop says
121
+ * otherwise), so the spec's image is a template that has one: our box template, agentrun-box (box/build-agent37.mjs).
122
+ */
123
+ kind?: "desktop" | "linux";
124
+ /** The longest lifetime check takes: 24 h by default, the janitor's cap; Agent37 itself never ends an instance. */
125
+ maxLifetimeMs?: number;
126
+ timeouts?: Partial<HostedTimeouts>;
127
+ }
128
+ /** What create() takes: the provider's options, ssh2 optional (default the host's ssh2 package). */
129
+ export interface Agent37Options extends Omit<Agent37ProviderOptions, "ssh2"> {
130
+ ssh2?: Ssh2Module;
131
+ }
132
+ /** The port the platform's sshd answers on inside every instance, reached as {id}-22022.<domain> (cli.js:21, 720). */
133
+ export declare const AGENT37_SSH_PORT = 22022;
134
+ /** The mount kinds an Agent37 computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
135
+ export declare const MOUNT: readonly MountKind[];
136
+ /** The machine kind and groups of each configuration: kind linux (the default), and kind desktop on the box template. */
137
+ export declare const CAPABILITIES: readonly KindCapabilities[];
138
+ /** An answer of Agent37's REST API that is not a success: its HTTP status and the envelope's stable code (docs: errors). */
139
+ export declare class Agent37Error extends Error {
140
+ name: string;
141
+ readonly status: number;
142
+ readonly code: string | undefined;
143
+ constructor(status: number, code: string | undefined, message: string);
144
+ }
145
+ /** The SSH tunnel's WebSocket closed or failed before it opened, or while it carried the stream. */
146
+ export declare class Agent37TunnelError extends Error {
147
+ name: string;
148
+ }
149
+ /**
150
+ * An Agent37Provider from its options alone; it reads no environment. The key is options.apiKey and the SSH key
151
+ * options.sshKey, nowhere else (serve passes its AGENT37_API_KEY and AGENT37_SSH_KEY, the conformance module what it
152
+ * reads), and ssh2 is the host's package unless given. Throws in words when an option is missing or wrong, never echoing a key.
153
+ */
154
+ export declare function create(options: Agent37Options): Promise<Agent37Provider>;
155
+ /** The conformance CLI's module for Agent37: its live switch, the run's cap, its template and the drifted twin. */
156
+ export declare const conformance: () => Promise<typeof import("./conformance/agent37.js")>;
157
+ /**
158
+ * Computers that are Agent37 instances, on the shared adapter. A spec's image is an Agent37 template's name:
159
+ * "agent37-base", Agent37's plain Linux, for a sandbox; "agentrun-box", our box template with Xvfb, for a desktop.
160
+ */
161
+ export declare class Agent37Provider extends HostedProvider {
162
+ constructor(options: Agent37ProviderOptions);
163
+ }
164
+ /** The workspace a key reaches, in words, for the sweep's scope: the key's sha256 prefix, never the key. */
165
+ export declare function workspaceOf(apiKey: string, apiUrl?: string): string;