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 interface AgentSystemdScope {
87 readonly systemdRun: string;
88 readonly slice: string;
89 readonly unit: string;
90 readonly runtimeDir: string;
91 /** Extra `systemd-run` options, such as `--property=OOMPolicy=stop`. */
92 readonly options: ReadonlyArray<string>;
93}
94
95/**
96 * Builds the Linux launch for an agent command. Every step `exec`s, so the
97 * spawned PID, stdio, and signals all belong to the agent itself.
98 * `systemd-run --scope` registers its own PID as the scope and then runs the
99 * command, so the agent and all of its children start inside the scope.
100 */
101export function agentScopeCommand(input: {
102 readonly command: string;
103 readonly args: ReadonlyArray<string>;
104 readonly scope?: AgentSystemdScope | undefined;
105}): AgentScopeCommand {
106 const { command, args, scope } = input;
107 if (scope === undefined) {
108 return { command: "/bin/sh", args: ["-c", LAUNCH_SCRIPT, "t3-agent", command, ...args] };
109 }
110 return {
111 command: "/bin/sh",
112 args: [
113 "-c",
114 SCOPED_LAUNCH_SCRIPT,
115 "t3-agent",
116 scope.runtimeDir,
117 scope.systemdRun,
118 "--user",
119 "--scope",
120 "--quiet",
121 `--slice=${scope.slice}`,
122 `--unit=${scope.unit}`,
123 ...scope.options,
124 "--",
125 command,
126 ...args,
127 ],
128 };
129}