@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31
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/CHANGELOG.md +238 -0
- package/README.md +739 -116
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +18 -7
- package/dist/agents.js +19 -10
- package/dist/app.js +101 -26
- package/dist/background.d.ts +29 -0
- package/dist/background.js +397 -0
- package/dist/box-egress-vm.d.ts +125 -0
- package/dist/box-egress-vm.js +350 -0
- package/dist/box-egress.d.ts +99 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +84 -0
- package/dist/box-relay-vm.js +410 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +28 -5
- package/dist/boxes.js +44 -18
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +130 -21
- package/dist/cap.js +339 -67
- package/dist/cli.js +30 -4
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-CnJBf7Lc.js +486 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/decisions.d.ts +3 -3
- package/dist/decisions.js +4 -3
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +9 -1
- package/dist/files.js +10 -2
- package/dist/grade.d.ts +11 -11
- package/dist/grade.js +43 -55
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +110 -19
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-check.d.ts +12 -0
- package/dist/host-check.js +34 -0
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +6 -2
- package/dist/learn/grade.js +28 -14
- package/dist/learn/index.d.ts +3 -3
- package/dist/learn/index.js +3 -3
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +53 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +19 -4
- package/dist/learn/skills.js +95 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +30 -1
- package/dist/learning-routes.js +173 -19
- package/dist/learning-run.d.ts +8 -6
- package/dist/learning-run.js +70 -27
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +34 -13
- package/dist/learning.d.ts +52 -3
- package/dist/learning.js +204 -4
- package/dist/mcp-gateway.d.ts +96 -0
- package/dist/mcp-gateway.js +408 -0
- package/dist/mcp-meta.d.ts +17 -0
- package/dist/mcp-meta.js +38 -0
- package/dist/mcp-servers.d.ts +33 -9
- package/dist/mcp-servers.js +58 -10
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +407 -54
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -0
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +29 -5
- package/dist/place.js +51 -11
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +183 -23
- package/dist/runnable.d.ts +13 -3
- package/dist/runnable.js +63 -6
- package/dist/runs.d.ts +266 -37
- package/dist/runs.js +884 -90
- package/dist/secrets.d.ts +27 -0
- package/dist/secrets.js +38 -2
- package/dist/server.d.ts +141 -36
- package/dist/server.js +562 -118
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +281 -0
- package/dist/tool-gate.js +585 -0
- package/dist/tool-keys.d.ts +48 -11
- package/dist/tool-keys.js +46 -8
- package/dist/tool-plane.d.ts +116 -27
- package/dist/tool-plane.js +232 -50
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +148 -26
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/web-fetch.js +3 -3
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +16 -14
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// The box relay's VM half: how a run's process reaches its VM box without the VM provider's token. The token and the SDK
|
|
2
|
+
// client are the server's alone (boxes.ts, BOX_KEYS), so a run's process runs pi-transport's VM provider over a client of
|
|
3
|
+
// its own (relayedVmSdk) whose every call comes here, on loopback with its run's own door token (box-relay.ts checks it),
|
|
4
|
+
// and is made here with the server's client only when it is one of the calls a run's tools make of that run's own box:
|
|
5
|
+
// find it, read its state and its tags, start a program in it, and that program's input, output and exit. Nothing else
|
|
6
|
+
// passes: no create, listing, end or tag change (the server makes and seeds the box, pulls its work/ back and ends it),
|
|
7
|
+
// and no call to a sandbox that does not carry the run's label. The SDK speaks gRPC, so the relay carries its calls, not
|
|
8
|
+
// its bytes on the wire: each program started here is held by an id of its own until its exit is read and its output
|
|
9
|
+
// streams are done.
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { relayAddress } from "./box-relay.js";
|
|
12
|
+
import { redacted } from "./key-refusal.js";
|
|
13
|
+
/** The label that names a box's run (run-box.ts RUN_LABEL), kept here so the run's process loads no more than it needs. */
|
|
14
|
+
const RUN_LABEL = "agentrun.run";
|
|
15
|
+
/** The most bytes one relayed write to a program's input may send. */
|
|
16
|
+
const MAX_INPUT_BYTES = 64 * 2 ** 20;
|
|
17
|
+
/** The most programs one run may hold here at once. */
|
|
18
|
+
const MAX_EXECS_PER_RUN = 64;
|
|
19
|
+
/** How many bytes of a program's output stream the relay holds before it stops reading the stream, until the run's
|
|
20
|
+
* process reads them. */
|
|
21
|
+
const MAX_BUFFERED_BYTES = 16 * 2 ** 20;
|
|
22
|
+
/** How long a program the run's process stopped asking about is held, once it exited. A program is let go:
|
|
23
|
+
* - once its exit was read (or failed to be) and both its output replies ended, whole or broken (settle);
|
|
24
|
+
* - at once when a caller goes away mid-read (the reply's close);
|
|
25
|
+
* - at the run's end (drop), whatever it is doing, a program still starting then included, as it lands;
|
|
26
|
+
* - else EXEC_KEEP_MS after its exit: an exit or an output not read yet is still the caller's to read.
|
|
27
|
+
* A program still running holds its slot until it exits or the run ends. */
|
|
28
|
+
const EXEC_KEEP_MS = 10 * 60_000;
|
|
29
|
+
/** The most sandboxes the relay remembers the run of; past it, it asks the provider again. */
|
|
30
|
+
const KNOWN_MAX = 1024;
|
|
31
|
+
/** Its message is the SDK's, which can quote anything: cut of every value the server holds, and of secret-shaped text,
|
|
32
|
+
* by serve's one rule (key-refusal.ts redacted), before it goes to the run's process. */
|
|
33
|
+
const failureOf = (error, secrets = []) => {
|
|
34
|
+
const name = error?.constructor?.name ?? "Error";
|
|
35
|
+
const code = error?.code;
|
|
36
|
+
return { name, ...(typeof code === "number" ? { code } : {}), message: redacted(String(error?.message ?? error), secrets).slice(0, 300) };
|
|
37
|
+
};
|
|
38
|
+
function pump(source) {
|
|
39
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
40
|
+
const state = {
|
|
41
|
+
chunks: [], bytes: 0, done: false, cancelled: false,
|
|
42
|
+
// Let go: what it holds is dropped, the source's read is ended, and whoever waits on it is woken.
|
|
43
|
+
cancel() {
|
|
44
|
+
if (state.cancelled)
|
|
45
|
+
return;
|
|
46
|
+
state.cancelled = true;
|
|
47
|
+
state.chunks.length = 0;
|
|
48
|
+
state.bytes = 0;
|
|
49
|
+
state.done = true;
|
|
50
|
+
void Promise.resolve(iterator.return?.()).catch(() => undefined);
|
|
51
|
+
state.space?.();
|
|
52
|
+
state.wake?.();
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
void (async () => {
|
|
56
|
+
try {
|
|
57
|
+
for (;;) {
|
|
58
|
+
const next = await iterator.next();
|
|
59
|
+
if (next.done || state.cancelled)
|
|
60
|
+
break;
|
|
61
|
+
state.chunks.push(next.value);
|
|
62
|
+
state.bytes += next.value.length;
|
|
63
|
+
state.wake?.();
|
|
64
|
+
while (state.bytes > MAX_BUFFERED_BYTES && !state.cancelled)
|
|
65
|
+
await new Promise((resolve) => (state.space = resolve));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (!state.cancelled)
|
|
70
|
+
state.failure = error ?? new Error("the stream failed");
|
|
71
|
+
}
|
|
72
|
+
state.done = true;
|
|
73
|
+
state.wake?.();
|
|
74
|
+
})();
|
|
75
|
+
return state;
|
|
76
|
+
}
|
|
77
|
+
/** The relay's handler of a run's VM calls, over the server's client `sdk`: `handle(runId, path, req, res)` answers the
|
|
78
|
+
* call at `path` (what follows `/runs/<id>/vm/`), the caller's token already checked. `drop(runId)` lets go of the run's
|
|
79
|
+
* programs (at its end). */
|
|
80
|
+
export function vmRelay(sdk, secrets = () => []) {
|
|
81
|
+
const known = new Map();
|
|
82
|
+
const execs = new Map();
|
|
83
|
+
/** The program starts each run has under way, from the moment its request is taken (before the sandbox's lookup): each
|
|
84
|
+
* counts toward the run's limit, and one its run's end (drop) marks is let go as it lands, never held. A run is here
|
|
85
|
+
* only while it has one, so an ended run leaves nothing behind. */
|
|
86
|
+
const starting = new Map();
|
|
87
|
+
const startOf = (runId) => {
|
|
88
|
+
const start = { dropped: false };
|
|
89
|
+
const starts = starting.get(runId) ?? new Set();
|
|
90
|
+
starts.add(start);
|
|
91
|
+
starting.set(runId, starts);
|
|
92
|
+
return start;
|
|
93
|
+
};
|
|
94
|
+
const started = (runId, start) => {
|
|
95
|
+
const starts = starting.get(runId);
|
|
96
|
+
starts?.delete(start);
|
|
97
|
+
if (starts && !starts.size)
|
|
98
|
+
starting.delete(runId);
|
|
99
|
+
};
|
|
100
|
+
/** Sandbox `id` and the run its label names, as the provider says; undefined when it has none. */
|
|
101
|
+
const sandboxOf = async (id) => {
|
|
102
|
+
const held = known.get(id);
|
|
103
|
+
if (held)
|
|
104
|
+
return held;
|
|
105
|
+
const sandbox = await sdk.sandboxes.fromId(id);
|
|
106
|
+
const tags = await sandbox.getTags();
|
|
107
|
+
const value = { sandbox, run: typeof tags[RUN_LABEL] === "string" ? tags[RUN_LABEL] : undefined };
|
|
108
|
+
if (known.size >= KNOWN_MAX)
|
|
109
|
+
known.clear();
|
|
110
|
+
known.set(id, value);
|
|
111
|
+
return value;
|
|
112
|
+
};
|
|
113
|
+
const answer = (res, status, body) => {
|
|
114
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
115
|
+
res.end(JSON.stringify(body));
|
|
116
|
+
};
|
|
117
|
+
const failed = (res, error) => void (res.headersSent ? res.destroy() : answer(res, 502, { failure: failureOf(error, secrets()) }));
|
|
118
|
+
const notThere = (res) => answer(res, 404, { failure: { name: "NotFoundError", code: 5, message: "no such sandbox" } });
|
|
119
|
+
const refused = (res, path) => answer(res, 403, { message: `the box relay does not make ${path}: a run's process reaches only its own box's programs and files` });
|
|
120
|
+
const forget = (id) => {
|
|
121
|
+
const held = execs.get(id);
|
|
122
|
+
if (held?.timer)
|
|
123
|
+
clearTimeout(held.timer);
|
|
124
|
+
// Its streams' reads end with it, and a reply still writing one is let go.
|
|
125
|
+
held?.streams.stdout.cancel();
|
|
126
|
+
held?.streams.stderr.cancel();
|
|
127
|
+
execs.delete(id);
|
|
128
|
+
};
|
|
129
|
+
/** A program is let go once its exit was read and both its streams' replies ended (delivered whole, or broken because
|
|
130
|
+
* the stream failed), or EXEC_KEEP_MS after its exit. */
|
|
131
|
+
const settle = (id) => {
|
|
132
|
+
const held = execs.get(id);
|
|
133
|
+
if (!held || held.exited === undefined)
|
|
134
|
+
return;
|
|
135
|
+
if (held.waited && held.finished.size === 2)
|
|
136
|
+
return forget(id);
|
|
137
|
+
held.timer ??= setTimeout(() => forget(id), EXEC_KEEP_MS);
|
|
138
|
+
held.timer.unref?.();
|
|
139
|
+
};
|
|
140
|
+
async function handle(runId, path, req, res) {
|
|
141
|
+
if (req.method !== "POST")
|
|
142
|
+
return answer(res, 405, { message: "the Modal sandbox relay takes POST" });
|
|
143
|
+
const onSandbox = /^sandbox\/([^/]+)\/(find|poll|tags|exec)$/.exec(path);
|
|
144
|
+
// A start is under way from here: a run's end while its sandbox is looked up, or its program started, still finds it.
|
|
145
|
+
const start = onSandbox?.[2] === "exec" ? startOf(runId) : undefined;
|
|
146
|
+
if (onSandbox)
|
|
147
|
+
try {
|
|
148
|
+
const id = decodeURIComponent(onSandbox[1]);
|
|
149
|
+
let found;
|
|
150
|
+
try {
|
|
151
|
+
found = await sandboxOf(id);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return failureOf(error).name === "NotFoundError" || failureOf(error).code === 5 ? notThere(res) : failed(res, error);
|
|
155
|
+
}
|
|
156
|
+
// A sandbox of another run, or of none, is not there for this one: as the provider answers one it does not have.
|
|
157
|
+
if (found.run !== runId)
|
|
158
|
+
return notThere(res);
|
|
159
|
+
try {
|
|
160
|
+
switch (onSandbox[2]) {
|
|
161
|
+
case "find":
|
|
162
|
+
return answer(res, 200, { id });
|
|
163
|
+
case "poll":
|
|
164
|
+
return answer(res, 200, { code: await found.sandbox.poll() });
|
|
165
|
+
case "tags":
|
|
166
|
+
return answer(res, 200, { tags: await found.sandbox.getTags() });
|
|
167
|
+
default: {
|
|
168
|
+
const body = (await jsonOf(req));
|
|
169
|
+
const command = body?.command;
|
|
170
|
+
if (!Array.isArray(command) || !command.length || !command.every((part) => typeof part === "string"))
|
|
171
|
+
return answer(res, 400, { message: "exec names its command: a list of strings" });
|
|
172
|
+
// Its slot was taken as the request came (startOf), and is given back once the program is held or did not start.
|
|
173
|
+
const others = (starting.get(runId)?.size ?? 1) - 1;
|
|
174
|
+
if ([...execs.values()].filter((held) => held.run === runId).length + others >= MAX_EXECS_PER_RUN)
|
|
175
|
+
return answer(res, 429, { message: `a run holds at most ${MAX_EXECS_PER_RUN} programs in its box at once` });
|
|
176
|
+
const process = await found.sandbox.exec(command, { mode: "binary", ...(typeof body?.workdir === "string" ? { workdir: body.workdir } : {}), ...(typeof body?.timeoutMs === "number" ? { timeoutMs: body.timeoutMs } : {}) });
|
|
177
|
+
// The run's programs were let go while this one started (its end): it is let go too, its output never read.
|
|
178
|
+
if (start.dropped) {
|
|
179
|
+
for (const stream of [process.stdout, process.stderr])
|
|
180
|
+
void Promise.resolve(stream[Symbol.asyncIterator]().return?.()).catch(() => undefined);
|
|
181
|
+
return answer(res, 410, { message: "the run ended while the program started: it is not held" });
|
|
182
|
+
}
|
|
183
|
+
const exec = randomUUID();
|
|
184
|
+
const held = { run: runId, process, streams: { stdout: pump(process.stdout), stderr: pump(process.stderr) }, waited: false, read: new Set(), finished: new Set() };
|
|
185
|
+
execs.set(exec, held);
|
|
186
|
+
process.wait().then((code) => {
|
|
187
|
+
held.exited = code;
|
|
188
|
+
settle(exec);
|
|
189
|
+
}, () => {
|
|
190
|
+
held.exited = -1;
|
|
191
|
+
settle(exec);
|
|
192
|
+
});
|
|
193
|
+
return answer(res, 200, { exec });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
return failed(res, error);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
if (start)
|
|
203
|
+
started(runId, start);
|
|
204
|
+
}
|
|
205
|
+
const onExec = /^exec\/([^/]+)\/(stdin|stdin-close|stdout|stderr|wait)$/.exec(path);
|
|
206
|
+
if (!onExec)
|
|
207
|
+
return refused(res, path);
|
|
208
|
+
const id = decodeURIComponent(onExec[1]);
|
|
209
|
+
const held = execs.get(id);
|
|
210
|
+
// Another run's program is not there for this one.
|
|
211
|
+
if (!held || held.run !== runId)
|
|
212
|
+
return answer(res, 404, { message: "no such program" });
|
|
213
|
+
try {
|
|
214
|
+
switch (onExec[2]) {
|
|
215
|
+
case "stdin": {
|
|
216
|
+
const bytes = await bytesOf(req);
|
|
217
|
+
if (bytes === null)
|
|
218
|
+
return answer(res, 413, { message: `a write sends at most ${MAX_INPUT_BYTES} bytes` });
|
|
219
|
+
await held.process.stdin.writeBytes(new Uint8Array(bytes));
|
|
220
|
+
return answer(res, 200, {});
|
|
221
|
+
}
|
|
222
|
+
case "stdin-close":
|
|
223
|
+
await held.process.stdin.close();
|
|
224
|
+
return answer(res, 200, {});
|
|
225
|
+
case "wait": {
|
|
226
|
+
// The exit is read whether the provider gives it or fails to: either way the caller has its answer, and the
|
|
227
|
+
// program goes once its streams' replies have ended.
|
|
228
|
+
let code;
|
|
229
|
+
try {
|
|
230
|
+
code = await held.process.wait();
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
held.waited = true;
|
|
234
|
+
held.exited ??= -1;
|
|
235
|
+
failed(res, error);
|
|
236
|
+
return settle(id);
|
|
237
|
+
}
|
|
238
|
+
held.waited = true;
|
|
239
|
+
answer(res, 200, { code });
|
|
240
|
+
return settle(id);
|
|
241
|
+
}
|
|
242
|
+
default: {
|
|
243
|
+
const name = onExec[2];
|
|
244
|
+
if (held.read.has(name))
|
|
245
|
+
return answer(res, 409, { message: `the program's ${name} is read once` });
|
|
246
|
+
held.read.add(name);
|
|
247
|
+
const stream = held.streams[name];
|
|
248
|
+
res.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store" });
|
|
249
|
+
// A caller that goes away (its process ended, or it stopped reading) lets the stream go: its read is ended and
|
|
250
|
+
// nothing waits on it.
|
|
251
|
+
let gone = false;
|
|
252
|
+
let woke = () => { };
|
|
253
|
+
res.once("close", () => {
|
|
254
|
+
if (res.writableFinished)
|
|
255
|
+
return;
|
|
256
|
+
gone = true;
|
|
257
|
+
stream.cancel();
|
|
258
|
+
woke();
|
|
259
|
+
});
|
|
260
|
+
for (;;) {
|
|
261
|
+
while (stream.chunks.length && !gone) {
|
|
262
|
+
const chunk = stream.chunks.shift();
|
|
263
|
+
stream.bytes -= chunk.length;
|
|
264
|
+
stream.space?.();
|
|
265
|
+
if (!res.write(chunk))
|
|
266
|
+
await new Promise((resolve) => {
|
|
267
|
+
woke = resolve;
|
|
268
|
+
res.once("drain", resolve);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
if (stream.done || gone)
|
|
272
|
+
break;
|
|
273
|
+
await new Promise((resolve) => (stream.wake = woke = resolve));
|
|
274
|
+
}
|
|
275
|
+
if (gone)
|
|
276
|
+
return void forget(id);
|
|
277
|
+
// A stream that broke, or was let go before it was all sent (the run's end), is a broken answer, never a short
|
|
278
|
+
// one: the caller sees its read fail.
|
|
279
|
+
if (stream.failure !== undefined || stream.cancelled)
|
|
280
|
+
res.destroy();
|
|
281
|
+
else
|
|
282
|
+
res.end();
|
|
283
|
+
// Ended either way: a failed stream holds no slot once its exit is read too.
|
|
284
|
+
held.finished.add(name);
|
|
285
|
+
settle(id);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
return failed(res, error);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return {
|
|
295
|
+
handle,
|
|
296
|
+
drop(runId) {
|
|
297
|
+
for (const start of starting.get(runId) ?? [])
|
|
298
|
+
start.dropped = true;
|
|
299
|
+
for (const [id, held] of execs)
|
|
300
|
+
if (held.run === runId)
|
|
301
|
+
forget(id);
|
|
302
|
+
},
|
|
303
|
+
/** What the relay holds now, for the tests: its programs, and the runs with a start under way. */
|
|
304
|
+
footprint: () => ({ programs: execs.size, starting: starting.size }),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
async function bytesOf(req) {
|
|
308
|
+
const parts = [];
|
|
309
|
+
let size = 0;
|
|
310
|
+
for await (const part of req) {
|
|
311
|
+
size += part.length;
|
|
312
|
+
if (size > MAX_INPUT_BYTES)
|
|
313
|
+
return null;
|
|
314
|
+
parts.push(part);
|
|
315
|
+
}
|
|
316
|
+
return Buffer.concat(parts);
|
|
317
|
+
}
|
|
318
|
+
const jsonOf = async (req) => {
|
|
319
|
+
const bytes = await bytesOf(req);
|
|
320
|
+
try {
|
|
321
|
+
return bytes ? JSON.parse(bytes.toString("utf8") || "null") : null;
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
/** An error as the SDK would throw it, from the relay's answer: its class's name, so pi-transport's provider reads it the
|
|
328
|
+
* same (NotFoundError, a gRPC code). */
|
|
329
|
+
function errorOf(failure, fallback) {
|
|
330
|
+
const name = failure?.name && /^[A-Za-z]+$/.test(failure.name) ? failure.name : "Error";
|
|
331
|
+
const Named = { [name]: class extends Error {
|
|
332
|
+
} }[name];
|
|
333
|
+
return Object.assign(new Named(failure?.message ?? fallback), typeof failure?.code === "number" ? { code: failure.code } : {});
|
|
334
|
+
}
|
|
335
|
+
/** How the run's process's relay client waits on the relay: never on a clock of its own. A program's exit (`wait`) and
|
|
336
|
+
* its output streams take as long as the program runs, which its caller bounds (bash's timeout, and pi-transport's
|
|
337
|
+
* backstop over it); Node's own fetch would give up after 300 s with no answer or no bytes, failing a longer command
|
|
338
|
+
* as lost. */
|
|
339
|
+
export const RELAY_AGENT_OPTIONS = Object.freeze({ headersTimeout: 0, bodyTimeout: 0 });
|
|
340
|
+
/** The SDK client a run's process hands pi-transport's VM provider: each call it makes of a box goes to the relay in data
|
|
341
|
+
* root `root`, with the run's own door token. It finds a sandbox and runs programs in it; it makes, lists and ends none. */
|
|
342
|
+
export function relayedVmSdk(root, runDir, runId, agentOptions = RELAY_AGENT_OPTIONS) {
|
|
343
|
+
// Its own dispatcher, with the waits above: made at its first call, kept for the process.
|
|
344
|
+
let opened;
|
|
345
|
+
const open = () => (opened ??= import("undici").then(({ Agent, fetch }) => ({ dispatcher: new Agent(agentOptions), dial: fetch })));
|
|
346
|
+
const call = async (path, body, json = true) => {
|
|
347
|
+
const [{ url, token }, { dispatcher, dial }] = await Promise.all([relayAddress(root, runDir), open()]);
|
|
348
|
+
return dial(`${url}/runs/${encodeURIComponent(runId)}/vm/${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, ...(json ? { "content-type": "application/json" } : { "content-type": "application/octet-stream" }) }, ...(body === undefined ? {} : { body: body }), redirect: "error", dispatcher });
|
|
349
|
+
};
|
|
350
|
+
const result = async (path, body) => {
|
|
351
|
+
const answer = await call(path, body === undefined ? undefined : JSON.stringify(body));
|
|
352
|
+
const value = (await answer.json().catch(() => null));
|
|
353
|
+
if (!answer.ok)
|
|
354
|
+
throw errorOf(value?.failure, value?.message ?? `the box relay answered ${answer.status}`);
|
|
355
|
+
return value;
|
|
356
|
+
};
|
|
357
|
+
/** A program's output stream: read from the relay once its reader starts, failing as the relay's answer fails. */
|
|
358
|
+
const stream = (exec, name) => ({
|
|
359
|
+
async *[Symbol.asyncIterator]() {
|
|
360
|
+
const answer = await call(`exec/${exec}/${name}`);
|
|
361
|
+
if (!answer.ok || !answer.body)
|
|
362
|
+
throw errorOf(undefined, `the box relay answered ${answer.status} to the program's ${name}`);
|
|
363
|
+
for await (const chunk of answer.body)
|
|
364
|
+
yield chunk;
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
const sandbox = (sandboxId) => {
|
|
368
|
+
const at = `sandbox/${encodeURIComponent(sandboxId)}`;
|
|
369
|
+
return {
|
|
370
|
+
sandboxId,
|
|
371
|
+
poll: async () => (await result(`${at}/poll`, {})).code,
|
|
372
|
+
getTags: async () => (await result(`${at}/tags`, {})).tags,
|
|
373
|
+
terminate: async () => {
|
|
374
|
+
throw new Error("a run's process ends no box: the server does");
|
|
375
|
+
},
|
|
376
|
+
exec: async (command, params) => {
|
|
377
|
+
const { exec } = await result(`${at}/exec`, { command, ...(params.workdir ? { workdir: params.workdir } : {}), ...(params.timeoutMs === undefined ? {} : { timeoutMs: params.timeoutMs }) });
|
|
378
|
+
const id = encodeURIComponent(exec);
|
|
379
|
+
return {
|
|
380
|
+
stdin: {
|
|
381
|
+
writeBytes: async (bytes) => {
|
|
382
|
+
const answer = await call(`exec/${id}/stdin`, bytes, false);
|
|
383
|
+
if (!answer.ok)
|
|
384
|
+
throw errorOf((await answer.json().catch(() => null))?.failure, `the box relay answered ${answer.status} to a write`);
|
|
385
|
+
},
|
|
386
|
+
close: async () => void (await result(`exec/${id}/stdin-close`, {})),
|
|
387
|
+
},
|
|
388
|
+
stdout: stream(id, "stdout"),
|
|
389
|
+
stderr: stream(id, "stderr"),
|
|
390
|
+
wait: async () => (await result(`exec/${id}/wait`, {})).code,
|
|
391
|
+
};
|
|
392
|
+
},
|
|
393
|
+
};
|
|
394
|
+
};
|
|
395
|
+
const none = (what) => () => {
|
|
396
|
+
throw new Error(`a run's process ${what} no box: the server does`);
|
|
397
|
+
};
|
|
398
|
+
return {
|
|
399
|
+
apps: { fromName: none("names") },
|
|
400
|
+
images: { fromRegistry: none("names"), fromId: none("names") },
|
|
401
|
+
sandboxes: {
|
|
402
|
+
create: none("makes"),
|
|
403
|
+
list: none("lists"),
|
|
404
|
+
fromId: async (id) => {
|
|
405
|
+
await result(`sandbox/${encodeURIComponent(id)}/find`, {});
|
|
406
|
+
return sandbox(id);
|
|
407
|
+
},
|
|
408
|
+
},
|
|
409
|
+
};
|
|
410
|
+
}
|
package/dist/box-relay.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { vmRelay } from "./box-relay-vm.js";
|
|
1
2
|
/** The relay's address in the data directory: `{"url": "http://<loopback>:<port>"}`. */
|
|
2
3
|
export declare const BOX_RELAY_FILE = ".box-relay";
|
|
3
4
|
/** What a run's Daytona provider sends as its key: never a key. The relay sends the server's in its place. */
|
|
@@ -7,12 +8,14 @@ export type BoxRelayOptions = {
|
|
|
7
8
|
root: string;
|
|
8
9
|
/** Run `runId`'s own door token, which a call for that run must carry; undefined for a run that has none. */
|
|
9
10
|
tokenOf(runId: string): string | undefined;
|
|
10
|
-
/** Daytona's API and the server's key for it. */
|
|
11
|
-
apiUrl
|
|
12
|
-
apiKey
|
|
11
|
+
/** Daytona's API and the server's key for it; absent on a server with no Daytona box. */
|
|
12
|
+
apiUrl?: string;
|
|
13
|
+
apiKey?: string;
|
|
13
14
|
/** For tests. Default the global `fetch`. */
|
|
14
15
|
fetch?: typeof fetch;
|
|
15
|
-
/**
|
|
16
|
+
/** The VM half (box-relay-vm.ts), on a server with the VM box. */
|
|
17
|
+
vm?: ReturnType<typeof vmRelay>;
|
|
18
|
+
/** Whether `runId` is a run this server holds in a remote box that has not ended. */
|
|
16
19
|
serves(runId: string): boolean;
|
|
17
20
|
/** The run's box, found by its label or made with its work/ seeded (run-box.ts ensureRemoteBox): its id, and whether it is new. */
|
|
18
21
|
ensure(runId: string): Promise<{
|
|
@@ -38,5 +41,5 @@ export declare const relayFetch: (root: string, runDir: string, runId: string) =
|
|
|
38
41
|
export declare function relayedBox(root: string, runDir: string, runId: string, signal?: AbortSignal): Promise<{
|
|
39
42
|
id: string;
|
|
40
43
|
made: boolean;
|
|
41
|
-
apiUrl
|
|
44
|
+
apiUrl?: string;
|
|
42
45
|
}>;
|
package/dist/box-relay.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
// token is not this one), no create, listing, stop or delete (the server makes and seeds the box, pulls its work/ back
|
|
7
7
|
// and destroys it), no call to a sandbox that does not carry the run's label, and no redirect, ever followed: one would
|
|
8
8
|
// carry the key. The relay's address is a file in the data directory, read again at each call, so a run's process that
|
|
9
|
-
// outlives its server reaches the next one.
|
|
9
|
+
// outlives its server reaches the next one. A run in the VM box reaches it the same way, through the VM half
|
|
10
|
+
// (box-relay-vm.ts), which makes the calls with the server's own client.
|
|
10
11
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
11
12
|
import { readFile, rm } from "node:fs/promises";
|
|
12
13
|
import { createServer } from "node:http";
|
|
@@ -33,9 +34,9 @@ const KNOWN_MAX = 1024;
|
|
|
33
34
|
const digest = (text) => createHash("sha256").update(text).digest();
|
|
34
35
|
/** Starts the relay on loopback and writes its address; `close` stops it and removes the address. */
|
|
35
36
|
export async function startBoxRelay(options) {
|
|
36
|
-
const base = options.apiUrl.replace(/\/+$/, "");
|
|
37
|
+
const base = (options.apiUrl ?? "").replace(/\/+$/, "");
|
|
37
38
|
const upstream = options.fetch ?? fetch;
|
|
38
|
-
const api = { apiUrl: base, apiKey: options.apiKey, ...(options.fetch ? { fetch: options.fetch } : {}) };
|
|
39
|
+
const api = { apiUrl: base, apiKey: options.apiKey ?? "", ...(options.fetch ? { fetch: options.fetch } : {}) };
|
|
39
40
|
// Each sandbox's run (its label) and its toolbox's address, as Daytona answered the server: neither changes.
|
|
40
41
|
const known = new Map();
|
|
41
42
|
const remember = (id, value) => {
|
|
@@ -140,7 +141,7 @@ export async function startBoxRelay(options) {
|
|
|
140
141
|
};
|
|
141
142
|
const server = createServer((req, res) => {
|
|
142
143
|
void (async () => {
|
|
143
|
-
const path = /^\/runs\/([^/]+)\/(box|daytona)$/.exec(new URL(req.url ?? "/", "http://relay").pathname);
|
|
144
|
+
const path = /^\/runs\/([^/]+)\/(box|daytona|vm\/.+)$/.exec(new URL(req.url ?? "/", "http://relay").pathname);
|
|
144
145
|
const runId = path ? decodeURIComponent(path[1]) : "";
|
|
145
146
|
// The calling run's own token, and only for its own run: one run's process never speaks for another's.
|
|
146
147
|
const token = path ? options.tokenOf(runId) : undefined;
|
|
@@ -148,14 +149,18 @@ export async function startBoxRelay(options) {
|
|
|
148
149
|
if (!path || !token || !timingSafeEqual(digest(auth), digest(`Bearer ${token}`)))
|
|
149
150
|
return answer(res, 401, { message: "the box relay takes a run's call only with that run's own door token" });
|
|
150
151
|
if (!options.serves(runId))
|
|
151
|
-
return answer(res, 404, { message: "no run of this server is in a
|
|
152
|
+
return answer(res, 404, { message: "no run of this server is in a remote box by that id" });
|
|
152
153
|
if (path[2] === "box") {
|
|
153
154
|
if (req.method !== "POST")
|
|
154
155
|
return answer(res, 405, { message: "POST asks for the run's box" });
|
|
155
156
|
const box = await options.ensure(runId);
|
|
156
157
|
remember(box.id, { run: runId });
|
|
157
|
-
return answer(res, 200, { id: box.id, made: box.made, api_url: base });
|
|
158
|
+
return answer(res, 200, { id: box.id, made: box.made, ...(options.apiKey ? { api_url: base } : {}) });
|
|
158
159
|
}
|
|
160
|
+
if (path[2].startsWith("vm/"))
|
|
161
|
+
return options.vm ? options.vm.handle(runId, path[2].slice(3), req, res) : answer(res, 404, { message: "this server has no Modal sandbox" });
|
|
162
|
+
if (!options.apiKey)
|
|
163
|
+
return answer(res, 404, { message: "this server has no Daytona box" });
|
|
159
164
|
return forward(runId, req, res);
|
|
160
165
|
})().catch((error) => {
|
|
161
166
|
if (res.headersSent)
|
|
@@ -199,7 +204,7 @@ export async function relayAddress(root, runDir) {
|
|
|
199
204
|
const [file, token] = await Promise.all([readJson(join(root, BOX_RELAY_FILE)), readFile(join(runDir, RUN_DOOR_TOKEN), "utf8").catch(() => "")]);
|
|
200
205
|
const url = file && typeof file === "object" && !Array.isArray(file) && typeof file.url === "string" ? file.url : undefined;
|
|
201
206
|
if (!url || !token.trim())
|
|
202
|
-
throw new Error("this server's box relay is not running, and a run reaches its
|
|
207
|
+
throw new Error("this server's box relay is not running, and a run reaches its remote box only through it");
|
|
203
208
|
return { url, token: token.trim() };
|
|
204
209
|
}
|
|
205
210
|
/** The `fetch` a run's Daytona provider uses: each call goes to the relay, which sends it on with the key. */
|
|
@@ -215,8 +220,8 @@ export async function relayedBox(root, runDir, runId, signal) {
|
|
|
215
220
|
const { url, token } = await relayAddress(root, runDir);
|
|
216
221
|
const sent = await fetch(`${url}/runs/${encodeURIComponent(runId)}/box`, { method: "POST", headers: { authorization: `Bearer ${token}` }, redirect: "error", ...(signal ? { signal } : {}) });
|
|
217
222
|
const body = (await sent.json().catch(() => null));
|
|
218
|
-
if (!sent.ok || typeof body?.id !== "string"
|
|
223
|
+
if (!sent.ok || typeof body?.id !== "string") {
|
|
219
224
|
throw new Error(`the server did not give the run its box: ${typeof body?.message === "string" ? body.message : `it answered ${sent.status}`}`);
|
|
220
225
|
}
|
|
221
|
-
return { id: body.id, made: body.made === true, apiUrl: body.api_url };
|
|
226
|
+
return { id: body.id, made: body.made === true, ...(typeof body.api_url === "string" ? { apiUrl: body.api_url } : {}) };
|
|
222
227
|
}
|
package/dist/boxes.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { BoxProvider } from "@parcha/pi-transport";
|
|
2
|
+
/** Why the VM box has no network, said in capabilities whenever the server's host list is set: its provider's SDK takes
|
|
3
|
+
* a domain list at a sandbox's create, but has no read of a sandbox's network back, so the server could not check that
|
|
4
|
+
* a box holds the list it asked for (as it does Daytona's), and it never leaves the provider's open default either. */
|
|
5
|
+
export declare const VM_NO_LIST = "the Modal sandbox takes a host list, but this server cannot read a sandbox's list back to check that it holds, so the Modal sandbox has no network";
|
|
2
6
|
/** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
|
|
3
7
|
export declare const VM_PROVIDER: {
|
|
4
8
|
readonly id: "modal";
|
|
@@ -10,12 +14,20 @@ export declare const BOX_IDS: readonly ["bwrap", "docker", "modal", "daytona"];
|
|
|
10
14
|
export type BoxId = (typeof BOX_IDS)[number];
|
|
11
15
|
/** One box: whether this server has it, and why when not (or how it was checked). `state`, set where the server knows
|
|
12
16
|
* more than the probe did (box-image.ts): `preparing` is available, its image still coming. */
|
|
17
|
+
/** A box as capabilities show it. `network`: what an available box reaches (BOX_NETWORKS), with `network_reason` when
|
|
18
|
+
* it is available and has none for a cause of its own (a Docker in a VM, a daemon elsewhere; a Daytona that could not
|
|
19
|
+
* keep its domain list). */
|
|
13
20
|
export type BoxOffer = {
|
|
14
21
|
id: BoxId;
|
|
15
22
|
available: boolean;
|
|
16
23
|
state?: BoxState;
|
|
17
24
|
reason?: string;
|
|
25
|
+
network?: BoxNetwork;
|
|
26
|
+
network_reason?: string;
|
|
18
27
|
};
|
|
28
|
+
/** What an available box reaches: the hosts of `places.allow` (`allowlist`), or nothing (`none`). */
|
|
29
|
+
export declare const BOX_NETWORKS: readonly ["allowlist", "none"];
|
|
30
|
+
export type BoxNetwork = (typeof BOX_NETWORKS)[number];
|
|
19
31
|
/** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
|
|
20
32
|
export declare const BOX_STATES: readonly ["ready", "preparing", "unavailable"];
|
|
21
33
|
export type BoxState = (typeof BOX_STATES)[number];
|
|
@@ -25,9 +37,19 @@ export type BoxRegistry = {
|
|
|
25
37
|
offers(): BoxOffer[];
|
|
26
38
|
/** An available box's provider; undefined for any other. */
|
|
27
39
|
provider(id: BoxId): BoxProvider | undefined;
|
|
40
|
+
/** The VM box's SDK client, when it is available: the box relay makes a run's calls with it (box-relay-vm.ts). */
|
|
41
|
+
vmClient(): unknown;
|
|
28
42
|
};
|
|
29
|
-
/**
|
|
43
|
+
/** What boxRegistry takes beyond the environment: the probes' bound, and, for tests only, the module that stands in for
|
|
44
|
+
* the VM provider's SDK (startServe's `fauxVm`, under --faux). */
|
|
45
|
+
export type BoxRegistryOptions = {
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
vmSdk?: () => Promise<Record<string, unknown>>;
|
|
48
|
+
};
|
|
49
|
+
/** The setting that lists the boxes to set up: a comma list of box ids, empty or `none` for no box. */
|
|
30
50
|
export declare const BOXES_ENV = "AGENTRUN_BOXES";
|
|
51
|
+
/** The boxes a server sets up when AGENTRUN_BOXES is not set at all: Docker, probed as if listed. */
|
|
52
|
+
export declare const DEFAULT_BOXES: readonly BoxId[];
|
|
31
53
|
/** The VM provider's app, which its sandboxes live in (made when missing). */
|
|
32
54
|
export declare const BOX_APP_ENV = "AGENTRUN_BOX_APP";
|
|
33
55
|
/** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
|
|
@@ -42,13 +64,14 @@ export declare function daytonaApi(env: NodeJS.ProcessEnv): {
|
|
|
42
64
|
export declare const BOX_KEYS: readonly string[];
|
|
43
65
|
/** How long one box's probe may take; the probes run at once, so this bounds them all. */
|
|
44
66
|
export declare const PROBE_TIMEOUT_MS = 5000;
|
|
45
|
-
/**
|
|
67
|
+
/** Whether `env` leaves the boxes to this server's default (DEFAULT_BOXES): AGENTRUN_BOXES is not set at all. */
|
|
68
|
+
export declare const boxesByDefault: (env: NodeJS.ProcessEnv) => boolean;
|
|
69
|
+
/** The boxes `env` lists in AGENTRUN_BOXES, DEFAULT_BOXES when it is not set, none when it is empty or `none`; a name
|
|
70
|
+
* that is no box throws, naming it, and so does `none` with another. */
|
|
46
71
|
export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
|
|
47
72
|
/** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
|
|
48
73
|
* `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
|
|
49
74
|
* unavailable, with a short reason that holds no key and no answer's body. */
|
|
50
|
-
export declare function boxRegistry(env: NodeJS.ProcessEnv, options?:
|
|
51
|
-
timeoutMs?: number;
|
|
52
|
-
}): Promise<BoxRegistry>;
|
|
75
|
+
export declare function boxRegistry(env: NodeJS.ProcessEnv, options?: BoxRegistryOptions): Promise<BoxRegistry>;
|
|
53
76
|
/** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
|
|
54
77
|
export declare function boxesLog(offers: readonly BoxOffer[], listed: ReadonlySet<BoxId>): Record<string, string>;
|