pi-roundtable 0.53.5 → 0.54.0
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 +19 -0
- package/README.md +14 -2
- package/README.zh-TW.md +14 -2
- package/docs/plugins.md +201 -8
- package/package.json +3 -1
- package/runner/Dockerfile +46 -0
- package/runner/Dockerfile.dockerignore +5 -0
- package/src/cli/checks/images.ts +3 -2
- package/src/cli/checks/preset.ts +20 -0
- package/src/cli/checks/runner.ts +45 -0
- package/src/cli/doctor.ts +7 -1
- package/src/core/agents/agent-claim.ts +7 -4
- package/src/core/agents/agent-prompt.ts +11 -2
- package/src/core/agents/helper-workspace.ts +72 -0
- package/src/core/agents/team-options.ts +2 -0
- package/src/core/agents/team-prompt.ts +12 -1
- package/src/core/attachments/attachment-expiry.ts +12 -0
- package/src/core/attachments/attachment-store.ts +20 -5
- package/src/core/attachments/model-images.ts +3 -2
- package/src/core/builtin/agent-server.ts +8 -0
- package/src/core/builtin/polls.ts +67 -0
- package/src/core/builtin/runner.ts +139 -0
- package/src/core/config/config-schema.ts +4 -0
- package/src/core/config/config.ts +49 -185
- package/src/core/config/preset.ts +51 -0
- package/src/core/config/resolve-config.ts +175 -0
- package/src/core/config/runner-config.ts +80 -0
- package/src/core/contract/attachments.ts +2 -0
- package/src/core/contract/polls.ts +71 -0
- package/src/core/contract/runtime.ts +12 -0
- package/src/core/contract/surface.ts +13 -0
- package/src/core/discord/discord-polls.ts +156 -0
- package/src/core/discord/discord-replies.ts +55 -0
- package/src/core/discord/discord-surface.ts +13 -43
- package/src/core/domain/client.ts +6 -2
- package/src/core/domain/errors.ts +5 -0
- package/src/core/domain/sessions.ts +8 -1
- package/src/core/host/define-roundtable.ts +8 -0
- package/src/core/host/host-registration.ts +7 -0
- package/src/core/host/host.ts +8 -0
- package/src/core/i18n/schedules.ts +2 -0
- package/src/core/modules/polls/poll-result-turns.ts +124 -0
- package/src/core/modules/polls/poll-rules.ts +108 -0
- package/src/core/modules/polls/poll-service.ts +477 -0
- package/src/core/modules/polls/poll-store.ts +336 -0
- package/src/core/modules/polls/poll-tools.ts +118 -0
- package/src/core/modules/polls/poll-turn-text.ts +60 -0
- package/src/core/plugin-api/define.ts +9 -2
- package/src/core/plugin-api/holds.ts +2 -0
- package/src/core/plugin-api/plugin.ts +8 -0
- package/src/core/runner/protocol.ts +456 -0
- package/src/core/runner/runner-client.ts +450 -0
- package/src/core/runner/runner-drivers.ts +356 -0
- package/src/core/runner/runner-files.ts +102 -0
- package/src/core/runner/runner-holds.ts +76 -0
- package/src/core/runner/runner-port.ts +77 -0
- package/src/core/runner/runner-probe.ts +53 -0
- package/src/core/runner/runner-prompt.ts +36 -0
- package/src/core/runner/runner-session.ts +131 -0
- package/src/core/runner/runner-tiers.ts +20 -0
- package/src/core/runner/runner-tools.ts +325 -0
- package/src/core/runner/settings.ts +108 -0
- package/src/core/runtime/conversation-sessions.ts +73 -15
- package/src/core/runtime/extensions/approval-card.ts +29 -2
- package/src/core/runtime/extensions/confirmation-gate.ts +24 -63
- package/src/core/runtime/extensions/gate-card.ts +105 -0
- package/src/core/runtime/extensions/yolo.ts +17 -3
- package/src/core/runtime/pi-agent-runtime.ts +37 -68
- package/src/core/runtime/runtime-plugin.ts +9 -0
- package/src/core/runtime/runtime-types.ts +29 -1
- package/src/core/runtime/session-factory.ts +59 -62
- package/src/core/runtime/session-shell.ts +43 -0
- package/src/core/runtime/session-tool-names.ts +78 -0
- package/src/core/runtime/turn-selection.ts +97 -0
- package/src/core/shared/attachment-reader.ts +10 -1
- package/src/core/shared/generate-image-tool.ts +4 -4
- package/src/core/shared/poll-target.ts +14 -0
- package/src/core/shared/workspace-files.ts +42 -4
- package/src/core/testing/fake-polls.ts +131 -0
- package/src/core/testing/fake-runner.ts +146 -0
- package/src/core/testing/surface-contract-approvals.ts +215 -0
- package/src/core/testing/surface-contract-polls.ts +142 -0
- package/src/core/testing/surface-contract.ts +32 -208
- package/src/core/tool-set.snapshot.json +8 -0
- package/src/index.ts +17 -0
- package/src/kit/index.ts +6 -0
- package/src/kit/polls.ts +8 -0
- package/src/runner-server/exec.ts +174 -0
- package/src/runner-server/file-helper.ts +208 -0
- package/src/runner-server/files.ts +93 -0
- package/src/runner-server/host.ts +65 -0
- package/src/runner-server/main.ts +89 -0
- package/src/runner-server/server.ts +318 -0
- package/src/runner-server/shared-dirs.ts +45 -0
- package/src/runner-server/state.ts +293 -0
- package/src/runner-server/transports.ts +187 -0
- package/src/testing.ts +7 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { Readable, Writable } from "node:stream";
|
|
5
|
+
|
|
6
|
+
/** The search path every command gets; the image installs everything under it. */
|
|
7
|
+
export const COMMAND_PATH =
|
|
8
|
+
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
|
9
|
+
|
|
10
|
+
/** The only environment names a command sees. */
|
|
11
|
+
export const COMMAND_ENV_NAMES = [
|
|
12
|
+
"PATH",
|
|
13
|
+
"HOME",
|
|
14
|
+
"TMPDIR",
|
|
15
|
+
"LANG",
|
|
16
|
+
"TERM",
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
/** A command's whole environment: nothing of the server's own, no credential, no host variable. */
|
|
20
|
+
export function commandEnv(
|
|
21
|
+
dir: string,
|
|
22
|
+
): Record<(typeof COMMAND_ENV_NAMES)[number], string> {
|
|
23
|
+
return {
|
|
24
|
+
PATH: COMMAND_PATH,
|
|
25
|
+
HOME: dir,
|
|
26
|
+
TMPDIR: join(dir, ".tmp"),
|
|
27
|
+
LANG: "C.UTF-8",
|
|
28
|
+
TERM: "dumb",
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The argv that runs a command: bash reads the script from fd 3, closes it, and evaluates it, so
|
|
34
|
+
* the command's text is never an argument, which every uid could read in `/proc/<pid>/cmdline`
|
|
35
|
+
* while it runs. (The arguments of the programs the script starts, such as `python3 -c ...`, are
|
|
36
|
+
* theirs and stay readable there.) `/dev/fd/3` cannot be opened instead: Node's pipes are
|
|
37
|
+
* sockets, and a socket cannot be reopened by path.
|
|
38
|
+
*/
|
|
39
|
+
export const COMMAND_ARGV: readonly string[] = Object.freeze([
|
|
40
|
+
"bash",
|
|
41
|
+
"-c",
|
|
42
|
+
'IFS= read -r -d "" __roundtable_script <&3; exec 3<&-; eval "$__roundtable_script"',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
export interface CommandRun {
|
|
46
|
+
argv: readonly string[];
|
|
47
|
+
/** Written to the command's fd 3 and closed, for `COMMAND_ARGV` to read. */
|
|
48
|
+
script?: string;
|
|
49
|
+
cwd: string;
|
|
50
|
+
env: Record<string, string>;
|
|
51
|
+
timeoutMs: number;
|
|
52
|
+
maxOutputBytes: number;
|
|
53
|
+
signal: AbortSignal;
|
|
54
|
+
onData(chunk: Uint8Array): void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CommandResult {
|
|
58
|
+
/** The exit code, or 128 + the signal's number when the command was killed. */
|
|
59
|
+
code: number;
|
|
60
|
+
cut: boolean;
|
|
61
|
+
timedOut: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** How long output may still arrive after the main process ended and its group was killed. */
|
|
65
|
+
const DRAIN_MS = 1_000;
|
|
66
|
+
|
|
67
|
+
function signalCode(signal: NodeJS.Signals | null): number {
|
|
68
|
+
const number = signal ? constants.signals[signal] : undefined;
|
|
69
|
+
return 128 + (number ?? 9);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Runs one command in a process group of its own, streaming stdout and stderr together. Past
|
|
74
|
+
* `maxOutputBytes` the output is cut at the limit and the group killed; at the timeout or an abort
|
|
75
|
+
* the group is killed. Once the main process ends its group is killed and `cleanup` runs (the
|
|
76
|
+
* server kills every process of the conversation's uid there), so a background process that kept
|
|
77
|
+
* the output open cannot hold the call.
|
|
78
|
+
*/
|
|
79
|
+
export function runCommand(
|
|
80
|
+
run: CommandRun,
|
|
81
|
+
cleanup: () => Promise<void>,
|
|
82
|
+
): Promise<CommandResult> {
|
|
83
|
+
const [command, ...args] = run.argv;
|
|
84
|
+
if (command === undefined) throw new Error("an empty command line");
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
let sent = 0;
|
|
87
|
+
let cut = false;
|
|
88
|
+
let timedOut = false;
|
|
89
|
+
let exitCode: number | undefined;
|
|
90
|
+
let finished = false;
|
|
91
|
+
const child = spawn(command, args, {
|
|
92
|
+
cwd: run.cwd,
|
|
93
|
+
env: run.env,
|
|
94
|
+
detached: true,
|
|
95
|
+
stdio: [
|
|
96
|
+
"ignore",
|
|
97
|
+
"pipe",
|
|
98
|
+
"pipe",
|
|
99
|
+
run.script === undefined ? "ignore" : "pipe",
|
|
100
|
+
],
|
|
101
|
+
});
|
|
102
|
+
const scriptIn = child.stdio[3] as Writable | null;
|
|
103
|
+
if (scriptIn && run.script !== undefined) {
|
|
104
|
+
// A command that ended before reading its script makes this fail; its exit says why.
|
|
105
|
+
scriptIn.on("error", () => undefined);
|
|
106
|
+
scriptIn.end(run.script);
|
|
107
|
+
}
|
|
108
|
+
// Piped above; the fourth descriptor only widens what the types know of them.
|
|
109
|
+
const stdout = child.stdout as Readable;
|
|
110
|
+
const stderr = child.stderr as Readable;
|
|
111
|
+
const killGroup = () => {
|
|
112
|
+
if (child.pid === undefined) return;
|
|
113
|
+
try {
|
|
114
|
+
process.kill(-child.pid, "SIGKILL");
|
|
115
|
+
} catch {
|
|
116
|
+
// The group is already gone.
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const onData = (chunk: Buffer) => {
|
|
120
|
+
if (cut) return;
|
|
121
|
+
const room = run.maxOutputBytes - sent;
|
|
122
|
+
if (chunk.length > room) {
|
|
123
|
+
cut = true;
|
|
124
|
+
if (room > 0) run.onData(new Uint8Array(chunk.subarray(0, room)));
|
|
125
|
+
sent = run.maxOutputBytes;
|
|
126
|
+
killGroup();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
sent += chunk.length;
|
|
130
|
+
run.onData(new Uint8Array(chunk));
|
|
131
|
+
};
|
|
132
|
+
stdout.on("data", onData);
|
|
133
|
+
stderr.on("data", onData);
|
|
134
|
+
const timer = setTimeout(() => {
|
|
135
|
+
timedOut = true;
|
|
136
|
+
killGroup();
|
|
137
|
+
}, run.timeoutMs);
|
|
138
|
+
const onAbort = () => killGroup();
|
|
139
|
+
run.signal.addEventListener("abort", onAbort, { once: true });
|
|
140
|
+
if (run.signal.aborted) killGroup();
|
|
141
|
+
|
|
142
|
+
const finish = () => {
|
|
143
|
+
if (finished) return;
|
|
144
|
+
finished = true;
|
|
145
|
+
clearTimeout(drain);
|
|
146
|
+
stdout.destroy();
|
|
147
|
+
stderr.destroy();
|
|
148
|
+
resolve({ code: exitCode ?? 137, cut, timedOut });
|
|
149
|
+
};
|
|
150
|
+
let drain: ReturnType<typeof setTimeout> | undefined;
|
|
151
|
+
let closed = false;
|
|
152
|
+
let cleaned = false;
|
|
153
|
+
child.on("close", () => {
|
|
154
|
+
closed = true;
|
|
155
|
+
if (cleaned) finish();
|
|
156
|
+
});
|
|
157
|
+
const ended = (code: number) => {
|
|
158
|
+
if (exitCode !== undefined) return;
|
|
159
|
+
exitCode = code;
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
run.signal.removeEventListener("abort", onAbort);
|
|
162
|
+
killGroup();
|
|
163
|
+
void cleanup()
|
|
164
|
+
.catch(() => undefined)
|
|
165
|
+
.then(() => {
|
|
166
|
+
cleaned = true;
|
|
167
|
+
if (closed) finish();
|
|
168
|
+
else drain = setTimeout(finish, DRAIN_MS);
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
child.on("exit", (code, signal) => ended(code ?? signalCode(signal)));
|
|
172
|
+
child.on("error", () => ended(127));
|
|
173
|
+
});
|
|
174
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import {
|
|
2
|
+
access,
|
|
3
|
+
constants,
|
|
4
|
+
lstat,
|
|
5
|
+
mkdir,
|
|
6
|
+
open,
|
|
7
|
+
readFile,
|
|
8
|
+
realpath,
|
|
9
|
+
stat,
|
|
10
|
+
writeFile,
|
|
11
|
+
} from "node:fs/promises";
|
|
12
|
+
import { dirname } from "node:path";
|
|
13
|
+
import {
|
|
14
|
+
confinedPath,
|
|
15
|
+
type RunnerErrorCode,
|
|
16
|
+
type RunnerStat,
|
|
17
|
+
} from "../core/runner/protocol.ts";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The file helper: one file operation, run as the conversation's uid (the server starts it under
|
|
21
|
+
* `setpriv`), so the kernel enforces what it may touch. The path checks here keep a symlink from
|
|
22
|
+
* leading a workspace operation elsewhere; they are policy, not the boundary.
|
|
23
|
+
*
|
|
24
|
+
* Run as a script it reads one JSON request on stdin and writes one JSON reply on stdout.
|
|
25
|
+
*/
|
|
26
|
+
export type FileOpRequest = { dir: string; path: string } & (
|
|
27
|
+
| { op: "read"; maxBytes: number }
|
|
28
|
+
| { op: "write"; data: string; maxBytes: number }
|
|
29
|
+
| { op: "mkdir" }
|
|
30
|
+
| { op: "access"; mode: "r" | "rw" }
|
|
31
|
+
| { op: "stat" }
|
|
32
|
+
| { op: "detect-image" }
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
export type FileOpReply =
|
|
36
|
+
| { ok: true; result: unknown }
|
|
37
|
+
| { ok: false; code: RunnerErrorCode; message: string };
|
|
38
|
+
|
|
39
|
+
class Refusal extends Error {
|
|
40
|
+
constructor(
|
|
41
|
+
readonly code: RunnerErrorCode,
|
|
42
|
+
message: string,
|
|
43
|
+
) {
|
|
44
|
+
super(message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const outside = (path: string) =>
|
|
49
|
+
new Refusal("outside", `${path} is outside the workspace`);
|
|
50
|
+
|
|
51
|
+
/** Where `path` resolves, refused unless it stays inside `dir`. */
|
|
52
|
+
async function realInside(dir: string, path: string): Promise<string> {
|
|
53
|
+
const real = await realpath(path);
|
|
54
|
+
if (confinedPath(dir, real) === undefined) throw outside(path);
|
|
55
|
+
return real;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The nearest existing ancestor of `path` (or itself), checked to resolve inside `dir`. */
|
|
59
|
+
async function existingAncestorInside(
|
|
60
|
+
dir: string,
|
|
61
|
+
path: string,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
let at = path;
|
|
64
|
+
for (;;) {
|
|
65
|
+
try {
|
|
66
|
+
await lstat(at);
|
|
67
|
+
await realInside(dir, at);
|
|
68
|
+
return;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error instanceof Refusal) throw error;
|
|
71
|
+
const up = dirname(at);
|
|
72
|
+
if (up === at) throw outside(path);
|
|
73
|
+
at = up;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const MAGIC: [string, (head: Buffer) => boolean][] = [
|
|
79
|
+
[
|
|
80
|
+
"image/png",
|
|
81
|
+
(h) =>
|
|
82
|
+
h
|
|
83
|
+
.subarray(0, 8)
|
|
84
|
+
.equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
|
|
85
|
+
],
|
|
86
|
+
["image/jpeg", (h) => h[0] === 0xff && h[1] === 0xd8 && h[2] === 0xff],
|
|
87
|
+
["image/gif", (h) => h.subarray(0, 4).toString("latin1") === "GIF8"],
|
|
88
|
+
[
|
|
89
|
+
"image/webp",
|
|
90
|
+
(h) =>
|
|
91
|
+
h.subarray(0, 4).toString("latin1") === "RIFF" &&
|
|
92
|
+
h.subarray(8, 12).toString("latin1") === "WEBP",
|
|
93
|
+
],
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
async function head(path: string): Promise<Buffer> {
|
|
97
|
+
const handle = await open(path, "r");
|
|
98
|
+
try {
|
|
99
|
+
const buffer = Buffer.alloc(16);
|
|
100
|
+
const { bytesRead } = await handle.read(buffer, 0, 16, 0);
|
|
101
|
+
return buffer.subarray(0, bytesRead);
|
|
102
|
+
} finally {
|
|
103
|
+
await handle.close();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function regularFile(real: string, path: string): Promise<number> {
|
|
108
|
+
const info = await stat(real);
|
|
109
|
+
if (!info.isFile()) throw new Refusal("not-a-file", `${path} is not a file`);
|
|
110
|
+
return info.size;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function run(request: FileOpRequest): Promise<unknown> {
|
|
114
|
+
const dir = await realpath(request.dir);
|
|
115
|
+
const path = confinedPath(request.dir, request.path);
|
|
116
|
+
if (path === undefined) throw outside(request.path);
|
|
117
|
+
switch (request.op) {
|
|
118
|
+
case "read": {
|
|
119
|
+
const real = await realInside(dir, path);
|
|
120
|
+
const tooLarge = () =>
|
|
121
|
+
new Refusal("too-large", `${path} is over ${request.maxBytes} bytes`);
|
|
122
|
+
if ((await regularFile(real, path)) > request.maxBytes) throw tooLarge();
|
|
123
|
+
const data = await readFile(real);
|
|
124
|
+
if (data.length > request.maxBytes) throw tooLarge();
|
|
125
|
+
return { data: data.toString("base64") };
|
|
126
|
+
}
|
|
127
|
+
case "write": {
|
|
128
|
+
const data = Buffer.from(request.data, "base64");
|
|
129
|
+
if (data.length > request.maxBytes)
|
|
130
|
+
throw new Refusal(
|
|
131
|
+
"too-large",
|
|
132
|
+
`the content is over ${request.maxBytes} bytes`,
|
|
133
|
+
);
|
|
134
|
+
const exists = await lstat(path).then(
|
|
135
|
+
() => true,
|
|
136
|
+
() => false,
|
|
137
|
+
);
|
|
138
|
+
await realInside(dir, exists ? path : dirname(path));
|
|
139
|
+
await writeFile(path, data);
|
|
140
|
+
return {};
|
|
141
|
+
}
|
|
142
|
+
case "mkdir":
|
|
143
|
+
await existingAncestorInside(dir, path);
|
|
144
|
+
await mkdir(path, { recursive: true });
|
|
145
|
+
return {};
|
|
146
|
+
case "access":
|
|
147
|
+
await access(
|
|
148
|
+
await realInside(dir, path),
|
|
149
|
+
request.mode === "rw"
|
|
150
|
+
? constants.R_OK | constants.W_OK
|
|
151
|
+
: constants.R_OK,
|
|
152
|
+
);
|
|
153
|
+
return {};
|
|
154
|
+
case "stat": {
|
|
155
|
+
const real = await realInside(dir, path);
|
|
156
|
+
const info = await stat(real);
|
|
157
|
+
const result: RunnerStat = {
|
|
158
|
+
kind: info.isFile()
|
|
159
|
+
? "file"
|
|
160
|
+
: info.isDirectory()
|
|
161
|
+
? "directory"
|
|
162
|
+
: "other",
|
|
163
|
+
size: info.size,
|
|
164
|
+
mtimeMs: info.mtimeMs,
|
|
165
|
+
path: real,
|
|
166
|
+
};
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
case "detect-image": {
|
|
170
|
+
const real = await realInside(dir, path);
|
|
171
|
+
await regularFile(real, path);
|
|
172
|
+
const bytes = await head(real);
|
|
173
|
+
return {
|
|
174
|
+
mimeType: MAGIC.find(([, matches]) => matches(bytes))?.[0] ?? null,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const CODES: Record<string, RunnerErrorCode> = {
|
|
181
|
+
ENOENT: "not-found",
|
|
182
|
+
ENOTDIR: "not-found",
|
|
183
|
+
EACCES: "denied",
|
|
184
|
+
EPERM: "denied",
|
|
185
|
+
EISDIR: "not-a-file",
|
|
186
|
+
ELOOP: "outside",
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/** Runs one request; every failure comes back as a reply, never thrown. */
|
|
190
|
+
export async function fileOp(request: FileOpRequest): Promise<FileOpReply> {
|
|
191
|
+
try {
|
|
192
|
+
return { ok: true, result: await run(request) };
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error instanceof Refusal)
|
|
195
|
+
return { ok: false, code: error.code, message: error.message };
|
|
196
|
+
const code = (error as NodeJS.ErrnoException).code ?? "";
|
|
197
|
+
return {
|
|
198
|
+
ok: false,
|
|
199
|
+
code: CODES[code] ?? "failed",
|
|
200
|
+
message: `${request.op} ${request.path}: ${code || "failed"}`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (import.meta.main) {
|
|
206
|
+
const request = JSON.parse(await Bun.stdin.text()) as FileOpRequest;
|
|
207
|
+
process.stdout.write(JSON.stringify(await fileOp(request)));
|
|
208
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { MAX_FRAME_BYTES } from "../core/runner/protocol.ts";
|
|
4
|
+
import { COMMAND_PATH } from "./exec.ts";
|
|
5
|
+
import type { FileOpReply, FileOpRequest } from "./file-helper.ts";
|
|
6
|
+
import type { RunnerHost } from "./host.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The helper's argv when the server runs from its source, as it does in the image. Bun reads no
|
|
10
|
+
* config and no env file beyond what this names: the conversation could plant a `bunfig.toml`
|
|
11
|
+
* whose preload, or a `.env`, would otherwise run or steer code as its uid.
|
|
12
|
+
*/
|
|
13
|
+
export const DEFAULT_HELPER = [
|
|
14
|
+
process.execPath,
|
|
15
|
+
"--no-env-file",
|
|
16
|
+
"--config=/dev/null",
|
|
17
|
+
join(import.meta.dir, "file-helper.ts"),
|
|
18
|
+
] as const;
|
|
19
|
+
|
|
20
|
+
/** A file operation that has not answered by then is killed. */
|
|
21
|
+
const HELPER_TIMEOUT_MS = 60_000;
|
|
22
|
+
|
|
23
|
+
const failed = (message: string): FileOpReply => ({
|
|
24
|
+
ok: false,
|
|
25
|
+
code: "failed",
|
|
26
|
+
message,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Runs one file operation in the helper, as `uid`, with no environment but what Bun needs to start.
|
|
31
|
+
* It starts in `/` with `HOME` at `/`, which the uid cannot write, so nothing of the conversation's
|
|
32
|
+
* directory is picked up as configuration; the paths it gets are absolute.
|
|
33
|
+
*/
|
|
34
|
+
export function runFileOp(
|
|
35
|
+
host: RunnerHost,
|
|
36
|
+
uid: number,
|
|
37
|
+
request: FileOpRequest,
|
|
38
|
+
helper: readonly string[] = DEFAULT_HELPER,
|
|
39
|
+
): Promise<FileOpReply> {
|
|
40
|
+
const [command, ...args] = host.asUser(uid, helper);
|
|
41
|
+
if (command === undefined) return Promise.resolve(failed("no file helper"));
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const child = spawn(command, args, {
|
|
44
|
+
cwd: "/",
|
|
45
|
+
env: {
|
|
46
|
+
PATH: COMMAND_PATH,
|
|
47
|
+
HOME: "/",
|
|
48
|
+
LANG: "C.UTF-8",
|
|
49
|
+
// The helper runs on a read-only image; Bun need not cache its transpilation.
|
|
50
|
+
BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0",
|
|
51
|
+
},
|
|
52
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
53
|
+
});
|
|
54
|
+
const chunks: Buffer[] = [];
|
|
55
|
+
let size = 0;
|
|
56
|
+
let settled = false;
|
|
57
|
+
const settle = (reply: FileOpReply) => {
|
|
58
|
+
if (settled) return;
|
|
59
|
+
settled = true;
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
resolve(reply);
|
|
62
|
+
};
|
|
63
|
+
const timer = setTimeout(() => {
|
|
64
|
+
child.kill("SIGKILL");
|
|
65
|
+
settle(failed(`${request.op} ${request.path} took too long`));
|
|
66
|
+
}, HELPER_TIMEOUT_MS);
|
|
67
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
68
|
+
size += chunk.length;
|
|
69
|
+
if (size > MAX_FRAME_BYTES) {
|
|
70
|
+
child.kill("SIGKILL");
|
|
71
|
+
settle(failed(`${request.op} ${request.path} answered too much`));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
chunks.push(chunk);
|
|
75
|
+
});
|
|
76
|
+
child.on("error", (error) => settle(failed(error.message)));
|
|
77
|
+
child.on("close", (code) => {
|
|
78
|
+
try {
|
|
79
|
+
const reply = JSON.parse(
|
|
80
|
+
Buffer.concat(chunks).toString(),
|
|
81
|
+
) as FileOpReply;
|
|
82
|
+
if (typeof reply?.ok === "boolean") return settle(reply);
|
|
83
|
+
} catch {
|
|
84
|
+
// Reported below.
|
|
85
|
+
}
|
|
86
|
+
settle(
|
|
87
|
+
failed(`${request.op} ${request.path} failed (helper exit ${code})`),
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
child.stdin.on("error", () => undefined);
|
|
91
|
+
child.stdin.end(JSON.stringify(request));
|
|
92
|
+
});
|
|
93
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { lstatSync } from "node:fs";
|
|
3
|
+
import { chown } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
/** What the runner server needs of the machine beyond plain files: dropping to a uid, and its powers as root. */
|
|
6
|
+
export interface RunnerHost {
|
|
7
|
+
/** The argv that runs `argv` as `uid` (its own group, no supplementary groups, no capabilities). */
|
|
8
|
+
asUser(uid: number, argv: readonly string[]): string[];
|
|
9
|
+
/** Gives `path` (never a symlink the runner did not make) to `uid`. */
|
|
10
|
+
chown(path: string, uid: number): Promise<void>;
|
|
11
|
+
/** The uid that owns `path` itself, not what a symlink there points to; read at once, so a caller's order holds. */
|
|
12
|
+
ownerOf(path: string): number;
|
|
13
|
+
/** Kills every process running as `uid`. */
|
|
14
|
+
killUser(uid: number): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Spawns `argv` with no environment and no output, resolving to its exit code. */
|
|
18
|
+
export function runQuiet(argv: readonly string[]): Promise<number> {
|
|
19
|
+
const [command, ...args] = argv;
|
|
20
|
+
if (command === undefined) return Promise.resolve(127);
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
const child = spawn(command, args, {
|
|
23
|
+
stdio: "ignore",
|
|
24
|
+
env: { PATH: "/usr/sbin:/usr/bin:/sbin:/bin" },
|
|
25
|
+
});
|
|
26
|
+
child.on("error", () => resolve(127));
|
|
27
|
+
child.on("close", (code) => resolve(code ?? 128));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The argv prefix that drops to `uid` for good. The container holds no CAP_SETPCAP, so the bounding
|
|
33
|
+
* set cannot be cleared here; it does not need to be: the uid is not 0, no capability is inherited
|
|
34
|
+
* or ambient, and no_new_privs stops a setuid or file-capability binary from granting one.
|
|
35
|
+
*/
|
|
36
|
+
export function setprivArgs(uid: number): string[] {
|
|
37
|
+
return [
|
|
38
|
+
"setpriv",
|
|
39
|
+
`--reuid=${uid}`,
|
|
40
|
+
`--regid=${uid}`,
|
|
41
|
+
"--clear-groups",
|
|
42
|
+
"--no-new-privs",
|
|
43
|
+
"--inh-caps=-all",
|
|
44
|
+
"--",
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The runner container's host: root with only the capabilities the runner needs, `setpriv` from util-linux. */
|
|
49
|
+
export function setprivHost(): RunnerHost {
|
|
50
|
+
return {
|
|
51
|
+
asUser: (uid, argv) => [...setprivArgs(uid), ...argv],
|
|
52
|
+
chown: (path, uid) => chown(path, uid, uid),
|
|
53
|
+
ownerOf: (path) => lstatSync(path).uid,
|
|
54
|
+
// kill(-1) as the uid reaches exactly that uid's processes, except the killer itself, and
|
|
55
|
+
// is atomic against fork, so nothing it misses can start again.
|
|
56
|
+
killUser: async (uid) => {
|
|
57
|
+
await runQuiet([
|
|
58
|
+
...setprivArgs(uid),
|
|
59
|
+
"bash",
|
|
60
|
+
"-c",
|
|
61
|
+
"kill -KILL -1 2>/dev/null; exit 0",
|
|
62
|
+
]);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
RUNNER_SOCKET,
|
|
5
|
+
RUNNER_TOKEN_FILE,
|
|
6
|
+
RUNNER_WORKSPACES,
|
|
7
|
+
} from "../core/runner/protocol.ts";
|
|
8
|
+
import { setprivHost } from "./host.ts";
|
|
9
|
+
import { RunnerServer } from "./server.ts";
|
|
10
|
+
import { lockSharedDirs } from "./shared-dirs.ts";
|
|
11
|
+
import {
|
|
12
|
+
listenSocket,
|
|
13
|
+
prepareSocketDir,
|
|
14
|
+
relayStdio,
|
|
15
|
+
writeBootToken,
|
|
16
|
+
} from "./transports.ts";
|
|
17
|
+
|
|
18
|
+
const USAGE = `usage:
|
|
19
|
+
roundtable-runner serve [--socket <path>] [--workspaces <dir>]
|
|
20
|
+
Runs the runner server on a unix socket (default ${RUNNER_SOCKET}), writing a per-boot token
|
|
21
|
+
beside it. Runs as root inside the runner container.
|
|
22
|
+
roundtable-runner serve --stdio [--socket <path>]
|
|
23
|
+
Relays one client on stdin and stdout to the running server (for docker exec -i).`;
|
|
24
|
+
|
|
25
|
+
function parse(argv: string[]) {
|
|
26
|
+
const [command, ...rest] = argv;
|
|
27
|
+
if (command !== "serve") return undefined;
|
|
28
|
+
const options = {
|
|
29
|
+
stdio: false,
|
|
30
|
+
socket: RUNNER_SOCKET,
|
|
31
|
+
workspaces: RUNNER_WORKSPACES,
|
|
32
|
+
};
|
|
33
|
+
for (let i = 0; i < rest.length; i++) {
|
|
34
|
+
const flag = rest[i];
|
|
35
|
+
if (flag === "--stdio") options.stdio = true;
|
|
36
|
+
else if (flag === "--socket" || flag === "--workspaces") {
|
|
37
|
+
const value = rest[++i];
|
|
38
|
+
if (value === undefined) return undefined;
|
|
39
|
+
options[flag === "--socket" ? "socket" : "workspaces"] = value;
|
|
40
|
+
} else return undefined;
|
|
41
|
+
}
|
|
42
|
+
return options;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function serve(socket: string, workspaces: string): Promise<void> {
|
|
46
|
+
if (process.platform !== "linux" || process.getuid?.() !== 0)
|
|
47
|
+
throw new Error(
|
|
48
|
+
"the runner server runs as root on Linux, inside its container",
|
|
49
|
+
);
|
|
50
|
+
// Whatever a command or the file helper creates is private to its uid unless it says otherwise.
|
|
51
|
+
process.umask(0o077);
|
|
52
|
+
// No directory every uid may write, where one conversation could leave something for another.
|
|
53
|
+
lockSharedDirs();
|
|
54
|
+
const dir = dirname(socket);
|
|
55
|
+
const owner = await prepareSocketDir(dir);
|
|
56
|
+
const token = await writeBootToken(dir, owner);
|
|
57
|
+
const server = await RunnerServer.open({
|
|
58
|
+
workspaces,
|
|
59
|
+
host: setprivHost(),
|
|
60
|
+
token,
|
|
61
|
+
// A conversation running as the socket directory's owner could read the token beside it.
|
|
62
|
+
reservedUids: [owner],
|
|
63
|
+
});
|
|
64
|
+
const listener = await listenSocket(server, socket, owner);
|
|
65
|
+
process.stderr.write(`roundtable-runner listening on ${socket}\n`);
|
|
66
|
+
const stop = () => listener.close(() => process.exit(0));
|
|
67
|
+
process.once("SIGTERM", stop);
|
|
68
|
+
process.once("SIGINT", stop);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const options = parse(process.argv.slice(2));
|
|
72
|
+
if (options === undefined) {
|
|
73
|
+
process.stderr.write(`${USAGE}\n`);
|
|
74
|
+
process.exit(2);
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
if (options.stdio) {
|
|
78
|
+
await relayStdio({
|
|
79
|
+
socket: options.socket,
|
|
80
|
+
tokenFile: join(dirname(options.socket), RUNNER_TOKEN_FILE),
|
|
81
|
+
input: process.stdin,
|
|
82
|
+
output: process.stdout,
|
|
83
|
+
});
|
|
84
|
+
process.exit(0);
|
|
85
|
+
} else await serve(options.socket, options.workspaces);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
process.stderr.write(`roundtable-runner: ${(error as Error).message}\n`);
|
|
88
|
+
process.exit(1);
|
|
89
|
+
}
|