Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3
4/**
5 * Isolates long-lived agent and terminal processes from the server on Linux.
6 *
7 * Each wrapped command runs with a high `oom_score_adj`, so the kernel OOM
8 * killer picks it before the server. Under a systemd user manager it also runs
9 * in its own transient scope, so systemd-oomd (which kills whole leaf cgroups)
10 * kills one agent instead of the server and every other agent.
11 *
12 * The server provides the real implementation. The default leaves commands
13 * unchanged, which is also the behavior on macOS, Windows, and in tests.
14 */
15export interface AgentScopeShape {
16 /**
17 * Wraps the command that starts an agent or terminal. `name` labels the
18 * scope unit, for example "claude" or "terminal". `env` is the environment
19 * the command will run with, used to resolve it on PATH. A command that does
20 * not resolve stays unwrapped, so a missing binary still fails at spawn.
21 */
22 readonly wrap: (input: {
23 readonly command: string;
24 readonly args: ReadonlyArray<string>;
25 readonly name: string;
26 readonly threadId?: string | undefined;
27 readonly env?: NodeJS.ProcessEnv | undefined;
28 }) => Effect.Effect<AgentScopeCommand>;
29 /**
30 * Whether the latest agent scope of this thread was killed because the
31 * machine or the agents slice ran out of memory. The answer holds until the
32 * thread launches its next agent, so a retried failure reads the same.
33 */
34 readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
35 /**
36 * Forgets the thread's scope. The session manager calls it before it opens
37 * a provider session, so a scope only answers for the session that launched
38 * it, even when the next session runs without one (Cursor, OpenCode).
39 */
40 readonly clear: (threadId: string) => Effect.Effect<void>;
41}
42
43export interface AgentScopeCommand {
44 readonly command: string;
45 readonly args: ReadonlyArray<string>;
46}
47
48export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
49 defaultValue: () => ({
50 wrap: ({ command, args }) => Effect.succeed({ command, args }),
51 oomKilled: () => Effect.succeed(false),
52 clear: () => Effect.void,
53 }),
54});
55
56/**
57 * The thread an ACP runtime is spawned for. ACP runtimes are shared by several
58 * provider flavors and do not take a thread id, so the ACP adapter provides it.
59 */
60export const AgentScopeThreadId = Context.Reference<string | undefined>(
61 "@t3tools/shared/AgentScope/ThreadId",
62 { defaultValue: () => undefined },
63);
64
65/**
66 * Agents get this `oom_score_adj` so the kernel kills them before the server.
67 * An unprivileged process may raise its own score, never lower it.
68 */
69export const AGENT_OOM_SCORE_ADJ = 800;
70
71/** Shell line that raises the score of the current process, ignoring failure. */
72export const RAISE_OOM_SCORE_LINE = `{ echo ${AGENT_OOM_SCORE_ADJ} >/proc/self/oom_score_adj; } 2>/dev/null`;
73
74const LAUNCH_SCRIPT = [RAISE_OOM_SCORE_LINE, 'exec "$@"'].join("\n");
75
76// systemd-run needs XDG_RUNTIME_DIR to reach the user manager. Fill it in when
77// the agent environment does not carry it; it is the same user either way.
78const SCOPED_LAUNCH_SCRIPT = [
79 RAISE_OOM_SCORE_LINE,
80 ': "${XDG_RUNTIME_DIR:=$1}"',
81 "export XDG_RUNTIME_DIR",
82 "shift",
83 'exec "$@"',
84].join("\n");
85
86export const SCOPE_WATCH_SCRIPT = [
87 "server=$1 systemctl=$2 unit=$3 agent=$4",
88 "reap() {",
89 ' kill "$sleeper" 2>/dev/null',
90 ' kill -0 "$server" 2>/dev/null || exec "$systemctl" --user stop "$unit"',
91 " exit 0",
92 "}",
93 "trap reap TERM",
94 'kill -0 "$agent" 2>/dev/null || reap',
95 "while :; do",
96 " sleep 3600 &",
97 " sleeper=$!",
98 ' wait "$sleeper"',
99 "done",
100].join("\n");
101
102const SCOPE_GUARD_SCRIPT = [
103 "server=$PPID",
104 '"$1" --pdeathsig TERM -- /bin/sh -c "$2" t3-agent-watch "$server" "$3" "$4" "$$" >/dev/null 2>&1 </dev/null &',
105 "shift 4",
106 'exec "$@"',
107].join("\n");
108
109export interface AgentSystemdScope {
110 readonly systemdRun: string;
111 readonly systemctl: string;
112 readonly slice: string;
113 readonly unit: string;
114 readonly runtimeDir: string;
115 /** Extra `systemd-run` options, such as `--property=OOMPolicy=stop`. */
116 readonly options: ReadonlyArray<string>;
117}
118
119/**
120 * Builds the Linux launch for an agent command. Every step `exec`s, so the
121 * spawned PID, stdio, and signals all belong to the agent itself.
122 * `systemd-run --scope` registers its own PID as the scope and then runs the
123 * command, so the agent and all of its children start inside the scope.
124 */
125export function agentScopeCommand(input: {
126 readonly command: string;
127 readonly args: ReadonlyArray<string>;
128 readonly scope?: AgentSystemdScope | undefined;
129 readonly setpriv?: string | undefined;
130}): AgentScopeCommand {
131 const { command, args, scope, setpriv } = input;
132 const dieWithServer = setpriv === undefined ? [] : [setpriv, "--pdeathsig", "TERM", "--"];
133 if (scope === undefined) {
134 return {
135 command: "/bin/sh",
136 args: ["-c", LAUNCH_SCRIPT, "t3-agent", ...dieWithServer, command, ...args],
137 };
138 }
139 return {
140 command: "/bin/sh",
141 args: [
142 "-c",
143 SCOPED_LAUNCH_SCRIPT,
144 "t3-agent",
145 scope.runtimeDir,
146 ...dieWithServer,
147 scope.systemdRun,
148 "--user",
149 "--scope",
150 "--quiet",
151 `--slice=${scope.slice}`,
152 `--unit=${scope.unit}`,
153 ...scope.options,
154 "--",
155 ...(setpriv === undefined
156 ? []
157 : [
158 "/bin/sh",
159 "-c",
160 SCOPE_GUARD_SCRIPT,
161 "t3-agent-guard",
162 setpriv,
163 SCOPE_WATCH_SCRIPT,
164 scope.systemctl,
165 scope.unit,
166 ]),
167 command,
168 ...args,
169 ],
170 };
171}