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 * Forgets the thread's scope. The session manager calls it before it opens
26 * a provider session, so a scope only answers for the session that launched
27 * it, even when the next session runs without one (Cursor, OpenCode).
28 */
29 readonly clear: (threadId: string) => Effect.Effect<void>;
30}
31
32export interface AgentScopeCommand {
33 readonly command: string;
34 readonly args: ReadonlyArray<string>;
35}
36
37export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
38 defaultValue: () => ({
39 wrap: ({ command, args }) => Effect.succeed({ command, args }),
40 oomKilled: () => Effect.succeed(false),
41 clear: () => Effect.void,
42 }),
43});
44
45export const AgentScopeThreadId = Context.Reference<string | undefined>(
46 "@t3tools/shared/AgentScope/ThreadId",
47 { defaultValue: () => undefined },
48);
49
50export const AGENT_OOM_SCORE_ADJ = 800;
51
52export const RAISE_OOM_SCORE_LINE = `{ echo ${AGENT_OOM_SCORE_ADJ} >/proc/self/oom_score_adj; } 2>/dev/null`;
53
54const LAUNCH_SCRIPT = [RAISE_OOM_SCORE_LINE, 'exec "$@"'].join("\n");
55
56// systemd-run needs XDG_RUNTIME_DIR to reach the user manager. Fill it in when
57// the agent environment does not carry it; it is the same user either way.
58const SCOPED_LAUNCH_SCRIPT = [
59 RAISE_OOM_SCORE_LINE,
60 ': "${XDG_RUNTIME_DIR:=$1}"',
61 "export XDG_RUNTIME_DIR",
62 "shift",
63 'exec "$@"',
64].join("\n");
65
66export interface AgentSystemdScope {
67 readonly systemdRun: string;
68 readonly slice: string;
69 readonly unit: string;
70 readonly runtimeDir: string;
71 readonly options: ReadonlyArray<string>;
72}
73
74/**
75 * Every step `exec`s, so the spawned PID, stdio, and signals all belong to the agent itself.
76 * `systemd-run --scope` registers its own PID as the scope and then runs the command, so the
77 * agent and all of its children start inside the scope.
78 */
79export function agentScopeCommand(input: {
80 readonly command: string;
81 readonly args: ReadonlyArray<string>;
82 readonly scope?: AgentSystemdScope | undefined;
83}): AgentScopeCommand {
84 const { command, args, scope } = input;
85 if (scope === undefined) {
86 return { command: "/bin/sh", args: ["-c", LAUNCH_SCRIPT, "t3-agent", command, ...args] };
87 }
88 return {
89 command: "/bin/sh",
90 args: [
91 "-c",
92 SCOPED_LAUNCH_SCRIPT,
93 "t3-agent",
94 scope.runtimeDir,
95 scope.systemdRun,
96 "--user",
97 "--scope",
98 "--quiet",
99 `--slice=${scope.slice}`,
100 `--unit=${scope.unit}`,
101 ...scope.options,
102 "--",
103 command,
104 ...args,
105 ],
106 };
107}