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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +251 -46
  2. package/box/Dockerfile +3 -1
  3. package/box/agentrun-archil +59 -7
  4. package/box/build-daytona.py +20 -4
  5. package/dist/browser.d.ts +73 -23
  6. package/dist/browser.js +141 -17
  7. package/dist/browserbase.d.ts +48 -25
  8. package/dist/browserbase.js +176 -29
  9. package/dist/chrome.d.ts +3 -4
  10. package/dist/chrome.js +6 -11
  11. package/dist/computerd-linux-amd64 +0 -0
  12. package/dist/computerd-linux-arm64 +0 -0
  13. package/dist/conformance/browserbase.js +1 -1
  14. package/dist/conformance/cases/provider.js +78 -3
  15. package/dist/conformance/daytona.d.ts +4 -0
  16. package/dist/conformance/daytona.js +7 -1
  17. package/dist/conformance/e2b.js +2 -1
  18. package/dist/conformance/fixture.js +24 -2
  19. package/dist/conformance/kernel.js +1 -1
  20. package/dist/conformance/kind.js +2 -1
  21. package/dist/conformance/{local.d.ts → local-chrome.d.ts} +7 -7
  22. package/dist/conformance/{local.js → local-chrome.js} +11 -11
  23. package/dist/conformance/orgo.d.ts +11 -5
  24. package/dist/conformance/orgo.js +37 -8
  25. package/dist/conformance/phone-harness.js +2 -1
  26. package/dist/conformance/report.js +3 -2
  27. package/dist/conformance/runner.js +25 -7
  28. package/dist/conformance/types.d.ts +21 -8
  29. package/dist/conformance/types.js +10 -0
  30. package/dist/conformance/windows-fixture.d.ts +1 -0
  31. package/dist/conformance/windows-fixture.js +37 -0
  32. package/dist/daytona.d.ts +16 -35
  33. package/dist/daytona.js +87 -95
  34. package/dist/descriptor.d.ts +116 -0
  35. package/dist/descriptor.js +92 -0
  36. package/dist/descriptors/browserbase.d.ts +25 -0
  37. package/dist/descriptors/browserbase.js +20 -0
  38. package/dist/descriptors/daytona.d.ts +83 -0
  39. package/dist/descriptors/daytona.js +81 -0
  40. package/dist/descriptors/docker.d.ts +12 -0
  41. package/dist/descriptors/docker.js +17 -0
  42. package/dist/descriptors/e2b.d.ts +22 -0
  43. package/dist/descriptors/e2b.js +19 -0
  44. package/dist/descriptors/index.d.ts +256 -0
  45. package/dist/descriptors/index.js +19 -0
  46. package/dist/descriptors/kernel.d.ts +21 -0
  47. package/dist/descriptors/kernel.js +17 -0
  48. package/dist/descriptors/local-chrome.d.ts +17 -0
  49. package/dist/descriptors/local-chrome.js +21 -0
  50. package/dist/descriptors/modal.d.ts +54 -0
  51. package/dist/descriptors/modal.js +48 -0
  52. package/dist/descriptors/orgo.d.ts +99 -0
  53. package/dist/descriptors/orgo.js +49 -0
  54. package/dist/descriptors/phone-harness.d.ts +33 -0
  55. package/dist/descriptors/phone-harness.js +23 -0
  56. package/dist/descriptors/shared.d.ts +7 -0
  57. package/dist/descriptors/shared.js +6 -0
  58. package/dist/desktop.d.ts +4 -4
  59. package/dist/desktop.js +4 -4
  60. package/dist/docker/egress.d.ts +5 -4
  61. package/dist/docker/egress.js +7 -6
  62. package/dist/docker/image.js +17 -15
  63. package/dist/docker/inspect.d.ts +147 -0
  64. package/dist/docker/inspect.js +335 -0
  65. package/dist/docker.d.ts +6 -6
  66. package/dist/docker.js +53 -47
  67. package/dist/drift.d.ts +3 -145
  68. package/dist/drift.js +5 -334
  69. package/dist/e2b.d.ts +2 -8
  70. package/dist/e2b.js +17 -23
  71. package/dist/index.d.ts +9 -12
  72. package/dist/index.js +14 -12
  73. package/dist/isolation.js +2 -2
  74. package/dist/janitor.d.ts +20 -2
  75. package/dist/janitor.js +67 -19
  76. package/dist/kernel.d.ts +19 -29
  77. package/dist/kernel.js +110 -32
  78. package/dist/kinds.d.ts +59 -34
  79. package/dist/kinds.js +19 -117
  80. package/dist/labels.d.ts +20 -0
  81. package/dist/labels.js +62 -1
  82. package/dist/{local.d.ts → local-chrome.d.ts} +8 -9
  83. package/dist/{local.js → local-chrome.js} +26 -19
  84. package/dist/local-supervisor.d.ts +3 -3
  85. package/dist/local-supervisor.js +3 -3
  86. package/dist/modal.d.ts +6 -25
  87. package/dist/modal.js +86 -88
  88. package/dist/mount-archil.d.ts +25 -3
  89. package/dist/mount-archil.js +43 -12
  90. package/dist/orgo-channel.js +16 -13
  91. package/dist/orgo-desktop.d.ts +162 -0
  92. package/dist/orgo-desktop.js +1856 -0
  93. package/dist/orgo-names.d.ts +178 -0
  94. package/dist/orgo-names.js +287 -0
  95. package/dist/orgo.d.ts +34 -20
  96. package/dist/orgo.js +424 -173
  97. package/dist/phone-harness.d.ts +7 -12
  98. package/dist/phone-harness.js +70 -54
  99. package/dist/protocol.d.ts +5 -0
  100. package/dist/provider.d.ts +153 -10
  101. package/dist/provider.js +48 -1
  102. package/dist/providers.d.ts +23 -24
  103. package/dist/providers.js +14 -17
  104. package/dist/result.d.ts +11 -1
  105. package/dist/result.js +11 -0
  106. package/dist/test-connection.js +2 -2
  107. package/package.json +42 -2
package/dist/isolation.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // raise them, holding no CAP_NET_ADMIN, and the read-back here proves it through computerd's probe. Network "none" is
8
8
  // all such a computer takes until a proxy carries open and allowlists out of that namespace.
9
9
  import { DAEMON_IN_COMPUTER } from "./drift.js";
10
- import { fail, ok } from "./result.js";
10
+ import { fail, failAs, ok } from "./result.js";
11
11
  /** The uid:gid the programs of a remote computer run as by default: the box image's agentrun-tool, no sudo. */
12
12
  export const TOOL_USER = "2510:2510";
13
13
  /** Why a remote provider refuses network open or an allowlist, in words. */
@@ -42,7 +42,7 @@ export function probeOwnNetworkDrift(report) {
42
42
  export async function readOwnNetwork(client, timeoutMs, signal) {
43
43
  const ran = await client.call("exec.run", { argv: [DAEMON_IN_COMPUTER, "probe"], timeoutMs }, signal ? { signal } : undefined);
44
44
  if (!ran.ok)
45
- return fail(ran.error.code, `reading the computer's own network back (computerd probe): ${ran.error.message}`);
45
+ return failAs(ran.error, `reading the computer's own network back (computerd probe): ${ran.error.message}`);
46
46
  const out = Buffer.from(ran.value.stdout, "base64").toString("utf8");
47
47
  if (ran.value.exitCode !== 0)
48
48
  return fail("refused", `computerd probe, reading the computer's own network back, exited ${ran.value.exitCode}: ${Buffer.from(ran.value.stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
package/dist/janitor.d.ts CHANGED
@@ -1,10 +1,16 @@
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. */
5
5
  labels?: Record<string, string>;
6
6
  /** The time to compare deadlines with; default now. */
7
7
  now?: Date;
8
+ /**
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.
12
+ */
13
+ ownerGone?: (owner: ComputerOwner) => boolean | Promise<boolean>;
8
14
  signal?: AbortSignal;
9
15
  }
10
16
  export interface Swept {
@@ -22,11 +28,20 @@ export interface Swept {
22
28
  * "janitor"; a caller runs it on a schedule. A computer that cannot be deleted does not stop the sweep: the result is
23
29
  * then an error naming it and what was deleted. A provider with sweepLeftovers then removes, with the same labels and
24
30
  * time, what its computers left behind (Docker: egress proxies and volumes whose computer is gone).
31
+ *
32
+ * An agent's computer (an owner label, or an info the provider marks owned, of a provider that declares persistence: of
33
+ * one that does not, an owner label is a caller's and keeps nothing) is never deleted by a deadline: only when
34
+ * its owner is gone (ownerGone), or once it has been detached for longer than its owner's idle TTL. One whose owner
35
+ * the janitor cannot read is kept. A
36
+ * provider that declares persistence is swept for its agents' computers alone under lifetime "vendor", since no vendor
37
+ * ends them.
25
38
  */
26
- export declare function sweep(provider: ComputerProvider, { labels, now, signal }?: SweepOptions): Promise<Result<Swept>>;
39
+ export declare function sweep(provider: ComputerProvider, { labels, now, ownerGone, signal }?: SweepOptions): Promise<Result<Swept>>;
27
40
  export interface ReleasedOlder {
28
41
  /** The run's computers deleted: each with a lower epoch, and each that carries no epoch it can read. */
29
42
  released: ComputerRef[];
43
+ /** The agents' computers among them, detached instead of deleted: their state kept for the claim to attach. */
44
+ detached: ComputerRef[];
30
45
  /** The run's computers of this very epoch, left as they are. */
31
46
  kept: ComputerRef[];
32
47
  /** Of those released, each whose epoch label was missing or not an epoch, with what was wrong: it could not prove it is current. */
@@ -46,5 +61,8 @@ export interface ReleasedOlder {
46
61
  * released: a partial cleanup is never a success, so a caller revokes nothing and mounts nothing after it. An aborted
47
62
  * call starts no further release and says which ran. It revokes no mount: that is the root helper's, inside the
48
63
  * computer, and a deleted computer holds none.
64
+ *
65
+ * An agent's computer (an owner label, readable or not, or an info marked owned, of a provider that declares
66
+ * persistence) of a lower epoch is detached, never deleted: its state is the agent's, and the new claim attaches it.
49
67
  */
50
68
  export declare function releaseOlder(provider: ComputerProvider, run: string, epoch: number, { signal }?: CallContext): Promise<Result<ReleasedOlder>>;
package/dist/janitor.js CHANGED
@@ -1,9 +1,39 @@
1
1
  // The janitor: ends computers whose deadline has passed, for a provider whose vendor does not end them itself; and, on a
2
2
  // takeover, the run's computers of an older claim.
3
- import { epochOf, epochProblem, RUN_LABEL, runProblem } from "./labels.js";
4
- import { fail, ok } from "./result.js";
3
+ import { epochOf, epochProblem, ownerOf, RUN_LABEL, runProblem } from "./labels.js";
4
+ import { fail, failAs, ok } from "./result.js";
5
5
  /** Clock skew a deadline may carry past now + maxLifetimeMs before it counts as unreadable. */
6
6
  const SKEW_MS = 60_000;
7
+ /** Whether a run's computer's deadline is ahead of at, and readable: no later than at + cap. */
8
+ const alive = (deadline, at, cap) => {
9
+ const time = deadline instanceof Date ? deadline.getTime() : Number.NaN;
10
+ return !Number.isNaN(time) && time > at && time <= at + cap;
11
+ };
12
+ /**
13
+ * Whose a listed computer is. A provider that declares no persistence keeps no agent's computer, so all of its are runs',
14
+ * whatever their labels say: an owner label a caller put on a run's spec never keeps it from the janitor. Of a provider
15
+ * that declares persistence, an agent's: its owner label says so (an owner label that cannot be read too, with no owner
16
+ * known), or the provider marks it owned (its info's owned, with owner when the listing knows it). A run's otherwise.
17
+ */
18
+ function tenureOf(info, persistence) {
19
+ if (persistence === undefined)
20
+ return { agent: false };
21
+ const label = ownerOf(info.labels);
22
+ if (!label.ok)
23
+ return { agent: true };
24
+ if (label.value !== undefined)
25
+ return { agent: true, owner: label.value };
26
+ if (info.owned === true)
27
+ return { agent: true, ...(info.owner === undefined ? {} : { owner: info.owner }) };
28
+ return { agent: false };
29
+ }
30
+ /** Whether an agent's computer ends: its owner is gone, or it has been detached for longer than its idle TTL. */
31
+ async function ownerEnds(info, owner, at, ownerGone) {
32
+ if (ownerGone !== undefined && (await ownerGone(owner)) === true)
33
+ return true;
34
+ const since = info.detachedAt instanceof Date ? info.detachedAt.getTime() : Number.NaN;
35
+ return owner.idleTtlMs !== undefined && !Number.isNaN(since) && at - since >= owner.idleTtlMs;
36
+ }
7
37
  /**
8
38
  * Deletes every computer the provider lists whose deadline has passed, or whose deadline is missing or unreadable
9
39
  * (fail closed); leaves the rest. A deadline more than the provider's maxLifetimeMs past now (with a minute for clock
@@ -11,10 +41,17 @@ const SKEW_MS = 60_000;
11
41
  * "janitor"; a caller runs it on a schedule. A computer that cannot be deleted does not stop the sweep: the result is
12
42
  * then an error naming it and what was deleted. A provider with sweepLeftovers then removes, with the same labels and
13
43
  * time, what its computers left behind (Docker: egress proxies and volumes whose computer is gone).
44
+ *
45
+ * An agent's computer (an owner label, or an info the provider marks owned, of a provider that declares persistence: of
46
+ * one that does not, an owner label is a caller's and keeps nothing) is never deleted by a deadline: only when
47
+ * its owner is gone (ownerGone), or once it has been detached for longer than its owner's idle TTL. One whose owner
48
+ * the janitor cannot read is kept. A
49
+ * provider that declares persistence is swept for its agents' computers alone under lifetime "vendor", since no vendor
50
+ * ends them.
14
51
  */
15
- export async function sweep(provider, { labels = {}, now, signal } = {}) {
16
- const { lifetime, maxLifetimeMs } = provider.capabilities();
17
- if (lifetime !== "janitor") {
52
+ export async function sweep(provider, { labels = {}, now, ownerGone, signal } = {}) {
53
+ const { lifetime, maxLifetimeMs, persistence } = provider.capabilities();
54
+ if (lifetime !== "janitor" && persistence === undefined) {
18
55
  return fail("refused", `the ${provider.id} provider declares lifetime "${lifetime}": its vendor ends its computers itself, so the janitor does not sweep them`);
19
56
  }
20
57
  if (now !== undefined && !(now instanceof Date && !Number.isNaN(now.getTime())))
@@ -31,9 +68,13 @@ export async function sweep(provider, { labels = {}, now, signal } = {}) {
31
68
  const failed = [];
32
69
  let firstError;
33
70
  let kept = 0;
34
- for (const { ref, deadline } of listed.value) {
35
- const time = deadline instanceof Date ? deadline.getTime() : Number.NaN;
36
- if (!Number.isNaN(time) && time > at && time <= at + cap) {
71
+ for (const info of listed.value) {
72
+ const { ref, deadline } = info;
73
+ const tenure = tenureOf(info, persistence);
74
+ // An agent's computer goes by its owner's rules, never a deadline: one whose owner the janitor cannot read is kept.
75
+ // A run's goes by its deadline, and under lifetime "vendor" its vendor ends it.
76
+ const ends = tenure.agent ? tenure.owner !== undefined && (await ownerEnds(info, tenure.owner, at, ownerGone)) : lifetime === "janitor" && !alive(deadline, at, cap);
77
+ if (!ends) {
37
78
  kept++;
38
79
  continue;
39
80
  }
@@ -64,7 +105,7 @@ export async function sweep(provider, { labels = {}, now, signal } = {}) {
64
105
  }
65
106
  if (firstError) {
66
107
  const words = [...(failed.length > 0 ? [`could not delete ${failed.join("; ")}`] : []), ...(leftBehind === undefined ? [] : [`could not remove what its computers left behind: ${leftBehind}`])];
67
- return fail(firstError.code, `the sweep deleted ${deleted.join(", ") || "none"} but ${words.join(", and ")}`);
108
+ return failAs(firstError, `the sweep deleted ${deleted.join(", ") || "none"} but ${words.join(", and ")}`);
68
109
  }
69
110
  return ok({ deleted, kept, ...(leftovers === undefined ? {} : { leftovers }) });
70
111
  }
@@ -79,6 +120,9 @@ export async function sweep(provider, { labels = {}, now, signal } = {}) {
79
120
  * released: a partial cleanup is never a success, so a caller revokes nothing and mounts nothing after it. An aborted
80
121
  * call starts no further release and says which ran. It revokes no mount: that is the root helper's, inside the
81
122
  * computer, and a deleted computer holds none.
123
+ *
124
+ * An agent's computer (an owner label, readable or not, or an info marked owned, of a provider that declares
125
+ * persistence) of a lower epoch is detached, never deleted: its state is the agent's, and the new claim attaches it.
82
126
  */
83
127
  export async function releaseOlder(provider, run, epoch, { signal } = {}) {
84
128
  const problem = runProblem(run) ?? epochProblem(epoch);
@@ -89,21 +133,24 @@ export async function releaseOlder(provider, run, epoch, { signal } = {}) {
89
133
  return fail("aborted", `${what} was aborted before it began`);
90
134
  const listed = await provider.list({ [RUN_LABEL]: run }, { signal });
91
135
  if (!listed.ok)
92
- return fail(listed.error.code, `could not list run ${JSON.stringify(run)}'s computers: ${listed.error.message}`);
136
+ return failAs(listed.error, `could not list run ${JSON.stringify(run)}'s computers: ${listed.error.message}`);
137
+ const { persistence } = provider.capabilities();
93
138
  const older = [];
94
139
  const kept = [];
95
140
  const unproven = [];
96
141
  const newer = [];
97
- for (const { ref, labels } of listed.value) {
142
+ for (const info of listed.value) {
143
+ const { ref, labels } = info;
98
144
  if (labels?.[RUN_LABEL] !== run)
99
145
  continue;
100
146
  const read = epochOf(labels);
147
+ const owned = tenureOf(info, persistence).agent;
101
148
  if (!read.ok) {
102
- older.push({ ref });
149
+ older.push({ ref, owned });
103
150
  unproven.push({ ref, problem: read.error.message });
104
151
  }
105
152
  else if (read.value < epoch)
106
- older.push({ ref, epoch: read.value });
153
+ older.push({ ref, epoch: read.value, owned });
107
154
  else if (read.value === epoch)
108
155
  kept.push(ref);
109
156
  else
@@ -113,23 +160,24 @@ export async function releaseOlder(provider, run, epoch, { signal } = {}) {
113
160
  return fail("refused", `fenced: run ${JSON.stringify(run)} has ${newer.join(", ")}, above this claim's epoch ${epoch}; a later claim holds the run, so nothing was released`);
114
161
  }
115
162
  const released = [];
163
+ const detached = [];
116
164
  const failed = [];
117
165
  let firstError;
118
- const done = () => `it released ${released.map((ref) => ref.name).join(", ") || "none"}${failed.length > 0 ? `, and could not release ${failed.join("; ")}` : ""}`;
119
- for (const [at, { ref, epoch: was }] of older.entries()) {
166
+ const done = () => `it released ${released.map((ref) => ref.name).join(", ") || "none"}${detached.length > 0 ? `, detached the agents' ${detached.map((ref) => ref.name).join(", ")}` : ""}${failed.length > 0 ? `, and could not release ${failed.join("; ")}` : ""}`;
167
+ for (const [at, { ref, epoch: was, owned }] of older.entries()) {
120
168
  if (signal?.aborted) {
121
169
  const left = older.slice(at).map((one) => one.ref.name);
122
170
  return fail("aborted", `${what} was aborted: ${done()}; it did not start ${left.join(", ")}`);
123
171
  }
124
- const result = await provider.release(ref, "delete");
172
+ const result = await provider.release(ref, owned ? "detach" : "delete");
125
173
  if (result.ok)
126
- released.push(ref);
174
+ (owned ? detached : released).push(ref);
127
175
  else {
128
176
  firstError ??= result.error;
129
177
  failed.push(`${ref.name} (${was === undefined ? "no epoch" : `epoch ${was}`}): ${result.error.message}`);
130
178
  }
131
179
  }
132
180
  if (firstError)
133
- return fail(firstError.code, `${what} is incomplete: ${done()}`);
134
- return ok({ released, kept, unproven });
181
+ return failAs(firstError, `${what} is incomplete: ${done()}`);
182
+ return ok({ released, detached, kept, unproven });
135
183
  }
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, CallContext, ComputerCapabilities, ComputerConnection, ComputerInfo, ComputerProvider, ComputerRef, ComputerSpec, CreatedComputer, NetworkForm, NetworkPolicy, NetworkSpec, Refusal } from "./provider.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";
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. */
@@ -11,9 +11,7 @@ export declare const KERNEL_MIN_LIFETIME_MS = 10000;
11
11
  export declare const KERNEL_MAX_LIFETIME_MS = 259200000;
12
12
  /** A browser takes no mount. */
13
13
  export declare const MOUNT: readonly MountKind[];
14
- /** The network a Kernel browser runs on: Kernel's own, open; it cannot be closed or narrowed. */
15
- export declare const NETWORK: readonly NetworkForm[];
16
- /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
14
+ /** The one configuration it offers, its descriptor's: a browser with a CDP target and a live view. */
17
15
  export declare const CAPABILITIES: readonly KindCapabilities[];
18
16
  /** A browser as Kernel answers it; only what the provider reads. */
19
17
  export interface KernelBrowser {
@@ -28,13 +26,9 @@ export interface KernelBrowser {
28
26
  /**
29
27
  * One Kernel request, never retried: a create sent twice would be a second paid browser. It answers 404 as a reply,
30
28
  * and throws on any other failure, with the HTTP status as `status`; the provider returns that as a result whose hidden
31
- * cause is the thrown error, so a host that gave its own request rethrows its own error.
29
+ * cause is the thrown error.
32
30
  */
33
- export type KernelRequest = (method: string, route: string, init?: {
34
- body?: unknown;
35
- query?: URLSearchParams;
36
- signal?: AbortSignal;
37
- }) => Promise<RestReply>;
31
+ export type KernelRequest = (method: string, route: string, init?: RestInit) => Promise<RestReply>;
38
32
  /** Kernel's REST API over fetch: the default request. */
39
33
  export declare function kernelRest({ apiKey, apiUrl, fetch: fetcher }: {
40
34
  apiKey: string;
@@ -42,41 +36,38 @@ export declare function kernelRest({ apiKey, apiUrl, fetch: fetcher }: {
42
36
  fetch?: typeof fetch;
43
37
  }): KernelRequest;
44
38
  export interface KernelProviderOptions {
45
- /** 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. */
46
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. */
47
42
  apiUrl?: string;
43
+ /** The host's own variables its descriptor declares (hostEnv): KERNEL_BASE_URL alone. */
44
+ env?: Readonly<Record<string, string | undefined>>;
48
45
  fetch?: typeof fetch;
49
- /** One Kernel request, a host's own; default the REST one. */
50
- request?: KernelRequest;
51
- /** Where the signed CDP URLs are held; default a Map of this provider's own. */
52
- urls?: UrlStore;
53
- /** Where the live views' URLs are held; default a Map of this provider's own. */
54
- liveUrls?: UrlStore;
55
46
  confirm?: ReleaseConfirm;
56
47
  sleep?: (ms: number) => Promise<void>;
57
48
  }
58
- /** What a host may add to a browser's create body: Kernel's own fields (headless, stealth, viewport, a profile, extensions). */
59
- export type KernelBrowserSettings = Record<string, unknown>;
60
49
  /** Computers that are Kernel browsers. */
61
- export declare class KernelProvider implements ComputerProvider {
50
+ export declare class KernelProvider implements ComputerProvider, BrowserComputerProvider {
62
51
  #private;
63
52
  readonly id = "kernel";
64
53
  readonly version: string;
65
- 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);
66
56
  /**
67
57
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
68
58
  * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
69
- * 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.
70
61
  */
71
62
  capabilities(): ComputerCapabilities;
72
63
  check(spec: ComputerSpec): Refusal[];
73
64
  /**
74
65
  * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
75
- * 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.
76
68
  */
77
- create(spec: ComputerSpec, { signal, settings }?: {
69
+ create(spec: ComputerSpec, { signal }?: {
78
70
  signal?: AbortSignal;
79
- settings?: KernelBrowserSettings;
80
71
  }): Promise<Result<CreatedComputer>>;
81
72
  /**
82
73
  * Settings' test: one page of the organization's active browsers (GET /browsers?status=active), which makes nothing.
@@ -100,15 +91,14 @@ export declare class KernelProvider implements ComputerProvider {
100
91
  */
101
92
  connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
102
93
  /** Deletes the browser and waits until Kernel reads it as gone; one already deleted or unknown is released. */
103
- release(ref: ComputerRef, how: "stop" | "delete", { signal }?: CallContext): Promise<Result<void>>;
94
+ release(ref: ComputerRef, how: ReleaseHow, { signal }?: CallContext): Promise<Result<void>>;
104
95
  /** The browser's live view, which takes input: a view-only one is refused, never handed over as one. */
105
96
  stream(ref: ComputerRef, options?: {
106
97
  viewOnly?: boolean;
107
98
  }, { signal }?: CallContext): Promise<Result<BrowserStream>>;
108
99
  }
109
100
  /**
110
- * The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
111
- * host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
101
+ * 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.
112
102
  */
113
103
  export declare function create(options: KernelProviderOptions): KernelProvider;
114
104
  /** 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,25 @@
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
- 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";
21
+ import { KERNEL } from "./descriptors/kernel.js";
22
+ import { BROWSER_IMAGE } from "./descriptors/shared.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";
24
+ import { runLifetimeMs, } from "./provider.js";
25
+ import { failFor, ok, vendorFail } from "./result.js";
17
26
  import { connectionError } from "./test-connection.js";
27
+ /** This module's failures: one with code vendor names Kernel. */
28
+ const fail = failFor("kernel");
18
29
  const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
19
30
  const NAME = "Kernel";
20
31
  export const KERNEL_API_URL = "https://api.onkernel.com";
@@ -27,54 +38,59 @@ export const KERNEL_MAX_LIFETIME_MS = 259_200_000;
27
38
  /** The most pages a list reads before it fails rather than run on. */
28
39
  const MAX_PAGES = 100;
29
40
  /** A browser takes no mount. */
30
- export const MOUNT = [];
31
- /** The network a Kernel browser runs on: Kernel's own, open; it cannot be closed or narrowed. */
32
- export const NETWORK = ["open"];
33
- /** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
34
- export const CAPABILITIES = [{ kind: "browser", groups: ["cdp", "stream"] }];
41
+ export const MOUNT = KERNEL.mounts;
42
+ /** The one configuration it offers, its descriptor's: a browser with a CDP target and a live view. */
43
+ export const CAPABILITIES = KERNEL.capabilities;
35
44
  /** Kernel's REST API over fetch: the default request. */
36
45
  export function kernelRest({ apiKey, apiUrl = KERNEL_API_URL, fetch: fetcher = fetch }) {
37
46
  const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Kernel API URL"), headers: { Authorization: `Bearer ${apiKey}` } };
38
47
  return (method, route, init = {}) => restCall(o, method, route, `${method} ${callName(route)}`, init);
39
48
  }
40
- /** A route as a failure names it: ids out, so no session id reads as a secret's neighbour. */
41
- 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}");
42
51
  const text = (value) => (typeof value === "string" ? value.trim() : "");
43
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 });
44
56
  /** Computers that are Kernel browsers. */
45
57
  export class KernelProvider {
46
58
  id = "kernel";
47
59
  version = VERSION;
60
+ profiles = { create: (context) => this.#createProfile(context), remove: (pointer, context) => this.#removeProfile(pointer, context) };
48
61
  #request;
49
62
  #urls;
50
63
  #live;
51
64
  #confirm;
52
65
  #sleep;
53
- constructor({ apiKey, apiUrl, fetch: fetcher, request, urls, liveUrls, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
54
- if (request === undefined && (typeof apiKey !== "string" || apiKey === ""))
55
- 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");
56
- this.#request = request ?? kernelRest({ apiKey: apiKey, ...(apiUrl ? { apiUrl } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
57
- this.#urls = urls ?? memoryUrls();
58
- 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();
59
73
  this.#confirm = confirm;
60
74
  this.#sleep = sleep;
61
75
  }
62
76
  /**
63
77
  * A browser: Kernel ends a browser after its idle timeout (lifetime vendor), at most 72 h; it reaches the open web;
64
78
  * each browser is its own VM. Kernel's replays and file APIs are not wired here, so recordings and downloads are not
65
- * 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.
66
81
  */
67
82
  capabilities() {
68
83
  return {
69
84
  kind: "browser",
70
85
  lifetime: "vendor",
71
- network: [...NETWORK],
86
+ network: [...KERNEL.network],
72
87
  isolation: "vm",
73
88
  os: "linux",
74
89
  daemon: "none",
75
90
  groups: [...CAPABILITIES[0].groups],
76
91
  maxLifetimeMs: KERNEL_MAX_LIFETIME_MS,
77
92
  release: ["delete"],
93
+ browser: KERNEL_BROWSER(),
78
94
  };
79
95
  }
80
96
  check(spec) {
@@ -82,16 +98,30 @@ export class KernelProvider {
82
98
  }
83
99
  /**
84
100
  * Makes a browser at most once, with the lifetime as its idle timeout in whole seconds and the labels as its tags.
85
- * 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.
86
103
  */
87
- async create(spec, { signal, settings = {} } = {}) {
104
+ async create(spec, { signal } = {}) {
88
105
  const refusals = this.check(spec);
89
106
  if (refusals.length > 0)
90
107
  return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
91
108
  if (signal?.aborted)
92
109
  return fail("aborted", "create was aborted before Kernel was called");
110
+ const options = spec.browser;
111
+ if (options?.profile !== undefined) {
112
+ const ensured = await this.#ensureProfile(options.profile.pointer, signal);
113
+ if (!ensured.ok)
114
+ return causedFail(ensured.error.code, `the profile could not be made ready: ${ensured.error.message}; no browser was made`, causeOf(ensured), "kernel");
115
+ }
93
116
  const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
94
- const body = { ...settings, timeout_seconds: Math.ceil(spec.lifetimeMs / 1000), tags: written };
117
+ const body = {
118
+ ...(options !== undefined ? { stealth: false } : {}),
119
+ ...(options?.viewport ? { viewport: { width: options.viewport.width, height: options.viewport.height } } : {}),
120
+ ...(options?.headless !== undefined ? { headless: options.headless } : {}),
121
+ ...(options?.profile ? { profile: { name: options.profile.pointer, save_changes: options.profile.save } } : {}),
122
+ timeout_seconds: Math.ceil(runLifetimeMs(spec) / 1000),
123
+ tags: written,
124
+ };
95
125
  let made;
96
126
  try {
97
127
  made = await this.#request("POST", "/browsers", { body, ...(signal ? { signal } : {}) });
@@ -101,7 +131,7 @@ export class KernelProvider {
101
131
  if (failed.ok || !createUncertain(error))
102
132
  return failed;
103
133
  // The browser may have been made though its answer never came: found by its create label, never made again.
104
- return vendorFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed));
134
+ return causedFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed), "kernel");
105
135
  }
106
136
  const browser = (made.json ?? {});
107
137
  const id = text(browser.session_id);
@@ -116,7 +146,7 @@ export class KernelProvider {
116
146
  if (unusable !== undefined) {
117
147
  // The browser is made and billed until its idle timeout: deleted here, not left to a later sweep.
118
148
  const released = await this.release(refOf(id), "delete");
119
- 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`}`);
149
+ return vendorFail("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`}`);
120
150
  }
121
151
  this.#urls.set(id, url);
122
152
  const live = text(browser.browser_live_view_url);
@@ -124,6 +154,55 @@ export class KernelProvider {
124
154
  this.#live.set(id, live);
125
155
  return ok(refOf(id));
126
156
  }
157
+ /** A browser names only a profile Kernel knows: made if it is not (GET, then POST); a 409 is another process making it. */
158
+ async #ensureProfile(name, signal) {
159
+ try {
160
+ const found = await this.#request("GET", `/profiles/${encodeURIComponent(name)}`, signal ? { signal } : {});
161
+ if (found.status !== 404)
162
+ return ok(undefined);
163
+ }
164
+ catch (error) {
165
+ return vendorFailure("kernel", NAME, "GET /profiles/{name}", error);
166
+ }
167
+ try {
168
+ const made = await this.#request("POST", "/profiles", { body: { name }, ...(signal ? { signal } : {}) });
169
+ if (made.status === 404)
170
+ return vendorFailure("kernel", NAME, "POST /profiles", new BrowserVendorError(NAME, "POST /profiles", 404));
171
+ return ok(undefined);
172
+ }
173
+ catch (error) {
174
+ return statusOf(error) === 409 ? ok(undefined) : vendorFailure("kernel", NAME, "POST /profiles", error);
175
+ }
176
+ }
177
+ /** A new profile under a random name, which is its pointer: one POST /profiles, never retried. */
178
+ async #createProfile({ signal } = {}) {
179
+ const name = `agentrun-${randomBytes(12).toString("hex")}`;
180
+ const call = "POST /profiles";
181
+ let made;
182
+ try {
183
+ made = await this.#request("POST", "/profiles", { body: { name }, ...(signal ? { signal } : {}) });
184
+ }
185
+ catch (error) {
186
+ return vendorFailure("kernel", NAME, call, error);
187
+ }
188
+ if (made.status === 404)
189
+ return vendorFailure("kernel", NAME, call, new BrowserVendorError(NAME, call, 404));
190
+ if (made.json?.name !== name)
191
+ return vendorFail("kernel", `Kernel ${call} answered ${made.status} with another profile's name than the one asked for`);
192
+ return ok(name);
193
+ }
194
+ /** Deletes the profile; one Kernel no longer knows is removed. The words never carry the pointer. */
195
+ async #removeProfile(pointer, { signal } = {}) {
196
+ if (!pointerOk(pointer))
197
+ return fail("invalid", "a profile's pointer is a plain token, as profiles.create gave it");
198
+ try {
199
+ await this.#request("DELETE", `/profiles/${encodeURIComponent(pointer)}`, signal ? { signal } : {});
200
+ return ok(undefined);
201
+ }
202
+ catch (error) {
203
+ return vendorFailure("kernel", NAME, "DELETE /profiles/{name}", error);
204
+ }
205
+ }
127
206
  /**
128
207
  * The browsers a lost create made, released: what recoverCreate says of them. They are found as list finds any, by the
129
208
  * tags the create wrote (its create label first, so the query names it, then the run's), through #browsers: another
@@ -155,9 +234,9 @@ export class KernelProvider {
155
234
  return fail(reached ? connectionError(failed.error).code : "unreachable", failed.error.message);
156
235
  }
157
236
  if (page.status === 404)
158
- return fail("kernel", `Kernel ${call} answered 404: the API URL is not Kernel's`);
237
+ return vendorFail("kernel", `Kernel ${call} answered 404: the API URL is not Kernel's`);
159
238
  if (!Array.isArray(page.json))
160
- return fail("kernel", `Kernel ${call} answered ${page.status} (not_a_list)`);
239
+ return vendorFail("kernel", `Kernel ${call} answered ${page.status} (not_a_list)`);
161
240
  const n = page.json.length;
162
241
  const more = page.headers.get("x-has-more") === "true" ? " or more" : "";
163
242
  return ok({ detail: `Kernel answered: ${n}${more} active ${n === 1 && more === "" ? "browser" : "browsers"} in the organization` });
@@ -252,10 +331,10 @@ export class KernelProvider {
252
331
  return ok(found);
253
332
  const next = Number(page.headers.get("x-next-offset"));
254
333
  if (!Number.isInteger(next) || next <= offset)
255
- return fail("kernel", "Kernel reported more browsers without the next page's offset");
334
+ return vendorFail("kernel", "Kernel reported more browsers without the next page's offset");
256
335
  offset = next;
257
336
  }
258
- return fail("kernel", `Kernel kept answering more pages of browsers past ${MAX_PAGES}`);
337
+ return vendorFail("kernel", `Kernel kept answering more pages of browsers past ${MAX_PAGES}`);
259
338
  }
260
339
  async list(labels, { signal } = {}) {
261
340
  const found = await this.#browsers(labels, signal);
@@ -300,7 +379,7 @@ export class KernelProvider {
300
379
  // Whatever held it (create, a read, a host's url store), a URL a driver would dial is wss: on Kernel's own domain.
301
380
  const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
302
381
  if (unusable !== undefined)
303
- return fail("kernel", `the Kernel browser ${id} is not handed over: ${unusable}`);
382
+ return vendorFail("kernel", `the Kernel browser ${id} is not handed over: ${unusable}`);
304
383
  this.#urls.set(id, url);
305
384
  const hello = browserHello(VERSION, this.capabilities().groups);
306
385
  const client = browserClient(hello, (signal) => this.#alive(id, signal));
@@ -350,8 +429,7 @@ export class KernelProvider {
350
429
  }
351
430
  }
352
431
  /**
353
- * The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
354
- * host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
432
+ * 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.
355
433
  */
356
434
  export function create(options) {
357
435
  return new KernelProvider(options ?? {});