@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
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 +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- 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 +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- 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 +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { BoxRecord, Reaped } from "@parcha/agentrun-kernel/host";
|
|
2
|
+
/** The data directory's file of quarantined boxes. */
|
|
3
|
+
export declare const BOX_QUARANTINE = "box-quarantine.json";
|
|
4
|
+
/** What serve needs of the box: its reap, and on a shared server the run cgroups under its delegated subtree. */
|
|
5
|
+
export interface BoxHost {
|
|
6
|
+
reap(record: BoxRecord): Promise<Reaped>;
|
|
7
|
+
cgroups?: {
|
|
8
|
+
/** Every run cgroup under the subtree, by path. */
|
|
9
|
+
list(): Promise<string[]>;
|
|
10
|
+
/** Removes an empty cgroup. */
|
|
11
|
+
remove(path: string): Promise<void>;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** A process's start time as /proc/<pid>/stat gives it (clock ticks since boot), or undefined when it is not running. */
|
|
15
|
+
export declare function startTimeOf(pid: number): string | undefined;
|
|
16
|
+
/** The record's writer is gone: no process has its pid, or the one that has it started at another time (a reused pid).
|
|
17
|
+
* box-image.ts asks the same of the server that wrote the image's record. */
|
|
18
|
+
export declare function writerGone(writer: BoxRecord["writer"] | undefined): boolean;
|
|
19
|
+
/** The boxes that a reap could not let go, kept across restarts: by run (or "" for a cgroup no record named). */
|
|
20
|
+
export declare class Quarantine {
|
|
21
|
+
private readonly file;
|
|
22
|
+
private readonly entries;
|
|
23
|
+
private constructor();
|
|
24
|
+
static open(file: string): Promise<Quarantine>;
|
|
25
|
+
has(key: string): boolean;
|
|
26
|
+
list(): Array<{
|
|
27
|
+
key: string;
|
|
28
|
+
record: BoxRecord;
|
|
29
|
+
why: string;
|
|
30
|
+
at: string;
|
|
31
|
+
}>;
|
|
32
|
+
add(key: string, record: BoxRecord, why: string): Promise<void>;
|
|
33
|
+
clear(key: string): Promise<void>;
|
|
34
|
+
private saving;
|
|
35
|
+
private save;
|
|
36
|
+
}
|
|
37
|
+
export type Settled = "none" | "owned" | "reaped" | "cleared" | "quarantined";
|
|
38
|
+
/** The quarantine key of a run's box: by the box, so a run whose box is quarantined and that opens a new one keeps the
|
|
39
|
+
* old one held, and the new one's reap never clears it. */
|
|
40
|
+
export declare const boxKey: (runId: string, record: Pick<BoxRecord, "id">) => string;
|
|
41
|
+
/**
|
|
42
|
+
* The box the run in `runDir` recorded, let go if nothing owns it: none recorded, or already let go (`none`); its writer,
|
|
43
|
+
* the run process, still alive, so the box is that process's (`owned`); else reaped. Empty: marked, its cgroup removed
|
|
44
|
+
* (`reaped`). Nothing to count, with its writer gone: marked (`cleared`). Anything else: quarantined, its record kept.
|
|
45
|
+
*/
|
|
46
|
+
export declare function settleBox(host: BoxHost, quarantine: Quarantine, runId: string, runDir: string): Promise<Settled>;
|
|
47
|
+
/** At start, before any run opens a box: every run's box let go that nothing owns; then every box the quarantine still
|
|
48
|
+
* holds that is no longer its run's current one (the run opened another since), tried again by its own record; then
|
|
49
|
+
* every run cgroup no record names, reaped by the cgroup and removed when empty. */
|
|
50
|
+
export declare function sweepBoxes(host: BoxHost, quarantine: Quarantine, runs: ReadonlyArray<{
|
|
51
|
+
id: string;
|
|
52
|
+
dir: string;
|
|
53
|
+
}>): Promise<Record<string, Settled>>;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// What serve does with the boxes runs leave: the box a run's process recorded (its box.json), reaped once nothing owns
|
|
2
|
+
// it, and the cgroups no record names. A box is let go only on the reap's own count: empty, its record is marked reaped
|
|
3
|
+
// and its cgroup removed; anything else (left processes, a reap that throws) quarantines it, its record kept, and every
|
|
4
|
+
// later sweep tries again. A record nothing could count (no pid and no cgroup: a crash before the box's first process
|
|
5
|
+
// was known) is cleared only once the run process that wrote it is gone, by its pid and start time, so a box still
|
|
6
|
+
// starting is never written off.
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { readJson, writeDurable } from "../files.js";
|
|
10
|
+
import { BOX_RECORD } from "./record.js";
|
|
11
|
+
/** The data directory's file of quarantined boxes. */
|
|
12
|
+
export const BOX_QUARANTINE = "box-quarantine.json";
|
|
13
|
+
/** A run cgroup removed, or already gone: a reap that empties a cgroup may remove it itself (bwrapBox's does), so a
|
|
14
|
+
* missing one is the removal done. Any other failure is the caller's. */
|
|
15
|
+
async function removeCgroup(cgroups, path) {
|
|
16
|
+
try {
|
|
17
|
+
await cgroups.remove(path);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error?.code !== "ENOENT")
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** A process's start time as /proc/<pid>/stat gives it (clock ticks since boot), or undefined when it is not running. */
|
|
25
|
+
export function startTimeOf(pid) {
|
|
26
|
+
try {
|
|
27
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
28
|
+
return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The record's writer is gone: no process has its pid, or the one that has it started at another time (a reused pid).
|
|
35
|
+
* box-image.ts asks the same of the server that wrote the image's record. */
|
|
36
|
+
export function writerGone(writer) {
|
|
37
|
+
if (!writer || !Number.isSafeInteger(writer.pid) || writer.pid <= 0)
|
|
38
|
+
return true;
|
|
39
|
+
return startTimeOf(writer.pid) !== writer.startTime;
|
|
40
|
+
}
|
|
41
|
+
/** The boxes that a reap could not let go, kept across restarts: by run (or "" for a cgroup no record named). */
|
|
42
|
+
export class Quarantine {
|
|
43
|
+
file;
|
|
44
|
+
entries;
|
|
45
|
+
constructor(file, entries) {
|
|
46
|
+
this.file = file;
|
|
47
|
+
this.entries = entries;
|
|
48
|
+
}
|
|
49
|
+
static async open(file) {
|
|
50
|
+
const kept = await readJson(file);
|
|
51
|
+
const entries = new Map();
|
|
52
|
+
if (Array.isArray(kept))
|
|
53
|
+
for (const e of kept)
|
|
54
|
+
if (e && typeof e.key === "string")
|
|
55
|
+
entries.set(e.key, { record: e.record, why: e.why, at: e.at });
|
|
56
|
+
return new Quarantine(file, entries);
|
|
57
|
+
}
|
|
58
|
+
has(key) {
|
|
59
|
+
return this.entries.has(key);
|
|
60
|
+
}
|
|
61
|
+
list() {
|
|
62
|
+
return [...this.entries].map(([key, e]) => ({ key, ...e }));
|
|
63
|
+
}
|
|
64
|
+
async add(key, record, why) {
|
|
65
|
+
this.entries.set(key, { record, why, at: new Date().toISOString() });
|
|
66
|
+
await this.save();
|
|
67
|
+
}
|
|
68
|
+
async clear(key) {
|
|
69
|
+
if (this.entries.delete(key))
|
|
70
|
+
await this.save();
|
|
71
|
+
}
|
|
72
|
+
// One save at a time, each writing the whole set as it is then: concurrent writes of the same file would share its
|
|
73
|
+
// temporary file, and one could lose another's entries or fail its rename.
|
|
74
|
+
saving = Promise.resolve();
|
|
75
|
+
save() {
|
|
76
|
+
const next = this.saving.catch(() => { }).then(async () => void (await writeDurable(this.file, `${JSON.stringify(this.list())}\n`)));
|
|
77
|
+
this.saving = next;
|
|
78
|
+
return next;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** The quarantine key of a cgroup no record named. */
|
|
82
|
+
const leftoverKey = (path) => `cgroup:${path}`;
|
|
83
|
+
/** The quarantine key of a run's box: by the box, so a run whose box is quarantined and that opens a new one keeps the
|
|
84
|
+
* old one held, and the new one's reap never clears it. */
|
|
85
|
+
export const boxKey = (runId, record) => `${runId}/${record.id}`;
|
|
86
|
+
/** Whether a cgroup is still named by a box other than `key`'s that is not yet let go: a quarantined one, or (`current`)
|
|
87
|
+
* the run's current box. A run's boxes share its cgroup, so one box's empty count never removes another's. */
|
|
88
|
+
function namedElsewhere(quarantine, cgroup, key, current) {
|
|
89
|
+
if (current && !current.reaped && current.cgroup === cgroup && current.id !== key.slice(key.lastIndexOf("/") + 1))
|
|
90
|
+
return true;
|
|
91
|
+
return quarantine.list().some((entry) => entry.key !== key && entry.record.cgroup === cgroup);
|
|
92
|
+
}
|
|
93
|
+
const left = (verdict) => `its reap left ${verdict.left} process${verdict.left === 1 ? "" : "es"} (counted by ${verdict.by})`;
|
|
94
|
+
/**
|
|
95
|
+
* The box the run in `runDir` recorded, let go if nothing owns it: none recorded, or already let go (`none`); its writer,
|
|
96
|
+
* the run process, still alive, so the box is that process's (`owned`); else reaped. Empty: marked, its cgroup removed
|
|
97
|
+
* (`reaped`). Nothing to count, with its writer gone: marked (`cleared`). Anything else: quarantined, its record kept.
|
|
98
|
+
*/
|
|
99
|
+
export async function settleBox(host, quarantine, runId, runDir) {
|
|
100
|
+
const path = join(runDir, BOX_RECORD);
|
|
101
|
+
const stored = (await readJson(path));
|
|
102
|
+
if (!stored || typeof stored.id !== "string" || stored.reaped)
|
|
103
|
+
return "none";
|
|
104
|
+
if (!writerGone(stored.writer))
|
|
105
|
+
return "owned";
|
|
106
|
+
const { reaped: _, ...record } = stored;
|
|
107
|
+
let verdict;
|
|
108
|
+
try {
|
|
109
|
+
verdict = await host.reap(record);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
await quarantine.add(boxKey(runId, record), record, `its reap failed: ${error.message}`);
|
|
113
|
+
return "quarantined";
|
|
114
|
+
}
|
|
115
|
+
if (verdict.by === "none") {
|
|
116
|
+
// Nothing named the box to count, and its writer is gone: --die-with-parent ended whatever had started.
|
|
117
|
+
await writeDurable(path, `${JSON.stringify({ ...record, reaped: { at: new Date().toISOString(), by: "none" } })}\n`);
|
|
118
|
+
await quarantine.clear(boxKey(runId, record));
|
|
119
|
+
return "cleared";
|
|
120
|
+
}
|
|
121
|
+
if (!verdict.empty) {
|
|
122
|
+
await quarantine.add(boxKey(runId, record), record, left(verdict));
|
|
123
|
+
return "quarantined";
|
|
124
|
+
}
|
|
125
|
+
if (record.cgroup && host.cgroups && !namedElsewhere(quarantine, record.cgroup, boxKey(runId, record)))
|
|
126
|
+
await removeCgroup(host.cgroups, record.cgroup);
|
|
127
|
+
await writeDurable(path, `${JSON.stringify({ ...record, reaped: { at: new Date().toISOString(), by: verdict.by } })}\n`);
|
|
128
|
+
await quarantine.clear(boxKey(runId, record));
|
|
129
|
+
return "reaped";
|
|
130
|
+
}
|
|
131
|
+
/** At start, before any run opens a box: every run's box let go that nothing owns; then every box the quarantine still
|
|
132
|
+
* holds that is no longer its run's current one (the run opened another since), tried again by its own record; then
|
|
133
|
+
* every run cgroup no record names, reaped by the cgroup and removed when empty. */
|
|
134
|
+
export async function sweepBoxes(host, quarantine, runs) {
|
|
135
|
+
const settled = {};
|
|
136
|
+
const named = new Set();
|
|
137
|
+
for (const run of runs) {
|
|
138
|
+
settled[run.id] = await settleBox(host, quarantine, run.id, run.dir);
|
|
139
|
+
if (settled[run.id] === "owned" || settled[run.id] === "quarantined") {
|
|
140
|
+
const cgroup = (await readJson(join(run.dir, BOX_RECORD)))?.cgroup;
|
|
141
|
+
if (cgroup)
|
|
142
|
+
named.add(cgroup);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// A run's earlier box, still held: only its own reap's count lets it go. Its cgroup stays named while it is held.
|
|
146
|
+
const current = new Set(runs.map((run) => run.id));
|
|
147
|
+
for (const entry of quarantine.list()) {
|
|
148
|
+
if (entry.key.startsWith("cgroup:"))
|
|
149
|
+
continue;
|
|
150
|
+
const runId = entry.key.slice(0, entry.key.lastIndexOf("/"));
|
|
151
|
+
const now = current.has(runId) ? (await readJson(join(runs.find((r) => r.id === runId).dir, BOX_RECORD))) : null;
|
|
152
|
+
if (now?.id === entry.record.id) {
|
|
153
|
+
if (entry.record.cgroup && quarantine.has(entry.key))
|
|
154
|
+
named.add(entry.record.cgroup);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
let verdict;
|
|
158
|
+
if (!writerGone(entry.record.writer))
|
|
159
|
+
verdict = undefined;
|
|
160
|
+
else
|
|
161
|
+
verdict = await host.reap(entry.record).catch(() => undefined);
|
|
162
|
+
if (verdict && (verdict.empty || verdict.by === "none")) {
|
|
163
|
+
const cgroup = entry.record.cgroup;
|
|
164
|
+
if (verdict.empty && cgroup && host.cgroups && !namedElsewhere(quarantine, cgroup, entry.key, now))
|
|
165
|
+
await removeCgroup(host.cgroups, cgroup);
|
|
166
|
+
await quarantine.clear(entry.key);
|
|
167
|
+
}
|
|
168
|
+
else if (entry.record.cgroup)
|
|
169
|
+
named.add(entry.record.cgroup);
|
|
170
|
+
}
|
|
171
|
+
if (!host.cgroups)
|
|
172
|
+
return settled;
|
|
173
|
+
for (const cgroup of await host.cgroups.list()) {
|
|
174
|
+
if (named.has(cgroup))
|
|
175
|
+
continue;
|
|
176
|
+
const record = { id: leftoverKey(cgroup), cgroup, writer: { pid: 0, startTime: "" } };
|
|
177
|
+
let verdict;
|
|
178
|
+
try {
|
|
179
|
+
verdict = await host.reap(record);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
await quarantine.add(leftoverKey(cgroup), record, `its reap failed: ${error.message}`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (verdict.empty) {
|
|
186
|
+
await removeCgroup(host.cgroups, cgroup);
|
|
187
|
+
await quarantine.clear(leftoverKey(cgroup));
|
|
188
|
+
}
|
|
189
|
+
else
|
|
190
|
+
await quarantine.add(leftoverKey(cgroup), record, left(verdict));
|
|
191
|
+
}
|
|
192
|
+
return settled;
|
|
193
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** Where the proxy's directory is in the box, read-only. */
|
|
2
|
+
export declare const EGRESS_MOUNT = "/run/agentrun/egress";
|
|
3
|
+
/** The proxy's socket, in its directory. */
|
|
4
|
+
export declare const EGRESS_SOCKET = "egress.sock";
|
|
5
|
+
/** The box's loopback port socat relays to the socket. */
|
|
6
|
+
export declare const EGRESS_PORT = 3128;
|
|
7
|
+
/** What a box with a list adds to its fixed environment (run-box.ts BOX_ENV): constants, no user, no password. */
|
|
8
|
+
export declare const PROXY_ENV: Readonly<Record<string, string>>;
|
|
9
|
+
/** The box's relay to the proxy's socket `socket` (in EGRESS_MOUNT), started once each time the run's box opens (made
|
|
10
|
+
* or found): a second one finds the port taken and exits. Each connection opens the socket by its path, so a proxy
|
|
11
|
+
* started again is reached with no new relay. */
|
|
12
|
+
export declare const forwarder: (socket?: string) => string[];
|
|
13
|
+
/** The relay's start, in the box, answered once it listens: exit 127 when the image has no socat, 126 when it has no
|
|
14
|
+
* setsid, and 124 when the relay is not listening within 3 s (its own error, if it gave one, on stderr). A relay a
|
|
15
|
+
* process before this one started still listens, so a second start finds the port taken and answers at once. */
|
|
16
|
+
export declare const forwarderStart: (socket?: string) => string[];
|
|
17
|
+
/** The timeline row of a box whose relay could not start, by the start's exit (forwarderStart): the box keeps no network. */
|
|
18
|
+
export declare function relayFailed(code: number, said: string): string;
|
|
19
|
+
/** The row for an image with no socat (relayFailed 127). */
|
|
20
|
+
export declare const NO_SOCAT: string;
|
|
21
|
+
/** What a refusal of a host off the list says to do, after its words. */
|
|
22
|
+
export declare const ALLOW_HINT = "use web_fetch for web pages, or ask the operator to add it to AGENTRUN_BOX_ALLOW";
|
|
23
|
+
/** Each run's proxy: connections open at once, and in all. */
|
|
24
|
+
export declare const MAX_TUNNELS = 64;
|
|
25
|
+
export declare const MAX_CONNECTIONS = 20000;
|
|
26
|
+
/** Under `--faux` only: a module whose default export gives the proxy's `lookup` and `dial` (the tests' fake network), so
|
|
27
|
+
* a test's box reaches no host but its fake. */
|
|
28
|
+
export declare const FAUX_EGRESS_ENV = "AGENTRUN_SERVE_FAUX_EGRESS";
|
|
29
|
+
/** The proxy's directory for run `runId`: short, so its socket's path stays within a Unix socket's limit (107 bytes)
|
|
30
|
+
* wherever the data root is, and the same each time the run's process starts, since the box keeps its bind. */
|
|
31
|
+
export declare function egressDir(runId: string, uid?: number): string;
|
|
32
|
+
/** Removes a run's proxy directory once its box is gone. */
|
|
33
|
+
export declare const removeEgressDir: (runId: string) => Promise<void>;
|
|
34
|
+
/** Where a run's box finds its proxy: what is mounted read-only at EGRESS_MOUNT, and the socket's name there. The one
|
|
35
|
+
* seam between the box's side, which is the same wherever the proxy runs (the mount, the relay, the proxy variables),
|
|
36
|
+
* and where the proxy runs. Today that is hostEgress: the run's own process, its socket's directory on this machine
|
|
37
|
+
* bound into the box. */
|
|
38
|
+
export type BoxEgress = (runId: string) => Promise<{
|
|
39
|
+
mount: {
|
|
40
|
+
source: string;
|
|
41
|
+
target: typeof EGRESS_MOUNT;
|
|
42
|
+
readOnly: true;
|
|
43
|
+
};
|
|
44
|
+
socket: string;
|
|
45
|
+
fresh: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
/** The proxy in the run's process (hostEgress): for a Docker daemon on this Linux machine, which can reach a socket in a
|
|
48
|
+
* directory of this machine bound into a container. */
|
|
49
|
+
export declare const hostEgress: (allow: readonly string[], env: NodeJS.ProcessEnv, log: (line: string) => void) => BoxEgress;
|
|
50
|
+
/** How long `docker info` may take to say where this Docker runs. */
|
|
51
|
+
export declare const INFO_TIMEOUT_MS = 5000;
|
|
52
|
+
/** What `docker info` is asked: the daemon's OS type, its kernel, where it keeps its data, and the name it gives its OS. */
|
|
53
|
+
export declare const INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.DockerRootDir}}|{{.OperatingSystem}}";
|
|
54
|
+
/** `docker info`'s answer to INFO_FORMAT, its stdout, or a throw that says why there is none. */
|
|
55
|
+
export type DockerInfo = (env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<string>;
|
|
56
|
+
/** `docker info` in the server's environment through the cut a run's takes, nothing on its stdin, within `timeoutMs`. */
|
|
57
|
+
export declare const dockerInfo: DockerInfo;
|
|
58
|
+
/**
|
|
59
|
+
* Why a Docker box on this server cannot reach its proxy, or undefined when it can. The proxy's socket is a file of this
|
|
60
|
+
* machine bound into the box, which only a Docker daemon on this same Linux machine can connect to: a daemon in a VM
|
|
61
|
+
* (Docker Desktop, OrbStack and their kin) sees the socket and is refused. So the network goes on only with positive
|
|
62
|
+
* evidence that the daemon is this machine's: this machine is Linux; the docker CLI's endpoint is a local unix socket
|
|
63
|
+
* (no DOCKER_HOST or a unix:// one, and the default context or a unix one: pi-transport's dockerDaemon); and `docker
|
|
64
|
+
* info` answers within its bound with OS type linux and this machine's own kernel (os.release()): the same kernel, so no
|
|
65
|
+
* VM in between; and the directory it keeps its data in (DockerRootDir) is one this server sees. A server in a container
|
|
66
|
+
* given the host's docker socket shares the host's kernel, but not its files: it would bind a directory the daemon does
|
|
67
|
+
* not have, so every box would fail to start. Anything else is no network, and the reason says what was seen, naming the
|
|
68
|
+
* runtime docker info gives. A kernel is the evidence, not a runtime's name: Docker Desktop on WSL2 runs the kernel this
|
|
69
|
+
* server does, but keeps its data outside the distro, so it passes only where the distro has that directory too.
|
|
70
|
+
*/
|
|
71
|
+
export declare function egressBlockedBy(env: NodeJS.ProcessEnv, options?: {
|
|
72
|
+
info?: DockerInfo;
|
|
73
|
+
platform?: string;
|
|
74
|
+
kernel?: string;
|
|
75
|
+
timeoutMs?: number;
|
|
76
|
+
sees?: (dir: string) => boolean;
|
|
77
|
+
}): Promise<string | undefined>;
|
|
78
|
+
/** How old a run's proxy directory with no live socket must be before the start's sweep takes it: one just made, whose
|
|
79
|
+
* proxy is still starting, is not yet listening. */
|
|
80
|
+
export declare const STALE_EGRESS_MS = 60000;
|
|
81
|
+
/**
|
|
82
|
+
* The start's sweep of this user's proxy directories (egressDir's parent): each whose socket refuses a connect (or has
|
|
83
|
+
* none) and that is older than STALE_EGRESS_MS is a run's process that is gone, and is removed, by its exact path. One
|
|
84
|
+
* whose socket answers is a live run's, this server's or another's under this uid, and stays. Returns how many went.
|
|
85
|
+
*/
|
|
86
|
+
export declare function sweepEgressDirs(uid?: number, now?: number): Promise<number>;
|
|
87
|
+
/** What a server's Docker boxes reach, resolved once at its start (run-box.ts boxNetworkOf): the list, or none and why. */
|
|
88
|
+
export type DockerNetwork = {
|
|
89
|
+
allow: readonly string[];
|
|
90
|
+
} | {
|
|
91
|
+
allow: "none";
|
|
92
|
+
reason: string;
|
|
93
|
+
};
|
|
94
|
+
/** What the server hands a run's process: the list its box reaches, resolved (boxNetworkOf), or `none`. The run's
|
|
95
|
+
* process reads this, never AGENTRUN_BOX_ALLOW: unset, it is none. */
|
|
96
|
+
export declare const RUN_BOX_ALLOW_ENV = "AGENTRUN_RUN_BOX_ALLOW";
|
|
97
|
+
/** The run's process's reading of RUN_BOX_ALLOW_ENV: the list, or `none` when it says so, is unset or is not a list. */
|
|
98
|
+
export declare function runBoxAllowOf(env: NodeJS.ProcessEnv): readonly string[] | "none";
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// A Docker box's way out to the network: the hosts on the server's list (AGENTRUN_BOX_ALLOW), and nothing else. The box
|
|
2
|
+
// stays `--network none`, with its own loopback alone. The run's process starts the kernel's egress proxy with the list
|
|
3
|
+
// (@parcha/agentrun-kernel/host), on a Unix socket in a directory of its own, which is bound into the box read-only at
|
|
4
|
+
// EGRESS_MOUNT; a socat in the box relays its own loopback port EGRESS_PORT to it, and the box's fixed environment
|
|
5
|
+
// names that port as its HTTP(S) proxy. The proxy refuses, before any lookup, a host off the list, an IP literal and any port but 80 and
|
|
6
|
+
// 443, and a listed name that resolves to a private or metadata address; it holds no key and adds none. A program in the
|
|
7
|
+
// box that ignores the proxy variables has no route and no resolver: its connection is unreachable. The list is the
|
|
8
|
+
// setting's one reading (run-box.ts boxAllowOf), as the server resolves it for this machine (boxNetworkOf); with `none`,
|
|
9
|
+
// a box is as it was: no proxy, no mount, no proxy variables. The proxy is never started without an explicit list: one
|
|
10
|
+
// with none would reach every public host.
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { statSync } from "node:fs";
|
|
14
|
+
import { lstat, mkdir, readdir, rm } from "node:fs/promises";
|
|
15
|
+
import { connect } from "node:net";
|
|
16
|
+
import { release } from "node:os";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { pathToFileURL } from "node:url";
|
|
19
|
+
import { parseAllow, startEgressProxy } from "@parcha/agentrun-kernel/host";
|
|
20
|
+
import { FAUX_ENV } from "./model.js";
|
|
21
|
+
import { withoutSecrets } from "./secrets.js";
|
|
22
|
+
/** Where the proxy's directory is in the box, read-only. */
|
|
23
|
+
export const EGRESS_MOUNT = "/run/agentrun/egress";
|
|
24
|
+
/** The proxy's socket, in its directory. */
|
|
25
|
+
export const EGRESS_SOCKET = "egress.sock";
|
|
26
|
+
/** The box's loopback port socat relays to the socket. */
|
|
27
|
+
export const EGRESS_PORT = 3128;
|
|
28
|
+
/** The box's own loopback, where its relay listens: never a service of this machine's. */
|
|
29
|
+
const BOX_LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule the box own loopback where its relay listens
|
|
30
|
+
/** The proxy's address in the box: EGRESS_PORT on its loopback. */
|
|
31
|
+
const PROXY_URL = `http://${BOX_LOOPBACK}:${EGRESS_PORT}`;
|
|
32
|
+
const NO_PROXY = "localhost,127.0.0.1,::1"; // key-gate: loopback-rule the box own loopback names the proxy leaves out
|
|
33
|
+
/** What a box with a list adds to its fixed environment (run-box.ts BOX_ENV): constants, no user, no password. */
|
|
34
|
+
export const PROXY_ENV = Object.freeze({ HTTP_PROXY: PROXY_URL, HTTPS_PROXY: PROXY_URL, http_proxy: PROXY_URL, https_proxy: PROXY_URL, NO_PROXY, no_proxy: NO_PROXY });
|
|
35
|
+
/** The box's relay to the proxy's socket `socket` (in EGRESS_MOUNT), started once each time the run's box opens (made
|
|
36
|
+
* or found): a second one finds the port taken and exits. Each connection opens the socket by its path, so a proxy
|
|
37
|
+
* started again is reached with no new relay. */
|
|
38
|
+
export const forwarder = (socket = EGRESS_SOCKET) => ["socat", `TCP-LISTEN:${EGRESS_PORT},bind=127.0.0.1,reuseaddr,fork`, `UNIX-CONNECT:${EGRESS_MOUNT}/${socket}`]; // key-gate: loopback-rule the box own proxy port inside the box
|
|
39
|
+
/** How long the relay has to listen once started, in tenths of a second. */
|
|
40
|
+
const RELAY_WAIT_TENTHS = 30;
|
|
41
|
+
/** EGRESS_PORT on the box's loopback as /proc/net/tcp writes a listening socket: address and port in hex, state 0A. */
|
|
42
|
+
const LISTENING = ` 0100007F:${EGRESS_PORT.toString(16).toUpperCase().padStart(4, "0")} 00000000:0000 0A `;
|
|
43
|
+
/** The relay's start, in the box, answered once it listens: exit 127 when the image has no socat, 126 when it has no
|
|
44
|
+
* setsid, and 124 when the relay is not listening within 3 s (its own error, if it gave one, on stderr). A relay a
|
|
45
|
+
* process before this one started still listens, so a second start finds the port taken and answers at once. */
|
|
46
|
+
export const forwarderStart = (socket = EGRESS_SOCKET) => ["sh", "-c", [
|
|
47
|
+
"command -v socat >/dev/null 2>&1 || exit 127",
|
|
48
|
+
"command -v setsid >/dev/null 2>&1 || exit 126",
|
|
49
|
+
`listening() { grep -q '${LISTENING}' /proc/net/tcp 2>/dev/null; }`,
|
|
50
|
+
"listening && exit 0",
|
|
51
|
+
`log=$(mktemp); setsid ${forwarder(socket).join(" ")} </dev/null >/dev/null 2>"$log" &`,
|
|
52
|
+
`i=0; while [ "$i" -lt ${RELAY_WAIT_TENTHS} ]; do listening && { rm -f "$log"; exit 0; }; i=$((i + 1)); sleep 0.1; done`,
|
|
53
|
+
`head -c 300 "$log" >&2; rm -f "$log"; exit 124`,
|
|
54
|
+
].join("\n")];
|
|
55
|
+
/** The timeline row of a box whose relay could not start, by the start's exit (forwarderStart): the box keeps no network. */
|
|
56
|
+
export function relayFailed(code, said) {
|
|
57
|
+
if (code === 127)
|
|
58
|
+
return "This box's image has no socat, so it has no network. Add socat to the image, or set AGENTRUN_BOX_ALLOW=none to silence this.";
|
|
59
|
+
if (code === 126)
|
|
60
|
+
return "This box's image has no setsid, so it has no network. Add util-linux's setsid to the image, or set AGENTRUN_BOX_ALLOW=none to silence this.";
|
|
61
|
+
const why = said.trim().replace(/[\u0000-\u001f]+/g, " ").slice(0, 200);
|
|
62
|
+
return `This box's network relay did not start within 3 s (${code === 124 ? why || "it was not listening" : `exit ${code}`}), so it has no network.`;
|
|
63
|
+
}
|
|
64
|
+
/** The row for an image with no socat (relayFailed 127). */
|
|
65
|
+
export const NO_SOCAT = relayFailed(127, "");
|
|
66
|
+
/** What a refusal of a host off the list says to do, after its words. */
|
|
67
|
+
export const ALLOW_HINT = `use web_fetch for web pages, or ask the operator to add it to AGENTRUN_BOX_ALLOW`;
|
|
68
|
+
/** Each run's proxy: connections open at once, and in all. */
|
|
69
|
+
export const MAX_TUNNELS = 64;
|
|
70
|
+
export const MAX_CONNECTIONS = 20_000;
|
|
71
|
+
/** Under `--faux` only: a module whose default export gives the proxy's `lookup` and `dial` (the tests' fake network), so
|
|
72
|
+
* a test's box reaches no host but its fake. */
|
|
73
|
+
export const FAUX_EGRESS_ENV = "AGENTRUN_SERVE_FAUX_EGRESS";
|
|
74
|
+
/** The proxy's directory for run `runId`: short, so its socket's path stays within a Unix socket's limit (107 bytes)
|
|
75
|
+
* wherever the data root is, and the same each time the run's process starts, since the box keeps its bind. */
|
|
76
|
+
export function egressDir(runId, uid = process.getuid?.() ?? 0) {
|
|
77
|
+
return join("/tmp", `agentrun-egress-${uid}`, createHash("sha256").update(runId).digest("hex").slice(0, 16));
|
|
78
|
+
}
|
|
79
|
+
/** Removes a run's proxy directory once its box is gone. */
|
|
80
|
+
export const removeEgressDir = (runId) => rm(egressDir(runId), { recursive: true, force: true });
|
|
81
|
+
/** This user's parent directory in /tmp: made 0700, and refused unless it is a directory of this user's, not a link. */
|
|
82
|
+
async function ownParent(dir) {
|
|
83
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
84
|
+
const at = await lstat(dir);
|
|
85
|
+
const uid = process.getuid?.();
|
|
86
|
+
if (!at.isDirectory() || at.isSymbolicLink() || (uid !== undefined && at.uid !== uid) || (at.mode & 0o077) !== 0) {
|
|
87
|
+
throw new Error(`the box's network directory ${dir} is not a directory of this user's alone (0700, not a link): remove it, or set AGENTRUN_BOX_ALLOW=none`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** The proxy in the run's process (hostEgress): for a Docker daemon on this Linux machine, which can reach a socket in a
|
|
91
|
+
* directory of this machine bound into a container. */
|
|
92
|
+
export const hostEgress = (allow, env, log) => async (runId) => {
|
|
93
|
+
const { dir, fresh } = await runProxy(runId, allow, env, log);
|
|
94
|
+
return { mount: { source: dir, target: EGRESS_MOUNT, readOnly: true }, socket: EGRESS_SOCKET, fresh };
|
|
95
|
+
};
|
|
96
|
+
const started = new Map();
|
|
97
|
+
const opened = new Set();
|
|
98
|
+
/** Run `runId`'s proxy in this process, with `allow`, started once: its directory, to bind into the box, and whether that
|
|
99
|
+
* directory was made now (`fresh`): a box bound to one an earlier process made, which the start's sweep took since, holds
|
|
100
|
+
* the old directory, not this one. Its decisions go to `log`. */
|
|
101
|
+
async function runProxy(runId, allow, env, log) {
|
|
102
|
+
const dir = egressDir(runId);
|
|
103
|
+
let proxy = started.get(runId);
|
|
104
|
+
if (!proxy) {
|
|
105
|
+
proxy = (async () => {
|
|
106
|
+
await ownParent(join(dir, ".."));
|
|
107
|
+
const fresh = await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => {
|
|
108
|
+
if (error.code !== "EEXIST")
|
|
109
|
+
throw error;
|
|
110
|
+
return false;
|
|
111
|
+
});
|
|
112
|
+
const proxy = await startEgressProxy({ socketPath: join(dir, EGRESS_SOCKET), maxTunnels: MAX_TUNNELS, maxConnections: MAX_CONNECTIONS, log, allow: [...allow], allowHint: ALLOW_HINT, ...(await fauxSeams(env)) });
|
|
113
|
+
log(`egress start allow=${allow.join(",")}`);
|
|
114
|
+
return { proxy, fresh };
|
|
115
|
+
})();
|
|
116
|
+
started.set(runId, proxy);
|
|
117
|
+
proxy.catch(() => started.delete(runId));
|
|
118
|
+
}
|
|
119
|
+
// Fresh once: a later open in this process binds what the first one did.
|
|
120
|
+
const fresh = (await proxy).fresh && !opened.has(runId);
|
|
121
|
+
opened.add(runId);
|
|
122
|
+
return { dir, fresh };
|
|
123
|
+
}
|
|
124
|
+
/** The tests' seams, under `--faux` with FAUX_EGRESS_ENV set: its module's. */
|
|
125
|
+
async function fauxSeams(env) {
|
|
126
|
+
const module = env[FAUX_ENV] ? env[FAUX_EGRESS_ENV] : undefined;
|
|
127
|
+
if (!module)
|
|
128
|
+
return {};
|
|
129
|
+
return (await import(pathToFileURL(module).href)).default();
|
|
130
|
+
}
|
|
131
|
+
/** How long `docker info` may take to say where this Docker runs. */
|
|
132
|
+
export const INFO_TIMEOUT_MS = 5_000;
|
|
133
|
+
/** A platform by the name people use. */
|
|
134
|
+
const PLATFORM_NAMES = { darwin: "macOS", win32: "Windows" };
|
|
135
|
+
/** What `docker info` is asked: the daemon's OS type, its kernel, where it keeps its data, and the name it gives its OS. */
|
|
136
|
+
export const INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.DockerRootDir}}|{{.OperatingSystem}}";
|
|
137
|
+
/** `docker info` in the server's environment through the cut a run's takes, nothing on its stdin, within `timeoutMs`. */
|
|
138
|
+
export const dockerInfo = (env, timeoutMs) => new Promise((resolve, reject) => execFile("docker", ["info", "--format", INFO_FORMAT], { env: withoutSecrets(env), timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024 }, (error, stdout) => {
|
|
139
|
+
if (!error)
|
|
140
|
+
return resolve(String(stdout));
|
|
141
|
+
const failed = error;
|
|
142
|
+
reject(new Error(failed.killed ? `it did not answer within ${Math.round(timeoutMs / 1000)} s` : typeof failed.code === "number" ? `it failed (exit ${failed.code})` : `it failed (${failed.code ?? failed.name})`));
|
|
143
|
+
}).stdin?.end());
|
|
144
|
+
/**
|
|
145
|
+
* Why a Docker box on this server cannot reach its proxy, or undefined when it can. The proxy's socket is a file of this
|
|
146
|
+
* machine bound into the box, which only a Docker daemon on this same Linux machine can connect to: a daemon in a VM
|
|
147
|
+
* (Docker Desktop, OrbStack and their kin) sees the socket and is refused. So the network goes on only with positive
|
|
148
|
+
* evidence that the daemon is this machine's: this machine is Linux; the docker CLI's endpoint is a local unix socket
|
|
149
|
+
* (no DOCKER_HOST or a unix:// one, and the default context or a unix one: pi-transport's dockerDaemon); and `docker
|
|
150
|
+
* info` answers within its bound with OS type linux and this machine's own kernel (os.release()): the same kernel, so no
|
|
151
|
+
* VM in between; and the directory it keeps its data in (DockerRootDir) is one this server sees. A server in a container
|
|
152
|
+
* given the host's docker socket shares the host's kernel, but not its files: it would bind a directory the daemon does
|
|
153
|
+
* not have, so every box would fail to start. Anything else is no network, and the reason says what was seen, naming the
|
|
154
|
+
* runtime docker info gives. A kernel is the evidence, not a runtime's name: Docker Desktop on WSL2 runs the kernel this
|
|
155
|
+
* server does, but keeps its data outside the distro, so it passes only where the distro has that directory too.
|
|
156
|
+
*/
|
|
157
|
+
export async function egressBlockedBy(env, options = {}) {
|
|
158
|
+
const platform = options.platform ?? process.platform;
|
|
159
|
+
if (platform !== "linux")
|
|
160
|
+
return `this server runs on ${PLATFORM_NAMES[platform] ?? platform}, where Docker runs in a VM that can't reach this server's egress proxy yet`;
|
|
161
|
+
const { dockerDaemon } = await import("@parcha/pi-transport/box/docker");
|
|
162
|
+
const daemon = dockerDaemon(env);
|
|
163
|
+
if (!daemon.local)
|
|
164
|
+
return `this Docker (${daemon.named}) is not on this machine, so it can't reach this server's egress proxy`;
|
|
165
|
+
let answer;
|
|
166
|
+
try {
|
|
167
|
+
answer = await (options.info ?? dockerInfo)(env, options.timeoutMs ?? INFO_TIMEOUT_MS);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
return `docker info did not say where this Docker runs (${error.message}), so this server can't tell it is on this machine`;
|
|
171
|
+
}
|
|
172
|
+
const fields = answer.trim().split("|");
|
|
173
|
+
const [osType, kernel, root, name] = fields.map((field) => field.trim());
|
|
174
|
+
const shown = (text) => JSON.stringify(text.slice(0, 80));
|
|
175
|
+
if (fields.length !== 4 || !osType || !kernel || !root)
|
|
176
|
+
return `docker info's answer could not be read (${shown(answer.trim())}), so this server can't tell this Docker is on this machine`;
|
|
177
|
+
const runtime = name ? `this Docker (${name.slice(0, 80)})` : "this Docker";
|
|
178
|
+
if (osType !== "linux")
|
|
179
|
+
return `${runtime} runs ${shown(osType)} containers, not Linux ones on this machine, so it can't reach this server's egress proxy`;
|
|
180
|
+
const here = options.kernel ?? release();
|
|
181
|
+
if (kernel !== here)
|
|
182
|
+
return `${runtime} runs in a VM (its kernel is ${shown(kernel)}, this machine's ${shown(here)}) that can't reach this server's egress proxy yet`;
|
|
183
|
+
const sees = options.sees ?? ((dir) => {
|
|
184
|
+
try {
|
|
185
|
+
return statSync(dir).isDirectory();
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
if (!sees(root))
|
|
192
|
+
return `${runtime} keeps its data in ${shown(root)}, which this server can't see: it runs on another machine's files (this server in a container, given the host's docker socket), so it can't reach this server's egress proxy`;
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
/** How old a run's proxy directory with no live socket must be before the start's sweep takes it: one just made, whose
|
|
196
|
+
* proxy is still starting, is not yet listening. */
|
|
197
|
+
export const STALE_EGRESS_MS = 60_000;
|
|
198
|
+
/**
|
|
199
|
+
* The start's sweep of this user's proxy directories (egressDir's parent): each whose socket refuses a connect (or has
|
|
200
|
+
* none) and that is older than STALE_EGRESS_MS is a run's process that is gone, and is removed, by its exact path. One
|
|
201
|
+
* whose socket answers is a live run's, this server's or another's under this uid, and stays. Returns how many went.
|
|
202
|
+
*/
|
|
203
|
+
export async function sweepEgressDirs(uid = process.getuid?.() ?? 0, now = Date.now()) {
|
|
204
|
+
const parent = join("/tmp", `agentrun-egress-${uid}`);
|
|
205
|
+
let names;
|
|
206
|
+
try {
|
|
207
|
+
const at = await lstat(parent);
|
|
208
|
+
if (!at.isDirectory() || at.isSymbolicLink() || at.uid !== uid)
|
|
209
|
+
return 0;
|
|
210
|
+
names = await readdir(parent);
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return 0;
|
|
214
|
+
}
|
|
215
|
+
let removed = 0;
|
|
216
|
+
for (const name of names) {
|
|
217
|
+
if (!/^[0-9a-f]{16}$/.test(name))
|
|
218
|
+
continue;
|
|
219
|
+
const dir = join(parent, name);
|
|
220
|
+
try {
|
|
221
|
+
const at = await lstat(dir);
|
|
222
|
+
if (!at.isDirectory() || at.isSymbolicLink() || at.uid !== uid || now - at.mtimeMs < STALE_EGRESS_MS)
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (await answers(join(dir, EGRESS_SOCKET)))
|
|
229
|
+
continue;
|
|
230
|
+
await rm(dir, { recursive: true, force: true });
|
|
231
|
+
removed++;
|
|
232
|
+
}
|
|
233
|
+
return removed;
|
|
234
|
+
}
|
|
235
|
+
/** Whether a Unix socket at `path` takes a connection: no for a refusal or no such file, yes for anything else. */
|
|
236
|
+
function answers(path) {
|
|
237
|
+
return new Promise((resolve) => {
|
|
238
|
+
const socket = connect(path);
|
|
239
|
+
const timer = setTimeout(() => (socket.destroy(), resolve(true)), 2_000);
|
|
240
|
+
socket.once("connect", () => (clearTimeout(timer), socket.destroy(), resolve(true)));
|
|
241
|
+
socket.once("error", (error) => (clearTimeout(timer), resolve(error.code !== "ECONNREFUSED" && error.code !== "ENOENT")));
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/** What the server hands a run's process: the list its box reaches, resolved (boxNetworkOf), or `none`. The run's
|
|
245
|
+
* process reads this, never AGENTRUN_BOX_ALLOW: unset, it is none. */
|
|
246
|
+
export const RUN_BOX_ALLOW_ENV = "AGENTRUN_RUN_BOX_ALLOW";
|
|
247
|
+
/** The run's process's reading of RUN_BOX_ALLOW_ENV: the list, or `none` when it says so, is unset or is not a list. */
|
|
248
|
+
export function runBoxAllowOf(env) {
|
|
249
|
+
const value = env[RUN_BOX_ALLOW_ENV]?.trim();
|
|
250
|
+
if (!value || value === "none")
|
|
251
|
+
return "none";
|
|
252
|
+
try {
|
|
253
|
+
const list = parseAllow(value);
|
|
254
|
+
return list.length ? list : "none";
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return "none";
|
|
258
|
+
}
|
|
259
|
+
}
|