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