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): stop capped runs before the gateway refuses them (#109004)

posthog[bot]b2cb6ed24e92
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.md
index ccd65b58e8de..3ebd0ab6c5b5 100644
--- a/products/desktop/packages/agent/README.md
+++ b/products/desktop/packages/agent/README.md
@@ -165,7 +165,7 @@ Required environment variables (validated by zod in `src/server/bin.ts`):
Optional behavior toggles:
-- `AI_GATEWAY_TOKEN_CAP_USD` — the per-run spend cap of the gateway token the cloud worker minted for the sandbox. When set on a cloud run, the Claude adapter arms the run budget guard: it prices every assistant message, snaps to the SDK's cumulative cost at turn end, steers the live turn at 50% (ship what is on disk, skip polish) and 70% (commit and stop) of the cap, and denies new `Agent`, `Task`, `Workflow`, `WebFetch` and `WebSearch` calls once critical. The stages sit well below the cap because the estimate trails the gateway ledger and the finishing work needs budget of its own. Unset or invalid means no guard.
+- `AI_GATEWAY_TOKEN_CAP_USD` — the per-run spend cap of the gateway token the cloud worker minted for the sandbox. When set on a cloud run, the Claude adapter arms the run budget guard: it prices every assistant message, snaps to the SDK's cumulative cost at turn end, steers the live turn at 50% (ship what is on disk, skip polish) and 70% (commit and stop) of the cap, and denies new `Agent`, `Task`, `Workflow`, `WebFetch` and `WebSearch` calls once critical. At 90% of the cap it denies every tool, cancels the running turn with the interrupt reason `budget_exhausted`, and refuses new and queued prompts the same way, so no model call reaches the gateway refusal. The stages sit well below the cap because the estimate trails the gateway ledger and the finishing work needs budget of its own. Unset or invalid means no guard.
- `AI_GATEWAY_MODEL_PRICES_JSON` — optional override of the guard's per-million-token price table, a JSON object of `{ "<model id regex>": { input, output, cacheRead, cacheWrite } }` in USD. Defaults cover the Anthropic, GLM, Kimi and DeepSeek families the adapter serves.
- `POSTHOG_BENJAMIN` — `1` or `true` appends the vendored Benjamin-Plus token-efficiency instruction (`@posthog/harness/extensions/benjamin`, source at `packages/harness/src/extensions/benjamin/instruction.ts`) to the Claude system prompt and the Codex instructions, and stamps the pinned upstream commit into run state as `benjamin_version` at session start. Any other value leaves prompts unchanged.
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 28ab7be510fb..8bca88cff063 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -201,6 +201,14 @@ const SESSION_ENDED_MESSAGE =
"The Claude Agent session has ended. Please start a new session.";
const MAX_TITLE_LENGTH = 256;
+const BUDGET_EXHAUSTED_INTERRUPT_REASON = "budget_exhausted";
+
+function budgetExhaustedResponse(): PromptResponse {
+ return {
+ stopReason: "cancelled",
+ _meta: { interruptReason: BUDGET_EXHAUSTED_INTERRUPT_REASON },
+ };
+}
const LOCAL_ONLY_COMMANDS = new Set(["/context", "/heapdump", "/extra-usage"]);
/**
@@ -719,6 +727,28 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
await this.reportBudgetSteer(guard, sessionId, stage, delivered, summary);
}
+ /** Cancel the turn so no model call starts after the budget is spent. */
+ private stopForBudget(session: Session, sessionId: string): void {
+ const guard = session.budgetGuard;
+ if (this.session !== session || !guard?.takeStop()) return;
+ const message = `[BudgetGuard] stop: $${guard.spentUsd.toFixed(2)} of $${guard.capUsd.toFixed(2)} spent, cancelling the turn before the gateway refuses it`;
+ this.logger.warn(message);
+ void this.client
+ .extNotification(POSTHOG_NOTIFICATIONS.CONSOLE, {
+ sessionId,
+ level: "warn",
+ message,
+ })
+ .catch((error) =>
+ this.logger.warn("[BudgetGuard] Failed to report the stop", { error }),
+ );
+ if (!session.activeTurn || session.activeTurn.settled) return;
+ session.interruptReason = BUDGET_EXHAUSTED_INTERRUPT_REASON;
+ this.interrupt().catch((error) =>
+ this.logger.warn("[BudgetGuard] Stop failed", { error }),
+ );
+ }
+
private async reportBudgetSteer(
guard: RunBudgetGuard,
sessionId: string,
@@ -760,6 +790,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
return this.clearConversation(params);
}
+ if (this.session.budgetGuard?.exhausted) {
+ this.logger.warn("[BudgetGuard] Refusing a prompt: budget exhausted");
+ return budgetExhaustedResponse();
+ }
+
const budgetSteerMode = (
params._meta as { budgetSteerMode?: unknown } | undefined
)?.budgetSteerMode;
@@ -895,6 +930,29 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
return response;
}
+ /** Settle prompts queued before the budget ran out, without sending them. */
+ private refuseQueuedTurnsForBudget(session: Session): void {
+ const refused = session.turnQueue.filter(
+ (turn) => !turn.settled && turn.pendingInput,
+ );
+ if (refused.length === 0) return;
+ this.logger.warn(
+ "[BudgetGuard] Refusing queued prompts: budget exhausted",
+ {
+ count: refused.length,
+ },
+ );
+ for (const turn of refused) {
+ turn.settled = true;
+ turn.pendingInput = undefined;
+ declinePendingSteers(turn, "cancelled");
+ turn.resolve(budgetExhaustedResponse());
+ }
+ session.turnQueue = session.turnQueue.filter(
+ (turn) => !refused.includes(turn),
+ );
+ }
+
private dispatchQueuedInput(session: Session): void {
if (session.queryClosed) {
return;
@@ -902,6 +960,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
if (session.activeTurn && !session.activeTurn.settled) {
return;
}
+ if (session.budgetGuard?.exhausted) {
+ this.refuseQueuedTurnsForBudget(session);
+ return;
+ }
const head = session.turnQueue.find((turn) => !turn.settled);
if (!head?.pendingInput) {
return;
@@ -1823,6 +1885,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
if (budgetEvent) {
void this.deliverBudgetSteer(session, sessionId, budgetEvent);
}
+ this.stopForBudget(session, sessionId);
if (message.parent_tool_use_id === null) {
confirmConsumedBackgroundSteers(session);
}
@@ -2494,6 +2557,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
if (event) {
void this.deliverBudgetSteer(session, sessionId, event);
}
+ this.stopForBudget(session, sessionId);
}),
SIDE_QUESTION_TIMEOUT_MS,
);
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.turn-queue.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.turn-queue.test.ts
index 4f38a04134ac..67fad15f90d3 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.turn-queue.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.turn-queue.test.ts
@@ -9,7 +9,9 @@ import {
createSuccessResult,
type MockQuery,
} from "../../test/mocks/claude-sdk";
+import { Logger } from "../../utils/logger";
import { Pushable } from "../../utils/streams";
+import { DEFAULT_MODEL_PRICES, RunBudgetGuard } from "./session/budget-guard";
vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
query: vi.fn(),
@@ -33,7 +35,10 @@ interface Harness {
pushed: SDKUserMessage[];
}
-function installHarness(sessionId: string): Harness {
+function installHarness(
+ sessionId: string,
+ budgetGuard?: RunBudgetGuard,
+): Harness {
const client = {
sessionUpdate: vi.fn().mockResolvedValue(undefined),
extNotification: vi.fn().mockResolvedValue(undefined),
@@ -79,6 +84,7 @@ function installHarness(sessionId: string): Harness {
taskRunId: "run-1",
lastContextWindowSize: 200_000,
modelId: "claude-sonnet-4-6",
+ budgetGuard,
};
(agent as unknown as { session: typeof session }).session = session;
@@ -115,13 +121,44 @@ function tick(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
-async function runningTurnWithQueuedSecond(sessionId: string): Promise<
+function budgetGuard(): RunBudgetGuard {
+ return new RunBudgetGuard(
+ 1,
+ DEFAULT_MODEL_PRICES,
+ new Logger({ debug: false }),
+ );
+}
+
+function sendCostlyAssistantMessage(query: MockQuery): void {
+ query._mockHelpers.sendMessage({
+ type: "assistant",
+ uuid: "a1",
+ session_id: "s",
+ parent_tool_use_id: null,
+ message: {
+ id: "m1",
+ role: "assistant",
+ model: "claude-opus-5",
+ content: [],
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_input_tokens: 2_000_000,
+ },
+ },
+ } as unknown as SDKMessage);
+}
+
+async function runningTurnWithQueuedSecond(
+ sessionId: string,
+ guard?: RunBudgetGuard,
+): Promise<
Harness & {
first: Promise<unknown>;
second: Promise<unknown>;
}
> {
- const harness = installHarness(sessionId);
+ const harness = installHarness(sessionId, guard);
const first = harness.agent.prompt({
sessionId,
prompt: [{ type: "text", text: "first" }],
@@ -213,4 +250,61 @@ describe("ClaudeAcpAgent turn queue input dispatch", () => {
await expect(first).resolves.toMatchObject({ stopReason: "cancelled" });
expect(pushed).toHaveLength(1);
});
+
+ it("cancels the running turn and refuses new prompts once the budget is spent", async () => {
+ const sessionId = "s-budget-stop";
+ const harness = installHarness(sessionId, budgetGuard());
+ harness.query.interrupt.mockImplementation(async () => {});
+ const first = harness.agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "first" }],
+ });
+ await tick();
+ echoTurn(harness.query, sessionOf(harness.agent).turnQueue[0].promptUuid);
+ await tick();
+
+ sendCostlyAssistantMessage(harness.query);
+ await tick();
+ expect(harness.query.interrupt).toHaveBeenCalledTimes(1);
+
+ await expect(
+ harness.agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "keep going" }],
+ }),
+ ).resolves.toEqual({
+ stopReason: "cancelled",
+ _meta: { interruptReason: "budget_exhausted" },
+ });
+ expect(harness.pushed).toHaveLength(1);
+
+ harness.query._mockHelpers.sendMessage({
+ type: "system",
+ subtype: "session_state_changed",
+ state: "idle",
+ } as unknown as SDKMessage);
+ await expect(first).resolves.toMatchObject({
+ stopReason: "cancelled",
+ _meta: { interruptReason: "budget_exhausted" },
+ });
+ });
+
+ it("never sends a prompt queued before the turn that spent the budget", async () => {
+ const { query, pushed, first, second } = await runningTurnWithQueuedSecond(
+ "s-budget-queued",
+ budgetGuard(),
+ );
+
+ query._mockHelpers.sendMessage(createSuccessResult({ total_cost_usd: 1 }));
+ await tick();
+
+ await expect(second).resolves.toEqual({
+ stopReason: "cancelled",
+ _meta: { interruptReason: "budget_exhausted" },
+ });
+ expect(pushed).toHaveLength(1);
+ expect(query.interrupt).not.toHaveBeenCalled();
+ query._mockHelpers.complete();
+ await expect(first).resolves.toMatchObject({ stopReason: "end_turn" });
+ });
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.test.ts
index 75edb5fbf988..1d5bc6871f6a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.test.ts
@@ -372,6 +372,32 @@ describe("RunBudgetGuard", () => {
}
});
+ test("denies every tool and fires the stop once, before the cap", async () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ const hook = guard.preToolUseHook();
+ guard.recordAssistantMessage(opusCall("m1", 1_700_000));
+ expect(guard.currentStage).toBe("critical");
+ expect(guard.exhausted).toBe(false);
+ expect(guard.takeStop()).toBe(false);
+ expect(await hook(spawn("Bash"), undefined, hookOptions())).toEqual({
+ continue: true,
+ });
+ guard.recordAssistantMessage(opusCall("m2", 100_000));
+ expect(guard.exhausted).toBe(true);
+ expect(guard.spentUsd).toBeLessThan(guard.capUsd);
+ expect(guard.takeStop()).toBe(true);
+ expect(guard.takeStop()).toBe(false);
+ for (const tool of [
+ "Bash",
+ "Edit",
+ "mcp__posthog-code-tools__git_signed_commit",
+ ]) {
+ expect(await hook(spawn(tool), undefined, hookOptions())).toMatchObject({
+ hookSpecificOutput: { permissionDecision: "deny" },
+ });
+ }
+ });
+
test("leaves enough of the cap for the finishing work at critical", () => {
const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
guard.recordAssistantMessage(opusCall("m1", 1_400_000));
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.ts b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.ts
index f7e149de7073..aa06fab86b7b 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.ts
@@ -5,6 +5,8 @@ export const BUDGET_CAP_ENV = "AI_GATEWAY_TOKEN_CAP_USD";
export const BUDGET_PRICES_ENV = "AI_GATEWAY_MODEL_PRICES_JSON";
export const BUDGET_WARN_RATIO = 0.5;
export const BUDGET_CRITICAL_RATIO = 0.7;
+// The local estimate trails the gateway's billed spend, so stop before the cap.
+export const BUDGET_STOP_RATIO = 0.9;
export const FAST_MODE_PRICE_MULTIPLIER = 2;
export const ONE_HOUR_CACHE_WRITE_INPUT_MULTIPLIER = 2;
@@ -204,6 +206,7 @@ export class RunBudgetGuard {
private pendingSteer: BudgetSteerStage | null = null;
private steerMode: BudgetSteerMode;
private readonly steers: BudgetSteerRecord[] = [];
+ private stopTaken = false;
constructor(
readonly capUsd: number,
@@ -212,6 +215,7 @@ export class RunBudgetGuard {
mode: BudgetSteerMode = "wrap_up",
private readonly warnRatio: number = BUDGET_WARN_RATIO,
private readonly criticalRatio: number = BUDGET_CRITICAL_RATIO,
+ private readonly stopRatio: number = BUDGET_STOP_RATIO,
) {
this.steerMode = mode;
}
@@ -260,6 +264,17 @@ export class RunBudgetGuard {
return this.stage;
}
+ get exhausted(): boolean {
+ return this.ratio >= this.stopRatio;
+ }
+
+ /** True once, on the first check after spend reaches the stop ratio. */
+ takeStop(): boolean {
+ if (this.stopTaken || !this.exhausted) return false;
+ this.stopTaken = true;
+ return true;
+ }
+
recordAssistantMessage(
message: AssistantUsageLike,
source: BudgetSpendSource = "main",
@@ -398,6 +413,21 @@ export class RunBudgetGuard {
preToolUseHook(): HookCallback {
return async (input: HookInput) => {
if (input.hook_event_name !== "PreToolUse") return { continue: true };
+ if (this.exhausted) {
+ this.logger.warn(
+ `[BudgetGuard] Blocking ${input.tool_name}: budget exhausted at ${formatUsd(this.spentUsd)} of ${formatUsd(this.capUsd)}`,
+ );
+ return {
+ continue: true,
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse" as const,
+ permissionDecision: "deny" as const,
+ permissionDecisionReason:
+ `This run has used about ${formatUsd(this.spentUsd)} of its ${formatUsd(this.capUsd)} model budget, ` +
+ "so no more tools can run. End your turn now with a short summary of your result.",
+ },
+ };
+ }
if (!CRITICAL_BLOCKED_TOOL_NAMES.has(input.tool_name)) {
return { continue: true };
}