Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- unit names and RAM size come from the host.
2import * as NodeCrypto from "node:crypto";
3import * as NodeOS from "node:os";
4
5import {
6 AgentScope,
7 agentScopeCommand,
8 type AgentScopeShape,
9 type AgentSystemdScope,
10} from "@t3tools/shared/AgentScope";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import { resolveCommandPath } from "@t3tools/shared/shell";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Path from "effect/Path";
17
18import * as ServerConfig from "../config.ts";
19import * as ProcessRunner from "../processRunner.ts";
20
21const AGENT_SLICE = "app-t3code-agents.slice";
22
23export function ownedAgentSlice(stateDir: string): string {
24 const hash = NodeCrypto.createHash("sha256").update(stateDir).digest("hex").slice(0, 12);
25 return `app-t3code-agents-${hash}.slice`;
26}
27
28const GiB = 1024 ** 3;
29
30/**
31 * Agents together leave about 6 GB free before they are throttled and 4 GB
32 * before the kernel kills one, so the server, sshd, and tailscaled keep
33 * working. Small machines still give agents at least half of RAM before
34 * throttling and three quarters before a kill.
35 */
36export function agentSliceMemoryLimits(totalBytes: number) {
37 return {
38 high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)),
39 max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)),
40 };
41}
42
43export interface ScopeState {
44 readonly loadState: string;
45 readonly activeState: string;
46 readonly result: string;
47 readonly oomKills: number;
48 readonly populated: boolean | undefined;
49}
50
51/**
52 * Our pipe can close before systemd handles the kill, so a scope that is
53 * still stopping, is empty, or already counted an OOM kill is "stopping":
54 * systemd records `Result=oom-kill` for it in a moment.
55 */
56export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
57 if (state.result === "oom-kill") return "oom-killed";
58 if (
59 state.loadState !== "loaded" ||
60 state.activeState === "inactive" ||
61 state.activeState === "failed"
62 ) {
63 return "gone";
64 }
65 if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) {
66 return "stopping";
67 }
68 return "running";
69}
70
71function parseKeyValues(text: string): Map<string, string> {
72 const values = new Map<string, string>();
73 for (const line of text.split("\n")) {
74 const index = line.indexOf("=");
75 if (index > 0) values.set(line.slice(0, index), line.slice(index + 1).trim());
76 }
77 return values;
78}
79
80function parseCgroupCounter(text: string, key: string): number | undefined {
81 const match = new RegExp(`^${key} (\\d+)$`, "m").exec(text);
82 return match === null ? undefined : Number(match[1]);
83}
84
85// A stop sends SIGTERM, then SIGKILL after this long. systemd's 90 s default
86// would outlast the wait for a previous server's agents below.
87const STOP_TIMEOUT_OPTION = "--property=TimeoutStopSec=10s";
88const STOPPING_POLL_INTERVAL = "100 millis";
89const STOPPING_POLL_ATTEMPTS = 20;
90const CLEAR_FAILED_INTERVAL = "1 second";
91const CLEAR_FAILED_ATTEMPTS = 120;
92const MAX_TRACKED_THREADS = 500;
93
94export const make = Effect.gen(function* () {
95 const platform = yield* HostProcess.Platform;
96 if (platform !== "linux") return AgentScope.defaultValue();
97
98 const runner = yield* ProcessRunner.ProcessRunner;
99 const fileSystem = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const hostEnvironment = yield* HostProcess.Environment;
102 const { stateDir } = yield* ServerConfig.ServerConfig;
103 const ownedSlice = ownedAgentSlice(stateDir);
104 const layerScope = yield* Effect.scope;
105
106 const resolve = (command: string, env: NodeJS.ProcessEnv) =>
107 resolveCommandPath(command, { env }).pipe(
108 Effect.provideService(FileSystem.FileSystem, fileSystem),
109 Effect.provideService(Path.Path, path),
110 Effect.provideService(HostProcess.Platform, platform),
111 );
112
113 const run = (command: string, args: ReadonlyArray<string>) =>
114 runner.run({ command, args, timeout: "5 seconds" }).pipe(Effect.option);
115
116 const readCgroupFile = (controlGroup: string, file: string) =>
117 fileSystem
118 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
119 .pipe(Effect.orElseSucceed(() => ""));
120
121 // Old agents keep their scopes when the server is killed, and the restarted
122 // server resumes their sessions. Stop them first, so two copies of one
123 // session never work in the same worktree.
124 const stopLeftoverAgents = (systemctl: string) =>
125 Effect.gen(function* () {
126 const shown = yield* run(systemctl, [
127 "--user",
128 "show",
129 ownedSlice,
130 "--property=ActiveState,ControlGroup",
131 ]);
132 if (shown._tag === "None") return;
133 const values = parseKeyValues(shown.value.stdout);
134 if (values.get("ActiveState") !== "active") return;
135 const controlGroup = values.get("ControlGroup") ?? "";
136 const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
137 if (parseCgroupCounter(events, "populated") === 0) return;
138 yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
139 const stopped = yield* runner
140 .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
141 .pipe(Effect.option);
142 if (stopped._tag === "None" || stopped.value.code !== 0) {
143 yield* Effect.logWarning("Could not stop agents left by a previous server", {
144 slice: ownedSlice,
145 stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
146 });
147 }
148 });
149
150 const systemd = yield* Effect.cached(
151 Effect.gen(function* () {
152 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
153 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
154 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
155 const systemctl = yield* resolve("systemctl", hostEnvironment);
156 if (systemdRun === null || systemctl === null) return undefined;
157 yield* stopLeftoverAgents(systemctl);
158 const probe = (options: ReadonlyArray<string>) =>
159 run(systemdRun, [
160 "--user",
161 "--scope",
162 "--quiet",
163 "--collect",
164 `--slice=${AGENT_SLICE}`,
165 ...options,
166 "--",
167 "true",
168 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
169 // Stop the whole scope when the kernel kills one of its processes, and
170 // record the result as oom-kill. Scopes take OOMPolicy from systemd 253;
171 // older user managers still get scopes, without the OOM label.
172 const stopOptions = [STOP_TIMEOUT_OPTION];
173 const oomOptions = [...stopOptions, "--property=OOMPolicy=stop"];
174 const scopeOptions = (yield* probe(oomOptions))
175 ? oomOptions
176 : (yield* probe(stopOptions))
177 ? stopOptions
178 : undefined;
179 if (scopeOptions === undefined) {
180 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
181 return undefined;
182 }
183 const limits = agentSliceMemoryLimits(NodeOS.totalmem());
184 const limited = yield* run(systemctl, [
185 "--user",
186 "set-property",
187 "--runtime",
188 AGENT_SLICE,
189 `MemoryHigh=${limits.high}`,
190 `MemoryMax=${limits.max}`,
191 ]);
192 if (limited._tag === "None" || limited.value.code !== 0) {
193 yield* Effect.logWarning("Could not set memory limits on the agents slice", {
194 stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined,
195 });
196 }
197 yield* Effect.logInfo("Agent scopes are on", {
198 slice: AGENT_SLICE,
199 ...limits,
200 oomPolicy: scopeOptions.length > 0,
201 });
202 return {
203 systemdRun,
204 systemctl,
205 runtimeDir,
206 scopeOptions,
207 };
208 }),
209 );
210
211 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();
212
213 const readScope = (systemctl: string, unit: string) =>
214 Effect.gen(function* () {
215 const shown = yield* run(systemctl, [
216 "--user",
217 "show",
218 unit,
219 "--property=LoadState,ActiveState,Result,ControlGroup",
220 ]);
221 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
222 const values = parseKeyValues(shown.value.stdout);
223 const controlGroup = values.get("ControlGroup") ?? "";
224 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
225 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
226 const populated = parseCgroupCounter(cgroupEvents, "populated");
227 return {
228 loadState: values.get("LoadState") ?? "",
229 activeState: values.get("ActiveState") ?? "",
230 result: values.get("Result") ?? "",
231 oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
232 populated: populated === undefined ? undefined : populated === 1,
233 } satisfies ScopeState;
234 });
235
236 const clearFailed = (systemctl: string, unit: string) =>
237 Effect.gen(function* () {
238 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
239 const state = yield* readScope(systemctl, unit);
240 if (state === undefined) return;
241 if (state.activeState === "failed") {
242 yield* run(systemctl, ["--user", "reset-failed", unit]);
243 return;
244 }
245 if (state.activeState !== "deactivating") return;
246 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
247 }
248 });
249
250 const forget = (systemctl: string, unit: string) =>
251 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
252
253 const evictOldest = (systemctl: string) =>
254 Effect.gen(function* () {
255 const oldest = scopeByThread.entries().next();
256 if (oldest.done === true) return;
257 const [threadId, tracked] = oldest.value;
258 const state = yield* readScope(systemctl, tracked.unit);
259 if (scopeByThread.get(threadId) !== tracked) return;
260 scopeByThread.delete(threadId);
261 const status = state === undefined ? "running" : classifyScope(state);
262 if (status === "running" || status === "stopping") {
263 scopeByThread.set(threadId, tracked);
264 return;
265 }
266 yield* forget(systemctl, tracked.unit);
267 });
268
269 const track = (systemctl: string, threadId: string, unit: string | undefined) =>
270 Effect.gen(function* () {
271 const previous = scopeByThread.get(threadId);
272 scopeByThread.delete(threadId);
273 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
274 if (previous !== undefined) yield* forget(systemctl, previous.unit);
275 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
276 });
277
278 const oomKilled: AgentScopeShape["oomKilled"] = (threadId) =>
279 Effect.gen(function* () {
280 const tracked = scopeByThread.get(threadId);
281 if (tracked === undefined) return false;
282 if (tracked.oomKilled) return true;
283 const scope = yield* systemd;
284 if (scope === undefined) return false;
285 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
286 const state = yield* readScope(scope.systemctl, tracked.unit);
287 if (state === undefined) return false;
288 const status = classifyScope(state);
289 if (status === "running") return false;
290 if (status === "stopping") {
291 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
292 continue;
293 }
294 yield* forget(scope.systemctl, tracked.unit);
295 if (status === "gone") return false;
296 yield* Effect.logWarning("Agent scope was killed: out of memory", {
297 threadId,
298 unit: tracked.unit,
299 });
300 tracked.oomKilled = true;
301 return true;
302 }
303 return false;
304 });
305
306 const clear: AgentScopeShape["clear"] = (threadId) =>
307 Effect.gen(function* () {
308 if (!scopeByThread.has(threadId)) return;
309 const scope = yield* systemd;
310 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
311 });
312
313 return {
314 wrap: Effect.fn("AgentScope.wrap")(function* ({
315 command,
316 args,
317 name,
318 threadId,
319 env,
320 survivesRestart,
321 }) {
322 const resolved = yield* resolve(command, env ?? hostEnvironment);
323 if (resolved === null) return { command, args };
324 const scope = yield* systemd;
325 if (scope === undefined) return agentScopeCommand({ command: resolved, args });
326 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
327 if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit);
328 const systemdScope: AgentSystemdScope = {
329 systemdRun: scope.systemdRun,
330 runtimeDir: scope.runtimeDir,
331 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
332 unit,
333 // Without a thread nothing reads the result, so let systemd unload
334 // the unit even when it fails.
335 options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions,
336 };
337 return agentScopeCommand({ command: resolved, args, scope: systemdScope });
338 }),
339 oomKilled,
340 clear,
341 } satisfies AgentScopeShape;
342});
343
344export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));