Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

agentScope.ts

535 lines20.9 KB

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