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.
- package/CHANGELOG.md +18 -0
- package/README.md +6 -2
- package/README.zh-TW.md +6 -2
- package/docs/plugins.md +199 -7
- 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/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/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/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/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,318 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type ClientFrame,
|
|
4
|
+
confinedPath,
|
|
5
|
+
FrameError,
|
|
6
|
+
parseClientFrame,
|
|
7
|
+
RUNNER_PROTOCOL_VERSION,
|
|
8
|
+
type RunnerErrorCode,
|
|
9
|
+
type RunnerRequest,
|
|
10
|
+
type ServerFrame,
|
|
11
|
+
} from "../core/runner/protocol.ts";
|
|
12
|
+
import { COMMAND_ARGV, commandEnv, runCommand } from "./exec.ts";
|
|
13
|
+
import type { FileOpRequest } from "./file-helper.ts";
|
|
14
|
+
import { DEFAULT_HELPER, runFileOp } from "./files.ts";
|
|
15
|
+
import type { RunnerHost } from "./host.ts";
|
|
16
|
+
import { WorkspaceState } from "./state.ts";
|
|
17
|
+
|
|
18
|
+
export interface RunnerServerOptions {
|
|
19
|
+
/** Where the workspaces live; the protocol's paths are under it. */
|
|
20
|
+
workspaces: string;
|
|
21
|
+
host: RunnerHost;
|
|
22
|
+
/** The per-boot token a hello must carry; without one, reaching the server is the authentication. */
|
|
23
|
+
token?: string;
|
|
24
|
+
now?: () => number;
|
|
25
|
+
/** The file helper's argv; the default runs `file-helper.ts` with this Bun. */
|
|
26
|
+
helper?: readonly string[];
|
|
27
|
+
/** Uids no conversation may run as: the socket directory owner's, who can read the token. */
|
|
28
|
+
reservedUids?: readonly number[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Where a connection's frames go. */
|
|
32
|
+
export interface ConnectionSink {
|
|
33
|
+
send(frame: ServerFrame): void;
|
|
34
|
+
/** Ends the stream; the server calls it after refusing a hello. */
|
|
35
|
+
close(): void;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One client's stream, as the transport feeds it. */
|
|
39
|
+
export interface Connection {
|
|
40
|
+
/** One parsed JSON frame from the client. */
|
|
41
|
+
receive(value: unknown): void;
|
|
42
|
+
/** The client went away: its requests are aborted. */
|
|
43
|
+
closed(): void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A request that cannot be served, answered as an `error` frame. */
|
|
47
|
+
class Refused extends Error {
|
|
48
|
+
constructor(
|
|
49
|
+
readonly code: RunnerErrorCode,
|
|
50
|
+
message: string,
|
|
51
|
+
) {
|
|
52
|
+
super(message);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const digest = (value: string) => createHash("sha256").update(value).digest();
|
|
57
|
+
|
|
58
|
+
/** Waits for `previous`, or refuses as soon as `signal` aborts; leaves no listener or stray rejection behind. */
|
|
59
|
+
async function waitUnlessAborted(
|
|
60
|
+
previous: Promise<void>,
|
|
61
|
+
signal: AbortSignal,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
let refuse = () => {};
|
|
64
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
65
|
+
refuse = () => reject(new Refused("aborted", "aborted"));
|
|
66
|
+
});
|
|
67
|
+
if (signal.aborted) refuse();
|
|
68
|
+
else signal.addEventListener("abort", refuse, { once: true });
|
|
69
|
+
try {
|
|
70
|
+
await Promise.race([previous, aborted]);
|
|
71
|
+
} finally {
|
|
72
|
+
signal.removeEventListener("abort", refuse);
|
|
73
|
+
aborted.catch(() => undefined);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The runner server: serves any number of connections; requests of one conversation run one at
|
|
79
|
+
* a time in arrival order (they all run as its uid, and every command ends by killing that uid's
|
|
80
|
+
* processes), conversations side by side.
|
|
81
|
+
*/
|
|
82
|
+
export class RunnerServer {
|
|
83
|
+
readonly #queues = new Map<string, Promise<void>>();
|
|
84
|
+
readonly #started: number;
|
|
85
|
+
|
|
86
|
+
private constructor(
|
|
87
|
+
private readonly options: RunnerServerOptions,
|
|
88
|
+
private readonly state: WorkspaceState,
|
|
89
|
+
) {
|
|
90
|
+
this.#started = (options.now ?? Date.now)();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
static async open(options: RunnerServerOptions): Promise<RunnerServer> {
|
|
94
|
+
const state = await WorkspaceState.open({
|
|
95
|
+
root: options.workspaces,
|
|
96
|
+
host: options.host,
|
|
97
|
+
now: options.now,
|
|
98
|
+
reservedUids: options.reservedUids,
|
|
99
|
+
});
|
|
100
|
+
return new RunnerServer(options, state);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
connect(sink: ConnectionSink): Connection {
|
|
104
|
+
let phase: "hello" | "open" | "closed" = "hello";
|
|
105
|
+
const inflight = new Map<number, AbortController>();
|
|
106
|
+
const send = (frame: ServerFrame) => {
|
|
107
|
+
if (phase !== "closed") sink.send(frame);
|
|
108
|
+
};
|
|
109
|
+
const refuse = (code: RunnerErrorCode, message: string) => {
|
|
110
|
+
send({ type: "error", code, message });
|
|
111
|
+
phase = "closed";
|
|
112
|
+
for (const controller of inflight.values()) controller.abort();
|
|
113
|
+
sink.close();
|
|
114
|
+
};
|
|
115
|
+
const greet = (value: unknown) => {
|
|
116
|
+
let frame: ClientFrame;
|
|
117
|
+
try {
|
|
118
|
+
frame = parseClientFrame(value);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return refuse("bad-frame", (error as Error).message);
|
|
121
|
+
}
|
|
122
|
+
if (frame.type !== "hello")
|
|
123
|
+
return refuse("bad-frame", "the first frame must be hello");
|
|
124
|
+
if (frame.version !== RUNNER_PROTOCOL_VERSION)
|
|
125
|
+
return refuse(
|
|
126
|
+
"version",
|
|
127
|
+
`this runner speaks version ${RUNNER_PROTOCOL_VERSION}, not ${frame.version}`,
|
|
128
|
+
);
|
|
129
|
+
const expected = this.options.token;
|
|
130
|
+
if (
|
|
131
|
+
expected !== undefined &&
|
|
132
|
+
(frame.token === undefined ||
|
|
133
|
+
!timingSafeEqual(digest(frame.token), digest(expected)))
|
|
134
|
+
)
|
|
135
|
+
return refuse("auth", "the runner token is missing or wrong");
|
|
136
|
+
phase = "open";
|
|
137
|
+
send({ type: "welcome", version: RUNNER_PROTOCOL_VERSION });
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
receive: (value) => {
|
|
141
|
+
if (phase === "closed") return;
|
|
142
|
+
if (phase === "hello") return greet(value);
|
|
143
|
+
let frame: ClientFrame;
|
|
144
|
+
try {
|
|
145
|
+
frame = parseClientFrame(value);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
const id = (value as { id?: unknown } | null)?.id;
|
|
148
|
+
const message =
|
|
149
|
+
error instanceof FrameError ? error.message : String(error);
|
|
150
|
+
return send(
|
|
151
|
+
typeof id === "number" && Number.isSafeInteger(id) && id > 0
|
|
152
|
+
? { type: "error", id, code: "bad-frame", message }
|
|
153
|
+
: { type: "error", code: "bad-frame", message },
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (frame.type === "hello")
|
|
157
|
+
return send({
|
|
158
|
+
type: "error",
|
|
159
|
+
code: "bad-frame",
|
|
160
|
+
message: "hello was already said",
|
|
161
|
+
});
|
|
162
|
+
if (frame.type === "abort") return inflight.get(frame.id)?.abort();
|
|
163
|
+
if (inflight.has(frame.id))
|
|
164
|
+
return send({
|
|
165
|
+
type: "error",
|
|
166
|
+
id: frame.id,
|
|
167
|
+
code: "bad-frame",
|
|
168
|
+
message: `request ${frame.id} is still running`,
|
|
169
|
+
});
|
|
170
|
+
const controller = new AbortController();
|
|
171
|
+
inflight.set(frame.id, controller);
|
|
172
|
+
const id = frame.id;
|
|
173
|
+
void this.#serve(frame, controller.signal, send)
|
|
174
|
+
.catch((error: unknown) =>
|
|
175
|
+
send(
|
|
176
|
+
error instanceof Refused
|
|
177
|
+
? {
|
|
178
|
+
type: "error",
|
|
179
|
+
id,
|
|
180
|
+
code: error.code,
|
|
181
|
+
message: error.message,
|
|
182
|
+
}
|
|
183
|
+
: {
|
|
184
|
+
type: "error",
|
|
185
|
+
id,
|
|
186
|
+
code: "failed",
|
|
187
|
+
message: (error as Error).message ?? String(error),
|
|
188
|
+
},
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
.finally(() => inflight.delete(id));
|
|
192
|
+
},
|
|
193
|
+
closed: () => {
|
|
194
|
+
phase = "closed";
|
|
195
|
+
for (const controller of inflight.values()) controller.abort();
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Runs `task` after every earlier task of `key`; an abort while waiting refuses at once. */
|
|
201
|
+
async #serial<T>(
|
|
202
|
+
key: string,
|
|
203
|
+
signal: AbortSignal | undefined,
|
|
204
|
+
task: () => Promise<T>,
|
|
205
|
+
): Promise<T> {
|
|
206
|
+
const previous = this.#queues.get(key) ?? Promise.resolve();
|
|
207
|
+
let release = () => {};
|
|
208
|
+
const mine = new Promise<void>((resolve) => {
|
|
209
|
+
release = resolve;
|
|
210
|
+
});
|
|
211
|
+
// The next task waits for this one and for everything before it, even if this one was
|
|
212
|
+
// aborted while still waiting.
|
|
213
|
+
const tail = previous.then(() => mine);
|
|
214
|
+
this.#queues.set(key, tail);
|
|
215
|
+
try {
|
|
216
|
+
await (signal ? waitUnlessAborted(previous, signal) : previous);
|
|
217
|
+
if (signal?.aborted) throw new Refused("aborted", "aborted");
|
|
218
|
+
return await task();
|
|
219
|
+
} finally {
|
|
220
|
+
release();
|
|
221
|
+
void tail.then(() => {
|
|
222
|
+
if (this.#queues.get(key) === tail) this.#queues.delete(key);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async #removeWorkspace(conversation: string): Promise<boolean> {
|
|
228
|
+
const uid = this.state.uidOf(conversation);
|
|
229
|
+
if (uid !== undefined) await this.options.host.killUser(uid);
|
|
230
|
+
return this.state.remove(conversation);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async #serve(
|
|
234
|
+
request: RunnerRequest,
|
|
235
|
+
signal: AbortSignal,
|
|
236
|
+
send: (frame: ServerFrame) => void,
|
|
237
|
+
): Promise<void> {
|
|
238
|
+
const ok = (result: unknown) =>
|
|
239
|
+
send({ type: "ok", id: request.id, result });
|
|
240
|
+
switch (request.type) {
|
|
241
|
+
case "ping":
|
|
242
|
+
return ok({
|
|
243
|
+
version: RUNNER_PROTOCOL_VERSION,
|
|
244
|
+
uptimeMs: (this.options.now ?? Date.now)() - this.#started,
|
|
245
|
+
});
|
|
246
|
+
case "sweep": {
|
|
247
|
+
const removed: string[] = [];
|
|
248
|
+
for (const id of await this.state.idle(request.keepDays))
|
|
249
|
+
await this.#serial(id, undefined, async () => {
|
|
250
|
+
// Used again while waiting its turn: kept.
|
|
251
|
+
if (!(await this.state.idle(request.keepDays)).includes(id)) return;
|
|
252
|
+
if (await this.#removeWorkspace(id)) removed.push(id);
|
|
253
|
+
});
|
|
254
|
+
return ok({ removed });
|
|
255
|
+
}
|
|
256
|
+
case "remove-workspace":
|
|
257
|
+
return ok({
|
|
258
|
+
removed: await this.#serial(request.conversation, signal, () =>
|
|
259
|
+
this.#removeWorkspace(request.conversation),
|
|
260
|
+
),
|
|
261
|
+
});
|
|
262
|
+
case "exec":
|
|
263
|
+
return this.#serial(request.conversation, signal, async () => {
|
|
264
|
+
const workspace = await this.state.workspace(request.conversation);
|
|
265
|
+
if (confinedPath(workspace.dir, request.cwd) === undefined)
|
|
266
|
+
throw new Refused(
|
|
267
|
+
"outside",
|
|
268
|
+
`${request.cwd} is outside the workspace`,
|
|
269
|
+
);
|
|
270
|
+
const host = this.options.host;
|
|
271
|
+
const result = await runCommand(
|
|
272
|
+
{
|
|
273
|
+
argv: host.asUser(workspace.uid, COMMAND_ARGV),
|
|
274
|
+
script: request.command,
|
|
275
|
+
cwd: request.cwd,
|
|
276
|
+
env: commandEnv(workspace.dir),
|
|
277
|
+
timeoutMs: request.timeoutMs,
|
|
278
|
+
maxOutputBytes: request.maxOutputBytes,
|
|
279
|
+
signal,
|
|
280
|
+
onData: (chunk) =>
|
|
281
|
+
send({
|
|
282
|
+
type: "data",
|
|
283
|
+
id: request.id,
|
|
284
|
+
data: Buffer.from(chunk).toString("base64"),
|
|
285
|
+
}),
|
|
286
|
+
},
|
|
287
|
+
() => host.killUser(workspace.uid),
|
|
288
|
+
);
|
|
289
|
+
send({ type: "exit", id: request.id, ...result });
|
|
290
|
+
});
|
|
291
|
+
default:
|
|
292
|
+
return this.#serial(request.conversation, signal, async () => {
|
|
293
|
+
const workspace = await this.state.workspace(request.conversation);
|
|
294
|
+
if (confinedPath(workspace.dir, request.path) === undefined)
|
|
295
|
+
throw new Refused(
|
|
296
|
+
"outside",
|
|
297
|
+
`${request.path} is outside the workspace`,
|
|
298
|
+
);
|
|
299
|
+
const { type, id: _id, conversation: _c, ...fields } = request;
|
|
300
|
+
const host = this.options.host;
|
|
301
|
+
let reply: Awaited<ReturnType<typeof runFileOp>>;
|
|
302
|
+
try {
|
|
303
|
+
reply = await runFileOp(
|
|
304
|
+
host,
|
|
305
|
+
workspace.uid,
|
|
306
|
+
{ ...fields, op: type, dir: workspace.dir } as FileOpRequest,
|
|
307
|
+
this.options.helper ?? DEFAULT_HELPER,
|
|
308
|
+
);
|
|
309
|
+
} finally {
|
|
310
|
+
// As after a command: nothing the uid started outlives the operation.
|
|
311
|
+
await host.killUser(workspace.uid);
|
|
312
|
+
}
|
|
313
|
+
if (!reply.ok) throw new Refused(reply.code, reply.message);
|
|
314
|
+
ok(reply.result);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { chmodSync, statSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
/** The message queue root: `mq_open` creates in it whether or not it is mounted anywhere. */
|
|
4
|
+
const MQUEUE = "/dev/mqueue";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Directories a container gets that every uid may write, where one conversation could leave
|
|
8
|
+
* something for another to find or trip on: `/tmp`, POSIX shared memory, and message queues.
|
|
9
|
+
*/
|
|
10
|
+
export const SHARED_DIRS: readonly string[] = ["/tmp", "/dev/shm", MQUEUE];
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Makes each of `dirs` that every uid may write root's alone (0755), returning those it changed.
|
|
14
|
+
* The flags `--tmpfs /tmp:mode=0755 --ipc none` leave nothing for it to do but the message queue
|
|
15
|
+
* root, which no flag reaches; for a sidecar started without them it closes the rest. A read-only
|
|
16
|
+
* directory is left as it is, since no one writes it, except the message queue root, which a
|
|
17
|
+
* read-only mount does not close. Throws when a directory stays writable by every uid.
|
|
18
|
+
*/
|
|
19
|
+
export function lockSharedDirs(
|
|
20
|
+
dirs: readonly string[] = SHARED_DIRS,
|
|
21
|
+
chmod: (path: string, mode: number) => void = chmodSync,
|
|
22
|
+
): string[] {
|
|
23
|
+
const locked: string[] = [];
|
|
24
|
+
for (const dir of dirs) {
|
|
25
|
+
let mode: number;
|
|
26
|
+
try {
|
|
27
|
+
mode = statSync(dir).mode;
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
if ((mode & 0o002) === 0) continue;
|
|
33
|
+
try {
|
|
34
|
+
chmod(dir, 0o755);
|
|
35
|
+
locked.push(dir);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if ((error as NodeJS.ErrnoException).code === "EROFS" && dir !== MQUEUE)
|
|
38
|
+
continue;
|
|
39
|
+
throw new Error(
|
|
40
|
+
`${dir} is writable by every uid and could not be made root's (${(error as Error).message}); run the runner container with --tmpfs /tmp:mode=0755 --ipc none`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return locked;
|
|
45
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { lstatSync, type Stats } from "node:fs";
|
|
2
|
+
import {
|
|
3
|
+
chmod,
|
|
4
|
+
lstat,
|
|
5
|
+
mkdir,
|
|
6
|
+
readdir,
|
|
7
|
+
readFile,
|
|
8
|
+
rename,
|
|
9
|
+
rm,
|
|
10
|
+
writeFile,
|
|
11
|
+
} from "node:fs/promises";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { isConversationId } from "../core/runner/protocol.ts";
|
|
14
|
+
import { type RunnerHost, runQuiet } from "./host.ts";
|
|
15
|
+
|
|
16
|
+
/** The first uid a conversation gets; uids count up from it and are never handed out twice. */
|
|
17
|
+
export const FIRST_UID = 20_000;
|
|
18
|
+
|
|
19
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
20
|
+
/** A use refreshes the stored time only when it moved this much, so not every call writes the file. */
|
|
21
|
+
const TOUCH_MS = 60_000;
|
|
22
|
+
|
|
23
|
+
interface Entry {
|
|
24
|
+
uid: number;
|
|
25
|
+
lastUsedMs: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface StateFile {
|
|
29
|
+
version: 1;
|
|
30
|
+
nextUid: number;
|
|
31
|
+
conversations: Record<string, Entry>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Workspace {
|
|
35
|
+
uid: number;
|
|
36
|
+
dir: string;
|
|
37
|
+
scratch: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseState(text: string, file: string): StateFile {
|
|
41
|
+
const fail = (): never => {
|
|
42
|
+
throw new Error(
|
|
43
|
+
`${file} is not the runner's state file; move it away to start over (each workspace then keeps the uid that owns its directory, and new ones get uids above every uid there)`,
|
|
44
|
+
);
|
|
45
|
+
};
|
|
46
|
+
let value: unknown;
|
|
47
|
+
try {
|
|
48
|
+
value = JSON.parse(text);
|
|
49
|
+
} catch {
|
|
50
|
+
return fail();
|
|
51
|
+
}
|
|
52
|
+
const state = value as Partial<StateFile>;
|
|
53
|
+
if (
|
|
54
|
+
state?.version !== 1 ||
|
|
55
|
+
!Number.isInteger(state.nextUid) ||
|
|
56
|
+
typeof state.conversations !== "object" ||
|
|
57
|
+
state.conversations === null
|
|
58
|
+
)
|
|
59
|
+
fail();
|
|
60
|
+
for (const [id, entry] of Object.entries(
|
|
61
|
+
state.conversations as Record<string, Partial<Entry>>,
|
|
62
|
+
))
|
|
63
|
+
if (
|
|
64
|
+
!isConversationId(id) ||
|
|
65
|
+
!Number.isInteger(entry?.uid) ||
|
|
66
|
+
typeof entry?.lastUsedMs !== "number"
|
|
67
|
+
)
|
|
68
|
+
fail();
|
|
69
|
+
return state as StateFile;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The state of a root whose state file is gone: each conversation directory keeps the uid that owns
|
|
74
|
+
* it, unless that uid is reserved, below the first, or owns another directory too; and uids go on
|
|
75
|
+
* above every uid a directory there holds, so none is handed out a second time.
|
|
76
|
+
*/
|
|
77
|
+
async function rebuiltState(
|
|
78
|
+
root: string,
|
|
79
|
+
host: RunnerHost,
|
|
80
|
+
reserved: ReadonlySet<number>,
|
|
81
|
+
): Promise<StateFile> {
|
|
82
|
+
let highest = FIRST_UID - 1;
|
|
83
|
+
const found = new Map<number, { id: string; lastUsedMs: number }[]>();
|
|
84
|
+
for (const item of await readdir(root, { withFileTypes: true })) {
|
|
85
|
+
if (!isConversationId(item.name) || !item.isDirectory()) continue;
|
|
86
|
+
const path = join(root, item.name);
|
|
87
|
+
const uid = host.ownerOf(path);
|
|
88
|
+
highest = Math.max(highest, uid);
|
|
89
|
+
if (uid < FIRST_UID || reserved.has(uid)) continue;
|
|
90
|
+
const lastUsedMs = (await lstat(path)).mtimeMs;
|
|
91
|
+
found.set(uid, [...(found.get(uid) ?? []), { id: item.name, lastUsedMs }]);
|
|
92
|
+
}
|
|
93
|
+
const conversations: Record<string, Entry> = {};
|
|
94
|
+
for (const [uid, dirs] of found)
|
|
95
|
+
if (dirs.length === 1 && dirs[0])
|
|
96
|
+
conversations[dirs[0].id] = { uid, lastUsedMs: dirs[0].lastUsedMs };
|
|
97
|
+
return { version: 1, nextUid: highest + 1, conversations };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The conversations' uids and last uses, in `<root>/.state/uids.json` (root only), and their
|
|
102
|
+
* directories `<root>/<conversation>`, each 0700 and owned by its uid. The root is 0711, so a uid
|
|
103
|
+
* reaches its own directory but cannot list the others. One server process owns the state; its
|
|
104
|
+
* writes are serialized and atomic (a temp file renamed over the old one). A reserved uid, such as
|
|
105
|
+
* the socket directory owner's, is never a conversation's.
|
|
106
|
+
*/
|
|
107
|
+
export class WorkspaceState {
|
|
108
|
+
#writing: Promise<void> = Promise.resolve();
|
|
109
|
+
|
|
110
|
+
private constructor(
|
|
111
|
+
readonly root: string,
|
|
112
|
+
private readonly host: RunnerHost,
|
|
113
|
+
private readonly now: () => number,
|
|
114
|
+
private readonly file: string,
|
|
115
|
+
private state: StateFile,
|
|
116
|
+
private readonly reserved: ReadonlySet<number>,
|
|
117
|
+
) {}
|
|
118
|
+
|
|
119
|
+
static async open(options: {
|
|
120
|
+
root: string;
|
|
121
|
+
host: RunnerHost;
|
|
122
|
+
now?: () => number;
|
|
123
|
+
/** Uids no conversation may run as: the socket directory owner's, who reads the token. */
|
|
124
|
+
reservedUids?: readonly number[];
|
|
125
|
+
}): Promise<WorkspaceState> {
|
|
126
|
+
const { root, host } = options;
|
|
127
|
+
const reserved = new Set(options.reservedUids ?? []);
|
|
128
|
+
await mkdir(root, { recursive: true });
|
|
129
|
+
await chmod(root, 0o711);
|
|
130
|
+
const stateDir = join(root, ".state");
|
|
131
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
132
|
+
await chmod(stateDir, 0o700);
|
|
133
|
+
const file = join(stateDir, "uids.json");
|
|
134
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
135
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
136
|
+
throw error;
|
|
137
|
+
});
|
|
138
|
+
const state =
|
|
139
|
+
text === undefined
|
|
140
|
+
? await rebuiltState(root, host, reserved)
|
|
141
|
+
: parseState(text, file);
|
|
142
|
+
const opened = new WorkspaceState(
|
|
143
|
+
root,
|
|
144
|
+
host,
|
|
145
|
+
options.now ?? Date.now,
|
|
146
|
+
file,
|
|
147
|
+
state,
|
|
148
|
+
reserved,
|
|
149
|
+
);
|
|
150
|
+
if (text === undefined) await opened.#save();
|
|
151
|
+
return opened;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
#save(): Promise<void> {
|
|
155
|
+
const snapshot = `${JSON.stringify(this.state)}\n`;
|
|
156
|
+
const write = this.#writing.then(async () => {
|
|
157
|
+
const temp = `${this.file}.tmp`;
|
|
158
|
+
await writeFile(temp, snapshot, { mode: 0o600 });
|
|
159
|
+
await chmod(temp, 0o600);
|
|
160
|
+
await rename(temp, this.file);
|
|
161
|
+
});
|
|
162
|
+
this.#writing = write.catch(() => undefined);
|
|
163
|
+
return write;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The conversation's uid, if it has one. */
|
|
167
|
+
uidOf(conversation: string): number | undefined {
|
|
168
|
+
return this.state.conversations[conversation]?.uid;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The conversation's workspace, made on first use, its last use set to now. A directory is
|
|
173
|
+
* handed only to the uid that owns it, and never to a reserved uid; one that is there without
|
|
174
|
+
* being the conversation's (the state lost it, or another uid owns it) is refused until removed.
|
|
175
|
+
*/
|
|
176
|
+
async workspace(conversation: string): Promise<Workspace> {
|
|
177
|
+
if (!isConversationId(conversation))
|
|
178
|
+
throw new Error(`${conversation} is not a conversation id`);
|
|
179
|
+
const dir = join(this.root, conversation);
|
|
180
|
+
const scratch = join(dir, ".tmp");
|
|
181
|
+
// Read at once with the entry and the uid it may take, so first uses get uids in the order
|
|
182
|
+
// they were asked for, and two at once never take one each for the same conversation.
|
|
183
|
+
const owner = this.#ownerOf(dir);
|
|
184
|
+
let entry = this.state.conversations[conversation];
|
|
185
|
+
if (entry !== undefined && this.reserved.has(entry.uid))
|
|
186
|
+
throw new Error(
|
|
187
|
+
`${dir} runs as uid ${entry.uid}, which is reserved for the runner's socket; remove the workspace (remove-workspace) to start it anew`,
|
|
188
|
+
);
|
|
189
|
+
if (owner !== undefined && owner !== entry?.uid)
|
|
190
|
+
throw new Error(
|
|
191
|
+
`${dir} is owned by uid ${owner}, not by its conversation's uid${entry ? ` ${entry.uid}` : ""}; remove the workspace (remove-workspace) to start it anew`,
|
|
192
|
+
);
|
|
193
|
+
const now = this.now();
|
|
194
|
+
let changed = false;
|
|
195
|
+
if (entry === undefined) {
|
|
196
|
+
entry = { uid: this.#takeUid(), lastUsedMs: now };
|
|
197
|
+
this.state.conversations[conversation] = entry;
|
|
198
|
+
changed = true;
|
|
199
|
+
} else if (Math.abs(now - entry.lastUsedMs) >= TOUCH_MS) {
|
|
200
|
+
entry.lastUsedMs = now;
|
|
201
|
+
changed = true;
|
|
202
|
+
}
|
|
203
|
+
if (changed) await this.#save();
|
|
204
|
+
await this.#ensure(entry.uid, dir, scratch);
|
|
205
|
+
return { uid: entry.uid, dir, scratch };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The next uid no one has had, skipping the reserved ones. */
|
|
209
|
+
#takeUid(): number {
|
|
210
|
+
while (this.reserved.has(this.state.nextUid)) this.state.nextUid += 1;
|
|
211
|
+
const uid = this.state.nextUid;
|
|
212
|
+
this.state.nextUid += 1;
|
|
213
|
+
return uid;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Who owns the conversation's directory; undefined when there is none. */
|
|
217
|
+
#ownerOf(dir: string): number | undefined {
|
|
218
|
+
let info: Stats;
|
|
219
|
+
try {
|
|
220
|
+
info = lstatSync(dir);
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
226
|
+
throw new Error(`${dir} is not a directory`);
|
|
227
|
+
return this.host.ownerOf(dir);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async #ensure(uid: number, dir: string, scratch: string): Promise<void> {
|
|
231
|
+
const info = await lstat(dir).catch(() => undefined);
|
|
232
|
+
if (info === undefined) {
|
|
233
|
+
// Made by root inside the root-owned 0711 root and handed over only once complete, so
|
|
234
|
+
// no uid can place a symlink in it before the chown.
|
|
235
|
+
await mkdir(dir, { mode: 0o700 });
|
|
236
|
+
await mkdir(scratch, { mode: 0o700 });
|
|
237
|
+
await chmod(dir, 0o700);
|
|
238
|
+
await chmod(scratch, 0o700);
|
|
239
|
+
await this.host.chown(scratch, uid);
|
|
240
|
+
await this.host.chown(dir, uid);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
244
|
+
throw new Error(`${dir} is not a directory`);
|
|
245
|
+
// Inside the uid's own directory root touches nothing; a missing scratch dir is made as the uid.
|
|
246
|
+
if ((await lstat(scratch).catch(() => undefined)) === undefined)
|
|
247
|
+
await runQuiet(
|
|
248
|
+
this.host.asUser(uid, ["mkdir", "-p", "-m", "700", scratch]),
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Conversations idle for `keepDays` or longer: by their last use, or, for a directory the state
|
|
254
|
+
* does not know, by its modification time.
|
|
255
|
+
*/
|
|
256
|
+
async idle(keepDays: number): Promise<string[]> {
|
|
257
|
+
const cutoff = this.now() - keepDays * DAY_MS;
|
|
258
|
+
const known = Object.entries(this.state.conversations)
|
|
259
|
+
.filter(([, entry]) => entry.lastUsedMs <= cutoff)
|
|
260
|
+
.map(([id]) => id);
|
|
261
|
+
const strays: string[] = [];
|
|
262
|
+
for (const entry of await readdir(this.root, { withFileTypes: true })) {
|
|
263
|
+
if (
|
|
264
|
+
!isConversationId(entry.name) ||
|
|
265
|
+
this.state.conversations[entry.name] !== undefined
|
|
266
|
+
)
|
|
267
|
+
continue;
|
|
268
|
+
const info = await lstat(join(this.root, entry.name)).catch(
|
|
269
|
+
() => undefined,
|
|
270
|
+
);
|
|
271
|
+
if (info !== undefined && info.mtimeMs <= cutoff) strays.push(entry.name);
|
|
272
|
+
}
|
|
273
|
+
return [...known, ...strays];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Removes the conversation's directory and forgets its uid (which is never reused). The caller
|
|
278
|
+
* has its processes killed first. False when there was nothing to remove.
|
|
279
|
+
*/
|
|
280
|
+
async remove(conversation: string): Promise<boolean> {
|
|
281
|
+
if (!isConversationId(conversation)) return false;
|
|
282
|
+
const dir = join(this.root, conversation);
|
|
283
|
+
const existed = (await lstat(dir).catch(() => undefined)) !== undefined;
|
|
284
|
+
// rm does not follow symlinks, so nothing outside the directory is touched.
|
|
285
|
+
await rm(dir, { recursive: true, force: true });
|
|
286
|
+
const known = this.state.conversations[conversation] !== undefined;
|
|
287
|
+
if (known) {
|
|
288
|
+
delete this.state.conversations[conversation];
|
|
289
|
+
await this.#save();
|
|
290
|
+
}
|
|
291
|
+
return existed || known;
|
|
292
|
+
}
|
|
293
|
+
}
|