Skip to content

Commit 73ceaa3

Browse files
Radu028claude
andcommitted
fix(acp-registry): Copilot SDK Stop kills the CLI's processes on Linux and macOS
The SDK's forceStop SIGKILLs only the CLI, so a forced Stop left its shells and agents running outside Windows. T3 now freezes the CLI and kills every process under it first, as taskkill /T does on Windows. A mode switch Copilot answers with a compaction confirmation now stops the turn like a refused model switch, instead of being recorded as applied. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2c4a108 commit 73ceaa3

3 files changed

Lines changed: 163 additions & 9 deletions

File tree

‎packages/provider-acp-registry/src/server/copilotSdk.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,79 @@ export interface CopilotProcess {
5353
readonly exited: Promise<void>;
5454
/** SIGKILLs the process directly, for when the SDK no longer tracks it. */
5555
readonly kill: () => void;
56+
/**
57+
* Linux and macOS: freezes the CLI and SIGKILLs every process under it, which the SDK's kill
58+
* leaves running. Resolves with why it may have missed some.
59+
*/
60+
readonly killDescendants: () => Promise<string | undefined>;
5661
}
5762

5863
// A grandchild holding an inherited pipe can keep stdio open long after the exit.
5964
const STDIO_CLOSE_TIMEOUT_MS = 5_000;
65+
const PROCESS_LIST_TIMEOUT_MS = 5_000;
66+
67+
/** Pids under `rootPid` in a `ps -o pid=,ppid=` listing, each parent before its children. */
68+
export function descendantPids(listing: string, rootPid: number): ReadonlyArray<number> {
69+
const children = new Map<number, Array<number>>();
70+
for (const line of listing.split("\n")) {
71+
const [pid, ppid] = line.trim().split(/\s+/).map(Number);
72+
if (pid === undefined || ppid === undefined || !(pid > 1) || !Number.isSafeInteger(ppid)) {
73+
continue;
74+
}
75+
children.set(ppid, [...(children.get(ppid) ?? []), pid]);
76+
}
77+
const found: Array<number> = [];
78+
const seen = new Set([rootPid]);
79+
const pending = [rootPid];
80+
for (let parent = pending.shift(); parent !== undefined; parent = pending.shift()) {
81+
for (const child of children.get(parent) ?? []) {
82+
if (seen.has(child)) continue;
83+
seen.add(child);
84+
found.push(child);
85+
pending.push(child);
86+
}
87+
}
88+
return found;
89+
}
90+
91+
const listProcesses = () =>
92+
new Promise<string>((resolve, reject) => {
93+
NodeChildProcess.execFile(
94+
"ps",
95+
["-A", "-o", "pid=,ppid="],
96+
{ timeout: PROCESS_LIST_TIMEOUT_MS },
97+
(error, stdout) => (error ? reject(error) : resolve(stdout)),
98+
);
99+
});
100+
101+
const signalQuietly = (pid: number, signal: NodeJS.Signals) => {
102+
try {
103+
process.kill(pid, signal);
104+
} catch {
105+
// Already gone.
106+
}
107+
};
108+
109+
/** SIGKILLs the processes under `rootPid`; stopped first, so none can start another meanwhile. */
110+
async function killPosixDescendants(rootPid: number): Promise<string | undefined> {
111+
signalQuietly(rootPid, "SIGSTOP");
112+
const stopped: Array<number> = [];
113+
let failure: string | undefined;
114+
try {
115+
// The second listing catches processes started before the first round of stops landed.
116+
for (let pass = 0; pass < 2; pass += 1) {
117+
for (const pid of descendantPids(await listProcesses(), rootPid)) {
118+
if (pid === process.pid || stopped.includes(pid)) continue;
119+
signalQuietly(pid, "SIGSTOP");
120+
stopped.push(pid);
121+
}
122+
}
123+
} catch (cause) {
124+
failure = `listing Copilot's processes failed: ${cause instanceof Error ? cause.message : String(cause)}`;
125+
}
126+
for (const pid of [...stopped].reverse()) signalQuietly(pid, "SIGKILL");
127+
return failure;
128+
}
60129

61130
/**
62131
* Tracks the SDK client's CLI child. Its exit alone is too early: notifications can still sit
@@ -81,10 +150,13 @@ export function copilotClientProcess(client: object): CopilotProcess | undefined
81150
child.once("close", () => resolve());
82151
child.once("exit", () => setTimeout(resolve, STDIO_CLOSE_TIMEOUT_MS).unref());
83152
});
153+
const pid = child.pid;
84154
return {
85-
id: child.pid,
155+
id: pid,
86156
hasExited,
87157
kill: () => void child.kill("SIGKILL"),
158+
// Once the CLI exited its pid can be recycled, so only a live CLI's tree is ours.
159+
killDescendants: () => (hasExited() ? Promise.resolve(undefined) : killPosixDescendants(pid)),
88160
exited: stdioClosed
89161
.then(() => (typeof drain === "function" ? Reflect.apply(drain, connection, []) : undefined))
90162
.then(

‎packages/provider-acp-registry/src/server/copilotSdkAdapter.test.ts‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { AcpRegistrySettings } from "../settings.ts";
4949
import {
5050
copilotClientProcess,
5151
copilotSdkCliCandidates,
52+
descendantPids,
5253
type CopilotSdkClient,
5354
type CopilotSdkClientOptions,
5455
type CopilotSdkSession,
@@ -125,6 +126,7 @@ const makeFakeCopilot = Effect.fnUntraced(function* () {
125126
const switchFailures: Array<Error> = [];
126127
// Each entry refuses one permission-mode switch, reporting the mode Copilot kept.
127128
const permissionRefusals: Array<"allow-all" | "manual"> = [];
129+
const modeResults: Array<Awaited<ReturnType<CopilotSdkSession["rpc"]["mode"]["set"]>>> = [];
128130
const gate = () => {
129131
let release!: () => void;
130132
const promise = new Promise<void>((resolve) => {
@@ -171,7 +173,7 @@ const makeFakeCopilot = Effect.fnUntraced(function* () {
171173
mode: {
172174
set: async (params) => {
173175
record("mode.set", params);
174-
return { status: "applied", modelChanged: false };
176+
return modeResults.shift() ?? { status: "applied", modelChanged: false };
175177
},
176178
},
177179
permissions: {
@@ -281,6 +283,10 @@ const makeFakeCopilot = Effect.fnUntraced(function* () {
281283
record("process.kill");
282284
if (!stopFails) exitProcess();
283285
},
286+
killDescendants: async () => {
287+
record("killDescendants");
288+
return undefined;
289+
},
284290
},
285291
};
286292
};
@@ -331,6 +337,9 @@ const makeFakeCopilot = Effect.fnUntraced(function* () {
331337
refuseNextPermissionMode: (kept: (typeof permissionRefusals)[number]) => {
332338
permissionRefusals.push(kept);
333339
},
340+
queueModeResult: (result: (typeof modeResults)[number]) => {
341+
modeResults.push(result);
342+
},
334343
config: () => config,
335344
hangAbort: () => {
336345
hangAbort = true;
@@ -1486,7 +1495,9 @@ describe("CopilotSdkAdapterV2", () => {
14861495
const fake = yield* makeFakeCopilot();
14871496
fake.hangAbort();
14881497
const releaseExit = fake.holdExit();
1489-
const harness = yield* makeHarness(fake);
1498+
const harness = yield* makeHarness(fake).pipe(
1499+
Effect.provideService(HostProcess.Platform, "linux"),
1500+
);
14901501
yield* harness.runtime.startTurn(yield* turnInput(harness.providerThread));
14911502
const turnId = (yield* harness.takeRunningTurn()).id;
14921503
yield* fake.takeCall("sendAndWait");
@@ -1495,8 +1506,10 @@ describe("CopilotSdkAdapterV2", () => {
14951506
.pipe(Effect.forkScoped);
14961507
yield* fake.takeCall("abort");
14971508
yield* TestClock.adjust("30 seconds");
1509+
// The SDK's SIGKILL reaches only the CLI, so its shells and agents go first.
1510+
assert.deepInclude(yield* fake.nextCall, { method: "killDescendants" });
14981511
// forceStop has rejected the request; the process has not exited yet.
1499-
yield* fake.takeCall("forceStop");
1512+
assert.deepInclude(yield* fake.nextCall, { method: "forceStop" });
15001513
yield* releaseExit;
15011514
yield* Fiber.join(interrupting);
15021515
assert.deepInclude((yield* harness.untilTerminal()).at(-1), {
@@ -1727,9 +1740,52 @@ describe("CopilotSdkAdapterV2", () => {
17271740
args: [{ mode: "allow-all" }],
17281741
});
17291742
assert.deepInclude(yield* fake.nextCall, { method: "sendAndWait" });
1743+
yield* fake.finishRun();
1744+
yield* harness.untilTerminal();
1745+
// Leaving plan mode can restore a model the conversation no longer fits. Copilot asks for
1746+
// compaction and stays in plan mode, so the prompt must wait and the switch be retried.
1747+
fake.queueModeResult({
1748+
status: "confirmation_required",
1749+
modelChanged: false,
1750+
confirmation: {
1751+
targetModelDisplayName: "GPT-5.5",
1752+
currentTokens: 180000,
1753+
targetLimit: 128000,
1754+
},
1755+
});
1756+
const leavePlan = yield* harness.runtime
1757+
.startTurn({ ...gpt, providerTurnOrdinal: 8 })
1758+
.pipe(Effect.flip);
1759+
assert.include(makeProviderFailure({ cause: leavePlan }).message, "Send /compact");
1760+
assert.deepInclude(yield* fake.nextCall, {
1761+
method: "mode.set",
1762+
args: [{ mode: "interactive" }],
1763+
});
1764+
yield* harness.runtime.startTurn({ ...gpt, providerTurnOrdinal: 8 });
1765+
assert.deepInclude(yield* fake.nextCall, {
1766+
method: "mode.set",
1767+
args: [{ mode: "interactive" }],
1768+
});
1769+
yield* fake.takeCall("sendAndWait");
17301770
}).pipe(Effect.scoped, Effect.provide(testLayer)),
17311771
);
17321772

1773+
it("lists the processes under Copilot's CLI from a ps listing", () => {
1774+
const listing = [
1775+
" 1 0",
1776+
" 40 1",
1777+
"100 40",
1778+
"101 100",
1779+
"102 101",
1780+
"103 100",
1781+
"200 1",
1782+
"",
1783+
];
1784+
// Breadth first, so killing in reverse reaches children before their parents.
1785+
assert.deepStrictEqual(descendantPids(listing.join("\n"), 100), [101, 103, 102]);
1786+
assert.deepStrictEqual(descendantPids(listing.join("\n"), 102), []);
1787+
});
1788+
17331789
it.effect(
17341790
"opens Copilot sessions with T3's system message, MCP server, delegation, tier and discovery",
17351791
() =>

‎packages/provider-acp-registry/src/server/copilotSdkAdapter.ts‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -673,8 +673,8 @@ export const makeCopilotSdkAdapterV2 = Effect.fn("makeCopilotSdkAdapterV2")(func
673673
);
674674
return created;
675675
});
676-
// The SDK's kill reaches only copilot.exe on Windows; taskkill /T also stops its shells and agents.
677-
const killProcessTree = Effect.fnUntraced(function* (pid: number) {
676+
// The SDK's kill reaches only the CLI; taskkill /T also stops its shells and agents.
677+
const killWindowsProcessTree = Effect.fnUntraced(function* (pid: number) {
678678
const exitCode = yield* Effect.scoped(
679679
Effect.gen(function* () {
680680
const taskkill = yield* spawner.spawn(
@@ -692,10 +692,22 @@ export const makeCopilotSdkAdapterV2 = Effect.fn("makeCopilotSdkAdapterV2")(func
692692
/** Kills the client's process tree; returns why it may not all have stopped. */
693693
const terminate = Effect.fnUntraced(function* (target: CopilotSdkClient) {
694694
// Once the process exited its pid can be recycled, so only a live process is ours to kill.
695+
const live =
696+
target.process !== undefined && !target.process.hasExited() ? target.process : undefined;
695697
const treeFailure =
696-
platform === "win32" && target.process !== undefined && !target.process.hasExited()
697-
? yield* killProcessTree(target.process.id)
698-
: undefined;
698+
live === undefined
699+
? undefined
700+
: platform === "win32"
701+
? yield* killWindowsProcessTree(live.id)
702+
: yield* Effect.tryPromise(() => live.killDescendants()).pipe(
703+
Effect.timeoutOption(CLIENT_STOP_TIMEOUT),
704+
Effect.map((killed) =>
705+
Option.isSome(killed)
706+
? killed.value
707+
: "stopping Copilot's processes did not finish",
708+
),
709+
Effect.orElseSucceed(() => "stopping Copilot's processes failed"),
710+
);
699711
// forceStop rejects when the CLI outlives its SIGKILL.
700712
const stopped = yield* Effect.tryPromise(() => target.forceStop()).pipe(
701713
Effect.timeoutOption(CLIENT_STOP_TIMEOUT),
@@ -2507,6 +2519,20 @@ export const makeCopilotSdkAdapterV2 = Effect.fn("makeCopilotSdkAdapterV2")(func
25072519
const switched = yield* call("mode switch", () =>
25082520
target.rpc.mode.set({ mode: settings.mode }),
25092521
);
2522+
// Leaving plan mode can restore a model the conversation no longer fits; Copilot then
2523+
// asks for compaction instead of switching, as model.switchTo does below.
2524+
const confirmation = switched.confirmation;
2525+
if (confirmation !== undefined) {
2526+
applied = {};
2527+
return yield* new CopilotModelSwitchError({
2528+
model: confirmation.targetModelDisplayName,
2529+
currentTokens: confirmation.currentTokens,
2530+
targetLimit: confirmation.targetLimit,
2531+
});
2532+
}
2533+
if (switched.modeApplied === false) {
2534+
return yield* protocolError(`Copilot did not switch to ${settings.mode} mode`);
2535+
}
25102536
// A configured plan model can come with the mode; the model switch below sets it back.
25112537
applied = switched.modelChanged
25122538
? { ...applied, mode: settings.mode, model: undefined, reasoningEffort: undefined }

0 commit comments

Comments
 (0)