Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3
4export interface AgentScopeShape {
5 readonly wrap: (input: {
6 readonly command: string;
7 readonly args: ReadonlyArray<string>;
8 readonly name: string;
9 readonly threadId?: string | undefined;
10 readonly env?: NodeJS.ProcessEnv | undefined;
11 /** Terminals may survive restarts; agents must remain eligible for orphan cleanup. */
12 readonly survivesRestart?: boolean | undefined;
13 /**
14 * Keep a shared process running after a tool OOM when supported.
15 * Falls back to ordinary scope behavior on older systemd.
16 */
17 readonly shared?: boolean | undefined;
18 }) => Effect.Effect<AgentScopeCommand>;
19 readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
20 /**
21 * Reaps processes left after the owning agent exits, including setsid
22 * descendants outside its process group. Preserves systemd OOM diagnosis.
23 */
24 readonly stop: (unit: string) => Effect.Effect<void>;
25 /**
26 * SIGKILLs every process in the thread's own scope, which works even while
27 * the kernel throttles them. Shared scopes serve other threads and are never
28 * killed here. Succeeds with whether a scope was killed.
29 */
30 readonly kill: (threadId: string) => Effect.Effect<boolean>;
31 /**
32 * Where agents' memory can be read: the cgroup of the agents slice and of each
33 * live agent scope, with the thread that owns it. Undefined without scopes.
34 */
35 readonly controlGroups: Effect.Effect<AgentControlGroups | undefined>;
36 /**
37 * Forgets the thread's scope. The session manager calls it before it opens
38 * a provider session, so a scope only answers for the session that launched
39 * it, even when the next session runs without one (Cursor, OpenCode).
40 */
41 readonly clear: (threadId: string) => Effect.Effect<void>;
42}
43
44export interface AgentControlGroups {
45 /** Relative to the cgroup root, such as `/user.slice/.../app-t3code-agents.slice`. */
46 readonly slice: string;
47 readonly scopes: ReadonlyArray<{
48 readonly path: string;
49 /** Undefined for a process several threads share. */
50 readonly threadId: string | undefined;
51 /** What launched it, such as `claude` or `codex`. */
52 readonly agent: string;
53 }>;
54}
55
56export interface AgentScopeCommand {
57 readonly command: string;
58 readonly args: ReadonlyArray<string>;
59 /** The systemd scope the command runs in, for `stop`. */
60 readonly unit?: string | undefined;
61}
62
63export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
64 defaultValue: () => ({
65 wrap: ({ command, args }) => Effect.succeed({ command, args }),
66 oomKilled: () => Effect.succeed(false),
67 stop: () => Effect.void,
68 kill: () => Effect.succeed(false),
69 controlGroups: Effect.undefined,
70 clear: () => Effect.void,
71 }),
72});
73
74export const AgentScopeThreadId = Context.Reference<string | undefined>(
75 "@t3tools/shared/AgentScope/ThreadId",
76 { defaultValue: () => undefined },
77);
78
79export const AGENT_OOM_SCORE_ADJ = 800;
80
81export const RAISE_OOM_SCORE_LINE = `{ echo ${AGENT_OOM_SCORE_ADJ} >/proc/self/oom_score_adj; } 2>/dev/null`;
82
83const LAUNCH_SCRIPT = [RAISE_OOM_SCORE_LINE, 'exec "$@"'].join("\n");
84
85// systemd-run needs XDG_RUNTIME_DIR to reach this user's manager.
86const SCOPED_LAUNCH_SCRIPT = [
87 RAISE_OOM_SCORE_LINE,
88 ': "${XDG_RUNTIME_DIR:=$1}"',
89 "export XDG_RUNTIME_DIR",
90 "shift",
91 'exec "$@"',
92].join("\n");
93
94export interface AgentSystemdScope {
95 readonly systemdRun: string;
96 readonly slice: string;
97 readonly unit: string;
98 readonly runtimeDir: string;
99 readonly options: ReadonlyArray<string>;
100}
101
102const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
103
104/** An executable file for launchers that take a path, not a command line, such as Playwright. */
105export function agentScopeLauncherScript(launch: AgentScopeCommand): string {
106 const command = [launch.command, ...launch.args].map(quoteShell).join(" ");
107 return `#!/bin/sh\nexec ${command} "$@"\n`;
108}
109
110/** Exec at every step preserves the agent PID, stdio, and signals; systemd-run places it and descendants in the scope. */
111export function agentScopeCommand(input: {
112 readonly command: string;
113 readonly args: ReadonlyArray<string>;
114 readonly scope?: AgentSystemdScope | undefined;
115 readonly shell?: string | undefined;
116}): AgentScopeCommand {
117 const { command, args, scope, shell = "/bin/sh" } = input;
118 if (scope === undefined) {
119 return { command: shell, args: ["-c", LAUNCH_SCRIPT, "t3-agent", command, ...args] };
120 }
121 return {
122 command: shell,
123 args: [
124 "-c",
125 SCOPED_LAUNCH_SCRIPT,
126 "t3-agent",
127 scope.runtimeDir,
128 scope.systemdRun,
129 "--user",
130 "--scope",
131 "--quiet",
132 `--slice=${scope.slice}`,
133 `--unit=${scope.unit}`,
134 ...scope.options,
135 "--",
136 command,
137 ...args,
138 ],
139 };
140}