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 */
36function 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 | undefined;
48 readonly populated: boolean | undefined;
49}
50
51/** Pipes can close before systemd records oom-kill; stopping, empty or OOM-counted scopes remain pending. */
52export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
53 if (state.result === "oom-kill") return "oom-killed";
54 if (
55 state.loadState !== "loaded" ||
56 state.activeState === "inactive" ||
57 state.activeState === "failed"
58 ) {
59 return "gone";
60 }
61 if (
62 state.activeState === "deactivating" ||
63 (state.oomKills ?? 0) > 0 ||
64 state.populated === false
65 ) {
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// systemd's default 90 s stop timeout would outlast our leftover-agent wait.
86// Delegation lets rootless containers (Podman, kind) manage their own cgroups.
87const SCOPE_OPTIONS = ["--property=TimeoutStopSec=10s", "--property=Delegate=yes"];
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 = Effect.fn("agentScope.stopLeftoverAgents")(function* (
125 systemctl: string,
126 ) {
127 const shown = yield* run(systemctl, [
128 "--user",
129 "show",
130 ownedSlice,
131 "--property=ActiveState,ControlGroup",
132 ]);
133 if (shown._tag === "None") return;
134 const values = parseKeyValues(shown.value.stdout);
135 if (values.get("ActiveState") !== "active") return;
136 const controlGroup = values.get("ControlGroup") ?? "";
137 const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
138 if (parseCgroupCounter(events, "populated") === 0) return;
139 yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
140 const stopped = yield* runner
141 .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
142 .pipe(Effect.option);
143 if (stopped._tag === "None" || stopped.value.code !== 0) {
144 yield* Effect.logWarning("Could not stop agents left by a previous server", {
145 slice: ownedSlice,
146 stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
147 });
148 }
149 });
150
151 const systemd = yield* Effect.cached(
152 Effect.gen(function* () {
153 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
154 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
155 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
156 const systemctl = yield* resolve("systemctl", hostEnvironment);
157 if (systemdRun === null || systemctl === null) return undefined;
158 yield* stopLeftoverAgents(systemctl);
159 const probe = (options: ReadonlyArray<string>) =>
160 run(systemdRun, [
161 "--user",
162 "--scope",
163 "--quiet",
164 "--collect",
165 `--slice=${AGENT_SLICE}`,
166 ...options,
167 "--",
168 "true",
169 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
170 // Scopes take OOMPolicy from systemd 253; older managers still get scopes.
171 const supportsOomPolicy = yield* probe([...SCOPE_OPTIONS, "--property=OOMPolicy=stop"]);
172 if (!supportsOomPolicy && !(yield* probe(SCOPE_OPTIONS))) {
173 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
174 return undefined;
175 }
176 const limits = agentSliceMemoryLimits(NodeOS.totalmem());
177 const limited = yield* run(systemctl, [
178 "--user",
179 "set-property",
180 "--runtime",
181 AGENT_SLICE,
182 `MemoryHigh=${limits.high}`,
183 `MemoryMax=${limits.max}`,
184 ]);
185 if (limited._tag === "None" || limited.value.code !== 0) {
186 yield* Effect.logWarning("Could not set memory limits on the agents slice", {
187 stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined,
188 });
189 }
190 yield* Effect.logInfo("Agent scopes are on", {
191 slice: AGENT_SLICE,
192 ...limits,
193 oomPolicy: supportsOomPolicy,
194 });
195 return {
196 systemdRun,
197 systemctl,
198 runtimeDir,
199 supportsOomPolicy,
200 };
201 }),
202 );
203
204 // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.
205 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();
206
207 const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {
208 const shown = yield* run(systemctl, [
209 "--user",
210 "show",
211 unit,
212 "--property=LoadState,ActiveState,Result,ControlGroup",
213 ]);
214 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
215 const values = parseKeyValues(shown.value.stdout);
216 const controlGroup = values.get("ControlGroup") ?? "";
217 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
218 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
219 const populated = parseCgroupCounter(cgroupEvents, "populated");
220 return {
221 loadState: values.get("LoadState") ?? "",
222 activeState: values.get("ActiveState") ?? "",
223 result: values.get("Result") ?? "",
224 oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
225 populated: populated === undefined ? undefined : populated === 1,
226 } satisfies ScopeState;
227 });
228
229 const clearFailed = Effect.fn("agentScope.clearFailed")(function* (
230 systemctl: string,
231 unit: string,
232 ) {
233 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
234 const state = yield* readScope(systemctl, unit);
235 if (state === undefined) return;
236 if (state.activeState === "failed") {
237 yield* run(systemctl, ["--user", "reset-failed", unit]);
238 return;
239 }
240 if (state.activeState !== "deactivating") return;
241 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
242 }
243 });
244
245 const forget = (systemctl: string, unit: string) =>
246 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
247
248 const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {
249 const oldest = scopeByThread.entries().next();
250 if (oldest.done === true) return;
251 const [threadId, tracked] = oldest.value;
252 const state = yield* readScope(systemctl, tracked.unit);
253 if (scopeByThread.get(threadId) !== tracked) return;
254 scopeByThread.delete(threadId);
255 const status = state === undefined ? "running" : classifyScope(state);
256 if (status === "running" || status === "stopping") {
257 scopeByThread.set(threadId, tracked);
258 return;
259 }
260 yield* forget(systemctl, tracked.unit);
261 });
262
263 const track = Effect.fn("agentScope.track")(function* (
264 systemctl: string,
265 threadId: string,
266 unit: string | undefined,
267 shared = false,
268 ) {
269 const previous = scopeByThread.get(threadId);
270 scopeByThread.delete(threadId);
271 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false, shared });
272 if (previous !== undefined) yield* forget(systemctl, previous.unit);
273 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
274 });
275
276 const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(
277 function* (threadId) {
278 const tracked = scopeByThread.get(threadId);
279 if (tracked === undefined) return false;
280 if (tracked.oomKilled) return true;
281 const scope = yield* systemd;
282 if (scope === undefined) return false;
283 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
284 const state = yield* readScope(scope.systemctl, tracked.unit);
285 if (state === undefined) return false;
286 const status = classifyScope(state);
287 if (status === "running") return false;
288 if (status === "stopping") {
289 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
290 continue;
291 }
292 yield* forget(scope.systemctl, tracked.unit);
293 if (status === "gone") return false;
294 yield* Effect.logWarning("Agent scope was killed: out of memory", {
295 threadId,
296 unit: tracked.unit,
297 });
298 tracked.oomKilled = true;
299 return true;
300 }
301 return false;
302 },
303 );
304
305 const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
306 if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
307 const scope = yield* systemd;
308 if (scope === undefined) return;
309 const state = yield* readScope(scope.systemctl, unit);
310 if (
311 state === undefined ||
312 state.loadState !== "loaded" ||
313 state.activeState !== "active" ||
314 state.result === "oom-kill" ||
315 state.populated === false
316 )
317 return;
318 // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
319 // record the result before a manual stop can overwrite it; an unreadable
320 // counter cannot rule out that race. Older managers need us to stop it.
321 if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
322 const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
323 if (stopped._tag === "None" || stopped.value.code !== 0) {
324 yield* Effect.logWarning("Could not stop an exited agent's scope", {
325 unit,
326 exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
327 });
328 }
329 });
330
331 const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) {
332 const tracked = scopeByThread.get(threadId);
333 if (tracked === undefined || tracked.shared) return false;
334 const scope = yield* systemd;
335 if (scope === undefined) return false;
336 const shown = yield* run(scope.systemctl, [
337 "--user",
338 "show",
339 tracked.unit,
340 "--property=ActiveState,ControlGroup",
341 ]);
342 if (shown._tag === "None" || shown.value.code !== 0) return false;
343 const values = parseKeyValues(shown.value.stdout);
344 if (values.get("ActiveState") !== "active") return false;
345 const controlGroup = values.get("ControlGroup") ?? "";
346 // cgroup.kill (Linux 5.14+) kills the whole tree at once; systemd's kill is the fallback.
347 const killedByCgroup =
348 controlGroup.length > 0 &&
349 (yield* fileSystem
350 .writeFileString(path.join("/sys/fs/cgroup", controlGroup, "cgroup.kill"), "1")
351 .pipe(
352 Effect.as(true),
353 Effect.orElseSucceed(() => false),
354 ));
355 if (killedByCgroup) return true;
356 const killed = yield* run(scope.systemctl, [
357 "--user",
358 "kill",
359 "--signal=SIGKILL",
360 tracked.unit,
361 ]);
362 return killed._tag === "Some" && killed.value.code === 0;
363 });
364
365 const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
366 if (!scopeByThread.has(threadId)) return;
367 const scope = yield* systemd;
368 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
369 });
370
371 return {
372 wrap: Effect.fn("AgentScope.wrap")(function* ({
373 command,
374 args,
375 name,
376 threadId,
377 env,
378 survivesRestart,
379 shared,
380 }) {
381 const resolved = yield* resolve(command, env ?? hostEnvironment);
382 if (resolved === null) return { command, args };
383 const scope = yield* systemd;
384 if (scope === undefined) return agentScopeCommand({ command: resolved, args });
385 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
386 // A continuing shared scope cannot attribute a tool's OOM to one thread.
387 // Clear the launch thread's previous scope instead.
388 const continuing = shared === true && scope.supportsOomPolicy;
389 const owned = threadId !== undefined && !continuing;
390 if (threadId !== undefined)
391 yield* track(scope.systemctl, threadId, owned ? unit : undefined, shared === true);
392 const systemdScope: AgentSystemdScope = {
393 systemdRun: scope.systemdRun,
394 runtimeDir: scope.runtimeDir,
395 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
396 unit,
397 // Without an owning thread nothing reads the result, so let systemd
398 // unload the unit even when it fails.
399 options: [
400 ...SCOPE_OPTIONS,
401 ...(scope.supportsOomPolicy
402 ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]
403 : []),
404 ...(owned ? [] : ["--collect"]),
405 ],
406 };
407 return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit };
408 }),
409 oomKilled,
410 stop,
411 kill,
412 clear,
413 } satisfies AgentScopeShape;
414});
415
416export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));