Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import {
mcpAppToolResourceUri,
} from "@t3tools/shared/mcpApp";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as ProviderProcesses from "../../process/providerProcesses.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
Expand Down Expand Up @@ -372,21 +373,26 @@ const CLAUDE_DESCENDANT_POLL = "1 second";
const CLAUDE_ROOT_REFUSAL =
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";

// fd 4 gates the launch until the server has recorded the process it is about to become.
const CLAUDE_GROUP_WATCH_SCRIPT = [
"read -r _ <&4 || exit 1",
"exec 4<&-",
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
'exec "$@" 3<&-',
].join("\n");

/**
* Kill the CLI's group on exit to stop MCP grandchildren; `onExit` stops its agent scope for
* setsid daemons. The CLI keeps working after its pipes close, so a watcher stops the group on
* EOF from a pipe only this server holds, including when the server crashes.
* EOF from a pipe only this server holds, including when the server crashes. `register` records
* the CLI before it may run, so a restarted server can reap it if the watcher did not.
*/
export function spawnClaudeProcessGroup(
options: ClaudeSpawnOptions,
onExit?: () => void,
onStderr: (text: string) => void = () => {},
onStderrClose: () => void = () => {},
register?: (pid: number) => () => void,
): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
const child = NodeChildProcess.spawn(
"/bin/sh",
Expand All @@ -395,18 +401,34 @@ export function spawnClaudeProcessGroup(
cwd: options.cwd,
env: options.env,
signal: options.signal,
stdio: ["pipe", "pipe", "pipe", "pipe"],
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"],
detached: true,
},
);
let forget: (() => void) | undefined;
// Always drained, so a chatty CLI never blocks on a full stderr pipe.
child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose);
child.once("exit", () => {
try {
signalProcessGroup(child.pid ?? 0, "SIGKILL");
} catch {}
try {
forget?.();
} catch {}
onExit?.();
});
const gate = child.stdio[4];
if (child.pid !== undefined && gate !== null && gate !== undefined && "end" in gate) {
try {
forget = register?.(child.pid);
gate.on("error", () => child.kill("SIGKILL"));
gate.end("ready\n");
} catch (cause) {
child.kill("SIGKILL");
gate.destroy();
throw cause;
}
}
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid">;
}
Expand Down Expand Up @@ -1256,6 +1278,7 @@ export const layerQueryRunner: Layer.Layer<
const path = yield* Path.Path;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const providerProcesses = yield* ProviderProcesses.ProviderProcesses;
const platform = yield* HostProcess.Platform;
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const hostEnvironment = yield* HostProcess.Environment;
Expand Down Expand Up @@ -1372,6 +1395,7 @@ export const layerQueryRunner: Layer.Layer<
stopScope,
appendStderr,
stderrDone,
providerProcesses.register,
);
if (unit === undefined && child.pid !== undefined) {
const tracker = trackDescendants(child.pid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,47 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
}),
);

// A restarted server reaps recorded CLIs, so a CLI must never run before its record exists.
it.effect("records the CLI before it runs and forgets it once it exits", () =>
Effect.gen(function* () {
const cli = fakeClaudeCli(
['dir=$(dirname "$0")', 'printf \'%s %s\' "$$" "$(cat "$dir/record")" > "$dir/seen"'].join(
"\n",
),
);
const dir = NodePath.dirname(cli);
NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "seen")]);
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
);
const forgotten = yield* Deferred.make<void>();
let registered = 0;
spawnClaudeProcessGroup(
{
command: cli,
args: [],
cwd: dir,
env: process.env,
// @effect-diagnostics-next-line abortControllerInEffect:off - The CLI exits on its own.
signal: new AbortController().signal,
},
undefined,
undefined,
undefined,
(pid) => {
registered = pid;
NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid));
return () => Deferred.doneUnsafe(forgotten, Effect.void);
},
);
const seen = yield* Effect.promise(() =>
NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"),
);
assert.equal(seen, `${registered} ${registered}`);
yield* Deferred.await(forgotten);
}),
);

it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
let runningAgents = 0;
let releaseAgent!: () => void;
Expand Down
59 changes: 39 additions & 20 deletions apps/server/src/process/agentScope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as ServerConfig from "../config.ts";
import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ProviderProcesses from "./providerProcesses.ts";
import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";

const running: ScopeState = {
Expand Down Expand Up @@ -55,7 +56,14 @@ const withFakeSystemd = <A, E>(
{
oomPolicy = true,
stopFails = false,
}: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {},
leftovers = false,
liveOwner = false,
}: {
readonly oomPolicy?: boolean;
readonly stopFails?: boolean;
readonly leftovers?: boolean;
readonly liveOwner?: boolean;
} = {},
) =>
Effect.gen(function* () {
const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
Expand Down Expand Up @@ -102,7 +110,12 @@ const withFakeSystemd = <A, E>(
}),
});
const fileSystem = yield* FileSystem.FileSystem;
const { stateDir } = yield* ServerConfig.ServerConfig;
if (leftovers) {
units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
}
const scope = yield* make.pipe(
Effect.provideService(ProviderProcesses.ProviderProcesses, { hasOtherLiveOwner: liveOwner }),
Effect.provideService(ProcessRunner.ProcessRunner, runner),
Effect.provideService(HostProcess.Platform, "linux"),
Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
Expand All @@ -114,7 +127,6 @@ const withFakeSystemd = <A, E>(
fileSystem.writeFileString(path.replace("/sys/fs/cgroup", cgroupRoot), data, options),
}),
);
const { stateDir } = yield* ServerConfig.ServerConfig;
return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
);
Expand Down Expand Up @@ -308,27 +320,34 @@ describe("AgentScope service", () => {
),
);

it.effect("stops agents a killed server left before the first launch", () =>
withFakeSystemd(({ scope, units, calls, stateDir }) =>
Effect.gen(function* () {
units.set(ownedAgentSlice(stateDir), { activeState: "active", result: "success" });
const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
const stops = calls.filter(([, verb]) => verb === "stop");
expect(stops).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
expect(agent.args).toContain("--property=TimeoutStopSec=10s");
const terminal = yield* scope.wrap({
command: "agent",
args: [],
name: "terminal",
survivesRestart: true,
});
expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
expect(calls.filter(([, verb]) => verb === "stop")).toHaveLength(1);
}),
it.effect("stops agents a killed server left before startup completes", () =>
withFakeSystemd(
({ scope, calls, stateDir }) =>
Effect.gen(function* () {
expect(stopsOf(calls)).toEqual([["--user", "stop", ownedAgentSlice(stateDir)]]);
const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
expect(sliceOf(agent)).toBe(ownedAgentSlice(stateDir));
expect(agent.args).toContain("--property=TimeoutStopSec=10s");
const terminal = yield* scope.wrap({
command: "agent",
args: [],
name: "terminal",
survivesRestart: true,
});
expect(sliceOf(terminal)).toBe("app-t3code-agents.slice");
expect(stopsOf(calls)).toHaveLength(1);
}),
{ leftovers: true },
),
);

it.effect("leaves the slice to another live server sharing this home", () =>
withFakeSystemd(({ calls }) => Effect.sync(() => expect(stopsOf(calls)).toEqual([])), {
leftovers: true,
liveOwner: true,
}),
);

it.effect("stops leftover processes only in an active agent scope", () =>
withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
Effect.gen(function* () {
Expand Down
12 changes: 11 additions & 1 deletion apps/server/src/process/agentScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import * as Path from "effect/Path";

import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ProviderProcesses from "./providerProcesses.ts";

const AGENT_SLICE = "app-t3code-agents.slice";
// Owns every agent slice and competes with the server's unit or scope under app.slice.
Expand Down Expand Up @@ -106,6 +107,7 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const hostEnvironment = yield* HostProcess.Environment;
const { stateDir } = yield* ServerConfig.ServerConfig;
const { hasOtherLiveOwner } = yield* ProviderProcesses.ProviderProcesses;
const ownedSlice = ownedAgentSlice(stateDir);
const layerScope = yield* Effect.scope;

Expand All @@ -130,6 +132,7 @@ export const make = Effect.gen(function* () {
const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
systemctl: string,
) {
if (hasOtherLiveOwner) return;
const shown = yield* run(systemctl, [
"--user",
"show",
Expand Down Expand Up @@ -215,6 +218,10 @@ export const make = Effect.gen(function* () {
}),
);

// Layer acquisition is the startup barrier: recovery must not terminalize or
// continue old runs while a previous server's providers can still execute.
yield* systemd;

// `shared` scopes serve other threads too: tracked only for OOM diagnosis on old systemd.
const scopeByThread = new Map<string, { unit: string; oomKilled: boolean; shared: boolean }>();

Expand Down Expand Up @@ -427,4 +434,7 @@ export const make = Effect.gen(function* () {
} satisfies AgentScopeShape;
});

export const layer = Layer.effect(AgentScope, make).pipe(Layer.provide(ProcessRunner.layer));
export const layer = Layer.effect(AgentScope, make).pipe(
Layer.provide(ProcessRunner.layer),
Layer.provideMerge(ProviderProcesses.layer),
);
Loading
Loading