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 /** The POSIX shell that runs the launch script; hosts without /bin/sh resolve another. */
62 readonly shell?: string | undefined;
63}
64
65export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
66 defaultValue: () => ({
67 wrap: ({ command, args }) => Effect.succeed({ command, args }),
68 oomKilled: () => Effect.succeed(false),
69 stop: () => Effect.void,
70 kill: () => Effect.succeed(false),
71 controlGroups: Effect.undefined,
72 clear: () => Effect.void,
73 }),
74});
75
76export const AgentScopeThreadId = Context.Reference<string | undefined>(
77 "@t3tools/shared/AgentScope/ThreadId",
78 { defaultValue: () => undefined },
79);
80
81// Above the user manager's default (200) so agents die before the session, but close
82// to it: jobs agents detach with `systemd-run --user` get that default, so a detached
83// job using most of memory dies before an agent does.
84export const AGENT_OOM_SCORE_ADJ = 300;
85
86export const RAISE_OOM_SCORE_LINE = `{ echo ${AGENT_OOM_SCORE_ADJ} >/proc/self/oom_score_adj; } 2>/dev/null`;
87
88const LAUNCH_SCRIPT = [RAISE_OOM_SCORE_LINE, 'exec "$@"'].join("\n");
89
90// systemd-run needs XDG_RUNTIME_DIR to reach this user's manager.
91const SCOPED_LAUNCH_SCRIPT = [
92 RAISE_OOM_SCORE_LINE,
93 ': "${XDG_RUNTIME_DIR:=$1}"',
94 "export XDG_RUNTIME_DIR",
95 "shift",
96 'exec "$@"',
97].join("\n");
98
99export interface AgentSystemdScope {
100 readonly systemdRun: string;
101 readonly slice: string;
102 readonly unit: string;
103 readonly runtimeDir: string;
104 readonly options: ReadonlyArray<string>;
105}
106
107const DEFAULT_SHELL = "/bin/sh";
108
109const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
110
111/** An executable file for launchers that take a path, not a command line, such as Playwright. */
112export function agentScopeLauncherScript(launch: AgentScopeCommand): string {
113 const command = [launch.command, ...launch.args].map(quoteShell).join(" ");
114 const shell = launch.shell ?? DEFAULT_SHELL;
115 const interpreter = shell.startsWith("/") && !/[\s\0]/.test(shell) ? shell : DEFAULT_SHELL;
116 return `#!${interpreter}\nexec ${command} "$@"\n`;
117}
118
119/** Exec at every step preserves the agent PID, stdio, and signals; systemd-run places it and descendants in the scope. */
120export function agentScopeCommand(input: {
121 readonly command: string;
122 readonly args: ReadonlyArray<string>;
123 readonly scope?: AgentSystemdScope | undefined;
124 readonly shell?: string | undefined;
125}): AgentScopeCommand {
126 const { command, args, scope, shell = DEFAULT_SHELL } = input;
127 if (scope === undefined) {
128 return { command: shell, args: ["-c", LAUNCH_SCRIPT, "t3-agent", command, ...args], shell };
129 }
130 return {
131 command: shell,
132 args: [
133 "-c",
134 SCOPED_LAUNCH_SCRIPT,
135 "t3-agent",
136 scope.runtimeDir,
137 scope.systemdRun,
138 "--user",
139 "--scope",
140 "--quiet",
141 `--slice=${scope.slice}`,
142 `--unit=${scope.unit}`,
143 ...scope.options,
144 "--",
145 command,
146 ...args,
147 ],
148 shell,
149 };
150}