@parcha/agentrun-computer 0.0.0-stage → 0.1.0-beta.32

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 (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +2401 -2
  4. package/box/Dockerfile +69 -0
  5. package/box/agentrun-archil +168 -0
  6. package/box/build-daytona.py +26 -0
  7. package/box/build-e2b.mjs +32 -0
  8. package/box/build-modal.py +17 -0
  9. package/dist/actions.d.ts +18 -0
  10. package/dist/actions.js +139 -0
  11. package/dist/browser.d.ts +151 -0
  12. package/dist/browser.js +305 -0
  13. package/dist/browserbase.d.ts +139 -0
  14. package/dist/browserbase.js +408 -0
  15. package/dist/child.d.ts +40 -0
  16. package/dist/child.js +127 -0
  17. package/dist/client.d.ts +22 -0
  18. package/dist/client.js +136 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/archil.d.ts +68 -0
  22. package/dist/conformance/archil.js +152 -0
  23. package/dist/conformance/browserbase.d.ts +35 -0
  24. package/dist/conformance/browserbase.js +45 -0
  25. package/dist/conformance/cases/apps.d.ts +2 -0
  26. package/dist/conformance/cases/apps.js +155 -0
  27. package/dist/conformance/cases/browser.d.ts +4 -0
  28. package/dist/conformance/cases/browser.js +105 -0
  29. package/dist/conformance/cases/drift.d.ts +2 -0
  30. package/dist/conformance/cases/drift.js +64 -0
  31. package/dist/conformance/cases/exec.d.ts +2 -0
  32. package/dist/conformance/cases/exec.js +125 -0
  33. package/dist/conformance/cases/files.d.ts +2 -0
  34. package/dist/conformance/cases/files.js +294 -0
  35. package/dist/conformance/cases/health.d.ts +2 -0
  36. package/dist/conformance/cases/health.js +71 -0
  37. package/dist/conformance/cases/index.d.ts +9 -0
  38. package/dist/conformance/cases/index.js +37 -0
  39. package/dist/conformance/cases/input.d.ts +12 -0
  40. package/dist/conformance/cases/input.js +109 -0
  41. package/dist/conformance/cases/isolation.d.ts +21 -0
  42. package/dist/conformance/cases/isolation.js +92 -0
  43. package/dist/conformance/cases/lifetime.d.ts +2 -0
  44. package/dist/conformance/cases/lifetime.js +64 -0
  45. package/dist/conformance/cases/mount.d.ts +2 -0
  46. package/dist/conformance/cases/mount.js +252 -0
  47. package/dist/conformance/cases/process.d.ts +2 -0
  48. package/dist/conformance/cases/process.js +240 -0
  49. package/dist/conformance/cases/provider.d.ts +2 -0
  50. package/dist/conformance/cases/provider.js +302 -0
  51. package/dist/conformance/cases/screen.d.ts +9 -0
  52. package/dist/conformance/cases/screen.js +230 -0
  53. package/dist/conformance/cases/settings.d.ts +57 -0
  54. package/dist/conformance/cases/settings.js +142 -0
  55. package/dist/conformance/cases/touch.d.ts +2 -0
  56. package/dist/conformance/cases/touch.js +117 -0
  57. package/dist/conformance/cases/util.d.ts +7 -0
  58. package/dist/conformance/cases/util.js +8 -0
  59. package/dist/conformance/cdp.d.ts +13 -0
  60. package/dist/conformance/cdp.js +88 -0
  61. package/dist/conformance/cli.d.ts +29 -0
  62. package/dist/conformance/cli.js +231 -0
  63. package/dist/conformance/daytona-sweep.d.ts +18 -0
  64. package/dist/conformance/daytona-sweep.js +118 -0
  65. package/dist/conformance/daytona.d.ts +83 -0
  66. package/dist/conformance/daytona.js +107 -0
  67. package/dist/conformance/docker.d.ts +38 -0
  68. package/dist/conformance/docker.js +70 -0
  69. package/dist/conformance/drift-daemon.d.ts +8 -0
  70. package/dist/conformance/drift-daemon.js +41 -0
  71. package/dist/conformance/e2b-diagnose.d.ts +16 -0
  72. package/dist/conformance/e2b-diagnose.js +61 -0
  73. package/dist/conformance/e2b-sweep.d.ts +18 -0
  74. package/dist/conformance/e2b-sweep.js +125 -0
  75. package/dist/conformance/e2b.d.ts +74 -0
  76. package/dist/conformance/e2b.js +111 -0
  77. package/dist/conformance/fixture.d.ts +65 -0
  78. package/dist/conformance/fixture.js +98 -0
  79. package/dist/conformance/index.d.ts +8 -0
  80. package/dist/conformance/index.js +8 -0
  81. package/dist/conformance/kernel.d.ts +31 -0
  82. package/dist/conformance/kernel.js +40 -0
  83. package/dist/conformance/kind.d.ts +23 -0
  84. package/dist/conformance/kind.js +58 -0
  85. package/dist/conformance/modal-sweep.d.ts +22 -0
  86. package/dist/conformance/modal-sweep.js +190 -0
  87. package/dist/conformance/modal.d.ts +69 -0
  88. package/dist/conformance/modal.js +76 -0
  89. package/dist/conformance/orgo.d.ts +41 -0
  90. package/dist/conformance/orgo.js +69 -0
  91. package/dist/conformance/phone-harness.d.ts +61 -0
  92. package/dist/conformance/phone-harness.js +241 -0
  93. package/dist/conformance/png.d.ts +16 -0
  94. package/dist/conformance/png.js +132 -0
  95. package/dist/conformance/report.d.ts +2 -0
  96. package/dist/conformance/report.js +86 -0
  97. package/dist/conformance/runner.d.ts +11 -0
  98. package/dist/conformance/runner.js +585 -0
  99. package/dist/conformance/tar.d.ts +13 -0
  100. package/dist/conformance/tar.js +105 -0
  101. package/dist/conformance/types.d.ts +257 -0
  102. package/dist/conformance/types.js +24 -0
  103. package/dist/daemon-copy.d.ts +40 -0
  104. package/dist/daemon-copy.js +259 -0
  105. package/dist/daytona.d.ts +178 -0
  106. package/dist/daytona.js +1484 -0
  107. package/dist/desktop.d.ts +24 -0
  108. package/dist/desktop.js +68 -0
  109. package/dist/docker/egress-main.d.ts +1 -0
  110. package/dist/docker/egress-main.js +68 -0
  111. package/dist/docker/egress-proxy.d.ts +53 -0
  112. package/dist/docker/egress-proxy.js +450 -0
  113. package/dist/docker/egress-table.d.ts +39 -0
  114. package/dist/docker/egress-table.js +197 -0
  115. package/dist/docker/egress.d.ts +109 -0
  116. package/dist/docker/egress.js +318 -0
  117. package/dist/docker/image.d.ts +49 -0
  118. package/dist/docker/image.js +302 -0
  119. package/dist/docker/stage.d.ts +21 -0
  120. package/dist/docker/stage.js +290 -0
  121. package/dist/docker/volume.d.ts +24 -0
  122. package/dist/docker/volume.js +67 -0
  123. package/dist/docker.d.ts +150 -0
  124. package/dist/docker.js +1200 -0
  125. package/dist/drift.d.ts +200 -0
  126. package/dist/drift.js +416 -0
  127. package/dist/e2b.d.ts +335 -0
  128. package/dist/e2b.js +1515 -0
  129. package/dist/entry.d.ts +2 -0
  130. package/dist/entry.js +24 -0
  131. package/dist/files.d.ts +50 -0
  132. package/dist/files.js +208 -0
  133. package/dist/index.d.ts +27 -0
  134. package/dist/index.js +26 -0
  135. package/dist/isolation.d.ts +29 -0
  136. package/dist/isolation.js +71 -0
  137. package/dist/janitor.d.ts +50 -0
  138. package/dist/janitor.js +135 -0
  139. package/dist/kernel.d.ts +113 -0
  140. package/dist/kernel.js +358 -0
  141. package/dist/kinds.d.ts +79 -0
  142. package/dist/kinds.js +133 -0
  143. package/dist/labels.d.ts +23 -0
  144. package/dist/labels.js +50 -0
  145. package/dist/modal.d.ts +302 -0
  146. package/dist/modal.js +1374 -0
  147. package/dist/mount-archil.d.ts +164 -0
  148. package/dist/mount-archil.js +471 -0
  149. package/dist/mount.d.ts +57 -0
  150. package/dist/mount.js +104 -0
  151. package/dist/orgo-channel.d.ts +96 -0
  152. package/dist/orgo-channel.js +391 -0
  153. package/dist/orgo.d.ts +139 -0
  154. package/dist/orgo.js +1006 -0
  155. package/dist/phone-harness.d.ts +185 -0
  156. package/dist/phone-harness.js +1420 -0
  157. package/dist/processes.d.ts +24 -0
  158. package/dist/processes.js +40 -0
  159. package/dist/protocol.d.ts +729 -0
  160. package/dist/protocol.js +54 -0
  161. package/dist/provider.d.ts +245 -0
  162. package/dist/provider.js +37 -0
  163. package/dist/providers.d.ts +68 -0
  164. package/dist/providers.js +25 -0
  165. package/dist/result.d.ts +15 -0
  166. package/dist/result.js +2 -0
  167. package/dist/screen-watch.d.ts +150 -0
  168. package/dist/screen-watch.js +490 -0
  169. package/dist/test-connection.d.ts +17 -0
  170. package/dist/test-connection.js +26 -0
  171. package/dist/wait.d.ts +23 -0
  172. package/dist/wait.js +65 -0
  173. package/package.json +62 -4
@@ -0,0 +1,113 @@
1
+ import { type BrowserStream, type ReleaseConfirm, type RestReply, type UrlStore } from "./browser.js";
2
+ import type { KindCapabilities } from "./kinds.js";
3
+ import type { MountKind } from "./mount.js";
4
+ import type { AttachedComputer, CallContext, ComputerCapabilities, ComputerConnection, ComputerInfo, ComputerProvider, ComputerRef, ComputerSpec, CreatedComputer, NetworkPolicy, NetworkSpec, Refusal } from "./provider.js";
5
+ import { type Result } from "./result.js";
6
+ export declare const KERNEL_API_URL = "https://api.onkernel.com";
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. */
8
+ export declare const KERNEL_CDP_DOMAIN = "kernel.sh";
9
+ /** Kernel's shortest and longest idle timeout. */
10
+ export declare const KERNEL_MIN_LIFETIME_MS = 10000;
11
+ export declare const KERNEL_MAX_LIFETIME_MS = 259200000;
12
+ /** A browser takes no mount. */
13
+ export declare const MOUNT: readonly MountKind[];
14
+ /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
15
+ export declare const CAPABILITIES: readonly KindCapabilities[];
16
+ /** A browser as Kernel answers it; only what the provider reads. */
17
+ export interface KernelBrowser {
18
+ session_id?: unknown;
19
+ /** The signed CDP URL: a secret. */
20
+ cdp_ws_url?: unknown;
21
+ /** The live view's URL: a secret. */
22
+ browser_live_view_url?: unknown;
23
+ tags?: unknown;
24
+ deleted_at?: unknown;
25
+ }
26
+ /**
27
+ * One Kernel request, never retried: a create sent twice would be a second paid browser. It answers 404 as a reply,
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.
30
+ */
31
+ export type KernelRequest = (method: string, route: string, init?: {
32
+ body?: unknown;
33
+ query?: URLSearchParams;
34
+ signal?: AbortSignal;
35
+ }) => Promise<RestReply>;
36
+ /** Kernel's REST API over fetch: the default request. */
37
+ export declare function kernelRest({ apiKey, apiUrl, fetch: fetcher }: {
38
+ apiKey: string;
39
+ apiUrl?: string;
40
+ fetch?: typeof fetch;
41
+ }): KernelRequest;
42
+ export interface KernelProviderOptions {
43
+ /** With apiUrl and fetch, the REST request is built from it; required unless request is given. */
44
+ apiKey?: string;
45
+ apiUrl?: string;
46
+ 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
+ confirm?: ReleaseConfirm;
54
+ sleep?: (ms: number) => Promise<void>;
55
+ }
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
+ /** Computers that are Kernel browsers. */
59
+ export declare class KernelProvider implements ComputerProvider {
60
+ #private;
61
+ readonly id = "kernel";
62
+ readonly version: string;
63
+ constructor({ apiKey, apiUrl, fetch: fetcher, request, urls, liveUrls, confirm, sleep }: KernelProviderOptions);
64
+ /**
65
+ * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
66
+ * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
67
+ * declared.
68
+ */
69
+ capabilities(): ComputerCapabilities;
70
+ check(spec: ComputerSpec): Refusal[];
71
+ /**
72
+ * 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.
74
+ */
75
+ create(spec: ComputerSpec, { signal, settings }?: {
76
+ signal?: AbortSignal;
77
+ settings?: KernelBrowserSettings;
78
+ }): Promise<Result<CreatedComputer>>;
79
+ /**
80
+ * Settings' test: one page of the organization's active browsers (GET /browsers?status=active), which makes nothing.
81
+ * A refused key is unauthorized and a Kernel not reached unreachable; the words name the call, never the key.
82
+ */
83
+ testConnection({ signal }?: CallContext): Promise<Result<{
84
+ detail: string;
85
+ }>>;
86
+ attach(ref: {
87
+ id: string;
88
+ } | {
89
+ labels: Record<string, string>;
90
+ }, { signal }?: CallContext): Promise<Result<AttachedComputer>>;
91
+ list(labels: Record<string, string>, { signal }?: CallContext): Promise<Result<ComputerInfo[]>>;
92
+ /** Always open: a Kernel browser reaches the open web, and a change is refused in words. */
93
+ network(ref: ComputerRef, policy?: NetworkSpec, { signal }?: CallContext): Promise<Result<NetworkPolicy>>;
94
+ /**
95
+ * The browser's signed CDP URL, held since create or read from Kernel, and a client that answers hello and ping. The
96
+ * browser is read first, held URL or not: one deleted, or that Kernel no longer knows though its URL is held, is gone,
97
+ * never handed over.
98
+ */
99
+ connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
100
+ /** Deletes the browser and waits until Kernel reads it as gone; one already deleted or unknown is released. */
101
+ release(ref: ComputerRef, how: "stop" | "delete", { signal }?: CallContext): Promise<Result<void>>;
102
+ /** The browser's live view, which takes input: a view-only one is refused, never handed over as one. */
103
+ stream(ref: ComputerRef, options?: {
104
+ viewOnly?: boolean;
105
+ }, { signal }?: CallContext): Promise<Result<BrowserStream>>;
106
+ }
107
+ /**
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.
110
+ */
111
+ export declare function create(options: KernelProviderOptions): KernelProvider;
112
+ /** The conformance CLI's module for Kernel: its live switch, its image and its notes. */
113
+ export declare const conformance: () => Promise<typeof import("./conformance/kernel.js")>;
package/dist/kernel.js ADDED
@@ -0,0 +1,358 @@
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
4
+ // URLs are secrets: they stay in memory and never reach a ref, a list, an error's words or a report.
5
+ //
6
+ // Calls: POST /browsers (create, with timeout_seconds and tags), GET /browsers/{id} (read; 404 or deleted_at once
7
+ // deleted), GET /browsers?status=all&tags[key]=value&limit&offset (list, every state, the deleted dropped by deleted_at;
8
+ // paged by X-Has-More and X-Next-Offset), and
9
+ // DELETE /browsers/{id} (release). The key is a bearer token.
10
+ //
11
+ // Kernel's timeout_seconds is an idle timeout: Kernel ends a browser that long after its last CDP or live-view
12
+ // connection closes, and sets no wall clock. So lifetimeMs is the longest a browser lives unwatched, at most Kernel's
13
+ // largest idle timeout (72 h), and list reads no deadline.
14
+ import { readFileSync } from "node:fs";
15
+ import { cdpUrlProblem, BROWSER_IMAGE, browserClient, browserHello, BrowserVendorError, CREATE_LABEL, carries, causeOf, checkBrowser, createLabelValue, createUncertain, DEFAULT_CONFIRM, defaultSleep, httpsBase, idProblem, labelsOf, labelsProblem, memoryUrls, queryable, recoverCreate, releaseConfirmed, restCall, vendorFail, vendorFailure, withoutCreateLabel, } from "./browser.js";
16
+ import { fail, ok } from "./result.js";
17
+ import { connectionError } from "./test-connection.js";
18
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
19
+ const NAME = "Kernel";
20
+ export const KERNEL_API_URL = "https://api.onkernel.com";
21
+ /** 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. */
22
+ export const KERNEL_CDP_DOMAIN = "kernel.sh";
23
+ const CDP_DOMAIN = KERNEL_CDP_DOMAIN;
24
+ /** Kernel's shortest and longest idle timeout. */
25
+ export const KERNEL_MIN_LIFETIME_MS = 10_000;
26
+ export const KERNEL_MAX_LIFETIME_MS = 259_200_000;
27
+ /** The most pages a list reads before it fails rather than run on. */
28
+ const MAX_PAGES = 100;
29
+ /** A browser takes no mount. */
30
+ export const MOUNT = [];
31
+ /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
32
+ export const CAPABILITIES = [{ kind: "browser", groups: ["cdp", "stream"] }];
33
+ /** Kernel's REST API over fetch: the default request. */
34
+ export function kernelRest({ apiKey, apiUrl = KERNEL_API_URL, fetch: fetcher = fetch }) {
35
+ const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Kernel API URL"), headers: { Authorization: `Bearer ${apiKey}` } };
36
+ return (method, route, init = {}) => restCall(o, method, route, `${method} ${callName(route)}`, init);
37
+ }
38
+ /** A route as a failure names it: ids out, so no session id reads as a secret's neighbour. */
39
+ const callName = (route) => route.replace(/\/browsers\/[^/?]+/, "/browsers/{id}");
40
+ const text = (value) => (typeof value === "string" ? value.trim() : "");
41
+ const refOf = (id) => ({ id, name: id });
42
+ /** Computers that are Kernel browsers. */
43
+ export class KernelProvider {
44
+ id = "kernel";
45
+ version = VERSION;
46
+ #request;
47
+ #urls;
48
+ #live;
49
+ #confirm;
50
+ #sleep;
51
+ constructor({ apiKey, apiUrl, fetch: fetcher, request, urls, liveUrls, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
52
+ if (request === undefined && (typeof apiKey !== "string" || apiKey === ""))
53
+ 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");
54
+ this.#request = request ?? kernelRest({ apiKey: apiKey, ...(apiUrl ? { apiUrl } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
55
+ this.#urls = urls ?? memoryUrls();
56
+ this.#live = liveUrls ?? memoryUrls();
57
+ this.#confirm = confirm;
58
+ this.#sleep = sleep;
59
+ }
60
+ /**
61
+ * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
62
+ * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
63
+ * declared.
64
+ */
65
+ capabilities() {
66
+ return {
67
+ kind: "browser",
68
+ lifetime: "vendor",
69
+ network: ["open"],
70
+ isolation: "vm",
71
+ os: "linux",
72
+ daemon: "none",
73
+ groups: [...CAPABILITIES[0].groups],
74
+ maxLifetimeMs: KERNEL_MAX_LIFETIME_MS,
75
+ release: ["delete"],
76
+ };
77
+ }
78
+ check(spec) {
79
+ return checkBrowser(spec, this.capabilities(), NAME, KERNEL_MIN_LIFETIME_MS);
80
+ }
81
+ /**
82
+ * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
83
+ * settings are Kernel's own create fields a host adds; what the protocol sets wins over them.
84
+ */
85
+ async create(spec, { signal, settings = {} } = {}) {
86
+ const refusals = this.check(spec);
87
+ if (refusals.length > 0)
88
+ return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
89
+ if (signal?.aborted)
90
+ return fail("aborted", "create was aborted before Kernel was called");
91
+ const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
92
+ const body = { ...settings, timeout_seconds: Math.ceil(spec.lifetimeMs / 1000), tags: written };
93
+ let made;
94
+ try {
95
+ made = await this.#request("POST", "/browsers", { body, ...(signal ? { signal } : {}) });
96
+ }
97
+ catch (error) {
98
+ const failed = vendorFailure("kernel", NAME, "POST /browsers", error);
99
+ if (failed.ok || !createUncertain(error))
100
+ return failed;
101
+ // The browser may have been made though its answer never came: found by its create label, never made again.
102
+ return vendorFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed));
103
+ }
104
+ const browser = (made.json ?? {});
105
+ const id = text(browser.session_id);
106
+ const url = text(browser.cdp_ws_url);
107
+ if (made.status === 404)
108
+ return vendorFailure("kernel", NAME, "POST /browsers", new BrowserVendorError(NAME, "POST /browsers", made.status, "no_session"));
109
+ if (idProblem(id, NAME) !== undefined) {
110
+ const failed = vendorFailure("kernel", NAME, "POST /browsers", new BrowserVendorError(NAME, "POST /browsers", made.status, "no_session"));
111
+ return failed.ok ? failed : fail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`);
112
+ }
113
+ const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
114
+ if (unusable !== undefined) {
115
+ // The browser is made and billed until its idle timeout: deleted here, not left to a later sweep.
116
+ const released = await this.release(refOf(id), "delete");
117
+ return fail("kernel", `Kernel POST /browsers made a browser with no CDP URL to hand over: ${unusable}; ${released.ok ? "the browser was released" : `the browser was not released (${released.error.code}), and its tags let a sweep find it`}`);
118
+ }
119
+ this.#urls.set(id, url);
120
+ const live = text(browser.browser_live_view_url);
121
+ if (live !== "")
122
+ this.#live.set(id, live);
123
+ return ok(refOf(id));
124
+ }
125
+ /**
126
+ * The browsers a lost create made, released: what recoverCreate says of them. They are found as list finds any, by the
127
+ * tags the create wrote (its create label first, so the query names it, then the run's), through #browsers: another
128
+ * browser of the same run carries a create label of its own and is left alone. #browsers reads every state not
129
+ * deleted, so a browser still starting is found and released too.
130
+ */
131
+ #recover(labels) {
132
+ const find = async (signal) => {
133
+ const found = await this.#browsers(labels, signal);
134
+ return found.ok ? ok(found.value.map((b) => b.id)) : found;
135
+ };
136
+ return recoverCreate("browser", find, (id) => this.release(refOf(id), "delete"), this.#sleep);
137
+ }
138
+ /**
139
+ * Settings' test: one page of the organization's active browsers (GET /browsers?status=active), which makes nothing.
140
+ * A refused key is unauthorized and a Kernel not reached unreachable; the words name the call, never the key.
141
+ */
142
+ async testConnection({ signal } = {}) {
143
+ const call = "GET /browsers";
144
+ let page;
145
+ try {
146
+ page = await this.#request("GET", "/browsers", { query: new URLSearchParams({ status: "active", limit: "100", offset: "0" }), ...(signal ? { signal } : {}) });
147
+ }
148
+ catch (error) {
149
+ const failed = vendorFailure("kernel", NAME, call, error);
150
+ if (failed.ok)
151
+ return failed;
152
+ const reached = error?.status !== undefined || failed.error.code === "aborted";
153
+ return fail(reached ? connectionError(failed.error).code : "unreachable", failed.error.message);
154
+ }
155
+ if (page.status === 404)
156
+ return fail("kernel", `Kernel ${call} answered 404: the API URL is not Kernel's`);
157
+ if (!Array.isArray(page.json))
158
+ return fail("kernel", `Kernel ${call} answered ${page.status} (not_a_list)`);
159
+ const n = page.json.length;
160
+ const more = page.headers.get("x-has-more") === "true" ? " or more" : "";
161
+ return ok({ detail: `Kernel answered: ${n}${more} active ${n === 1 && more === "" ? "browser" : "browsers"} in the organization` });
162
+ }
163
+ /** The browser, when Kernel still runs it; not_found in words when it does not know it, gone when it was deleted. */
164
+ async #running(id, signal) {
165
+ const problem = idProblem(id, NAME);
166
+ if (problem)
167
+ return fail("invalid", problem);
168
+ let found;
169
+ try {
170
+ found = await this.#request("GET", `/browsers/${encodeURIComponent(id)}`, signal ? { signal } : {});
171
+ }
172
+ catch (error) {
173
+ return vendorFailure("kernel", NAME, "GET /browsers/{id}", error);
174
+ }
175
+ const browser = found.json;
176
+ if (found.status === 404 || browser === null || typeof browser !== "object")
177
+ return fail("not_found", `no Kernel browser has the id ${id}`);
178
+ if (browser.deleted_at)
179
+ return fail("gone", `the Kernel browser ${id} was deleted: only a running browser is attached or connected to`);
180
+ return ok(browser);
181
+ }
182
+ async #alive(id, signal) {
183
+ const found = await this.#running(id, signal);
184
+ if (found.ok)
185
+ return ok(true);
186
+ return found.error.code === "not_found" || found.error.code === "gone" ? ok(false) : found;
187
+ }
188
+ #attached(id) {
189
+ return { ...refOf(id), spec: { image: BROWSER_IMAGE, user: "unknown", network: "open", kind: "browser" } };
190
+ }
191
+ async attach(ref, { signal } = {}) {
192
+ const given = (typeof ref === "object" && ref !== null ? ref : {});
193
+ if ((given.id === undefined) === (given.labels === undefined))
194
+ return fail("invalid", "attach takes { id } or { labels }, one of them");
195
+ if (given.id !== undefined) {
196
+ const found = await this.#running(given.id, signal);
197
+ return found.ok ? ok(this.#attached(given.id)) : found;
198
+ }
199
+ const labels = given.labels;
200
+ const listed = await this.#browsers(labels, signal);
201
+ if (!listed.ok)
202
+ return listed;
203
+ const words = JSON.stringify(labels);
204
+ if (listed.value.length === 0)
205
+ return fail("not_found", `no running Kernel browser has the labels ${words}`);
206
+ if (listed.value.length > 1)
207
+ return fail("invalid", `${listed.value.length} Kernel browsers have the labels ${words}: ${listed.value.map((b) => b.id).join(", ")}`);
208
+ return ok(this.#attached(listed.value[0].id));
209
+ }
210
+ /**
211
+ * The live browsers with all of these labels, every page read. Kernel is asked by the first label a query carries as
212
+ * it is, in every state (status=all: its filter takes one value, active, deleted or all, and active may leave out a
213
+ * browser still starting, which bills), and a row with deleted_at is dropped here; so list and attach show a starting
214
+ * browser, as Browserbase lists a PENDING session, and a lost create's recovery misses none. The match is the
215
+ * provider's own, so a lane that drops the filter never hands back another's. A page that cannot be read fails the
216
+ * whole list: a release trusts it.
217
+ */
218
+ async #browsers(labels, signal) {
219
+ const problem = labelsProblem(labels);
220
+ if (problem)
221
+ return fail("invalid", problem);
222
+ if (Object.keys(labels).length === 0)
223
+ return fail("invalid", "list and attach take at least one label: a Kernel organization holds browsers this provider did not make");
224
+ const first = Object.entries(labels).find(queryable);
225
+ const found = [];
226
+ const seen = new Set();
227
+ const call = "GET /browsers";
228
+ for (let offset = 0, pages = 0; pages < MAX_PAGES; pages++) {
229
+ const query = new URLSearchParams({ status: "all", ...(first === undefined ? {} : { [`tags[${first[0]}]`]: first[1] }), limit: "100", offset: String(offset) });
230
+ let page;
231
+ try {
232
+ page = await this.#request("GET", "/browsers", { query, ...(signal ? { signal } : {}) });
233
+ }
234
+ catch (error) {
235
+ return vendorFailure("kernel", NAME, call, error);
236
+ }
237
+ // A list is never "not found": a 404 is a wrong base URL, and an empty answer would hide every browser.
238
+ if (page.status === 404)
239
+ return vendorFailure("kernel", NAME, call, new BrowserVendorError(NAME, call, 404));
240
+ if (!Array.isArray(page.json))
241
+ return vendorFailure("kernel", NAME, call, new BrowserVendorError(NAME, call, page.status, "not_a_list"));
242
+ for (const row of page.json) {
243
+ const id = text(row?.session_id);
244
+ if (id !== "" && !row.deleted_at && carries(row.tags, labels) && !seen.has(id)) {
245
+ seen.add(id);
246
+ found.push({ id, tags: withoutCreateLabel(labelsOf(row.tags)) });
247
+ }
248
+ }
249
+ if (page.headers.get("x-has-more") !== "true")
250
+ return ok(found);
251
+ const next = Number(page.headers.get("x-next-offset"));
252
+ if (!Number.isInteger(next) || next <= offset)
253
+ return fail("kernel", "Kernel reported more browsers without the next page's offset");
254
+ offset = next;
255
+ }
256
+ return fail("kernel", `Kernel kept answering more pages of browsers past ${MAX_PAGES}`);
257
+ }
258
+ async list(labels, { signal } = {}) {
259
+ const found = await this.#browsers(labels, signal);
260
+ if (!found.ok)
261
+ return found;
262
+ // Kernel's timeout is idle time, not a wall clock: no deadline to read.
263
+ return ok(found.value.map(({ id, tags }) => ({ ref: refOf(id), labels: tags, deadline: undefined, state: "running", network: "open" })));
264
+ }
265
+ /** Always open: a Kernel browser reaches the open web, and a change is refused in words. */
266
+ async network(ref, policy, { signal } = {}) {
267
+ if (policy !== undefined && policy !== "open")
268
+ return fail("refused", `a Kernel browser's network is open; it cannot be set to ${JSON.stringify(policy)}`);
269
+ const found = await this.#running(ref?.id, signal);
270
+ return found.ok ? ok("open") : found;
271
+ }
272
+ /**
273
+ * The browser's signed CDP URL, held since create or read from Kernel, and a client that answers hello and ping. The
274
+ * browser is read first, held URL or not: one deleted, or that Kernel no longer knows though its URL is held, is gone,
275
+ * never handed over.
276
+ */
277
+ async connect(ref) {
278
+ const id = ref?.id;
279
+ const problem = idProblem(id, NAME);
280
+ if (problem)
281
+ return fail("invalid", problem);
282
+ let url = this.#urls.get(id);
283
+ const found = await this.#running(id);
284
+ if (!found.ok) {
285
+ // A vendor that did not answer leaves the held URL for the next connect; a browser it deleted takes it along.
286
+ if (found.error.code !== "not_found" && found.error.code !== "gone")
287
+ return found;
288
+ if (url === undefined)
289
+ return found;
290
+ this.#urls.delete(id);
291
+ return fail("gone", found.error.code === "gone" ? found.error.message : `the Kernel browser ${id} is gone: ${found.error.message}`);
292
+ }
293
+ if (url === undefined) {
294
+ url = text(found.value.cdp_ws_url);
295
+ if (url === "")
296
+ return fail("not_found", `the Kernel browser ${id} is not available for connection`);
297
+ }
298
+ // Whatever held it (create, a read, a host's url store), a URL a driver would dial is wss: on Kernel's own domain.
299
+ const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
300
+ if (unusable !== undefined)
301
+ return fail("kernel", `the Kernel browser ${id} is not handed over: ${unusable}`);
302
+ this.#urls.set(id, url);
303
+ const hello = browserHello(VERSION, this.capabilities().groups);
304
+ const client = browserClient(hello, (signal) => this.#alive(id, signal));
305
+ return ok({ client, hello, cdp: { url }, close: async () => client.close() });
306
+ }
307
+ /** Deletes the browser and waits until Kernel reads it as gone; one already deleted or unknown is released. */
308
+ async release(ref, how, { signal } = {}) {
309
+ if (how !== "delete")
310
+ return fail("refused", `a Kernel browser is released with "delete"; it cannot be stopped and kept, so ${String(how)} is refused and the browser is left as it is`);
311
+ const id = ref?.id;
312
+ const problem = idProblem(id, NAME);
313
+ if (problem)
314
+ return fail("invalid", problem);
315
+ const released = await releaseConfirmed({
316
+ request: async () => {
317
+ try {
318
+ const answer = await this.#request("DELETE", `/browsers/${encodeURIComponent(id)}`, signal ? { signal } : {});
319
+ return ok(answer.status === 404 ? "gone" : "asked");
320
+ }
321
+ catch (error) {
322
+ return vendorFailure("kernel", NAME, "DELETE /browsers/{id}", error);
323
+ }
324
+ },
325
+ running: () => this.#alive(id, signal),
326
+ confirm: this.#confirm,
327
+ sleep: this.#sleep,
328
+ stillRunning: `Kernel session ${id} still running after its delete`,
329
+ });
330
+ if (released.ok) {
331
+ this.#urls.delete(id);
332
+ this.#live.delete(id);
333
+ }
334
+ return released;
335
+ }
336
+ /** The browser's live view, which takes input: a view-only one is refused, never handed over as one. */
337
+ async stream(ref, options = {}, { signal } = {}) {
338
+ if (options.viewOnly)
339
+ return fail("unsupported", "Kernel's live view takes input; it has no view-only URL here");
340
+ const found = await this.#running(ref?.id, signal);
341
+ if (!found.ok)
342
+ return found;
343
+ const url = this.#live.get(ref.id) ?? text(found.value.browser_live_view_url);
344
+ if (url === "")
345
+ return fail("not_found", `Kernel gave no live view for the browser ${ref.id}: a headless browser has none`);
346
+ this.#live.set(ref.id, url);
347
+ return ok({ url });
348
+ }
349
+ }
350
+ /**
351
+ * The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
352
+ * host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
353
+ */
354
+ export function create(options) {
355
+ return new KernelProvider(options ?? {});
356
+ }
357
+ /** The conformance CLI's module for Kernel: its live switch, its image and its notes. */
358
+ export const conformance = () => import("./conformance/kernel.js");
@@ -0,0 +1,79 @@
1
+ import type { MountKind } from "./mount.js";
2
+ import type { ComputerKind, Group } from "./protocol.js";
3
+ import type { ComputerCapabilities } from "./provider.js";
4
+ import type { Result } from "./result.js";
5
+ /**
6
+ * What an agent is given. none: the run's folder only, no computer. sandbox: a Linux shell with files and processes.
7
+ * desktop: a screen, a pointer and keys (Linux, Windows or macOS), a shell when it has one. phone: a screen, touch and
8
+ * apps. browser: a CDP target.
9
+ */
10
+ export type ComputerSettingKind = "none" | "sandbox" | "desktop" | "phone" | "browser";
11
+ /** A setting kind's machine kinds and groups. */
12
+ export interface SettingKindSpec {
13
+ /** The capabilities().kind values that can serve it. */
14
+ machineKinds: readonly ComputerKind[];
15
+ /** Every one declared, and passing its conformance cases, to serve it. */
16
+ required: readonly Group[];
17
+ /** Brought when declared. */
18
+ optional: readonly Group[];
19
+ }
20
+ export declare const SETTING_KINDS: Readonly<Record<ComputerSettingKind, SettingKindSpec>>;
21
+ /** Every setting kind, in the table's order. */
22
+ export declare const SETTING_KIND_NAMES: ComputerSettingKind[];
23
+ /** The capabilities serves() and kindOf() read. */
24
+ export type KindCapabilities = Pick<ComputerCapabilities, "kind" | "groups">;
25
+ /** Why capabilities do not serve a setting kind, in words; none when they do. */
26
+ export declare function servingRefusals(capabilities: KindCapabilities, kind: ComputerSettingKind): string[];
27
+ /** Whether a provider with these capabilities serves the kind: its machine kind is one of the kind's, and it declares every required group. */
28
+ export declare function serves(capabilities: KindCapabilities, kind: ComputerSettingKind): boolean;
29
+ /** The setting kind these capabilities serve, or undefined when they serve none. Machine kinds are apart, so at most one. */
30
+ export declare function kindOf(capabilities: KindCapabilities): ComputerSettingKind | undefined;
31
+ /** One key a provider takes in Settings: its serve-side name (Settings accepts only these), and whether it is needed. */
32
+ export interface ProviderKey {
33
+ name: string;
34
+ required: boolean;
35
+ }
36
+ /** A provider as Settings shows it. */
37
+ export interface ProviderEntry {
38
+ /** Its id: a line of the provider registry (providers.ts) once its file lands. */
39
+ id: string;
40
+ label: string;
41
+ /** Derived: the setting kinds its capabilities serve (serves), never written by hand. */
42
+ kinds: readonly ComputerSettingKind[];
43
+ /** The serve-side key names only; never a value. */
44
+ keys: readonly ProviderKey[];
45
+ /** The mount kinds its computers take; [] cannot mount the run's folder. Its module's MOUNT, once its file lands. */
46
+ mounts: readonly MountKind[];
47
+ /** The vendor bills by time; prices are the vendor's page, not ours. */
48
+ metered: boolean;
49
+ /**
50
+ * Its static capabilities: the machine kind and groups of each configuration it offers. Its module's CAPABILITIES,
51
+ * once its file lands, and each built configuration's capabilities().
52
+ */
53
+ capabilities: readonly KindCapabilities[];
54
+ /**
55
+ * The image a computer of each setting kind starts from when its setting names none, each the constant its provider
56
+ * module owns. A kind with no entry has no default, and the caller refuses the setting in words. Docker's sandbox has
57
+ * none: serve builds its image itself (DOCKER_RECIPE).
58
+ */
59
+ defaultImage?: Partial<Record<ComputerSettingKind, string>>;
60
+ }
61
+ /**
62
+ * Every provider Settings offers, each with its provider file in the registry;
63
+ * a unit test then holds each to its module (CAPABILITIES, MOUNT). daytona, modal and e2b take archil mounts.
64
+ */
65
+ export declare const PROVIDERS: readonly ProviderEntry[];
66
+ /** What testConnection is given: the provider's keys by their serve-side names, and the caller's signal. */
67
+ export interface TestConnectionOptions {
68
+ keys: Readonly<Record<string, string>>;
69
+ signal?: AbortSignal;
70
+ }
71
+ /**
72
+ * Settings' "test connection": ONE account-level read with the given keys (a list by label, the vendor's whoami) that
73
+ * never creates a computer, so it never spends. ok with words on what it read; else unauthorized, unreachable, refused
74
+ * or another code, the message never carrying a key. A full live check (create, then the kind's conformance) is the QA
75
+ * board's, not this.
76
+ */
77
+ export type TestConnection = (providerId: string, options: TestConnectionOptions) => Promise<Result<{
78
+ detail: string;
79
+ }>>;