@parcha/agentrun-computer 0.0.0-stage → 0.1.0-beta.33
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 +2411 -2
- 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 +98 -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 +126 -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 +132 -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 +213 -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 +180 -0
- package/dist/daytona.js +1498 -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 +156 -0
- package/dist/docker.js +1277 -0
- package/dist/drift.d.ts +200 -0
- package/dist/drift.js +416 -0
- package/dist/e2b.d.ts +337 -0
- package/dist/e2b.js +1516 -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 +62 -4
package/dist/mount.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Refusal } from "./provider.js";
|
|
2
|
+
/**
|
|
3
|
+
* Why epoch is not a claim epoch, in words, or undefined when it is one: a whole number from 0 to 2^53 - 1. It lives here,
|
|
4
|
+
* not in labels.ts, so ./mount loads node built-ins alone; labels.ts takes it from here.
|
|
5
|
+
*/
|
|
6
|
+
export declare function epochProblem(epoch: unknown): string | undefined;
|
|
7
|
+
/** Where the run's folder is mounted in every computer. HOME is elsewhere (a Docker computer's is /work). */
|
|
8
|
+
export declare const WORKSPACE = "/workspace";
|
|
9
|
+
/**
|
|
10
|
+
* The run's folder, mounted at WORKSPACE. bind: a folder on the provider's host, bound in (the local Docker computer).
|
|
11
|
+
* archil: the run's folder inside an Archil disk in its region, mounted in the computer with the disk's token (a remote
|
|
12
|
+
* computer).
|
|
13
|
+
*/
|
|
14
|
+
export type MountSpec = {
|
|
15
|
+
kind: "bind";
|
|
16
|
+
path: string;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "archil";
|
|
19
|
+
disk: string;
|
|
20
|
+
region: string;
|
|
21
|
+
folder: string;
|
|
22
|
+
token: string;
|
|
23
|
+
};
|
|
24
|
+
export type MountKind = MountSpec["kind"];
|
|
25
|
+
export declare const MOUNT_KINDS: readonly MountKind[];
|
|
26
|
+
/**
|
|
27
|
+
* A computer's mount as read back from the computer itself: its kind and where it comes from, never the token. `other`
|
|
28
|
+
* is a mount at WORKSPACE the provider never makes (read-only, a volume), in words. An Archil mount also reads back
|
|
29
|
+
* whether it holds the folder exclusively (no other client writes it) and the claim epoch it was made under: the
|
|
30
|
+
* computer's agentrun.epoch label (labels.ts), since Archil's hold on a folder carries no epoch of its own.
|
|
31
|
+
*/
|
|
32
|
+
export type MountReadBack = {
|
|
33
|
+
kind: "bind";
|
|
34
|
+
path: string;
|
|
35
|
+
} | {
|
|
36
|
+
kind: "archil";
|
|
37
|
+
disk: string;
|
|
38
|
+
region: string;
|
|
39
|
+
folder: string;
|
|
40
|
+
exclusive: boolean;
|
|
41
|
+
epoch: number;
|
|
42
|
+
} | {
|
|
43
|
+
other: string;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The one mount rule, with no vendor call: no mount is no refusal; a kind the provider does not declare is refused in
|
|
47
|
+
* words; a bind's path is absolute, canonical (its own realpath: what a provider reads back is what is bound), an
|
|
48
|
+
* existing directory on the host, with no NUL; an Archil mount's disk, region, folder and token are non-empty strings with no
|
|
49
|
+
* NUL, the folder relative to the disk's root and never above it. Each refusal names a field, never an Archil value.
|
|
50
|
+
*/
|
|
51
|
+
export declare function checkMount(mount: unknown, declared: readonly MountKind[] | undefined): Refusal[];
|
|
52
|
+
/**
|
|
53
|
+
* What a provider reads back of a mount it made as asked: its kind and source, never the token. An Archil mount is
|
|
54
|
+
* always exclusive, and is read back under `epoch`, the computer's claim epoch. With no epoch, or a value that is not
|
|
55
|
+
* one, it is `{ other }` in words: a mount under no claim, which no attach takes, never a guessed epoch. A bind takes none.
|
|
56
|
+
*/
|
|
57
|
+
export declare function readBackOf(mount: MountSpec, epoch?: number): MountReadBack;
|
package/dist/mount.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The run's folder in a computer: the one path it is mounted at, the spec rule every provider's check() shares, and the
|
|
2
|
+
// shape a provider reads it back in. An Archil mount's token is a secret: no refusal, read-back or word here holds it.
|
|
3
|
+
import { realpathSync, statSync } from "node:fs";
|
|
4
|
+
/**
|
|
5
|
+
* Why epoch is not a claim epoch, in words, or undefined when it is one: a whole number from 0 to 2^53 - 1. It lives here,
|
|
6
|
+
* not in labels.ts, so ./mount loads node built-ins alone; labels.ts takes it from here.
|
|
7
|
+
*/
|
|
8
|
+
export function epochProblem(epoch) {
|
|
9
|
+
if (typeof epoch === "number" && Number.isSafeInteger(epoch) && epoch >= 0)
|
|
10
|
+
return undefined;
|
|
11
|
+
return `an epoch must be a whole number from 0 to ${Number.MAX_SAFE_INTEGER}, not ${typeof epoch === "number" ? String(epoch) : JSON.stringify(epoch) ?? typeof epoch}`;
|
|
12
|
+
}
|
|
13
|
+
/** Where the run's folder is mounted in every computer. HOME is elsewhere (a Docker computer's is /work). */
|
|
14
|
+
export const WORKSPACE = "/workspace";
|
|
15
|
+
export const MOUNT_KINDS = ["bind", "archil"];
|
|
16
|
+
const SHAPE = 'mount is { kind: "bind", path } or { kind: "archil", disk, region, folder, token }';
|
|
17
|
+
const FIELDS = { bind: ["kind", "path"], archil: ["kind", "disk", "region", "folder", "token"] };
|
|
18
|
+
const NUL = "a NUL byte cannot be passed to a mount";
|
|
19
|
+
const filled = (value) => typeof value === "string" && value !== "";
|
|
20
|
+
/**
|
|
21
|
+
* The one mount rule, with no vendor call: no mount is no refusal; a kind the provider does not declare is refused in
|
|
22
|
+
* words; a bind's path is absolute, canonical (its own realpath: what a provider reads back is what is bound), an
|
|
23
|
+
* existing directory on the host, with no NUL; an Archil mount's disk, region, folder and token are non-empty strings with no
|
|
24
|
+
* NUL, the folder relative to the disk's root and never above it. Each refusal names a field, never an Archil value.
|
|
25
|
+
*/
|
|
26
|
+
export function checkMount(mount, declared) {
|
|
27
|
+
if (mount === undefined)
|
|
28
|
+
return [];
|
|
29
|
+
const refuse = (message) => [{ field: "mount", message }];
|
|
30
|
+
const given = typeof mount === "object" && mount !== null && !Array.isArray(mount) ? mount : undefined;
|
|
31
|
+
const kind = given?.kind;
|
|
32
|
+
if (given === undefined || !MOUNT_KINDS.includes(kind))
|
|
33
|
+
return refuse(SHAPE);
|
|
34
|
+
const takes = declared ?? [];
|
|
35
|
+
if (!takes.includes(kind)) {
|
|
36
|
+
return refuse(takes.length === 0
|
|
37
|
+
? `this provider declares no mount kind, so it mounts no run folder (capabilities().mount)`
|
|
38
|
+
: `this provider does not take a mount of kind ${kind}; it takes ${takes.join(" or ")}`);
|
|
39
|
+
}
|
|
40
|
+
const extra = Object.keys(given).find((field) => !FIELDS[kind].includes(field) && given[field] !== undefined);
|
|
41
|
+
if (extra !== undefined)
|
|
42
|
+
return refuse(`mount.${extra} is not a field of ${kind === "bind" ? "a bind" : "an archil"} mount`);
|
|
43
|
+
return kind === "bind" ? bindRefusals(given.path).map((message) => ({ field: "mount", message })) : archilRefusals(given).map((message) => ({ field: "mount", message }));
|
|
44
|
+
}
|
|
45
|
+
function bindRefusals(path) {
|
|
46
|
+
if (!filled(path))
|
|
47
|
+
return ["mount.path is required: the run folder's absolute path on the host"];
|
|
48
|
+
if (path.includes("\0"))
|
|
49
|
+
return [`mount.path: ${NUL}`];
|
|
50
|
+
if (!path.startsWith("/"))
|
|
51
|
+
return [`mount.path must be absolute, not ${JSON.stringify(path)}`];
|
|
52
|
+
let directory = false;
|
|
53
|
+
let real;
|
|
54
|
+
try {
|
|
55
|
+
directory = statSync(path).isDirectory();
|
|
56
|
+
real = realpathSync(path);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
directory = false;
|
|
60
|
+
}
|
|
61
|
+
if (!directory)
|
|
62
|
+
return [`mount.path ${JSON.stringify(path)} is not a directory on the host`];
|
|
63
|
+
if (real !== path)
|
|
64
|
+
return [`mount.path ${JSON.stringify(path)} is not canonical: it resolves to ${JSON.stringify(real)}; give that path`];
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
/** An Archil mount's refusals, by field: no value is ever in them, since the token may be in any field by mistake. */
|
|
68
|
+
function archilRefusals({ disk, region, folder, token }) {
|
|
69
|
+
const found = [];
|
|
70
|
+
if (!filled(disk))
|
|
71
|
+
found.push("mount.disk is required: the Archil disk's name");
|
|
72
|
+
else if (disk.includes("\0"))
|
|
73
|
+
found.push(`mount.disk: ${NUL}`);
|
|
74
|
+
if (!filled(region))
|
|
75
|
+
found.push("mount.region is required: the Archil disk's region");
|
|
76
|
+
else if (region.includes("\0"))
|
|
77
|
+
found.push(`mount.region: ${NUL}`);
|
|
78
|
+
if (!filled(folder))
|
|
79
|
+
found.push("mount.folder is required: the run's folder inside the disk, relative to its root");
|
|
80
|
+
else if (folder.includes("\0"))
|
|
81
|
+
found.push(`mount.folder: ${NUL}`);
|
|
82
|
+
else if (folder.startsWith("/"))
|
|
83
|
+
found.push("mount.folder must be relative to the disk's root");
|
|
84
|
+
else if (folder.split("/").includes(".."))
|
|
85
|
+
found.push('mount.folder must stay inside the disk: no ".." part');
|
|
86
|
+
if (!filled(token))
|
|
87
|
+
found.push("mount.token is required: the disk's token, a non-empty string");
|
|
88
|
+
else if (token.includes("\0"))
|
|
89
|
+
found.push(`mount.token: ${NUL}`);
|
|
90
|
+
return found;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* What a provider reads back of a mount it made as asked: its kind and source, never the token. An Archil mount is
|
|
94
|
+
* always exclusive, and is read back under `epoch`, the computer's claim epoch. With no epoch, or a value that is not
|
|
95
|
+
* one, it is `{ other }` in words: a mount under no claim, which no attach takes, never a guessed epoch. A bind takes none.
|
|
96
|
+
*/
|
|
97
|
+
export function readBackOf(mount, epoch) {
|
|
98
|
+
if (mount.kind === "bind")
|
|
99
|
+
return { kind: "bind", path: mount.path };
|
|
100
|
+
const problem = epochProblem(epoch);
|
|
101
|
+
if (problem !== undefined)
|
|
102
|
+
return { other: `an Archil mount of ${mount.disk}:/${mount.folder} with no epoch to read it back under (${problem})` };
|
|
103
|
+
return { kind: "archil", disk: mount.disk, region: mount.region, folder: mount.folder, exclusive: true, epoch: epoch };
|
|
104
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type Readable, Writable } from "node:stream";
|
|
2
|
+
import { type Result } from "./result.js";
|
|
3
|
+
/** Orgo's API. */
|
|
4
|
+
export declare const ORGO_API_URL = "https://www.orgo.ai/api";
|
|
5
|
+
/** The most Orgo's one-step upload takes. */
|
|
6
|
+
export declare const MAX_UPLOAD_BYTES: number;
|
|
7
|
+
/** Where a detached start writes what it prints. */
|
|
8
|
+
export declare const START_LOG = "/tmp/agentrun-init.log";
|
|
9
|
+
/** One word for bash: single-quoted. */
|
|
10
|
+
export declare const quote: (word: string) => string;
|
|
11
|
+
/** An argv as one bash command line. */
|
|
12
|
+
export declare const commandLine: (argv: readonly string[]) => string;
|
|
13
|
+
/** An Orgo REST failure: the error's code and words, and Orgo's status and code when it answered. */
|
|
14
|
+
export type OrgoFailure = Result<never> & {
|
|
15
|
+
status?: number;
|
|
16
|
+
orgoCode?: string;
|
|
17
|
+
};
|
|
18
|
+
export interface OrgoRest {
|
|
19
|
+
/** Orgo's origin, from which the terminal socket's URL is made. */
|
|
20
|
+
readonly origin: string;
|
|
21
|
+
request<T>(method: string, path: string, options: {
|
|
22
|
+
body?: unknown;
|
|
23
|
+
form?: FormData;
|
|
24
|
+
headers?: Record<string, string>;
|
|
25
|
+
timeoutMs: number;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}): Promise<Result<T> | OrgoFailure>;
|
|
28
|
+
}
|
|
29
|
+
/** Orgo's REST API with a key: every call bounded, every failure a code and words that never hold the key. */
|
|
30
|
+
export declare function orgoRest({ apiKey, apiUrl, fetch: fetcher }: {
|
|
31
|
+
apiKey: string;
|
|
32
|
+
apiUrl?: string;
|
|
33
|
+
fetch?: typeof fetch;
|
|
34
|
+
}): OrgoRest;
|
|
35
|
+
/** computerd's stdio bridge as a byte stream: what it prints, what it reads, and its end. */
|
|
36
|
+
export interface OrgoStream {
|
|
37
|
+
readable: Readable;
|
|
38
|
+
writable: Writable;
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
/** What ended the stream, in words (an exit code, an error frame, a close code), or "" while it runs. */
|
|
41
|
+
said(): string;
|
|
42
|
+
}
|
|
43
|
+
/** How a long-lived command is started: from bash, detached, or typed into a named terminal session. */
|
|
44
|
+
export type OrgoStart = "bash" | "session";
|
|
45
|
+
/** A provider's way into one of its Orgo computers, as root. Every result's words hold no key or password. */
|
|
46
|
+
export interface OrgoChannel {
|
|
47
|
+
/** argv as root, in the foreground, within timeoutMs (at most 300 s): its exit code and what it printed. */
|
|
48
|
+
run(computer: string, argv: readonly string[], options: {
|
|
49
|
+
timeoutMs: number;
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
}): Promise<Result<{
|
|
52
|
+
exitCode: number;
|
|
53
|
+
output: string;
|
|
54
|
+
}>>;
|
|
55
|
+
/** argv started as root so that it outlives this call and its channel; its output goes to a log in the computer. */
|
|
56
|
+
start(computer: string, argv: readonly string[], options: {
|
|
57
|
+
how: OrgoStart;
|
|
58
|
+
timeoutMs: number;
|
|
59
|
+
signal?: AbortSignal;
|
|
60
|
+
}): Promise<Result<void>>;
|
|
61
|
+
/** argv as root with its stdin and stdout as a byte stream, from its first byte: computerd's bridge. */
|
|
62
|
+
stdio(computer: string, argv: readonly string[], options: {
|
|
63
|
+
timeoutMs: number;
|
|
64
|
+
signal?: AbortSignal;
|
|
65
|
+
}): Promise<Result<OrgoStream>>;
|
|
66
|
+
/** bytes as the file at path (an absolute path) in the computer. */
|
|
67
|
+
upload(computer: string, path: string, bytes: Uint8Array, options: {
|
|
68
|
+
timeoutMs: number;
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}): Promise<Result<void>>;
|
|
71
|
+
}
|
|
72
|
+
/** The parts of a WebSocket the terminal channel uses: Node's global WebSocket, or a fake. */
|
|
73
|
+
export interface OrgoSocket {
|
|
74
|
+
addEventListener(type: "open" | "message" | "close" | "error", listener: (event: {
|
|
75
|
+
data?: unknown;
|
|
76
|
+
code?: number;
|
|
77
|
+
reason?: string;
|
|
78
|
+
}) => void): void;
|
|
79
|
+
send(data: string): void;
|
|
80
|
+
close(code?: number, reason?: string): void;
|
|
81
|
+
}
|
|
82
|
+
export type OrgoWebSocketFactory = (url: string) => OrgoSocket;
|
|
83
|
+
/**
|
|
84
|
+
* The channel over Orgo's own calls: run is the bash call, upload the file upload, start a bash call that detaches the
|
|
85
|
+
* command with setsid (or the command typed into the named terminal session, which survives the socket), and stdio the
|
|
86
|
+
* root terminal made raw (`stty raw -echo`, so the PTY neither echoes nor rewrites a byte), whose output before a marker
|
|
87
|
+
* line (the prompt, the typed line's echo) is dropped. The marker is printed from two words, so the echo of the line
|
|
88
|
+
* that prints it never holds it.
|
|
89
|
+
*/
|
|
90
|
+
export declare function orgoTerminalChannel({ rest, workspaceId, webSocket, echoMs, }: {
|
|
91
|
+
rest: OrgoRest;
|
|
92
|
+
workspaceId: string;
|
|
93
|
+
webSocket?: OrgoWebSocketFactory;
|
|
94
|
+
/** How long a typed line waits for the shell's echo before it is typed again. */
|
|
95
|
+
echoMs?: number;
|
|
96
|
+
}): OrgoChannel;
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
// How the Orgo provider reaches Orgo: its REST API (orgoRest), and, inside one computer, a channel (OrgoChannel) that
|
|
2
|
+
// runs a command as root, starts one that outlives the call, puts a file there, and carries computerd's stdio bridge.
|
|
3
|
+
// The provider sees only the OrgoChannel interface, so another transport (SSH: root on the computer's public port) can
|
|
4
|
+
// replace the terminal one without touching it. Every fact here is from docs.orgo.ai:
|
|
5
|
+
// - REST: https://www.orgo.ai/api, `Authorization: Bearer <key>`; an error answers { error, code } with its status.
|
|
6
|
+
// - POST /computers/{id}/bash { command, timeout }: synchronous, root (HOME=/root), the timeout clamped to 1-300 s, the
|
|
7
|
+
// proxy waiting 30 s past it; it answers { exit_code, output }, stdout then stderr in output.
|
|
8
|
+
// - POST /files/upload, multipart: file, workspaceId, desktopId, destPath; with destPath the file goes to that computer
|
|
9
|
+
// alone, at <destPath>/<file name>; at most 10 MB.
|
|
10
|
+
// - The terminal: wss://www.orgo.ai/desktops/{id}/ws/terminal?token=<the computer's VNC password>, a root `bash -l` in
|
|
11
|
+
// a PTY, JSON text frames: input { type: "input", data } in, { type: "output", data } and { type: "exit", code } out.
|
|
12
|
+
// It ends with the socket unless `session=<name>` names it; then the shell survives the socket.
|
|
13
|
+
// The key goes in the Authorization header and nowhere else; the VNC password only in the terminal socket's URL, held in
|
|
14
|
+
// memory for the call. Neither is in a word this module returns.
|
|
15
|
+
import { randomBytes } from "node:crypto";
|
|
16
|
+
import { PassThrough, Writable } from "node:stream";
|
|
17
|
+
import { fail, ok } from "./result.js";
|
|
18
|
+
/** Orgo's API. */
|
|
19
|
+
export const ORGO_API_URL = "https://www.orgo.ai/api";
|
|
20
|
+
/** The most Orgo's one-step upload takes. */
|
|
21
|
+
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
|
22
|
+
/** Orgo's bash call's longest timeout, in seconds. */
|
|
23
|
+
const BASH_MAX_S = 300;
|
|
24
|
+
/** How much longer than the command's own timeout Orgo's proxy waits for a bash call. */
|
|
25
|
+
const BASH_PROXY_MS = 30_000;
|
|
26
|
+
/** Where a detached start writes what it prints. */
|
|
27
|
+
export const START_LOG = "/tmp/agentrun-init.log";
|
|
28
|
+
/** The terminal session a session start runs in: it survives the socket. */
|
|
29
|
+
const SESSION = "agentrun-init";
|
|
30
|
+
/** One word for bash: single-quoted. */
|
|
31
|
+
export const quote = (word) => `'${word.replaceAll("'", "'\\''")}'`;
|
|
32
|
+
/** An argv as one bash command line. */
|
|
33
|
+
export const commandLine = (argv) => argv.map(quote).join(" ");
|
|
34
|
+
const codeOfStatus = (status) => status === 401 || status === 403 ? "denied" : status === 404 ? "not_found" : status === 429 ? "limit" : status === 400 || status === 422 ? "invalid" : status === 409 ? "refused" : "orgo";
|
|
35
|
+
/** Orgo's REST API with a key: every call bounded, every failure a code and words that never hold the key. */
|
|
36
|
+
export function orgoRest({ apiKey, apiUrl = ORGO_API_URL, fetch: fetcher = globalThis.fetch }) {
|
|
37
|
+
const base = apiUrl.replace(/\/+$/, "");
|
|
38
|
+
const scrub = (text) => text.replaceAll(apiKey, "[key]").replace(/\s+/g, " ").slice(0, 300);
|
|
39
|
+
return {
|
|
40
|
+
origin: new URL(base).origin,
|
|
41
|
+
async request(method, path, { body, form, headers = {}, timeoutMs, signal }) {
|
|
42
|
+
const what = `Orgo's ${method} ${path}`;
|
|
43
|
+
if (signal?.aborted)
|
|
44
|
+
return fail("aborted", `${what} was aborted before it was sent`);
|
|
45
|
+
const bound = AbortSignal.timeout(timeoutMs);
|
|
46
|
+
let response;
|
|
47
|
+
try {
|
|
48
|
+
response = await fetcher(`${base}${path}`, {
|
|
49
|
+
method,
|
|
50
|
+
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }), ...headers },
|
|
51
|
+
...(form !== undefined ? { body: form } : body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
52
|
+
redirect: "error",
|
|
53
|
+
signal: signal ? AbortSignal.any([signal, bound]) : bound,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (signal?.aborted)
|
|
58
|
+
return fail("aborted", `${what} was aborted`);
|
|
59
|
+
if (bound.aborted)
|
|
60
|
+
return fail("timeout", `${what} did not answer within ${timeoutMs / 1000} s`);
|
|
61
|
+
return fail("orgo", `${what} failed: ${scrub(error instanceof Error ? error.message : String(error))}`);
|
|
62
|
+
}
|
|
63
|
+
const text = await response.text().catch(() => "");
|
|
64
|
+
let parsed;
|
|
65
|
+
try {
|
|
66
|
+
parsed = text === "" ? undefined : JSON.parse(text);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
parsed = undefined;
|
|
70
|
+
}
|
|
71
|
+
if (response.ok)
|
|
72
|
+
return ok(parsed);
|
|
73
|
+
const { error, code } = (parsed ?? {});
|
|
74
|
+
const words = typeof error === "string" ? error : text || response.statusText;
|
|
75
|
+
const orgoCode = typeof code === "string" ? code : undefined;
|
|
76
|
+
return { ...fail(codeOfStatus(response.status), `${what} answered ${response.status}: ${scrub(words)}${orgoCode ? ` (${orgoCode})` : ""}`), status: response.status, ...(orgoCode ? { orgoCode } : {}) };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const defaultWebSocket = (url) => new WebSocket(url);
|
|
81
|
+
/** How many times a line the shell never echoed is typed in all. */
|
|
82
|
+
const TYPE_TRIES = 3;
|
|
83
|
+
/**
|
|
84
|
+
* Types line into the terminal's shell once it has prompted (any output: a shell still starting drops what is typed,
|
|
85
|
+
* as Orgo's `bash -l` did live), and types it again when the shell has not heard it (heard(): its echo, or what it
|
|
86
|
+
* prints) within echoMs, at most TYPE_TRIES times in all, all before deadline. Its error's words are the reason alone.
|
|
87
|
+
*/
|
|
88
|
+
async function typeLine(terminal, line, heard, { deadline, echoMs }) {
|
|
89
|
+
const left = () => Math.max(1, deadline - Date.now());
|
|
90
|
+
const prompted = await terminal.waitFor(() => terminal.text() !== "" || terminal.ended() !== undefined, left());
|
|
91
|
+
if (!prompted)
|
|
92
|
+
return fail("timeout", "the shell never prompted");
|
|
93
|
+
for (let tries = 1; tries <= TYPE_TRIES; tries++) {
|
|
94
|
+
const ended = terminal.ended();
|
|
95
|
+
if (ended !== undefined)
|
|
96
|
+
return fail("orgo", ended);
|
|
97
|
+
terminal.send(line);
|
|
98
|
+
if (await terminal.waitFor(() => heard() || terminal.ended() !== undefined, Math.min(echoMs, left()))) {
|
|
99
|
+
const after = terminal.ended();
|
|
100
|
+
return after !== undefined && !heard() ? fail("orgo", after) : ok(undefined);
|
|
101
|
+
}
|
|
102
|
+
if (Date.now() >= deadline)
|
|
103
|
+
return fail("timeout", `the line was typed ${tries} ${tries === 1 ? "time" : "times"}, and the shell had not echoed it`);
|
|
104
|
+
}
|
|
105
|
+
return fail("orgo", `the line was typed ${TYPE_TRIES} times, and the shell never echoed it`);
|
|
106
|
+
}
|
|
107
|
+
/** A frame's bytes as text, when they are: a string, an ArrayBuffer or a typed array; a Blob is read, in order. */
|
|
108
|
+
function frameText(data) {
|
|
109
|
+
if (typeof data === "string")
|
|
110
|
+
return { text: data, binary: false };
|
|
111
|
+
if (data instanceof ArrayBuffer)
|
|
112
|
+
return { text: Buffer.from(data).toString("utf8"), binary: true };
|
|
113
|
+
if (ArrayBuffer.isView(data))
|
|
114
|
+
return { text: Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8"), binary: true };
|
|
115
|
+
if (typeof Blob !== "undefined" && data instanceof Blob)
|
|
116
|
+
return data.text().then((text) => ({ text, binary: true }));
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The channel over Orgo's own calls: run is the bash call, upload the file upload, start a bash call that detaches the
|
|
121
|
+
* command with setsid (or the command typed into the named terminal session, which survives the socket), and stdio the
|
|
122
|
+
* root terminal made raw (`stty raw -echo`, so the PTY neither echoes nor rewrites a byte), whose output before a marker
|
|
123
|
+
* line (the prompt, the typed line's echo) is dropped. The marker is printed from two words, so the echo of the line
|
|
124
|
+
* that prints it never holds it.
|
|
125
|
+
*/
|
|
126
|
+
export function orgoTerminalChannel({ rest, workspaceId, webSocket = defaultWebSocket, echoMs = 3_000, }) {
|
|
127
|
+
const bash = async (computer, command, timeoutMs, signal) => {
|
|
128
|
+
const timeout = Math.min(BASH_MAX_S, Math.max(1, Math.ceil(timeoutMs / 1000)));
|
|
129
|
+
const ran = await rest.request("POST", `/computers/${encodeURIComponent(computer)}/bash`, { body: { command, timeout }, timeoutMs: timeout * 1000 + BASH_PROXY_MS, ...(signal ? { signal } : {}) });
|
|
130
|
+
if (!ran.ok)
|
|
131
|
+
return ran;
|
|
132
|
+
const { exit_code: exitCode, output } = ran.value ?? {};
|
|
133
|
+
if (typeof exitCode !== "number")
|
|
134
|
+
return fail("orgo", `Orgo's bash call answered no exit code (${JSON.stringify(ran.value)?.slice(0, 200)})`);
|
|
135
|
+
return ok({ exitCode, output: typeof output === "string" ? output : "" });
|
|
136
|
+
};
|
|
137
|
+
const open = async (computer, { session, timeoutMs, signal }) => {
|
|
138
|
+
const read = await rest.request("GET", `/computers/${encodeURIComponent(computer)}`, { timeoutMs, ...(signal ? { signal } : {}) });
|
|
139
|
+
if (!read.ok)
|
|
140
|
+
return read;
|
|
141
|
+
const password = read.value?.vnc_password;
|
|
142
|
+
if (typeof password !== "string" || password === "")
|
|
143
|
+
return fail("orgo", `Orgo gave no terminal password for ${computer}: is it running?`);
|
|
144
|
+
const url = new URL(`/desktops/${encodeURIComponent(computer)}/ws/terminal`, rest.origin.replace(/^http/, "ws"));
|
|
145
|
+
url.searchParams.set("token", password);
|
|
146
|
+
if (session !== undefined)
|
|
147
|
+
url.searchParams.set("session", session);
|
|
148
|
+
let socket;
|
|
149
|
+
try {
|
|
150
|
+
socket = webSocket(url.href);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
return fail("orgo", `the terminal of ${computer} could not be opened: ${String(error?.message ?? error).replaceAll(password, "[password]").slice(0, 200)}`);
|
|
154
|
+
}
|
|
155
|
+
const outputs = [];
|
|
156
|
+
const ends = [];
|
|
157
|
+
let ended;
|
|
158
|
+
let transcript = "";
|
|
159
|
+
const waiters = new Set();
|
|
160
|
+
const poke = () => {
|
|
161
|
+
for (const waiter of [...waiters])
|
|
162
|
+
waiter();
|
|
163
|
+
};
|
|
164
|
+
const end = (words) => {
|
|
165
|
+
if (ended !== undefined)
|
|
166
|
+
return;
|
|
167
|
+
ended = words;
|
|
168
|
+
for (const listener of ends)
|
|
169
|
+
listener(words);
|
|
170
|
+
poke();
|
|
171
|
+
};
|
|
172
|
+
// Binary frames as ArrayBuffers, where the socket takes the setting: no Blob to read out of order.
|
|
173
|
+
if ("binaryType" in socket)
|
|
174
|
+
socket.binaryType = "arraybuffer";
|
|
175
|
+
const kinds = new Map();
|
|
176
|
+
const count = (kind) => kinds.set(kind, (kinds.get(kind) ?? 0) + 1);
|
|
177
|
+
// Output before the first listener (the prompt, which comes as the socket opens) is kept for it.
|
|
178
|
+
const backlog = [];
|
|
179
|
+
const output = (data) => {
|
|
180
|
+
transcript = (transcript + data).slice(-65536);
|
|
181
|
+
if (outputs.length === 0)
|
|
182
|
+
backlog.push(data);
|
|
183
|
+
for (const listener of outputs)
|
|
184
|
+
listener(data);
|
|
185
|
+
poke();
|
|
186
|
+
};
|
|
187
|
+
// The docs give JSON text frames; output that comes as plain text or binary frames is taken as the bytes it is.
|
|
188
|
+
const take = ({ text, binary }) => {
|
|
189
|
+
let frame;
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(text);
|
|
192
|
+
frame = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && typeof parsed.type === "string" ? parsed : undefined;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
frame = undefined;
|
|
196
|
+
}
|
|
197
|
+
if (frame === undefined) {
|
|
198
|
+
count(binary ? "binary" : "text");
|
|
199
|
+
return output(text);
|
|
200
|
+
}
|
|
201
|
+
if (frame.type === "output" && typeof frame.data === "string") {
|
|
202
|
+
count("output");
|
|
203
|
+
output(frame.data);
|
|
204
|
+
}
|
|
205
|
+
else if (frame.type === "exit") {
|
|
206
|
+
count("exit");
|
|
207
|
+
end(`the terminal's program exited with ${String(frame.code)}`);
|
|
208
|
+
}
|
|
209
|
+
else if (frame.type === "error") {
|
|
210
|
+
count("error");
|
|
211
|
+
end(`the terminal said: ${String(frame.message).replaceAll(password, "[password]").slice(0, 200)}`);
|
|
212
|
+
}
|
|
213
|
+
else
|
|
214
|
+
count("other");
|
|
215
|
+
};
|
|
216
|
+
// A frame read at once is taken at once; a Blob is read in order, and frames after it wait their turn.
|
|
217
|
+
let order = Promise.resolve();
|
|
218
|
+
let reading = 0;
|
|
219
|
+
socket.addEventListener("message", ({ data }) => {
|
|
220
|
+
const read = frameText(data);
|
|
221
|
+
if (read === undefined)
|
|
222
|
+
return void count("other");
|
|
223
|
+
if (!(read instanceof Promise) && reading === 0)
|
|
224
|
+
return take(read);
|
|
225
|
+
reading++;
|
|
226
|
+
order = order
|
|
227
|
+
.then(() => (read instanceof Promise ? read.then(take, () => void count("other")) : take(read)))
|
|
228
|
+
.finally(() => {
|
|
229
|
+
reading--;
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
socket.addEventListener("close", ({ code, reason }) => end(`the terminal closed with ${code ?? "no code"}${reason ? ` (${String(reason).slice(0, 100)})` : ""}`));
|
|
233
|
+
socket.addEventListener("error", () => end("the terminal's socket failed"));
|
|
234
|
+
const terminal = {
|
|
235
|
+
socket,
|
|
236
|
+
onOutput: (listener) => {
|
|
237
|
+
outputs.push(listener);
|
|
238
|
+
for (const data of backlog.splice(0))
|
|
239
|
+
listener(data);
|
|
240
|
+
},
|
|
241
|
+
onEnd: (listener) => (ended === undefined ? ends.push(listener) : listener(ended)),
|
|
242
|
+
send: (data) => socket.send(JSON.stringify({ type: "input", data })),
|
|
243
|
+
close: () => {
|
|
244
|
+
try {
|
|
245
|
+
socket.close(1000);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
// Closed already.
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
seen: () => {
|
|
252
|
+
const total = [...kinds.values()].reduce((sum, n) => sum + n, 0);
|
|
253
|
+
return `${total} frame${total === 1 ? "" : "s"}${total === 0 ? "" : ` (${[...kinds].map(([kind, n]) => `${n} ${kind}`).join(", ")})`}`;
|
|
254
|
+
},
|
|
255
|
+
text: () => transcript,
|
|
256
|
+
ended: () => ended,
|
|
257
|
+
waitFor: (cond, ms) => new Promise((done) => {
|
|
258
|
+
if (cond())
|
|
259
|
+
return done(true);
|
|
260
|
+
const finish = (value) => {
|
|
261
|
+
clearTimeout(timer);
|
|
262
|
+
waiters.delete(check);
|
|
263
|
+
done(value);
|
|
264
|
+
};
|
|
265
|
+
const check = () => {
|
|
266
|
+
if (cond())
|
|
267
|
+
finish(true);
|
|
268
|
+
};
|
|
269
|
+
const timer = setTimeout(() => finish(cond()), ms);
|
|
270
|
+
waiters.add(check);
|
|
271
|
+
}),
|
|
272
|
+
};
|
|
273
|
+
const opened = await new Promise((settle) => {
|
|
274
|
+
const timer = setTimeout(() => settle(fail("timeout", `the terminal of ${computer} did not open within ${timeoutMs / 1000} s`)), timeoutMs);
|
|
275
|
+
socket.addEventListener("open", () => {
|
|
276
|
+
clearTimeout(timer);
|
|
277
|
+
settle(ok(undefined));
|
|
278
|
+
});
|
|
279
|
+
terminal.onEnd((words) => {
|
|
280
|
+
clearTimeout(timer);
|
|
281
|
+
settle(fail("orgo", `the terminal of ${computer} did not open: ${words}`));
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
if (!opened.ok) {
|
|
285
|
+
terminal.close();
|
|
286
|
+
return opened;
|
|
287
|
+
}
|
|
288
|
+
return ok(terminal);
|
|
289
|
+
};
|
|
290
|
+
return {
|
|
291
|
+
run: (computer, argv, { timeoutMs, signal }) => bash(computer, commandLine(argv), timeoutMs, signal),
|
|
292
|
+
async upload(computer, path, bytes, { timeoutMs, signal }) {
|
|
293
|
+
if (bytes.length > MAX_UPLOAD_BYTES)
|
|
294
|
+
return fail("invalid", `Orgo's upload takes at most 10 MB, and ${path} is ${bytes.length} bytes`);
|
|
295
|
+
const at = path.lastIndexOf("/");
|
|
296
|
+
if (at < 0 || path.slice(at + 1) === "")
|
|
297
|
+
return fail("invalid", `an upload goes to an absolute file path, not ${JSON.stringify(path)}`);
|
|
298
|
+
const form = new FormData();
|
|
299
|
+
form.set("file", new Blob([new Uint8Array(bytes)]), path.slice(at + 1));
|
|
300
|
+
form.set("workspaceId", workspaceId);
|
|
301
|
+
form.set("desktopId", computer);
|
|
302
|
+
form.set("destPath", path.slice(0, at) || "/");
|
|
303
|
+
const put = await rest.request("POST", "/files/upload", { form, timeoutMs, ...(signal ? { signal } : {}) });
|
|
304
|
+
return put.ok ? ok(undefined) : put;
|
|
305
|
+
},
|
|
306
|
+
async start(computer, argv, { how, timeoutMs, signal }) {
|
|
307
|
+
const detached = `${commandLine(argv)} </dev/null >>${START_LOG} 2>&1`;
|
|
308
|
+
if (how === "bash") {
|
|
309
|
+
const ran = await bash(computer, `setsid -f ${detached}`, timeoutMs, signal);
|
|
310
|
+
if (!ran.ok)
|
|
311
|
+
return ran;
|
|
312
|
+
return ran.value.exitCode === 0 ? ok(undefined) : fail("orgo", `starting ${argv[0]} from bash exited ${ran.value.exitCode}: ${ran.value.output.trim().slice(0, 300)}`);
|
|
313
|
+
}
|
|
314
|
+
const deadline = Date.now() + timeoutMs;
|
|
315
|
+
const terminal = await open(computer, { session: SESSION, timeoutMs, ...(signal ? { signal } : {}) });
|
|
316
|
+
if (!terminal.ok)
|
|
317
|
+
return terminal;
|
|
318
|
+
const typed = await typeLine(terminal.value, `exec ${detached}\r`, () => terminal.value.text().includes("exec "), { deadline, echoMs });
|
|
319
|
+
terminal.value.close();
|
|
320
|
+
return typed.ok ? ok(undefined) : fail(typed.error.code, `starting ${argv[0]} in the terminal session ${SESSION} failed: ${typed.error.message}`);
|
|
321
|
+
},
|
|
322
|
+
async stdio(computer, argv, { timeoutMs, signal }) {
|
|
323
|
+
const deadline = Date.now() + timeoutMs;
|
|
324
|
+
const opened = await open(computer, { timeoutMs, ...(signal ? { signal } : {}) });
|
|
325
|
+
if (!opened.ok)
|
|
326
|
+
return opened;
|
|
327
|
+
const terminal = opened.value;
|
|
328
|
+
const nonce = randomBytes(8).toString("hex");
|
|
329
|
+
const marker = `AGENTRUN-BRIDGE-${nonce}`;
|
|
330
|
+
const readable = new PassThrough();
|
|
331
|
+
let said = "";
|
|
332
|
+
let before = "";
|
|
333
|
+
let through = false;
|
|
334
|
+
let settle = () => { };
|
|
335
|
+
const ready = new Promise((done) => (settle = done));
|
|
336
|
+
terminal.onOutput((data) => {
|
|
337
|
+
if (through)
|
|
338
|
+
return void readable.write(data);
|
|
339
|
+
before = (before + data).slice(-65536);
|
|
340
|
+
const at = before.indexOf(marker);
|
|
341
|
+
if (at < 0)
|
|
342
|
+
return;
|
|
343
|
+
const after = before.slice(at + marker.length).replace(/^\r?\n/, "");
|
|
344
|
+
through = true;
|
|
345
|
+
settle(ok(undefined));
|
|
346
|
+
if (after !== "")
|
|
347
|
+
readable.write(after);
|
|
348
|
+
});
|
|
349
|
+
// What came before the marker, for the words of a bridge that never started: by kind, and its last bytes escaped.
|
|
350
|
+
const sent = () => `the terminal sent ${terminal.seen()} and no marker; its last bytes: ${JSON.stringify(before.slice(-300))}`;
|
|
351
|
+
terminal.onEnd((words) => {
|
|
352
|
+
said = words;
|
|
353
|
+
settle(fail("orgo", `computerd's bridge in ${computer} ended before it started: ${words}; ${sent()}`));
|
|
354
|
+
readable.end();
|
|
355
|
+
});
|
|
356
|
+
const late = (why) => fail("timeout", `computerd's bridge in ${computer} did not start within ${timeoutMs / 1000} s: ${why}; ${sent()}`);
|
|
357
|
+
// Typed once the shell prompts, and again if it never echoed (it was still starting); then the marker, by the deadline.
|
|
358
|
+
const line = `stty raw -echo; printf '%s%s\\n' AGENTRUN- BRIDGE-${nonce}; exec ${commandLine(argv)}\r`;
|
|
359
|
+
const typed = await typeLine(terminal, line, () => through || before.includes("stty raw -echo"), { deadline, echoMs });
|
|
360
|
+
if (!typed.ok)
|
|
361
|
+
settle(typed.error.code === "timeout" ? late(typed.error.message) : fail(typed.error.code, `computerd's bridge in ${computer} did not start: ${typed.error.message}; ${sent()}`));
|
|
362
|
+
else if (!(await terminal.waitFor(() => through || terminal.ended() !== undefined, Math.max(1, deadline - Date.now()))))
|
|
363
|
+
settle(late("the shell echoed the line and printed no marker"));
|
|
364
|
+
const started = await ready;
|
|
365
|
+
if (!started.ok) {
|
|
366
|
+
terminal.close();
|
|
367
|
+
return started;
|
|
368
|
+
}
|
|
369
|
+
const writable = new Writable({
|
|
370
|
+
write(chunk, _encoding, done) {
|
|
371
|
+
try {
|
|
372
|
+
terminal.send(chunk.toString("utf8"));
|
|
373
|
+
done();
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
done(error instanceof Error ? error : new Error(String(error)));
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
return ok({
|
|
381
|
+
readable,
|
|
382
|
+
writable,
|
|
383
|
+
close: async () => {
|
|
384
|
+
terminal.close();
|
|
385
|
+
readable.end();
|
|
386
|
+
},
|
|
387
|
+
said: () => said,
|
|
388
|
+
});
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|