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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +321 -308
  3. package/box/build-agent37.mjs +177 -0
  4. package/dist/agent37.d.ts +165 -0
  5. package/dist/agent37.js +759 -0
  6. package/dist/attach.d.ts +146 -0
  7. package/dist/attach.js +469 -0
  8. package/dist/browserbase.d.ts +2 -4
  9. package/dist/browserbase.js +2 -1
  10. package/dist/client.d.ts +33 -1
  11. package/dist/client.js +53 -0
  12. package/dist/computerd-linux-amd64 +0 -0
  13. package/dist/computerd-linux-arm64 +0 -0
  14. package/dist/conformance/agent37.d.ts +96 -0
  15. package/dist/conformance/agent37.js +154 -0
  16. package/dist/conformance/cases/apps.d.ts +5 -0
  17. package/dist/conformance/cases/apps.js +160 -73
  18. package/dist/conformance/cases/health.js +14 -0
  19. package/dist/conformance/cases/index.js +2 -0
  20. package/dist/conformance/cases/provider.js +27 -1
  21. package/dist/conformance/cases/screen.d.ts +3 -0
  22. package/dist/conformance/cases/screen.js +18 -0
  23. package/dist/conformance/cases/settings.d.ts +29 -23
  24. package/dist/conformance/cases/settings.js +76 -58
  25. package/dist/conformance/cases/touch.js +19 -17
  26. package/dist/conformance/cases/ui.d.ts +2 -0
  27. package/dist/conformance/cases/ui.js +475 -0
  28. package/dist/conformance/cli.d.ts +9 -0
  29. package/dist/conformance/cli.js +28 -3
  30. package/dist/conformance/e2b.d.ts +6 -0
  31. package/dist/conformance/e2b.js +9 -2
  32. package/dist/conformance/fixture.d.ts +1 -1
  33. package/dist/conformance/fixture.js +25 -1
  34. package/dist/conformance/modal.d.ts +17 -13
  35. package/dist/conformance/modal.js +18 -9
  36. package/dist/conformance/orgo.d.ts +3 -3
  37. package/dist/conformance/orgo.js +6 -8
  38. package/dist/conformance/phone-harness.d.ts +6 -2
  39. package/dist/conformance/phone-harness.js +21 -4
  40. package/dist/conformance/report.js +1 -1
  41. package/dist/conformance/runner.js +23 -4
  42. package/dist/conformance/sweep.d.ts +50 -0
  43. package/dist/conformance/sweep.js +187 -0
  44. package/dist/conformance/types.d.ts +11 -3
  45. package/dist/conformance/ui-fixture.d.ts +56 -0
  46. package/dist/conformance/ui-fixture.js +43 -0
  47. package/dist/create-requests.d.ts +51 -0
  48. package/dist/create-requests.js +121 -0
  49. package/dist/daytona.d.ts +2 -4
  50. package/dist/daytona.js +3 -2
  51. package/dist/descriptor.d.ts +5 -0
  52. package/dist/descriptor.js +2 -0
  53. package/dist/descriptors/agent37.d.ts +41 -0
  54. package/dist/descriptors/agent37.js +28 -0
  55. package/dist/descriptors/index.d.ts +38 -2
  56. package/dist/descriptors/index.js +4 -2
  57. package/dist/descriptors/orgo.d.ts +2 -1
  58. package/dist/descriptors/orgo.js +3 -2
  59. package/dist/descriptors/phone-harness.d.ts +1 -1
  60. package/dist/descriptors/phone-harness.js +2 -2
  61. package/dist/docker.d.ts +7 -4
  62. package/dist/docker.js +271 -29
  63. package/dist/e2b.d.ts +9 -165
  64. package/dist/e2b.js +282 -1342
  65. package/dist/fake-ui-driver.d.ts +97 -0
  66. package/dist/fake-ui-driver.js +717 -0
  67. package/dist/host.d.ts +182 -0
  68. package/dist/host.js +1 -0
  69. package/dist/hosted/process.d.ts +67 -0
  70. package/dist/hosted/process.js +228 -0
  71. package/dist/hosted/provider.d.ts +146 -0
  72. package/dist/hosted/provider.js +1364 -0
  73. package/dist/hosted/scripts.d.ts +76 -0
  74. package/dist/{child.js → hosted/scripts.js} +93 -12
  75. package/dist/index.d.ts +7 -3
  76. package/dist/index.js +7 -4
  77. package/dist/kernel.d.ts +2 -4
  78. package/dist/kernel.js +2 -1
  79. package/dist/kinds.d.ts +8 -1
  80. package/dist/kinds.js +20 -4
  81. package/dist/local-chrome.d.ts +2 -4
  82. package/dist/local-chrome.js +2 -1
  83. package/dist/modal.d.ts +23 -181
  84. package/dist/modal.js +271 -1244
  85. package/dist/orgo-channel.d.ts +3 -2
  86. package/dist/orgo-channel.js +5 -2
  87. package/dist/orgo-desktop.d.ts +9 -4
  88. package/dist/orgo-desktop.js +33 -13
  89. package/dist/orgo-workspaces.d.ts +47 -0
  90. package/dist/orgo-workspaces.js +94 -0
  91. package/dist/orgo.d.ts +10 -4
  92. package/dist/orgo.js +30 -12
  93. package/dist/phone-harness.d.ts +31 -22
  94. package/dist/phone-harness.js +510 -698
  95. package/dist/png.d.ts +4 -0
  96. package/dist/png.js +27 -0
  97. package/dist/protocol.d.ts +335 -32
  98. package/dist/protocol.js +96 -3
  99. package/dist/provider.d.ts +34 -6
  100. package/dist/provider.js +16 -0
  101. package/dist/result.d.ts +1 -1
  102. package/dist/surface/api.d.ts +248 -0
  103. package/dist/surface/api.js +1 -0
  104. package/dist/surface/core.d.ts +42 -0
  105. package/dist/surface/core.js +393 -0
  106. package/dist/surface/index.d.ts +5 -0
  107. package/dist/surface/index.js +3 -0
  108. package/dist/surface/outline.d.ts +8 -0
  109. package/dist/surface/outline.js +50 -0
  110. package/dist/surface/script.d.ts +10 -0
  111. package/dist/surface/script.js +92 -0
  112. package/dist/ui-engine.d.ts +114 -0
  113. package/dist/ui-engine.js +798 -0
  114. package/package.json +17 -1
  115. package/dist/child.d.ts +0 -42
  116. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  117. package/dist/conformance/e2b-diagnose.js +0 -61
  118. package/dist/conformance/e2b-sweep.d.ts +0 -18
  119. package/dist/conformance/e2b-sweep.js +0 -132
  120. package/dist/conformance/modal-sweep.d.ts +0 -22
  121. package/dist/conformance/modal-sweep.js +0 -213
package/dist/host.d.ts ADDED
@@ -0,0 +1,182 @@
1
+ import type { MountKind } from "./mount.js";
2
+ import type { ComputerCapabilities, ComputerSpec, GpuCapability, GpuSpec, NetworkForm, NetworkPolicy, Refusal } from "./provider.js";
3
+ import type { ComputerErrorCode, Result } from "./result.js";
4
+ /**
5
+ * One vendor's machines. Every call answers a Result: an expected failure (the vendor refused, the machine is not
6
+ * there) is a result with a code from errorCode, never a throw. A call that throws is read through errorCode as well.
7
+ * The adapter bounds each call by ctx.timeoutMs and ctx.signal; a host passes both on to its vendor call when it can.
8
+ */
9
+ export interface MachineHost {
10
+ /** The provider's descriptor id ("e2b"): the vendor named by every error of code vendor. */
11
+ readonly id: string;
12
+ readonly facts: HostFacts;
13
+ /**
14
+ * Makes one machine, by its options, and answers once the vendor has its id. It does not wait for the machine to run
15
+ * (the adapter polls get while it is starting) or to be listed (the adapter waits for that too). The machine carries
16
+ * req.name where the vendor can find it again by listing: the vendor's native name, or a label. An answer that never
17
+ * comes is not a machine the adapter forgets: it lists by req.labels and deletes what it finds.
18
+ */
19
+ create(req: MachineRequest, ctx: HostCall): Promise<Result<{
20
+ id: string;
21
+ }>>;
22
+ /** One machine as the vendor reads it now; undefined once the vendor no longer has it (not found is that, not an error). */
23
+ get(id: string, ctx: HostCall): Promise<Result<Machine | undefined>>;
24
+ /**
25
+ * Every machine of the account that carries all of these labels, every page, each as get reads it (network included,
26
+ * where the vendor reads one back), within ctx.timeoutMs in all. A machine the vendor is deleting may still be listed.
27
+ */
28
+ list(labels: Record<string, string>, ctx: HostCall): Promise<Result<Machine[]>>;
29
+ /** Deletes a machine; not found is ok. It answers once the vendor took the delete: the adapter waits for gone. */
30
+ delete(id: string, ctx: HostCall): Promise<Result<void>>;
31
+ /**
32
+ * Starts argv in the machine as root (the vendor's own command user when it is root, else one with passwordless
33
+ * sudo), the vendor's agent's own process, outside the computer's tools. With opts.stdin, the process reads what
34
+ * write() gives until end(). No command timeout: the adapter kills it, or it ends. Answers once it has started.
35
+ */
36
+ exec(id: string, argv: readonly string[], opts: {
37
+ stdin: boolean;
38
+ }, ctx: HostCall): Promise<Result<MachineProcess>>;
39
+ /**
40
+ * Puts bytes at path in the machine, as root. Optional: a vendor with no file API leaves it out, and the adapter
41
+ * streams the file through exec's stdin.
42
+ */
43
+ upload?(id: string, path: string, bytes: Uint8Array, ctx: HostCall): Promise<Result<void>>;
44
+ /** The code of an error the vendor's client threw: one of ComputerErrorCode, "vendor" for anything else. */
45
+ errorCode(error: unknown): ComputerErrorCode;
46
+ /** Vendor settings a machine takes once it runs and before the daemon goes in (egress rules, an idle timer). */
47
+ prepare?(id: string, ctx: HostCall): Promise<Result<void>>;
48
+ /** Stops a machine, keeping it; declared with facts.release "stop". It answers once the machine reads stopped (or gone with stopDeletes). */
49
+ stop?(id: string, ctx: HostCall): Promise<Result<void>>;
50
+ /**
51
+ * Moves the vendor's own timer (facts.lifetime "vendor") so the machine ends at want.end, never past want.most, the
52
+ * most it may live. A refusal (limit, in words) when no timer the vendor takes lands there without moving the end
53
+ * earlier than it is or past want.most: nothing moves then. The adapter reads the end back with get.
54
+ */
55
+ setTimer?(id: string, want: {
56
+ end: Date;
57
+ most: Date;
58
+ }, ctx: HostCall): Promise<Result<void>>;
59
+ /** Replaces some labels of a machine (the janitor's deadline label, at extend); facts.lifetime "janitor". */
60
+ setLabels?(id: string, labels: Record<string, string>, ctx: HostCall): Promise<Result<void>>;
61
+ /** The vendor's own rules of a spec, over the adapter's shared ones: an image name it takes, a GPU's image. No call. */
62
+ check?(spec: ComputerSpec): Refusal[];
63
+ /** Settings' test, where a list would make something (an app); default: one list by the adapter's label, counted. */
64
+ testConnection?(ctx: HostCall): Promise<Result<{
65
+ detail: string;
66
+ }>>;
67
+ }
68
+ /** Every call's bound: the adapter's timeout for this kind of call, and the caller's signal when it has one. */
69
+ export interface HostCall {
70
+ signal?: AbortSignal;
71
+ timeoutMs: number;
72
+ }
73
+ /** What create asks of the vendor: the adapter fills every field but the ones facts.specFields leaves out. */
74
+ export interface MachineRequest {
75
+ /** computer-<12 hex digits>, from the create's request id: the vendor's native name, or a label it lists by. */
76
+ name: string;
77
+ /** The image or template, as the spec names it (host.check holds it to the vendor's rule). */
78
+ image: string;
79
+ /** The caller's labels and the adapter's own (agentrun.computer*, the Archil mount's), every one to be read back. */
80
+ labels: Record<string, string>;
81
+ /** With facts.lifetime "vendor": the vendor's timer, the spec's lifetime. Absent for a janitor's machine. */
82
+ lifetimeMs?: number;
83
+ /**
84
+ * The vendor's network for the machine: "open" only for an Archil computer's root, which reaches Archil; its tools'
85
+ * network is init's own, none, read from inside.
86
+ */
87
+ network: "none" | "open";
88
+ /** facts.daemon "pid1" alone: the machine's main process (the entrypoint that waits for the daemon, then becomes init). */
89
+ command?: readonly string[];
90
+ gpu?: GpuSpec;
91
+ cpus?: number;
92
+ memoryMb?: number;
93
+ workdir?: string;
94
+ user?: string;
95
+ }
96
+ /** One machine as the vendor reads it back. */
97
+ export interface Machine {
98
+ id: string;
99
+ /** Every label it carries, the adapter's own included. */
100
+ labels: Record<string, string>;
101
+ /** starting: not yet running; going: being deleted or ended; failed: the vendor gave up on it (why says how). */
102
+ state: "starting" | "running" | "stopped" | "going" | "failed";
103
+ /** The vendor's own read of its network; absent when the vendor reads none back (the probe stands for it then). */
104
+ network?: NetworkPolicy;
105
+ /** What the vendor resolved the image to, by its own name (a template's id, a snapshot). */
106
+ image?: {
107
+ resolved?: string;
108
+ };
109
+ /**
110
+ * When the vendor made it, by its clock, where it says. Two creates of one request on two provider instances can each
111
+ * make a machine before either is listed: the oldest is kept, by this, or by the lowest id where a machine has none.
112
+ */
113
+ createdAt?: Date;
114
+ /** With facts.lifetime "vendor": when the vendor's timer ends it. */
115
+ endsAt?: Date;
116
+ /**
117
+ * With facts.lifetime "vendor": the vendor's timer was moved past where create set it (by an extend), so endsAt,
118
+ * held to the most the machine may live, stands for its deadline: the vendor keeps no label change.
119
+ */
120
+ timerMoved?: boolean;
121
+ /**
122
+ * The vendor's own create options read back wrong, in words, one each ("lifecycle onTimeout: declared ..."). Held at
123
+ * create and at attach alike, so only what holds for the machine's whole life: a timer an extend moved is timerMoved,
124
+ * never drift (create refuses a machine whose timer reads moved before any extend).
125
+ */
126
+ drift?: string[];
127
+ /** The size the vendor reads back, in CPUs and MiB: attach reports it. */
128
+ size?: {
129
+ cpus?: number;
130
+ memoryMb?: number;
131
+ };
132
+ gpu?: GpuSpec;
133
+ /** The vendor's words for a failed state. */
134
+ why?: string;
135
+ }
136
+ /** A process exec started: its output as it comes, its stdin, and its end. */
137
+ export interface MachineProcess {
138
+ stdout: AsyncIterable<Uint8Array>;
139
+ stderr: AsyncIterable<Uint8Array>;
140
+ /** Writes to its stdin, in order; rejects once the process has ended. */
141
+ write(bytes: Uint8Array): Promise<void>;
142
+ /** Ends its stdin, so it reads end of file. */
143
+ end(): Promise<void>;
144
+ /** Its exit code once it has ended. */
145
+ wait(): Promise<number>;
146
+ /** Ends it, best effort, and lets go of its streams; never throws. */
147
+ kill(): Promise<void>;
148
+ }
149
+ /** What a vendor's machines are, static: with the adapter's options, capabilities() is built from these alone. */
150
+ export interface HostFacts {
151
+ /** child: the vendor's agent is the machine's first process and starts init; pid1: init is the machine's main process. */
152
+ daemon: "child" | "pid1";
153
+ isolation: ComputerCapabilities["isolation"];
154
+ /** Who ends a machine at its deadline: the vendor's timer, or the janitor by label. */
155
+ lifetime: "vendor" | "janitor";
156
+ /** The vendor's hard cap of a machine's life; the adapter's maxLifetimeMs may only lower it. */
157
+ maxLifetimeMs: number;
158
+ arch: "amd64" | "arm64";
159
+ /** The TCP ports the vendor's own agent listens on inside the machine (E2B's envd 49983). */
160
+ vendorAgentPorts: number[];
161
+ /** Whether get reads the network back from the vendor. */
162
+ networkReadBack: boolean;
163
+ /** The network forms its computers take: of its descriptor's. */
164
+ network: NetworkForm[];
165
+ /** The mount kinds it takes: of its descriptor's. */
166
+ mounts?: MountKind[];
167
+ /** How release may end one; "stop" needs host.stop. */
168
+ release: Array<"stop" | "delete">;
169
+ stopDeletes?: boolean;
170
+ gpu?: GpuCapability;
171
+ /** What spec.user may ask for, beside the daemon user. */
172
+ user?: Array<"root" | "uid">;
173
+ /** The spec's size and place fields the vendor takes, passed in MachineRequest; any other is refused. */
174
+ specFields?: Array<"cpus" | "memoryMb" | "workdir" | "user">;
175
+ /** The vendor's label rules: how many labels a machine takes, and the names it takes. */
176
+ labelRules?: {
177
+ max?: number;
178
+ key?: RegExp;
179
+ };
180
+ /** The runtime a machine of this request runs: "gvisor" only where the vendor runs one (a pid1 host's GPU). */
181
+ runtime?(req: MachineRequest): "vm" | "gvisor";
182
+ }
package/dist/host.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import type { HostCall, MachineHost } from "../host.js";
2
+ import type { ArchilRoot } from "../mount-archil.js";
3
+ import type { ComputerConnection } from "../provider.js";
4
+ import { type ComputerErrorCode, type Result } from "../result.js";
5
+ /** What a call's race adds to the bound it gives the vendor's own call, so the vendor's timeout, not the race, reports a slow call. */
6
+ export declare const CALL_SLACK_MS = 5000;
7
+ export declare const seconds: (ms: number) => string;
8
+ /** An error in words, the vendor's name kept, cut to one line of 300 characters. */
9
+ export declare const words: (error: unknown) => string;
10
+ /** A pause that ends early when signal aborts; never rejects. */
11
+ export declare const pause: (ms: number, signal?: AbortSignal) => Promise<void>;
12
+ /** A signal that aborts with the caller's, or once ms pass. */
13
+ export declare const bounded: (ms: number, signal?: AbortSignal) => AbortSignal;
14
+ /** The failures of one host: an error of code vendor names it. */
15
+ export declare const failOf: (host: Pick<MachineHost, "id">) => (code: ComputerErrorCode, message: string) => Result<never>;
16
+ /**
17
+ * Settles with the promise's result, or a timeout or abort in words once ms pass or signal aborts. A host call that
18
+ * answers a Result is passed on as it answers; one that throws is read through the host's errorCode.
19
+ */
20
+ export declare function race<T>(host: Pick<MachineHost, "id" | "errorCode">, promise: Promise<T>, what: string, ms: number, signal?: AbortSignal): Promise<Result<T>>;
21
+ /**
22
+ * One host call, bounded: ctx.timeoutMs is the vendor's own bound, and the race gives it CALL_SLACK_MS more. A call
23
+ * that throws at once is an error like one that rejects; a Result the host answers keeps its own words, prefixed.
24
+ */
25
+ export declare function hostCall<T>(host: Pick<MachineHost, "id" | "errorCode">, what: string, run: (ctx: HostCall) => Promise<Result<T>>, ms: number, signal?: AbortSignal): Promise<Result<T>>;
26
+ /** What one process run to its end printed: its exit code, and both streams (each cut to its last 64 KiB). */
27
+ export interface RunResult {
28
+ exitCode: number;
29
+ stdout: string;
30
+ stderr: string;
31
+ }
32
+ /**
33
+ * argv run in the machine as root through exec, stdin (when given) written and ended, waited for until it ends, within
34
+ * ms and the caller's signal; a process past them is killed, and the kill waited for at most ms (and CALL_SLACK_MS).
35
+ * A non-zero exit is a result, not an error.
36
+ */
37
+ export declare function runToExit(host: MachineHost, id: string, argv: readonly string[], { stdin, ms, signal, what }: {
38
+ stdin?: Uint8Array;
39
+ ms: number;
40
+ signal?: AbortSignal;
41
+ what: string;
42
+ }): Promise<Result<RunResult>>;
43
+ /** The default upload, for a vendor with no file API: the bytes streamed into `cat` as root through exec's stdin. */
44
+ export declare function uploadThroughExec(host: MachineHost, id: string, path: string, bytes: Uint8Array, ms: number, signal?: AbortSignal): Promise<Result<void>>;
45
+ /**
46
+ * The root channel into a machine (for the shared Archil steps): argv as root through exec, stdin (one line, then
47
+ * closed) when given. What it printed is both streams, stdout first; a non-zero exit is a result. An error never holds
48
+ * what stdin was given.
49
+ */
50
+ export declare function rootOf(host: MachineHost, id: string, name: string): ArchilRoot;
51
+ /** A connection the bridge opened, with why it could not be: notListening when no daemon listens yet (try again). */
52
+ export type Opened = Result<ComputerConnection> & {
53
+ notListening?: true;
54
+ };
55
+ /**
56
+ * One connection to the daemon over a process the stdio command runs: its stdout is what the client reads, writes go to
57
+ * its stdin in order, and close kills it. Hello is asked within helloMs; a bridge that ended before hello, with no
58
+ * daemon to reach, is notListening.
59
+ */
60
+ export declare function openBridge(host: MachineHost, id: string, { argv, name, version, requestMs, helloMs, signal }: {
61
+ argv: readonly string[];
62
+ name: string;
63
+ version: string;
64
+ requestMs: number;
65
+ helloMs: number;
66
+ signal?: AbortSignal;
67
+ }): Promise<Opened>;
@@ -0,0 +1,228 @@
1
+ // The adapter's plumbing over a MachineHost: one bounded call, a process run to its end, a file put through exec when
2
+ // the vendor has no file API, the root channel an Archil mount runs through, and the stdio bridge that carries the
3
+ // daemon's wire over one exec'd process.
4
+ import { PassThrough, Writable } from "node:stream";
5
+ import { DaemonClient } from "../client.js";
6
+ import { errorOf, ok } from "../result.js";
7
+ /** What a call's race adds to the bound it gives the vendor's own call, so the vendor's timeout, not the race, reports a slow call. */
8
+ export const CALL_SLACK_MS = 5_000;
9
+ export const seconds = (ms) => `${ms / 1000} s`;
10
+ /** An error in words, the vendor's name kept, cut to one line of 300 characters. */
11
+ export const words = (error) => {
12
+ const name = error?.name;
13
+ const message = error instanceof Error ? error.message : String(error);
14
+ return `${typeof name === "string" && name !== "Error" ? `${name}: ` : ""}${message}`.replace(/\s+/g, " ").slice(0, 300);
15
+ };
16
+ /** A pause that ends early when signal aborts; never rejects. */
17
+ export const pause = (ms, signal) => new Promise((done) => {
18
+ const timer = setTimeout(finish, ms);
19
+ function finish() {
20
+ clearTimeout(timer);
21
+ signal?.removeEventListener("abort", finish);
22
+ done();
23
+ }
24
+ if (signal?.aborted)
25
+ finish();
26
+ else
27
+ signal?.addEventListener("abort", finish, { once: true });
28
+ });
29
+ /** A signal that aborts with the caller's, or once ms pass. */
30
+ export const bounded = (ms, signal) => (signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms));
31
+ /** The failures of one host: an error of code vendor names it. */
32
+ export const failOf = (host) => (code, message) => ({ ok: false, error: errorOf(code, message, host.id) });
33
+ /**
34
+ * Settles with the promise's result, or a timeout or abort in words once ms pass or signal aborts. A host call that
35
+ * answers a Result is passed on as it answers; one that throws is read through the host's errorCode.
36
+ */
37
+ export function race(host, promise, what, ms, signal) {
38
+ const fail = failOf(host);
39
+ if (signal?.aborted) {
40
+ promise.catch(() => { });
41
+ return Promise.resolve(fail("aborted", `${what} was aborted`));
42
+ }
43
+ return new Promise((settle) => {
44
+ const timer = setTimeout(() => done(fail("timeout", `${what} did not answer within ${seconds(ms)}`)), ms);
45
+ const onAbort = () => done(fail("aborted", `${what} was aborted`));
46
+ signal?.addEventListener("abort", onAbort, { once: true });
47
+ let settled = false;
48
+ function done(result) {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ clearTimeout(timer);
53
+ signal?.removeEventListener("abort", onAbort);
54
+ settle(result);
55
+ }
56
+ promise.then((value) => done(ok(value)), (error) => done(signal?.aborted ? fail("aborted", `${what} was aborted`) : fail(host.errorCode(error), `${what} failed: ${words(error)}`)));
57
+ });
58
+ }
59
+ /**
60
+ * One host call, bounded: ctx.timeoutMs is the vendor's own bound, and the race gives it CALL_SLACK_MS more. A call
61
+ * that throws at once is an error like one that rejects; a Result the host answers keeps its own words, prefixed.
62
+ */
63
+ export async function hostCall(host, what, run, ms, signal) {
64
+ const fail = failOf(host);
65
+ if (signal?.aborted)
66
+ return fail("aborted", `${what} was aborted before it was called`);
67
+ let promise;
68
+ try {
69
+ promise = Promise.resolve(run({ timeoutMs: ms, ...(signal ? { signal } : {}) }));
70
+ }
71
+ catch (error) {
72
+ return fail(host.errorCode(error), `${what} failed: ${words(error)}`);
73
+ }
74
+ const raced = await race(host, promise, what, ms + CALL_SLACK_MS, signal);
75
+ if (!raced.ok)
76
+ return raced;
77
+ const answered = raced.value;
78
+ if (answered.ok)
79
+ return answered;
80
+ return { ok: false, error: { ...answered.error, message: `${what} failed: ${answered.error.message}` } };
81
+ }
82
+ /** Reads every chunk of a stream into one buffer, at most `max` bytes kept (the last ones). */
83
+ async function drain(stream, max) {
84
+ let kept = Buffer.alloc(0);
85
+ try {
86
+ for await (const chunk of stream) {
87
+ kept = Buffer.concat([kept, Buffer.from(chunk)]);
88
+ if (kept.length > max)
89
+ kept = kept.subarray(kept.length - max);
90
+ }
91
+ }
92
+ catch {
93
+ // A stream that ends in an error has given what it had.
94
+ }
95
+ return kept;
96
+ }
97
+ const OUTPUT_MAX = 64 * 1024;
98
+ /**
99
+ * argv run in the machine as root through exec, stdin (when given) written and ended, waited for until it ends, within
100
+ * ms and the caller's signal; a process past them is killed, and the kill waited for at most ms (and CALL_SLACK_MS).
101
+ * A non-zero exit is a result, not an error.
102
+ */
103
+ export async function runToExit(host, id, argv, { stdin, ms, signal, what }) {
104
+ const fail = failOf(host);
105
+ const started = await hostCall(host, what, (ctx) => host.exec(id, argv, { stdin: stdin !== undefined }, ctx), ms, signal);
106
+ if (!started.ok)
107
+ return started;
108
+ const proc = started.value;
109
+ const out = drain(proc.stdout, OUTPUT_MAX);
110
+ const err = drain(proc.stderr, OUTPUT_MAX);
111
+ const ran = (async () => {
112
+ if (stdin !== undefined) {
113
+ // In pieces, so a vendor whose stdin takes one request at a time (E2B's sendStdin) is never handed a whole binary.
114
+ for (let at = 0; at < stdin.length; at += STDIN_CHUNK)
115
+ await proc.write(stdin.subarray(at, at + STDIN_CHUNK));
116
+ await proc.end();
117
+ }
118
+ const exitCode = await proc.wait();
119
+ return { exitCode, stdout: (await out).toString("utf8"), stderr: (await err).toString("utf8") };
120
+ })();
121
+ const result = await race(host, ran, what, ms + CALL_SLACK_MS, signal);
122
+ if (!result.ok) {
123
+ // Bounded, as the bridge's close is: a kill the vendor never answers (a remote call that stalls) must not hold
124
+ // up the caller, which may be a create on its way to deleting the whole machine.
125
+ const killing = Promise.resolve().then(() => proc.kill());
126
+ await race(host, killing, `${what}'s kill`, Math.min(ms, CALL_SLACK_MS));
127
+ return result.error.code === "timeout" ? fail("timeout", `${what} did not end within ${seconds(ms)}`) : result;
128
+ }
129
+ return result;
130
+ }
131
+ const STDIN_CHUNK = 256 * 1024;
132
+ /** The default upload, for a vendor with no file API: the bytes streamed into `cat` as root through exec's stdin. */
133
+ export async function uploadThroughExec(host, id, path, bytes, ms, signal) {
134
+ const ran = await runToExit(host, id, ["sh", "-c", 'umask 077 && cat > "$1"', "sh", path], { stdin: bytes, ms, ...(signal ? { signal } : {}), what: `the upload to ${path}` });
135
+ if (!ran.ok)
136
+ return ran;
137
+ return ran.value.exitCode === 0 ? ok(undefined) : failOf(host)("vendor", `the upload to ${path} exited with ${ran.value.exitCode}: ${`${ran.value.stdout} ${ran.value.stderr}`.trim().slice(0, 300)}`);
138
+ }
139
+ /**
140
+ * The root channel into a machine (for the shared Archil steps): argv as root through exec, stdin (one line, then
141
+ * closed) when given. What it printed is both streams, stdout first; a non-zero exit is a result. An error never holds
142
+ * what stdin was given.
143
+ */
144
+ export function rootOf(host, id, name) {
145
+ return {
146
+ run: async (argv, { stdin, timeoutMs, signal }) => {
147
+ const ran = await runToExit(host, id, argv, { ...(stdin === undefined ? {} : { stdin: new Uint8Array(Buffer.from(stdin, "utf8")) }), ms: timeoutMs, ...(signal ? { signal } : {}), what: `root's ${argv[0] === undefined ? "command" : argv[0].split("/").pop()} in ${name}` });
148
+ return ran.ok ? ok({ exitCode: ran.value.exitCode, output: `${ran.value.stdout}${ran.value.stderr}` }) : ran;
149
+ },
150
+ };
151
+ }
152
+ /**
153
+ * One connection to the daemon over a process the stdio command runs: its stdout is what the client reads, writes go to
154
+ * its stdin in order, and close kills it. Hello is asked within helloMs; a bridge that ended before hello, with no
155
+ * daemon to reach, is notListening.
156
+ */
157
+ export async function openBridge(host, id, { argv, name, version, requestMs, helloMs, signal }) {
158
+ const fail = failOf(host);
159
+ const what = `starting the daemon's stdio bridge in ${name}`;
160
+ if (signal?.aborted)
161
+ return fail("aborted", `${what} was aborted before it was called`);
162
+ let starting;
163
+ try {
164
+ starting = Promise.resolve(host.exec(id, argv, { stdin: true }, { timeoutMs: requestMs }));
165
+ }
166
+ catch (error) {
167
+ return fail(host.errorCode(error), `${what} failed: ${words(error)}`);
168
+ }
169
+ const raced = await race(host, starting, what, requestMs + CALL_SLACK_MS, signal);
170
+ if (!raced.ok) {
171
+ // The bridge has no command timeout: one the vendor starts after this was given up on is killed as it lands.
172
+ if (raced.error.code === "timeout" || raced.error.code === "aborted") {
173
+ starting.then((late) => (late.ok ? late.value.kill() : undefined), () => { });
174
+ return fail(raced.error.code, `${raced.error.message}; a bridge that starts after this is killed`);
175
+ }
176
+ return raced;
177
+ }
178
+ if (!raced.value.ok)
179
+ return fail(raced.value.error.code, `${what} failed: ${raced.value.error.message}`);
180
+ const proc = raced.value.value;
181
+ const readable = new PassThrough();
182
+ let stderr = "";
183
+ void (async () => {
184
+ try {
185
+ for await (const chunk of proc.stdout)
186
+ if (!readable.destroyed)
187
+ readable.write(Buffer.from(chunk));
188
+ }
189
+ catch {
190
+ // The bridge's end, for any reason, ends what the client reads.
191
+ }
192
+ readable.end();
193
+ })();
194
+ void (async () => {
195
+ try {
196
+ for await (const chunk of proc.stderr)
197
+ stderr = (stderr + Buffer.from(chunk).toString("utf8")).slice(-4096);
198
+ }
199
+ catch {
200
+ // Its words are what came before.
201
+ }
202
+ })();
203
+ const writable = new Writable({
204
+ write(chunk, _encoding, done) {
205
+ proc.write(new Uint8Array(chunk)).then(() => done(), (error) => done(error instanceof Error ? error : new Error(String(error))));
206
+ },
207
+ });
208
+ const client = new DaemonClient({ readable, writable });
209
+ let closed;
210
+ const close = () => (closed ??= (async () => {
211
+ client.close();
212
+ await race(host, proc.kill(), "the stdio bridge's kill", requestMs).catch(() => { });
213
+ })());
214
+ const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${version}` }, { signal: bounded(helloMs, signal) });
215
+ if (!hello.ok) {
216
+ await close();
217
+ if (signal?.aborted)
218
+ return fail("aborted", `hello to the daemon in ${name} was aborted`);
219
+ if (hello.error.code === "aborted")
220
+ return fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(helloMs)}`);
221
+ if (hello.error.code !== "gone")
222
+ return hello;
223
+ // Its stderr may come a moment after its stdout ended.
224
+ await pause(20);
225
+ return { ...fail("vendor", `cannot reach the daemon in ${name}: ${stderr.trim() || hello.error.message}`), notListening: true };
226
+ }
227
+ return ok({ client, hello: hello.value, close });
228
+ }
@@ -0,0 +1,146 @@
1
+ import { type DesktopOptions } from "../desktop.js";
2
+ import type { Machine, MachineHost } from "../host.js";
3
+ import { type ProviderNote } from "../mount-archil.js";
4
+ import { type AttachedComputer, type AttachContext, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreateContext, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseContext, type ReleaseHow } from "../provider.js";
5
+ import { type Result } from "../result.js";
6
+ import { type ScreenWatch, type ScreenWatchHandlers, type WatchOptions } from "../screen-watch.js";
7
+ /** The longest each kind of call may take, and the pauses between polls. */
8
+ export interface HostedTimeouts {
9
+ /** One control-plane call: get, delete, a timer, a bridge's start. */
10
+ requestMs: number;
11
+ /** The vendor's create, and the wait until the machine runs. */
12
+ createMs: number;
13
+ /** The daemon's upload. */
14
+ uploadMs: number;
15
+ /** The install command, and init's start. */
16
+ execMs: number;
17
+ /** From a connect's start to the daemon's hello, and each read-back call after it. */
18
+ helloMs: number;
19
+ /** The probe, run through the daemon: it takes at most 20 s (10 s to connect, 10 s to answer, every target at once). */
20
+ probeMs: number;
21
+ /** One whole list, every page and every machine's read-back. */
22
+ listMs: number;
23
+ /** From a delete to a machine the vendor no longer has and no longer lists. */
24
+ goneMs: number;
25
+ /** The first pause between two reads while release waits; the pauses double up to 5 s. */
26
+ pollMs: number;
27
+ /** How long create waits for the listing to show the new computer. */
28
+ listedMs: number;
29
+ /**
30
+ * The listing's stability window: create's wait ends once the listing has shown the new computer on two consecutive
31
+ * polls, the first of them at least this long before the last, and on every poll between.
32
+ */
33
+ listedStableMs: number;
34
+ /** Each root step of an Archil mount (the preflight, mount or revoke, serve), and its checkin at release. */
35
+ mountMs: number;
36
+ }
37
+ export interface HostedOptions {
38
+ /** The vendor's name in words ("E2B"), for refusals and Settings' test. */
39
+ label: string;
40
+ /** desktop: an X server started through the daemon; linux (default): no screen. */
41
+ kind?: "desktop" | "linux";
42
+ /** The display and its X server, for kind desktop. Default Xvfb on :0, 1280x800. */
43
+ desktop?: DesktopOptions;
44
+ /** The longest lifetime check takes; at most facts.maxLifetimeMs, which is its default. */
45
+ maxLifetimeMs?: number;
46
+ /** The daemon binary for the host's arch on this machine. Default this package's dist/computerd-linux-<arch>. */
47
+ daemonPath?: string;
48
+ /**
49
+ * Who the daemon runs as, uid:gid in numbers, never root. Default 2510:2510 (TOOL_USER), a uid no vendor process
50
+ * holds: init refuses to start while another process does.
51
+ */
52
+ daemonUser?: string;
53
+ timeouts?: Partial<HostedTimeouts>;
54
+ /**
55
+ * The addresses the probe tries, to show none of them answers a computer with network none: host:port over TCP, or
56
+ * host:port/udp, a DNS query over UDP.
57
+ */
58
+ probeTargets?: string[];
59
+ /** Told what is no failure of the call it came from: a release that did not let an Archil folder go cleanly. */
60
+ onNote?: ProviderNote;
61
+ /**
62
+ * The egress gateway an Archil computer's archil client reaches Archil through, `<IPv4 gateway>:<mount lane>:<data
63
+ * lane>` such as 192.0.2.40:18100:42050 (archilEgressOf): for a vendor whose machines reach Archil only through it.
64
+ * Given to the helper's mount and revoke. Unset or empty, the client reaches Archil as the machine's network allows.
65
+ */
66
+ archilEgress?: string;
67
+ }
68
+ export declare const NAME_LABEL = "agentrun.computer.name";
69
+ /** The image create was asked for: a vendor may report another name for it (a template's id). */
70
+ export declare const IMAGE_LABEL = "agentrun.computer.image";
71
+ /** The most extend may move the deadline to: create's time plus the cap, by this machine's clock, as init was given. */
72
+ export declare const MAX_LABEL = "agentrun.computer.max-deadline";
73
+ /**
74
+ * When a machine ends: the deadline create wrote; or, once an extend moved the vendor's own timer past where create set
75
+ * it (the vendor keeps no label change), that end, up to the most the computer may live, which is what init was given.
76
+ */
77
+ export declare function deadlineOf(machine: Pick<Machine, "labels" | "endsAt" | "timerMoved">): Date | undefined;
78
+ /** Only a machine this adapter made counts: its label, a name of its making, and the name asked for when one is. */
79
+ export declare const ours: (labels: Record<string, string> | undefined, name?: string) => boolean;
80
+ type Extend = (ref: ComputerRef, ttlMs: number, context?: CallContext) => Promise<Result<{
81
+ deadline: Date;
82
+ }>>;
83
+ /** hostedProvider's provider: a ComputerProvider whose vendor is host. */
84
+ export declare class HostedProvider implements ComputerProvider {
85
+ #private;
86
+ readonly id: string;
87
+ readonly version: string;
88
+ /** The vendor's machines, for the live sweep (conformance/sweep.ts); nothing else reaches past the provider to them. */
89
+ readonly host: MachineHost;
90
+ readonly extend?: Extend;
91
+ constructor(host: MachineHost, options: HostedOptions);
92
+ /** The computer's facts, from the host's and the adapter's options alone. */
93
+ capabilities(): ComputerCapabilities;
94
+ check(spec: ComputerSpec): Refusal[];
95
+ /**
96
+ * Makes a computer, once per request: context.requestId names it (computerNameFor), and a create of a request already made
97
+ * finds that computer instead of making another. One still starting is waited for (within createMs); one up is
98
+ * returned once its labels and daemon read back as attach reads them, else refused as exists; one that ended (or
99
+ * that this provider gave up on) is refused as exists, in words. A second create of a request still in flight waits
100
+ * for the first and answers what it does.
101
+ */
102
+ create(spec: ComputerSpec, context: CreateContext): Promise<Result<CreatedComputer>>;
103
+ /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
104
+ watch(ref: ComputerRef, handlers: ScreenWatchHandlers, options?: WatchOptions): Promise<Result<ScreenWatch>>;
105
+ connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
106
+ attach(ref: {
107
+ id: string;
108
+ } | {
109
+ labels: Record<string, string>;
110
+ }, { signal }?: AttachContext): Promise<Result<AttachedComputer>>;
111
+ /**
112
+ * Settings' test: the host's own, or one list by the adapter's label, counted, which makes nothing; a refused key is
113
+ * unauthorized, a vendor not reached unreachable, the message never carrying a key.
114
+ */
115
+ testConnection({ signal }?: CallContext): Promise<Result<{
116
+ detail: string;
117
+ }>>;
118
+ /**
119
+ * Every computer this provider made that carries all of these labels, running or stopped, each one's network read
120
+ * back. One deadline, listMs from the call, bounds every page and every read-back.
121
+ */
122
+ list(labels: Record<string, string>, { signal }?: CallContext): Promise<Result<ComputerInfo[]>>;
123
+ /** The vendor reads the policy back (or the probe stands for it). A change is refused: the network is fixed at create. */
124
+ network(ref: ComputerRef, policy?: NetworkSpec, { signal }?: CallContext): Promise<Result<NetworkPolicy>>;
125
+ /**
126
+ * delete reads the machine back to check it is this provider's, then deletes it, both never signalled, so a release
127
+ * after an abort, or one aborted during the read, still sends the delete; it is idempotent: one the vendor no longer
128
+ * has is ok. The vendor answers a delete before the machine is gone, so release then waits (#settle) until the vendor
129
+ * reads it gone and no longer lists it, within goneMs and the caller's signal, the one step the signal ends. A running
130
+ * Archil computer lets go of the run's folder first (archilRelease: the final sync through computerd, then checkin as
131
+ * root); the delete runs whatever that answers. A folder not let go cleanly loses nothing (every call that changed it
132
+ * synced, and the next claim revokes the hold), so it is said through onNote, and the release succeeds once the
133
+ * machine is gone. stop, where the host declares it, stops the machine and keeps it.
134
+ */
135
+ release(ref: ComputerRef, how: ReleaseHow, { signal }?: ReleaseContext): Promise<Result<void>>;
136
+ }
137
+ /**
138
+ * Waits until the host reads a machine gone and no longer lists it under its name, twice running (see #settle). Shared
139
+ * with the live sweep, which waits the same way.
140
+ */
141
+ export declare function settleGone(host: MachineHost, ref: ComputerRef, { requestMs, listMs, pollMs, goneMs, signal }: Pick<HostedTimeouts, "requestMs" | "listMs" | "pollMs" | "goneMs"> & {
142
+ signal?: AbortSignal;
143
+ }): Promise<Result<void>>;
144
+ /** The shared machine-host adapter: host's machines as a ComputerProvider (see HostedProvider). */
145
+ export declare function hostedProvider(host: MachineHost, options: HostedOptions): HostedProvider;
146
+ export {};