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 type AgentControlGroups,
7 AgentScope,
8 agentScopeCommand,
9 type AgentScopeShape,
10 type AgentSystemdScope,
11} from "@t3tools/shared/AgentScope";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { resolveCommandPath } from "@t3tools/shared/shell";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Path from "effect/Path";
18import * as Semaphore from "effect/Semaphore";
19
20import * as ServerConfig from "../config.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import * as ProviderProcesses from "./providerProcesses.ts";
23
24const AGENT_SLICE = "app-t3code-agents.slice";
25// Owns every agent slice and competes with the server's unit or scope under app.slice.
26const AGENTS_PARENT_SLICE = "app-t3code.slice";
27// Low weights yield CPU and disk to the server under contention, where the user manager
28// has those controllers: current systemd delegates cpu, rarely io. TasksMax keeps agents
29// below logind's 33% per-user task limit, leaving forks for the server.
30const AGENTS_PARENT_PROPERTIES = ["CPUWeight=10", "IOWeight=10", "TasksMax=25%"];
31
32export function ownedAgentSlice(stateDir: string): string {
33 const hash = NodeCrypto.createHash("sha256").update(stateDir).digest("hex").slice(0, 12);
34 return `app-t3code-agents-${hash}.slice`;
35}
36
37const GiB = 1024 ** 3;
38
39/**
40 * Agents leave about 6 GB free before throttling and 4 GB before an OOM kill (at
41 * least half and three quarters of RAM go to agents) so the server and sshd keep
42 * working. Without swap, MemoryHigh stalls every agent and never reaches the kill.
43 */
44function agentSliceMemoryLimits(totalBytes: number, hasSwap: boolean) {
45 return {
46 high: hasSwap ? Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)) : "infinity",
47 max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)),
48 };
49}
50
51export interface ScopeState {
52 readonly loadState: string;
53 readonly activeState: string;
54 readonly result: string;
55 readonly oomKills: number | undefined;
56 readonly populated: boolean | undefined;
57}
58
59/** Pipes can close before systemd records oom-kill; stopping, empty or OOM-counted scopes remain pending. */
60export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
61 if (state.result === "oom-kill") return "oom-killed";
62 if (
63 state.loadState !== "loaded" ||
64 state.activeState === "inactive" ||
65 state.activeState === "failed"
66 ) {
67 return "gone";
68 }
69 if (
70 state.activeState === "deactivating" ||
71 (state.oomKills ?? 0) > 0 ||
72 state.populated === false
73 ) {
74 return "stopping";
75 }
76 return "running";
77}
78
79function parseKeyValues(text: string): Map<string, string> {
80 const values = new Map<string, string>();
81 for (const line of text.split("\n")) {
82 const index = line.indexOf("=");
83 if (index > 0) values.set(line.slice(0, index), line.slice(index + 1).trim());
84 }
85 return values;
86}
87
88function parseCgroupCounter(text: string, key: string): number | undefined {
89 const match = new RegExp(`^${key} (\\d+)$`, "m").exec(text);
90 return match === null ? undefined : Number(match[1]);
91}
92
93// systemd's default 90 s stop timeout would outlast our leftover-agent wait.
94// Delegation lets rootless containers (Podman, kind) manage their own cgroups.
95const SCOPE_OPTIONS = ["--property=TimeoutStopSec=10s", "--property=Delegate=yes"];
96const STOPPING_POLL_INTERVAL = "100 millis";
97const STOPPING_POLL_ATTEMPTS = 20;
98const CLEAR_FAILED_INTERVAL = "1 second";
99const CLEAR_FAILED_ATTEMPTS = 120;
100const MAX_TRACKED_THREADS = 500;
101
102export const make = Effect.gen(function* () {
103 const platform = yield* HostProcess.Platform;
104 if (platform !== "linux") return AgentScope.defaultValue();
105
106 const runner = yield* ProcessRunner.ProcessRunner;
107 const fileSystem = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const hostEnvironment = yield* HostProcess.Environment;
110 const { stateDir } = yield* ServerConfig.ServerConfig;
111 const { hasOtherLiveOwner } = yield* ProviderProcesses.ProviderProcesses;
112 const ownedSlice = ownedAgentSlice(stateDir);
113 const layerScope = yield* Effect.scope;
114
115 const resolve = (command: string, env: NodeJS.ProcessEnv) =>
116 resolveCommandPath(command, { env }).pipe(
117 Effect.provideService(FileSystem.FileSystem, fileSystem),
118 Effect.provideService(Path.Path, path),
119 Effect.provideService(HostProcess.Platform, platform),
120 );
121
122 // Termux and similar hosts have no /bin/sh, only an `sh` on PATH.
123 const shell = (yield* fileSystem.exists("/bin/sh").pipe(Effect.orElseSucceed(() => false)))
124 ? "/bin/sh"
125 : ((yield* resolve("sh", hostEnvironment)) ?? "/bin/sh");
126
127 const run = (command: string, args: ReadonlyArray<string>) =>
128 runner.run({ command, args, timeout: "5 seconds" }).pipe(Effect.option);
129
130 const readCgroupFile = (controlGroup: string, file: string) =>
131 fileSystem
132 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
133 .pipe(Effect.orElseSucceed(() => ""));
134
135 // Old agents keep their scopes when the server is killed, and the restarted
136 // server resumes their sessions. Stop them first, so two copies of one
137 // session never work in the same worktree.
138 const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
139 systemctl: string,
140 ) {
141 if (hasOtherLiveOwner) return;
142 const shown = yield* run(systemctl, [
143 "--user",
144 "show",
145 ownedSlice,
146 "--property=ActiveState,ControlGroup",
147 ]);
148 if (shown._tag === "None") return;
149 const values = parseKeyValues(shown.value.stdout);
150 if (values.get("ActiveState") !== "active") return;
151 const controlGroup = values.get("ControlGroup") ?? "";
152 const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
153 if (parseCgroupCounter(events, "populated") === 0) return;
154 yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
155 const stopped = yield* runner
156 .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
157 .pipe(Effect.option);
158 if (stopped._tag === "None" || stopped.value.code !== 0) {
159 yield* Effect.logWarning("Could not stop agents left by a previous server", {
160 slice: ownedSlice,
161 stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
162 });
163 }
164 });
165
166 const systemd = yield* Effect.cached(
167 Effect.gen(function* () {
168 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
169 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
170 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
171 const systemctl = yield* resolve("systemctl", hostEnvironment);
172 if (systemdRun === null || systemctl === null) return undefined;
173 yield* stopLeftoverAgents(systemctl);
174 const probe = (options: ReadonlyArray<string>) =>
175 run(systemdRun, [
176 "--user",
177 "--scope",
178 "--quiet",
179 "--collect",
180 `--slice=${AGENT_SLICE}`,
181 ...options,
182 "--",
183 "true",
184 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
185 // Scopes take OOMPolicy from systemd 253; older managers still get scopes.
186 const supportsOomPolicy = yield* probe([...SCOPE_OPTIONS, "--property=OOMPolicy=stop"]);
187 if (!supportsOomPolicy && !(yield* probe(SCOPE_OPTIONS))) {
188 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
189 return undefined;
190 }
191 const setProperties = Effect.fn("agentScope.setProperties")(function* (
192 slice: string,
193 properties: ReadonlyArray<string>,
194 ) {
195 const result = yield* run(systemctl, [
196 "--user",
197 "set-property",
198 "--runtime",
199 slice,
200 ...properties,
201 ]);
202 if (result._tag === "Some" && result.value.code === 0) return true;
203 yield* Effect.logWarning("Could not set resource limits on an agents slice", {
204 slice,
205 properties,
206 stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined,
207 });
208 return false;
209 });
210 // VMs and containers can resize RAM live, so each launch re-checks the total
211 // the limits came from. A failed update is retried by the next launch.
212 // An unreadable meminfo keeps the throttle, as before swap was checked.
213 const readHasSwap = fileSystem.readFileString("/proc/meminfo").pipe(
214 Effect.map((text) => /^SwapTotal:\s*0 kB$/m.exec(text) === null),
215 Effect.orElseSucceed(() => true),
216 );
217 let appliedTotal: number | undefined;
218 let appliedHasSwap: boolean | undefined;
219 const memoryLimitsLock = yield* Semaphore.make(1);
220 const applyMemoryLimits = memoryLimitsLock.withPermits(1)(
221 Effect.gen(function* () {
222 const total = NodeOS.totalmem();
223 const hasSwap = yield* readHasSwap;
224 if (total === appliedTotal && hasSwap === appliedHasSwap) return;
225 const limits = agentSliceMemoryLimits(total, hasSwap);
226 const applied = yield* setProperties(AGENT_SLICE, [
227 `MemoryHigh=${limits.high}`,
228 `MemoryMax=${limits.max}`,
229 ]);
230 if (!applied) return;
231 if (appliedTotal !== undefined) {
232 yield* Effect.logInfo("Agent memory limits follow a memory change", {
233 slice: AGENT_SLICE,
234 previousTotal: appliedTotal,
235 total,
236 ...limits,
237 });
238 }
239 appliedTotal = total;
240 appliedHasSwap = hasSwap;
241 }),
242 );
243 yield* applyMemoryLimits;
244 yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES);
245 yield* Effect.logInfo("Agent scopes are on", {
246 slice: AGENT_SLICE,
247 ...agentSliceMemoryLimits(NodeOS.totalmem(), yield* readHasSwap),
248 oomPolicy: supportsOomPolicy,
249 });
250 return {
251 systemdRun,
252 systemctl,
253 runtimeDir,
254 supportsOomPolicy,
255 applyMemoryLimits,
256 };
257 }),
258 );
259
260 // Layer acquisition is the startup barrier: recovery must not terminalize or
261 // continue old runs while a previous server's providers can still execute.
262 yield* systemd;
263
264 // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.
265 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();
266
267 const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {
268 const shown = yield* run(systemctl, [
269 "--user",
270 "show",
271 unit,
272 "--property=LoadState,ActiveState,Result,ControlGroup",
273 ]);
274 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
275 const values = parseKeyValues(shown.value.stdout);
276 const controlGroup = values.get("ControlGroup") ?? "";
277 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
278 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
279 const populated = parseCgroupCounter(cgroupEvents, "populated");
280 return {
281 loadState: values.get("LoadState") ?? "",
282 activeState: values.get("ActiveState") ?? "",
283 result: values.get("Result") ?? "",
284 oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
285 populated: populated === undefined ? undefined : populated === 1,
286 } satisfies ScopeState;
287 });
288
289 const clearFailed = Effect.fn("agentScope.clearFailed")(function* (
290 systemctl: string,
291 unit: string,
292 ) {
293 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
294 const state = yield* readScope(systemctl, unit);
295 if (state === undefined) return;
296 if (state.activeState === "failed") {
297 yield* run(systemctl, ["--user", "reset-failed", unit]);
298 return;
299 }
300 if (state.activeState !== "deactivating") return;
301 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
302 }
303 });
304
305 const forget = (systemctl: string, unit: string) =>
306 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
307
308 const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {
309 const oldest = scopeByThread.entries().next();
310 if (oldest.done === true) return;
311 const [threadId, tracked] = oldest.value;
312 const state = yield* readScope(systemctl, tracked.unit);
313 if (scopeByThread.get(threadId) !== tracked) return;
314 scopeByThread.delete(threadId);
315 const status = state === undefined ? "running" : classifyScope(state);
316 if (status === "running" || status === "stopping") {
317 scopeByThread.set(threadId, tracked);
318 return;
319 }
320 yield* forget(systemctl, tracked.unit);
321 });
322
323 const track = Effect.fn("agentScope.track")(function* (
324 systemctl: string,
325 threadId: string,
326 unit: string | undefined,
327 shared = false,
328 ) {
329 const previous = scopeByThread.get(threadId);
330 scopeByThread.delete(threadId);
331 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false, shared });
332 if (previous !== undefined) yield* forget(systemctl, previous.unit);
333 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
334 });
335
336 const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(
337 function* (threadId) {
338 const tracked = scopeByThread.get(threadId);
339 if (tracked === undefined) return false;
340 if (tracked.oomKilled) return true;
341 const scope = yield* systemd;
342 if (scope === undefined) return false;
343 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
344 const state = yield* readScope(scope.systemctl, tracked.unit);
345 if (state === undefined) return false;
346 const status = classifyScope(state);
347 if (status === "running") return false;
348 if (status === "stopping") {
349 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
350 continue;
351 }
352 yield* forget(scope.systemctl, tracked.unit);
353 if (status === "gone") return false;
354 yield* Effect.logWarning("Agent scope was killed: out of memory", {
355 threadId,
356 unit: tracked.unit,
357 });
358 tracked.oomKilled = true;
359 return true;
360 }
361 return false;
362 },
363 );
364
365 const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
366 if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
367 const scope = yield* systemd;
368 if (scope === undefined) return;
369 const state = yield* readScope(scope.systemctl, unit);
370 if (
371 state === undefined ||
372 state.loadState !== "loaded" ||
373 state.activeState !== "active" ||
374 state.result === "oom-kill" ||
375 state.populated === false
376 )
377 return;
378 // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
379 // record the result before a manual stop can overwrite it; an unreadable
380 // counter cannot rule out that race. Older managers need us to stop it.
381 if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
382 const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
383 if (stopped._tag === "None" || stopped.value.code !== 0) {
384 yield* Effect.logWarning("Could not stop an exited agent's scope", {
385 unit,
386 exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
387 });
388 }
389 });
390
391 const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) {
392 const tracked = scopeByThread.get(threadId);
393 if (tracked === undefined || tracked.shared) return false;
394 const scope = yield* systemd;
395 if (scope === undefined) return false;
396 const shown = yield* run(scope.systemctl, [
397 "--user",
398 "show",
399 tracked.unit,
400 "--property=ActiveState,ControlGroup",
401 ]);
402 if (shown._tag === "None" || shown.value.code !== 0) return false;
403 const values = parseKeyValues(shown.value.stdout);
404 if (values.get("ActiveState") !== "active") return false;
405 const controlGroup = values.get("ControlGroup") ?? "";
406 // cgroup.kill (Linux 5.14+) kills the whole tree at once; systemd's kill is the fallback.
407 const killedByCgroup =
408 controlGroup.length > 0 &&
409 (yield* fileSystem
410 .writeFileString(path.join("/sys/fs/cgroup", controlGroup, "cgroup.kill"), "1")
411 .pipe(
412 Effect.as(true),
413 Effect.orElseSucceed(() => false),
414 ));
415 if (killedByCgroup) return true;
416 const killed = yield* run(scope.systemctl, [
417 "--user",
418 "kill",
419 "--signal=SIGKILL",
420 tracked.unit,
421 ]);
422 return killed._tag === "Some" && killed.value.code === 0;
423 });
424
425 let sliceControlGroup: string | undefined;
426 const controlGroups: AgentScopeShape["controlGroups"] = Effect.gen(function* () {
427 const scope = yield* systemd;
428 if (scope === undefined) return undefined;
429 if (sliceControlGroup === undefined) {
430 const shown = yield* run(scope.systemctl, [
431 "--user",
432 "show",
433 AGENT_SLICE,
434 "--property=ControlGroup",
435 ]);
436 const controlGroup =
437 shown._tag === "Some" ? parseKeyValues(shown.value.stdout).get("ControlGroup") : undefined;
438 // Empty until the first agent starts the slice.
439 if (controlGroup === undefined || controlGroup.length === 0) return undefined;
440 sliceControlGroup = controlGroup;
441 }
442 const ownedControlGroup = path.join(sliceControlGroup, ownedSlice);
443 const entries = yield* fileSystem
444 .readDirectory(path.join("/sys/fs/cgroup", ownedControlGroup))
445 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
446 const threadByUnit = new Map(
447 [...scopeByThread].flatMap(([threadId, tracked]) =>
448 tracked.shared ? [] : [[tracked.unit, threadId] as const],
449 ),
450 );
451 return {
452 slice: sliceControlGroup,
453 scopes: entries.flatMap((unit) => {
454 const agent = /^t3code-(.+)-[0-9a-f]{8}\.scope$/.exec(unit)?.[1];
455 return agent === undefined
456 ? []
457 : [{ path: path.join(ownedControlGroup, unit), threadId: threadByUnit.get(unit), agent }];
458 }),
459 } satisfies AgentControlGroups;
460 });
461
462 const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
463 if (!scopeByThread.has(threadId)) return;
464 const scope = yield* systemd;
465 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
466 });
467
468 return {
469 wrap: Effect.fn("AgentScope.wrap")(function* ({
470 command,
471 args,
472 name,
473 threadId,
474 env,
475 survivesRestart,
476 shared,
477 }) {
478 const resolved = yield* resolve(command, env ?? hostEnvironment);
479 if (resolved === null) return { command, args };
480 const scope = yield* systemd;
481 if (scope === undefined) return agentScopeCommand({ command: resolved, args, shell });
482 yield* scope.applyMemoryLimits;
483 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
484 // A continuing shared scope cannot attribute a tool's OOM to one thread.
485 // Clear the launch thread's previous scope instead.
486 const continuing = shared === true && scope.supportsOomPolicy;
487 const owned = threadId !== undefined && !continuing;
488 if (threadId !== undefined)
489 yield* track(scope.systemctl, threadId, owned ? unit : undefined, shared === true);
490 const systemdScope: AgentSystemdScope = {
491 systemdRun: scope.systemdRun,
492 runtimeDir: scope.runtimeDir,
493 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
494 unit,
495 // Without an owning thread nothing reads the result, so let systemd
496 // unload the unit even when it fails.
497 options: [
498 ...SCOPE_OPTIONS,
499 ...(scope.supportsOomPolicy
500 ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]
501 : []),
502 ...(owned ? [] : ["--collect"]),
503 ],
504 };
505 // systemd-run does not search the caller's cwd, so anchor a relative path to it. Keep ".."
506 // as spelled: collapsing it would skip a symlinked parent directory.
507 const executable = path.isAbsolute(resolved)
508 ? resolved
509 : `${process.cwd()}${path.sep}${resolved}`;
510 return {
511 ...agentScopeCommand({ command: executable, args, scope: systemdScope, shell }),
512 unit,
513 };
514 }),
515 oomKilled,
516 stop,
517 kill,
518 controlGroups,
519 clear,
520 } satisfies AgentScopeShape;
521});
522
523export const layer = Layer.effect(AgentScope, make).pipe(
524 Layer.provide(ProcessRunner.layer),
525 Layer.provideMerge(ProviderProcesses.layer),
526);