@devries-cameron20 / t3code Mirror · read-only / commits / 1aa7179670
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 18:15 UTC

fix(server): agent-browser and Chrome no longer outlive the agent that started them (#21299)

Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Theo Browne <me@theo.li> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Joseph Vidal committed Oct 23, 2026 at 06:22 UTC 1aa71796709b6dd2c1f1f6ee111b819b69ec9d35
16 files changed +642 -37
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+15 -3
@@ -323,14 +323,18 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [
323 * When the CLI exits it stops the MCP servers it started, but not their children: a plugin's
324 * `bun run start` wrapper dies and its `bun server.ts` keeps running, writing to a pipe nobody
325 * reads (#3089). Those stay in the CLI's group, so the rest of the group gets SIGKILL once the
326 - * CLI exits for any reason.
326 + * CLI exits for any reason. `onExit` then stops the CLI's agent scope, for daemons a tool
327 + * detached from the group with setsid.
328 *
329 * That cleanup needs this server alive, and the CLI finishes its turn after its pipes close. A
330 * server that crashes or is killed would leave the CLI working next to the session it resumes
331 * (#23370), so a watcher in the group reads a pipe only this server holds and stops the group at
332 * its end-of-file.
333 */
333 -export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpawnedProcess {
334 +export function spawnClaudeProcessGroup(
335 + options: ClaudeSpawnOptions,
336 + onExit?: () => void,
337 +): ClaudeSpawnedProcess {
338 const child = NodeChildProcess.spawn(
339 "/bin/sh",
340 ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
@@ -346,6 +350,7 @@ export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpaw
350 try {
351 signalProcessGroup(child.pid ?? 0, "SIGKILL");
352 } catch {}
353 + onExit?.();
354 });
355 // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
356 return child as ClaudeSpawnedProcess;
@@ -892,6 +897,7 @@ export const layerQueryRunner: Layer.Layer<
897 const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
898 const agentScope = yield* AgentScope;
899 const platform = yield* HostProcess.Platform;
900 + const runFork = Effect.runForkWith(yield* Effect.context<never>());
901
902 return ClaudeAgentSdkQueryRunner.of({
903 allocateSessionId: crypto
@@ -942,10 +948,16 @@ export const layerQueryRunner: Layer.Layer<
948 pathToClaudeCodeExecutable: launch.command,
949 executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
950 };
951 + const unit = launch?.unit;
952 + const stopScope =
953 + unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
954 // Windows has no process groups, so there the SDK spawns the CLI itself.
955 const spawnClaudeCodeProcess =
956 options.spawnClaudeCodeProcess ??
948 - (platform === "win32" ? undefined : spawnClaudeProcessGroup);
957 + (platform === "win32"
958 + ? undefined
959 + : (spawnOptions: ClaudeSpawnOptions) =>
960 + spawnClaudeProcessGroup(spawnOptions, stopScope));
961 const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
962 Effect.try({
963 try: () =>
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+19 -2
@@ -8,12 +8,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { assert, describe, it } from "@effect/vitest";
9 import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
10 import * as Effect from "effect/Effect";
11 +import * as Deferred from "effect/Deferred";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
14 import * as Path from "effect/Path";
15 import { vi } from "vite-plus/test";
16
17 import * as HostProcess from "@t3tools/shared/HostProcess";
18 +import { AgentScope } from "@t3tools/shared/AgentScope";
19 import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
20 import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
21 import {
@@ -162,11 +164,26 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
164 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
165 alive.resume();
166
165 - const session = yield* openFakeCli(cli);
167 + const stopped = yield* Deferred.make<string>();
168 + const session = yield* openFakeCli(cli).pipe(
169 + Effect.provide(
170 + realQueryRunner.pipe(
171 + Layer.provide(
172 + Layer.succeed(AgentScope, {
173 + ...AgentScope.defaultValue(),
174 + wrap: ({ command, args }) =>
175 + Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
176 + stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
177 + }),
178 + ),
179 + ),
180 + ),
181 + );
182 yield* Effect.promise(() => leftoverStarted);
183 yield* session.close;
184 yield* Effect.promise(() => leftoverStopped);
169 - }).pipe(Effect.provide(realQueryRunner)),
185 + assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
186 + }),
187 );
188
189 // The CLI keeps running its turn after its pipes close, so a server that
apps/server/src/process/agentScope.test.ts
+144 -5
@@ -8,7 +8,9 @@ import { assert, describe, expect, it } from "@effect/vitest";
8 import { AgentScope } from "@t3tools/shared/AgentScope";
9 import * as HostProcess from "@t3tools/shared/HostProcess";
10 import * as Effect from "effect/Effect";
11 +import * as FileSystem from "effect/FileSystem";
12 import * as Layer from "effect/Layer";
13 +import * as Logger from "effect/Logger";
14 import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16 import * as ServerConfig from "../config.ts";
@@ -35,21 +37,33 @@ describe("classifyScope", () => {
37 });
38 });
39
40 +interface FakeUnit {
41 + activeState: string;
42 + result: string;
43 + controlGroup?: string;
44 +}
45 +
46 const withFakeSystemd = <A, E>(
47 body: (input: {
48 readonly scope: Effect.Success<typeof make>;
41 - readonly units: Map<string, { activeState: string; result: string }>;
49 + readonly units: Map<string, FakeUnit>;
50 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
51 readonly stateDir: string;
52 + readonly cgroupRoot: string;
53 }) => Effect.Effect<A, E>,
45 - { oomPolicy = true }: { readonly oomPolicy?: boolean } = {},
54 + // A user manager older than systemd 253 rejects OOMPolicy on scopes.
55 + {
56 + oomPolicy = true,
57 + stopFails = false,
58 + }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {},
59 ) =>
60 Effect.gen(function* () {
61 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
62 for (const name of ["systemd-run", "systemctl", "agent"]) {
63 NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
64 }
52 - const units = new Map<string, { activeState: string; result: string }>();
65 + const cgroupRoot = NodePath.join(bin, "cgroup");
66 + const units = new Map<string, FakeUnit>();
67 const calls: Array<ReadonlyArray<string>> = [];
68 const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
69 stdout,
@@ -69,23 +83,37 @@ const withFakeSystemd = <A, E>(
83 return output("", 1);
84 }
85 const [, verb, unit = ""] = args;
86 + if (stopFails && verb === "stop") {
87 + return {
88 + ...output(""),
89 + stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`,
90 + code: ChildProcessSpawner.ExitCode(5),
91 + };
92 + }
93 if (verb === "reset-failed") units.delete(unit);
94 if (verb !== "show") return output("");
95 const state = units.get(unit);
96 return output(
97 state === undefined
98 ? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
78 - : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`,
99 + : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` +
100 + `ControlGroup=${state.controlGroup ?? ""}\n`,
101 );
102 }),
103 });
104 + const fileSystem = yield* FileSystem.FileSystem;
105 const scope = yield* make.pipe(
106 Effect.provideService(ProcessRunner.ProcessRunner, runner),
107 Effect.provideService(HostProcess.Platform, "linux"),
108 Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
109 + Effect.provideService(FileSystem.FileSystem, {
110 + ...fileSystem,
111 + readFileString: (path, encoding) =>
112 + fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),
113 + }),
114 );
115 const { stateDir } = yield* ServerConfig.ServerConfig;
88 - return yield* body({ scope, units, calls, stateDir }).pipe(
116 + return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
117 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
118 );
119 }).pipe(
@@ -103,6 +131,31 @@ const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
131 const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
132 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
133
134 +/** An active scope as systemd and the kernel report it, with the agent itself gone. */
135 +const exitedAgent = (
136 + units: Map<string, FakeUnit>,
137 + cgroupRoot: string,
138 + unit: string,
139 + { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
140 +) => {
141 + const controlGroup = `/${unit}`;
142 + NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
143 + NodeFS.writeFileSync(
144 + NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
145 + `populated ${populated ? 1 : 0}\nfrozen 0\n`,
146 + );
147 + // An undefined count leaves memory.events unreadable.
148 + if (oomKills !== undefined) {
149 + NodeFS.writeFileSync(
150 + NodePath.join(cgroupRoot, controlGroup, "memory.events"),
151 + `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
152 + );
153 + }
154 + units.set(unit, { activeState: "active", result: "success", controlGroup });
155 +};
156 +
157 +const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
158 + calls.filter(([, verb]) => verb === "stop");
159 const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
160 makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
161 Effect.provideService(AgentScope, scope),
@@ -194,4 +247,90 @@ describe("AgentScope service", () => {
247 }),
248 ),
249 );
250 +
251 + it.effect("stops leftover processes only in an active agent scope", () =>
252 + withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
253 + Effect.gen(function* () {
254 + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
255 + const unit = unitOf(agent);
256 + expect(agent.unit).toBe(unit);
257 +
258 + yield* scope.stop("session-2.scope");
259 + expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
260 + yield* scope.stop(unit);
261 + exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
262 + yield* scope.stop(unit);
263 + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
264 + units.get(unit)!.activeState = "deactivating";
265 + yield* scope.stop(unit);
266 + expect(stopsOf(calls)).toEqual([]);
267 +
268 + units.get(unit)!.activeState = "active";
269 + yield* scope.stop(unit);
270 + expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
271 + expect(yield* scope.oomKilled("a")).toBe(false);
272 + }),
273 + ),
274 + );
275 +
276 + it.effect.each([true, false])(
277 + "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
278 + (oomPolicy) =>
279 + withFakeSystemd(
280 + ({ scope, units, calls, cgroupRoot }) =>
281 + Effect.gen(function* () {
282 + const agent = yield* scope.wrap({
283 + command: "agent",
284 + args: [],
285 + name: "t",
286 + threadId: "a",
287 + });
288 + const unit = unitOf(agent);
289 + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
290 + yield* scope.stop(unit);
291 + expect(stopsOf(calls)).toEqual(
292 + oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
293 + );
294 +
295 + // The kernel records the kill before systemd records the OOM result.
296 + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
297 + yield* scope.stop(unit);
298 + expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
299 +
300 + if (oomPolicy) {
301 + units.set(unit, { activeState: "failed", result: "oom-kill" });
302 + expect(yield* scope.oomKilled("a")).toBe(true);
303 + units.delete(unit);
304 + expect(yield* scope.oomKilled("a")).toBe(true);
305 + }
306 + }),
307 + { oomPolicy },
308 + ),
309 + );
310 +
311 + it.effect("reports failed daemon cleanup without failing session teardown", () => {
312 + const warnings: Array<unknown> = [];
313 + const logger = Logger.make(({ message }) => {
314 + warnings.push(message);
315 + });
316 + return withFakeSystemd(
317 + ({ scope, units, cgroupRoot }) =>
318 + Effect.gen(function* () {
319 + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
320 + exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
321 + yield* scope.stop(unitOf(agent));
322 + expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
323 + }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
324 + { stopFails: true },
325 + );
326 + });
327 +
328 + it.effect("leaves a quiet slice alone", () =>
329 + withFakeSystemd(({ scope, calls }) =>
330 + Effect.gen(function* () {
331 + yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
332 + expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
333 + }),
334 + ),
335 + );
336 });
apps/server/src/process/agentScope.ts
+35 -4
@@ -44,7 +44,7 @@ export interface ScopeState {
44 readonly loadState: string;
45 readonly activeState: string;
46 readonly result: string;
47 - readonly oomKills: number;
47 + readonly oomKills: number | undefined;
48 readonly populated: boolean | undefined;
49 }
50
@@ -62,7 +62,11 @@ export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "runni
62 ) {
63 return "gone";
64 }
65 - if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) {
65 + if (
66 + state.activeState === "deactivating" ||
67 + (state.oomKills ?? 0) > 0 ||
68 + state.populated === false
69 + ) {
70 return "stopping";
71 }
72 return "running";
@@ -220,7 +224,7 @@ export const make = Effect.gen(function* () {
224 loadState: values.get("LoadState") ?? "",
225 activeState: values.get("ActiveState") ?? "",
226 result: values.get("Result") ?? "",
223 - oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
227 + oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
228 populated: populated === undefined ? undefined : populated === 1,
229 } satisfies ScopeState;
230 });
@@ -300,6 +304,32 @@ export const make = Effect.gen(function* () {
304 },
305 );
306
307 + const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
308 + if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
309 + const scope = yield* systemd;
310 + if (scope === undefined) return;
311 + const state = yield* readScope(scope.systemctl, unit);
312 + if (
313 + state === undefined ||
314 + state.loadState !== "loaded" ||
315 + state.activeState !== "active" ||
316 + state.result === "oom-kill" ||
317 + state.populated === false
318 + )
319 + return;
320 + // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
321 + // record the result before a manual stop can overwrite it; an unreadable
322 + // counter cannot rule out that race. Older managers need us to stop it.
323 + if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
324 + const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
325 + if (stopped._tag === "None" || stopped.value.code !== 0) {
326 + yield* Effect.logWarning("Could not stop an exited agent's scope", {
327 + unit,
328 + exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
329 + });
330 + }
331 + });
332 +
333 const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
334 if (!scopeByThread.has(threadId)) return;
335 const scope = yield* systemd;
@@ -341,9 +371,10 @@ export const make = Effect.gen(function* () {
371 ...(owned ? [] : ["--collect"]),
372 ],
373 };
344 - return agentScopeCommand({ command: resolved, args, scope: systemdScope });
374 + return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit };
375 }),
376 oomKilled,
377 + stop,
378 clear,
379 } satisfies AgentScopeShape;
380 });
apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+31 -1
@@ -14,9 +14,11 @@ import * as Fiber from "effect/Fiber";
14 import * as Scope from "effect/Scope";
15 import * as Result from "effect/Result";
16 import * as Stream from "effect/Stream";
17 +import { ChildProcessSpawner } from "effect/process";
18 import { describe, expect } from "vite-plus/test";
19
20 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
21 +import { AgentScope } from "@t3tools/shared/AgentScope";
22 import * as EffectAcpErrors from "effect-acp/errors";
23
24 const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -193,10 +195,38 @@ describe("AcpSessionRuntime", () => {
195
196 it.effect("reports an idle child exit and rejects later prompts", () =>
197 Effect.gen(function* () {
196 - const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions);
198 + const stopped = yield* Deferred.make<string>();
199 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
200 + const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions).pipe(
201 + Effect.provideService(
202 + ChildProcessSpawner.ChildProcessSpawner,
203 + ChildProcessSpawner.make((command) =>
204 + spawner.spawn(command).pipe(
205 + Effect.map((child) =>
206 + ChildProcessSpawner.makeHandle({
207 + ...child,
208 + // Model an inherited pipe held open until detached work is stopped.
209 + stdout: Stream.concat(
210 + child.stdout,
211 + Stream.fromEffect(Deferred.await(stopped)).pipe(Stream.drain),
212 + ),
213 + }),
214 + ),
215 + ),
216 + ),
217 + ),
218 + Effect.provideService(AgentScope, {
219 + ...AgentScope.defaultValue(),
220 + wrap: ({ command, args }) =>
221 + Effect.succeed({ command, args, unit: "t3code-acp-test.scope" }),
222 + stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
223 + }),
224 + );
225 yield* runtime.start();
226 + expect(yield* Deferred.isDone(stopped)).toBe(false);
227 yield* runtime.notify("_test/exit", {});
228 const events = yield* runtime.getEvents().pipe(Stream.take(1), Stream.runCollect);
229 + expect(yield* Deferred.await(stopped)).toBe("t3code-acp-test.scope");
230 const event = events[0];
231 expect(event).toMatchObject({ _tag: "ConnectionTerminated", error: { code: 19 } });
232 if (event?._tag !== "ConnectionTerminated") return;
packages/provider-acp/src/server/AcpSessionRuntime.ts
+25 -12
@@ -1435,19 +1435,24 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1435 cause: new Error("Contained ACP command was not found on PATH"),
1436 });
1437 });
1438 - const scopedSpawnCommand =
1438 + const agentScope = yield* AgentScope;
1439 + const scopedLaunch =
1440 linuxCgroupLease !== undefined || spawnCommand.shell
1440 - ? spawnCommand
1441 - : {
1442 - ...(yield* (yield* AgentScope).wrap({
1443 - command: spawnCommand.command,
1444 - args: spawnCommand.args,
1445 - name: "acp",
1446 - threadId: yield* AgentScopeThreadId,
1447 - env: { ...process.env, ...options.spawn.env },
1448 - })),
1449 - shell: false,
1450 - };
1441 + ? undefined
1442 + : yield* agentScope.wrap({
1443 + command: spawnCommand.command,
1444 + args: spawnCommand.args,
1445 + name: "acp",
1446 + threadId: yield* AgentScopeThreadId,
1447 + env: { ...process.env, ...options.spawn.env },
1448 + });
1449 + const scopedSpawnCommand =
1450 + scopedLaunch === undefined ? spawnCommand : { ...scopedLaunch, shell: false };
1451 + // Finalizers run in reverse order: reap detached work after terminating the agent.
1452 + const scopeUnit = scopedLaunch?.unit;
1453 + const stopScope =
1454 + scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
1455 + yield* Scope.addFinalizer(runtimeScope, stopScope);
1456 const containedSpawnCommand =
1457 linuxCgroupLease === undefined
1458 ? scopedSpawnCommand
@@ -1486,6 +1491,14 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1491 ),
1492 );
1493
1494 + // Detached children can keep stdout open, delaying protocol termination.
1495 + if (scopeUnit !== undefined) {
1496 + yield* child.exitCode.pipe(
1497 + Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
1498 + Effect.forkIn(runtimeScope),
1499 + );
1500 + }
1501 +
1502 const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();
1503 const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();
1504 const posixOwnershipChildQueues = new Map<number, Array<number>>();
packages/provider-muse/src/server/adapter.test.ts
+137 -2
@@ -19,6 +19,7 @@ import {
19 type OrchestrationV2ProviderThread,
20 } from "@t3tools/contracts";
21 import * as HostProcess from "@t3tools/shared/HostProcess";
22 +import { AgentScope } from "@t3tools/shared/AgentScope";
23 import { MuseSettings } from "../settings.ts";
24 import * as DateTime from "effect/DateTime";
25 import * as Deferred from "effect/Deferred";
@@ -30,11 +31,12 @@ import * as Layer from "effect/Layer";
31 import * as Queue from "effect/Queue";
32 import * as Schema from "effect/Schema";
33 import * as Stream from "effect/Stream";
34 +import * as TestClock from "effect/testing/TestClock";
35
36 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
37 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
38 import type { MuseItem, MuseSubscriptionUsage } from "./protocol.ts";
37 -import type { MuseSdkHost } from "./sdk.ts";
39 +import type { MuseSdkHost, MuseSdkHostOptions } from "./sdk.ts";
40 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
41 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
42 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -87,8 +89,10 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
89 let notify: Parameters<MuseSdkHost["connection"]["onNotification"]>[0] = () => {};
90 let sequence = 0;
91 let sessionId = "";
92 + const closing = pendingPromise<void>();
93 let closeCount = 0;
94 let closeGate: Promise<void> | undefined;
95 + let onProcessExit: MuseSdkHostOptions["onProcessExit"];
96 let history: MuseItem[] = [];
97 const responses = new Map<
98 string,
@@ -143,6 +147,7 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
147 exited: exited.promise,
148 close: async () => {
149 closeCount += 1;
150 + closing.resolve();
151 await closeGate;
152 closed.resolve();
153 exited.resolve({ code: 0, signal: null });
@@ -152,6 +157,11 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
157 host,
158 calls,
159 closeCount: () => closeCount,
160 + closing: closing.promise,
161 + observeProcessExit: (callback: MuseSdkHostOptions["onProcessExit"]) => {
162 + onProcessExit = callback;
163 + },
164 + exitProcess: () => Effect.sync(() => onProcessExit?.({ code: 1, signal: null })),
165 holdClose: (gate: Promise<void>) => {
166 closeGate = gate;
167 },
@@ -204,7 +214,11 @@ const makeHarness = Effect.fnUntraced(function* (
214 instanceId,
215 settings: museSettings,
216 environment: { PATH: "/fake/bin" },
207 - createHost: async () => (hostCount++ === 0 ? fake.host : (replacement ?? fake).host),
217 + createHost: async (options) => {
218 + const selected = hostCount++ === 0 ? fake : (replacement ?? fake);
219 + selected.observeProcessExit(options.onProcessExit);
220 + return selected.host;
221 + },
222 ...overrides,
223 });
224 const runtime = yield* adapter.openSession({
@@ -751,6 +765,57 @@ describe("MuseAdapterV2", () => {
765 }).pipe(Effect.scoped, Effect.provide(testLayer)),
766 );
767
768 + it.effect.each(["normal", "inherited pipe"] as const)(
769 + "closes its SDK host exactly once on session teardown with %s shutdown",
770 + (shutdown) =>
771 + Effect.gen(function* () {
772 + const fake = yield* makeFakeMuse();
773 + const pipeClosed = pendingPromise<void>();
774 + if (shutdown === "inherited pipe") fake.holdClose(pipeClosed.promise);
775 + let hostExited = false;
776 + void fake.host.exited.then(() => {
777 + hostExited = true;
778 + });
779 + const stopped: Array<{ unit: string; hostExited: boolean }> = [];
780 + const release = makeHarness(fake).pipe(
781 + Effect.scoped,
782 + Effect.provideService(AgentScope, {
783 + ...AgentScope.defaultValue(),
784 + wrap: ({ command, args }) =>
785 + Effect.succeed({ command, args, unit: "t3code-muse-test.scope" }),
786 + stop: (unit) =>
787 + Effect.sync(() => {
788 + stopped.push({ unit, hostExited });
789 + pipeClosed.resolve();
790 + }),
791 + }),
792 + );
793 + if (shutdown === "inherited pipe") {
794 + yield* Effect.gen(function* () {
795 + const releasing = yield* release.pipe(Effect.forkChild({ startImmediately: true }));
796 + yield* Effect.promise(() => fake.closing);
797 + yield* TestClock.adjust("12999 millis");
798 + assert.strictEqual(fake.closeCount(), 1);
799 + assert.deepStrictEqual(stopped, []);
800 + yield* TestClock.adjust("1 millis");
801 + assert.deepStrictEqual(
802 + [...stopped],
803 + [{ unit: "t3code-muse-test.scope", hostExited: false }],
804 + );
805 + yield* Fiber.join(releasing);
806 + }).pipe(Effect.ensuring(Effect.sync(() => pipeClosed.resolve())));
807 + } else {
808 + yield* release;
809 + }
810 + assert.strictEqual(fake.closeCount(), 1);
811 + assert.deepStrictEqual(stopped, [
812 + { unit: "t3code-muse-test.scope", hostExited: shutdown === "normal" },
813 + ]);
814 + yield* Effect.promise(() => fake.host.exited);
815 + assert.isTrue(hostExited);
816 + }).pipe(Effect.provide(testLayer)),
817 + );
818 +
819 it.effect(
820 "closes a newly opened host when native session registration returns another identity",
821 () =>
@@ -768,6 +833,76 @@ describe("MuseAdapterV2", () => {
833 }).pipe(Effect.scoped, Effect.provide(testLayer)),
834 );
835
836 + it.effect(
837 + "settles an active turn and reaps its scope on raw exit before inherited stdio closes",
838 + () =>
839 + Effect.gen(function* () {
840 + const fake = yield* makeFakeMuse();
841 + const pipeClosed = pendingPromise<void>();
842 + fake.holdClose(pipeClosed.promise);
843 + const stopped = yield* Deferred.make<void>();
844 + const units: string[] = [];
845 + let hostExited = false;
846 + let connectionClosed = false;
847 + void fake.host.exited.then(() => {
848 + hostExited = true;
849 + });
850 + void fake.host.connection.closed.then(() => {
851 + connectionClosed = true;
852 + });
853 + yield* Effect.gen(function* () {
854 + const harness = yield* makeHarness(fake);
855 + const { nativeId } = yield* startConversation(harness, fake);
856 + yield* fake.emit("approval/requested", approval(nativeId));
857 + yield* harness.takeEvent(
858 + "runtime_request.updated",
859 + (event) => event.runtimeRequest.status === "pending",
860 + );
861 + yield* fake.exitProcess();
862 + yield* Deferred.await(stopped);
863 + assert.deepStrictEqual(units, ["t3code-muse-exit.scope"]);
864 + const terminal = yield* harness.takeEvent("turn.terminal");
865 + assert.strictEqual(terminal.status, "failed");
866 + assert.strictEqual(terminal.threadDisposition, "broken");
867 + assert.isFalse(hostExited);
868 + assert.isFalse(connectionClosed);
869 + assert.isTrue(
870 + harness.allEvents.some(
871 + (event) =>
872 + event.type === "runtime_request.updated" &&
873 + event.runtimeRequest.status === "cancelled",
874 + ),
875 + );
876 + pipeClosed.resolve();
877 + yield* fake.disconnect();
878 + yield* Deferred.await(harness.eventsEnded);
879 + const result = yield* harness.runtime
880 + .startTurn(yield* turnInput(harness.providerThread, 2))
881 + .pipe(Effect.exit);
882 + assert.strictEqual(result._tag, "Failure");
883 + assert.strictEqual(
884 + harness.allEvents.filter((event) => event.type === "turn.terminal").length,
885 + 1,
886 + );
887 + assert.strictEqual(fake.calls.filter((call) => call.method === "turn/start").length, 1);
888 + }).pipe(
889 + Effect.ensuring(Effect.sync(() => pipeClosed.resolve())),
890 + Effect.scoped,
891 + Effect.provideService(AgentScope, {
892 + ...AgentScope.defaultValue(),
893 + wrap: ({ command, args }) =>
894 + Effect.succeed({ command, args, unit: "t3code-muse-exit.scope" }),
895 + stop: (unit) =>
896 + Effect.gen(function* () {
897 + units.push(unit);
898 + yield* Deferred.succeed(stopped, undefined);
899 + }),
900 + }),
901 + );
902 + assert.deepStrictEqual(units, ["t3code-muse-exit.scope"]);
903 + }).pipe(Effect.provide(testLayer)),
904 + );
905 +
906 it.effect("settles an active turn once when both the connection and host exit unexpectedly", () =>
907 Effect.gen(function* () {
908 const fake = yield* makeFakeMuse();
packages/provider-muse/src/server/adapter.ts
+27 -4
@@ -1,4 +1,4 @@
1 -import { MspError, type SendUserTurnOptions } from "@muse-code/sdk";
1 +import { MspError, type ProcessExit, type SendUserTurnOptions } from "@muse-code/sdk";
2 import {
3 MUSE_DEFAULT_MODEL,
4 ProviderDriverKind,
@@ -1678,6 +1678,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1678 threadId: input.threadId,
1679 env: environment,
1680 });
1681 + // Finalizers run in reverse order: reap detached work after closing the host.
1682 + const scopeUnit = launch.unit;
1683 + const stopScope =
1684 + scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
1685 + yield* Scope.addFinalizer(scope, stopScope);
1686 + const processExited = yield* Deferred.make<ProcessExit>();
1687 + // Observe raw exit before acquisition: inherited stdout can also block startup cleanup.
1688 + yield* Deferred.await(processExited).pipe(Effect.andThen(stopScope), Effect.forkIn(scope));
1689 const created = yield* Effect.acquireRelease(
1690 createMuseSdkHostEffect(
1691 {
@@ -1686,6 +1694,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1694 cwd,
1695 environment,
1696 runtimeMode: input.runtimePolicy.runtimeMode,
1697 + onProcessExit: (exit) => {
1698 + Deferred.doneUnsafe(processExited, Effect.succeed(exit));
1699 + },
1700 },
1701 options.createHost,
1702 ).pipe(
@@ -1704,7 +1715,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1715 closed = true;
1716 hostEpoch++;
1717 }
1707 - yield* Effect.tryPromise(() => created.close()).pipe(Effect.ignore);
1718 + const close = Effect.tryPromise(() => created.close());
1719 + // SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can
1720 + // keep its close promise pending. Let the scope reap those holders.
1721 + yield* (
1722 + scopeUnit === undefined
1723 + ? close
1724 + : close.pipe(Effect.interruptible, Effect.timeoutOption("13 seconds"))
1725 + ).pipe(Effect.ignore);
1726 }),
1727 { interruptible: true },
1728 ).pipe(Effect.provideService(Scope.Scope, scope));
@@ -1733,7 +1751,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1751 epoch,
1752 });
1753 });
1736 - void created.exited.then((exit) => {
1754 + const reportExit = (exit: ProcessExit) => {
1755 if (!closed && epoch === hostEpoch) {
1756 const reason = created
1757 .stderrTail?.()
@@ -1747,7 +1765,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1765 epoch,
1766 });
1767 }
1750 - });
1768 + };
1769 + void created.exited.then(reportExit);
1770 + yield* Deferred.await(processExited).pipe(
1771 + Effect.tap((exit) => Effect.sync(() => reportExit(exit))),
1772 + Effect.forkIn(scope),
1773 + );
1774 });
1775 yield* Effect.addFinalizer(() =>
1776 Effect.gen(function* () {
packages/provider-muse/src/server/sdk.test.ts
+80 -1
@@ -9,7 +9,7 @@ import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Path from "effect/Path";
12 -import { afterEach, describe, expect, vi } from "vite-plus/test";
12 +import { afterEach, describe, expect, onTestFinished, vi } from "vite-plus/test";
13 import {
14 createMuseSdkHost,
15 createMuseSdkHostEffect,
@@ -135,6 +135,85 @@ describe("Muse SDK host", () => {
135 },
136 );
137
138 + it.effect(
139 + "observes native host exit while the SDK still waits for a detached stdout holder",
140 + () =>
141 + Effect.gen(function* () {
142 + if ((yield* HostProcess.Platform) === "win32") return;
143 + yield* Effect.promise(async () => {
144 + const sdk = await vi.importActual<typeof import("@muse-code/sdk")>("@muse-code/sdk");
145 + const processExited = pending<{ code: number | null; signal: NodeJS.Signals | null }>();
146 + const holderSource = `process.send("ready", () => {
147 + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
148 + });`;
149 + const fixture = `
150 + const { spawn } = require("node:child_process");
151 + require("node:readline").createInterface({ input: process.stdin }).on("line", async line => {
152 + const frame = JSON.parse(line);
153 + if (!("id" in frame)) return;
154 + let result = { schema: { version: 1, fingerprint: "t3-native-fixture" }, grantedCapabilities: [] };
155 + if (frame.method === "fixture/exit") {
156 + const holder = spawn(process.execPath, ["-e", ${JSON.stringify(holderSource)}], {
157 + detached: true, stdio: ["ignore", 1, 2, "ipc"]
158 + });
159 + await new Promise(resolve => holder.once("message", resolve));
160 + result = { pid: holder.pid };
161 + }
162 + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result }) + "\\n",
163 + () => { if (frame.method === "fixture/exit") process.exit(7); });
164 + });
165 + `;
166 + let holderPid: number | undefined;
167 + let host: MuseSdkHost | undefined;
168 + const reap = () => {
169 + if (holderPid !== undefined) {
170 + try {
171 + process.kill(holderPid, "SIGKILL");
172 + } catch {
173 + /* Already reaped. */
174 + }
175 + holderPid = undefined;
176 + }
177 + };
178 + onTestFinished(async () => {
179 + reap();
180 + await host?.close();
181 + });
182 + try {
183 + host = await createMuseSdkHost(
184 + {
185 + binaryPath: process.execPath,
186 + launch: { command: process.execPath, args: ["-e", fixture] },
187 + onProcessExit: processExited.resolve,
188 + },
189 + sdk.spawnMspConnection,
190 + );
191 + let sdkExited = false;
192 + let connectionClosed = false;
193 + void host.exited.then(() => {
194 + sdkExited = true;
195 + });
196 + void host.connection.closed.then(() => {
197 + connectionClosed = true;
198 + });
199 + const response = await host.connection.request("fixture/exit", {});
200 + expect(response).toMatchObject({ pid: expect.any(Number) });
201 + holderPid = Number((response as { pid: number }).pid);
202 + expect(await processExited.promise).toEqual({ code: 7, signal: null });
203 + expect(sdkExited).toBe(false);
204 + expect(connectionClosed).toBe(false);
205 + reap();
206 + expect(await host.exited).toEqual({ code: 7, signal: null });
207 + await host.close();
208 + expect(connectionClosed).toBe(true);
209 + } finally {
210 + reap();
211 + await host?.close();
212 + }
213 + });
214 + }),
215 + );
216 +
217 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
218 Effect.gen(function* () {
219 const started = pending<void>();
packages/provider-muse/src/server/sdk.ts
+2
@@ -48,6 +48,7 @@ export interface MuseSdkHostOptions {
48 readonly sessionLogging?: boolean;
49 readonly signal?: AbortSignal;
50 readonly startupTimeoutMs?: number;
51 + readonly onProcessExit?: (exit: ProcessExit) => void;
52 }
53
54 export function makeMuseEnvironment(
@@ -172,6 +173,7 @@ export async function createMuseSdkHost(
173 ...(options.cwd ? { cwd: options.cwd } : {}),
174 env: options.environment ?? makeMuseEnvironment(),
175 shutdownTimeoutMs: 10_000,
176 + ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
177 });
178 let closePromise: Promise<void> | undefined;
179 const close = () => {
packages/provider-pi/src/server/adapter.test.ts
+55
@@ -20,6 +20,8 @@ import {
20 } from "@t3tools/contracts";
21 import * as Cause from "effect/Cause";
22 import * as DateTime from "effect/DateTime";
23 +import * as Deferred from "effect/Deferred";
24 +import * as Duration from "effect/Duration";
25 import * as Effect from "effect/Effect";
26 import * as Exit from "effect/Exit";
27 import * as Fiber from "effect/Fiber";
@@ -38,6 +40,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
40 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41 import { handoffBudget } from "@t3tools/provider-core/server/handoffBudget";
42 import * as HostProcess from "@t3tools/shared/HostProcess";
43 +import { AgentScope } from "@t3tools/shared/AgentScope";
44 import { toolOutputImages, compactDynamicToolOutput } from "@t3tools/shared/toolOutput";
45 import {
46 makePiAdapterV2,
@@ -1366,6 +1369,58 @@ describe("PiAdapterV2", () => {
1369 }).pipe(Effect.scoped, Effect.provide(layerTest)),
1370 );
1371
1372 + it.effect.each(["session", "process"] as const)("cleans up detached work on Pi %s exit", (exit) =>
1373 + Effect.gen(function* () {
1374 + const fake = yield* makeFakePi;
1375 + const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
1376 + const scopeStopped = yield* Deferred.make<void>();
1377 + let processReleased = false;
1378 + const stopped: Array<{ unit: string; processReleased: boolean }> = [];
1379 + yield* Effect.gen(function* () {
1380 + yield* openRuntime({
1381 + ...fake,
1382 + spawner: ChildProcessSpawner.make((command) =>
1383 + Effect.acquireRelease(
1384 + fake.spawner
1385 + .spawn(command)
1386 + .pipe(
1387 + Effect.map((child) =>
1388 + ChildProcessSpawner.makeHandle({ ...child, exitCode: Deferred.await(exited) }),
1389 + ),
1390 + ),
1391 + () =>
1392 + Effect.sync(() => {
1393 + processReleased = true;
1394 + }),
1395 + ),
1396 + ),
1397 + });
1398 + assert.deepStrictEqual(stopped, []);
1399 + if (exit === "process") {
1400 + // Stdout stays open as it would for a child holding the inherited pipe.
1401 + yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(19));
1402 + yield* Deferred.await(scopeStopped);
1403 + assert.isFalse(processReleased);
1404 + }
1405 + }).pipe(
1406 + Effect.scoped,
1407 + Effect.provideService(AgentScope, {
1408 + ...AgentScope.defaultValue(),
1409 + wrap: ({ command, args }) =>
1410 + Effect.succeed({ command, args, unit: "t3code-pi-test.scope" }),
1411 + stop: (unit) =>
1412 + Effect.sync(() => void stopped.push({ unit, processReleased })).pipe(
1413 + Effect.andThen(Deferred.succeed(scopeStopped, undefined)),
1414 + Effect.asVoid,
1415 + ),
1416 + }),
1417 + );
1418 + assert.deepStrictEqual(stopped, [
1419 + { unit: "t3code-pi-test.scope", processReleased: exit === "session" },
1420 + ]);
1421 + }).pipe(Effect.provide(layerTest)),
1422 + );
1423 +
1424 it.effect("gives notify and extension-error items distinct ids in each thread", () =>
1425 Effect.gen(function* () {
1426 const itemIds = new Set<string>();
packages/provider-pi/src/server/adapter.ts
+12
@@ -481,6 +481,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
481 threadId: input.threadId,
482 env: launch.env,
483 });
484 + // Finalizers run in reverse order: reap detached work after terminating Pi.
485 + const scopeUnit = scopedLaunch.unit;
486 + const stopScope =
487 + scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
488 + yield* Effect.addFinalizer(() => stopScope);
489 const connection: PiRpcConnection = yield* makePiRpcConnection({
490 command: scopedLaunch.command,
491 args: scopedLaunch.args,
@@ -497,6 +502,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
502 }),
503 ),
504 );
505 + // Detached children can keep stdout open after Pi exits.
506 + if (scopeUnit !== undefined) {
507 + yield* connection.exited.pipe(
508 + Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
509 + Effect.forkIn(scope),
510 + );
511 + }
512 const now = yield* DateTime.now;
513 let sessionEntity: OrchestrationV2ProviderSession = {
514 id: input.providerSessionId,
packages/shared/src/AgentScope.ts
+8
@@ -21,6 +21,11 @@ export interface AgentScopeShape {
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,12 +37,15 @@ export interface AgentScopeShape {
37 export 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
44 export 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 });
patches/@muse-code__sdk@1.4.6.patch new
+46
@@ -0,0 +1,46 @@
1 +diff --git a/dist/src/connection/spawn.d.ts b/dist/src/connection/spawn.d.ts
2 +index b67e690eae07748e6aee2c8ee59bbfef13b2eea8..581ef3e9184da89cde8471a8fe03c86209ac7c81 100644
3 +--- a/dist/src/connection/spawn.d.ts
4 ++++ b/dist/src/connection/spawn.d.ts
5 +@@ -20,6 +20,8 @@ export interface SpawnMspConnectionOptions {
6 + readonly onStderr?: (chunk: string) => void;
7 + /** See {@link MuseServeChildOptions.shutdownTimeoutMs}. */
8 + readonly shutdownTimeoutMs?: number;
9 ++ /** Raw process exit, before inherited stdio drains and `exited` settles. */
10 ++ readonly onProcessExit?: (exit: ProcessExit) => void;
11 + }
12 + /**
13 + * How the host process ended: its exit code, or the signal that ended it.
14 +@@ -74,6 +76,8 @@ export interface MuseServeChildOptions {
15 + * `0..2147483647`; anything else throws `RangeError` at spawn.
16 + */
17 + readonly shutdownTimeoutMs?: number;
18 ++ /** Raw process exit, before inherited stdio drains and `exited` settles. */
19 ++ readonly onProcessExit?: (exit: ProcessExit) => void;
20 + /**
21 + * Deterministic-test seam; production always uses `child_process.spawn`.
22 + * A stub here observes the exact options the call site passes, so a
23 +diff --git a/dist/src/connection/spawn.js b/dist/src/connection/spawn.js
24 +index 28aeb6246ba937c5321f1393dc120eface0707f3..0c835bb9d45a73eacd6a35b5e589191f04104537 100644
25 +--- a/dist/src/connection/spawn.js
26 ++++ b/dist/src/connection/spawn.js
27 +@@ -390,7 +390,10 @@ export class MuseServeChild {
28 + detached: ownsProcessGroup,
29 + });
30 + const spawnChild = options.spawnFn ?? spawn;
31 +- return new MuseServeChild(spawnChild(options.museBin, [...(options.args ?? [])], spawnOptions), options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
32 ++ const child = spawnChild(options.museBin, [...(options.args ?? [])], spawnOptions);
33 ++ if (options.onProcessExit !== undefined)
34 ++ child.once("exit", (code, signal) => options.onProcessExit({ code, signal }));
35 ++ return new MuseServeChild(child, options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
36 + }
37 + get stderrTail() {
38 + return this.#tail.lines();
39 +@@ -414,6 +417,7 @@ export class MspHandshake {
40 + constructor(options) {
41 + this.child = MuseServeChild.spawn({
42 + museBin: options.command,
43 ++ ...(options.onProcessExit === undefined ? {} : { onProcessExit: options.onProcessExit }),
44 + ...(options.args === undefined ? {} : { args: options.args }),
45 + ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
46 + ...(options.env === undefined ? {} : { env: options.env }),
pnpm-lock.yaml
+4 -3
@@ -350,6 +350,7 @@ patchedDependencies:
350 '@expo/ui@58.0.20': 5a26480373850c1a7943919aa21f904151b335a0cb01042109e0746def37923e
351 '@ff-labs/fff-node@0.11.0': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c
352 '@legendapp/list@3.3.5': 011a862a7116ec5b5f4bba17d37bc58c9b5a8f64a6a9f527345f316ce9c96e63
353 + '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101
354 '@pierre/diffs@1.5.2': 2ec81ba1e8ce4681095a3473c2bf78e630417740c622720ef624febb467c25fc
355 '@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
356 '@react-native-menu/menu@2.0.0': a4866ecfcd44f318043de839d20110c17e14909004900f002ffe12050376f2ba
@@ -850,7 +851,7 @@ importers:
851 version: 0.11.0(patch_hash=cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c)
852 '@muse-code/sdk':
853 specifier: 1.4.6
853 - version: 1.4.6(@types/node@24.12.4)
854 + version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4)
855 '@napi-rs/keyring':
856 specifier: ^1.3.0
857 version: 1.3.0
@@ -1613,7 +1614,7 @@ importers:
1614 dependencies:
1615 '@muse-code/sdk':
1616 specifier: 1.4.6
1616 - version: 1.4.6(@types/node@24.12.4)
1617 + version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4)
1618 '@t3tools/contracts':
1619 specifier: workspace:*
1620 version: link:../contracts
@@ -14706,7 +14707,7 @@ snapshots:
14707 sparse-bitfield: 3.0.3
14708 optional: true
14709
14709 - '@muse-code/sdk@1.4.6(@types/node@24.12.4)':
14710 + '@muse-code/sdk@1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4)':
14711 optionalDependencies:
14712 '@types/node': 24.12.4
14713
pnpm-workspace.yaml
+2
@@ -386,6 +386,8 @@ patchedDependencies:
386 # Android: Maven-resolved gradle plugins (expo-widgets) have no sourceDir; without this
387 # skip, the fingerprint silently drops every Expo native module and OTAs reach stale binaries.
388 "@expo/fingerprint@0.21.5": patches/@expo__fingerprint@0.21.5.patch
389 + # Observe the owned host exit independently of descendants retaining its stdio.
390 + "@muse-code/sdk@1.4.6": patches/@muse-code__sdk@1.4.6.patch
391 app-builder-lib@26.16.1: patches/app-builder-lib@26.16.1.patch
392
393 peerDependencyRules: