Skip to content

Commit 4589d85

Browse files
authored
fix(gateway): stop agent terminal processes after session archive (#125784)
* fix(gateway): stop terminal PTYs on session archive Bind agent terminals to the durable session incarnation, drain exact ownership during archive, and terminate every job-control process group in the PTY session.\n\nCloses #125769 * test(gateway): cover terminal cleanup on archive * test(gateway): align terminal outcome assertions * test(gateway): preserve session exports in invoke test * fix(gateway): await terminal exit before archive * test(codex): consolidate supervised instruction coverage Move the duplicated two-attempt regression into the canonical thread lifecycle test so the exact two-worker extension shard stays bounded on low-core CI.\n\nRelated: #125783
1 parent 68f808f commit 4589d85

31 files changed

Lines changed: 860 additions & 298 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3133,7 +3133,6 @@ src/gateway/talk-agent-consult.ts 3
31333133
src/gateway/talk-realtime-relay-forced-consults.ts 1
31343134
src/gateway/talk-realtime-relay-session-create.ts 1
31353135
src/gateway/terminal/node-relay.ts 1
3136-
src/gateway/terminal/session-manager.ts 1
31373136
src/gateway/test-http-response.ts 4
31383137
src/gateway/test-temp-config.ts 1
31393138
src/gateway/tools-invoke-http.ts 1

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 0 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -4059,95 +4059,6 @@ describe("runCodexAppServerAttempt", () => {
40594059
expect(resumedInstructions).not.toContain(updatedGuidance);
40604060
});
40614061

4062-
it("freezes external-cwd agent instructions across supervised materialization", async () => {
4063-
const { sessionFile, workspaceDir: executionDir } = createRunPaths();
4064-
const agentWorkspaceDir = path.join(tempDir, "agent-workspace");
4065-
const sourceThreadId = "thread-source";
4066-
const probeThreadId = "thread-probe";
4067-
const materializedThreadId = "thread-materialized";
4068-
const agentsGuidance = "Follow the frozen supervised AGENTS guidance.";
4069-
const updatedGuidance = "Updated supervised guidance belongs to a new session.";
4070-
const supervisionPluginConfig = { supervision: { enabled: true } } as const;
4071-
await fs.mkdir(executionDir, { recursive: true });
4072-
await fs.mkdir(agentWorkspaceDir, { recursive: true });
4073-
await fs.writeFile(path.join(agentWorkspaceDir, "AGENTS.md"), agentsGuidance);
4074-
await fs.writeFile(path.join(executionDir, "AGENTS.md"), "Execution project instructions");
4075-
const supervisionAppServer = resolveCodexSupervisionAppServerRuntimeOptions({
4076-
pluginConfig: supervisionPluginConfig,
4077-
});
4078-
await writeExistingBinding(sessionFile, executionDir, {
4079-
threadId: sourceThreadId,
4080-
connectionScope: "supervision",
4081-
supervisionSourceThreadId: sourceThreadId,
4082-
preserveNativeModel: true,
4083-
pendingSupervisionBranch: {
4084-
sourceThreadId,
4085-
connectionFingerprint: buildCodexAppServerConnectionFingerprint(supervisionAppServer),
4086-
},
4087-
conversationSourceTransferComplete: true,
4088-
historyCoveredThrough: new Date(0).toISOString(),
4089-
});
4090-
const materializeHarness = createAppServerHarness(async (method) => {
4091-
if (method === "thread/read") {
4092-
return { thread: threadStartResult(sourceThreadId).thread };
4093-
}
4094-
if (method === "thread/fork") {
4095-
return threadStartResult(probeThreadId);
4096-
}
4097-
if (method === "thread/start") {
4098-
return threadStartResult(materializedThreadId);
4099-
}
4100-
if (method === "turn/start") {
4101-
return turnStartResult();
4102-
}
4103-
return {};
4104-
});
4105-
const params = createParams(sessionFile, executionDir);
4106-
params.bootstrapWorkspaceDir = agentWorkspaceDir;
4107-
setAgentWorkspaceForTest(params, agentWorkspaceDir);
4108-
4109-
const run = runCodexAppServerAttempt(params, {
4110-
pluginConfig: supervisionPluginConfig,
4111-
});
4112-
await materializeHarness.waitForMethod("turn/start");
4113-
await materializeHarness.completeTurn({ threadId: materializedThreadId, turnId: "turn-1" });
4114-
await run;
4115-
4116-
await fs.writeFile(path.join(agentWorkspaceDir, "AGENTS.md"), updatedGuidance);
4117-
const resumeHarness = createAppServerHarness(async (method) => {
4118-
if (method === "thread/read") {
4119-
return { thread: threadStartResult(materializedThreadId).thread };
4120-
}
4121-
if (method === "thread/resume") {
4122-
return threadStartResult(materializedThreadId);
4123-
}
4124-
if (method === "turn/start") {
4125-
return turnStartResult("turn-2");
4126-
}
4127-
return {};
4128-
});
4129-
const resumeParams = createParams(sessionFile, executionDir);
4130-
resumeParams.bootstrapWorkspaceDir = agentWorkspaceDir;
4131-
setAgentWorkspaceForTest(resumeParams, agentWorkspaceDir);
4132-
const resumedRun = runCodexAppServerAttempt(resumeParams, {
4133-
pluginConfig: supervisionPluginConfig,
4134-
});
4135-
await resumeHarness.waitForMethod("turn/start");
4136-
await resumeHarness.completeTurn({ threadId: materializedThreadId, turnId: "turn-2" });
4137-
await resumedRun;
4138-
4139-
const threadResume = resumeHarness.requests.find(
4140-
(request) => request.method === "thread/resume",
4141-
);
4142-
if (!threadResume) {
4143-
throw new Error("expected thread/resume request");
4144-
}
4145-
const resumedInstructions =
4146-
(threadResume.params as { developerInstructions?: string }).developerInstructions ?? "";
4147-
expect(resumedInstructions).toContain(agentsGuidance);
4148-
expect(resumedInstructions).not.toContain(updatedGuidance);
4149-
});
4150-
41514062
it("injects bounded MEMORY.md when memory tools are unavailable", async () => {
41524063
const { sessionFile, workspaceDir } = createRunPaths();
41534064
const memorySummary = "Memory summary goes here.";

‎extensions/codex/src/app-server/thread-lifecycle.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3173,11 +3173,12 @@ describe("Codex app-server supervised branch lifecycle", () => {
31733173
vi.restoreAllMocks();
31743174
});
31753175

3176-
it("materializes a model-locked canonical branch and injects the same visible snapshot once", async () => {
3176+
it("materializes a model-locked canonical branch with frozen agent instructions", async () => {
31773177
const sourceThreadId = "thread-source";
31783178
const probeThreadId = "thread-probe";
31793179
const finalThreadId = "thread-final";
31803180
const lastTurnId = "turn-terminal";
3181+
const agentWorkspaceDeveloperInstructions = "Follow the frozen supervised AGENTS guidance.";
31813182
const workspaceDir = path.join(tempDir, "workspace");
31823183
const attempt = createThreadLifecycleParams(path.join(tempDir, "session.jsonl"), workspaceDir);
31833184
attempt.modelId = "outer-global-default";
@@ -3244,6 +3245,8 @@ describe("Codex app-server supervised branch lifecycle", () => {
32443245
params: attempt,
32453246
cwd: workspaceDir,
32463247
dynamicTools,
3248+
developerInstructions: agentWorkspaceDeveloperInstructions,
3249+
agentWorkspaceDeveloperInstructions,
32473250
environmentSelection: [{ environmentId: "local", cwd: workspaceDir }],
32483251
shellEnvironment: { GH_TOKEN: "", GITHUB_TOKEN: "" },
32493252
disableLoginShell: true,
@@ -3269,6 +3272,7 @@ describe("Codex app-server supervised branch lifecycle", () => {
32693272
threadId: sourceThreadId,
32703273
lastTurnId,
32713274
excludeTurns: true,
3275+
developerInstructions: agentWorkspaceDeveloperInstructions,
32723276
config: {
32733277
allow_login_shell: false,
32743278
shell_environment_policy: {
@@ -3285,6 +3289,7 @@ describe("Codex app-server supervised branch lifecycle", () => {
32853289
expect(startParams).toMatchObject({
32863290
model: "native-effective",
32873291
modelProvider: "native-provider",
3292+
developerInstructions: agentWorkspaceDeveloperInstructions,
32883293
dynamicTools,
32893294
environments: [{ environmentId: "local", cwd: workspaceDir }],
32903295
config: {
@@ -3320,6 +3325,7 @@ describe("Codex app-server supervised branch lifecycle", () => {
33203325
model: "native-effective",
33213326
modelProvider: "native-provider",
33223327
preserveNativeModel: true,
3328+
agentWorkspaceDeveloperInstructions,
33233329
conversationSourceTransferComplete: true,
33243330
lifecycle: { action: "forked" },
33253331
});
@@ -3330,6 +3336,7 @@ describe("Codex app-server supervised branch lifecycle", () => {
33303336
model: "native-effective",
33313337
modelProvider: "native-provider",
33323338
preserveNativeModel: true,
3339+
agentWorkspaceDeveloperInstructions,
33333340
conversationSourceTransferComplete: true,
33343341
appServerRuntimeFingerprint: buildCodexAppServerConnectionFingerprint(commonParams.appServer),
33353342
});
@@ -3344,6 +3351,9 @@ describe("Codex app-server supervised branch lifecycle", () => {
33443351
expect(request.mock.calls[0]?.[1]).toEqual({ threadId: finalThreadId, includeTurns: false });
33453352
expect(request.mock.calls[1]?.[1]).not.toHaveProperty("model");
33463353
expect(request.mock.calls[1]?.[1]).not.toHaveProperty("modelProvider");
3354+
expect(request.mock.calls[1]?.[1]).toMatchObject({
3355+
developerInstructions: agentWorkspaceDeveloperInstructions,
3356+
});
33473357
expect(resumed).toMatchObject({
33483358
threadId: finalThreadId,
33493359
preserveNativeModel: true,

‎packages/agent-core/src/harness/env/kill-tree.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,48 @@ export function signalProcessTree(
8484
opts?.onComplete?.();
8585
}
8686

87+
/** Signals every process group and process still owned by one forkpty session. */
88+
export function signalPtySessionTree(pid: number, signal: "SIGTERM" | "SIGKILL"): void {
89+
if (!Number.isFinite(pid) || pid <= 0) {
90+
return;
91+
}
92+
if (process.platform === "win32") {
93+
void signalProcessTreeWindowsAndWait(pid, signal);
94+
return;
95+
}
96+
const darwinTty = process.platform === "darwin" ? readDarwinPtyTty(pid) : undefined;
97+
if (process.platform === "darwin" && !darwinTty) {
98+
signalProcessTreeUnix(pid, signal, true);
99+
return;
100+
}
101+
const members = readProcessSessionMembers(pid, darwinTty);
102+
if (!members) {
103+
signalProcessTreeUnix(pid, signal, true);
104+
return;
105+
}
106+
const signalMembers = (snapshot: Array<{ pid: number; pgid: number }>) => {
107+
const groups = new Set(snapshot.map((member) => member.pgid));
108+
groups.delete(pid);
109+
for (const pgid of groups) {
110+
signalUnixTarget(-pgid, signal);
111+
}
112+
for (const member of snapshot) {
113+
if (member.pid !== pid) {
114+
signalUnixTarget(member.pid, signal);
115+
}
116+
}
117+
};
118+
signalMembers(members);
119+
// Keep the leader alive through the rescan: Darwin drops the controlling-tty
120+
// lookup once the session leader exits.
121+
const remaining = readProcessSessionMembers(pid, darwinTty);
122+
if (remaining) {
123+
signalMembers(remaining);
124+
}
125+
signalUnixTarget(-pid, signal);
126+
signalUnixTarget(pid, signal);
127+
}
128+
87129
function normalizeGraceMs(value?: number): number {
88130
if (typeof value !== "number" || !Number.isFinite(value)) {
89131
return DEFAULT_GRACE_MS;
@@ -141,6 +183,53 @@ function readProcessGroupIdFromProc(pid: number): number | undefined {
141183
}
142184
}
143185

186+
function readDarwinPtyTty(sessionLeaderPid: number): string | undefined {
187+
try {
188+
// Darwin ps omits numeric SIDs. A forkpty session exclusively owns its
189+
// controlling tty, resolved here from the trusted spawn-time leader.
190+
const leader = spawnSync("ps", ["-p", String(sessionLeaderPid), "-o", "tty="], {
191+
encoding: "utf8",
192+
timeout: 500,
193+
});
194+
const tty = leader.stdout.trim();
195+
if (leader.error || leader.status !== 0 || !tty || tty === "?" || tty === "??") {
196+
return undefined;
197+
}
198+
return tty;
199+
} catch {
200+
return undefined;
201+
}
202+
}
203+
204+
function readProcessSessionMembers(
205+
sessionId: number,
206+
darwinTty?: string,
207+
): Array<{ pid: number; pgid: number }> | undefined {
208+
try {
209+
const expectedSession = darwinTty ?? String(sessionId);
210+
const args = darwinTty ? ["-t", darwinTty, "-o", "pid=,pgid="] : ["-axo", "pid=,pgid=,sid="];
211+
const result = spawnSync("ps", args, {
212+
encoding: "utf8",
213+
timeout: 500,
214+
});
215+
if (result.error || result.status !== 0) {
216+
return undefined;
217+
}
218+
const members: Array<{ pid: number; pgid: number }> = [];
219+
for (const line of result.stdout.split("\n")) {
220+
const [pidText, pgidText, session] = line.trim().split(/\s+/);
221+
const pid = parseProcessGroupId(pidText);
222+
const pgid = parseProcessGroupId(pgidText);
223+
if (pid && pgid && (darwinTty || session === expectedSession)) {
224+
members.push({ pid, pgid });
225+
}
226+
}
227+
return members;
228+
} catch {
229+
return undefined;
230+
}
231+
}
232+
144233
/** Fail closed to direct-PID signaling when group ownership cannot be proved. */
145234
function isProcessGroupLeader(pid: number): boolean {
146235
// Linux exposes the fact in procfs; avoid a synchronous child process on the common path.
@@ -170,6 +259,14 @@ function signalProcessTreeUnix(
170259
}
171260
}
172261

262+
function signalUnixTarget(pid: number, signal: "SIGTERM" | "SIGKILL"): void {
263+
try {
264+
process.kill(pid, signal);
265+
} catch {
266+
// Already gone or not signalable; remaining exact targets still run.
267+
}
268+
}
269+
173270
function runTaskkill(args: string[], onExit?: (code: number | null) => void): Promise<void> {
174271
return new Promise((resolve) => {
175272
let settled = false;

‎src/agents/openclaw-tools.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,7 @@ export function createOpenClawTools(
531531
createTerminalTool({
532532
agentId: sessionAgentId,
533533
agentSessionKey: options?.runSessionKey ?? options?.agentSessionKey,
534+
sessionId: options?.sessionId,
534535
runId: options?.runId,
535536
}),
536537
createPortalTool(),

0 commit comments

Comments
 (0)