Skip to content
TypeScript

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

Joseph Vidal1aa71796709b
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 91c08f565a2..0e0868918ea 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -323,14 +323,18 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [
* When the CLI exits it stops the MCP servers it started, but not their children: a plugin's
* `bun run start` wrapper dies and its `bun server.ts` keeps running, writing to a pipe nobody
* reads (#3089). Those stay in the CLI's group, so the rest of the group gets SIGKILL once the
- * CLI exits for any reason.
+ * CLI exits for any reason. `onExit` then stops the CLI's agent scope, for daemons a tool
+ * detached from the group with setsid.
*
* That cleanup needs this server alive, and the CLI finishes its turn after its pipes close. A
* server that crashes or is killed would leave the CLI working next to the session it resumes
* (#23370), so a watcher in the group reads a pipe only this server holds and stops the group at
* its end-of-file.
*/
-export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpawnedProcess {
+export function spawnClaudeProcessGroup(
+ options: ClaudeSpawnOptions,
+ onExit?: () => void,
+): ClaudeSpawnedProcess {
const child = NodeChildProcess.spawn(
"/bin/sh",
["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
@@ -346,6 +350,7 @@ export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpaw
try {
signalProcessGroup(child.pid ?? 0, "SIGKILL");
} catch {}
+ onExit?.();
});
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
return child as ClaudeSpawnedProcess;
@@ -892,6 +897,7 @@ export const layerQueryRunner: Layer.Layer<
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
+ const runFork = Effect.runForkWith(yield* Effect.context<never>());
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: crypto
@@ -942,10 +948,16 @@ export const layerQueryRunner: Layer.Layer<
pathToClaudeCodeExecutable: launch.command,
executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
};
+ const unit = launch?.unit;
+ const stopScope =
+ unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
// Windows has no process groups, so there the SDK spawns the CLI itself.
const spawnClaudeCodeProcess =
options.spawnClaudeCodeProcess ??
- (platform === "win32" ? undefined : spawnClaudeProcessGroup);
+ (platform === "win32"
+ ? undefined
+ : (spawnOptions: ClaudeSpawnOptions) =>
+ spawnClaudeProcessGroup(spawnOptions, stopScope));
const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
Effect.try({
try: () =>
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
index 248e78a1796..9a4a7ba3cc7 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
@@ -8,12 +8,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as Deferred from "effect/Deferred";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { vi } from "vite-plus/test";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { AgentScope } from "@t3tools/shared/AgentScope";
import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
import {
@@ -162,11 +164,26 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
alive.resume();
- const session = yield* openFakeCli(cli);
+ const stopped = yield* Deferred.make<string>();
+ const session = yield* openFakeCli(cli).pipe(
+ Effect.provide(
+ realQueryRunner.pipe(
+ Layer.provide(
+ Layer.succeed(AgentScope, {
+ ...AgentScope.defaultValue(),
+ wrap: ({ command, args }) =>
+ Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
+ stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
+ }),
+ ),
+ ),
+ ),
+ );
yield* Effect.promise(() => leftoverStarted);
yield* session.close;
yield* Effect.promise(() => leftoverStopped);
- }).pipe(Effect.provide(realQueryRunner)),
+ assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
+ }),
);
// The CLI keeps running its turn after its pipes close, so a server that
diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts
index 30be9346dc1..44e9d6dbf4c 100644
--- a/apps/server/src/process/agentScope.test.ts
+++ b/apps/server/src/process/agentScope.test.ts
@@ -8,7 +8,9 @@ import { assert, describe, expect, it } from "@effect/vitest";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as ServerConfig from "../config.ts";
@@ -35,21 +37,33 @@ describe("classifyScope", () => {
});
});
+interface FakeUnit {
+ activeState: string;
+ result: string;
+ controlGroup?: string;
+}
+
const withFakeSystemd = <A, E>(
body: (input: {
readonly scope: Effect.Success<typeof make>;
- readonly units: Map<string, { activeState: string; result: string }>;
+ readonly units: Map<string, FakeUnit>;
readonly calls: ReadonlyArray<ReadonlyArray<string>>;
readonly stateDir: string;
+ readonly cgroupRoot: string;
}) => Effect.Effect<A, E>,
- { oomPolicy = true }: { readonly oomPolicy?: boolean } = {},
+ // A user manager older than systemd 253 rejects OOMPolicy on scopes.
+ {
+ oomPolicy = true,
+ stopFails = false,
+ }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {},
) =>
Effect.gen(function* () {
const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
for (const name of ["systemd-run", "systemctl", "agent"]) {
NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 });
}
- const units = new Map<string, { activeState: string; result: string }>();
+ const cgroupRoot = NodePath.join(bin, "cgroup");
+ const units = new Map<string, FakeUnit>();
const calls: Array<ReadonlyArray<string>> = [];
const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
stdout,
@@ -69,23 +83,37 @@ const withFakeSystemd = <A, E>(
return output("", 1);
}
const [, verb, unit = ""] = args;
+ if (stopFails && verb === "stop") {
+ return {
+ ...output(""),
+ stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`,
+ code: ChildProcessSpawner.ExitCode(5),
+ };
+ }
if (verb === "reset-failed") units.delete(unit);
if (verb !== "show") return output("");
const state = units.get(unit);
return output(
state === undefined
? "LoadState=not-found\nActiveState=inactive\nResult=success\n"
- : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`,
+ : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` +
+ `ControlGroup=${state.controlGroup ?? ""}\n`,
);
}),
});
+ const fileSystem = yield* FileSystem.FileSystem;
const scope = yield* make.pipe(
Effect.provideService(ProcessRunner.ProcessRunner, runner),
Effect.provideService(HostProcess.Platform, "linux"),
Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }),
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fileSystem,
+ readFileString: (path, encoding) =>
+ fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding),
+ }),
);
const { stateDir } = yield* ServerConfig.ServerConfig;
- return yield* body({ scope, units, calls, stateDir }).pipe(
+ return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe(
Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))),
);
}).pipe(
@@ -103,6 +131,31 @@ const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
+/** An active scope as systemd and the kernel report it, with the agent itself gone. */
+const exitedAgent = (
+ units: Map<string, FakeUnit>,
+ cgroupRoot: string,
+ unit: string,
+ { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined },
+) => {
+ const controlGroup = `/${unit}`;
+ NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true });
+ NodeFS.writeFileSync(
+ NodePath.join(cgroupRoot, controlGroup, "cgroup.events"),
+ `populated ${populated ? 1 : 0}\nfrozen 0\n`,
+ );
+ // An undefined count leaves memory.events unreadable.
+ if (oomKills !== undefined) {
+ NodeFS.writeFileSync(
+ NodePath.join(cgroupRoot, controlGroup, "memory.events"),
+ `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`,
+ );
+ }
+ units.set(unit, { activeState: "active", result: "success", controlGroup });
+};
+
+const stopsOf = (calls: ReadonlyArray<ReadonlyArray<string>>) =>
+ calls.filter(([, verb]) => verb === "stop");
const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
Effect.provideService(AgentScope, scope),
@@ -194,4 +247,90 @@ describe("AgentScope service", () => {
}),
),
);
+
+ it.effect("stops leftover processes only in an active agent scope", () =>
+ withFakeSystemd(({ scope, units, calls, cgroupRoot }) =>
+ Effect.gen(function* () {
+ const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
+ const unit = unitOf(agent);
+ expect(agent.unit).toBe(unit);
+
+ yield* scope.stop("session-2.scope");
+ expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false);
+ yield* scope.stop(unit);
+ exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 });
+ yield* scope.stop(unit);
+ exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 });
+ units.get(unit)!.activeState = "deactivating";
+ yield* scope.stop(unit);
+ expect(stopsOf(calls)).toEqual([]);
+
+ units.get(unit)!.activeState = "active";
+ yield* scope.stop(unit);
+ expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]);
+ expect(yield* scope.oomKilled("a")).toBe(false);
+ }),
+ ),
+ );
+
+ it.effect.each([true, false])(
+ "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)",
+ (oomPolicy) =>
+ withFakeSystemd(
+ ({ scope, units, calls, cgroupRoot }) =>
+ Effect.gen(function* () {
+ const agent = yield* scope.wrap({
+ command: "agent",
+ args: [],
+ name: "t",
+ threadId: "a",
+ });
+ const unit = unitOf(agent);
+ exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined });
+ yield* scope.stop(unit);
+ expect(stopsOf(calls)).toEqual(
+ oomPolicy ? [] : [["--user", "stop", "--no-block", unit]],
+ );
+
+ // The kernel records the kill before systemd records the OOM result.
+ exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 });
+ yield* scope.stop(unit);
+ expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2);
+
+ if (oomPolicy) {
+ units.set(unit, { activeState: "failed", result: "oom-kill" });
+ expect(yield* scope.oomKilled("a")).toBe(true);
+ units.delete(unit);
+ expect(yield* scope.oomKilled("a")).toBe(true);
+ }
+ }),
+ { oomPolicy },
+ ),
+ );
+
+ it.effect("reports failed daemon cleanup without failing session teardown", () => {
+ const warnings: Array<unknown> = [];
+ const logger = Logger.make(({ message }) => {
+ warnings.push(message);
+ });
+ return withFakeSystemd(
+ ({ scope, units, cgroupRoot }) =>
+ Effect.gen(function* () {
+ const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
+ exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 });
+ yield* scope.stop(unitOf(agent));
+ expect(warnings.flat()).toContain("Could not stop an exited agent's scope");
+ }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
+ { stopFails: true },
+ );
+ });
+
+ it.effect("leaves a quiet slice alone", () =>
+ withFakeSystemd(({ scope, calls }) =>
+ Effect.gen(function* () {
+ yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
+ expect(calls.filter(([, verb]) => verb === "stop")).toEqual([]);
+ }),
+ ),
+ );
});
diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts
index 74858468d1b..d923a1bc7e9 100644
--- a/apps/server/src/process/agentScope.ts
+++ b/apps/server/src/process/agentScope.ts
@@ -44,7 +44,7 @@ export interface ScopeState {
readonly loadState: string;
readonly activeState: string;
readonly result: string;
- readonly oomKills: number;
+ readonly oomKills: number | undefined;
readonly populated: boolean | undefined;
}
@@ -62,7 +62,11 @@ export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "runni
) {
return "gone";
}
- if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) {
+ if (
+ state.activeState === "deactivating" ||
+ (state.oomKills ?? 0) > 0 ||
+ state.populated === false
+ ) {
return "stopping";
}
return "running";
@@ -220,7 +224,7 @@ export const make = Effect.gen(function* () {
loadState: values.get("LoadState") ?? "",
activeState: values.get("ActiveState") ?? "",
result: values.get("Result") ?? "",
- oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
+ oomKills: parseCgroupCounter(memoryEvents, "oom_kill"),
populated: populated === undefined ? undefined : populated === 1,
} satisfies ScopeState;
});
@@ -300,6 +304,32 @@ export const make = Effect.gen(function* () {
},
);
+ const stop = Effect.fn("AgentScope.stop")(function* (unit: string) {
+ if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return;
+ const scope = yield* systemd;
+ if (scope === undefined) return;
+ const state = yield* readScope(scope.systemctl, unit);
+ if (
+ state === undefined ||
+ state.loadState !== "loaded" ||
+ state.activeState !== "active" ||
+ state.result === "oom-kill" ||
+ state.populated === false
+ )
+ return;
+ // The kernel counts OOM kills before signaling the victim. Let OOMPolicy
+ // record the result before a manual stop can overwrite it; an unreadable
+ // counter cannot rule out that race. Older managers need us to stop it.
+ if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return;
+ const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]);
+ if (stopped._tag === "None" || stopped.value.code !== 0) {
+ yield* Effect.logWarning("Could not stop an exited agent's scope", {
+ unit,
+ exitCode: stopped._tag === "Some" ? stopped.value.code : undefined,
+ });
+ }
+ });
+
const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
if (!scopeByThread.has(threadId)) return;
const scope = yield* systemd;
@@ -341,9 +371,10 @@ export const make = Effect.gen(function* () {
...(owned ? [] : ["--collect"]),
],
};
- return agentScopeCommand({ command: resolved, args, scope: systemdScope });
+ return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit };
}),
oomKilled,
+ stop,
clear,
} satisfies AgentScopeShape;
});
diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
index 36fee6411d7..9e2da61be2a 100644
--- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
@@ -14,9 +14,11 @@ import * as Fiber from "effect/Fiber";
import * as Scope from "effect/Scope";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
+import { ChildProcessSpawner } from "effect/process";
import { describe, expect } from "vite-plus/test";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
+import { AgentScope } from "@t3tools/shared/AgentScope";
import * as EffectAcpErrors from "effect-acp/errors";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -193,10 +195,38 @@ describe("AcpSessionRuntime", () => {
it.effect("reports an idle child exit and rejects later prompts", () =>
Effect.gen(function* () {
- const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions);
+ const stopped = yield* Deferred.make<string>();
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) =>
+ spawner.spawn(command).pipe(
+ Effect.map((child) =>
+ ChildProcessSpawner.makeHandle({
+ ...child,
+ // Model an inherited pipe held open until detached work is stopped.
+ stdout: Stream.concat(
+ child.stdout,
+ Stream.fromEffect(Deferred.await(stopped)).pipe(Stream.drain),
+ ),
+ }),
+ ),
+ ),
+ ),
+ ),
+ Effect.provideService(AgentScope, {
+ ...AgentScope.defaultValue(),
+ wrap: ({ command, args }) =>
+ Effect.succeed({ command, args, unit: "t3code-acp-test.scope" }),
+ stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
+ }),
+ );
yield* runtime.start();
+ expect(yield* Deferred.isDone(stopped)).toBe(false);
yield* runtime.notify("_test/exit", {});
const events = yield* runtime.getEvents().pipe(Stream.take(1), Stream.runCollect);
+ expect(yield* Deferred.await(stopped)).toBe("t3code-acp-test.scope");
const event = events[0];
expect(event).toMatchObject({ _tag: "ConnectionTerminated", error: { code: 19 } });
if (event?._tag !== "ConnectionTerminated") return;
diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts
index 5aef32a1a5a..f69be279a9b 100644
--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts
+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts
@@ -1435,19 +1435,24 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
cause: new Error("Contained ACP command was not found on PATH"),
});
});
- const scopedSpawnCommand =
+ const agentScope = yield* AgentScope;
+ const scopedLaunch =
linuxCgroupLease !== undefined || spawnCommand.shell
- ? spawnCommand
- : {
- ...(yield* (yield* AgentScope).wrap({
- command: spawnCommand.command,
- args: spawnCommand.args,
- name: "acp",
- threadId: yield* AgentScopeThreadId,
- env: { ...process.env, ...options.spawn.env },
- })),
- shell: false,
- };
+ ? undefined
+ : yield* agentScope.wrap({
+ command: spawnCommand.command,
+ args: spawnCommand.args,
+ name: "acp",
+ threadId: yield* AgentScopeThreadId,
+ env: { ...process.env, ...options.spawn.env },
+ });
+ const scopedSpawnCommand =
+ scopedLaunch === undefined ? spawnCommand : { ...scopedLaunch, shell: false };
+ // Finalizers run in reverse order: reap detached work after terminating the agent.
+ const scopeUnit = scopedLaunch?.unit;
+ const stopScope =
+ scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
+ yield* Scope.addFinalizer(runtimeScope, stopScope);
const containedSpawnCommand =
linuxCgroupLease === undefined
? scopedSpawnCommand
@@ -1486,6 +1491,14 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
),
);
+ // Detached children can keep stdout open, delaying protocol termination.
+ if (scopeUnit !== undefined) {
+ yield* child.exitCode.pipe(
+ Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
+ Effect.forkIn(runtimeScope),
+ );
+ }
+
const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();
const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();
const posixOwnershipChildQueues = new Map<number, Array<number>>();
diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts
index 122e77a760f..63e0a1779d2 100644
--- a/packages/provider-muse/src/server/adapter.test.ts
+++ b/packages/provider-muse/src/server/adapter.test.ts
@@ -19,6 +19,7 @@ import {
type OrchestrationV2ProviderThread,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { AgentScope } from "@t3tools/shared/AgentScope";
import { MuseSettings } from "../settings.ts";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -30,11 +31,12 @@ import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
+import * as TestClock from "effect/testing/TestClock";
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import type { MuseItem, MuseSubscriptionUsage } from "./protocol.ts";
-import type { MuseSdkHost } from "./sdk.ts";
+import type { MuseSdkHost, MuseSdkHostOptions } from "./sdk.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
@@ -87,8 +89,10 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
let notify: Parameters<MuseSdkHost["connection"]["onNotification"]>[0] = () => {};
let sequence = 0;
let sessionId = "";
+ const closing = pendingPromise<void>();
let closeCount = 0;
let closeGate: Promise<void> | undefined;
+ let onProcessExit: MuseSdkHostOptions["onProcessExit"];
let history: MuseItem[] = [];
const responses = new Map<
string,
@@ -143,6 +147,7 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
exited: exited.promise,
close: async () => {
closeCount += 1;
+ closing.resolve();
await closeGate;
closed.resolve();
exited.resolve({ code: 0, signal: null });
@@ -152,6 +157,11 @@ const makeFakeMuse = Effect.fnUntraced(function* (idPrefix = "native") {
host,
calls,
closeCount: () => closeCount,
+ closing: closing.promise,
+ observeProcessExit: (callback: MuseSdkHostOptions["onProcessExit"]) => {
+ onProcessExit = callback;
+ },
+ exitProcess: () => Effect.sync(() => onProcessExit?.({ code: 1, signal: null })),
holdClose: (gate: Promise<void>) => {
closeGate = gate;
},
@@ -204,7 +214,11 @@ const makeHarness = Effect.fnUntraced(function* (
instanceId,
settings: museSettings,
environment: { PATH: "/fake/bin" },
- createHost: async () => (hostCount++ === 0 ? fake.host : (replacement ?? fake).host),
+ createHost: async (options) => {
+ const selected = hostCount++ === 0 ? fake : (replacement ?? fake);
+ selected.observeProcessExit(options.onProcessExit);
+ return selected.host;
+ },
...overrides,
});
const runtime = yield* adapter.openSession({
@@ -751,6 +765,57 @@ describe("MuseAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(testLayer)),
);
+ it.effect.each(["normal", "inherited pipe"] as const)(
+ "closes its SDK host exactly once on session teardown with %s shutdown",
+ (shutdown) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakeMuse();
+ const pipeClosed = pendingPromise<void>();
+ if (shutdown === "inherited pipe") fake.holdClose(pipeClosed.promise);
+ let hostExited = false;
+ void fake.host.exited.then(() => {
+ hostExited = true;
+ });
+ const stopped: Array<{ unit: string; hostExited: boolean }> = [];
+ const release = makeHarness(fake).pipe(
+ Effect.scoped,
+ Effect.provideService(AgentScope, {
+ ...AgentScope.defaultValue(),
+ wrap: ({ command, args }) =>
+ Effect.succeed({ command, args, unit: "t3code-muse-test.scope" }),
+ stop: (unit) =>
+ Effect.sync(() => {
+ stopped.push({ unit, hostExited });
+ pipeClosed.resolve();
+ }),
+ }),
+ );
+ if (shutdown === "inherited pipe") {
+ yield* Effect.gen(function* () {
+ const releasing = yield* release.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Effect.promise(() => fake.closing);
+ yield* TestClock.adjust("12999 millis");
+ assert.strictEqual(fake.closeCount(), 1);
+ assert.deepStrictEqual(stopped, []);
+ yield* TestClock.adjust("1 millis");
+ assert.deepStrictEqual(
+ [...stopped],
+ [{ unit: "t3code-muse-test.scope", hostExited: false }],
+ );
+ yield* Fiber.join(releasing);
+ }).pipe(Effect.ensuring(Effect.sync(() => pipeClosed.resolve())));
+ } else {
+ yield* release;
+ }
+ assert.strictEqual(fake.closeCount(), 1);
+ assert.deepStrictEqual(stopped, [
+ { unit: "t3code-muse-test.scope", hostExited: shutdown === "normal" },
+ ]);
+ yield* Effect.promise(() => fake.host.exited);
+ assert.isTrue(hostExited);
+ }).pipe(Effect.provide(testLayer)),
+ );
+
it.effect(
"closes a newly opened host when native session registration returns another identity",
() =>
@@ -768,6 +833,76 @@ describe("MuseAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(testLayer)),
);
+ it.effect(
+ "settles an active turn and reaps its scope on raw exit before inherited stdio closes",
+ () =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakeMuse();
+ const pipeClosed = pendingPromise<void>();
+ fake.holdClose(pipeClosed.promise);
+ const stopped = yield* Deferred.make<void>();
+ const units: string[] = [];
+ let hostExited = false;
+ let connectionClosed = false;
+ void fake.host.exited.then(() => {
+ hostExited = true;
+ });
+ void fake.host.connection.closed.then(() => {
+ connectionClosed = true;
+ });
+ yield* Effect.gen(function* () {
+ const harness = yield* makeHarness(fake);
+ const { nativeId } = yield* startConversation(harness, fake);
+ yield* fake.emit("approval/requested", approval(nativeId));
+ yield* harness.takeEvent(
+ "runtime_request.updated",
+ (event) => event.runtimeRequest.status === "pending",
+ );
+ yield* fake.exitProcess();
+ yield* Deferred.await(stopped);
+ assert.deepStrictEqual(units, ["t3code-muse-exit.scope"]);
+ const terminal = yield* harness.takeEvent("turn.terminal");
+ assert.strictEqual(terminal.status, "failed");
+ assert.strictEqual(terminal.threadDisposition, "broken");
+ assert.isFalse(hostExited);
+ assert.isFalse(connectionClosed);
+ assert.isTrue(
+ harness.allEvents.some(
+ (event) =>
+ event.type === "runtime_request.updated" &&
+ event.runtimeRequest.status === "cancelled",
+ ),
+ );
+ pipeClosed.resolve();
+ yield* fake.disconnect();
+ yield* Deferred.await(harness.eventsEnded);
+ const result = yield* harness.runtime
+ .startTurn(yield* turnInput(harness.providerThread, 2))
+ .pipe(Effect.exit);
+ assert.strictEqual(result._tag, "Failure");
+ assert.strictEqual(
+ harness.allEvents.filter((event) => event.type === "turn.terminal").length,
+ 1,
+ );
+ assert.strictEqual(fake.calls.filter((call) => call.method === "turn/start").length, 1);
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => pipeClosed.resolve())),
+ Effect.scoped,
+ Effect.provideService(AgentScope, {
+ ...AgentScope.defaultValue(),
+ wrap: ({ command, args }) =>
+ Effect.succeed({ command, args, unit: "t3code-muse-exit.scope" }),
+ stop: (unit) =>
+ Effect.gen(function* () {
+ units.push(unit);
+ yield* Deferred.succeed(stopped, undefined);
+ }),
+ }),
+ );
+ assert.deepStrictEqual(units, ["t3code-muse-exit.scope"]);
+ }).pipe(Effect.provide(testLayer)),
+ );
+
it.effect("settles an active turn once when both the connection and host exit unexpectedly", () =>
Effect.gen(function* () {
const fake = yield* makeFakeMuse();
diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts
index c098a0aa7ea..4ea37a2cc9e 100644
--- a/packages/provider-muse/src/server/adapter.ts
+++ b/packages/provider-muse/src/server/adapter.ts
@@ -1,4 +1,4 @@
-import { MspError, type SendUserTurnOptions } from "@muse-code/sdk";
+import { MspError, type ProcessExit, type SendUserTurnOptions } from "@muse-code/sdk";
import {
MUSE_DEFAULT_MODEL,
ProviderDriverKind,
@@ -1678,6 +1678,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
threadId: input.threadId,
env: environment,
});
+ // Finalizers run in reverse order: reap detached work after closing the host.
+ const scopeUnit = launch.unit;
+ const stopScope =
+ scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
+ yield* Scope.addFinalizer(scope, stopScope);
+ const processExited = yield* Deferred.make<ProcessExit>();
+ // Observe raw exit before acquisition: inherited stdout can also block startup cleanup.
+ yield* Deferred.await(processExited).pipe(Effect.andThen(stopScope), Effect.forkIn(scope));
const created = yield* Effect.acquireRelease(
createMuseSdkHostEffect(
{
@@ -1686,6 +1694,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
cwd,
environment,
runtimeMode: input.runtimePolicy.runtimeMode,
+ onProcessExit: (exit) => {
+ Deferred.doneUnsafe(processExited, Effect.succeed(exit));
+ },
},
options.createHost,
).pipe(
@@ -1704,7 +1715,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
closed = true;
hostEpoch++;
}
- yield* Effect.tryPromise(() => created.close()).pipe(Effect.ignore);
+ const close = Effect.tryPromise(() => created.close());
+ // SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can
+ // keep its close promise pending. Let the scope reap those holders.
+ yield* (
+ scopeUnit === undefined
+ ? close
+ : close.pipe(Effect.interruptible, Effect.timeoutOption("13 seconds"))
+ ).pipe(Effect.ignore);
}),
{ interruptible: true },
).pipe(Effect.provideService(Scope.Scope, scope));
@@ -1733,7 +1751,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
epoch,
});
});
- void created.exited.then((exit) => {
+ const reportExit = (exit: ProcessExit) => {
if (!closed && epoch === hostEpoch) {
const reason = created
.stderrTail?.()
@@ -1747,7 +1765,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
epoch,
});
}
- });
+ };
+ void created.exited.then(reportExit);
+ yield* Deferred.await(processExited).pipe(
+ Effect.tap((exit) => Effect.sync(() => reportExit(exit))),
+ Effect.forkIn(scope),
+ );
});
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts
index d2ac0821bb5..565f8aa6a75 100644
--- a/packages/provider-muse/src/server/sdk.test.ts
+++ b/packages/provider-muse/src/server/sdk.test.ts
@@ -9,7 +9,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
-import { afterEach, describe, expect, vi } from "vite-plus/test";
+import { afterEach, describe, expect, onTestFinished, vi } from "vite-plus/test";
import {
createMuseSdkHost,
createMuseSdkHostEffect,
@@ -135,6 +135,85 @@ describe("Muse SDK host", () => {
},
);
+ it.effect(
+ "observes native host exit while the SDK still waits for a detached stdout holder",
+ () =>
+ Effect.gen(function* () {
+ if ((yield* HostProcess.Platform) === "win32") return;
+ yield* Effect.promise(async () => {
+ const sdk = await vi.importActual<typeof import("@muse-code/sdk")>("@muse-code/sdk");
+ const processExited = pending<{ code: number | null; signal: NodeJS.Signals | null }>();
+ const holderSource = `process.send("ready", () => {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
+ });`;
+ const fixture = `
+ const { spawn } = require("node:child_process");
+ require("node:readline").createInterface({ input: process.stdin }).on("line", async line => {
+ const frame = JSON.parse(line);
+ if (!("id" in frame)) return;
+ let result = { schema: { version: 1, fingerprint: "t3-native-fixture" }, grantedCapabilities: [] };
+ if (frame.method === "fixture/exit") {
+ const holder = spawn(process.execPath, ["-e", ${JSON.stringify(holderSource)}], {
+ detached: true, stdio: ["ignore", 1, 2, "ipc"]
+ });
+ await new Promise(resolve => holder.once("message", resolve));
+ result = { pid: holder.pid };
+ }
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result }) + "\\n",
+ () => { if (frame.method === "fixture/exit") process.exit(7); });
+ });
+ `;
+ let holderPid: number | undefined;
+ let host: MuseSdkHost | undefined;
+ const reap = () => {
+ if (holderPid !== undefined) {
+ try {
+ process.kill(holderPid, "SIGKILL");
+ } catch {
+ /* Already reaped. */
+ }
+ holderPid = undefined;
+ }
+ };
+ onTestFinished(async () => {
+ reap();
+ await host?.close();
+ });
+ try {
+ host = await createMuseSdkHost(
+ {
+ binaryPath: process.execPath,
+ launch: { command: process.execPath, args: ["-e", fixture] },
+ onProcessExit: processExited.resolve,
+ },
+ sdk.spawnMspConnection,
+ );
+ let sdkExited = false;
+ let connectionClosed = false;
+ void host.exited.then(() => {
+ sdkExited = true;
+ });
+ void host.connection.closed.then(() => {
+ connectionClosed = true;
+ });
+ const response = await host.connection.request("fixture/exit", {});
+ expect(response).toMatchObject({ pid: expect.any(Number) });
+ holderPid = Number((response as { pid: number }).pid);
+ expect(await processExited.promise).toEqual({ code: 7, signal: null });
+ expect(sdkExited).toBe(false);
+ expect(connectionClosed).toBe(false);
+ reap();
+ expect(await host.exited).toEqual({ code: 7, signal: null });
+ await host.close();
+ expect(connectionClosed).toBe(true);
+ } finally {
+ reap();
+ await host?.close();
+ }
+ });
+ }),
+ );
+
it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
Effect.gen(function* () {
const started = pending<void>();
diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts
index 0ae8c2b3ebd..5f3514b0d6d 100644
--- a/packages/provider-muse/src/server/sdk.ts
+++ b/packages/provider-muse/src/server/sdk.ts
@@ -48,6 +48,7 @@ export interface MuseSdkHostOptions {
readonly sessionLogging?: boolean;
readonly signal?: AbortSignal;
readonly startupTimeoutMs?: number;
+ readonly onProcessExit?: (exit: ProcessExit) => void;
}
export function makeMuseEnvironment(
@@ -172,6 +173,7 @@ export async function createMuseSdkHost(
...(options.cwd ? { cwd: options.cwd } : {}),
env: options.environment ?? makeMuseEnvironment(),
shutdownTimeoutMs: 10_000,
+ ...(options.onProcessExit ? { onProcessExit: options.onProcessExit } : {}),
});
let closePromise: Promise<void> | undefined;
const close = () => {
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index be502f95337..fcd2fa5478c 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -20,6 +20,8 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
@@ -38,6 +40,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { handoffBudget } from "@t3tools/provider-core/server/handoffBudget";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { AgentScope } from "@t3tools/shared/AgentScope";
import { toolOutputImages, compactDynamicToolOutput } from "@t3tools/shared/toolOutput";
import {
makePiAdapterV2,
@@ -1366,6 +1369,58 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
+ it.effect.each(["session", "process"] as const)("cleans up detached work on Pi %s exit", (exit) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
+ const scopeStopped = yield* Deferred.make<void>();
+ let processReleased = false;
+ const stopped: Array<{ unit: string; processReleased: boolean }> = [];
+ yield* Effect.gen(function* () {
+ yield* openRuntime({
+ ...fake,
+ spawner: ChildProcessSpawner.make((command) =>
+ Effect.acquireRelease(
+ fake.spawner
+ .spawn(command)
+ .pipe(
+ Effect.map((child) =>
+ ChildProcessSpawner.makeHandle({ ...child, exitCode: Deferred.await(exited) }),
+ ),
+ ),
+ () =>
+ Effect.sync(() => {
+ processReleased = true;
+ }),
+ ),
+ ),
+ });
+ assert.deepStrictEqual(stopped, []);
+ if (exit === "process") {
+ // Stdout stays open as it would for a child holding the inherited pipe.
+ yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(19));
+ yield* Deferred.await(scopeStopped);
+ assert.isFalse(processReleased);
+ }
+ }).pipe(
+ Effect.scoped,
+ Effect.provideService(AgentScope, {
+ ...AgentScope.defaultValue(),
+ wrap: ({ command, args }) =>
+ Effect.succeed({ command, args, unit: "t3code-pi-test.scope" }),
+ stop: (unit) =>
+ Effect.sync(() => void stopped.push({ unit, processReleased })).pipe(
+ Effect.andThen(Deferred.succeed(scopeStopped, undefined)),
+ Effect.asVoid,
+ ),
+ }),
+ );
+ assert.deepStrictEqual(stopped, [
+ { unit: "t3code-pi-test.scope", processReleased: exit === "session" },
+ ]);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("gives notify and extension-error items distinct ids in each thread", () =>
Effect.gen(function* () {
const itemIds = new Set<string>();
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index 6cac78ea945..30a493fb0b0 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -481,6 +481,11 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
threadId: input.threadId,
env: launch.env,
});
+ // Finalizers run in reverse order: reap detached work after terminating Pi.
+ const scopeUnit = scopedLaunch.unit;
+ const stopScope =
+ scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
+ yield* Effect.addFinalizer(() => stopScope);
const connection: PiRpcConnection = yield* makePiRpcConnection({
command: scopedLaunch.command,
args: scopedLaunch.args,
@@ -497,6 +502,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
}),
),
);
+ // Detached children can keep stdout open after Pi exits.
+ if (scopeUnit !== undefined) {
+ yield* connection.exited.pipe(
+ Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
+ Effect.forkIn(scope),
+ );
+ }
const now = yield* DateTime.now;
let sessionEntity: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.ts
index 80902e8bbd1..ed53b4311d3 100644
--- a/packages/shared/src/AgentScope.ts
+++ b/packages/shared/src/AgentScope.ts
@@ -21,6 +21,11 @@ export interface AgentScopeShape {
readonly shared?: boolean | undefined;
}) => Effect.Effect<AgentScopeCommand>;
readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
+ /**
+ * Reaps processes left after the owning agent exits, including setsid
+ * descendants outside its process group. Preserves systemd OOM diagnosis.
+ */
+ readonly stop: (unit: string) => Effect.Effect<void>;
/**
* Forgets the thread's scope. The session manager calls it before it opens
* a provider session, so a scope only answers for the session that launched
@@ -32,12 +37,15 @@ export interface AgentScopeShape {
export interface AgentScopeCommand {
readonly command: string;
readonly args: ReadonlyArray<string>;
+ /** The systemd scope the command runs in, for `stop`. */
+ readonly unit?: string | undefined;
}
export const AgentScope = Context.Reference<AgentScopeShape>("@t3tools/shared/AgentScope", {
defaultValue: () => ({
wrap: ({ command, args }) => Effect.succeed({ command, args }),
oomKilled: () => Effect.succeed(false),
+ stop: () => Effect.void,
clear: () => Effect.void,
}),
});
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 00000000000..e35a859700a
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,46 @@
+diff --git a/dist/src/connection/spawn.d.ts b/dist/src/connection/spawn.d.ts
+index b67e690eae07748e6aee2c8ee59bbfef13b2eea8..581ef3e9184da89cde8471a8fe03c86209ac7c81 100644
+--- a/dist/src/connection/spawn.d.ts
++++ b/dist/src/connection/spawn.d.ts
+@@ -20,6 +20,8 @@ export interface SpawnMspConnectionOptions {
+ readonly onStderr?: (chunk: string) => void;
+ /** See {@link MuseServeChildOptions.shutdownTimeoutMs}. */
+ readonly shutdownTimeoutMs?: number;
++ /** Raw process exit, before inherited stdio drains and `exited` settles. */
++ readonly onProcessExit?: (exit: ProcessExit) => void;
+ }
+ /**
+ * How the host process ended: its exit code, or the signal that ended it.
+@@ -74,6 +76,8 @@ export interface MuseServeChildOptions {
+ * `0..2147483647`; anything else throws `RangeError` at spawn.
+ */
+ readonly shutdownTimeoutMs?: number;
++ /** Raw process exit, before inherited stdio drains and `exited` settles. */
++ readonly onProcessExit?: (exit: ProcessExit) => void;
+ /**
+ * Deterministic-test seam; production always uses `child_process.spawn`.
+ * A stub here observes the exact options the call site passes, so a
+diff --git a/dist/src/connection/spawn.js b/dist/src/connection/spawn.js
+index 28aeb6246ba937c5321f1393dc120eface0707f3..0c835bb9d45a73eacd6a35b5e589191f04104537 100644
+--- a/dist/src/connection/spawn.js
++++ b/dist/src/connection/spawn.js
+@@ -390,7 +390,10 @@ export class MuseServeChild {
+ detached: ownsProcessGroup,
+ });
+ const spawnChild = options.spawnFn ?? spawn;
+- return new MuseServeChild(spawnChild(options.museBin, [...(options.args ?? [])], spawnOptions), options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
++ const child = spawnChild(options.museBin, [...(options.args ?? [])], spawnOptions);
++ if (options.onProcessExit !== undefined)
++ child.once("exit", (code, signal) => options.onProcessExit({ code, signal }));
++ return new MuseServeChild(child, options.onStderr, options.shutdownTimeoutMs, ownsProcessGroup);
+ }
+ get stderrTail() {
+ return this.#tail.lines();
+@@ -414,6 +417,7 @@ export class MspHandshake {
+ constructor(options) {
+ this.child = MuseServeChild.spawn({
+ museBin: options.command,
++ ...(options.onProcessExit === undefined ? {} : { onProcessExit: options.onProcessExit }),
+ ...(options.args === undefined ? {} : { args: options.args }),
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
+ ...(options.env === undefined ? {} : { env: options.env }),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 54e2889fa5d..d440b8830fe 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -350,6 +350,7 @@ patchedDependencies:
'@expo/[email protected]': 5a26480373850c1a7943919aa21f904151b335a0cb01042109e0746def37923e
'@ff-labs/[email protected]': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c
'@legendapp/[email protected]': 011a862a7116ec5b5f4bba17d37bc58c9b5a8f64a6a9f527345f316ce9c96e63
+ '@muse-code/[email protected]': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101
'@pierre/[email protected]': 2ec81ba1e8ce4681095a3473c2bf78e630417740c622720ef624febb467c25fc
'@react-native-ai/[email protected]': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
'@react-native-menu/[email protected]': a4866ecfcd44f318043de839d20110c17e14909004900f002ffe12050376f2ba
@@ -850,7 +851,7 @@ importers:
version: 0.11.0(patch_hash=cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c)
'@muse-code/sdk':
specifier: 1.4.6
- version: 1.4.6(@types/[email protected])
+ version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/[email protected])
'@napi-rs/keyring':
specifier: ^1.3.0
version: 1.3.0
@@ -1613,7 +1614,7 @@ importers:
dependencies:
'@muse-code/sdk':
specifier: 1.4.6
- version: 1.4.6(@types/[email protected])
+ version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/[email protected])
'@t3tools/contracts':
specifier: workspace:*
version: link:../contracts
@@ -14706,7 +14707,7 @@ snapshots:
sparse-bitfield: 3.0.3
optional: true
- '@muse-code/[email protected](@types/[email protected])':
+ '@muse-code/[email protected](patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/[email protected])':
optionalDependencies:
'@types/node': 24.12.4
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a8b2ec7ca41..9a0f8f5aa4c 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -386,6 +386,8 @@ patchedDependencies:
# Android: Maven-resolved gradle plugins (expo-widgets) have no sourceDir; without this
# skip, the fingerprint silently drops every Expo native module and OTAs reach stale binaries.
+ # Observe the owned host exit independently of descendants retaining its stdio.
+ "@muse-code/[email protected]": patches/@[email protected]
peerDependencyRules: