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 // systemd-run does not search the caller's cwd, so anchor a relative path to it. Keep ".."
123 // as spelled: collapsing it would skip a symlinked parent directory.
124 const anchor = (resolved: string) =>
125 path.isAbsolute(resolved) ? resolved : `${process.cwd()}${path.sep}${resolved}`;
126
127 // Termux and similar hosts have no /bin/sh, only an `sh` on PATH. Launcher
128 // scripts put it in a shebang, which needs an absolute path.
129 const shell = (yield* fileSystem.exists("/bin/sh").pipe(Effect.orElseSucceed(() => false)))
130 ? "/bin/sh"
131 : anchor((yield* resolve("sh", hostEnvironment)) ?? "/bin/sh");
132
133 const run = (command: string, args: ReadonlyArray<string>) =>
134 runner.run({ command, args, timeout: "5 seconds" }).pipe(Effect.option);
135
136 const readCgroupFile = (controlGroup: string, file: string) =>
137 fileSystem
138 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
139 .pipe(Effect.orElseSucceed(() => ""));
140
141 // Old agents keep their scopes when the server is killed, and the restarted
142 // server resumes their sessions. Stop them first, so two copies of one
143 // session never work in the same worktree.
144 const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
145 systemctl: string,
146 ) {
147 if (hasOtherLiveOwner) return;
148 const shown = yield* run(systemctl, [
149 "--user",
150 "show",
151 ownedSlice,
152 "--property=ActiveState,ControlGroup",
153 ]);
154 if (shown._tag === "None") return;
155 const values = parseKeyValues(shown.value.stdout);
156 if (values.get("ActiveState") !== "active") return;
157 const controlGroup = values.get("ControlGroup") ?? "";
158 const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
159 if (parseCgroupCounter(events, "populated") === 0) return;
160 yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
161 const stopped = yield* runner
162 .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
163 .pipe(Effect.option);
164 if (stopped._tag === "None" || stopped.value.code !== 0) {
165 yield* Effect.logWarning("Could not stop agents left by a previous server", {
166 slice: ownedSlice,
167 stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
168 });
169 }
170 });
171
172 const systemd = yield* Effect.cached(
173 Effect.gen(function* () {
174 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
175 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
176 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
177 const systemctl = yield* resolve("systemctl", hostEnvironment);
178 if (systemdRun === null || systemctl === null) return undefined;
179 yield* stopLeftoverAgents(systemctl);
180 const probe = (options: ReadonlyArray<string>) =>
181 run(systemdRun, [
182 "--user",
183 "--scope",
184 "--quiet",
185 "--collect",
186 `--slice=${AGENT_SLICE}`,
187 ...options,
188 "--",
189 "true",
190 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
191 // Scopes take OOMPolicy from systemd 253; older managers still get scopes.
192 const supportsOomPolicy = yield* probe([...SCOPE_OPTIONS, "--property=OOMPolicy=stop"]);
193 if (!supportsOomPolicy && !(yield* probe(SCOPE_OPTIONS))) {
194 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
195 return undefined;
196 }
197 const setProperties = Effect.fn("agentScope.setProperties")(function* (
198 slice: string,
199 properties: ReadonlyArray<string>,
200 ) {
201 const result = yield* run(systemctl, [
202 "--user",
203 "set-property",
204 "--runtime",
205 slice,
206 ...properties,
207 ]);
208 if (result._tag === "Some" && result.value.code === 0) return true;
209 yield* Effect.logWarning("Could not set resource limits on an agents slice", {
210 slice,
211 properties,
212 stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined,
213 });
214 return false;
215 });
216 // VMs and containers can resize RAM live, so each launch re-checks the total
217 // the limits came from. A failed update is retried by the next launch.
218 // An unreadable meminfo keeps the throttle, as before swap was checked.
219 const readHasSwap = fileSystem.readFileString("/proc/meminfo").pipe(
220 Effect.map((text) => /^SwapTotal:\s*0 kB$/m.exec(text) === null),
221 Effect.orElseSucceed(() => true),
222 );
223 let appliedTotal: number | undefined;
224 let appliedHasSwap: boolean | undefined;
225 const memoryLimitsLock = yield* Semaphore.make(1);
226 const applyMemoryLimits = memoryLimitsLock.withPermits(1)(
227 Effect.gen(function* () {
228 const total = NodeOS.totalmem();
229 const hasSwap = yield* readHasSwap;
230 if (total === appliedTotal && hasSwap === appliedHasSwap) return;
231 const limits = agentSliceMemoryLimits(total, hasSwap);
232 const applied = yield* setProperties(AGENT_SLICE, [
233 `MemoryHigh=${limits.high}`,
234 `MemoryMax=${limits.max}`,
235 ]);
236 if (!applied) return;
237 if (appliedTotal !== undefined) {
238 yield* Effect.logInfo("Agent memory limits follow a memory change", {
239 slice: AGENT_SLICE,
240 previousTotal: appliedTotal,
241 total,
242 ...limits,
243 });
244 }
245 appliedTotal = total;
246 appliedHasSwap = hasSwap;
247 }),
248 );
249 yield* applyMemoryLimits;
250 yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES);
251 yield* Effect.logInfo("Agent scopes are on", {
252 slice: AGENT_SLICE,
253 ...agentSliceMemoryLimits(NodeOS.totalmem(), yield* readHasSwap),
254 oomPolicy: supportsOomPolicy,
255 });
256 return {
257 systemdRun,
258 systemctl,
259 runtimeDir,
260 supportsOomPolicy,
261 applyMemoryLimits,
262 };
263 }),
264 );
265
266 // Layer acquisition is the startup barrier: recovery must not terminalize or
267 // continue old runs while a previous server's providers can still execute.
268 yield* systemd;
269
270 // `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.
271 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();
272
273 const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {
274 const shown = yield* run(systemctl, [
275 "--user",
276 "show",
277 unit,
278 "--property=LoadState,ActiveState,Result,ControlGroup",
279 ]);
280 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
281 const values = parseKeyValues(shown.value.stdout);
282 const controlGroup = values.get("ControlGroup") ?? "";
283 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
284 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
285 const populated = parseCgroupCounter(cgroupEvents, "populated");
286 return {
287 loadState: values.get("LoadState") ?? "",
288 activeState: values.get("ActiveState") ?? "",
289 result: values.get("Result") ?? "",
290 oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
291 populated: populated === undefined ? undefined : populated === 1,
292 } satisfies ScopeState;
293 });
294
295 const clearFailed = Effect.fn("agentScope.clearFailed")(function* (
296 systemctl: string,
297 unit: string,
298 ) {
299 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
300 const state = yield* readScope(systemctl, unit);
301 if (state === undefined) return;
302 if (state.activeState === "failed") {
303 yield* run(systemctl, ["--user", "reset-failed", unit]);
304 return;
305 }
306 if (state.activeState !== "deactivating") return;
307 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
308 }
309 });
310
311 const forget = (systemctl: string, unit: string) =>
312 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
313
314 const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {
315 const oldest = scopeByThread.entries().next();
316 if (oldest.done === true) return;
317 const [threadId, tracked] = oldest.value;
318 const state = yield* readScope(systemctl, tracked.unit);
319 if (scopeByThread.get(threadId) !== tracked) return;
320 scopeByThread.delete(threadId);
321 const status = state === undefined ? "running" : classifyScope(state);
322 if (status === "running" || status === "stopping") {
323 scopeByThread.set(threadId, tracked);
324 return;
325 }
326 yield* forget(systemctl, tracked.unit);
327 });
328
329 const track = Effect.fn("agentScope.track")(function* (
330 systemctl: string,
331 threadId: string,
332 unit: string | undefined,
333 shared = false,
334 ) {
335 const previous = scopeByThread.get(threadId);
336 scopeByThread.delete(threadId);
337 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false, shared });
338 if (previous !== undefined) yield* forget(systemctl, previous.unit);
339 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
340 });
341
342 const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(
343 function* (threadId) {
344 const tracked = scopeByThread.get(threadId);
345 if (tracked === undefined) return false;
346 if (tracked.oomKilled) return true;
347 const scope = yield* systemd;
348 if (scope === undefined) return false;
349 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
350 const state = yield* readScope(scope.systemctl, tracked.unit);
351 if (state === undefined) return false;
352 const status = classifyScope(state);
353 if (status === "running") return false;
354 if (status === "stopping") {
355 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
356 continue;
357 }
358 yield* forget(scope.systemctl, tracked.unit);
359 if (status === "gone") return false;
360 yield* Effect.logWarning("Agent scope was killed: out of memory", {
361 threadId,
362 unit: tracked.unit,
363 });
364 tracked.oomKilled = true;
365 return true;
366 }
367 return false;
368 },
369 );
370
371 const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
372 if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
373 const scope = yield* systemd;
374 if (scope === undefined) return;
375 const state = yield* readScope(scope.systemctl, unit);
376 if (
377 state === undefined ||
378 state.loadState !== "loaded" ||
379 state.activeState !== "active" ||
380 state.result === "oom-kill" ||
381 state.populated === false
382 )
383 return;
384 // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
385 // record the result before a manual stop can overwrite it; an unreadable
386 // counter cannot rule out that race. Older managers need us to stop it.
387 if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
388 const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
389 if (stopped._tag === "None" || stopped.value.code !== 0) {
390 yield* Effect.logWarning("Could not stop an exited agent's scope", {
391 unit,
392 exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
393 });
394 }
395 });
396
397 const kill: AgentScopeShape["kill"] = Effect.fn("AgentScope.kill")(function* (threadId) {
398 const tracked = scopeByThread.get(threadId);
399 if (tracked === undefined || tracked.shared) return false;
400 const scope = yield* systemd;
401 if (scope === undefined) return false;
402 const shown = yield* run(scope.systemctl, [
403 "--user",
404 "show",
405 tracked.unit,
406 "--property=ActiveState,ControlGroup",
407 ]);
408 if (shown._tag === "None" || shown.value.code !== 0) return false;
409 const values = parseKeyValues(shown.value.stdout);
410 if (values.get("ActiveState") !== "active") return false;
411 const controlGroup = values.get("ControlGroup") ?? "";
412 // cgroup.kill (Linux 5.14+) kills the whole tree at once; systemd's kill is the fallback.
413 const killedByCgroup =
414 controlGroup.length > 0 &&
415 (yield* fileSystem
416 .writeFileString(path.join("/sys/fs/cgroup", controlGroup, "cgroup.kill"), "1")
417 .pipe(
418 Effect.as(true),
419 Effect.orElseSucceed(() => false),
420 ));
421 if (killedByCgroup) return true;
422 const killed = yield* run(scope.systemctl, [
423 "--user",
424 "kill",
425 "--signal=SIGKILL",
426 tracked.unit,
427 ]);
428 return killed._tag === "Some" && killed.value.code === 0;
429 });
430
431 let sliceControlGroup: string | undefined;
432 const controlGroups: AgentScopeShape["controlGroups"] = Effect.gen(function* () {
433 const scope = yield* systemd;
434 if (scope === undefined) return undefined;
435 if (sliceControlGroup === undefined) {
436 const shown = yield* run(scope.systemctl, [
437 "--user",
438 "show",
439 AGENT_SLICE,
440 "--property=ControlGroup",
441 ]);
442 const controlGroup =
443 shown._tag === "Some" ? parseKeyValues(shown.value.stdout).get("ControlGroup") : undefined;
444 // Empty until the first agent starts the slice.
445 if (controlGroup === undefined || controlGroup.length === 0) return undefined;
446 sliceControlGroup = controlGroup;
447 }
448 const ownedControlGroup = path.join(sliceControlGroup, ownedSlice);
449 const entries = yield* fileSystem
450 .readDirectory(path.join("/sys/fs/cgroup", ownedControlGroup))
451 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
452 const threadByUnit = new Map(
453 [...scopeByThread].flatMap(([threadId, tracked]) =>
454 tracked.shared ? [] : [[tracked.unit, threadId] as const],
455 ),
456 );
457 return {
458 slice: sliceControlGroup,
459 scopes: entries.flatMap((unit) => {
460 const agent = /^t3code-(.+)-[0-9a-f]{8}\.scope$/.exec(unit)?.[1];
461 return agent === undefined
462 ? []
463 : [{ path: path.join(ownedControlGroup, unit), threadId: threadByUnit.get(unit), agent }];
464 }),
465 } satisfies AgentControlGroups;
466 });
467
468 const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
469 if (!scopeByThread.has(threadId)) return;
470 const scope = yield* systemd;
471 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
472 });
473
474 return {
475 wrap: Effect.fn("AgentScope.wrap")(function* ({
476 command,
477 args,
478 name,
479 threadId,
480 env,
481 survivesRestart,
482 shared,
483 }) {
484 const resolved = yield* resolve(command, env ?? hostEnvironment);
485 if (resolved === null) return { command, args };
486 const scope = yield* systemd;
487 if (scope === undefined) return agentScopeCommand({ command: resolved, args, shell });
488 yield* scope.applyMemoryLimits;
489 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
490 // A continuing shared scope cannot attribute a tool's OOM to one thread.
491 // Clear the launch thread's previous scope instead.
492 const continuing = shared === true && scope.supportsOomPolicy;
493 const owned = threadId !== undefined && !continuing;
494 if (threadId !== undefined)
495 yield* track(scope.systemctl, threadId, owned ? unit : undefined, shared === true);
496 const systemdScope: AgentSystemdScope = {
497 systemdRun: scope.systemdRun,
498 runtimeDir: scope.runtimeDir,
499 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
500 unit,
501 // Without an owning thread nothing reads the result, so let systemd
502 // unload the unit even when it fails.
503 options: [
504 ...SCOPE_OPTIONS,
505 ...(scope.supportsOomPolicy
506 ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]
507 : []),
508 ...(owned ? [] : ["--collect"]),
509 ],
510 };
511 return {
512 ...agentScopeCommand({ command: anchor(resolved), args, scope: systemdScope, shell }),
513 unit,
514 };
515 }),
516 oomKilled,
517 stop,
518 kill,
519 controlGroups,
520 clear,
521 } satisfies AgentScopeShape;
522});
523
524export const layer = Layer.effect(AgentScope, make).pipe(
525 Layer.provide(ProcessRunner.layer),
526 Layer.provideMerge(ProviderProcesses.layer),
527);