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

agentScope.ts

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