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