Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): tell the agent when the memory watchdog stops its command (#109213)

posthog[bot]8662d7eff357
diff --git a/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md b/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
index a420256120e3..8605b23452ad 100644
--- a/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
+++ b/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
@@ -45,6 +45,7 @@ Fork of `@anthropic-ai/claude-agent-acp`. Upstream repo: https://github.com/anth
of upstream's raw-explanation `agent_message_chunk` (supersedes the v0.42.0
"Refusal handling" port and the v0.44.0 `model_refusal_fallback` skip)
- SettingsManager `PreToolUse` hook for permission rules
+- Sandbox memory watchdog notice (`session/memory-kill-hook.ts`): `PostToolUse`/`PostToolUseFailure` hook that tells the agent when the watchdog stopped a Bash process tree
- `ensureLocalSettings` / `clearStatsigCache`
- `ELECTRON_RUN_AS_NODE` / `ENABLE_TOOL_SEARCH` env vars
- `machine-auth.ts` (`MachineClaudeAuth`, `applyMachineClaudeAuth`): strips gateway/telemetry env
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts
new file mode 100644
index 000000000000..6f0b2306912e
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts
@@ -0,0 +1,126 @@
+import { appendFile, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { HookInput } from "@anthropic-ai/claude-agent-sdk";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { MemoryWatchdogKillReader } from "../../../server/memory-watchdog";
+import { Logger } from "../../../utils/logger";
+import { createMemoryKillNoticeHook } from "./memory-kill-hook";
+
+const GIB = 1024 ** 3;
+const STARTED_AT_SECONDS = 1_800_000_000;
+
+function killRecord(pid: number, ts: number): string {
+ return JSON.stringify({
+ event: "kill",
+ ts,
+ pid,
+ comm: "bash",
+ tree_rss: 22 * GIB,
+ current: 27 * GIB,
+ limit: 32 * GIB,
+ signal: "SIGKILL",
+ });
+}
+
+function shellInput(
+ hookEventName: "PostToolUse" | "PostToolUseFailure",
+ toolName = "Bash",
+ error = "Exit code 137",
+): HookInput {
+ return {
+ session_id: "s",
+ transcript_path: "/tmp/t",
+ cwd: "/tmp",
+ hook_event_name: hookEventName,
+ tool_name: toolName,
+ tool_input: { command: "pnpm test" },
+ tool_use_id: "toolu_1",
+ ...(hookEventName === "PostToolUse" ? { tool_response: "" } : { error }),
+ } as unknown as HookInput;
+}
+
+type HookOutput = {
+ hookSpecificOutput?: { hookEventName: string; additionalContext: string };
+};
+
+describe("createMemoryKillNoticeHook", () => {
+ let dir: string;
+ let path: string;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), "memory-kill-hook-"));
+ path = join(dir, "events.jsonl");
+ });
+
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ it.each([
+ ["PostToolUse", "Bash"],
+ ["PostToolUseFailure", "Bash"],
+ ["PostToolUse", "BashOutput"],
+ ] as const)(
+ "tells the agent about a new kill once after a %s %s call",
+ async (hookEventName, toolName) => {
+ await writeFile(
+ path,
+ `${killRecord(7, STARTED_AT_SECONDS - 60)}\n${killRecord(8, STARTED_AT_SECONDS + 5)}\n`,
+ );
+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {
+ reader: new MemoryWatchdogKillReader(path),
+ startedAtMs: STARTED_AT_SECONDS * 1000,
+ killRecordWaitMs: 0,
+ });
+ const opts = { signal: new AbortController().signal };
+
+ const first = (await hook(
+ shellInput(hookEventName, toolName),
+ "toolu_1",
+ opts,
+ )) as HookOutput;
+ const second = await hook(
+ shellInput(hookEventName, toolName),
+ "toolu_2",
+ opts,
+ );
+
+ expect(first.hookSpecificOutput?.hookEventName).toBe(hookEventName);
+ const context = first.hookSpecificOutput?.additionalContext ?? "";
+ expect(context).toContain("(pid 8) with SIGKILL");
+ expect(context).toContain("22.0 GiB");
+ expect(context).not.toContain("pid 7");
+ expect(second).toEqual({ continue: true });
+ },
+ );
+
+ it("waits for a kill record written after Bash exits with a signal code", async () => {
+ await writeFile(path, "");
+ const reader = new MemoryWatchdogKillReader(path);
+ const read = reader.readNewKills.bind(reader);
+ let reads = 0;
+ reader.readNewKills = async () => {
+ const kills = await read();
+ reads += 1;
+ if (reads === 1) {
+ await appendFile(path, `${killRecord(8, STARTED_AT_SECONDS + 5)}\n`);
+ }
+ return kills;
+ };
+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {
+ reader,
+ startedAtMs: STARTED_AT_SECONDS * 1000,
+ killRecordWaitMs: 60_000,
+ killRecordPollMs: 1,
+ });
+
+ const result = (await hook(
+ shellInput("PostToolUseFailure", "Bash", "Exit code 143"),
+ "toolu_1",
+ { signal: new AbortController().signal },
+ )) as HookOutput;
+
+ expect(result.hookSpecificOutput?.additionalContext).toContain("(pid 8)");
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.ts b/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.ts
new file mode 100644
index 000000000000..3e49e8129213
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/memory-kill-hook.ts
@@ -0,0 +1,108 @@
+import { setTimeout as sleep } from "node:timers/promises";
+import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";
+import type { ProcessKilledParams } from "../../../acp-extensions";
+import { MemoryWatchdogKillReader } from "../../../server/memory-watchdog";
+import type { Logger } from "../../../utils/logger";
+
+const BYTES_PER_GIB = 1024 ** 3;
+// BashOutput and TaskOutput return the result of a background Bash command,
+// which the watchdog can stop after the Bash call itself has returned.
+const SHELL_RESULT_TOOLS = new Set(["Bash", "BashOutput", "TaskOutput"]);
+const SIGNAL_EXIT_PATTERN = /exit[ _]?code"?\s*:?\s*(137|143)\b/i;
+// The watchdog writes the kill record only after the process tree is gone
+// and memory is below the trigger. That takes up to two grace periods of
+// 2 seconds each, so the record can arrive after the shell has exited.
+const KILL_RECORD_WAIT_MS = 5_000;
+const KILL_RECORD_POLL_MS = 250;
+
+function formatGib(bytes: number): string {
+ return `${(bytes / BYTES_PER_GIB).toFixed(1)} GiB`;
+}
+
+export function formatMemoryKillNotice(kills: ProcessKilledParams[]): string {
+ const lines = kills.map(
+ (kill) =>
+ `- ${kill.at}: stopped \`${kill.comm}\` (pid ${kill.pid}) with ${kill.signal}. Its process tree used ${formatGib(kill.treeRssBytes)}. Sandbox memory was at ${formatGib(kill.memoryCurrentBytes)} of ${formatGib(kill.memoryLimitBytes)}.`,
+ );
+ return [
+ "## Sandbox memory watchdog",
+ "",
+ "The sandbox stopped a shell command because the sandbox was close to its memory limit:",
+ ...lines,
+ "",
+ "The exit status of that command is from this stop, not from the command itself.",
+ "If you run the same command again without changes, the sandbox will stop it again.",
+ "Run a smaller command instead: fewer test files, fewer parallel workers, or one package at a time.",
+ ].join("\n");
+}
+
+export interface MemoryKillNoticeHookOptions {
+ reader?: MemoryWatchdogKillReader;
+ startedAtMs?: number;
+ killRecordWaitMs?: number;
+ killRecordPollMs?: number;
+}
+
+function endedBySignal(input: HookInput): boolean {
+ const result =
+ input.hook_event_name === "PostToolUseFailure"
+ ? input.error
+ : input.hook_event_name === "PostToolUse"
+ ? input.tool_response
+ : undefined;
+ const text = typeof result === "string" ? result : JSON.stringify(result);
+ return SIGNAL_EXIT_PATTERN.test(text ?? "");
+}
+
+// The Bash tool only sees an exit code when the watchdog stops its process
+// tree, so without this notice the agent reruns the same command.
+export const createMemoryKillNoticeHook = (
+ logger: Logger,
+ {
+ reader = new MemoryWatchdogKillReader(),
+ startedAtMs = Date.now(),
+ killRecordWaitMs = KILL_RECORD_WAIT_MS,
+ killRecordPollMs = KILL_RECORD_POLL_MS,
+ }: MemoryKillNoticeHookOptions = {},
+): HookCallback => {
+ const readKills = async (): Promise<ProcessKilledParams[]> =>
+ (await reader.readNewKills()).filter(
+ (kill) => Date.parse(kill.at) >= startedAtMs,
+ );
+
+ return async (input: HookInput, _toolUseId, { signal }) => {
+ if (
+ input.hook_event_name !== "PostToolUse" &&
+ input.hook_event_name !== "PostToolUseFailure"
+ ) {
+ return { continue: true };
+ }
+ if (!SHELL_RESULT_TOOLS.has(input.tool_name)) return { continue: true };
+
+ let kills: ProcessKilledParams[];
+ try {
+ kills = await readKills();
+ if (kills.length === 0 && endedBySignal(input)) {
+ const deadline = Date.now() + killRecordWaitMs;
+ while (kills.length === 0 && Date.now() < deadline && !signal.aborted) {
+ await sleep(killRecordPollMs);
+ kills = await readKills();
+ }
+ }
+ } catch (error) {
+ logger.debug("Memory watchdog events read failed", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return { continue: true };
+ }
+ if (kills.length === 0) return { continue: true };
+
+ return {
+ continue: true,
+ hookSpecificOutput: {
+ hookEventName: input.hook_event_name,
+ additionalContext: formatMemoryKillNotice(kills),
+ },
+ };
+ };
+};
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
index 3e5f0581fc7d..2a4aeaa07bbc 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -5,6 +5,7 @@ import * as path from "node:path";
import type { Readable, Writable } from "node:stream";
import type {
CanUseTool,
+ HookCallback,
McpServerConfig,
Options,
OutputFormat,
@@ -53,6 +54,7 @@ import { type CodeExecutionMode, toSdkPermissionMode } from "../tools";
import type { EffortLevel } from "../types";
import type { RunBudgetGuard } from "./budget-guard";
import { loadUserClaudeJsonMcpServers } from "./mcp-config";
+import { createMemoryKillNoticeHook } from "./memory-kill-hook";
import { DEFAULT_MODEL, resolveFallbackModel } from "./models";
import { createRtkRewriteHook } from "./rtk-hook";
import type { SettingsManager } from "./settings";
@@ -412,6 +414,13 @@ function buildHooks(
preToolUseHooks.push(createRtkRewriteHook(rtkPrefix, logger));
}
+ const postToolUseFailureHooks: HookCallback[] = [];
+ if (cloudMode) {
+ const memoryKillNoticeHook = createMemoryKillNoticeHook(logger);
+ postToolUseHooks.push(memoryKillNoticeHook);
+ postToolUseFailureHooks.push(memoryKillNoticeHook);
+ }
+
const taskHook = createTaskHook(taskState, onTaskStateChange);
return {
@@ -420,6 +429,10 @@ function buildHooks(
...(userHooks?.PostToolUse || []),
{ hooks: postToolUseHooks },
],
+ PostToolUseFailure: [
+ ...(userHooks?.PostToolUseFailure || []),
+ { hooks: postToolUseFailureHooks },
+ ],
PreToolUse: [...(userHooks?.PreToolUse || []), { hooks: preToolUseHooks }],
TaskCreated: [...(userHooks?.TaskCreated || []), { hooks: [taskHook] }],
TaskCompleted: [...(userHooks?.TaskCompleted || []), { hooks: [taskHook] }],
diff --git a/products/desktop/packages/agent/src/server/memory-watchdog.test.ts b/products/desktop/packages/agent/src/server/memory-watchdog.test.ts
index 003e11a511d7..86b017a90e11 100644
--- a/products/desktop/packages/agent/src/server/memory-watchdog.test.ts
+++ b/products/desktop/packages/agent/src/server/memory-watchdog.test.ts
@@ -14,6 +14,7 @@ import { Logger } from "../utils/logger";
import {
CliProcessRegistry,
JsonlTail,
+ MemoryWatchdogKillReader,
MemoryWatchdogWatcher,
toProcessKilledParams,
} from "./memory-watchdog";
@@ -162,6 +163,19 @@ describe("memory watchdog", () => {
]);
});
+ it("reports a kill to only one of two overlapping reads", async () => {
+ await writeFile(path, `${JSON.stringify(KILL_RECORD)}\n`);
+ const reader = new MemoryWatchdogKillReader(path);
+
+ const reads = await Promise.all([
+ reader.readNewKills(),
+ reader.readNewKills(),
+ ]);
+
+ expect(reads.flat()).toEqual([KILL_PARAMS]);
+ expect(await reader.readNewKills()).toEqual([]);
+ });
+
it.each([
{
name: "keeps the other pid after one of two exits",
diff --git a/products/desktop/packages/agent/src/server/memory-watchdog.ts b/products/desktop/packages/agent/src/server/memory-watchdog.ts
index d4ce3bb3806e..4399e541fee3 100644
--- a/products/desktop/packages/agent/src/server/memory-watchdog.ts
+++ b/products/desktop/packages/agent/src/server/memory-watchdog.ts
@@ -111,6 +111,55 @@ export function isTaskRunSandbox(env: NodeJS.ProcessEnv): boolean {
return Boolean(env.POSTHOG_TASK_RUN_ID);
}
+export class MemoryWatchdogKillReader {
+ private readonly tail = new JsonlTail();
+ private inode: number | null = null;
+ private reads: Promise<unknown> = Promise.resolve();
+
+ constructor(readonly path: string = MEMORY_WATCHDOG_EVENTS_PATH) {}
+
+ // Parallel tool calls run their hooks at the same time. Two overlapping
+ // reads would read from the same offset and report the same kills twice.
+ readNewKills(): Promise<ProcessKilledParams[]> {
+ const read = this.reads.then(() => this.readOnce());
+ this.reads = read.catch(() => undefined);
+ return read;
+ }
+
+ private async readOnce(): Promise<ProcessKilledParams[]> {
+ let size: number;
+ let inode: number;
+ try {
+ const stats = await stat(this.path);
+ size = stats.size;
+ inode = stats.ino;
+ } catch {
+ return [];
+ }
+ if (this.inode !== null && inode !== this.inode) this.tail.reset();
+ this.inode = inode;
+ if (size < this.tail.position) this.tail.reset();
+ if (size === this.tail.position) return [];
+ const length = Math.min(size - this.tail.position, MAX_READ_BYTES);
+ const handle = await open(this.path, "r");
+ try {
+ const buffer = Buffer.alloc(length);
+ const { bytesRead } = await handle.read(
+ buffer,
+ 0,
+ length,
+ this.tail.position,
+ );
+ return this.tail
+ .consume(buffer.subarray(0, bytesRead))
+ .map(toProcessKilledParams)
+ .filter((params): params is ProcessKilledParams => params !== null);
+ } finally {
+ await handle.close();
+ }
+ }
+}
+
export interface MemoryWatchdogWatcherOptions {
onProcessKilled: (params: ProcessKilledParams) => void;
logger: Logger;
@@ -119,22 +168,20 @@ export interface MemoryWatchdogWatcherOptions {
}
export class MemoryWatchdogWatcher {
- private readonly path: string;
+ private readonly reader: MemoryWatchdogKillReader;
private readonly intervalMs: number;
- private readonly tail = new JsonlTail();
private timer: ReturnType<typeof setInterval> | null = null;
private polling = false;
- private inode: number | null = null;
constructor(private readonly options: MemoryWatchdogWatcherOptions) {
- this.path = options.path ?? MEMORY_WATCHDOG_EVENTS_PATH;
+ this.reader = new MemoryWatchdogKillReader(options.path);
this.intervalMs = options.intervalMs ?? POLL_INTERVAL_MS;
}
async start(): Promise<boolean> {
if (this.timer) return true;
try {
- await access(dirname(this.path), fsConstants.W_OK);
+ await access(dirname(this.reader.path), fsConstants.W_OK);
} catch {
return false;
}
@@ -155,7 +202,7 @@ export class MemoryWatchdogWatcher {
if (this.polling) return;
this.polling = true;
try {
- for (const params of await this.readNewKills()) {
+ for (const params of await this.reader.readNewKills()) {
this.options.onProcessKilled(params);
}
} catch (error) {
@@ -166,39 +213,6 @@ export class MemoryWatchdogWatcher {
this.polling = false;
}
}
-
- private async readNewKills(): Promise<ProcessKilledParams[]> {
- let size: number;
- let inode: number;
- try {
- const stats = await stat(this.path);
- size = stats.size;
- inode = stats.ino;
- } catch {
- return [];
- }
- if (this.inode !== null && inode !== this.inode) this.tail.reset();
- this.inode = inode;
- if (size < this.tail.position) this.tail.reset();
- if (size === this.tail.position) return [];
- const length = Math.min(size - this.tail.position, MAX_READ_BYTES);
- const handle = await open(this.path, "r");
- try {
- const buffer = Buffer.alloc(length);
- const { bytesRead } = await handle.read(
- buffer,
- 0,
- length,
- this.tail.position,
- );
- return this.tail
- .consume(buffer.subarray(0, bytesRead))
- .map(toProcessKilledParams)
- .filter((params): params is ProcessKilledParams => params !== null);
- } finally {
- await handle.close();
- }
- }
}
export class CliProcessRegistry {