@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
@@ -0,0 +1,76 @@
1
+ import type { ComputerCapabilities, ComputerConnection } from "../provider.js";
2
+ import { type Result } from "../result.js";
3
+ /** Who ran install, from its output's `installer <uid> <name>[ sudo]` line, in words; undefined when it has none. */
4
+ export declare function installerOf(output: string): string | undefined;
5
+ /** One string for a shell: `sh -c '<script>' sh '<arg>' ...`, every word quoted. */
6
+ export declare const shellCommand: (script: string, args: readonly string[]) => string;
7
+ /** One argv as one shell line, every word but a plain one ("sh", "-c") single-quoted: for a vendor whose exec takes a line. */
8
+ export declare const shellLine: (argv: readonly string[]) => string;
9
+ /** Where start leaves what init writes, root's alone: the words a create that never hears the daemon gives back. */
10
+ export declare const INIT_LOG = "/run/agentrun-init.log";
11
+ /**
12
+ * Where a pid1 Archil computer's entrypoint waits for root's word that the run's folder is mounted: beside the daemon,
13
+ * in the directory install makes root's alone before root makes the gate, so no other user can make it early. (A path
14
+ * under /run would hang on an image without /run, or one whose /run another user can write.)
15
+ */
16
+ export declare const ARCHIL_GATE: string;
17
+ /** The scripts the adapter runs, each one argv (see the file's head). */
18
+ export interface HostedCommands {
19
+ install: string[];
20
+ /** child: init's start, detached; it answers once init is started. */
21
+ start: string[];
22
+ stdio: string[];
23
+ log: string[];
24
+ /** pid1: the machine's command. */
25
+ entrypoint: string[];
26
+ }
27
+ /**
28
+ * The adapter's commands for one computer. Init's flags are the child's (childCommands) for both modes: --own-network
29
+ * always, the display and the most deadline.extend may move the deadline to when given. waitS bounds a pid1 entrypoint's
30
+ * wait for the daemon (and gate, for an Archil computer); with atomic, install moves the daemon into place last, and only
31
+ * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for.
32
+ */
33
+ export declare function hostedCommands({ staging, deadline, user, display, maxDeadline, atomic, waitS, gate, sha256, nonce, }?: ChildCommandOptions & {
34
+ atomic?: boolean;
35
+ waitS?: number;
36
+ gate?: string;
37
+ sha256?: string;
38
+ nonce?: string;
39
+ }): HostedCommands;
40
+ export interface ChildCommandOptions {
41
+ /** Where the vendor's upload left the daemon. */
42
+ staging?: string;
43
+ /** Init's deadline, an ISO time. */
44
+ deadline?: string;
45
+ /** Who the daemon becomes, uid:gid in numbers. */
46
+ user?: string;
47
+ /** The X display init's screen and input methods drive (its DISPLAY); none for a computer with no screen. */
48
+ display?: string;
49
+ /** The most deadline.extend may move the deadline to, an ISO time; none, and the deadline cannot move. */
50
+ maxDeadline?: string;
51
+ }
52
+ /**
53
+ * The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
54
+ * its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
55
+ * every argument quoted.
56
+ */
57
+ export declare function childCommands({ staging, deadline, user, display, maxDeadline }?: ChildCommandOptions): {
58
+ install: string;
59
+ init: string;
60
+ stdio: string;
61
+ };
62
+ export interface DaemonExpected {
63
+ version: string;
64
+ /** The uid and gid it runs as; with neither, any one user that is not root (a spec named it, and attach reads it back). */
65
+ uid?: string;
66
+ gid?: string;
67
+ arch: string;
68
+ kind: ComputerCapabilities["kind"];
69
+ groups: ComputerCapabilities["groups"];
70
+ }
71
+ /**
72
+ * What the daemon reports of itself, read back through it: hello, its credentials (no capability in any set,
73
+ * no_new_privs, no groups, a seccomp filter), its network (its own loopback alone, from its /proc/self/net/dev), its
74
+ * working directory and binary. Each read is bounded by timeoutMs and the caller's signal.
75
+ */
76
+ export declare function daemonDrift(connection: ComputerConnection, expected: DaemonExpected, timeoutMs: number, signal?: AbortSignal): Promise<Result<string[]>>;
@@ -1,9 +1,12 @@
1
- // The daemon as a child: for a vendor whose own agent is the computer's first process (Daytona's toolbox, E2B's envd),
2
- // computerd goes in through the vendor's file upload and starts as a command that agent runs. These are the shell
3
- // commands such a provider sends, exactly, and the read-back of the daemon it started: the same for every such vendor.
4
- import { DAEMON_IN_COMPUTER, helloDrift, SOCKET_DIR, WORK } from "./drift.js";
5
- import { readOwnNetwork, TOOL_USER } from "./isolation.js";
6
- import { fail, ok } from "./result.js";
1
+ // The scripts the shared machine-host adapter (./provider.ts) sends into a machine, exactly, and the read-back of the
2
+ // daemon it started: the same for every vendor. A child host (the vendor's own agent is the machine's first process:
3
+ // E2B's envd, Daytona's toolbox) gets the daemon through its upload, installs it, and starts init detached (start);
4
+ // a pid1 host's machine runs the entrypoint as its main process, which waits for the daemon and becomes init. Every
5
+ // connection runs stdio. Each is one argv, `sh -c '<script>' sh <args>`; shellCommand gives it as one string for a
6
+ // vendor whose exec takes a shell line.
7
+ import { DAEMON_IN_COMPUTER, helloDrift, SOCKET_DIR, WORK } from "../drift.js";
8
+ import { readOwnNetwork, TOOL_USER } from "../isolation.js";
9
+ import { fail, ok } from "../result.js";
7
10
  const PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
8
11
  const CAPS = ["CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"];
9
12
  /** Root for what follows: the command's own user when it is root, else passwordless sudo, which the install checked. */
@@ -22,14 +25,22 @@ const HELD = 'held() { x=$1; while :; do set -- $(ls -ldn "$x" 2>/dev/null); cas
22
25
  * image's is relied on. */
23
26
  const INSTALL_SCRIPT = [
24
27
  "# agentrun-computer: install",
25
- "s=$1; d=$2; h=$3; r=$4; b=${d%/*}",
28
+ // a: when set, the binary goes in beside its path and is moved into place last, so a pid1 entrypoint waiting for the
29
+ // path never starts one half written; e: when set too, the sha256 it must read before it is moved, so the entrypoint
30
+ // never starts one that is not the daemon uploaded; n: when set too, this create's nonce, written to the marker beside
31
+ // the daemon once it is in place, so the entrypoint starts the daemon this create installed and never one the image
32
+ // had there. (Not x: held() assigns x.)
33
+ "s=$1; d=$2; h=$3; r=$4; a=${5-}; e=${6-}; n=${7-}; b=${d%/*}; t=$d; [ -z \"$a\" ] || t=$d.part",
26
34
  'if [ "$(id -u)" = 0 ]; then p=; elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then p="sudo -n"; else echo "the sandbox user $(id -un) is not root and has no passwordless sudo, so the daemon cannot be installed"; exit 3; fi',
27
35
  HELD,
28
36
  '[ -d "${b%/*}" ] || $p mkdir -p -m 0755 "${b%/*}" || { echo "installing the daemon at $d failed"; exit 5; }',
29
37
  'held "${b%/*}" || exit 6',
30
38
  '[ ! -L "$b" ] || { echo "the daemon at $d is not root\'s alone: $b is a symbolic link"; exit 6; }',
31
- '$p mkdir -p "$b" "$h" "$r" && $p chown 0:0 "$b" && $p chmod 0755 "$b" && $p rm -f "$d" && $p install -m 0755 -o 0 -g 0 "$s" "$d" || { echo "installing the daemon at $d failed"; exit 5; }',
39
+ '$p mkdir -p "$b" "$h" "$r" && $p chown 0:0 "$b" && $p chmod 0755 "$b" && $p rm -f "$d" "$t" "$d.installed" && $p install -m 0755 -o 0 -g 0 "$s" "$t" || { echo "installing the daemon at $d failed"; exit 5; }',
40
+ 'if [ -n "$a" ] && [ -n "$e" ]; then w=$($p sha256sum "$t" | cut -c1-64); [ "$w" = "$e" ] || { echo "sha256 $w"; echo "the daemon written to $t reads sha256 $w, not $e, so it is not moved into place"; $p rm -f "$t"; exit 7; }; fi',
41
+ '[ "$t" = "$d" ] || $p mv -f "$t" "$d" || { echo "installing the daemon at $d failed"; exit 5; }',
32
42
  'held "$d" || exit 6',
43
+ `[ -z "$n" ] || { printf '%s\\n' "$n" | $p tee "$d.installed" >/dev/null; } || { echo "installing the daemon at $d failed: its marker was not written"; exit 5; }`,
33
44
  'rm -f "$s"',
34
45
  // Who installed it: the sandbox user's uid and name, and "sudo" when through passwordless sudo (installerOf).
35
46
  'echo "installer $(id -u) $(id -un 2>/dev/null || echo unnamed)${p:+ sudo}"',
@@ -67,6 +78,73 @@ const STDIO_SCRIPT = ["# agentrun-computer: stdio", "d=$1; r=$2", HELD, 'held "$
67
78
  const quote = (word) => `'${word.replaceAll("'", "'\\''")}'`;
68
79
  /** One string for a shell: `sh -c '<script>' sh '<arg>' ...`, every word quoted. */
69
80
  export const shellCommand = (script, args) => ["sh", "-c", quote(script), "sh", ...args.map(quote)].join(" ");
81
+ /** One argv as one shell line, every word but a plain one ("sh", "-c") single-quoted: for a vendor whose exec takes a line. */
82
+ export const shellLine = (argv) => argv.map((word) => (/^[A-Za-z0-9_./:=@%+-]+$/.test(word) ? word : quote(word))).join(" ");
83
+ const argvOf = (script, args) => ["sh", "-c", script, "sh", ...args];
84
+ /** Where start leaves what init writes, root's alone: the words a create that never hears the daemon gives back. */
85
+ export const INIT_LOG = `${SOCKET_DIR}-init.log`;
86
+ /**
87
+ * Starts init detached from the call that starts it: in a session of its own (setsid), its output to the log, its stdin
88
+ * none, so the vendor's call ends at once and nothing of it holds init. As root, or through passwordless sudo.
89
+ */
90
+ const START_SCRIPT = ["# agentrun-computer: start", "l=$1; shift", ROOT, `exec $p sh -c 'exec >"$0" 2>&1 </dev/null; setsid "$@" &' "$l" "$@"`].join("\n");
91
+ /** The last words init wrote to its log, as root; nothing when it wrote none. */
92
+ const LOG_SCRIPT = ["# agentrun-computer: log", "l=$1", ROOT, '$p tail -c 2000 "$l" 2>/dev/null || true'].join("\n");
93
+ /**
94
+ * A pid1 machine's main process: waits, bounded, for the daemon this create installed to be moved into place executable
95
+ * (the marker beside it, `<daemon>.installed`, holds this create's nonce: a daemon the image had at the path, or one an
96
+ * earlier install left, has none, or another, and is never started), then becomes it with exec, so init is the machine's main process and the machine ends when init does. It starts init as start does a
97
+ * child's: from its home (HOME, and the working directory), with the display, when given, as its DISPLAY. POSIX sh and
98
+ * tools in BusyBox and coreutils alike; `date +%s` bounds the wait however long a sleep takes. An Archil computer's
99
+ * (`--gate <path>` before init's arguments) also waits for the gate, which root makes once the run's folder is mounted;
100
+ * a gate there before it starts (an image that holds one) is not this computer's, and goes first.
101
+ */
102
+ const ENTRYPOINT_SCRIPT = [
103
+ "# agentrun-computer: entrypoint",
104
+ // The display is v, as in init's script; empty for a computer with no screen. n is this create's nonce.
105
+ "d=$1; w=$2; h=$3; v=$4; n=$5; shift 5",
106
+ 'g=; if [ "${1-}" = --gate ]; then g=$2; shift 2; rm -f "$g"; fi',
107
+ "end=$(( $(date +%s) + $w ))",
108
+ // Ours: the daemon executable, and the marker install writes after the move holding this create's nonce.
109
+ 'ours() { [ -f "$d" ] && [ -x "$d" ] && [ -n "$n" ] && [ "$(cat "$d.installed" 2>/dev/null)" = "$n" ]; }',
110
+ 'until ours && { [ -z "$g" ] || [ -f "$g" ]; }; do',
111
+ '\tif [ "$(date +%s)" -gt "$end" ]; then',
112
+ '\t\tif ours; then echo "agentrun-computer: the Archil mount was not made within $w s ($g is not there), so this computer ends" >&2',
113
+ '\t\telse echo "agentrun-computer: the daemon did not arrive at $d within $w s, so this computer ends" >&2; fi',
114
+ "\t\texit 3",
115
+ "\tfi",
116
+ "\tsleep 0.2 2>/dev/null || sleep 1",
117
+ "done",
118
+ 'export HOME="$h"',
119
+ 'cd "$h" || { echo "agentrun-computer: init\'s home $h cannot be entered, so this computer ends" >&2; exit 4; }',
120
+ 'if [ -n "$v" ]; then export DISPLAY="$v"; else unset DISPLAY; fi',
121
+ 'exec "$d" "$@"',
122
+ ].join("\n");
123
+ /**
124
+ * Where a pid1 Archil computer's entrypoint waits for root's word that the run's folder is mounted: beside the daemon,
125
+ * in the directory install makes root's alone before root makes the gate, so no other user can make it early. (A path
126
+ * under /run would hang on an image without /run, or one whose /run another user can write.)
127
+ */
128
+ export const ARCHIL_GATE = `${DAEMON_IN_COMPUTER.slice(0, DAEMON_IN_COMPUTER.lastIndexOf("/"))}/archil-mounted`;
129
+ /**
130
+ * The adapter's commands for one computer. Init's flags are the child's (childCommands) for both modes: --own-network
131
+ * always, the display and the most deadline.extend may move the deadline to when given. waitS bounds a pid1 entrypoint's
132
+ * wait for the daemon (and gate, for an Archil computer); with atomic, install moves the daemon into place last, and only
133
+ * once it reads sha256, when given, then writes nonce, when given, to the marker the entrypoint waits for.
134
+ */
135
+ export function hostedCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "", atomic = false, waitS = 600, gate, sha256 = "", nonce = "", } = {}) {
136
+ const init = [DAEMON_IN_COMPUTER, deadline, user, WORK, SOCKET_DIR];
137
+ if (display !== "" || maxDeadline !== "")
138
+ init.push(display, maxDeadline);
139
+ const initArgs = ["init", "--deadline", deadline, "--user", user, "--own-network", ...(maxDeadline === "" ? [] : ["--max-deadline", maxDeadline])];
140
+ return {
141
+ install: argvOf(INSTALL_SCRIPT, [staging, DAEMON_IN_COMPUTER, WORK, SOCKET_DIR, ...(atomic ? ["1", sha256, nonce] : [])]),
142
+ start: argvOf(START_SCRIPT, [INIT_LOG, ...argvOf(INIT_SCRIPT, init)]),
143
+ stdio: argvOf(STDIO_SCRIPT, [DAEMON_IN_COMPUTER, SOCKET_DIR]),
144
+ log: argvOf(LOG_SCRIPT, [INIT_LOG]),
145
+ entrypoint: argvOf(ENTRYPOINT_SCRIPT, [DAEMON_IN_COMPUTER, String(waitS), WORK, display, nonce, ...(gate === undefined ? [] : ["--gate", gate]), ...initArgs]),
146
+ };
147
+ }
70
148
  /**
71
149
  * The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
72
150
  * its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
@@ -104,10 +182,13 @@ export async function daemonDrift(connection, expected, timeoutMs, signal) {
104
182
  const ids = (name) => (fields.get(name) ?? "").split(/\s+/).filter(Boolean);
105
183
  const uids = ids("Uid");
106
184
  const gids = ids("Gid");
107
- if (uids.length !== 4 || uids.some((id) => id !== expected.uid))
108
- found.push(`daemon user: declared uid ${expected.uid}, read back ${show(fields.get("Uid"))}`);
109
- if (gids.length !== 4 || gids.some((id) => id !== expected.gid))
110
- found.push(`daemon group: declared gid ${expected.gid}, read back ${show(fields.get("Gid"))}`);
185
+ // With no user expected, the one it runs as: every id of the four the same, and uid not root.
186
+ const uid = expected.uid ?? (uids[0] === "0" ? undefined : uids[0]);
187
+ const gid = expected.gid ?? gids[0];
188
+ if (uids.length !== 4 || uid === undefined || uids.some((id) => id !== uid))
189
+ found.push(`daemon user: declared ${expected.uid === undefined ? "one uid that is not root" : `uid ${expected.uid}`}, read back ${show(fields.get("Uid"))}`);
190
+ if (gids.length !== 4 || gid === undefined || gids.some((id) => id !== gid))
191
+ found.push(`daemon group: declared ${expected.gid === undefined ? "one gid" : `gid ${expected.gid}`}, read back ${show(fields.get("Gid"))}`);
111
192
  if ((fields.get("Groups") ?? "") !== "")
112
193
  found.push(`daemon groups: declared none, read back ${show(fields.get("Groups"))}`);
113
194
  if (fields.get("NoNewPrivs") !== "1")
package/dist/index.d.ts CHANGED
@@ -1,26 +1,30 @@
1
1
  export * from "./protocol.js";
2
2
  export * from "./result.js";
3
3
  export * from "./provider.js";
4
+ export * from "./ui-engine.js";
5
+ export * from "./attach.js";
4
6
  export * from "./mount.js";
5
- export { type CallOptions, DaemonClient, type DaemonStream } from "./client.js";
7
+ export { type CallOptions, DaemonClient, type DaemonStream, findNodes, refusedStep, type UiActOptions, type UiQuery, UiSession } from "./client.js";
6
8
  export { type ActionFailure, type CheckActionsOptions, checkActions, isKey } from "./actions.js";
7
9
  export { pullTar, pullTarStream, pushTar, readFile, writeFile, type PulledTar } from "./files.js";
8
10
  export { listProcesses, readAll, type ReadAllResult } from "./processes.js";
9
11
  export { type ActionMapper, createActionMapper, daemonWatch, redactWords, type ScreenFrame, type ScreenFrames, type ScreenWatch, ScreenWatchError, type ScreenWatchHandlers, toAction, type ViewerEvent, type WatchEndCode, watchEndCode, type WatchOptions, watchScreen, } from "./screen-watch.js";
12
+ export type { HostCall, HostFacts, Machine, MachineHost, MachineProcess, MachineRequest } from "./host.js";
13
+ export { HostedProvider, type HostedOptions, type HostedTimeouts, hostedProvider } from "./hosted/provider.js";
10
14
  export { type DockerVolume, VOLUME_SUBPATH_ENGINE } from "./docker/volume.js";
11
15
  export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, ensureImage, type EnsureImageOptions, IMAGE_REPOSITORY, IMAGE_TIMEOUT_MS, type ImageSource, imageSourceProblem, type Making, RECIPE_LABEL, recipeHash, recipeTag, } from "./docker/image.js";
12
16
  export { EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
13
- export { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, type ArchilMount, type ArchilMountOptions, type ArchilRoot, type ProviderNote, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, claimEpoch, helperSha256, mountDrift, mountWords, type RecordedArchil, readArchilMount, recordedArchil, recordedMount, syncingClient, } from "./mount-archil.js";
14
- export { type BrowserStream, BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, type ReleaseConfirm, type RestReply, type UrlStore, } from "./browser.js";
17
+ export { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, type ArchilMount, type ArchilEgress, type ArchilMountOptions, type ArchilRoot, type ProviderNote, archilEgressOf, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, claimEpoch, helperSha256, mountDrift, mountWords, type RecordedArchil, readArchilMount, recordedArchil, recordedMount, syncingClient, } from "./mount-archil.js";
18
+ export { type BrowserComputerProvider, type BrowserDownloads, type BrowserFile, type BrowserProfiles, browserSpecRefusals, type BrowserStream, isBrowserProvider, BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, type ReleaseConfirm, type RestReply, type UrlStore, } from "./browser.js";
15
19
  export { CHROME_ENV, CHROME_FLAGS, checkChrome, chromeFence, findChrome, killTree, NO_CHROME } from "./chrome.js";
16
20
  export { DAEMON_IN_COMPUTER, helloDrift, type HelloExpected } from "./drift.js";
17
21
  export { drift, hostOf, inspectDrift, mountOf, networkOf, type DockerHost, type DockerInfo, type DockerInspect, type DriftExpected } from "./docker/inspect.js";
18
22
  export { type ReleasedOlder, releaseOlder, sweep, type SweepOptions, type Swept } from "./janitor.js";
19
- export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, ownerLabels, ownerOf, RUN_HASH_LABEL, RUN_LABEL, runHash, runLabels, runProblem } from "./labels.js";
23
+ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerFilter, ownerLabels, ownerOf, RUN_HASH_LABEL, RUN_LABEL, runHash, runLabels, runProblem } from "./labels.js";
20
24
  export { waitUntil, type WaitOptions } from "./wait.js";
21
25
  export { type BuiltinProviderId, type ConformanceModule, descriptorOf, isProviderId, type ProviderEnv, providerFor, type ProviderId, providerIds, type ProviderModule, providerModule, type ProviderOptions, providers, } from "./providers.js";
22
- export { type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
23
- export { BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
26
+ export { type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type HostCommand, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
27
+ export { AGENT37, AGENT37_BASE_TEMPLATE, AGENT37_BOX_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
24
28
  export type { PhoneLedger, PhoneLedgerEntry } from "./phone-harness.js";
25
- export { type ComputerSettingKind, configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, type ProviderEntry, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, type SettingKindSpec, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
29
+ export { type ComputerSettingKind, configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, kindServed, type ProviderEntry, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, type SettingKindSpec, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
26
30
  export * from "./conformance/index.js";
package/dist/index.js CHANGED
@@ -1,30 +1,33 @@
1
1
  export * from "./protocol.js";
2
2
  export * from "./result.js";
3
3
  export * from "./provider.js";
4
+ export * from "./ui-engine.js";
5
+ export * from "./attach.js";
4
6
  export * from "./mount.js";
5
- export { DaemonClient } from "./client.js";
7
+ export { DaemonClient, findNodes, refusedStep, UiSession } from "./client.js";
6
8
  export { checkActions, isKey } from "./actions.js";
7
9
  export { pullTar, pullTarStream, pushTar, readFile, writeFile } from "./files.js";
8
10
  export { listProcesses, readAll } from "./processes.js";
9
11
  export { createActionMapper, daemonWatch, redactWords, ScreenWatchError, toAction, watchEndCode, watchScreen, } from "./screen-watch.js";
12
+ export { HostedProvider, hostedProvider } from "./hosted/provider.js";
10
13
  // The provider classes and their option types are not here: each provider loads by its id through the registry
11
- // (providerFor), or from its own subpath (@parcha/agentrun-computer/docker, /daytona, /modal, /e2b, /orgo,
14
+ // (providerFor), or from its own subpath (@parcha/agentrun-computer/docker, /daytona, /modal, /e2b, /agent37, /orgo,
12
15
  // /phone-harness, /browserbase, /kernel, /local: each the provider file's name).
13
16
  export { VOLUME_SUBPATH_ENGINE } from "./docker/volume.js";
14
17
  export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, ensureImage, IMAGE_REPOSITORY, IMAGE_TIMEOUT_MS, imageSourceProblem, RECIPE_LABEL, recipeHash, recipeTag, } from "./docker/image.js";
15
18
  export { EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
16
- export { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, claimEpoch, helperSha256, mountDrift, mountWords, readArchilMount, recordedArchil, recordedMount, syncingClient, } from "./mount-archil.js";
17
- export { BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, } from "./browser.js";
19
+ export { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_SYNC_SOCKET, ARCHIL_TOOL_UID, ARCHIL_TOOL_USER, ARCHIL_VERSION, archilEgressOf, archilLabels, archilMount, archilReadBack, archilRefusals, archilRelease, claimEpoch, helperSha256, mountDrift, mountWords, readArchilMount, recordedArchil, recordedMount, syncingClient, } from "./mount-archil.js";
20
+ export { browserSpecRefusals, isBrowserProvider, BrowserVendorError, CREATE_LABEL, causeOf, memoryUrls, RECOVER_MS, } from "./browser.js";
18
21
  // Local Chrome's provider class is on its provider id's subpath (@parcha/agentrun-computer/local-chrome), as every
19
22
  // provider's is; the Chrome helpers it runs on are not a provider and stay here.
20
23
  export { CHROME_ENV, CHROME_FLAGS, checkChrome, chromeFence, findChrome, killTree, NO_CHROME } from "./chrome.js";
21
24
  export { DAEMON_IN_COMPUTER, helloDrift } from "./drift.js";
22
25
  export { drift, hostOf, inspectDrift, mountOf, networkOf } from "./docker/inspect.js";
23
26
  export { releaseOlder, sweep } from "./janitor.js";
24
- export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, ownerLabels, ownerOf, RUN_HASH_LABEL, RUN_LABEL, runHash, runLabels, runProblem } from "./labels.js";
27
+ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_SERVER_LABEL, ownerFilter, ownerLabels, ownerOf, RUN_HASH_LABEL, RUN_LABEL, runHash, runLabels, runProblem } from "./labels.js";
25
28
  export { waitUntil } from "./wait.js";
26
29
  export { descriptorOf, isProviderId, providerFor, providerIds, providerModule, providers, } from "./providers.js";
27
30
  export { defineProvider, descriptorProblems } from "./descriptor.js";
28
- export { BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
29
- export { configurationOf, entryOf, imagesOf, kindOf, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, serves, servingRefusals, } from "./kinds.js";
31
+ export { AGENT37, AGENT37_BASE_TEMPLATE, AGENT37_BOX_TEMPLATE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE, KERNEL, LOCAL, MODAL, MODAL_DEFAULT_IMAGE, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
32
+ export { configurationOf, entryOf, imagesOf, kindOf, kindServed, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, serves, servingRefusals, } from "./kinds.js";
30
33
  export * from "./conformance/index.js";
package/dist/janitor.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CallContext, ComputerProvider, ComputerRef } from "./provider.js";
1
+ import type { CallContext, ComputerOwner, ComputerProvider, ComputerRef } from "./provider.js";
2
2
  import { type Result } from "./result.js";
3
3
  export interface SweepOptions {
4
4
  /** Only computers with all of these labels; default every computer the provider made. */
@@ -6,10 +6,11 @@ export interface SweepOptions {
6
6
  /** The time to compare deadlines with; default now. */
7
7
  now?: Date;
8
8
  /**
9
- * Whether an agent is gone, by its id: the caller's answer (serve's agents). An agent's computer whose owner is gone
10
- * is deleted; without this, no agent counts as gone.
9
+ * Whether an owner is gone, by the owner the computer carries (its agent, and its server when it names one): the
10
+ * caller's answer (serve's: its own agent that no longer exists; another server's owner is never gone to it). An
11
+ * agent's computer whose owner is gone is deleted; without this, no owner counts as gone.
11
12
  */
12
- ownerGone?: (agent: string) => boolean | Promise<boolean>;
13
+ ownerGone?: (owner: ComputerOwner) => boolean | Promise<boolean>;
13
14
  signal?: AbortSignal;
14
15
  }
15
16
  export interface Swept {
package/dist/janitor.js CHANGED
@@ -29,7 +29,7 @@ function tenureOf(info, persistence) {
29
29
  }
30
30
  /** Whether an agent's computer ends: its owner is gone, or it has been detached for longer than its idle TTL. */
31
31
  async function ownerEnds(info, owner, at, ownerGone) {
32
- if (ownerGone !== undefined && (await ownerGone(owner.agent)) === true)
32
+ if (ownerGone !== undefined && (await ownerGone(owner)) === true)
33
33
  return true;
34
34
  const since = info.detachedAt instanceof Date ? info.detachedAt.getTime() : Number.NaN;
35
35
  return owner.idleTtlMs !== undefined && !Number.isNaN(since) && at - since >= owner.idleTtlMs;
package/dist/kernel.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { type BrowserStream, type ReleaseConfirm, type RestReply, type UrlStore } from "./browser.js";
1
+ import { type BrowserComputerProvider, type BrowserProfiles, type BrowserStream, type ReleaseConfirm, type RestInit, type RestReply } from "./browser.js";
2
2
  import type { KindCapabilities } from "./kinds.js";
3
3
  import type { MountKind } from "./mount.js";
4
- import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
4
+ import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreateContext, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
5
5
  import { type Result } from "./result.js";
6
6
  export declare const KERNEL_API_URL = "https://api.onkernel.com";
7
7
  /** The domain a Kernel CDP URL is on (wss://<host>.kernel.sh:8443, read live 11-08; its API is onkernel.com): cdpUrlProblem holds it there. */
@@ -26,13 +26,9 @@ export interface KernelBrowser {
26
26
  /**
27
27
  * One Kernel request, never retried: a create sent twice would be a second paid browser. It answers 404 as a reply,
28
28
  * and throws on any other failure, with the HTTP status as `status`; the provider returns that as a result whose hidden
29
- * cause is the thrown error, so a host that gave its own request rethrows its own error.
29
+ * cause is the thrown error.
30
30
  */
31
- export type KernelRequest = (method: string, route: string, init?: {
32
- body?: unknown;
33
- query?: URLSearchParams;
34
- signal?: AbortSignal;
35
- }) => Promise<RestReply>;
31
+ export type KernelRequest = (method: string, route: string, init?: RestInit) => Promise<RestReply>;
36
32
  /** Kernel's REST API over fetch: the default request. */
37
33
  export declare function kernelRest({ apiKey, apiUrl, fetch: fetcher }: {
38
34
  apiKey: string;
@@ -40,42 +36,37 @@ export declare function kernelRest({ apiKey, apiUrl, fetch: fetcher }: {
40
36
  fetch?: typeof fetch;
41
37
  }): KernelRequest;
42
38
  export interface KernelProviderOptions {
43
- /** With apiUrl and fetch, the REST request is built from it; required unless request is given. */
39
+ /** With apiUrl and fetch, the REST request is built from it. */
44
40
  apiKey?: string;
41
+ /** Kernel's API; default KERNEL_BASE_URL in env (a server behind a gateway that fronts it), else Kernel's own. */
45
42
  apiUrl?: string;
43
+ /** The host's own variables its descriptor declares (hostEnv): KERNEL_BASE_URL alone. */
44
+ env?: Readonly<Record<string, string | undefined>>;
46
45
  fetch?: typeof fetch;
47
- /** One Kernel request, a host's own; default the REST one. */
48
- request?: KernelRequest;
49
- /** Where the signed CDP URLs are held; default a Map of this provider's own. */
50
- urls?: UrlStore;
51
- /** Where the live views' URLs are held; default a Map of this provider's own. */
52
- liveUrls?: UrlStore;
53
46
  confirm?: ReleaseConfirm;
54
47
  sleep?: (ms: number) => Promise<void>;
55
48
  }
56
- /** What a host may add to a browser's create body: Kernel's own fields (headless, stealth, viewport, a profile, extensions). */
57
- export type KernelBrowserSettings = Record<string, unknown>;
58
49
  /** Computers that are Kernel browsers. */
59
- export declare class KernelProvider implements ComputerProvider {
50
+ export declare class KernelProvider implements ComputerProvider, BrowserComputerProvider {
60
51
  #private;
61
52
  readonly id = "kernel";
62
53
  readonly version: string;
63
- constructor({ apiKey, apiUrl, fetch: fetcher, request, urls, liveUrls, confirm, sleep }: KernelProviderOptions);
54
+ readonly profiles: BrowserProfiles;
55
+ constructor({ apiKey, apiUrl, env, fetch: fetcher, confirm, sleep }: KernelProviderOptions);
64
56
  /**
65
57
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
66
58
  * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
67
- * declared.
59
+ * declared. Its sessions' timeout is idle time (inactivity); a browser may be headless and opens a profile, which
60
+ * Kernel has written back once the browser is deleted (settleMs 0). Its stealth mode is not declared.
68
61
  */
69
62
  capabilities(): ComputerCapabilities;
70
63
  check(spec: ComputerSpec): Refusal[];
71
64
  /**
72
65
  * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
73
- * settings are Kernel's own create fields a host adds; what the protocol sets wins over them.
66
+ * spec.browser is the session's own options, each refused by check() unless declared; a profile is made first if
67
+ * Kernel does not know it.
74
68
  */
75
- create(spec: ComputerSpec, { signal, settings }?: {
76
- signal?: AbortSignal;
77
- settings?: KernelBrowserSettings;
78
- }): Promise<Result<CreatedComputer>>;
69
+ create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
79
70
  /**
80
71
  * Settings' test: one page of the organization's active browsers (GET /browsers?status=active), which makes nothing.
81
72
  * A refused key is unauthorized and a Kernel not reached unreachable; the words name the call, never the key.
@@ -105,8 +96,7 @@ export declare class KernelProvider implements ComputerProvider {
105
96
  }, { signal }?: CallContext): Promise<Result<BrowserStream>>;
106
97
  }
107
98
  /**
108
- * The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
109
- * host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
99
+ * The provider, built from its options alone, the key included (options.apiKey); it reads no environment, and throws in words when the key is missing, never echoing one.
110
100
  */
111
101
  export declare function create(options: KernelProviderOptions): KernelProvider;
112
102
  /** The conformance CLI's module for Kernel: its live switch, its image and its notes. */
package/dist/kernel.js CHANGED
@@ -1,6 +1,5 @@
1
- // Kernel as a computer of kind browser: each computer is a Kernel browser, over Kernel's REST API with fetch (no SDK),
2
- // or through a KernelRequest a host gives (pi-browser's own). Labels ride the browser's own tags; attach and list find a
3
- // browser by them; connect hands over its cdp_ws_url, which a driver dials; stream is its browser_live_view_url. Both
1
+ // Kernel as a computer of kind browser: each computer is a Kernel browser, over Kernel's REST API with fetch (no SDK). Labels
2
+ // ride the browser's own tags; attach and list find a browser by them; connect hands over its cdp_ws_url, which a driver dials; stream is its browser_live_view_url. Both
4
3
  // URLs are secrets: they stay in memory and never reach a ref, a list, an error's words or a report.
5
4
  //
6
5
  // Calls: POST /browsers (create, with timeout_seconds and tags), GET /browsers/{id} (read; 404 or deleted_at once
@@ -8,13 +7,20 @@
8
7
  // paged by X-Has-More and X-Next-Offset), and
9
8
  // DELETE /browsers/{id} (release). The key is a bearer token.
10
9
  //
10
+ // A session's own options (spec.browser): viewport and headless ride the create body (stealth false: Kernel's stealth
11
+ // mode brings its own proxy, which nothing here prices yet, so it is not declared); a profile is a
12
+ // Kernel profile by name, { name: pointer, save_changes: save }, made first if Kernel does not know it (GET
13
+ // /profiles/{name}, then POST /profiles; a 409 is another process making it). Profiles: POST /profiles { name } and
14
+ // DELETE /profiles/{name}.
15
+ //
11
16
  // Kernel's timeout_seconds is an idle timeout: Kernel ends a browser that long after its last CDP or live-view
12
17
  // connection closes, and sets no wall clock. So lifetimeMs is the longest a browser lives unwatched, at most Kernel's
13
18
  // largest idle timeout (72 h), and list reads no deadline.
19
+ import { randomBytes } from "node:crypto";
14
20
  import { readFileSync } from "node:fs";
15
21
  import { KERNEL } from "./descriptors/kernel.js";
16
22
  import { BROWSER_IMAGE } from "./descriptors/shared.js";
17
- import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, httpsBase, idProblem, labelsOf, labelsProblem, memoryUrls, queryable, recoverCreate, releaseConfirmed, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
23
+ import { cdpUrlProblem, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, httpsBase, idProblem, labelsOf, labelsProblem, memoryUrls, pointerOk, queryable, recoverCreate, releaseConfirmed, restCall, causedFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
18
24
  import { runLifetimeMs, } from "./provider.js";
19
25
  import { failFor, ok, vendorFail } from "./result.js";
20
26
  import { connectionError } from "./test-connection.js";
@@ -40,32 +46,38 @@ export function kernelRest({ apiKey, apiUrl = KERNEL_API_URL, fetch: fetcher = f
40
46
  const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Kernel API URL"), headers: { Authorization: `Bearer ${apiKey}` } };
41
47
  return (method, route, init = {}) => restCall(o, method, route, `${method} ${callName(route)}`, init);
42
48
  }
43
- /** A route as a failure names it: ids out, so no session id reads as a secret's neighbour. */
44
- const callName = (route) => route.replace(/\/browsers\/[^/?]+/, "/browsers/{id}");
49
+ /** A route as a failure names it: ids and names out, so no session id reads as a secret's neighbour and no profile's name (a pointer) is in words. */
50
+ const callName = (route) => route.replace(/\/browsers\/[^/?]+/, "/browsers/{id}").replace(/\/profiles\/[^/?]+/, "/profiles/{name}");
45
51
  const text = (value) => (typeof value === "string" ? value.trim() : "");
46
52
  const refOf = (id) => ({ id, name: id });
53
+ const statusOf = (error) => error?.status;
54
+ /** What a Kernel browser offers beyond the protocol, a fresh copy each time. */
55
+ const KERNEL_BROWSER = () => ({ timeout: "inactivity", minLifetimeMs: KERNEL_MIN_LIFETIME_MS, profiles: { settleMs: 0 }, headless: true });
47
56
  /** Computers that are Kernel browsers. */
48
57
  export class KernelProvider {
49
58
  id = "kernel";
50
59
  version = VERSION;
60
+ profiles = { create: (context) => this.#createProfile(context), remove: (pointer, context) => this.#removeProfile(pointer, context) };
51
61
  #request;
52
62
  #urls;
53
63
  #live;
54
64
  #confirm;
55
65
  #sleep;
56
- constructor({ apiKey, apiUrl, fetch: fetcher, request, urls, liveUrls, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
57
- if (request === undefined && (typeof apiKey !== "string" || apiKey === ""))
58
- throw new Error("set options.apiKey to a Kernel API key, or options.request to a host's own Kernel request: the provider reads no environment");
59
- this.#request = request ?? kernelRest({ apiKey: apiKey, ...(apiUrl ? { apiUrl } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
60
- this.#urls = urls ?? memoryUrls();
61
- this.#live = liveUrls ?? memoryUrls();
66
+ constructor({ apiKey, apiUrl, env = {}, fetch: fetcher, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
67
+ if (typeof apiKey !== "string" || apiKey === "")
68
+ throw new Error("set options.apiKey to a Kernel API key: the provider reads no environment");
69
+ const api = apiUrl || env.KERNEL_BASE_URL?.trim() || undefined;
70
+ this.#request = kernelRest({ apiKey, ...(api ? { apiUrl: api } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
71
+ this.#urls = memoryUrls();
72
+ this.#live = memoryUrls();
62
73
  this.#confirm = confirm;
63
74
  this.#sleep = sleep;
64
75
  }
65
76
  /**
66
77
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
67
78
  * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
68
- * declared.
79
+ * declared. Its sessions' timeout is idle time (inactivity); a browser may be headless and opens a profile, which
80
+ * Kernel has written back once the browser is deleted (settleMs 0). Its stealth mode is not declared.
69
81
  */
70
82
  capabilities() {
71
83
  return {
@@ -78,6 +90,7 @@ export class KernelProvider {
78
90
  groups: [...CAPABILITIES[0].groups],
79
91
  maxLifetimeMs: KERNEL_MAX_LIFETIME_MS,
80
92
  release: ["delete"],
93
+ browser: KERNEL_BROWSER(),
81
94
  };
82
95
  }
83
96
  check(spec) {
@@ -85,16 +98,31 @@ export class KernelProvider {
85
98
  }
86
99
  /**
87
100
  * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
88
- * settings are Kernel's own create fields a host adds; what the protocol sets wins over them.
101
+ * spec.browser is the session's own options, each refused by check() unless declared; a profile is made first if
102
+ * Kernel does not know it.
89
103
  */
90
- async create(spec, { signal, settings = {} } = {}) {
104
+ async create(spec, context) {
105
+ const signal = context?.signal;
91
106
  const refusals = this.check(spec);
92
107
  if (refusals.length > 0)
93
108
  return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
94
109
  if (signal?.aborted)
95
110
  return fail("aborted", "create was aborted before Kernel was called");
111
+ const options = spec.browser;
112
+ if (options?.profile !== undefined) {
113
+ const ensured = await this.#ensureProfile(options.profile.pointer, signal);
114
+ if (!ensured.ok)
115
+ return causedFail(ensured.error.code, `the profile could not be made ready: ${ensured.error.message}; no browser was made`, causeOf(ensured), "kernel");
116
+ }
96
117
  const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
97
- const body = { ...settings, timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000), tags: written };
118
+ const body = {
119
+ ...(options !== undefined ? { stealth: false } : {}),
120
+ ...(options?.viewport ? { viewport: { width: options.viewport.width, height: options.viewport.height } } : {}),
121
+ ...(options?.headless !== undefined ? { headless: options.headless } : {}),
122
+ ...(options?.profile ? { profile: { name: options.profile.pointer, save_changes: options.profile.save } } : {}),
123
+ timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000),
124
+ tags: written,
125
+ };
98
126
  let made;
99
127
  try {
100
128
  made = await this.#request("POST", "/browsers", { body, ...(signal ? { signal } : {}) });
@@ -127,6 +155,55 @@ export class KernelProvider {
127
155
  this.#live.set(id, live);
128
156
  return ok(refOf(id));
129
157
  }
158
+ /** A browser names only a profile Kernel knows: made if it is not (GET, then POST); a 409 is another process making it. */
159
+ async #ensureProfile(name, signal) {
160
+ try {
161
+ const found = await this.#request("GET", `/profiles/${encodeURIComponent(name)}`, signal ? { signal } : {});
162
+ if (found.status !== 404)
163
+ return ok(undefined);
164
+ }
165
+ catch (error) {
166
+ return vendorFailure("kernel", NAME, "GET /profiles/{name}", error);
167
+ }
168
+ try {
169
+ const made = await this.#request("POST", "/profiles", { body: { name }, ...(signal ? { signal } : {}) });
170
+ if (made.status === 404)
171
+ return vendorFailure("kernel", NAME, "POST /profiles", new BrowserVendorError(NAME, "POST /profiles", 404));
172
+ return ok(undefined);
173
+ }
174
+ catch (error) {
175
+ return statusOf(error) === 409 ? ok(undefined) : vendorFailure("kernel", NAME, "POST /profiles", error);
176
+ }
177
+ }
178
+ /** A new profile under a random name, which is its pointer: one POST /profiles, never retried. */
179
+ async #createProfile({ signal } = {}) {
180
+ const name = `agentrun-${randomBytes(12).toString("hex")}`;
181
+ const call = "POST /profiles";
182
+ let made;
183
+ try {
184
+ made = await this.#request("POST", "/profiles", { body: { name }, ...(signal ? { signal } : {}) });
185
+ }
186
+ catch (error) {
187
+ return vendorFailure("kernel", NAME, call, error);
188
+ }
189
+ if (made.status === 404)
190
+ return vendorFailure("kernel", NAME, call, new BrowserVendorError(NAME, call, 404));
191
+ if (made.json?.name !== name)
192
+ return vendorFail("kernel", `Kernel ${call} answered ${made.status} with another profile's name than the one asked for`);
193
+ return ok(name);
194
+ }
195
+ /** Deletes the profile; one Kernel no longer knows is removed. The words never carry the pointer. */
196
+ async #removeProfile(pointer, { signal } = {}) {
197
+ if (!pointerOk(pointer))
198
+ return fail("invalid", "a profile's pointer is a plain token, as profiles.create gave it");
199
+ try {
200
+ await this.#request("DELETE", `/profiles/${encodeURIComponent(pointer)}`, signal ? { signal } : {});
201
+ return ok(undefined);
202
+ }
203
+ catch (error) {
204
+ return vendorFailure("kernel", NAME, "DELETE /profiles/{name}", error);
205
+ }
206
+ }
130
207
  /**
131
208
  * The browsers a lost create made, released: what recoverCreate says of them. They are found as list finds any, by the
132
209
  * tags the create wrote (its create label first, so the query names it, then the run's), through #browsers: another
@@ -353,8 +430,7 @@ export class KernelProvider {
353
430
  }
354
431
  }
355
432
  /**
356
- * The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
357
- * host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
433
+ * The provider, built from its options alone, the key included (options.apiKey); it reads no environment, and throws in words when the key is missing, never echoing one.
358
434
  */
359
435
  export function create(options) {
360
436
  return new KernelProvider(options ?? {});