Registry Mirror
Skip to content

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import {
8484
mcpAppToolResourceUri,
8585
} from "@t3tools/shared/mcpApp";
8686
import { AgentScope } from "@t3tools/shared/AgentScope";
87+
import * as LaunchedChild from "../../process/launchedChild.ts";
8788
import * as ProviderProcesses from "../../process/providerProcesses.ts";
8889
import * as SpawnWorker from "../../process/SpawnWorker.ts";
8990
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -441,10 +442,11 @@ export function spawnClaudeProcessGroup(
441442
onStderr: (text: string) => void = () => {},
442443
onStderrClose: () => void = () => {},
443444
register?: (pid: number) => () => void,
444-
): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
445+
spawn: LaunchedChild.Spawn = LaunchedChild.spawnNative,
446+
): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid" | "once"> {
445447
// Relative to the server's cwd, as a native cwd is; the `./` keeps CDPATH out of it.
446448
const cwd = options.cwd ?? ".";
447-
const child = NodeChildProcess.spawn(
449+
const child = spawn(
448450
"/bin/sh",
449451
[
450452
"-c",
@@ -474,19 +476,29 @@ export function spawnClaudeProcessGroup(
474476
onExit?.();
475477
});
476478
const gate = child.stdio[4];
477-
if (child.pid !== undefined && gate !== null && gate !== undefined && "end" in gate) {
479+
const release = (pid: number) => {
480+
if (gate === null || gate === undefined || !("end" in gate)) return;
478481
try {
479-
forget = register?.(child.pid);
482+
forget = register?.(pid);
480483
gate.on("error", () => child.kill("SIGKILL"));
481484
gate.end("ready\n");
482485
} catch (cause) {
483486
child.kill("SIGKILL");
484487
gate.destroy();
485488
throw cause;
486489
}
490+
};
491+
if (child.pid !== undefined) release(child.pid);
492+
else {
493+
// A launched child has its pid once it has started; until then the gate holds it.
494+
child.once("spawn", () => {
495+
try {
496+
release(child.pid ?? 0);
497+
} catch {}
498+
});
487499
}
488500
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
489-
return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid">;
501+
return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid" | "once">;
490502
}
491503

492504
interface ClaudeProcessRow {
@@ -1668,6 +1680,8 @@ export const layerQueryRunner: Layer.Layer<
16681680
const providerProcesses = yield* ProviderProcesses.ProviderProcesses;
16691681
const platform = yield* HostProcess.Platform;
16701682
const runFork = Effect.runForkWith(yield* Effect.context<never>());
1683+
// On Linux the server's spawner is the process launcher, so the CLI never forks the server.
1684+
const launchChild = platform === "linux" ? LaunchedChild.makeLaunch(spawner) : undefined;
16711685
const hostEnvironment = yield* HostProcess.Environment;
16721686
const portDiscovery = yield* PortScanner.PortDiscovery;
16731687
const processRunner = yield* ProcessRunner.make();
@@ -1845,11 +1859,16 @@ export const layerQueryRunner: Layer.Layer<
18451859
appendStderr,
18461860
stderrDone,
18471861
providerProcesses.register,
1862+
launchChild,
18481863
);
1849-
if (unit === undefined && child.pid !== undefined) {
1850-
const tracker = trackDescendants(child.pid);
1851-
child.once("exit", () => runFork(tracker.stop));
1852-
descendants = tracker;
1864+
if (unit === undefined) {
1865+
const track = (pid: number) => {
1866+
const tracker = trackDescendants(pid);
1867+
child.once("exit", () => runFork(tracker.stop));
1868+
descendants = tracker;
1869+
};
1870+
if (child.pid !== undefined) track(child.pid);
1871+
else child.once("spawn", () => child.pid !== undefined && track(child.pid));
18531872
}
18541873
return child;
18551874
}

‎apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEven
2828
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
2929
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
3030
import * as PortScanner from "../../preview/PortScanner.ts";
31+
import * as LaunchedChild from "../../process/launchedChild.ts";
3132
import {
3233
ClaudeAgentSdkQueryRunner,
3334
type ClaudeAgentSdkQueryOpenInput,
@@ -1210,13 +1211,15 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
12101211
NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid));
12111212
return () => Deferred.doneUnsafe(forgotten, Effect.void);
12121213
},
1214+
// Linux servers launch it, so its pid and record come only once it has started.
1215+
LaunchedChild.makeLaunch(yield* ChildProcessSpawner.ChildProcessSpawner),
12131216
);
12141217
const seen = yield* Effect.promise(() =>
12151218
NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"),
12161219
);
12171220
assert.equal(seen, `${registered} ${registered}`);
12181221
yield* Deferred.await(forgotten);
1219-
}),
1222+
}).pipe(Effect.provide(NodeServices.layer)),
12201223
);
12211224

12221225
it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - the Claude SDK's spawn hook takes a ChildProcess-shaped object.
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeEvents from "node:events";
4+
import * as NodeStream from "node:stream";
5+
6+
import * as EffectNodeStream from "@effect/platform-node/NodeStream";
7+
import * as Effect from "effect/Effect";
8+
import * as Fiber from "effect/Fiber";
9+
import * as Stream from "effect/Stream";
10+
import * as ChildProcess from "effect/process/ChildProcess";
11+
import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12+
13+
export interface LaunchOptions {
14+
readonly cwd?: string | undefined;
15+
readonly env?: NodeJS.ProcessEnv | undefined;
16+
readonly signal?: AbortSignal | undefined;
17+
readonly detached?: boolean | undefined;
18+
/** One entry per fd; piped fds past 2 are written by the caller. */
19+
readonly stdio: ReadonlyArray<"pipe" | "ignore">;
20+
}
21+
22+
export type Spawn = (
23+
command: string,
24+
args: ReadonlyArray<string>,
25+
options: LaunchOptions,
26+
) => NodeChildProcess.ChildProcess | LaunchedChild;
27+
28+
export const spawnNative: Spawn = (command, args, options) =>
29+
NodeChildProcess.spawn(command, args, { ...options, stdio: [...options.stdio] });
30+
31+
// Effect reports a signal exit only as this message.
32+
const SIGNAL_EXIT = /receipt of signal: '(SIG[A-Z0-9]+)'/;
33+
34+
/** A ChildProcess whose streams exist at once and connect when the command starts. */
35+
class LaunchedChild extends NodeEvents.EventEmitter {
36+
pid: number | undefined;
37+
exitCode: number | null = null;
38+
signalCode: NodeJS.Signals | null = null;
39+
killed = false;
40+
readonly stdio: ReadonlyArray<NodeStream.PassThrough | null>;
41+
pendingSignal: NodeJS.Signals | undefined;
42+
43+
constructor(stdio: LaunchOptions["stdio"]) {
44+
super();
45+
this.stdio = stdio.map((mode) => (mode === "pipe" ? new NodeStream.PassThrough() : null));
46+
}
47+
48+
get stdin() {
49+
return this.stdio[0] ?? null;
50+
}
51+
52+
get stdout() {
53+
return this.stdio[1] ?? null;
54+
}
55+
56+
get stderr() {
57+
return this.stdio[2] ?? null;
58+
}
59+
60+
kill(signal: NodeJS.Signals = "SIGTERM"): boolean {
61+
if (this.exitCode !== null || this.signalCode !== null) return false;
62+
this.killed = true;
63+
if (this.pid === undefined) {
64+
this.pendingSignal = signal;
65+
return true;
66+
}
67+
try {
68+
process.kill(this.pid, signal);
69+
return true;
70+
} catch {
71+
return false;
72+
}
73+
}
74+
}
75+
76+
// Output is always read, as a ChildProcess pipe would be; a destroyed reader discards it.
77+
const write = (target: NodeStream.PassThrough, chunk: Uint8Array) =>
78+
Effect.callback<void>((resume) => {
79+
if (target.destroyed || target.write(chunk)) return resume(Effect.void);
80+
const done = () => {
81+
target.off("drain", done).off("close", done);
82+
resume(Effect.void);
83+
};
84+
target.on("drain", done).on("close", done);
85+
});
86+
87+
/**
88+
* A `child_process.spawn` for callers that must hold the child at once, such as the Claude
89+
* SDK's spawn hook, that starts the command through `spawner`. On Linux the server's spawner is
90+
* the process launcher, so the server is never forked. `pid` is set when "spawn" fires.
91+
*/
92+
export const makeLaunch =
93+
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]): Spawn =>
94+
(command, args, options) => {
95+
const child = new LaunchedChild(options.stdio);
96+
const { signal } = options;
97+
const abort = () => child.kill();
98+
if (signal?.aborted) child.kill();
99+
else signal?.addEventListener("abort", abort, { once: true });
100+
const inputs = child.stdio.flatMap((stream, fd) =>
101+
stream !== null && fd !== 1 && fd !== 2 ? [[fd, stream] as const] : [],
102+
);
103+
const launch = Effect.gen(function* () {
104+
const handle = yield* spawner.spawn(
105+
ChildProcess.make(command, args, {
106+
cwd: options.cwd,
107+
env: options.env,
108+
detached: options.detached ?? false,
109+
stdin: options.stdio[0] ?? "ignore",
110+
stdout: options.stdio[1] ?? "ignore",
111+
stderr: options.stdio[2] ?? "ignore",
112+
additionalFds: Object.fromEntries(
113+
inputs.filter(([fd]) => fd > 2).map(([fd]) => [`fd${fd}`, { type: "input" as const }]),
114+
),
115+
}),
116+
);
117+
for (const [fd, stream] of inputs) {
118+
// Like a closed pipe, a failed input discards what is written after it.
119+
yield* Stream.run(
120+
EffectNodeStream.fromReadable({ evaluate: () => stream, onError: () => undefined }),
121+
fd === 0 ? handle.stdin : handle.getInputFd(fd),
122+
).pipe(
123+
Effect.catch(() => Effect.sync(() => stream.resume())),
124+
Effect.forkScoped,
125+
);
126+
}
127+
const outputs = yield* Effect.forEach(
128+
[
129+
[handle.stdout, child.stdout],
130+
[handle.stderr, child.stderr],
131+
] as const,
132+
([output, target]) =>
133+
target === null
134+
? Effect.void
135+
: Stream.runForEach(output, (chunk) => write(target, chunk)).pipe(
136+
Effect.ignore,
137+
Effect.ensuring(Effect.sync(() => target.end())),
138+
),
139+
{ concurrency: "unbounded", discard: true },
140+
).pipe(Effect.forkScoped);
141+
child.pid = handle.pid;
142+
child.emit("spawn");
143+
if (child.pendingSignal !== undefined) child.kill(child.pendingSignal);
144+
const [code, exitSignal] = yield* handle.exitCode.pipe(
145+
Effect.map((code): [number | null, NodeJS.Signals | null] => [code, null]),
146+
Effect.catch((error) =>
147+
Effect.succeed<[number | null, NodeJS.Signals | null]>([
148+
null,
149+
(SIGNAL_EXIT.exec(String((error.cause as Error | undefined)?.message))?.[1] ??
150+
"SIGKILL") as NodeJS.Signals,
151+
]),
152+
),
153+
);
154+
signal?.removeEventListener("abort", abort);
155+
child.exitCode = code;
156+
child.signalCode = exitSignal;
157+
// Node destroys a child's stdin on exit; ending each input closes its pipe.
158+
for (const [, stream] of inputs) stream.end();
159+
child.emit("exit", code, exitSignal);
160+
yield* Fiber.await(outputs);
161+
}).pipe(
162+
Effect.scoped,
163+
Effect.catch((error) =>
164+
Effect.sync(() => {
165+
signal?.removeEventListener("abort", abort);
166+
for (const stream of child.stdio) stream?.end();
167+
child.emit("error", error.cause instanceof Error ? error.cause : error);
168+
}),
169+
),
170+
);
171+
Effect.runFork(launch);
172+
return child;
173+
};

‎apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,19 @@ import { assert, it } from "@effect/vitest";
77
import * as HostProcess from "@t3tools/shared/HostProcess";
88
import * as Effect from "effect/Effect";
99
import * as FileSystem from "effect/FileSystem";
10+
import * as Layer from "effect/Layer";
11+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1012
import * as Schema from "effect/Schema";
1113
import * as TestClock from "effect/testing/TestClock";
1214

1315
import {
1416
buildClaudeCapabilitiesProbeQueryOptions,
1517
probeClaudeCapabilities,
1618
probeClaudeWorkspaceSnapshot,
17-
spawnClaudeProbeThroughEnv,
19+
spawnClaudeProbeThroughLauncher,
1820
} from "./ClaudeProvider.ts";
21+
import * as LaunchedChild from "../process/launchedChild.ts";
22+
import * as NonBlockingSpawner from "../process/NonBlockingSpawner.ts";
1923

2024
vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
2125

@@ -48,18 +52,21 @@ it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
4852
const workspace = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
4953
yield* fileSystem.writeFileString(`${workspace}/claude`, '#!/bin/bash\nt3_launch "$@"\n');
5054
yield* fileSystem.chmod(`${workspace}/claude`, 0o755);
51-
const child = spawnClaudeProbeThroughEnv({
55+
const launch = LaunchedChild.makeLaunch(yield* ChildProcessSpawner.ChildProcessSpawner);
56+
const child = spawnClaudeProbeThroughLauncher(launch)({
5257
command: "claude",
5358
args: ["--probe"],
5459
cwd: workspace,
5560
env: { PATH: `.:${hostPath}`, "BASH_FUNC_t3_launch%%": '() { echo "$PWD $@"; }' },
5661
// @effect-diagnostics-next-line abortControllerInEffect:off - The launcher exits on its own.
5762
signal: new AbortController().signal,
5863
});
59-
assert.deepEqual(child.spawnargs.slice(0, 3), ["/usr/bin/env", "-C", workspace]);
6064
const output = yield* Effect.promise(() => child.stdout.setEncoding("utf8").toArray());
6165
assert.equal(output.join(""), `${workspace} --probe\n`);
62-
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
66+
}).pipe(
67+
Effect.scoped,
68+
Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer))),
69+
),
6370
);
6471

6572
it.effect("reports a deleted worktree's scan as finished, not pending", () =>

0 commit comments

Comments
 (0)