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

agentScope.ts

382 lines14.4 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";
20​
21const AGENT_SLICE = "app-t3code-agents.slice";
22​
23export function ownedAgentSlice(stateDir: string): string {
24 const hash = NodeCrypto.createHash("sha256").update(stateDir).digest("hex").slice(0, 12);
25 return `app-t3code-agents-${hash}.slice`;
27​
28const GiB = 1024 ** 3;
29​
30/**
31 * Agents together leave about 6 GB free before they are throttled and 4 GB
32 * before the kernel kills one, so the server, sshd, and tailscaled keep
33 * working. Small machines still give agents at least half of RAM before
34 * throttling and three quarters before a kill.
35 */
36function agentSliceMemoryLimits(totalBytes: number) {
37 return {
38 high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)),
39 max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)),
40 };
42​
43export interface ScopeState {
44 readonly loadState: string;
45 readonly activeState: string;
46 readonly result: string;
47 readonly oomKills: number | undefined;
48 readonly populated: boolean | undefined;
50​
51/**
52 * Our pipe can close before systemd handles the kill, so a scope that is
53 * still stopping, is empty, or already counted an OOM kill is "stopping":
54 * systemd records `Result=oom-kill` for it in a moment.
55 */
56export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
57 if (state.result === "oom-kill") return "oom-killed";
58 if (
59 state.loadState !== "loaded" ||
60 state.activeState === "inactive" ||
61 state.activeState === "failed"
62 ) {
63 return "gone";
64 }
65 if (
66 state.activeState === "deactivating" ||
67 (state.oomKills ?? 0) > 0 ||
68 state.populated === false
69 ) {
70 return "stopping";
71 }
72 return "running";
74​
75function parseKeyValues(text: string): Map<string, string> {
76 const values = new Map<string, string>();
77 for (const line of text.split("\n")) {
78 const index = line.indexOf("=");
79 if (index > 0) values.set(line.slice(0, index), line.slice(index + 1).trim());
80 }
81 return values;
83​
84function parseCgroupCounter(text: string, key: string): number | undefined {
85 const match = new RegExp(`^${key} (\\d+)$`, "m").exec(text);
86 return match === null ? undefined : Number(match[1]);
88​
89// A stop sends SIGTERM, then SIGKILL after this long. systemd's 90 s default
90// would outlast the wait for a previous server's agents below.
91const STOP_TIMEOUT_OPTION = "--property=TimeoutStopSec=10s";
92const STOPPING_POLL_INTERVAL = "100 millis";
93const STOPPING_POLL_ATTEMPTS = 20;
94const CLEAR_FAILED_INTERVAL = "1 second";
95const CLEAR_FAILED_ATTEMPTS = 120;
96const MAX_TRACKED_THREADS = 500;
97​
98export const make = Effect.gen(function* () {
99 const platform = yield* HostProcess.Platform;
100 if (platform !== "linux") return AgentScope.defaultValue();
101​
102 const runner = yield* ProcessRunner.ProcessRunner;
103 const fileSystem = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const hostEnvironment = yield* HostProcess.Environment;
106 const { stateDir } = yield* ServerConfig.ServerConfig;
107 const ownedSlice = ownedAgentSlice(stateDir);
108 const layerScope = yield* Effect.scope;
109​
110 const resolve = (command: string, env: NodeJS.ProcessEnv) =>
111 resolveCommandPath(command, { env }).pipe(
112 Effect.provideService(FileSystem.FileSystem, fileSystem),
113 Effect.provideService(Path.Path, path),
114 Effect.provideService(HostProcess.Platform, platform),
115 );
116​
117 const run = (command: string, args: ReadonlyArray<string>) =>
118 runner.run({ command, args, timeout: "5 seconds" }).pipe(Effect.option);
119​
120 const readCgroupFile = (controlGroup: string, file: string) =>
121 fileSystem
122 .readFileString(path.join("/sys/fs/cgroup", controlGroup, file))
123 .pipe(Effect.orElseSucceed(() => ""));
124​
125 // Old agents keep their scopes when the server is killed, and the restarted
126 // server resumes their sessions. Stop them first, so two copies of one
127 // session never work in the same worktree.
128 const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
129 systemctl: string,
130 ) {
131 const shown = yield* run(systemctl, [
132 "--user",
133 "show",
134 ownedSlice,
135 "--property=ActiveState,ControlGroup",
136 ]);
137 if (shown._tag === "None") return;
138 const values = parseKeyValues(shown.value.stdout);
139 if (values.get("ActiveState") !== "active") return;
140 const controlGroup = values.get("ControlGroup") ?? "";
141 const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
142 if (parseCgroupCounter(events, "populated") === 0) return;
143 yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
144 const stopped = yield* runner
145 .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
146 .pipe(Effect.option);
147 if (stopped._tag === "None" || stopped.value.code !== 0) {
148 yield* Effect.logWarning("Could not stop agents left by a previous server", {
149 slice: ownedSlice,
150 stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
151 });
152 }
153 });
154​
155 const systemd = yield* Effect.cached(
156 Effect.gen(function* () {
157 const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
158 if (runtimeDir === undefined || runtimeDir.length === 0) return undefined;
159 const systemdRun = yield* resolve("systemd-run", hostEnvironment);
160 const systemctl = yield* resolve("systemctl", hostEnvironment);
161 if (systemdRun === null || systemctl === null) return undefined;
162 yield* stopLeftoverAgents(systemctl);
163 const probe = (options: ReadonlyArray<string>) =>
164 run(systemdRun, [
165 "--user",
166 "--scope",
167 "--quiet",
168 "--collect",
169 `--slice=${AGENT_SLICE}`,
170 ...options,
171 "--",
172 "true",
173 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
174 // Scopes take OOMPolicy from systemd 253; older managers still get scopes.
175 const supportsOomPolicy = yield* probe([STOP_TIMEOUT_OPTION, "--property=OOMPolicy=stop"]);
176 if (!supportsOomPolicy && !(yield* probe([STOP_TIMEOUT_OPTION]))) {
177 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
178 return undefined;
179 }
180 const limits = agentSliceMemoryLimits(NodeOS.totalmem());
181 const limited = yield* run(systemctl, [
182 "--user",
183 "set-property",
184 "--runtime",
185 AGENT_SLICE,
186 `MemoryHigh=${limits.high}`,
187 `MemoryMax=${limits.max}`,
188 ]);
189 if (limited._tag === "None" || limited.value.code !== 0) {
190 yield* Effect.logWarning("Could not set memory limits on the agents slice", {
191 stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined,
192 });
193 }
194 yield* Effect.logInfo("Agent scopes are on", {
195 slice: AGENT_SLICE,
196 ...limits,
197 oomPolicy: supportsOomPolicy,
198 });
199 return {
200 systemdRun,
201 systemctl,
202 runtimeDir,
203 supportsOomPolicy,
204 };
205 }),
206 );
207​
208 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();
209​
210 const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {
211 const shown = yield* run(systemctl, [
212 "--user",
213 "show",
214 unit,
215 "--property=LoadState,ActiveState,Result,ControlGroup",
216 ]);
217 if (shown._tag === "None" || shown.value.code !== 0) return undefined;
218 const values = parseKeyValues(shown.value.stdout);
219 const controlGroup = values.get("ControlGroup") ?? "";
220 const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
221 const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
222 const populated = parseCgroupCounter(cgroupEvents, "populated");
223 return {
224 loadState: values.get("LoadState") ?? "",
225 activeState: values.get("ActiveState") ?? "",
226 result: values.get("Result") ?? "",
227 oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
228 populated: populated === undefined ? undefined : populated === 1,
229 } satisfies ScopeState;
230 });
231​
232 const clearFailed = Effect.fn("agentScope.clearFailed")(function* (
233 systemctl: string,
234 unit: string,
235 ) {
236 for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
237 const state = yield* readScope(systemctl, unit);
238 if (state === undefined) return;
239 if (state.activeState === "failed") {
240 yield* run(systemctl, ["--user", "reset-failed", unit]);
241 return;
242 }
243 if (state.activeState !== "deactivating") return;
244 yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
245 }
246 });
247​
248 const forget = (systemctl: string, unit: string) =>
249 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
250​
251 const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {
252 const oldest = scopeByThread.entries().next();
253 if (oldest.done === true) return;
254 const [threadId, tracked] = oldest.value;
255 const state = yield* readScope(systemctl, tracked.unit);
256 if (scopeByThread.get(threadId) !== tracked) return;
257 scopeByThread.delete(threadId);
258 const status = state === undefined ? "running" : classifyScope(state);
259 if (status === "running" || status === "stopping") {
260 scopeByThread.set(threadId, tracked);
261 return;
262 }
263 yield* forget(systemctl, tracked.unit);
264 });
265​
266 const track = Effect.fn("agentScope.track")(function* (
267 systemctl: string,
268 threadId: string,
269 unit: string | undefined,
270 ) {
271 const previous = scopeByThread.get(threadId);
272 scopeByThread.delete(threadId);
273 if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
274 if (previous !== undefined) yield* forget(systemctl, previous.unit);
275 if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
276 });
277​
278 const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(
279 function* (threadId) {
280 const tracked = scopeByThread.get(threadId);
281 if (tracked === undefined) return false;
282 if (tracked.oomKilled) return true;
283 const scope = yield* systemd;
284 if (scope === undefined) return false;
285 for (let attempt = 0; attempt < STOPPING_POLL_ATTEMPTS; attempt++) {
286 const state = yield* readScope(scope.systemctl, tracked.unit);
287 if (state === undefined) return false;
288 const status = classifyScope(state);
289 if (status === "running") return false;
290 if (status === "stopping") {
291 yield* Effect.sleep(STOPPING_POLL_INTERVAL);
292 continue;
293 }
294 yield* forget(scope.systemctl, tracked.unit);
295 if (status === "gone") return false;
296 yield* Effect.logWarning("Agent scope was killed: out of memory", {
297 threadId,
298 unit: tracked.unit,
299 });
300 tracked.oomKilled = true;
301 return true;
302 }
303 return false;
304 },
305 );
306​
307 const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
308 if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
309 const scope = yield* systemd;
310 if (scope === undefined) return;
311 const state = yield* readScope(scope.systemctl, unit);
312 if (
313 state === undefined ||
314 state.loadState !== "loaded" ||
315 state.activeState !== "active" ||
316 state.result === "oom-kill" ||
317 state.populated === false
318 )
319 return;
320 // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
321 // record the result before a manual stop can overwrite it; an unreadable
322 // counter cannot rule out that race. Older managers need us to stop it.
323 if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
324 const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
325 if (stopped._tag === "None" || stopped.value.code !== 0) {
326 yield* Effect.logWarning("Could not stop an exited agent's scope", {
327 unit,
328 exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
329 });
330 }
331 });
332​
333 const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
334 if (!scopeByThread.has(threadId)) return;
335 const scope = yield* systemd;
336 if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
337 });
338​
339 return {
340 wrap: Effect.fn("AgentScope.wrap")(function* ({
341 command,
342 args,
343 name,
344 threadId,
345 env,
346 survivesRestart,
347 shared,
348 }) {
349 const resolved = yield* resolve(command, env ?? hostEnvironment);
350 if (resolved === null) return { command, args };
351 const scope = yield* systemd;
352 if (scope === undefined) return agentScopeCommand({ command: resolved, args });
353 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
354 // A continuing shared scope cannot attribute a tool's OOM to one thread.
355 // Clear the launch thread's previous scope instead.
356 const continuing = shared === true && scope.supportsOomPolicy;
357 const owned = threadId !== undefined && !continuing;
358 if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined);
359 const systemdScope: AgentSystemdScope = {
360 systemdRun: scope.systemdRun,
361 runtimeDir: scope.runtimeDir,
362 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
363 unit,
364 // Without an owning thread nothing reads the result, so let systemd
365 // unload the unit even when it fails.
366 options: [
367 STOP_TIMEOUT_OPTION,
368 ...(scope.supportsOomPolicy
369 ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]
370 : []),
371 ...(owned ? [] : ["--collect"]),
372 ],
373 };
374 return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit };
375 }),
376 oomKilled,
377 stop,
378 clear,
379 } satisfies AgentScopeShape;
380});
381​
382export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));