@parcha/agentrun-computer 0.1.0-beta.34 → 0.1.0-beta.36

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 (107) hide show
  1. package/README.md +251 -46
  2. package/box/Dockerfile +3 -1
  3. package/box/agentrun-archil +59 -7
  4. package/box/build-daytona.py +20 -4
  5. package/dist/browser.d.ts +73 -23
  6. package/dist/browser.js +141 -17
  7. package/dist/browserbase.d.ts +48 -25
  8. package/dist/browserbase.js +176 -29
  9. package/dist/chrome.d.ts +3 -4
  10. package/dist/chrome.js +6 -11
  11. package/dist/computerd-linux-amd64 +0 -0
  12. package/dist/computerd-linux-arm64 +0 -0
  13. package/dist/conformance/browserbase.js +1 -1
  14. package/dist/conformance/cases/provider.js +78 -3
  15. package/dist/conformance/daytona.d.ts +4 -0
  16. package/dist/conformance/daytona.js +7 -1
  17. package/dist/conformance/e2b.js +2 -1
  18. package/dist/conformance/fixture.js +24 -2
  19. package/dist/conformance/kernel.js +1 -1
  20. package/dist/conformance/kind.js +2 -1
  21. package/dist/conformance/{local.d.ts → local-chrome.d.ts} +7 -7
  22. package/dist/conformance/{local.js → local-chrome.js} +11 -11
  23. package/dist/conformance/orgo.d.ts +11 -5
  24. package/dist/conformance/orgo.js +37 -8
  25. package/dist/conformance/phone-harness.js +2 -1
  26. package/dist/conformance/report.js +3 -2
  27. package/dist/conformance/runner.js +25 -7
  28. package/dist/conformance/types.d.ts +21 -8
  29. package/dist/conformance/types.js +10 -0
  30. package/dist/conformance/windows-fixture.d.ts +1 -0
  31. package/dist/conformance/windows-fixture.js +37 -0
  32. package/dist/daytona.d.ts +16 -35
  33. package/dist/daytona.js +87 -95
  34. package/dist/descriptor.d.ts +116 -0
  35. package/dist/descriptor.js +92 -0
  36. package/dist/descriptors/browserbase.d.ts +25 -0
  37. package/dist/descriptors/browserbase.js +20 -0
  38. package/dist/descriptors/daytona.d.ts +83 -0
  39. package/dist/descriptors/daytona.js +81 -0
  40. package/dist/descriptors/docker.d.ts +12 -0
  41. package/dist/descriptors/docker.js +17 -0
  42. package/dist/descriptors/e2b.d.ts +22 -0
  43. package/dist/descriptors/e2b.js +19 -0
  44. package/dist/descriptors/index.d.ts +256 -0
  45. package/dist/descriptors/index.js +19 -0
  46. package/dist/descriptors/kernel.d.ts +21 -0
  47. package/dist/descriptors/kernel.js +17 -0
  48. package/dist/descriptors/local-chrome.d.ts +17 -0
  49. package/dist/descriptors/local-chrome.js +21 -0
  50. package/dist/descriptors/modal.d.ts +54 -0
  51. package/dist/descriptors/modal.js +48 -0
  52. package/dist/descriptors/orgo.d.ts +99 -0
  53. package/dist/descriptors/orgo.js +49 -0
  54. package/dist/descriptors/phone-harness.d.ts +33 -0
  55. package/dist/descriptors/phone-harness.js +23 -0
  56. package/dist/descriptors/shared.d.ts +7 -0
  57. package/dist/descriptors/shared.js +6 -0
  58. package/dist/desktop.d.ts +4 -4
  59. package/dist/desktop.js +4 -4
  60. package/dist/docker/egress.d.ts +5 -4
  61. package/dist/docker/egress.js +7 -6
  62. package/dist/docker/image.js +17 -15
  63. package/dist/docker/inspect.d.ts +147 -0
  64. package/dist/docker/inspect.js +335 -0
  65. package/dist/docker.d.ts +6 -6
  66. package/dist/docker.js +53 -47
  67. package/dist/drift.d.ts +3 -145
  68. package/dist/drift.js +5 -334
  69. package/dist/e2b.d.ts +2 -8
  70. package/dist/e2b.js +17 -23
  71. package/dist/index.d.ts +9 -12
  72. package/dist/index.js +14 -12
  73. package/dist/isolation.js +2 -2
  74. package/dist/janitor.d.ts +20 -2
  75. package/dist/janitor.js +67 -19
  76. package/dist/kernel.d.ts +19 -29
  77. package/dist/kernel.js +110 -32
  78. package/dist/kinds.d.ts +59 -34
  79. package/dist/kinds.js +19 -117
  80. package/dist/labels.d.ts +20 -0
  81. package/dist/labels.js +62 -1
  82. package/dist/{local.d.ts → local-chrome.d.ts} +8 -9
  83. package/dist/{local.js → local-chrome.js} +26 -19
  84. package/dist/local-supervisor.d.ts +3 -3
  85. package/dist/local-supervisor.js +3 -3
  86. package/dist/modal.d.ts +6 -25
  87. package/dist/modal.js +86 -88
  88. package/dist/mount-archil.d.ts +25 -3
  89. package/dist/mount-archil.js +43 -12
  90. package/dist/orgo-channel.js +16 -13
  91. package/dist/orgo-desktop.d.ts +162 -0
  92. package/dist/orgo-desktop.js +1856 -0
  93. package/dist/orgo-names.d.ts +178 -0
  94. package/dist/orgo-names.js +287 -0
  95. package/dist/orgo.d.ts +34 -20
  96. package/dist/orgo.js +424 -173
  97. package/dist/phone-harness.d.ts +7 -12
  98. package/dist/phone-harness.js +70 -54
  99. package/dist/protocol.d.ts +5 -0
  100. package/dist/provider.d.ts +153 -10
  101. package/dist/provider.js +48 -1
  102. package/dist/providers.d.ts +23 -24
  103. package/dist/providers.js +14 -17
  104. package/dist/result.d.ts +11 -1
  105. package/dist/result.js +11 -0
  106. package/dist/test-connection.js +2 -2
  107. package/package.json +42 -2
@@ -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() {
@@ -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
  )
package/dist/browser.d.ts CHANGED
@@ -1,11 +1,8 @@
1
1
  import { type ComputerClient, type Group, type HelloResult } from "./protocol.js";
2
- import type { ComputerCapabilities, ComputerSpec, Refusal } from "./provider.js";
3
- import { type ComputerErrorCode, type Result } from "./result.js";
4
- /** The one image a browser computer runs: the vendor's own Chromium. */
5
- export declare const BROWSER_IMAGE = "chromium";
2
+ import type { BrowserFeatures, CallContext, ComputerCapabilities, ComputerProvider, ComputerRef, ComputerSpec, Refusal } from "./provider.js";
3
+ import { type ComputerError, type ComputerErrorCode, type Result } from "./result.js";
6
4
  /**
7
- * Where a provider keeps the URLs it was handed, by session id, in memory only. Default a Map of its own; a host that
8
- * builds one provider per call passes one store to all of them (pi-browser's process-wide holdings).
5
+ * Where a provider keeps the URLs it was handed, by session id, in memory only: a Map of its own.
9
6
  */
10
7
  export interface UrlStore {
11
8
  get(id: string): string | undefined;
@@ -33,17 +30,18 @@ export interface ReleaseConfirm {
33
30
  export declare const DEFAULT_CONFIRM: ReleaseConfirm;
34
31
  export declare const defaultSleep: (ms: number) => Promise<void>;
35
32
  /** A vendor call's failure as the provider returns it: a code and words, and the error the call threw, for a caller that rethrows it as it was. */
36
- export type VendorFailure = {
37
- code: ComputerErrorCode;
38
- message: string;
33
+ export type VendorFailure = ComputerError & {
39
34
  readonly cause?: unknown;
40
35
  };
41
- /** A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. */
42
- export declare function vendorFail(code: ComputerErrorCode, message: string, cause?: unknown): Result<never>;
43
- /** The error a vendor call threw, behind a failure vendorFail made; undefined for any other. */
36
+ /**
37
+ * A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. With
38
+ * code vendor, vendor (the provider's id) names whose.
39
+ */
40
+ export declare function causedFail(code: ComputerErrorCode, message: string, cause: unknown, vendor: string): Result<never>;
41
+ /** The error a vendor call threw, behind a failure causedFail made; undefined for any other. */
44
42
  export declare const causeOf: (result: Result<unknown>) => unknown;
45
- /** The code a vendor's HTTP status reads as. */
46
- export declare function statusCode(status: number | undefined, vendor: "browserbase" | "kernel"): ComputerErrorCode;
43
+ /** The code a vendor's HTTP status reads as: one of ours, or vendor. */
44
+ export declare function statusCode(status: number | undefined): ComputerErrorCode;
47
45
  /** Why labels are not ones a browser provider writes into a vendor's metadata, in words; undefined when they are. */
48
46
  export declare function labelsProblem(labels: unknown): string | undefined;
49
47
  /** A label a vendor's query can carry as it is: plain characters, so a quote never ends the query early. */
@@ -78,8 +76,9 @@ export declare const RECOVER_MS = 30000;
78
76
  export declare function recoverCreate(what: string, find: (signal: AbortSignal) => Promise<Result<string[]>>, release: (id: string) => Promise<Result<void>>, sleep: (ms: number) => Promise<void>): Promise<string>;
79
77
  /**
80
78
  * The checks every browser provider makes before a vendor call: the image is chromium, the lifetime is within the
81
- * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, and no field a
82
- * browser does not take (a size, a user, a workdir, a mount).
79
+ * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, the session's
80
+ * options are ones capabilities().browser declares (browserSpecRefusals), and no field a browser does not take (a size,
81
+ * a user, a workdir, a mount).
83
82
  */
84
83
  export declare function checkBrowser(spec: ComputerSpec, capabilities: ComputerCapabilities, vendor: string, minLifetimeMs?: number): Refusal[];
85
84
  /** hello for a browser: the provider's version, linux, kind browser and its groups. The vendor reports no arch. */
@@ -117,9 +116,9 @@ export declare class BrowserVendorError extends Error {
117
116
  export declare const plainCode: (code: unknown) => string | undefined;
118
117
  /**
119
118
  * A vendor call's thrown error as a result: aborted, or the code its status reads as, in words that name the call and the
120
- * status alone. The error itself rides along as the failure's hidden cause (vendorFail).
119
+ * status alone. The error itself rides along as the failure's hidden cause (causedFail). vendor is the provider's id.
121
120
  */
122
- export declare function vendorFailure(vendor: "browserbase" | "kernel", name: string, call: string, error: unknown): Result<never>;
121
+ export declare function vendorFailure(vendor: string, name: string, call: string, error: unknown): Result<never>;
123
122
  /**
124
123
  * Why a vendor's CDP URL is not one to hand a driver, in words that never carry it; undefined when it is. It must be wss:
125
124
  * (the session's signing key rides it) on the vendor's own domain or a host under it: a vendor answer that named another
@@ -127,6 +126,12 @@ export declare function vendorFailure(vendor: "browserbase" | "kernel", name: st
127
126
  * redirects refused; this holds the CDP URL itself to the same.
128
127
  */
129
128
  export declare function cdpUrlProblem(url: unknown, name: string, domain: string): string | undefined;
129
+ /** What a REST call sends: a JSON body, a query and a signal. */
130
+ export interface RestInit {
131
+ body?: unknown;
132
+ query?: URLSearchParams;
133
+ signal?: AbortSignal;
134
+ }
130
135
  /** What the REST calls share: one request, never retried, read whole; a failure throws a BrowserVendorError. */
131
136
  export interface RestReply {
132
137
  status: number;
@@ -140,12 +145,57 @@ export declare function restCall(o: {
140
145
  fetch: typeof fetch;
141
146
  base: string;
142
147
  headers: Record<string, string>;
143
- }, method: string, route: string, call: string, init?: {
144
- body?: unknown;
145
- query?: URLSearchParams;
146
- signal?: AbortSignal;
147
- }): Promise<RestReply>;
148
+ }, method: string, route: string, call: string, init?: RestInit): Promise<RestReply>;
148
149
  /** An https base URL, with no trailing slash, so a key never crosses in the clear; throws in words on another. */
149
150
  export declare function httpsBase(url: string, what: string): string;
150
151
  /** A vendor's session id as a ref or attach gives it: a plain token, never a path. */
151
152
  export declare const idProblem: (id: unknown, vendor: string) => string | undefined;
153
+ /**
154
+ * A GET whose success is bytes, streamed (Accept application/octet-stream); undefined when the vendor answers 404. A
155
+ * redirect is followed once, to https only, and without the key's headers, so a storage host is never handed the key.
156
+ * A failure throws a BrowserVendorError that names the call and the status alone.
157
+ */
158
+ export declare function restBytes(o: {
159
+ vendor: string;
160
+ fetch: typeof fetch;
161
+ base: string;
162
+ headers: Record<string, string>;
163
+ }, route: string, call: string, signal?: AbortSignal): Promise<AsyncIterable<Uint8Array> | undefined>;
164
+ /** The bytes as they come, failing in words once they pass maxBytes: what reached the reader before then is all it gets. */
165
+ export declare function limitedBytes(body: AsyncIterable<Uint8Array>, maxBytes: number, what: string): AsyncIterable<Uint8Array>;
166
+ /** One file a session downloaded, as downloads.list gives it. */
167
+ export interface BrowserFile {
168
+ name: string;
169
+ sizeBytes: number;
170
+ modifiedAt: string | null;
171
+ }
172
+ /** Saved profiles: a pointer is a capability (whoever holds it opens the profile), so no error's words carry one. */
173
+ export interface BrowserProfiles {
174
+ create(context?: CallContext): Promise<Result<string>>;
175
+ /** A profile the vendor no longer knows is removed. */
176
+ remove(pointer: string, context?: CallContext): Promise<Result<void>>;
177
+ }
178
+ /** The files a session downloaded, kept by the vendor. */
179
+ export interface BrowserDownloads {
180
+ list(ref: ComputerRef, context?: CallContext): Promise<Result<BrowserFile[]>>;
181
+ /** The file's bytes, streamed; the stream fails in words once it passes maxBytes. */
182
+ read(ref: ComputerRef, name: string, maxBytes: number, context?: CallContext): Promise<Result<AsyncIterable<Uint8Array>>>;
183
+ }
184
+ /**
185
+ * A provider of browsers, with the members its features may bring: profiles where capabilities().browser declares
186
+ * profiles, downloads where it declares downloads.
187
+ */
188
+ export interface BrowserComputerProvider extends ComputerProvider {
189
+ readonly profiles?: BrowserProfiles;
190
+ readonly downloads?: BrowserDownloads;
191
+ }
192
+ /** Whether a provider is a browser provider: its capabilities are of kind browser and declare its sessions' features. */
193
+ export declare function isBrowserProvider(provider: ComputerProvider): provider is BrowserComputerProvider;
194
+ /** A profile's pointer as a provider takes it: a plain token, so it is a path segment and never a path. */
195
+ export declare const pointerOk: (pointer: unknown) => pointer is string;
196
+ /**
197
+ * Why spec.browser is not one this provider takes, field by field: a malformed option, or one its features
198
+ * (capabilities().browser) do not declare (a flag set false asks for nothing, so it is never refused). The words never
199
+ * carry a pointer.
200
+ */
201
+ export declare function browserSpecRefusals(session: unknown, features: BrowserFeatures, vendor: string): Refusal[];
package/dist/browser.js CHANGED
@@ -5,9 +5,8 @@
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { PROTOCOL_VERSION } from "./protocol.js";
7
7
  import { checkGpu, checkLifetime } from "./provider.js";
8
- import { fail, ok } from "./result.js";
9
- /** The one image a browser computer runs: the vendor's own Chromium. */
10
- export const BROWSER_IMAGE = "chromium";
8
+ import { errorOf, fail, ok } from "./result.js";
9
+ import { BROWSER_IMAGE } from "./descriptors/shared.js";
11
10
  /** A key's or a value's longest, in characters: what both vendors keep of a metadata entry. */
12
11
  const MAX_LABEL = 256;
13
12
  export const memoryUrls = () => {
@@ -16,24 +15,27 @@ export const memoryUrls = () => {
16
15
  };
17
16
  export const DEFAULT_CONFIRM = { polls: 6, intervalMs: 500 };
18
17
  export const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
19
- /** A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. */
20
- export function vendorFail(code, message, cause) {
21
- const failed = fail(code, message);
18
+ /**
19
+ * A failure whose cause rides along out of sight: not enumerable, so it is in no JSON, no log line and no report. With
20
+ * code vendor, vendor (the provider's id) names whose.
21
+ */
22
+ export function causedFail(code, message, cause, vendor) {
23
+ const failed = { ok: false, error: errorOf(code, message, vendor) };
22
24
  if (cause !== undefined && !failed.ok)
23
25
  Object.defineProperty(failed.error, "cause", { value: cause, enumerable: false });
24
26
  return failed;
25
27
  }
26
- /** The error a vendor call threw, behind a failure vendorFail made; undefined for any other. */
28
+ /** The error a vendor call threw, behind a failure causedFail made; undefined for any other. */
27
29
  export const causeOf = (result) => (result.ok ? undefined : result.error.cause);
28
- /** The code a vendor's HTTP status reads as. */
29
- export function statusCode(status, vendor) {
30
+ /** The code a vendor's HTTP status reads as: one of ours, or vendor. */
31
+ export function statusCode(status) {
30
32
  if (status === 401 || status === 403)
31
33
  return "denied";
32
34
  if (status === 404)
33
35
  return "not_found";
34
36
  if (status === 429)
35
37
  return "limit";
36
- return vendor;
38
+ return "vendor";
37
39
  }
38
40
  /** Why labels are not ones a browser provider writes into a vendor's metadata, in words; undefined when they are. */
39
41
  export function labelsProblem(labels) {
@@ -107,16 +109,18 @@ export async function recoverCreate(what, find, release, sleep) {
107
109
  }
108
110
  return words.join("; ");
109
111
  }
110
- const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "gpu"]);
112
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "gpu", "browser"]);
111
113
  /**
112
114
  * The checks every browser provider makes before a vendor call: the image is chromium, the lifetime is within the
113
- * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, and no field a
114
- * browser does not take (a size, a user, a workdir, a mount).
115
+ * vendor's cap (and at least min), the network is open, the labels are ones the vendor's metadata holds, the session's
116
+ * options are ones capabilities().browser declares (browserSpecRefusals), and no field a browser does not take (a size,
117
+ * a user, a workdir, a mount).
115
118
  */
116
119
  export function checkBrowser(spec, capabilities, vendor, minLifetimeMs = 1) {
117
120
  const refusals = [];
118
121
  const given = (typeof spec === "object" && spec !== null ? spec : {});
119
122
  const { image, lifetimeMs, network, labels } = given;
123
+ refusals.push(...browserSpecRefusals(given.browser, capabilities.browser ?? { timeout: "wall-clock" }, vendor));
120
124
  if (image !== BROWSER_IMAGE)
121
125
  refusals.push({ field: "image", message: `a ${vendor} computer runs ${vendor}'s own Chromium: image is "${BROWSER_IMAGE}", not ${JSON.stringify(image)}` });
122
126
  const lifetime = checkLifetime(lifetimeMs, capabilities);
@@ -216,15 +220,15 @@ export const plainCode = (code) => (typeof code === "string" && /^[a-z][a-z_.-]{
216
220
  const isAbort = (error) => error?.name === "AbortError";
217
221
  /**
218
222
  * A vendor call's thrown error as a result: aborted, or the code its status reads as, in words that name the call and the
219
- * status alone. The error itself rides along as the failure's hidden cause (vendorFail).
223
+ * status alone. The error itself rides along as the failure's hidden cause (causedFail). vendor is the provider's id.
220
224
  */
221
225
  export function vendorFailure(vendor, name, call, error) {
222
226
  if (isAbort(error))
223
- return vendorFail("aborted", `${name} ${call} was aborted`, error);
227
+ return causedFail("aborted", `${name} ${call} was aborted`, error, vendor);
224
228
  const status = error?.status;
225
- const code = typeof status === "number" ? statusCode(status, vendor) : vendor;
229
+ const code = typeof status === "number" ? statusCode(status) : "vendor";
226
230
  const words = error instanceof BrowserVendorError ? error.message : typeof status === "number" ? `${name} ${call} answered ${status}` : `${name} ${call} failed`;
227
- return vendorFail(code, words, error);
231
+ return causedFail(code, words, error, vendor);
228
232
  }
229
233
  /**
230
234
  * Why a vendor's CDP URL is not one to hand a driver, in words that never carry it; undefined when it is. It must be wss:
@@ -306,3 +310,123 @@ export function httpsBase(url, what) {
306
310
  }
307
311
  /** A vendor's session id as a ref or attach gives it: a plain token, never a path. */
308
312
  export const idProblem = (id, vendor) => typeof id === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(id) ? undefined : `${typeof id === "string" ? JSON.stringify(id) : String(id)} is not a ${vendor} session's id`;
313
+ /**
314
+ * A GET whose success is bytes, streamed (Accept application/octet-stream); undefined when the vendor answers 404. A
315
+ * redirect is followed once, to https only, and without the key's headers, so a storage host is never handed the key.
316
+ * A failure throws a BrowserVendorError that names the call and the status alone.
317
+ */
318
+ export async function restBytes(o, route, call, signal) {
319
+ const get = (url, headers) => o.fetch(url, { method: "GET", headers: { ...headers, Accept: "application/octet-stream" }, redirect: "manual", ...(signal ? { signal } : {}) });
320
+ const drop = (response) => response.body?.cancel().catch(() => undefined);
321
+ let response;
322
+ try {
323
+ response = await get(`${o.base}${route}`, o.headers);
324
+ if (response.status >= 300 && response.status < 400) {
325
+ const location = response.headers.get("location");
326
+ await drop(response);
327
+ let next;
328
+ try {
329
+ next = location ? new URL(location, `${o.base}${route}`) : undefined;
330
+ }
331
+ catch {
332
+ next = undefined;
333
+ }
334
+ if (next === undefined)
335
+ throw new BrowserVendorError(o.vendor, call, response.status, "no_location");
336
+ if (next.protocol !== "https:")
337
+ throw new BrowserVendorError(o.vendor, call, response.status, "redirect_not_https");
338
+ response = await get(next.href, {});
339
+ }
340
+ }
341
+ catch (error) {
342
+ if (isAbort(error) || error instanceof BrowserVendorError)
343
+ throw error;
344
+ throw new BrowserVendorError(o.vendor, call, undefined, undefined, { cause: error });
345
+ }
346
+ if (response.status === 404) {
347
+ await drop(response);
348
+ return undefined;
349
+ }
350
+ if (!response.ok) {
351
+ await drop(response);
352
+ throw new BrowserVendorError(o.vendor, call, response.status);
353
+ }
354
+ if (response.body === null)
355
+ throw new BrowserVendorError(o.vendor, call, response.status, "no_body");
356
+ return response.body;
357
+ }
358
+ /** The bytes as they come, failing in words once they pass maxBytes: what reached the reader before then is all it gets. */
359
+ export async function* limitedBytes(body, maxBytes, what) {
360
+ let total = 0;
361
+ for await (const chunk of body) {
362
+ total += chunk.byteLength;
363
+ if (total > maxBytes)
364
+ throw new Error(`${what} is larger than the ${maxBytes}-byte limit`);
365
+ yield chunk;
366
+ }
367
+ }
368
+ /** Whether a provider is a browser provider: its capabilities are of kind browser and declare its sessions' features. */
369
+ export function isBrowserProvider(provider) {
370
+ let capabilities;
371
+ try {
372
+ capabilities = typeof provider?.capabilities === "function" ? provider.capabilities() : undefined;
373
+ }
374
+ catch {
375
+ return false;
376
+ }
377
+ const browser = capabilities?.browser;
378
+ return capabilities?.kind === "browser" && typeof browser === "object" && browser !== null;
379
+ }
380
+ /** A viewport's longest side, in pixels. */
381
+ const MAX_VIEWPORT = 10_000;
382
+ const SESSION_FIELDS = new Set(["viewport", "profile", "stealth", "headless"]);
383
+ /** A profile's pointer as a provider takes it: a plain token, so it is a path segment and never a path. */
384
+ export const pointerOk = (pointer) => typeof pointer === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(pointer);
385
+ const only = (value, fields) => Object.keys(value).every((key) => fields.includes(key));
386
+ /**
387
+ * Why spec.browser is not one this provider takes, field by field: a malformed option, or one its features
388
+ * (capabilities().browser) do not declare (a flag set false asks for nothing, so it is never refused). The words never
389
+ * carry a pointer.
390
+ */
391
+ export function browserSpecRefusals(session, features, vendor) {
392
+ if (session === undefined)
393
+ return [];
394
+ if (typeof session !== "object" || session === null || Array.isArray(session))
395
+ return [{ field: "browser", message: "a browser's options are an object" }];
396
+ const refusals = [];
397
+ const given = session;
398
+ for (const [field, value] of Object.entries(given)) {
399
+ if (!SESSION_FIELDS.has(field) && value !== undefined)
400
+ refusals.push({ field: `browser.${field}`, message: `a browser takes no ${field}` });
401
+ }
402
+ const { viewport, profile } = given;
403
+ if (viewport !== undefined) {
404
+ const side = (n) => Number.isInteger(n) && n >= 1 && n <= MAX_VIEWPORT;
405
+ const v = viewport;
406
+ if (typeof v !== "object" || v === null || !only(v, ["width", "height"]) || !side(v.width) || !side(v.height)) {
407
+ refusals.push({ field: "browser.viewport", message: `a viewport is { width, height }, each a whole number of pixels from 1 to ${MAX_VIEWPORT}` });
408
+ }
409
+ }
410
+ const flags = [
411
+ ["stealth", "stealth mode"],
412
+ ["headless", "headless mode"],
413
+ ];
414
+ for (const [field, what] of flags) {
415
+ const value = given[field];
416
+ if (value === undefined)
417
+ continue;
418
+ if (typeof value !== "boolean")
419
+ refusals.push({ field: `browser.${field}`, message: `${field} is true or false` });
420
+ else if (value && features[field] !== true)
421
+ refusals.push({ field: `browser.${field}`, message: `a ${vendor} browser has no ${what}, so ${field} is refused` });
422
+ }
423
+ if (profile !== undefined) {
424
+ const p = profile;
425
+ if (features.profiles === undefined)
426
+ refusals.push({ field: "browser.profile", message: `a ${vendor} browser keeps no profile` });
427
+ else if (typeof p !== "object" || p === null || !only(p, ["pointer", "save"]) || !pointerOk(p.pointer) || typeof p.save !== "boolean") {
428
+ refusals.push({ field: "browser.profile", message: "a profile is { pointer, save }: a plain token profiles.create gave, and true or false" });
429
+ }
430
+ }
431
+ return refusals;
432
+ }