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