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 /**
12 * Set for terminals, so a job the user detached (tmux, nohup) outlives a
13 * server restart. Agents leave it unset: the next server stops agents a
14 * killed server left running before it resumes their sessions.
15 */
16 readonly survivesRestart?: boolean | undefined;
17 /**
18 * Keep a shared process running after a tool OOM when supported.
19 * Falls back to ordinary scope behavior on older systemd.
20 */
21 readonly shared?: boolean | undefined;
22 }) => Effect.Effect<AgentScopeCommand>;
23 readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
24 /**
25 * Reaps processes left after the owning agent exits, including setsid
26 * descendants outside its process group. Preserves systemd OOM diagnosis.
27 */
28 readonly stop: (unit: string) => Effect.Effect<void>;
29 /**
30 * Forgets the thread's scope. The session manager calls it before it opens
31 * a provider session, so a scope only answers for the session that launched
32 * it, even when the next session runs without one (Cursor, OpenCode).
33 */
34 readonly clear: (threadId: string) => Effect.Effect<void>;
35}
36
37export interface AgentScopeCommand {
38 readonly command: string;
39 readonly args: ReadonlyArray<string>;
40 /** The systemd scope the command runs in, for `stop`. */
41 readonly unit?: string | undefined;
42}
43
44export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
45 defaultValue: () => ({
46 wrap: ({ command, args }) => Effect.succeed({ command, args }),
47 oomKilled: () => Effect.succeed(false),
48 stop: () => Effect.void,
49 clear: () => Effect.void,
50 }),
51});
52
53export const AgentScopeThreadId = Context.Reference<string | undefined>(
54 "@t3tools/shared/AgentScope/ThreadId",
55 { defaultValue: () => undefined },
56);
57
58export const AGENT_OOM_SCORE_ADJ = 800;
59
60export const RAISE_OOM_SCORE_LINE = `{ echo ${AGENT_OOM_SCORE_ADJ} >/proc/self/oom_score_adj; } 2>/dev/null`;
61
62const LAUNCH_SCRIPT = [RAISE_OOM_SCORE_LINE, 'exec "$@"'].join("\n");
63
64// systemd-run needs XDG_RUNTIME_DIR to reach the user manager. Fill it in when
65// the agent environment does not carry it; it is the same user either way.
66const SCOPED_LAUNCH_SCRIPT = [
67 RAISE_OOM_SCORE_LINE,
68 ': "${XDG_RUNTIME_DIR:=$1}"',
69 "export XDG_RUNTIME_DIR",
70 "shift",
71 'exec "$@"',
72].join("\n");
73
74export interface AgentSystemdScope {
75 readonly systemdRun: string;
76 readonly slice: string;
77 readonly unit: string;
78 readonly runtimeDir: string;
79 readonly options: ReadonlyArray<string>;
80}
81
82/**
83 * Every step `exec`s, so the spawned PID, stdio, and signals all belong to the agent itself.
84 * `systemd-run --scope` registers its own PID as the scope and then runs the command, so the
85 * agent and all of its children start inside the scope.
86 */
87export function agentScopeCommand(input: {
88 readonly command: string;
89 readonly args: ReadonlyArray<string>;
90 readonly scope?: AgentSystemdScope | undefined;
91}): AgentScopeCommand {
92 const { command, args, scope } = input;
93 if (scope === undefined) {
94 return { command: "/bin/sh", args: ["-c", LAUNCH_SCRIPT, "t3-agent", command, ...args] };
95 }
96 return {
97 command: "/bin/sh",
98 args: [
99 "-c",
100 SCOPED_LAUNCH_SCRIPT,
101 "t3-agent",
102 scope.runtimeDir,
103 scope.systemdRun,
104 "--user",
105 "--scope",
106 "--quiet",
107 `--slice=${scope.slice}`,
108 `--unit=${scope.unit}`,
109 ...scope.options,
110 "--",
111 command,
112 ...args,
113 ],
114 };
115}