@parcha/agentrun-computer 0.0.0-placeholder → 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.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +2400 -1
- package/box/Dockerfile +69 -0
- package/box/agentrun-archil +168 -0
- package/box/build-daytona.py +26 -0
- package/box/build-e2b.mjs +32 -0
- package/box/build-modal.py +17 -0
- package/dist/actions.d.ts +18 -0
- package/dist/actions.js +139 -0
- package/dist/browser.d.ts +151 -0
- package/dist/browser.js +305 -0
- package/dist/browserbase.d.ts +139 -0
- package/dist/browserbase.js +408 -0
- package/dist/child.d.ts +40 -0
- package/dist/child.js +127 -0
- package/dist/client.d.ts +22 -0
- package/dist/client.js +136 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/archil.d.ts +68 -0
- package/dist/conformance/archil.js +152 -0
- package/dist/conformance/browserbase.d.ts +35 -0
- package/dist/conformance/browserbase.js +45 -0
- package/dist/conformance/cases/apps.d.ts +2 -0
- package/dist/conformance/cases/apps.js +155 -0
- package/dist/conformance/cases/browser.d.ts +4 -0
- package/dist/conformance/cases/browser.js +105 -0
- package/dist/conformance/cases/drift.d.ts +2 -0
- package/dist/conformance/cases/drift.js +64 -0
- package/dist/conformance/cases/exec.d.ts +2 -0
- package/dist/conformance/cases/exec.js +125 -0
- package/dist/conformance/cases/files.d.ts +2 -0
- package/dist/conformance/cases/files.js +294 -0
- package/dist/conformance/cases/health.d.ts +2 -0
- package/dist/conformance/cases/health.js +71 -0
- package/dist/conformance/cases/index.d.ts +9 -0
- package/dist/conformance/cases/index.js +37 -0
- package/dist/conformance/cases/input.d.ts +12 -0
- package/dist/conformance/cases/input.js +109 -0
- package/dist/conformance/cases/isolation.d.ts +21 -0
- package/dist/conformance/cases/isolation.js +92 -0
- package/dist/conformance/cases/lifetime.d.ts +2 -0
- package/dist/conformance/cases/lifetime.js +64 -0
- package/dist/conformance/cases/mount.d.ts +2 -0
- package/dist/conformance/cases/mount.js +252 -0
- package/dist/conformance/cases/process.d.ts +2 -0
- package/dist/conformance/cases/process.js +240 -0
- package/dist/conformance/cases/provider.d.ts +2 -0
- package/dist/conformance/cases/provider.js +302 -0
- package/dist/conformance/cases/screen.d.ts +9 -0
- package/dist/conformance/cases/screen.js +230 -0
- package/dist/conformance/cases/settings.d.ts +57 -0
- package/dist/conformance/cases/settings.js +142 -0
- package/dist/conformance/cases/touch.d.ts +2 -0
- package/dist/conformance/cases/touch.js +117 -0
- package/dist/conformance/cases/util.d.ts +7 -0
- package/dist/conformance/cases/util.js +8 -0
- package/dist/conformance/cdp.d.ts +13 -0
- package/dist/conformance/cdp.js +88 -0
- package/dist/conformance/cli.d.ts +29 -0
- package/dist/conformance/cli.js +231 -0
- package/dist/conformance/daytona-sweep.d.ts +18 -0
- package/dist/conformance/daytona-sweep.js +118 -0
- package/dist/conformance/daytona.d.ts +83 -0
- package/dist/conformance/daytona.js +107 -0
- package/dist/conformance/docker.d.ts +38 -0
- package/dist/conformance/docker.js +70 -0
- package/dist/conformance/drift-daemon.d.ts +8 -0
- package/dist/conformance/drift-daemon.js +41 -0
- package/dist/conformance/e2b-diagnose.d.ts +16 -0
- package/dist/conformance/e2b-diagnose.js +61 -0
- package/dist/conformance/e2b-sweep.d.ts +18 -0
- package/dist/conformance/e2b-sweep.js +125 -0
- package/dist/conformance/e2b.d.ts +74 -0
- package/dist/conformance/e2b.js +111 -0
- package/dist/conformance/fixture.d.ts +65 -0
- package/dist/conformance/fixture.js +98 -0
- package/dist/conformance/index.d.ts +8 -0
- package/dist/conformance/index.js +8 -0
- package/dist/conformance/kernel.d.ts +31 -0
- package/dist/conformance/kernel.js +40 -0
- package/dist/conformance/kind.d.ts +23 -0
- package/dist/conformance/kind.js +58 -0
- package/dist/conformance/modal-sweep.d.ts +22 -0
- package/dist/conformance/modal-sweep.js +190 -0
- package/dist/conformance/modal.d.ts +69 -0
- package/dist/conformance/modal.js +76 -0
- package/dist/conformance/orgo.d.ts +41 -0
- package/dist/conformance/orgo.js +69 -0
- package/dist/conformance/phone-harness.d.ts +61 -0
- package/dist/conformance/phone-harness.js +241 -0
- package/dist/conformance/png.d.ts +16 -0
- package/dist/conformance/png.js +132 -0
- package/dist/conformance/report.d.ts +2 -0
- package/dist/conformance/report.js +86 -0
- package/dist/conformance/runner.d.ts +11 -0
- package/dist/conformance/runner.js +585 -0
- package/dist/conformance/tar.d.ts +13 -0
- package/dist/conformance/tar.js +105 -0
- package/dist/conformance/types.d.ts +257 -0
- package/dist/conformance/types.js +24 -0
- package/dist/daemon-copy.d.ts +40 -0
- package/dist/daemon-copy.js +259 -0
- package/dist/daytona.d.ts +178 -0
- package/dist/daytona.js +1484 -0
- package/dist/desktop.d.ts +24 -0
- package/dist/desktop.js +68 -0
- package/dist/docker/egress-main.d.ts +1 -0
- package/dist/docker/egress-main.js +68 -0
- package/dist/docker/egress-proxy.d.ts +53 -0
- package/dist/docker/egress-proxy.js +450 -0
- package/dist/docker/egress-table.d.ts +39 -0
- package/dist/docker/egress-table.js +197 -0
- package/dist/docker/egress.d.ts +109 -0
- package/dist/docker/egress.js +318 -0
- package/dist/docker/image.d.ts +49 -0
- package/dist/docker/image.js +302 -0
- package/dist/docker/stage.d.ts +21 -0
- package/dist/docker/stage.js +290 -0
- package/dist/docker/volume.d.ts +24 -0
- package/dist/docker/volume.js +67 -0
- package/dist/docker.d.ts +150 -0
- package/dist/docker.js +1200 -0
- package/dist/drift.d.ts +200 -0
- package/dist/drift.js +416 -0
- package/dist/e2b.d.ts +335 -0
- package/dist/e2b.js +1515 -0
- package/dist/entry.d.ts +2 -0
- package/dist/entry.js +24 -0
- package/dist/files.d.ts +50 -0
- package/dist/files.js +208 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +26 -0
- package/dist/isolation.d.ts +29 -0
- package/dist/isolation.js +71 -0
- package/dist/janitor.d.ts +50 -0
- package/dist/janitor.js +135 -0
- package/dist/kernel.d.ts +113 -0
- package/dist/kernel.js +358 -0
- package/dist/kinds.d.ts +79 -0
- package/dist/kinds.js +133 -0
- package/dist/labels.d.ts +23 -0
- package/dist/labels.js +50 -0
- package/dist/modal.d.ts +302 -0
- package/dist/modal.js +1374 -0
- package/dist/mount-archil.d.ts +164 -0
- package/dist/mount-archil.js +471 -0
- package/dist/mount.d.ts +57 -0
- package/dist/mount.js +104 -0
- package/dist/orgo-channel.d.ts +96 -0
- package/dist/orgo-channel.js +391 -0
- package/dist/orgo.d.ts +139 -0
- package/dist/orgo.js +1006 -0
- package/dist/phone-harness.d.ts +185 -0
- package/dist/phone-harness.js +1420 -0
- package/dist/processes.d.ts +24 -0
- package/dist/processes.js +40 -0
- package/dist/protocol.d.ts +729 -0
- package/dist/protocol.js +54 -0
- package/dist/provider.d.ts +245 -0
- package/dist/provider.js +37 -0
- package/dist/providers.d.ts +68 -0
- package/dist/providers.js +25 -0
- package/dist/result.d.ts +15 -0
- package/dist/result.js +2 -0
- package/dist/screen-watch.d.ts +150 -0
- package/dist/screen-watch.js +490 -0
- package/dist/test-connection.d.ts +17 -0
- package/dist/test-connection.js +26 -0
- package/dist/wait.d.ts +23 -0
- package/dist/wait.js +65 -0
- package/package.json +64 -1
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// Browserbase as a computer of kind browser: each computer is a Browserbase session, over Browserbase's v1 REST API with
|
|
2
|
+
// fetch (no SDK), or through a BrowserbaseApi a host gives (pi-browser's SDK client). Labels ride the session's own
|
|
3
|
+
// userMetadata; attach and list find a session by them; connect hands over the session's signed connectUrl, which a
|
|
4
|
+
// driver dials; stream is its live view (the debugger's fullscreen URL). Both URLs are secrets: they stay in memory and
|
|
5
|
+
// never reach a ref, a list, an error's words or a report.
|
|
6
|
+
//
|
|
7
|
+
// Calls: POST /v1/sessions (create, with timeout, keepAlive and userMetadata), GET /v1/sessions/{id} (read),
|
|
8
|
+
// GET /v1/sessions?status=&q= (list; q is user_metadata['key']:'value', and a status is always given, since q alone made
|
|
9
|
+
// Browserbase answer 504 after 75 s), POST /v1/sessions/{id} with status REQUEST_RELEASE (release), and
|
|
10
|
+
// GET /v1/sessions/{id}/debug (the live view). The key is the X-BB-API-Key header.
|
|
11
|
+
//
|
|
12
|
+
// A label's key is not its metadata key: Browserbase refuses a dot in a userMetadata key (POST /v1/sessions answered 400
|
|
13
|
+
// "Key is not a valid metadata key: agentrun.conformance", found live on 11-08), and the protocol's labels are dotted
|
|
14
|
+
// (agentrun.run, agentrun.epoch). metadataKey() writes each "." as "_", and labelKey() reads it back. check() takes a
|
|
15
|
+
// label key of letters, digits and dots alone, so no label key holds an "_" and the mapping is one to one; a value with
|
|
16
|
+
// ' or \ is refused too, since list's query quotes it.
|
|
17
|
+
import { readFileSync } from "node:fs";
|
|
18
|
+
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";
|
|
19
|
+
import { fail, ok } from "./result.js";
|
|
20
|
+
import { connectionError } from "./test-connection.js";
|
|
21
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
22
|
+
const NAME = "Browserbase";
|
|
23
|
+
export const BROWSERBASE_API_URL = "https://api.browserbase.com";
|
|
24
|
+
/** The domain a Browserbase CDP URL is on (wss://connect.browserbase.com, read live 11-08): cdpUrlProblem holds it there. */
|
|
25
|
+
export const BROWSERBASE_CDP_DOMAIN = "browserbase.com";
|
|
26
|
+
const CDP_DOMAIN = BROWSERBASE_CDP_DOMAIN;
|
|
27
|
+
/** Browserbase's longest session: a timeout of 21,600 s. */
|
|
28
|
+
export const BROWSERBASE_MAX_LIFETIME_MS = 6 * 60 * 60_000;
|
|
29
|
+
/** Browserbase's shortest session timeout: 60 s. */
|
|
30
|
+
export const BROWSERBASE_MIN_LIFETIME_MS = 60_000;
|
|
31
|
+
/** The statuses of a session that runs (PENDING bills once it starts); any other has ended. */
|
|
32
|
+
const LIVE = new Set(["RUNNING", "PENDING"]);
|
|
33
|
+
/** A label key Browserbase's metadata can carry once its dots are underscores: letters, digits and dots, so the mapping is one to one. */
|
|
34
|
+
const LABEL_KEY = /^[A-Za-z0-9.]+$/;
|
|
35
|
+
/** The userMetadata key a label key is written under: each "." as "_", since Browserbase refuses a dot there. */
|
|
36
|
+
export const metadataKey = (labelKey) => labelKey.replaceAll(".", "_");
|
|
37
|
+
/** The label key a userMetadata key reads back as: each "_" as ".". */
|
|
38
|
+
export const labelKey = (metadataKey) => metadataKey.replaceAll("_", ".");
|
|
39
|
+
/** Labels as userMetadata. */
|
|
40
|
+
const toMetadata = (labels = {}) => Object.fromEntries(Object.entries(labels).map(([key, value]) => [metadataKey(key), value]));
|
|
41
|
+
/** userMetadata as labels: its string entries, each key read back, the create label among them (what a match reads). */
|
|
42
|
+
const metadataLabels = (held) => Object.fromEntries(Object.entries(labelsOf(held)).map(([key, value]) => [labelKey(key), value]));
|
|
43
|
+
/** userMetadata as the labels list and attach show: without the provider's create label. */
|
|
44
|
+
const fromMetadata = (held) => withoutCreateLabel(metadataLabels(held));
|
|
45
|
+
/** Why labels cannot ride a Browserbase session's userMetadata, in words naming the label; undefined when they can. */
|
|
46
|
+
export function browserbaseLabelsProblem(labels) {
|
|
47
|
+
const problem = labelsProblem(labels);
|
|
48
|
+
if (problem)
|
|
49
|
+
return problem;
|
|
50
|
+
for (const [key, value] of Object.entries(labels)) {
|
|
51
|
+
if (!LABEL_KEY.test(key))
|
|
52
|
+
return `a Browserbase label's key is letters, digits and dots (each dot is written as "_" in the session's metadata, which refuses a dot), not ${JSON.stringify(key)}`;
|
|
53
|
+
if (/['\\]/.test(value))
|
|
54
|
+
return `the label ${JSON.stringify(key)} holds a quote or a backslash, which list's query to Browserbase cannot carry`;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
/** A browser takes no mount. */
|
|
59
|
+
export const MOUNT = [];
|
|
60
|
+
/** The one configuration it offers, the kind registry's entry (kinds.ts): a browser with a CDP target and a live view. */
|
|
61
|
+
export const CAPABILITIES = [{ kind: "browser", groups: ["cdp", "stream"] }];
|
|
62
|
+
/** Browserbase's v1 REST API over fetch: the default api. */
|
|
63
|
+
export function browserbaseRest({ apiKey, apiUrl = BROWSERBASE_API_URL, projectId, fetch: fetcher = fetch }) {
|
|
64
|
+
const o = { vendor: NAME, fetch: fetcher, base: httpsBase(apiUrl, "the Browserbase API URL"), headers: { "X-BB-API-Key": apiKey } };
|
|
65
|
+
const session = (call, json, status) => {
|
|
66
|
+
if (typeof json?.id !== "string")
|
|
67
|
+
throw new BrowserVendorError(NAME, call, status, "not_a_session");
|
|
68
|
+
return json;
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
async create(body, signal) {
|
|
72
|
+
const call = "POST /v1/sessions";
|
|
73
|
+
const answer = await restCall(o, "POST", "/v1/sessions", call, { body, ...(signal ? { signal } : {}) });
|
|
74
|
+
if (answer.status === 404)
|
|
75
|
+
throw new BrowserVendorError(NAME, call, 404);
|
|
76
|
+
return session(call, answer.json, answer.status);
|
|
77
|
+
},
|
|
78
|
+
async retrieve(id, signal) {
|
|
79
|
+
const call = "GET /v1/sessions/{id}";
|
|
80
|
+
const answer = await restCall(o, "GET", `/v1/sessions/${encodeURIComponent(id)}`, call, signal ? { signal } : {});
|
|
81
|
+
return answer.status === 404 ? undefined : session(call, answer.json, answer.status);
|
|
82
|
+
},
|
|
83
|
+
async list(query, signal) {
|
|
84
|
+
const call = "GET /v1/sessions";
|
|
85
|
+
const params = new URLSearchParams({ status: query.status, ...(query.q === undefined ? {} : { q: query.q }) });
|
|
86
|
+
const answer = await restCall(o, "GET", "/v1/sessions", call, { query: params, ...(signal ? { signal } : {}) });
|
|
87
|
+
// A list is never "not found": a 404 is a wrong base URL, and an empty answer would hide every session.
|
|
88
|
+
if (answer.status === 404)
|
|
89
|
+
throw new BrowserVendorError(NAME, call, 404);
|
|
90
|
+
if (!Array.isArray(answer.json))
|
|
91
|
+
throw new BrowserVendorError(NAME, call, answer.status, "not_a_list");
|
|
92
|
+
return answer.json;
|
|
93
|
+
},
|
|
94
|
+
async release(id, signal) {
|
|
95
|
+
const call = "POST /v1/sessions/{id}";
|
|
96
|
+
const body = { status: "REQUEST_RELEASE", ...(projectId ? { projectId } : {}) };
|
|
97
|
+
const answer = await restCall(o, "POST", `/v1/sessions/${encodeURIComponent(id)}`, call, { body, ...(signal ? { signal } : {}) });
|
|
98
|
+
return answer.status === 404 ? "gone" : "asked";
|
|
99
|
+
},
|
|
100
|
+
async debug(id, signal) {
|
|
101
|
+
const call = "GET /v1/sessions/{id}/debug";
|
|
102
|
+
const answer = await restCall(o, "GET", `/v1/sessions/${encodeURIComponent(id)}/debug`, call, signal ? { signal } : {});
|
|
103
|
+
if (answer.status === 404)
|
|
104
|
+
throw new BrowserVendorError(NAME, call, 404);
|
|
105
|
+
return (answer.json ?? {});
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const refOf = (s) => ({ id: s.id, name: s.id });
|
|
110
|
+
const deadlineOf = (s) => {
|
|
111
|
+
const at = typeof s.expiresAt === "string" ? new Date(s.expiresAt) : undefined;
|
|
112
|
+
return at !== undefined && Number.isFinite(at.getTime()) ? at : undefined;
|
|
113
|
+
};
|
|
114
|
+
/** Computers that are Browserbase sessions. */
|
|
115
|
+
export class BrowserbaseProvider {
|
|
116
|
+
id = "browserbase";
|
|
117
|
+
version = VERSION;
|
|
118
|
+
#api;
|
|
119
|
+
#projectId;
|
|
120
|
+
#urls;
|
|
121
|
+
#confirm;
|
|
122
|
+
#sleep;
|
|
123
|
+
constructor({ apiKey, projectId, apiUrl, fetch: fetcher, api, urls, confirm = DEFAULT_CONFIRM, sleep = defaultSleep }) {
|
|
124
|
+
if (api === undefined && (typeof apiKey !== "string" || apiKey === ""))
|
|
125
|
+
throw new Error("set options.apiKey to a Browserbase API key, or options.api to a host's own Browserbase calls: the provider reads no environment");
|
|
126
|
+
this.#projectId = projectId || undefined;
|
|
127
|
+
this.#api = api ?? browserbaseRest({ apiKey: apiKey, ...(apiUrl ? { apiUrl } : {}), ...(this.#projectId ? { projectId: this.#projectId } : {}), ...(fetcher ? { fetch: fetcher } : {}) });
|
|
128
|
+
this.#urls = urls ?? memoryUrls();
|
|
129
|
+
this.#confirm = confirm;
|
|
130
|
+
this.#sleep = sleep;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* A browser: Browserbase ends a session at its timeout (lifetime vendor), at most 6 h; it reaches the open web; each
|
|
134
|
+
* session is its own VM. Browserbase keeps a session's downloads, but the protocol has no method that reads them yet,
|
|
135
|
+
* so downloads is not declared.
|
|
136
|
+
*/
|
|
137
|
+
capabilities() {
|
|
138
|
+
return {
|
|
139
|
+
kind: "browser",
|
|
140
|
+
lifetime: "vendor",
|
|
141
|
+
network: ["open"],
|
|
142
|
+
isolation: "vm",
|
|
143
|
+
os: "linux",
|
|
144
|
+
daemon: "none",
|
|
145
|
+
groups: [...CAPABILITIES[0].groups],
|
|
146
|
+
maxLifetimeMs: BROWSERBASE_MAX_LIFETIME_MS,
|
|
147
|
+
release: ["delete"],
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
check(spec) {
|
|
151
|
+
const refusals = checkBrowser(spec, this.capabilities(), NAME, BROWSERBASE_MIN_LIFETIME_MS);
|
|
152
|
+
const labels = spec?.labels;
|
|
153
|
+
if (labels !== undefined && !refusals.some((r) => r.field === "labels")) {
|
|
154
|
+
const problem = browserbaseLabelsProblem(labels);
|
|
155
|
+
if (problem)
|
|
156
|
+
refusals.push({ field: "labels", message: problem });
|
|
157
|
+
}
|
|
158
|
+
return refusals;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Makes a session at most once: with keepAlive, so a dropped CDP client never ends it, the lifetime as its timeout in
|
|
162
|
+
* whole seconds, and the labels as its userMetadata. settings are Browserbase's own create fields a host adds (a
|
|
163
|
+
* proxy, a viewport, an extension); what the protocol sets wins over them.
|
|
164
|
+
*/
|
|
165
|
+
async create(spec, { signal, settings = {} } = {}) {
|
|
166
|
+
const refusals = this.check(spec);
|
|
167
|
+
if (refusals.length > 0)
|
|
168
|
+
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
169
|
+
if (signal?.aborted)
|
|
170
|
+
return fail("aborted", "create was aborted before Browserbase was called");
|
|
171
|
+
const written = { [CREATE_LABEL]: createLabelValue(), ...spec.labels };
|
|
172
|
+
const body = {
|
|
173
|
+
...settings,
|
|
174
|
+
timeout: Math.ceil(spec.lifetimeMs / 1000),
|
|
175
|
+
keepAlive: true,
|
|
176
|
+
userMetadata: toMetadata(written),
|
|
177
|
+
...(this.#projectId ? { projectId: this.#projectId } : {}),
|
|
178
|
+
};
|
|
179
|
+
let made;
|
|
180
|
+
try {
|
|
181
|
+
made = await this.#api.create(body, signal);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
const failed = vendorFailure("browserbase", NAME, "POST /v1/sessions", error);
|
|
185
|
+
if (failed.ok || !createUncertain(error))
|
|
186
|
+
return failed;
|
|
187
|
+
// The session may have been made though its answer never came: found by its create label, never made again.
|
|
188
|
+
return vendorFail(failed.error.code, `${failed.error.message}; ${await this.#recover(written)}`, causeOf(failed));
|
|
189
|
+
}
|
|
190
|
+
if (idProblem(made?.id, NAME) !== undefined) {
|
|
191
|
+
return fail("browserbase", `Browserbase POST /v1/sessions answered with no session id, so there is no session to connect to; ${await this.#recover(written)}`);
|
|
192
|
+
}
|
|
193
|
+
const unusable = cdpUrlProblem(made.connectUrl, NAME, CDP_DOMAIN);
|
|
194
|
+
if (unusable !== undefined) {
|
|
195
|
+
// The session is made and billed (keepAlive, up to its timeout): released here, not left to a later sweep.
|
|
196
|
+
const released = await this.release(refOf(made), "delete");
|
|
197
|
+
return fail("browserbase", `Browserbase POST /v1/sessions made a session with no CDP URL to hand over: ${unusable}; ${released.ok ? "the session was released" : `the session was not released (${released.error.code}), and its labels let a sweep find it`}`);
|
|
198
|
+
}
|
|
199
|
+
this.#urls.set(made.id, made.connectUrl);
|
|
200
|
+
return ok(refOf(made));
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The sessions a lost create made, released: what recoverCreate says of them. They are found as list finds any, by
|
|
204
|
+
* the labels the create wrote (its create label first, so the query names it, then the run's), through #sessions and
|
|
205
|
+
* its metadata-key mapping: another session of the same run carries a create label of its own and is left alone.
|
|
206
|
+
*/
|
|
207
|
+
#recover(labels) {
|
|
208
|
+
const find = async (signal) => {
|
|
209
|
+
const found = await this.#sessions(labels, signal);
|
|
210
|
+
return found.ok ? ok(found.value.map((s) => s.id)) : found;
|
|
211
|
+
};
|
|
212
|
+
return recoverCreate("session", find, (id) => this.release({ id, name: id }, "delete"), this.#sleep);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Settings' test: one read of the project's running sessions (GET /v1/sessions?status=RUNNING), which makes nothing.
|
|
216
|
+
* A refused key is unauthorized and a Browserbase not reached unreachable; the words name the call, never the key.
|
|
217
|
+
*/
|
|
218
|
+
async testConnection({ signal } = {}) {
|
|
219
|
+
let running;
|
|
220
|
+
try {
|
|
221
|
+
running = await this.#api.list({ status: "RUNNING" }, signal);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
const failed = vendorFailure("browserbase", NAME, "GET /v1/sessions", error);
|
|
225
|
+
if (failed.ok)
|
|
226
|
+
return failed;
|
|
227
|
+
const reached = error?.status !== undefined || failed.error.code === "aborted";
|
|
228
|
+
return fail(reached ? connectionError(failed.error).code : "unreachable", failed.error.message);
|
|
229
|
+
}
|
|
230
|
+
const n = Array.isArray(running) ? running.length : 0;
|
|
231
|
+
return ok({ detail: `Browserbase answered: ${n} running ${n === 1 ? "session" : "sessions"} in the project` });
|
|
232
|
+
}
|
|
233
|
+
/** The session, when Browserbase still runs it; not_found in words when it does not know it, gone when it has ended. */
|
|
234
|
+
async #running(id, signal) {
|
|
235
|
+
const problem = idProblem(id, NAME);
|
|
236
|
+
if (problem)
|
|
237
|
+
return fail("invalid", problem);
|
|
238
|
+
let found;
|
|
239
|
+
try {
|
|
240
|
+
found = await this.#api.retrieve(id, signal);
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
return vendorFailure("browserbase", NAME, "GET /v1/sessions/{id}", error);
|
|
244
|
+
}
|
|
245
|
+
if (found === undefined)
|
|
246
|
+
return fail("not_found", `no Browserbase session has the id ${id}`);
|
|
247
|
+
if (!LIVE.has(found.status ?? ""))
|
|
248
|
+
return fail("gone", `the Browserbase session ${id} has ended (${found.status ?? "no status"}): only a running session is attached or connected to`);
|
|
249
|
+
return ok(found);
|
|
250
|
+
}
|
|
251
|
+
async #alive(id, signal) {
|
|
252
|
+
const found = await this.#running(id, signal);
|
|
253
|
+
if (found.ok)
|
|
254
|
+
return ok(true);
|
|
255
|
+
return found.error.code === "not_found" || found.error.code === "gone" ? ok(false) : found;
|
|
256
|
+
}
|
|
257
|
+
#attached(s) {
|
|
258
|
+
const deadline = deadlineOf(s);
|
|
259
|
+
return { ...refOf(s), spec: { image: BROWSER_IMAGE, user: "unknown", network: "open", kind: "browser", ...(deadline ? { deadline } : {}) } };
|
|
260
|
+
}
|
|
261
|
+
async attach(ref, { signal } = {}) {
|
|
262
|
+
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
263
|
+
if ((given.id === undefined) === (given.labels === undefined))
|
|
264
|
+
return fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
265
|
+
if (given.id !== undefined) {
|
|
266
|
+
const found = await this.#running(given.id, signal);
|
|
267
|
+
return found.ok ? ok(this.#attached(found.value)) : found;
|
|
268
|
+
}
|
|
269
|
+
const labels = given.labels;
|
|
270
|
+
const listed = await this.#sessions(labels, signal);
|
|
271
|
+
if (!listed.ok)
|
|
272
|
+
return listed;
|
|
273
|
+
const words = JSON.stringify(labels);
|
|
274
|
+
if (listed.value.length === 0)
|
|
275
|
+
return fail("not_found", `no running Browserbase session has the labels ${words}`);
|
|
276
|
+
if (listed.value.length > 1)
|
|
277
|
+
return fail("invalid", `${listed.value.length} Browserbase sessions have the labels ${words}: ${listed.value.map((s) => s.id).join(", ")}`);
|
|
278
|
+
return ok(this.#attached(listed.value[0]));
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The running and pending sessions with all of these labels. Browserbase is asked by status and by the first label a
|
|
282
|
+
* query carries as it is; the match is the provider's own, so a lane that drops the query never hands back another's.
|
|
283
|
+
* Both statuses must answer: a release trusts this list.
|
|
284
|
+
*/
|
|
285
|
+
async #sessions(labels, signal) {
|
|
286
|
+
const problem = browserbaseLabelsProblem(labels);
|
|
287
|
+
if (problem)
|
|
288
|
+
return fail("invalid", problem);
|
|
289
|
+
if (Object.keys(labels).length === 0)
|
|
290
|
+
return fail("invalid", "list and attach take at least one label: a Browserbase project holds sessions this provider did not make");
|
|
291
|
+
const first = Object.entries(labels).find(queryable);
|
|
292
|
+
const q = first === undefined ? undefined : `user_metadata['${metadataKey(first[0])}']:'${first[1]}'`;
|
|
293
|
+
let pages;
|
|
294
|
+
try {
|
|
295
|
+
pages = await Promise.all(["RUNNING", "PENDING"].map((status) => this.#api.list({ status, ...(q === undefined ? {} : { q }) }, signal)));
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
return vendorFailure("browserbase", NAME, "GET /v1/sessions", error);
|
|
299
|
+
}
|
|
300
|
+
const seen = new Set();
|
|
301
|
+
return ok(pages.flat().filter((s) => typeof s?.id === "string" && LIVE.has(s.status ?? "") && carries(metadataLabels(s.userMetadata), labels) && !seen.has(s.id) && seen.add(s.id)));
|
|
302
|
+
}
|
|
303
|
+
async list(labels, { signal } = {}) {
|
|
304
|
+
const found = await this.#sessions(labels, signal);
|
|
305
|
+
if (!found.ok)
|
|
306
|
+
return found;
|
|
307
|
+
return ok(found.value.map((s) => ({ ref: refOf(s), labels: fromMetadata(s.userMetadata), deadline: deadlineOf(s), state: "running", network: "open" })));
|
|
308
|
+
}
|
|
309
|
+
/** Always open: a Browserbase browser reaches the open web, and a change is refused in words. */
|
|
310
|
+
async network(ref, policy, { signal } = {}) {
|
|
311
|
+
if (policy !== undefined && policy !== "open")
|
|
312
|
+
return fail("refused", `a Browserbase browser's network is open; it cannot be set to ${JSON.stringify(policy)}`);
|
|
313
|
+
const found = await this.#running(ref?.id, signal);
|
|
314
|
+
return found.ok ? ok("open") : found;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* The session's signed CDP URL, held since create or read from Browserbase, and a client that answers hello and ping.
|
|
318
|
+
* The session is read first, held URL or not: one that has ended, or that Browserbase no longer knows though its URL is
|
|
319
|
+
* held, is gone, never handed over. Dials nothing: the URL is the driver's to dial.
|
|
320
|
+
*/
|
|
321
|
+
async connect(ref) {
|
|
322
|
+
const id = ref?.id;
|
|
323
|
+
const problem = idProblem(id, NAME);
|
|
324
|
+
if (problem)
|
|
325
|
+
return fail("invalid", problem);
|
|
326
|
+
let url = this.#urls.get(id);
|
|
327
|
+
const found = await this.#running(id);
|
|
328
|
+
if (!found.ok) {
|
|
329
|
+
// A vendor that did not answer leaves the held URL for the next connect; a session it ended takes it along.
|
|
330
|
+
if (found.error.code !== "not_found" && found.error.code !== "gone")
|
|
331
|
+
return found;
|
|
332
|
+
if (url === undefined)
|
|
333
|
+
return found;
|
|
334
|
+
this.#urls.delete(id);
|
|
335
|
+
return fail("gone", found.error.code === "gone" ? found.error.message : `the Browserbase session ${id} is gone: ${found.error.message}`);
|
|
336
|
+
}
|
|
337
|
+
if (url === undefined) {
|
|
338
|
+
if (typeof found.value.connectUrl !== "string" || found.value.connectUrl === "")
|
|
339
|
+
return fail("not_found", `the Browserbase session ${id} is not available for connection`);
|
|
340
|
+
url = found.value.connectUrl;
|
|
341
|
+
}
|
|
342
|
+
// Whatever held it (create, a read, a host's url store), a URL a driver would dial is wss: on Browserbase's own domain.
|
|
343
|
+
const unusable = cdpUrlProblem(url, NAME, CDP_DOMAIN);
|
|
344
|
+
if (unusable !== undefined)
|
|
345
|
+
return fail("browserbase", `the Browserbase session ${id} is not handed over: ${unusable}`);
|
|
346
|
+
this.#urls.set(id, url);
|
|
347
|
+
const hello = browserHello(VERSION, this.capabilities().groups);
|
|
348
|
+
const client = browserClient(hello, (signal) => this.#alive(id, signal));
|
|
349
|
+
return ok({ client, hello, cdp: { url }, close: async () => client.close() });
|
|
350
|
+
}
|
|
351
|
+
/** Asks Browserbase to release the session and waits until it reads as ended; one already ended or unknown is released. */
|
|
352
|
+
async release(ref, how, { signal } = {}) {
|
|
353
|
+
if (how !== "delete")
|
|
354
|
+
return fail("refused", `a Browserbase session is released with "delete"; it cannot be stopped and kept, so ${String(how)} is refused and the session is left as it is`);
|
|
355
|
+
const id = ref?.id;
|
|
356
|
+
const problem = idProblem(id, NAME);
|
|
357
|
+
if (problem)
|
|
358
|
+
return fail("invalid", problem);
|
|
359
|
+
const released = await releaseConfirmed({
|
|
360
|
+
request: async () => {
|
|
361
|
+
try {
|
|
362
|
+
return ok(await this.#api.release(id, signal));
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
return vendorFailure("browserbase", NAME, "POST /v1/sessions/{id}", error);
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
running: () => this.#alive(id, signal),
|
|
369
|
+
confirm: this.#confirm,
|
|
370
|
+
sleep: this.#sleep,
|
|
371
|
+
stillRunning: `Browserbase session ${id} still running after a release request`,
|
|
372
|
+
});
|
|
373
|
+
if (released.ok)
|
|
374
|
+
this.#urls.delete(id);
|
|
375
|
+
return released;
|
|
376
|
+
}
|
|
377
|
+
/** The session's live view, which takes input: a view-only one is refused, never handed over as one. */
|
|
378
|
+
async stream(ref, options = {}, { signal } = {}) {
|
|
379
|
+
if (options.viewOnly)
|
|
380
|
+
return fail("unsupported", "Browserbase's live view takes input; it has no view-only URL");
|
|
381
|
+
const found = await this.#running(ref?.id, signal);
|
|
382
|
+
if (!found.ok)
|
|
383
|
+
return found;
|
|
384
|
+
let live;
|
|
385
|
+
try {
|
|
386
|
+
live = await this.#api.debug(ref.id, signal);
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
return vendorFailure("browserbase", NAME, "GET /v1/sessions/{id}/debug", error);
|
|
390
|
+
}
|
|
391
|
+
if (typeof live?.debuggerFullscreenUrl !== "string" || live.debuggerFullscreenUrl === "")
|
|
392
|
+
return fail("not_found", `Browserbase gave no live view for the session ${ref.id}`);
|
|
393
|
+
return ok({
|
|
394
|
+
url: live.debuggerFullscreenUrl,
|
|
395
|
+
...(typeof live.debuggerUrl === "string" ? { framed: live.debuggerUrl } : {}),
|
|
396
|
+
pages: (live.pages ?? []).map((p) => ({ id: p.id ?? null, url: p.url ?? null, title: p.title ?? null, fullscreen: p.debuggerFullscreenUrl ?? null })),
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* The provider, built from its options alone, the key included (options.apiKey, or options.api / options.request, a
|
|
402
|
+
* host's own transport); it reads no environment, and throws in words when the key is missing, never echoing one.
|
|
403
|
+
*/
|
|
404
|
+
export function create(options) {
|
|
405
|
+
return new BrowserbaseProvider(options ?? {});
|
|
406
|
+
}
|
|
407
|
+
/** The conformance CLI's module for Browserbase: its live switch, its image and its notes. */
|
|
408
|
+
export const conformance = () => import("./conformance/browserbase.js");
|
package/dist/child.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ComputerCapabilities, ComputerConnection } from "./provider.js";
|
|
2
|
+
import { type Result } from "./result.js";
|
|
3
|
+
/** One string for a shell: `sh -c '<script>' sh '<arg>' ...`, every word quoted. */
|
|
4
|
+
export declare const shellCommand: (script: string, args: readonly string[]) => string;
|
|
5
|
+
export interface ChildCommandOptions {
|
|
6
|
+
/** Where the vendor's upload left the daemon. */
|
|
7
|
+
staging?: string;
|
|
8
|
+
/** Init's deadline, an ISO time. */
|
|
9
|
+
deadline?: string;
|
|
10
|
+
/** Who the daemon becomes, uid:gid in numbers. */
|
|
11
|
+
user?: string;
|
|
12
|
+
/** The X display init's screen and input methods drive (its DISPLAY); none for a computer with no screen. */
|
|
13
|
+
display?: string;
|
|
14
|
+
/** The most deadline.extend may move the deadline to, an ISO time; none, and the deadline cannot move. */
|
|
15
|
+
maxDeadline?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
|
|
19
|
+
* its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
|
|
20
|
+
* every argument quoted.
|
|
21
|
+
*/
|
|
22
|
+
export declare function childCommands({ staging, deadline, user, display, maxDeadline }?: ChildCommandOptions): {
|
|
23
|
+
install: string;
|
|
24
|
+
init: string;
|
|
25
|
+
stdio: string;
|
|
26
|
+
};
|
|
27
|
+
export interface DaemonExpected {
|
|
28
|
+
version: string;
|
|
29
|
+
uid: string;
|
|
30
|
+
gid: string;
|
|
31
|
+
arch: string;
|
|
32
|
+
kind: ComputerCapabilities["kind"];
|
|
33
|
+
groups: ComputerCapabilities["groups"];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* What the daemon reports of itself, read back through it: hello, its credentials (no capability in any set,
|
|
37
|
+
* no_new_privs, no groups, a seccomp filter), its network (its own loopback alone, from its /proc/self/net/dev), its
|
|
38
|
+
* working directory and binary. Each read is bounded by timeoutMs and the caller's signal.
|
|
39
|
+
*/
|
|
40
|
+
export declare function daemonDrift(connection: ComputerConnection, expected: DaemonExpected, timeoutMs: number, signal?: AbortSignal): Promise<Result<string[]>>;
|
package/dist/child.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
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";
|
|
7
|
+
const PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
|
8
|
+
const CAPS = ["CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"];
|
|
9
|
+
/** Root for what follows: the command's own user when it is root, else passwordless sudo, which the install checked. */
|
|
10
|
+
const ROOT = 'p=; [ "$(id -u)" = 0 ] || p="sudo -n"';
|
|
11
|
+
/** Whether the daemon at d is root's alone: the binary and every directory above it owned by root and writable by no
|
|
12
|
+
* group or other user (and so no symbolic link, no ACL). Else a user who could rename an entry on the path could put
|
|
13
|
+
* another binary there, which init and every bridge would run as root. Only root can change an owner or a mode, so a
|
|
14
|
+
* path that holds once holds until root changes it. Prints why it does not, and fails. `ls -ldn` is in BusyBox and
|
|
15
|
+
* coreutils alike; a trailing `.` (an SELinux label) is allowed, a `+` (an ACL) is not. */
|
|
16
|
+
const HELD = 'held() { x=$1; while :; do set -- $(ls -ldn "$x" 2>/dev/null); case "$1" in ?????[!w]??[!w]?|?????[!w]??[!w]?.) ;; *) false ;; esac && [ "$3" = 0 ] || { echo "the daemon at $d is not root\'s alone: $x is ${1:-missing}, owner ${3:-none}"; return 1; }; [ "$x" = / ] && return 0; x=${x%/*}; x=${x:-/}; done; }';
|
|
17
|
+
/** Installs the uploaded daemon root-owned and read-only to its user, makes its home and socket directory (init gives
|
|
18
|
+
* them to the daemon's user), and prints the installed binary's sha256. As root, or through passwordless sudo; else
|
|
19
|
+
* it says why. The daemon's directory is made root's (0755) even when the image already had it, a stale entry at
|
|
20
|
+
* the daemon's path is removed first, and the whole path is held to `held` before and after; a path another user can
|
|
21
|
+
* change is refused with nothing installed. Every tool is in BusyBox and in coreutils alike: no privilege tool of the
|
|
22
|
+
* image's is relied on. */
|
|
23
|
+
const INSTALL_SCRIPT = [
|
|
24
|
+
"# agentrun-computer: install",
|
|
25
|
+
"s=$1; d=$2; h=$3; r=$4; b=${d%/*}",
|
|
26
|
+
'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
|
+
HELD,
|
|
28
|
+
'[ -d "${b%/*}" ] || $p mkdir -p -m 0755 "${b%/*}" || { echo "installing the daemon at $d failed"; exit 5; }',
|
|
29
|
+
'held "${b%/*}" || exit 6',
|
|
30
|
+
'[ ! -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; }',
|
|
32
|
+
'held "$d" || exit 6',
|
|
33
|
+
'rm -f "$s"',
|
|
34
|
+
'echo "sha256 $($p sha256sum "$d" | cut -c1-64)"',
|
|
35
|
+
].join("\n");
|
|
36
|
+
/** Starts init, the long-lived command, as root in a clean environment from its home: `init --user` gives HOME and the
|
|
37
|
+
* socket's directory to the daemon's user, sets no_new_privs and empties every capability set on every thread, and
|
|
38
|
+
* becomes that user with no groups. `--own-network` first cuts init and its programs off from the vendor's agent beside
|
|
39
|
+
* them (Daytona's toolbox, E2B's envd), which runs commands as root for whoever reaches it: a network of their own,
|
|
40
|
+
* their loopback alone, no vsock, no other process of their uid (src/isolation.ts). Init holds every process and ends
|
|
41
|
+
* them at the deadline. A display, when given, is init's DISPLAY, the X display its screen and input methods drive; a
|
|
42
|
+
* maximum, when given, is the most deadline.extend may move the deadline to. */
|
|
43
|
+
const INIT_SCRIPT = [
|
|
44
|
+
"# agentrun-computer: init",
|
|
45
|
+
// The display is v, not x: held() assigns x, and runs before the exec that reads it.
|
|
46
|
+
"d=$1; t=$2; w=$3; h=$4; r=$5; v=${6-}; m=${7-}",
|
|
47
|
+
HELD,
|
|
48
|
+
'held "$d" >&2 || exit 6',
|
|
49
|
+
ROOT,
|
|
50
|
+
`exec $p env -i PATH=${PATH} HOME="$h" AGENTRUN_COMPUTERD_SOCKET="$r/computerd.sock" \${v:+DISPLAY="$v"} sh -c 'cd "$HOME" && exec "$@"' sh "$d" init --deadline "$t" --user "$w" --own-network \${m:+--max-deadline "$m"}`,
|
|
51
|
+
].join("\n");
|
|
52
|
+
/** The bridge one connection runs: stdin and stdout to init's socket. As root, to reach a socket in a directory that is
|
|
53
|
+
* the daemon's user's alone; it only carries bytes, and the command's user is root or has passwordless sudo already.
|
|
54
|
+
* Like init, it runs the daemon only when its path is root's alone (`held`), so a computer attached from an older
|
|
55
|
+
* install is checked too. */
|
|
56
|
+
const STDIO_SCRIPT = ["# agentrun-computer: stdio", "d=$1; r=$2", HELD, 'held "$d" >&2 || exit 6', ROOT, `exec $p env -i PATH=${PATH} AGENTRUN_COMPUTERD_SOCKET="$r/computerd.sock" "$d" stdio`].join("\n");
|
|
57
|
+
const quote = (word) => `'${word.replaceAll("'", "'\\''")}'`;
|
|
58
|
+
/** One string for a shell: `sh -c '<script>' sh '<arg>' ...`, every word quoted. */
|
|
59
|
+
export const shellCommand = (script, args) => ["sh", "-c", quote(script), "sh", ...args.map(quote)].join(" ");
|
|
60
|
+
/**
|
|
61
|
+
* The three shell commands a child-daemon provider sends into a computer, exactly: install (the upload moved into place,
|
|
62
|
+
* its sha256 printed), init (long-lived) and stdio (one per connection). Each is one string for a shell, `sh -c` with
|
|
63
|
+
* every argument quoted.
|
|
64
|
+
*/
|
|
65
|
+
export function childCommands({ staging = "", deadline = "", user = TOOL_USER, display = "", maxDeadline = "" } = {}) {
|
|
66
|
+
const init = [DAEMON_IN_COMPUTER, deadline, user, WORK, SOCKET_DIR];
|
|
67
|
+
if (display !== "" || maxDeadline !== "")
|
|
68
|
+
init.push(display, maxDeadline);
|
|
69
|
+
return {
|
|
70
|
+
install: shellCommand(INSTALL_SCRIPT, [staging, DAEMON_IN_COMPUTER, WORK, SOCKET_DIR]),
|
|
71
|
+
init: shellCommand(INIT_SCRIPT, init),
|
|
72
|
+
stdio: shellCommand(STDIO_SCRIPT, [DAEMON_IN_COMPUTER, SOCKET_DIR]),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
76
|
+
/**
|
|
77
|
+
* What the daemon reports of itself, read back through it: hello, its credentials (no capability in any set,
|
|
78
|
+
* no_new_privs, no groups, a seccomp filter), its network (its own loopback alone, from its /proc/self/net/dev), its
|
|
79
|
+
* working directory and binary. Each read is bounded by timeoutMs and the caller's signal.
|
|
80
|
+
*/
|
|
81
|
+
export async function daemonDrift(connection, expected, timeoutMs, signal) {
|
|
82
|
+
const found = helloDrift(connection.hello, { version: expected.version, kind: expected.kind, groups: expected.groups, arch: expected.arch });
|
|
83
|
+
const bounded = () => (signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs));
|
|
84
|
+
const status = await connection.client.call("files.read", { path: "/proc/self/status" }, { signal: bounded() });
|
|
85
|
+
if (!status.ok)
|
|
86
|
+
return fail(status.error.code === "aborted" && !signal?.aborted ? "timeout" : status.error.code, `reading the daemon's /proc/self/status: ${status.error.message}`);
|
|
87
|
+
const fields = new Map();
|
|
88
|
+
for (const line of Buffer.from(status.value.data, "base64").toString("utf8").split("\n")) {
|
|
89
|
+
const at = line.indexOf(":");
|
|
90
|
+
if (at > 0)
|
|
91
|
+
fields.set(line.slice(0, at), line.slice(at + 1).trim());
|
|
92
|
+
}
|
|
93
|
+
const ids = (name) => (fields.get(name) ?? "").split(/\s+/).filter(Boolean);
|
|
94
|
+
const uids = ids("Uid");
|
|
95
|
+
const gids = ids("Gid");
|
|
96
|
+
if (uids.length !== 4 || uids.some((id) => id !== expected.uid))
|
|
97
|
+
found.push(`daemon user: declared uid ${expected.uid}, read back ${show(fields.get("Uid"))}`);
|
|
98
|
+
if (gids.length !== 4 || gids.some((id) => id !== expected.gid))
|
|
99
|
+
found.push(`daemon group: declared gid ${expected.gid}, read back ${show(fields.get("Gid"))}`);
|
|
100
|
+
if ((fields.get("Groups") ?? "") !== "")
|
|
101
|
+
found.push(`daemon groups: declared none, read back ${show(fields.get("Groups"))}`);
|
|
102
|
+
if (fields.get("NoNewPrivs") !== "1")
|
|
103
|
+
found.push(`daemon no_new_privs: declared 1, read back ${show(fields.get("NoNewPrivs"))}`);
|
|
104
|
+
for (const set of CAPS) {
|
|
105
|
+
const value = fields.get(set);
|
|
106
|
+
if (value === undefined || !/^0+$/.test(value))
|
|
107
|
+
found.push(`daemon ${set}: declared no capabilities, read back ${show(value)}`);
|
|
108
|
+
}
|
|
109
|
+
if (fields.get("Seccomp") !== "2")
|
|
110
|
+
found.push(`daemon seccomp: declared 2 (the filter that refuses vsock and io_uring), read back ${show(fields.get("Seccomp"))}`);
|
|
111
|
+
// Its own network, as its user sees it: the live interfaces lo alone, and none it could bring up (computerd probe).
|
|
112
|
+
const net = await readOwnNetwork(connection.client, timeoutMs, bounded());
|
|
113
|
+
if (!net.ok)
|
|
114
|
+
return fail(net.error.code === "aborted" && !signal?.aborted ? "timeout" : net.error.code, net.error.message);
|
|
115
|
+
found.push(...net.value);
|
|
116
|
+
for (const [path, want, what] of [
|
|
117
|
+
["/proc/self/cwd", WORK, "working directory"],
|
|
118
|
+
["/proc/self/exe", DAEMON_IN_COMPUTER, "binary"],
|
|
119
|
+
]) {
|
|
120
|
+
const stat = await connection.client.call("files.stat", { path }, { signal: bounded() });
|
|
121
|
+
if (!stat.ok)
|
|
122
|
+
return fail(stat.error.code === "aborted" && !signal?.aborted ? "timeout" : stat.error.code, `reading the daemon's ${path}: ${stat.error.message}`);
|
|
123
|
+
if (stat.value.target !== want)
|
|
124
|
+
found.push(`daemon ${what}: declared ${want}, read back ${show(stat.value.target)}`);
|
|
125
|
+
}
|
|
126
|
+
return ok(found);
|
|
127
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
import { type ComputerClient, type DaemonMethod, type DaemonMethods } from "./protocol.js";
|
|
3
|
+
import { type Result } from "./result.js";
|
|
4
|
+
export interface DaemonStream {
|
|
5
|
+
readable: Readable;
|
|
6
|
+
writable: Writable;
|
|
7
|
+
}
|
|
8
|
+
export interface CallOptions {
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Calls a daemon's methods. Each call gets its own id; replies may come in any order. An aborted call sends
|
|
13
|
+
* $/cancelRequest and returns `aborted` at once; the daemon still ends what the call started. When the stream ends,
|
|
14
|
+
* every pending and later call fails with `gone`. A line that is not a reply to a pending call is dropped.
|
|
15
|
+
*/
|
|
16
|
+
export declare class DaemonClient implements ComputerClient {
|
|
17
|
+
#private;
|
|
18
|
+
constructor({ readable, writable }: DaemonStream);
|
|
19
|
+
call<M extends DaemonMethod>(method: M, params: DaemonMethods[M]["params"], options?: CallOptions): Promise<Result<DaemonMethods[M]["result"]>>;
|
|
20
|
+
/** Ends the connection: pending and later calls fail with `gone`. */
|
|
21
|
+
close(): void;
|
|
22
|
+
}
|