pi-roundtable 0.53.6 → 0.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +6 -2
  3. package/README.zh-TW.md +6 -2
  4. package/docs/plugins.md +199 -7
  5. package/package.json +3 -1
  6. package/runner/Dockerfile +46 -0
  7. package/runner/Dockerfile.dockerignore +5 -0
  8. package/src/cli/checks/images.ts +3 -2
  9. package/src/cli/checks/preset.ts +20 -0
  10. package/src/cli/checks/runner.ts +45 -0
  11. package/src/cli/doctor.ts +7 -1
  12. package/src/core/agents/agent-claim.ts +7 -4
  13. package/src/core/agents/agent-prompt.ts +11 -2
  14. package/src/core/agents/helper-workspace.ts +72 -0
  15. package/src/core/agents/team-options.ts +2 -0
  16. package/src/core/agents/team-prompt.ts +12 -1
  17. package/src/core/builtin/agent-server.ts +8 -0
  18. package/src/core/builtin/polls.ts +67 -0
  19. package/src/core/builtin/runner.ts +139 -0
  20. package/src/core/config/config-schema.ts +4 -0
  21. package/src/core/config/config.ts +49 -185
  22. package/src/core/config/preset.ts +51 -0
  23. package/src/core/config/resolve-config.ts +175 -0
  24. package/src/core/config/runner-config.ts +80 -0
  25. package/src/core/contract/polls.ts +71 -0
  26. package/src/core/contract/runtime.ts +12 -0
  27. package/src/core/contract/surface.ts +13 -0
  28. package/src/core/discord/discord-polls.ts +156 -0
  29. package/src/core/discord/discord-replies.ts +55 -0
  30. package/src/core/discord/discord-surface.ts +13 -43
  31. package/src/core/domain/errors.ts +5 -0
  32. package/src/core/domain/sessions.ts +8 -1
  33. package/src/core/host/define-roundtable.ts +8 -0
  34. package/src/core/host/host-registration.ts +7 -0
  35. package/src/core/host/host.ts +8 -0
  36. package/src/core/i18n/schedules.ts +2 -0
  37. package/src/core/modules/polls/poll-result-turns.ts +124 -0
  38. package/src/core/modules/polls/poll-rules.ts +108 -0
  39. package/src/core/modules/polls/poll-service.ts +477 -0
  40. package/src/core/modules/polls/poll-store.ts +336 -0
  41. package/src/core/modules/polls/poll-tools.ts +118 -0
  42. package/src/core/modules/polls/poll-turn-text.ts +60 -0
  43. package/src/core/plugin-api/define.ts +9 -2
  44. package/src/core/plugin-api/holds.ts +2 -0
  45. package/src/core/plugin-api/plugin.ts +8 -0
  46. package/src/core/runner/protocol.ts +456 -0
  47. package/src/core/runner/runner-client.ts +450 -0
  48. package/src/core/runner/runner-drivers.ts +356 -0
  49. package/src/core/runner/runner-files.ts +102 -0
  50. package/src/core/runner/runner-holds.ts +76 -0
  51. package/src/core/runner/runner-port.ts +77 -0
  52. package/src/core/runner/runner-probe.ts +53 -0
  53. package/src/core/runner/runner-prompt.ts +36 -0
  54. package/src/core/runner/runner-session.ts +131 -0
  55. package/src/core/runner/runner-tiers.ts +20 -0
  56. package/src/core/runner/runner-tools.ts +325 -0
  57. package/src/core/runner/settings.ts +108 -0
  58. package/src/core/runtime/conversation-sessions.ts +73 -15
  59. package/src/core/runtime/extensions/approval-card.ts +29 -2
  60. package/src/core/runtime/extensions/confirmation-gate.ts +24 -63
  61. package/src/core/runtime/extensions/gate-card.ts +105 -0
  62. package/src/core/runtime/extensions/yolo.ts +17 -3
  63. package/src/core/runtime/pi-agent-runtime.ts +37 -68
  64. package/src/core/runtime/runtime-plugin.ts +9 -0
  65. package/src/core/runtime/runtime-types.ts +29 -1
  66. package/src/core/runtime/session-factory.ts +59 -62
  67. package/src/core/runtime/session-shell.ts +43 -0
  68. package/src/core/runtime/session-tool-names.ts +78 -0
  69. package/src/core/runtime/turn-selection.ts +97 -0
  70. package/src/core/shared/generate-image-tool.ts +4 -4
  71. package/src/core/shared/poll-target.ts +14 -0
  72. package/src/core/shared/workspace-files.ts +42 -4
  73. package/src/core/testing/fake-polls.ts +131 -0
  74. package/src/core/testing/fake-runner.ts +146 -0
  75. package/src/core/testing/surface-contract-approvals.ts +215 -0
  76. package/src/core/testing/surface-contract-polls.ts +142 -0
  77. package/src/core/testing/surface-contract.ts +32 -208
  78. package/src/core/tool-set.snapshot.json +8 -0
  79. package/src/index.ts +17 -0
  80. package/src/kit/index.ts +6 -0
  81. package/src/kit/polls.ts +8 -0
  82. package/src/runner-server/exec.ts +174 -0
  83. package/src/runner-server/file-helper.ts +208 -0
  84. package/src/runner-server/files.ts +93 -0
  85. package/src/runner-server/host.ts +65 -0
  86. package/src/runner-server/main.ts +89 -0
  87. package/src/runner-server/server.ts +318 -0
  88. package/src/runner-server/shared-dirs.ts +45 -0
  89. package/src/runner-server/state.ts +293 -0
  90. package/src/runner-server/transports.ts +187 -0
  91. package/src/testing.ts +7 -0
@@ -0,0 +1,356 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import { connect, type Socket } from "node:net";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { ConfigError } from "../domain/errors.ts";
7
+ import {
8
+ RUNNER_SOCKET,
9
+ RUNNER_TOKEN_FILE,
10
+ RUNNER_WORKSPACES,
11
+ } from "./protocol.ts";
12
+ import type { RunnerDriver, RunnerStream } from "./runner-client.ts";
13
+ import { RunnerError } from "./runner-port.ts";
14
+ import { RUNNER_DOCKER_DEFAULTS, type RunnerSettings } from "./settings.ts";
15
+
16
+ /** A socket as a runner stream. */
17
+ export function socketStream(socket: Socket): RunnerStream {
18
+ return {
19
+ write: (text) => void socket.write(text),
20
+ end: () => void socket.end(),
21
+ onData: (listener) => void socket.on("data", listener),
22
+ onClose: (listener) => {
23
+ let reason: string | undefined;
24
+ socket.on("error", (error) => {
25
+ reason = error.message;
26
+ });
27
+ socket.once("close", () => listener(reason));
28
+ },
29
+ };
30
+ }
31
+
32
+ /** A child process's stdin and stdout as a runner stream; its stderr says why it ended. */
33
+ export function processStream(child: ChildProcess): RunnerStream {
34
+ let stderr = "";
35
+ child.stderr?.on("data", (chunk: Buffer) => {
36
+ if (stderr.length < 4096) stderr += chunk.toString();
37
+ });
38
+ child.stdin?.on("error", () => undefined);
39
+ return {
40
+ write: (text) => void child.stdin?.write(text),
41
+ end: () => {
42
+ child.stdin?.end();
43
+ child.kill();
44
+ },
45
+ onData: (listener) => void child.stdout?.on("data", listener),
46
+ onClose: (listener) => {
47
+ child.once("error", (error) => {
48
+ stderr ||= error.message;
49
+ });
50
+ child.once("close", (code) =>
51
+ listener(
52
+ stderr.trim() || `the runner's relay exited with code ${code ?? "?"}`,
53
+ ),
54
+ );
55
+ },
56
+ };
57
+ }
58
+
59
+ /** How long the socket driver waits at start for the sidecar's socket, and the docker driver for its container. */
60
+ export const RUNNER_START_WAIT_MS = 30_000;
61
+
62
+ /** The sidecar driver: the runner's unix socket, and the per-boot token beside it. */
63
+ export function socketDriver(
64
+ socket: string,
65
+ ): RunnerDriver & { ready(waitMs?: number): Promise<boolean> } {
66
+ const tokenFile = join(dirname(socket), RUNNER_TOKEN_FILE);
67
+ return {
68
+ target: socket,
69
+ connect: async () => {
70
+ // Read on each connect, so a runner restarted with a new token is picked up.
71
+ const token = (await readFile(tokenFile, "utf8")).trim();
72
+ const stream = await new Promise<Socket>((done, fail) => {
73
+ const opened = connect(socket);
74
+ opened.once("connect", () => {
75
+ opened.off("error", fail);
76
+ done(opened);
77
+ });
78
+ opened.once("error", fail);
79
+ });
80
+ return { stream: socketStream(stream), token };
81
+ },
82
+ ready: async (waitMs = RUNNER_START_WAIT_MS) => {
83
+ const until = Date.now() + waitMs;
84
+ for (;;) {
85
+ const found = await stat(socket).then(
86
+ (info) => info.isSocket(),
87
+ () => false,
88
+ );
89
+ if (found || Date.now() >= until) return found;
90
+ await Bun.sleep(250);
91
+ }
92
+ },
93
+ };
94
+ }
95
+
96
+ /** What a command printed and how it ended. */
97
+ export interface CommandResult {
98
+ code: number;
99
+ stdout: string;
100
+ stderr: string;
101
+ }
102
+
103
+ /** Runs a command to its end; the docker driver's way to call the docker CLI. */
104
+ export type CommandRun = (argv: readonly string[]) => Promise<CommandResult>;
105
+
106
+ export const runCommand: CommandRun = (argv) => {
107
+ const [command, ...args] = argv;
108
+ return new Promise((done) => {
109
+ const child = spawn(command ?? "false", args, {
110
+ stdio: ["ignore", "pipe", "pipe"],
111
+ });
112
+ let stdout = "";
113
+ let stderr = "";
114
+ child.stdout.on("data", (chunk: Buffer) => {
115
+ stdout += chunk.toString();
116
+ });
117
+ child.stderr.on("data", (chunk: Buffer) => {
118
+ stderr += chunk.toString();
119
+ });
120
+ child.once("error", (error) =>
121
+ done({ code: 127, stdout, stderr: stderr || error.message }),
122
+ );
123
+ child.once("close", (code) =>
124
+ done({ code: code ?? 128, stdout: stdout.trim(), stderr: stderr.trim() }),
125
+ );
126
+ });
127
+ };
128
+
129
+ /** The container's name: the setting's, else one per data directory. */
130
+ export function runnerContainerName(
131
+ settings: Extract<RunnerSettings, { driver: "docker" }>,
132
+ dataDir: string,
133
+ ): string {
134
+ if (settings.name) return settings.name;
135
+ const digest = createHash("sha256").update(resolve(dataDir)).digest("hex");
136
+ return `roundtable-runner-${digest.slice(0, 12)}`;
137
+ }
138
+
139
+ /** The label that marks a container as a runner this host may replace. */
140
+ export const RUNNER_LABEL = "pi-roundtable.runner";
141
+
142
+ /**
143
+ * The isolation every runner container needs, a sidecar's as well: no network, the six
144
+ * capabilities the server needs and no other, no new privileges, a read-only root, and no
145
+ * directory every uid may write, where one conversation could leave a file for another: `/tmp` is
146
+ * root's (each conversation's TMPDIR is its own `.tmp`), and `--ipc none` mounts no `/dev/shm`, so
147
+ * POSIX shared memory, and Python multiprocessing's locks with it, is not there. The server itself
148
+ * makes the message queue root (`/dev/mqueue`) root's at start, which no flag can, and refuses to
149
+ * start while `/tmp` or `/dev/shm` stays writable by every uid.
150
+ */
151
+ export function runnerIsolationArgs(): string[] {
152
+ return [
153
+ "--network",
154
+ "none",
155
+ "--cap-drop",
156
+ "ALL",
157
+ ...["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"].flatMap(
158
+ (cap) => ["--cap-add", cap],
159
+ ),
160
+ "--security-opt",
161
+ "no-new-privileges",
162
+ "--read-only",
163
+ "--tmpfs",
164
+ "/tmp:mode=0755",
165
+ "--ipc",
166
+ "none",
167
+ ];
168
+ }
169
+
170
+ /**
171
+ * `docker run`'s arguments for the runner: `runnerIsolationArgs`, a tmpfs for the socket
172
+ * directory, the workspaces in a named volume, and the memory, CPU and process limits.
173
+ */
174
+ export function dockerRunArgs(
175
+ settings: Extract<RunnerSettings, { driver: "docker" }>,
176
+ name: string,
177
+ ): string[] {
178
+ const memoryMb = settings.memoryMb ?? RUNNER_DOCKER_DEFAULTS.memoryMb;
179
+ const cpus = settings.cpus ?? RUNNER_DOCKER_DEFAULTS.cpus;
180
+ const pids = settings.pids ?? RUNNER_DOCKER_DEFAULTS.pids;
181
+ return [
182
+ "docker",
183
+ "run",
184
+ "-d",
185
+ "--name",
186
+ name,
187
+ "--label",
188
+ `${RUNNER_LABEL}=1`,
189
+ ...runnerIsolationArgs(),
190
+ "--tmpfs",
191
+ `${dirname(RUNNER_SOCKET)}:mode=0700`,
192
+ "--volume",
193
+ `${name}-ws:${RUNNER_WORKSPACES}`,
194
+ "--memory",
195
+ `${memoryMb}m`,
196
+ "--cpus",
197
+ String(cpus),
198
+ "--pids-limit",
199
+ String(pids),
200
+ settings.image,
201
+ ];
202
+ }
203
+
204
+ const short = (result: CommandResult) =>
205
+ (result.stderr || result.stdout).split("\n")[0] ?? "";
206
+
207
+ /**
208
+ * The plain-host driver: a container the host runs itself, reached through one `docker exec -i
209
+ * <container> roundtable-runner serve --stdio` per stream. Docker access is the authentication, so
210
+ * no token or socket crosses into the host, which also works with Docker Desktop.
211
+ */
212
+ export class DockerDriver implements RunnerDriver {
213
+ readonly target: string;
214
+ readonly name: string;
215
+ readonly #settings: Extract<RunnerSettings, { driver: "docker" }>;
216
+ readonly #run: CommandRun;
217
+ readonly #spawn: (argv: readonly string[]) => ChildProcess;
218
+ #ensuring: Promise<void> | undefined;
219
+
220
+ constructor(
221
+ settings: Extract<RunnerSettings, { driver: "docker" }>,
222
+ dataDir: string,
223
+ run: CommandRun = runCommand,
224
+ spawnRelay: (argv: readonly string[]) => ChildProcess = ([cmd, ...args]) =>
225
+ spawn(cmd ?? "docker", args, { stdio: ["pipe", "pipe", "pipe"] }),
226
+ ) {
227
+ this.#settings = settings;
228
+ this.target = settings.image;
229
+ this.name = runnerContainerName(settings, dataDir);
230
+ this.#run = run;
231
+ this.#spawn = spawnRelay;
232
+ }
233
+
234
+ /** Refuses to start without the docker CLI or the image, naming `runner.image`; then starts the container. */
235
+ async check(): Promise<void> {
236
+ await this.installed();
237
+ await this.ensure();
238
+ }
239
+
240
+ /** Throws a ConfigError naming `runner.image` without the docker CLI or the image. */
241
+ async installed(): Promise<void> {
242
+ const version = await this.#run([
243
+ "docker",
244
+ "version",
245
+ "--format",
246
+ "{{.Client.Version}}",
247
+ ]);
248
+ if (version.code === 127)
249
+ throw new ConfigError(
250
+ `config runner.image: the docker driver runs ${this.#settings.image} with the docker CLI, which is not installed (${short(version)}). Install Docker, or use driver: "socket" with a runner sidecar.`,
251
+ );
252
+ await this.#imageId();
253
+ }
254
+
255
+ /** Whether the container runs the image now, and is a runner; changes nothing. */
256
+ async running(): Promise<boolean> {
257
+ const found = await this.#container();
258
+ return (
259
+ found?.running === true &&
260
+ found.runner &&
261
+ found.image === (await this.#imageId())
262
+ );
263
+ }
264
+
265
+ async #container(): Promise<
266
+ { running: boolean; image: string; runner: boolean } | undefined
267
+ > {
268
+ const found = await this.#run([
269
+ "docker",
270
+ "container",
271
+ "inspect",
272
+ "--format",
273
+ `{{.State.Running}} {{.Image}} {{index .Config.Labels "${RUNNER_LABEL}"}}`,
274
+ this.name,
275
+ ]);
276
+ if (found.code !== 0) return undefined;
277
+ const [running, image = "", label = ""] = found.stdout.trim().split(" ");
278
+ return { running: running === "true", image, runner: label === "1" };
279
+ }
280
+
281
+ async #imageId(): Promise<string> {
282
+ const image = await this.#run([
283
+ "docker",
284
+ "image",
285
+ "inspect",
286
+ "--format",
287
+ "{{.Id}}",
288
+ this.#settings.image,
289
+ ]);
290
+ if (image.code !== 0 || image.stdout === "")
291
+ throw new ConfigError(
292
+ `config runner.image: the image ${this.#settings.image} is not there (${short(image)}). Build it with \`docker build -t ${this.#settings.image} -f node_modules/pi-roundtable/runner/Dockerfile node_modules/pi-roundtable\`.`,
293
+ );
294
+ return image.stdout;
295
+ }
296
+
297
+ /** Runs the container unless one of its name runs the image; one at a time. */
298
+ ensure(): Promise<void> {
299
+ this.#ensuring ??= this.#ensure().finally(() => {
300
+ this.#ensuring = undefined;
301
+ });
302
+ return this.#ensuring;
303
+ }
304
+
305
+ async #ensure(): Promise<void> {
306
+ const image = await this.#imageId();
307
+ const found = await this.#container();
308
+ if (found) {
309
+ // Only a container this host started as its runner is reused or replaced.
310
+ if (!found.runner)
311
+ throw new ConfigError(
312
+ `config runner.name: a container named ${this.name} is there and is not a runner (it has no label ${RUNNER_LABEL}=1), so it is neither used nor removed. Name another container in runner.name, or remove that one yourself.`,
313
+ );
314
+ if (found.running && found.image === image) return;
315
+ await this.#run(["docker", "rm", "-f", this.name]);
316
+ }
317
+ const started = await this.#run(dockerRunArgs(this.#settings, this.name));
318
+ if (started.code !== 0)
319
+ throw new RunnerError(
320
+ "unreachable",
321
+ `the runner is not reachable: docker run ${this.name} failed (${short(started)})`,
322
+ );
323
+ // The server writes its token and then listens; the relay needs both.
324
+ const until = Date.now() + RUNNER_START_WAIT_MS;
325
+ while (Date.now() < until) {
326
+ const ready = await this.#run([
327
+ "docker",
328
+ "exec",
329
+ this.name,
330
+ "test",
331
+ "-S",
332
+ RUNNER_SOCKET,
333
+ ]);
334
+ if (ready.code === 0) return;
335
+ await Bun.sleep(200);
336
+ }
337
+ throw new RunnerError(
338
+ "unreachable",
339
+ `the runner is not reachable: container ${this.name} did not open its socket`,
340
+ );
341
+ }
342
+
343
+ async connect(): Promise<{ stream: RunnerStream }> {
344
+ await this.ensure();
345
+ const child = this.#spawn([
346
+ "docker",
347
+ "exec",
348
+ "-i",
349
+ this.name,
350
+ "roundtable-runner",
351
+ "serve",
352
+ "--stdio",
353
+ ]);
354
+ return { stream: processStream(child) };
355
+ }
356
+ }
@@ -0,0 +1,102 @@
1
+ import { posix } from "node:path";
2
+ import {
3
+ type WorkspaceFile,
4
+ WorkspaceFileError,
5
+ type WorkspaceFiles,
6
+ } from "../shared/workspace-files.ts";
7
+ import { confinedPath } from "./protocol.ts";
8
+ import { RunnerError } from "./runner-port.ts";
9
+ import type { RunnerBinding } from "./runner-tools.ts";
10
+
11
+ /** What the model is told about a path the runner refused, by the runner's reason. */
12
+ function refusal(path: string, error: unknown): never {
13
+ if (!(error instanceof RunnerError)) throw error;
14
+ switch (error.code) {
15
+ case "not-found":
16
+ throw new WorkspaceFileError(`${path} does not exist.`);
17
+ case "outside":
18
+ throw new WorkspaceFileError(
19
+ `${path} is outside the workspace; only files inside it can be sent.`,
20
+ );
21
+ case "not-a-file":
22
+ throw new WorkspaceFileError(`${path} is not a file.`);
23
+ case "too-large":
24
+ case "denied":
25
+ throw new WorkspaceFileError(`${path}: ${error.message}.`);
26
+ default:
27
+ throw new WorkspaceFileError(
28
+ `${path} could not be read: ${error.message}.`,
29
+ );
30
+ }
31
+ }
32
+
33
+ /**
34
+ * The conversation's files in the runner, for `attach_file`, `generate_image` and the other core
35
+ * tools that take a path: a path resolves against the workspace and must stay inside it, through
36
+ * symlinks too, which the runner follows and judges; nothing is read or written on the host.
37
+ */
38
+ export function runnerWorkspaceFiles(binding: RunnerBinding): WorkspaceFiles {
39
+ const { port, conversation, workspace, settings } = binding;
40
+ const inside = (path: string): string => {
41
+ const absolute = confinedPath(
42
+ workspace,
43
+ posix.resolve(workspace, path.replace(/^@/, "")),
44
+ );
45
+ if (absolute === undefined)
46
+ throw new WorkspaceFileError(
47
+ `${path} is outside the workspace; only files inside it can be sent.`,
48
+ );
49
+ return absolute;
50
+ };
51
+ const files: WorkspaceFiles = {
52
+ find: async (path) => {
53
+ const absolute = inside(path);
54
+ const info = await port
55
+ .stat(conversation, absolute)
56
+ .catch((error: unknown) => refusal(path, error));
57
+ if (
58
+ info.kind !== "file" ||
59
+ confinedPath(workspace, info.path) === undefined
60
+ )
61
+ refusal(
62
+ path,
63
+ new RunnerError(
64
+ info.kind === "file" ? "outside" : "not-a-file",
65
+ info.kind,
66
+ ),
67
+ );
68
+ const file: WorkspaceFile = {
69
+ path,
70
+ realPath: info.path,
71
+ name: posix.basename(absolute),
72
+ size: info.size,
73
+ files,
74
+ };
75
+ return file;
76
+ },
77
+ read: async (file, maxBytes) => {
78
+ const data = await port
79
+ .read(
80
+ conversation,
81
+ file.realPath,
82
+ Math.min(maxBytes, settings.maxFileBytes),
83
+ )
84
+ .catch((error: unknown) => refusal(file.path, error));
85
+ if (data.byteLength > maxBytes)
86
+ throw new WorkspaceFileError(
87
+ `${file.path} is ${data.byteLength} bytes, over the ${maxBytes} allowed.`,
88
+ );
89
+ return new Uint8Array(data);
90
+ },
91
+ write: async (path, data) => {
92
+ const absolute = inside(path);
93
+ try {
94
+ await port.mkdir(conversation, posix.dirname(absolute));
95
+ await port.write(conversation, absolute, data, settings.maxFileBytes);
96
+ } catch (error) {
97
+ refusal(path, error);
98
+ }
99
+ },
100
+ };
101
+ return files;
102
+ }
@@ -0,0 +1,76 @@
1
+ import { shellHoldRuleFor } from "../modules/host-shell/shell-policy.ts";
2
+ import type {
3
+ HoldContext,
4
+ HoldDescription,
5
+ HoldRule,
6
+ } from "../plugin-api/holds.ts";
7
+ import type { RunnerWorkspace } from "./settings.ts";
8
+
9
+ /** The name of the core's hold rule for the runner's shell and file tools. */
10
+ export const RUNNER_SHELL_RULE = "runner-shell";
11
+
12
+ const OWN = `${RUNNER_SHELL_RULE}.`;
13
+
14
+ /**
15
+ * The shell rule's class a runner-shell class stands for (`runner-shell.rm` for `shell.rm`), so
16
+ * yolo mode judges it as it judges the host's; undefined for any other id.
17
+ */
18
+ export function shellClassOf(id: string): string | undefined {
19
+ return id.startsWith(OWN) ? `shell.${id.slice(OWN.length)}` : undefined;
20
+ }
21
+
22
+ const HOST = " on the host";
23
+
24
+ /** The shell rule's sentence with the call placed in the runner: its last "on the host" is where. */
25
+ function inTheRunner(action: string): string {
26
+ const at = action.lastIndexOf(HOST);
27
+ return at < 0
28
+ ? action
29
+ : `${action.slice(0, at)} in the runner${action.slice(at + HOST.length)}`;
30
+ }
31
+
32
+ /** The hold context of a session the runner serves: its workspace and scratch dir there. */
33
+ export function runnerHoldContext(place: RunnerWorkspace): HoldContext {
34
+ return {
35
+ workspace: place.workspace,
36
+ scratchDir: place.scratchDir,
37
+ runner: true,
38
+ };
39
+ }
40
+
41
+ const shell = shellHoldRuleFor();
42
+
43
+ /**
44
+ * Judges the calls of a session the runner serves (`HoldContext.runner`) as the shell rule
45
+ * (`shellHoldRuleFor()`) judges an agent's on the host, with the runner's workspace and scratch
46
+ * dir as the scratch roots: a destructive command, or a write outside them, waits. A call a
47
+ * speaker below the owner raised is on a card that is theirs alone (`approval: "speaker"`), so in
48
+ * a room of several people only whoever asked for the command approves it, and yolo mode never
49
+ * does. An owner's is on the card a host shell hold has, which any owner may answer, and yolo
50
+ * mode decides it as it decides the host's. Its classes are the shell rule's under its own name
51
+ * (`runner-shell.rm`), which yolo judges as the shell class (`shellClassOf`). A host's own shell
52
+ * rules still see the call.
53
+ */
54
+ export const runnerShellRule: Readonly<HoldRule> = Object.freeze<HoldRule>({
55
+ name: RUNNER_SHELL_RULE,
56
+ describe: (tool, input, context) => {
57
+ if (context.runner !== true || context.workspace === undefined)
58
+ return undefined;
59
+ const action = shell.describe(tool, input, context);
60
+ return action === undefined ? undefined : inTheRunner(action);
61
+ },
62
+ holdClasses: (tool, input, context) => {
63
+ if (context.runner !== true || context.workspace === undefined)
64
+ return undefined;
65
+ return shell
66
+ .holdClasses?.(tool, input, context)
67
+ ?.map((id) => id.replace(/^shell\./, `${RUNNER_SHELL_RULE}.`));
68
+ },
69
+ describeInTurn: (tool, input, context, turn): HoldDescription | undefined => {
70
+ const text = runnerShellRule.describe(tool, input, context);
71
+ if (text === undefined) return undefined;
72
+ return turn.speaker?.tier === "owner"
73
+ ? { text }
74
+ : { text, approval: "speaker" };
75
+ },
76
+ });
@@ -0,0 +1,77 @@
1
+ import { type ServiceKey, serviceKey } from "../contract/services.ts";
2
+ import type {
3
+ AccessMode,
4
+ RunnerErrorCode,
5
+ RunnerResults,
6
+ RunnerStat,
7
+ } from "./protocol.ts";
8
+
9
+ /** Why a runner call failed: the runner's error code, or `unreachable` when no runner answered. */
10
+ export type RunnerFailure = RunnerErrorCode | "unreachable";
11
+
12
+ /** A runner call that failed; its message is safe to show the model. */
13
+ export class RunnerError extends Error {
14
+ override name = "RunnerError";
15
+ constructor(
16
+ readonly code: RunnerFailure,
17
+ message: string,
18
+ ) {
19
+ super(message);
20
+ }
21
+ }
22
+
23
+ /** One command for the runner to run in a conversation's workspace. */
24
+ export interface RunnerCommand {
25
+ conversation: string;
26
+ command: string;
27
+ /** An absolute path inside the conversation's workspace. */
28
+ cwd: string;
29
+ timeoutMs: number;
30
+ maxOutputBytes: number;
31
+ /** Each piece of the merged output as it comes. */
32
+ onData(chunk: Buffer): void;
33
+ /** Stops the command; the call then ends with the command's exit. */
34
+ signal?: AbortSignal;
35
+ }
36
+
37
+ /** How a command ended. */
38
+ export interface RunnerExit {
39
+ /** The exit code, 128 + the signal's number for a killed command. */
40
+ code: number;
41
+ /** The output passed `maxOutputBytes` and the command was stopped there. */
42
+ cut: boolean;
43
+ timedOut: boolean;
44
+ }
45
+
46
+ /**
47
+ * What the host asks of its runner, every path absolute and inside the conversation's workspace as
48
+ * the runner names it. A failure rejects with a `RunnerError`.
49
+ */
50
+ export interface RunnerPort {
51
+ exec(command: RunnerCommand): Promise<RunnerExit>;
52
+ read(conversation: string, path: string, maxBytes: number): Promise<Buffer>;
53
+ write(
54
+ conversation: string,
55
+ path: string,
56
+ data: Uint8Array,
57
+ maxBytes: number,
58
+ ): Promise<void>;
59
+ mkdir(conversation: string, path: string): Promise<void>;
60
+ access(conversation: string, path: string, mode: AccessMode): Promise<void>;
61
+ stat(conversation: string, path: string): Promise<RunnerStat>;
62
+ detectImage(conversation: string, path: string): Promise<string | null>;
63
+ /** Removes the conversation's workspace; false when it had none. */
64
+ removeWorkspace(conversation: string): Promise<boolean>;
65
+ /** Removes the workspaces unused for `keepDays`, returning their ids. */
66
+ sweep(keepDays: number): Promise<string[]>;
67
+ ping(): Promise<RunnerResults["ping"]>;
68
+ }
69
+
70
+ /** The host's runner, provided by the runner plugin when `runner` is configured. */
71
+ export const RUNNER: ServiceKey<RunnerPort> = serviceKey<RunnerPort>(
72
+ "roundtable.runner",
73
+ {
74
+ absent:
75
+ "No plugin provides the runner. defineRoundtable adds it when the configuration sets `runner`; a host composed by hand adds runnerPlugin() beside environment.runner.",
76
+ },
77
+ );
@@ -0,0 +1,53 @@
1
+ import { RunnerClient } from "./runner-client.ts";
2
+ import {
3
+ type CommandRun,
4
+ DockerDriver,
5
+ runCommand,
6
+ socketDriver,
7
+ } from "./runner-drivers.ts";
8
+ import type { RunnerSettings } from "./settings.ts";
9
+
10
+ /** Whether the host reaches its runner, and what it found. */
11
+ export type RunnerReach =
12
+ | { reachable: true; detail: string }
13
+ | { reachable: false; reason: string };
14
+
15
+ async function ping(client: RunnerClient): Promise<RunnerReach> {
16
+ try {
17
+ const { version } = await client.ping();
18
+ return { reachable: true, detail: `protocol ${version}` };
19
+ } catch (error) {
20
+ return { reachable: false, reason: (error as Error).message };
21
+ } finally {
22
+ client.end();
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Looks for the runner without starting it, for `roundtable doctor`: the docker CLI, the image,
28
+ * and the container if it runs, or the sidecar's socket; a runner found is pinged.
29
+ */
30
+ export async function probeRunner(
31
+ settings: RunnerSettings,
32
+ dataDir: string,
33
+ run: CommandRun = runCommand,
34
+ ): Promise<RunnerReach> {
35
+ if (settings.driver === "docker") {
36
+ const driver = new DockerDriver(settings, dataDir, run);
37
+ try {
38
+ await driver.installed();
39
+ } catch (error) {
40
+ return { reachable: false, reason: (error as Error).message };
41
+ }
42
+ if (!(await driver.running()))
43
+ return {
44
+ reachable: true,
45
+ detail: `the image is there; container ${driver.name} starts with the bot`,
46
+ };
47
+ return ping(new RunnerClient(driver));
48
+ }
49
+ const driver = socketDriver(settings.socket);
50
+ if (!(await driver.ready(0)))
51
+ return { reachable: false, reason: `no socket at ${settings.socket}` };
52
+ return ping(new RunnerClient(driver));
53
+ }
@@ -0,0 +1,36 @@
1
+ import type { ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
+ import { SHELL_TOOLS } from "../modules/host-shell/shell-policy.ts";
3
+ import type { RunnerBinding } from "./runner-tools.ts";
4
+
5
+ const SHELL: readonly string[] = SHELL_TOOLS;
6
+
7
+ /** What a session the runner serves is told about where its tools run. */
8
+ export function runnerPromptLine(binding: RunnerBinding): string {
9
+ const { workspace, scratchDir, settings } = binding;
10
+ const seconds = Math.round(settings.commandTimeoutMs / 1000);
11
+ return `Your bash, read, edit and write tools run in an isolated container, not on the host. Your workspace there is ${workspace}, and whoever else speaks with you sees its files; temporary files go in ${scratchDir}. The container has no network, so nothing can be downloaded or installed; use the tools it has. A command stops after ${seconds} seconds, and anything it started in the background ends with it. Files are kept ${settings.keepDays} days after the conversation was last used.`;
12
+ }
13
+
14
+ /**
15
+ * Tells a session the runner serves where its files are: before each run the prompt's working
16
+ * directory becomes its workspace in the runner, where `attach_file` paths resolve too, and a run
17
+ * that offers a shell or file tool also gets the line above, after the persona and the surface's
18
+ * formatting guidance.
19
+ */
20
+ export function runnerPromptExtension(
21
+ binding: RunnerBinding,
22
+ /** The run's tools, as the active-tools extension pins them. */
23
+ currentTools: () => readonly string[],
24
+ ): ExtensionFactory {
25
+ const line = runnerPromptLine(binding);
26
+ return (pi) => {
27
+ pi.on("before_agent_start", (event) => {
28
+ const options = event.systemPromptOptions;
29
+ options.cwd = binding.workspace;
30
+ if (!currentTools().some((tool) => SHELL.includes(tool))) return;
31
+ options.appendSystemPrompt = options.appendSystemPrompt
32
+ ? `${options.appendSystemPrompt}\n\n${line}`
33
+ : line;
34
+ });
35
+ };
36
+ }