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.

feat(tasks): steer a capped run to ship before the gateway refuses it (#102980)

Alessandro Pogliaghif67d1e771b4c
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.md
index 2e2ecb6a54cc..436f7c456972 100644
--- a/products/desktop/packages/agent/README.md
+++ b/products/desktop/packages/agent/README.md
@@ -165,6 +165,8 @@ 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 70% (ship what is on disk, skip polish) and 85% (commit and stop) of the cap, and denies new `Agent`, `Task` and `Workflow` spawns once critical. 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.
Optional run telemetry (the logs pair must both be set, otherwise telemetry stays off):
@@ -256,6 +258,8 @@ ACP defines standard methods like `session/prompt`, `session/update`, and `sessi
- `_posthog/mode_change` — `{ mode, previous_mode }` — permission mode changed (client updates mode selector)
- `_posthog/compact_boundary` — `{ sessionId, timestamp }` — marks where context compaction occurred, so the client knows the conversation was summarized at this point
- `_posthog/task_notification` — `{ sessionId, type, message?, data? }` — generic extensible notification for adapter-specific events
+- `_posthog/usage_update` — `{ sessionId, usage, budget? }` — cumulative token usage after each settled turn. `budget` is present on a capped cloud run: `{ cap_usd, spent_usd, estimated_usd, sdk_total_usd, stage, mode, steers }`, persisted by the agent-server into `TaskRun.state.budget_guard`
+- `_posthog/budget_steer` — `{ sessionId, stage, delivered, spent_usd, cap_usd, mode }` — the run budget guard steered the model at the `warn` (70% of the cap) or `critical` (85%) stage; `delivered` is false when the steer never reached the model and is retried on the next turn. The Django ingest captures each one as a `task run budget steer` event
**Client→agent commands** — notifications that flow from client to agent (via `POST /command` in cloud, or direct ACP in local). These are the "verbs" the client can send outside of `session/prompt`.
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.ts
index 88872a60b14d..9162b2616604 100644
--- a/products/desktop/packages/agent/src/acp-extensions.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.ts
@@ -96,6 +96,8 @@ export const POSTHOG_NOTIFICATIONS = {
/** RTK output-compression token savings tallied at the end of a run */
RTK_SAVINGS: "_posthog/rtk_savings",
+ BUDGET_STEER: "_posthog/budget_steer",
+
/** Latest native Codex goal state, persisted so cold cloud resumes can restore it. */
CODEX_GOAL: "_posthog/codex_goal",
/** Desktop → sandbox reply to an MCP relay request (docs/CLOUD-MCP-RELAY.md). */
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
index f6c282f2e9a8..22fd1ec072bc 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
@@ -2,7 +2,9 @@ import * as fs from "node:fs";
import type { AgentSideConnection } from "@agentclientprotocol/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { POSTHOG_METHODS, POSTHOG_NOTIFICATIONS } from "../../acp-extensions";
+import { Logger } from "../../utils/logger";
import { Pushable } from "../../utils/streams";
+import { DEFAULT_MODEL_PRICES, RunBudgetGuard } from "./session/budget-guard";
import { getSessionJsonlPath } from "./session/jsonl-hydration";
import { FALLBACK_MODEL } from "./session/models";
@@ -730,19 +732,39 @@ describe("ClaudeAcpAgent /clear", () => {
);
});
- it("resets pre-clear plan and notification state so it can't resurface after /clear", async () => {
+ it("resets pre-clear plan, notification and background-turn state so it can't resurface after /clear", async () => {
const { agent } = makeAgent();
const { session } = installFakeSession(agent, "s-plan");
(session as unknown as { lastPlanFilePath?: string }).lastPlanFilePath =
"/tmp/repo/.claude/plans/old.md";
session.notificationHistory.push({ type: "assistant", text: "old" });
agent.fileContentCache["/tmp/repo/.claude/plans/old.md"] = "stale content";
+ const live = session as unknown as {
+ backgroundTurnActive?: boolean;
+ budgetGuard?: RunBudgetGuard;
+ };
+ live.backgroundTurnActive = true;
+ const guard = new RunBudgetGuard(
+ 1,
+ DEFAULT_MODEL_PRICES,
+ new Logger({ debug: false }),
+ );
+ guard.recordAssistantMessage({
+ id: "m1",
+ model: "claude-opus-5",
+ usage: { input_tokens: 0, output_tokens: 40_000 },
+ });
+ expect(guard.takePendingSteer()).toBe("critical");
+ guard.recordSteer("critical", true);
+ live.budgetGuard = guard;
await agent.prompt({
sessionId: "s-plan",
prompt: [{ type: "text", text: "/clear" }],
});
+ expect(live.backgroundTurnActive).toBe(false);
+ expect(guard.takePendingSteer()).toBe("critical");
expect(
(session as unknown as { lastPlanFilePath?: string }).lastPlanFilePath,
).toBeUndefined();
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
index 5151e8dae111..e872ab5f78c5 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
@@ -142,6 +142,7 @@ function taskNotificationUserMessage(sessionId: string, event: string) {
role: "user",
content: `<task-notification>\n<event>${event}</event>\n</task-notification>`,
},
+ origin: { kind: "task-notification" },
};
}
@@ -207,6 +208,80 @@ describe("ClaudeAcpAgent — task-notification results", () => {
).toHaveLength(0);
});
+ it("acks a steer sent during a background turn only once the model acts on it", async () => {
+ const { agent } = makeAgent();
+ const sessionId = "s-task-notification-steer";
+ const { query, input } = installFakeSession(agent, sessionId);
+
+ const promptPromise = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "hi" }],
+ });
+ await tick();
+ await echoUserMessage(query, input);
+ await send(query, assistantMessage(sessionId, "msg_1", "hello"));
+ await send(query, resultSuccess(sessionId, "result-1"));
+ await promptPromise;
+
+ await send(query, taskNotificationUserMessage(sessionId, "ping 1"));
+ let steerSettled = false;
+ const steerPromise = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "wrap up now" }],
+ _meta: { steer: true },
+ });
+ void steerPromise.then(() => {
+ steerSettled = true;
+ });
+ await tick();
+
+ await send(query, assistantMessage(sessionId, "msg_2", "ping 1 received."));
+ await send(query, taskNotificationResult(sessionId, "result-2"));
+ expect(steerSettled).toBe(false);
+
+ await echoUserMessage(query, input);
+ expect(steerSettled).toBe(false);
+ await send(query, assistantMessage(sessionId, "msg_3", "wrapping up"));
+ await expect(steerPromise).resolves.toMatchObject({
+ _meta: { steer: true },
+ });
+ });
+
+ it("declines a background steer the SDK never echoes after the background turn ends", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ const { agent } = makeAgent();
+ const sessionId = "s-task-notification-steer-lost";
+ const { query, input } = installFakeSession(agent, sessionId);
+
+ const promptPromise = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "hi" }],
+ });
+ await tick();
+ await echoUserMessage(query, input);
+ await send(query, assistantMessage(sessionId, "msg_1", "hello"));
+ await send(query, resultSuccess(sessionId, "result-1"));
+ await promptPromise;
+
+ await send(query, taskNotificationUserMessage(sessionId, "ping 1"));
+ const steerPromise = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "wrap up now" }],
+ _meta: { steer: true },
+ });
+ await tick();
+ await send(query, taskNotificationResult(sessionId, "result-2"));
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ await expect(steerPromise).resolves.toMatchObject({
+ _meta: { steer: false, steerDeclineCause: "turn_ended_first" },
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("emits background_turn_complete with a refusal stop reason on a task-notification refusal", async () => {
const { agent, client } = makeAgent();
const sessionId = "s-task-notification-refusal";
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 b44c06a55087..4284897909c5 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -119,6 +119,13 @@ import {
setMcpToolApprovalStates,
} from "./mcp/tool-metadata";
import { canUseTool } from "./permissions/permission-handlers";
+import {
+ type AssistantUsageLike,
+ type BudgetSteerMode,
+ type BudgetSteerStage,
+ type BudgetThresholdEvent,
+ RunBudgetGuard,
+} from "./session/budget-guard";
import { getAvailableSlashCommands } from "./session/commands";
import { SessionInitialization } from "./session/initialization";
import { getSessionJsonlPath } from "./session/jsonl-hydration";
@@ -166,6 +173,7 @@ import type {
BackgroundTerminal,
EffortLevel,
NewSessionMeta,
+ PendingSteer,
SDKMessageFilter,
Session,
ToolUpdateMeta,
@@ -259,6 +267,54 @@ function declinePendingSteers(turn: Turn, cause: SteerDeclineCause): void {
turn.pendingSteers.clear();
}
+function hasUnconsumedBackgroundSteers(session: Session): boolean {
+ for (const steer of session.backgroundSteers?.values() ?? []) {
+ if (!steer.consumed) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function clearBackgroundSteerTimer(session: Session): void {
+ if (session.backgroundSteerTimer) {
+ clearTimeout(session.backgroundSteerTimer);
+ session.backgroundSteerTimer = undefined;
+ }
+}
+
+function confirmConsumedBackgroundSteers(session: Session): void {
+ const steers = session.backgroundSteers;
+ if (!steers) {
+ return;
+ }
+ for (const [uuid, steer] of steers) {
+ if (steer.consumed) {
+ steer.settle(true);
+ steers.delete(uuid);
+ }
+ }
+}
+
+function declineBackgroundSteers(
+ session: Session,
+ cause: SteerDeclineCause,
+ options: { onlyUnconsumed?: boolean } = {},
+): void {
+ clearBackgroundSteerTimer(session);
+ const steers = session.backgroundSteers;
+ if (!steers) {
+ return;
+ }
+ for (const [uuid, steer] of steers) {
+ if (options.onlyUnconsumed && steer.consumed) {
+ continue;
+ }
+ steer.settle(false, cause);
+ steers.delete(uuid);
+ }
+}
+
function isSdkMcpServer(
cfg: McpServerConfig,
): cfg is McpSdkServerConfigWithInstance {
@@ -597,6 +653,96 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
return this.listSessions(params);
}
+ private budgetSteerTail: Promise<void> = Promise.resolve();
+
+ private deliverBudgetSteer(
+ session: Session,
+ sessionId: string,
+ event: BudgetThresholdEvent,
+ ): Promise<void> {
+ const run = this.budgetSteerTail.then(() =>
+ this.sendBudgetSteer(session, sessionId, event),
+ );
+ this.budgetSteerTail = run.catch(() => undefined);
+ return run;
+ }
+
+ private async sendBudgetSteer(
+ session: Session,
+ sessionId: string,
+ event: BudgetThresholdEvent,
+ ): Promise<void> {
+ const guard = session.budgetGuard;
+ if (!guard || this.session !== session) return;
+ const stage = guard.takePendingSteer();
+ if (!stage) return;
+ const summary = `[BudgetGuard] ${stage}: $${event.spentUsd.toFixed(2)} of $${event.capUsd.toFixed(2)} spent, steering the turn`;
+ this.logger.warn(summary);
+ let delivered = false;
+ try {
+ const result = await this.prompt({
+ sessionId,
+ prompt: [
+ {
+ type: "text",
+ text: guard.steerText(stage),
+ _meta: { ui: { hidden: true }, budgetGuard: stage },
+ },
+ ],
+ _meta: { steer: true },
+ });
+ const meta = result._meta as
+ | { steer?: boolean; steerDeclineCause?: string }
+ | undefined;
+ delivered = meta?.steer === true;
+ if (!delivered) {
+ this.logger.warn("[BudgetGuard] Steer not delivered", {
+ stage,
+ cause: meta?.steerDeclineCause,
+ });
+ }
+ } catch (error) {
+ this.logger.warn("[BudgetGuard] Steer failed", { error });
+ }
+ if (this.session !== session) {
+ this.logger.warn("[BudgetGuard] Session replaced during the steer", {
+ stage,
+ });
+ return;
+ }
+ if (!delivered) {
+ guard.markUndelivered(stage);
+ }
+ await this.reportBudgetSteer(guard, sessionId, stage, delivered, summary);
+ }
+
+ private async reportBudgetSteer(
+ guard: RunBudgetGuard,
+ sessionId: string,
+ stage: BudgetSteerStage,
+ delivered: boolean,
+ summary: string,
+ ): Promise<void> {
+ const record = guard.recordSteer(stage, delivered);
+ try {
+ await this.client.extNotification(POSTHOG_NOTIFICATIONS.CONSOLE, {
+ sessionId,
+ level: "warn",
+ message: `${summary} (delivered=${delivered})`,
+ });
+ await this.client.extNotification(POSTHOG_NOTIFICATIONS.BUDGET_STEER, {
+ sessionId,
+ stage,
+ delivered,
+ spent_usd: record.spent_usd,
+ cap_usd: guard.capUsd,
+ mode: guard.mode,
+ });
+ } catch (error) {
+ this.logger.warn("[BudgetGuard] Failed to report the steer", { error });
+ }
+ }
+
async prompt(params: PromptRequest): Promise<PromptResponse> {
// Detect local-only slash commands that return results without model invocation
const command = promptSlashCommand(params);
@@ -608,6 +754,12 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
return this.clearConversation(params);
}
+ const budgetSteerMode = (
+ params._meta as { budgetSteerMode?: unknown } | undefined
+ )?.budgetSteerMode;
+ if (budgetSteerMode === "publish" || budgetSteerMode === "wrap_up") {
+ this.session.budgetGuard?.setMode(budgetSteerMode);
+ }
const userMessage = promptToClaude(params);
const promptUuid = randomUUID();
userMessage.uuid = promptUuid;
@@ -664,6 +816,25 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
return ack;
}
if (isSteer) {
+ if (this.session.backgroundTurnActive && !this.session.compacting) {
+ const session = this.session;
+ session.backgroundSteers ??= new Map<string, PendingSteer>();
+ const backgroundSteers = session.backgroundSteers;
+ const ack = new Promise<PromptResponse>((resolve) => {
+ backgroundSteers.set(promptUuid, {
+ consumed: false,
+ settle: (reachedModel, cause) =>
+ resolve(
+ reachedModel
+ ? { stopReason: "end_turn", _meta: { steer: true } }
+ : steerDeclined(cause ?? "turn_ended_first"),
+ ),
+ });
+ });
+ session.input.push(userMessage);
+ await this.broadcastUserMessage(params);
+ return ack;
+ }
return steerDeclined(
this.session.compacting ? "compacting" : "no_in_flight_turn",
);
@@ -732,7 +903,29 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
const input = head.pendingInput;
head.pendingInput = undefined;
head.dispatchedAt = performance.now();
+ const guard = session.budgetGuard;
+ const steer = guard && !head.commandName ? guard.takePendingSteer() : null;
+ if (guard && steer) {
+ const steerBlock = {
+ type: "text" as const,
+ text: guard.steerText(steer),
+ };
+ const content = input.message.content;
+ input.message.content =
+ typeof content === "string"
+ ? [{ type: "text", text: content }, steerBlock]
+ : [...content, steerBlock];
+ }
session.input.push(input);
+ if (guard && steer) {
+ void this.reportBudgetSteer(
+ guard,
+ this.sessionId,
+ steer,
+ true,
+ `[BudgetGuard] ${steer}: steer attached to the next turn`,
+ );
+ }
}
/** Time the window between handing a prompt to the SDK and the SDK's first
@@ -803,6 +996,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
private closeQueryStream(session: Session): void {
session.queryClosed = true;
session.consumer = undefined;
+ declineBackgroundSteers(session, "turn_ended_first");
if (session.forceCancelTimer) {
clearTimeout(session.forceCancelTimer);
session.forceCancelTimer = undefined;
@@ -1270,6 +1464,30 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
const isTaskNotification =
(message as { origin?: { kind?: string } }).origin?.kind ===
"task-notification";
+ if (isTaskNotification) {
+ session.backgroundTurnActive = false;
+ if (hasUnconsumedBackgroundSteers(session)) {
+ session.backgroundSteerTimer ??= setTimeout(() => {
+ session.backgroundSteerTimer = undefined;
+ this.logger.warn("Background steer never reached the model", {
+ sessionId,
+ });
+ declineBackgroundSteers(session, "turn_ended_first", {
+ onlyUnconsumed: true,
+ });
+ }, STEER_DELIVERY_GRACE_MS);
+ }
+ } else {
+ confirmConsumedBackgroundSteers(session);
+ }
+ const settledBudgetEvent = session.budgetGuard?.calibrate(
+ message.total_cost_usd,
+ );
+ if (settledBudgetEvent) {
+ this.logger.warn(
+ `[BudgetGuard] ${settledBudgetEvent.stage} at turn end: $${settledBudgetEvent.spentUsd.toFixed(2)} of $${settledBudgetEvent.capUsd.toFixed(2)} spent`,
+ );
+ }
if (!isTaskNotification) {
await this.syncFastModeState(
@@ -1359,6 +1577,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
cachedWriteTokens: message.usage.cache_creation_input_tokens,
},
cost: message.total_cost_usd,
+ budget: session.budgetGuard?.snapshot(),
breakdown: buildBreakdown(
session.contextBreakdownBaseline ?? emptyBaseline(),
breakdownInputTokens,
@@ -1526,10 +1745,27 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
case "user":
case "assistant": {
+ if (
+ message.type === "user" &&
+ (message as { origin?: { kind?: string } }).origin?.kind ===
+ "task-notification"
+ ) {
+ session.backgroundTurnActive = true;
+ }
// A user echo promotes its queued turn (handing off any still-
// active one first), then drops from the feed. Runs before the
// cancelled guard so a turn enqueued after a cancel still starts.
if (message.type === "user" && "uuid" in message && message.uuid) {
+ const backgroundSteer = session.backgroundSteers?.get(
+ message.uuid,
+ );
+ if (backgroundSteer) {
+ backgroundSteer.consumed = true;
+ if (!hasUnconsumedBackgroundSteers(session)) {
+ clearBackgroundSteerTimer(session);
+ }
+ break;
+ }
const steer = session.activeTurn?.pendingSteers.get(message.uuid);
if (steer) {
steer.consumed = true;
@@ -1575,6 +1811,15 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
if (message.type === "assistant") {
this.timeFirstModelOutput(session, sessionId);
+ const budgetEvent = session.budgetGuard?.recordAssistantMessage(
+ message.message as AssistantUsageLike,
+ );
+ if (budgetEvent) {
+ void this.deliverBudgetSteer(session, sessionId, budgetEvent);
+ }
+ if (message.parent_tool_use_id === null) {
+ confirmConsumedBackgroundSteers(session);
+ }
// Subagent output is a separate model context, so it is no
// evidence the steer reached this turn's model.
if (session.activeTurn && message.parent_tool_use_id === null) {
@@ -1855,6 +2100,8 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
session.queryGeneration += 1;
const oldConsumer = session.consumer;
session.consumer = undefined;
+ session.backgroundTurnActive = false;
+ declineBackgroundSteers(session, "turn_ended_first");
session.cancelController?.abort();
session.cancelController = undefined;
@@ -1998,6 +2245,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
newQuery = query({ prompt: newInput, options: newOptions });
session.query = newQuery;
+ session.budgetGuard?.onConversationCleared();
session.input = newInput;
session.queryOptions = newOptions;
session.abortController = newAbortController;
@@ -2171,6 +2419,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
const abortController = new AbortController();
this.sideQuestionAbort = abortController;
+ const session = this.session;
+ const guard = session.budgetGuard;
+ const sessionId = this.sessionId;
try {
// Drop `sessionId` (identity comes from `resume`), `hooks` (they close
// over live-session caches and task state), and `outputFormat` (a
@@ -2229,7 +2480,15 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
});
const answer = await withTimeout(
- collectSideQuestionAnswer(oneShot),
+ collectSideQuestionAnswer(oneShot, (message) => {
+ const event = guard?.recordAssistantMessage(
+ message.message as AssistantUsageLike,
+ "side",
+ );
+ if (event) {
+ void this.deliverBudgetSteer(session, sessionId, event);
+ }
+ }),
SIDE_QUESTION_TIMEOUT_MS,
);
@@ -2341,6 +2600,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
newQuery = query({ prompt: newInput, options: newOptions });
prev.query = newQuery;
+ prev.budgetGuard?.onQueryReset();
prev.input = newInput;
prev.queryOptions = newOptions;
prev.abortController = newAbortController;
@@ -2710,6 +2970,17 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
// Gate signed-commit wiring on cloud-run detection so the desktop (which
// signs via CommitSaga) is untouched.
const cloudRun = isCloudRun(meta);
+ const budgetSteerMode: BudgetSteerMode =
+ meta?.budgetSteer?.mode === "publish" ? "publish" : "wrap_up";
+ const budgetGuard = cloudRun
+ ? RunBudgetGuard.fromEnv(process.env, this.logger, budgetSteerMode)
+ : null;
+ if (budgetGuard) {
+ this.logger.info("[BudgetGuard] Armed", {
+ capUsd: budgetGuard.capUsd,
+ mode: budgetGuard.mode,
+ });
+ }
const effort = meta?.claudeCode?.options?.effort as EffortLevel | undefined;
// We want to create a new session id unless it is resume,
@@ -2884,6 +3155,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
enrichmentDeps: this.enrichment?.deps,
enrichedReadCache: this.enrichedReadCache,
cloudMode: cloudRun,
+ budgetGuard: budgetGuard ?? undefined,
onEnsureLocalToolsConnected: () =>
this.ensureLocalToolsConnected("guard-hook"),
taskState,
@@ -2922,6 +3194,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
cloudMode: cloudRun,
posthogExecPermissionRegex,
abortController,
+ budgetGuard: budgetGuard ?? undefined,
accumulatedUsage: {
inputTokens: 0,
outputTokens: 0,
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
new file mode 100644
index 000000000000..927dc84dbc17
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.test.ts
@@ -0,0 +1,352 @@
+import type { HookInput } from "@anthropic-ai/claude-agent-sdk";
+import { describe, expect, test } from "vitest";
+import { Logger } from "../../../utils/logger";
+import {
+ BUDGET_CAP_ENV,
+ BUDGET_PRICES_ENV,
+ DEFAULT_MODEL_PRICES,
+ estimateMessageCostUsd,
+ RunBudgetGuard,
+} from "./budget-guard";
+
+const logger = new Logger({ debug: false });
+
+function opusCall(id: string, cacheReadTokens: number) {
+ return {
+ id,
+ model: "claude-opus-5",
+ usage: {
+ input_tokens: 2,
+ output_tokens: 200,
+ cache_read_input_tokens: cacheReadTokens,
+ cache_creation_input_tokens: 1_000,
+ },
+ };
+}
+
+function spawn(toolName: string): HookInput {
+ return {
+ session_id: "s",
+ transcript_path: "/tmp/t",
+ cwd: "/tmp",
+ hook_event_name: "PreToolUse",
+ tool_name: toolName,
+ tool_input: {},
+ tool_use_id: "toolu_1",
+ } as HookInput;
+}
+
+const hookOptions = () => ({ signal: new AbortController().signal });
+
+describe("RunBudgetGuard", () => {
+ test("prices an opus call the way the gateway bills it", () => {
+ const cost = estimateMessageCostUsd(
+ opusCall("m1", 256_387),
+ DEFAULT_MODEL_PRICES,
+ );
+ expect(cost).toBeCloseTo(0.1395, 3);
+ });
+
+ test("falls back to opus pricing for an unknown model", () => {
+ const known = estimateMessageCostUsd(
+ opusCall("m1", 100_000),
+ DEFAULT_MODEL_PRICES,
+ );
+ const unknown = estimateMessageCostUsd(
+ { ...opusCall("m1", 100_000), model: "claude-something-new" },
+ DEFAULT_MODEL_PRICES,
+ );
+ expect(unknown).toBe(known);
+ });
+
+ test.each([
+ ["@cf/zai-org/glm-5.2", 5.94],
+ ["zai-org/glm-5.3", 5.94],
+ ["zai-org/glm-5.3-flash", 0.68],
+ ["moonshotai/kimi-k3", 18.3],
+ ["deepseek-ai/deepseek-v4-flash-0731", 0.418],
+ ])(
+ "prices %s below opus, the way the gateway bills it",
+ (model, perMillionEach) => {
+ const cost = estimateMessageCostUsd(
+ {
+ id: "m1",
+ model,
+ usage: {
+ input_tokens: 1_000_000,
+ output_tokens: 1_000_000,
+ cache_read_input_tokens: 1_000_000,
+ cache_creation_input_tokens: 0,
+ },
+ },
+ DEFAULT_MODEL_PRICES,
+ );
+ expect(cost).toBeCloseTo(perMillionEach, 6);
+ expect(cost).toBeLessThan(
+ estimateMessageCostUsd(
+ {
+ id: "m1",
+ model: "claude-opus-5",
+ usage: {
+ input_tokens: 1_000_000,
+ output_tokens: 1_000_000,
+ cache_read_input_tokens: 1_000_000,
+ cache_creation_input_tokens: 0,
+ },
+ },
+ DEFAULT_MODEL_PRICES,
+ ),
+ );
+ },
+ );
+
+ test("charges one-hour cache writes at twice the input price and fast mode at twice the price", () => {
+ const flat = estimateMessageCostUsd(
+ {
+ model: "claude-opus-5",
+ usage: { cache_creation_input_tokens: 1_000_000 },
+ },
+ DEFAULT_MODEL_PRICES,
+ );
+ const oneHour = estimateMessageCostUsd(
+ {
+ model: "claude-opus-5",
+ usage: {
+ cache_creation_input_tokens: 1_000_000,
+ cache_creation: { ephemeral_1h_input_tokens: 1_000_000 },
+ },
+ },
+ DEFAULT_MODEL_PRICES,
+ );
+ const fast = estimateMessageCostUsd(
+ {
+ model: "claude-opus-5",
+ usage: { output_tokens: 1_000_000, speed: "fast" },
+ },
+ DEFAULT_MODEL_PRICES,
+ );
+ expect(flat).toBeCloseTo(6.25, 6);
+ expect(oneHour).toBeCloseTo(10, 6);
+ expect(fast).toBeCloseTo(50, 6);
+ });
+
+ test("is disabled when the sandbox carries no cap", () => {
+ expect(RunBudgetGuard.fromEnv({}, logger)).toBeNull();
+ expect(
+ RunBudgetGuard.fromEnv({ [BUDGET_CAP_ENV]: "0" }, logger),
+ ).toBeNull();
+ expect(
+ RunBudgetGuard.fromEnv({ [BUDGET_CAP_ENV]: "abc" }, logger),
+ ).toBeNull();
+ });
+
+ test.each([
+ [
+ '{"opus": {"input": 0, "output": 0, "cacheRead": 10, "cacheWrite": 0}}',
+ 0.5,
+ ],
+ [
+ '{"opus": {"input": 0, "output": 0, "cacheRead": -10, "cacheWrite": 0}}',
+ 0.03626,
+ ],
+ [
+ '{"opus": {"input": 0, "output": 0, "cacheRead": 1e400, "cacheWrite": 0}}',
+ 0.03626,
+ ],
+ ["not json", 0.03626],
+ ])(
+ "price override %s yields spend %s for a 50k cache read",
+ (raw, expected) => {
+ const guard = RunBudgetGuard.fromEnv(
+ { [BUDGET_CAP_ENV]: "1", [BUDGET_PRICES_ENV]: raw },
+ logger,
+ );
+ guard?.recordAssistantMessage(opusCall("m1", 50_000));
+ expect(guard?.spentUsd).toBeCloseTo(expected, 4);
+ },
+ );
+
+ test("fires warn once and critical once, in order, and dedupes repeated message ids", () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ const events: string[] = [];
+ const record = (id: string, cacheRead: number) => {
+ const event = guard.recordAssistantMessage(opusCall(id, cacheRead));
+ if (event) events.push(event.stage);
+ };
+ record("m1", 1_000_000);
+ record("m1", 1_000_000);
+ expect(guard.spentUsd).toBeCloseTo(0.51126, 4);
+ expect(events).toEqual([]);
+ record("m2", 500_000);
+ expect(events).toEqual(["warn"]);
+ record("m3", 100_000);
+ record("m4", 200_000);
+ expect(events).toEqual(["warn", "critical"]);
+ record("m5", 1_000_000);
+ expect(events).toEqual(["warn", "critical"]);
+ });
+
+ test("keeps a threshold pending until a steer is delivered, and critical supersedes warn", () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ guard.recordAssistantMessage(opusCall("m1", 1_500_000));
+ expect(guard.takePendingSteer()).toBe("warn");
+ expect(guard.takePendingSteer()).toBeNull();
+ guard.markUndelivered("warn");
+ guard.recordAssistantMessage(opusCall("m2", 500_000));
+ expect(guard.takePendingSteer()).toBe("critical");
+ guard.markUndelivered("warn");
+ expect(guard.takePendingSteer()).toBe("warn");
+ guard.markUndelivered("critical");
+ guard.markUndelivered("warn");
+ expect(guard.takePendingSteer()).toBe("critical");
+ });
+
+ test("a warn steer that fails after the critical steer was delivered is not re-queued", () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ guard.recordAssistantMessage(opusCall("m1", 2_000_000));
+ expect(guard.takePendingSteer()).toBe("critical");
+ guard.recordSteer("critical", true);
+ guard.markUndelivered("warn");
+ expect(guard.takePendingSteer()).toBeNull();
+ guard.recordSteer("warn", false);
+ guard.markUndelivered("critical");
+ expect(guard.takePendingSteer()).toBeNull();
+ });
+
+ test("never lets a lower or zeroed SDK total erase spend already counted", () => {
+ const guard = new RunBudgetGuard(10, DEFAULT_MODEL_PRICES, logger);
+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));
+ expect(guard.spentUsd).toBeCloseTo(0.51126, 4);
+ guard.calibrate(2.0);
+ expect(guard.spentUsd).toBe(2.0);
+ guard.recordAssistantMessage(opusCall("m2", 1_000_000));
+ expect(guard.spentUsd).toBeCloseTo(2.51126, 4);
+ guard.calibrate(0);
+ expect(guard.spentUsd).toBeCloseTo(2.51126, 4);
+ guard.calibrate(1.0);
+ expect(guard.spentUsd).toBeCloseTo(2.51126, 4);
+ guard.calibrate(3.0);
+ expect(guard.spentUsd).toBeCloseTo(3.0, 4);
+ expect(guard.calibrate(8.6)).toMatchObject({ stage: "critical" });
+ expect(guard.recordAssistantMessage(opusCall("m3", 1_000))).toBeNull();
+ expect(guard.currentStage).toBe("critical");
+ });
+
+ test("re-queues the delivered stage after a conversation clear but not after a refresh", () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ guard.recordAssistantMessage(opusCall("m1", 2_000_000));
+ expect(guard.takePendingSteer()).toBe("critical");
+ guard.recordSteer("critical", true);
+ guard.onQueryReset();
+ expect(guard.takePendingSteer()).toBeNull();
+ guard.onConversationCleared();
+ expect(guard.takePendingSteer()).toBe("critical");
+ expect(guard.takePendingSteer()).toBeNull();
+ guard.markUndelivered("critical");
+ expect(guard.takePendingSteer()).toBe("critical");
+ expect(guard.spentUsd).toBeCloseTo(1.01126, 4);
+ });
+
+ test("carries spend across an explicit query reset only", () => {
+ const guard = new RunBudgetGuard(10, DEFAULT_MODEL_PRICES, logger);
+ guard.calibrate(4.0);
+ guard.onQueryReset();
+ guard.calibrate(0.5);
+ expect(guard.spentUsd).toBeCloseTo(4.5, 6);
+ guard.calibrate(0.9);
+ expect(guard.spentUsd).toBeCloseTo(4.9, 6);
+ guard.calibrate(0.2);
+ expect(guard.spentUsd).toBeCloseTo(4.9, 6);
+ expect(guard.snapshot().sdk_total_usd).toBeCloseTo(4.9, 6);
+ });
+
+ test("keeps side-question spend on top of the main query's calibrated total", () => {
+ const guard = new RunBudgetGuard(10, DEFAULT_MODEL_PRICES, logger);
+ guard.calibrate(2.0);
+ guard.recordAssistantMessage(opusCall("side1", 1_000_000), "side");
+ expect(guard.spentUsd).toBeCloseTo(2.51126, 4);
+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));
+ guard.calibrate(2.6);
+ expect(guard.spentUsd).toBeCloseTo(3.11126, 4);
+ });
+
+ test("switches steer text when the mode is upgraded to publish", () => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ expect(guard.mode).toBe("wrap_up");
+ expect(guard.steerText("warn")).not.toContain(
+ "open the draft pull request",
+ );
+ guard.setMode("publish");
+ expect(guard.snapshot().mode).toBe("publish");
+ expect(guard.steerText("warn")).toContain("open the draft pull request");
+ });
+
+ test.each(["Agent", "Task", "Workflow"])(
+ "denies a %s spawn only once the budget is critical",
+ async (toolName) => {
+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);
+ const hook = guard.preToolUseHook();
+ guard.recordAssistantMessage(opusCall("m1", 1_500_000));
+ expect(guard.currentStage).toBe("warn");
+ expect(await hook(spawn(toolName), undefined, hookOptions())).toEqual({
+ continue: true,
+ });
+ guard.recordAssistantMessage(opusCall("m2", 500_000));
+ expect(guard.currentStage).toBe("critical");
+ expect(
+ await hook(spawn(toolName), undefined, hookOptions()),
+ ).toMatchObject({
+ hookSpecificOutput: { permissionDecision: "deny" },
+ });
+ expect(await hook(spawn("Bash"), undefined, hookOptions())).toEqual({
+ continue: true,
+ });
+ },
+ );
+
+ test("only a publish-mode guard tells the agent to commit and open a pull request", () => {
+ const publish = new RunBudgetGuard(
+ 1,
+ DEFAULT_MODEL_PRICES,
+ logger,
+ "publish",
+ );
+ const wrapUp = new RunBudgetGuard(
+ 1,
+ DEFAULT_MODEL_PRICES,
+ logger,
+ "wrap_up",
+ );
+ for (const stage of ["warn", "critical"] as const) {
+ expect(publish.steerText(stage)).toContain("git_signed_commit");
+ expect(publish.steerText(stage)).not.toMatch(/, push,/);
+ expect(wrapUp.steerText(stage)).toContain(
+ "If the user asked you to open",
+ );
+ expect(wrapUp.steerText(stage)).not.toContain(
+ "open the draft pull request",
+ );
+ }
+ });
+
+ test("snapshots the steers it recorded", () => {
+ const guard = new RunBudgetGuard(
+ 1,
+ DEFAULT_MODEL_PRICES,
+ logger,
+ "publish",
+ );
+ guard.recordAssistantMessage(opusCall("m1", 1_500_000));
+ guard.recordSteer("warn", false);
+ guard.recordSteer("warn", true);
+ expect(guard.snapshot()).toMatchObject({
+ cap_usd: 1,
+ stage: "warn",
+ mode: "publish",
+ steers: [
+ { stage: "warn", delivered: false },
+ { stage: "warn", delivered: true },
+ ],
+ });
+ });
+});
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
new file mode 100644
index 000000000000..a51dfda7d02a
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/budget-guard.ts
@@ -0,0 +1,412 @@
+import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";
+import type { Logger } from "../../../utils/logger";
+
+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.7;
+export const BUDGET_CRITICAL_RATIO = 0.85;
+export const FAST_MODE_PRICE_MULTIPLIER = 2;
+export const ONE_HOUR_CACHE_WRITE_INPUT_MULTIPLIER = 2;
+
+export type BudgetStage = "ok" | "warn" | "critical";
+export type BudgetSteerStage = Exclude<BudgetStage, "ok">;
+export type BudgetSteerMode = "publish" | "wrap_up";
+export type BudgetSpendSource = "main" | "side";
+
+export interface ModelPrice {
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheWrite: number;
+}
+
+export interface ModelPriceRule {
+ match: RegExp;
+ price: ModelPrice;
+}
+
+export interface BudgetThresholdEvent {
+ stage: BudgetSteerStage;
+ spentUsd: number;
+ capUsd: number;
+}
+
+export interface BudgetSteerRecord {
+ stage: BudgetSteerStage;
+ spent_usd: number;
+ delivered: boolean;
+}
+
+export interface BudgetGuardSnapshot {
+ cap_usd: number;
+ spent_usd: number;
+ estimated_usd: number;
+ sdk_total_usd: number;
+ stage: BudgetStage;
+ mode: BudgetSteerMode;
+ steers: BudgetSteerRecord[];
+}
+
+export interface AssistantUsageLike {
+ id?: string | null;
+ model?: string | null;
+ usage?: {
+ input_tokens?: number | null;
+ output_tokens?: number | null;
+ cache_read_input_tokens?: number | null;
+ cache_creation_input_tokens?: number | null;
+ cache_creation?: {
+ ephemeral_1h_input_tokens?: number | null;
+ ephemeral_5m_input_tokens?: number | null;
+ } | null;
+ speed?: string | null;
+ } | null;
+}
+
+const OPUS_PRICE: ModelPrice = {
+ input: 5,
+ output: 25,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
+};
+
+export const DEFAULT_MODEL_PRICES: readonly ModelPriceRule[] = [
+ {
+ match: /fable|mythos/i,
+ price: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
+ },
+ { match: /opus/i, price: OPUS_PRICE },
+ {
+ match: /sonnet-5/i,
+ price: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 },
+ },
+ {
+ match: /sonnet/i,
+ price: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
+ },
+ {
+ match: /haiku/i,
+ price: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 },
+ },
+ {
+ match: /glm-[\d.]+-flash/i,
+ price: { input: 0.15, output: 0.5, cacheRead: 0.03, cacheWrite: 0.15 },
+ },
+ {
+ match: /glm/i,
+ price: { input: 1.4, output: 4.4, cacheRead: 0.14, cacheWrite: 1.4 },
+ },
+ {
+ match: /kimi/i,
+ price: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3 },
+ },
+ {
+ match: /deepseek/i,
+ price: { input: 0.13, output: 0.26, cacheRead: 0.028, cacheWrite: 0.13 },
+ },
+];
+
+const FAN_OUT_TOOL_NAMES = new Set(["Agent", "Task", "Workflow"]);
+
+const STAGE_RANK: Record<BudgetStage, number> = { ok: 0, warn: 1, critical: 2 };
+
+function isPrice(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
+}
+
+export function parseModelPricesJson(
+ raw: string | undefined,
+ logger: Logger,
+): ModelPriceRule[] | null {
+ if (!raw?.trim()) return null;
+ try {
+ const parsed = JSON.parse(raw) as Record<string, Partial<ModelPrice>>;
+ const rules: ModelPriceRule[] = [];
+ for (const [pattern, price] of Object.entries(parsed)) {
+ if (
+ !isPrice(price?.input) ||
+ !isPrice(price.output) ||
+ !isPrice(price.cacheRead) ||
+ !isPrice(price.cacheWrite)
+ ) {
+ continue;
+ }
+ rules.push({
+ match: new RegExp(pattern, "i"),
+ price: {
+ input: price.input,
+ output: price.output,
+ cacheRead: price.cacheRead,
+ cacheWrite: price.cacheWrite,
+ },
+ });
+ }
+ return rules.length > 0 ? rules : null;
+ } catch (error) {
+ logger.warn(`[BudgetGuard] Ignoring invalid ${BUDGET_PRICES_ENV}`, {
+ error,
+ });
+ return null;
+ }
+}
+
+export function estimateMessageCostUsd(
+ message: AssistantUsageLike,
+ prices: readonly ModelPriceRule[],
+): number {
+ const usage = message.usage;
+ if (!usage) return 0;
+ const model = message.model ?? "";
+ const price =
+ prices.find((rule) => rule.match.test(model))?.price ?? OPUS_PRICE;
+ const cacheWriteTotal = usage.cache_creation_input_tokens ?? 0;
+ const oneHourWrites = Math.min(
+ usage.cache_creation?.ephemeral_1h_input_tokens ?? 0,
+ cacheWriteTotal,
+ );
+ const fiveMinuteWrites = cacheWriteTotal - oneHourWrites;
+ const base =
+ ((usage.input_tokens ?? 0) * price.input +
+ (usage.output_tokens ?? 0) * price.output +
+ (usage.cache_read_input_tokens ?? 0) * price.cacheRead +
+ fiveMinuteWrites * price.cacheWrite +
+ oneHourWrites * price.input * ONE_HOUR_CACHE_WRITE_INPUT_MULTIPLIER) /
+ 1_000_000;
+ return usage.speed === "fast" ? base * FAST_MODE_PRICE_MULTIPLIER : base;
+}
+
+function formatUsd(value: number): string {
+ return `$${value.toFixed(2)}`;
+}
+
+export class RunBudgetGuard {
+ private readonly perMessageUsd = new Map<string, number>();
+ private estimatedUsd = 0;
+ private sideUsd = 0;
+ private sdkBaseUsd = 0;
+ private sdkTotalUsd = 0;
+ private estimatedAtSdkTotal = 0;
+ private stage: BudgetStage = "ok";
+ private deliveredStage: BudgetStage = "ok";
+ private pendingSteer: BudgetSteerStage | null = null;
+ private steerMode: BudgetSteerMode;
+ private readonly steers: BudgetSteerRecord[] = [];
+
+ constructor(
+ readonly capUsd: number,
+ private readonly prices: readonly ModelPriceRule[],
+ private readonly logger: Logger,
+ mode: BudgetSteerMode = "wrap_up",
+ private readonly warnRatio: number = BUDGET_WARN_RATIO,
+ private readonly criticalRatio: number = BUDGET_CRITICAL_RATIO,
+ ) {
+ this.steerMode = mode;
+ }
+
+ static fromEnv(
+ env: NodeJS.ProcessEnv,
+ logger: Logger,
+ mode: BudgetSteerMode = "wrap_up",
+ ): RunBudgetGuard | null {
+ const capUsd = Number.parseFloat(env[BUDGET_CAP_ENV] ?? "");
+ if (!Number.isFinite(capUsd) || capUsd <= 0) return null;
+ const prices =
+ parseModelPricesJson(env[BUDGET_PRICES_ENV], logger) ??
+ DEFAULT_MODEL_PRICES;
+ return new RunBudgetGuard(capUsd, prices, logger, mode);
+ }
+
+ get mode(): BudgetSteerMode {
+ return this.steerMode;
+ }
+
+ setMode(mode: BudgetSteerMode): void {
+ if (mode === this.steerMode) return;
+ this.logger.info("[BudgetGuard] Steer mode changed", {
+ from: this.steerMode,
+ to: mode,
+ });
+ this.steerMode = mode;
+ }
+
+ get spentUsd(): number {
+ const mainEstimatedUsd = this.estimatedUsd - this.sideUsd;
+ const calibrated =
+ this.sdkBaseUsd +
+ this.sdkTotalUsd +
+ this.sideUsd +
+ Math.max(0, mainEstimatedUsd - this.estimatedAtSdkTotal);
+ return Math.max(this.estimatedUsd, calibrated);
+ }
+
+ get ratio(): number {
+ return this.spentUsd / this.capUsd;
+ }
+
+ get currentStage(): BudgetStage {
+ return this.stage;
+ }
+
+ recordAssistantMessage(
+ message: AssistantUsageLike,
+ source: BudgetSpendSource = "main",
+ ): BudgetThresholdEvent | null {
+ const cost = estimateMessageCostUsd(message, this.prices);
+ let added = cost;
+ if (message.id) {
+ const previous = this.perMessageUsd.get(message.id) ?? 0;
+ if (cost <= previous) return this.advanceStage();
+ this.perMessageUsd.set(message.id, cost);
+ added = cost - previous;
+ }
+ this.estimatedUsd += added;
+ if (source === "side") this.sideUsd += added;
+ return this.advanceStage();
+ }
+
+ calibrate(totalCostUsd: number | undefined): BudgetThresholdEvent | null {
+ if (typeof totalCostUsd !== "number" || !Number.isFinite(totalCostUsd)) {
+ return null;
+ }
+ if (totalCostUsd < this.sdkTotalUsd) {
+ this.logger.debug("[BudgetGuard] Ignoring a lower SDK running total", {
+ totalCostUsd,
+ sdkTotalUsd: this.sdkTotalUsd,
+ });
+ return this.advanceStage();
+ }
+ this.sdkTotalUsd = totalCostUsd;
+ this.estimatedAtSdkTotal = this.estimatedUsd - this.sideUsd;
+ return this.advanceStage();
+ }
+
+ onQueryReset(): void {
+ this.sdkBaseUsd += this.sdkTotalUsd;
+ this.sdkTotalUsd = 0;
+ this.estimatedAtSdkTotal = this.estimatedUsd - this.sideUsd;
+ }
+
+ onConversationCleared(): void {
+ this.onQueryReset();
+ this.deliveredStage = "ok";
+ if (this.stage !== "ok") this.pendingSteer = this.stage;
+ }
+
+ takePendingSteer(): BudgetSteerStage | null {
+ const stage = this.pendingSteer;
+ this.pendingSteer = null;
+ return stage;
+ }
+
+ markUndelivered(stage: BudgetSteerStage): void {
+ if (STAGE_RANK[stage] <= STAGE_RANK[this.deliveredStage]) return;
+ if (
+ this.pendingSteer === null ||
+ STAGE_RANK[stage] > STAGE_RANK[this.pendingSteer]
+ ) {
+ this.pendingSteer = stage;
+ }
+ }
+
+ recordSteer(stage: BudgetSteerStage, delivered: boolean): BudgetSteerRecord {
+ const record = { stage, spent_usd: this.spentUsd, delivered };
+ this.steers.push(record);
+ if (delivered && STAGE_RANK[stage] > STAGE_RANK[this.deliveredStage]) {
+ this.deliveredStage = stage;
+ }
+ return record;
+ }
+
+ snapshot(): BudgetGuardSnapshot {
+ return {
+ cap_usd: this.capUsd,
+ spent_usd: this.spentUsd,
+ estimated_usd: this.estimatedUsd,
+ sdk_total_usd: this.sdkBaseUsd + this.sdkTotalUsd,
+ stage: this.stage,
+ mode: this.mode,
+ steers: [...this.steers],
+ };
+ }
+
+ steerText(stage: BudgetSteerStage): string {
+ const spent = formatUsd(this.spentUsd);
+ const cap = formatUsd(this.capUsd);
+ if (this.mode === "publish") {
+ if (stage === "critical") {
+ return (
+ `Budget critical: this run has used about ${spent} of its ${cap} model budget. ` +
+ "The gateway will refuse further calls very soon and everything uncommitted is lost then. " +
+ "Stop new work now. Stage what is on disk and commit it with the git_signed_commit tool " +
+ "(it publishes the commit for you; raw git commit and git push are blocked here), then open " +
+ "or update the pull request and end your turn with a two-line summary. " +
+ "Do not start subagents or workflows, and do not run further test or review passes."
+ );
+ }
+ return (
+ `Budget notice: this run has used about ${spent} of its ${cap} model budget. ` +
+ "Wrap up now. Finish the smallest coherent version of the change, run only the tests you " +
+ "already touched, then stage and commit with the git_signed_commit tool (it publishes the " +
+ "commit for you; raw git commit and git push are blocked here) and open the draft pull request. " +
+ "Skip optional polish such as /simplify or parallel review subagents: an open PR is what " +
+ "preserves the work. If a PR is already open, commit what you have and stop."
+ );
+ }
+ const explicitPr =
+ "If the user asked you to open or update a pull request, commit what is on disk with the " +
+ "git_signed_commit tool and do that first. ";
+ if (stage === "critical") {
+ return (
+ `Budget critical: this run has used about ${spent} of its ${cap} model budget. ` +
+ "The gateway will refuse further calls very soon. Stop new work now. " +
+ explicitPr +
+ "Then end your turn with your result so far: what is done, what is not, and what you found. " +
+ "Do not start subagents or workflows, and do not read or run anything else."
+ );
+ }
+ return (
+ `Budget notice: this run has used about ${spent} of its ${cap} model budget. ` +
+ "Wrap up now. Finish the step you are on, then give your result with what you have. " +
+ explicitPr +
+ "Skip further exploration, optional checks, and parallel subagents."
+ );
+ }
+
+ preToolUseHook(): HookCallback {
+ return async (input: HookInput) => {
+ if (input.hook_event_name !== "PreToolUse") return { continue: true };
+ if (!FAN_OUT_TOOL_NAMES.has(input.tool_name)) return { continue: true };
+ if (this.stage !== "critical") return { continue: true };
+ this.logger.warn(
+ `[BudgetGuard] Blocking ${input.tool_name} spawn at ${formatUsd(this.spentUsd)} of ${formatUsd(this.capUsd)}`,
+ );
+ const next =
+ this.mode === "publish"
+ ? "Commit what is on disk with the git_signed_commit tool and open or update the pull request yourself."
+ : "Finish with the result you have.";
+ 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 new subagents or workflows can start. ${next}`,
+ },
+ };
+ };
+ }
+
+ private advanceStage(): BudgetThresholdEvent | null {
+ const ratio = this.ratio;
+ let next: BudgetStage = "ok";
+ if (ratio >= this.criticalRatio) next = "critical";
+ else if (ratio >= this.warnRatio) next = "warn";
+ if (next === "ok" || next === this.stage || this.stage === "critical") {
+ return null;
+ }
+ this.stage = next;
+ this.pendingSteer = next;
+ return { stage: next, spentUsd: this.spentUsd, capUsd: this.capUsd };
+ }
+}
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 2f79e80e0367..3e5f0581fc7d 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -51,6 +51,7 @@ import {
} from "../machine-auth";
import { type CodeExecutionMode, toSdkPermissionMode } from "../tools";
import type { EffortLevel } from "../types";
+import type { RunBudgetGuard } from "./budget-guard";
import { loadUserClaudeJsonMcpServers } from "./mcp-config";
import { DEFAULT_MODEL, resolveFallbackModel } from "./models";
import { createRtkRewriteHook } from "./rtk-hook";
@@ -132,6 +133,7 @@ export interface BuildOptionsParams {
machineAuth?: MachineClaudeAuth;
/** Matched `bedrock-llm-gateway` variant; `test` serves this session from Bedrock. */
bedrockGatewayVariant?: BedrockGatewayVariant;
+ budgetGuard?: RunBudgetGuard;
/** Per-session context wiki mount — prevents global process.env mutation. */
contextWiki?: ContextWikiEnv;
}
@@ -378,6 +380,7 @@ function buildHooks(
taskState: TaskState,
onTaskStateChange: (() => Promise<void>) | undefined,
rtkPrefix: string | undefined,
+ budgetGuard: RunBudgetGuard | undefined,
): Options["hooks"] {
const postToolUseHooks = [
createReadImageGuardHook(),
@@ -401,6 +404,9 @@ function buildHooks(
createSignedCommitGuardHook(logger, onEnsureLocalToolsConnected),
);
}
+ if (budgetGuard) {
+ preToolUseHooks.push(budgetGuard.preToolUseHook());
+ }
// Registered last so the signed-commit guard evaluates the raw command first.
if (rtkPrefix) {
preToolUseHooks.push(createRtkRewriteHook(rtkPrefix, logger));
@@ -696,6 +702,7 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
params.taskState,
params.onTaskStateChange,
resolveRtkPrefix(process.env),
+ params.budgetGuard,
),
outputFormat: params.outputFormat,
abortController: getAbortController(
diff --git a/products/desktop/packages/agent/src/adapters/claude/side-question.ts b/products/desktop/packages/agent/src/adapters/claude/side-question.ts
index 2b9cad759335..0c161a77ce6e 100644
--- a/products/desktop/packages/agent/src/adapters/claude/side-question.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/side-question.ts
@@ -4,7 +4,10 @@
*/
import { RequestError } from "@agentclientprotocol/sdk";
-import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
+import type {
+ SDKAssistantMessage,
+ SDKMessage,
+} from "@anthropic-ai/claude-agent-sdk";
export const SIDE_QUESTION_TIMEOUT_MS = 120_000;
@@ -14,10 +17,12 @@ export const SIDE_QUESTION_TIMEOUT_MS = 120_000;
*/
export async function collectSideQuestionAnswer(
messages: AsyncIterable<SDKMessage>,
+ onAssistantMessage?: (message: SDKAssistantMessage) => void,
): Promise<string> {
const chunks: string[] = [];
for await (const message of messages) {
if (message.type === "assistant") {
+ onAssistantMessage?.(message);
for (const block of message.message.content) {
if (block.type === "text") {
chunks.push(block.text);
diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.ts
index ff818531c593..1bae51de1c1f 100644
--- a/products/desktop/packages/agent/src/adapters/claude/types.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts
@@ -20,6 +20,7 @@ import type { BaseSession } from "../base-acp-agent";
import type { ContextBreakdownBaseline } from "./context-breakdown";
import type { TaskState } from "./conversion/task-state";
import type { McpToolApprovals } from "./mcp/tool-metadata";
+import type { RunBudgetGuard } from "./session/budget-guard";
import type { SettingsManager } from "./session/settings";
import type { CodeExecutionMode } from "./tools";
@@ -122,6 +123,10 @@ export type Session = BaseSession & {
traceparentHookInstalled: boolean;
configOptions: SessionConfigOption[];
accumulatedUsage: AccumulatedUsage;
+ budgetGuard?: RunBudgetGuard;
+ backgroundTurnActive?: boolean;
+ backgroundSteers?: Map<string, PendingSteer>;
+ backgroundSteerTimer?: ReturnType<typeof setTimeout>;
/** PostHog products used during this session, derived from MCP exec calls.
* Accumulates for the whole session (deduped); each newly-seen product is
* emitted immediately so the client can show a persistent, de-duplicated
@@ -258,6 +263,7 @@ export type NewSessionMeta = {
* runtime whether it needs a repo and clones one only if so.
*/
channelMode?: boolean;
+ budgetSteer?: { mode?: "publish" | "wrap_up" };
taskOriginProduct?: string;
/** Workflow-action opt-in: exposes the `finish` tool to a workflow-origin run. */
endRunWhenDone?: boolean;
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 548732db3506..bd08a9648e10 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -1331,6 +1331,13 @@ describe("AgentServer HTTP Mode", () => {
expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
});
+ function usageUpdateWithBudget(budget: Record<string, unknown>) {
+ return {
+ method: POSTHOG_NOTIFICATIONS.USAGE_UPDATE,
+ params: { sessionId: "s", usage: {}, budget },
+ };
+ }
+
function createUsageTestServer() {
const testServer = new AgentServer({
port,
@@ -1346,6 +1353,7 @@ describe("AgentServer HTTP Mode", () => {
session: { payload: JwtPayload } | null;
posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };
recordTurnUsage(usage: unknown): void;
+ handleAcpTransportMessage(message: unknown): void;
};
testServer.posthogAPI = { updateTaskRun: vi.fn(async () => ({})) };
testServer.session = {
@@ -1423,14 +1431,26 @@ describe("AgentServer HTTP Mode", () => {
expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
});
- it("resets run usage on session cleanup so a later run starts from zero", async () => {
+ it("resets run usage and the budget snapshot on session cleanup so a later run starts from zero", async () => {
const testServer = createUsageTestServer();
const turnUsage = {
inputTokens: 100,
outputTokens: 50,
totalTokens: 150,
};
+ testServer.handleAcpTransportMessage(
+ usageUpdateWithBudget({ stage: "critical", steers: [] }),
+ );
testServer.recordTurnUsage(turnUsage);
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenLastCalledWith(
+ "task-1",
+ "run-1",
+ expect.objectContaining({
+ state: expect.objectContaining({
+ budget_guard: { stage: "critical", steers: [] },
+ }),
+ }),
+ );
const cleanupServer = stubSessionCleanup(testServer);
await cleanupServer.cleanupSession();
@@ -1466,6 +1486,32 @@ describe("AgentServer HTTP Mode", () => {
);
});
+ it("retries a budget snapshot whose write failed, and skips one that landed", async () => {
+ const testServer = createUsageTestServer();
+ testServer.posthogAPI.updateTaskRun
+ .mockRejectedValueOnce(new Error("503"))
+ .mockResolvedValue({});
+ const budget = { stage: "warn", steers: [{ stage: "warn" }] };
+
+ const settled = () => new Promise((resolve) => setImmediate(resolve));
+
+ testServer.handleAcpTransportMessage(usageUpdateWithBudget(budget));
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(1);
+ await settled();
+ testServer.handleAcpTransportMessage(usageUpdateWithBudget(budget));
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(2);
+ await settled();
+ testServer.handleAcpTransportMessage(usageUpdateWithBudget(budget));
+ testServer.handleAcpTransportMessage(usageUpdateWithBudget(budget));
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(2);
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenLastCalledWith(
+ "task-1",
+ "run-1",
+ { state: { budget_guard: budget } },
+ expect.any(AbortSignal),
+ );
+ });
+
// Sandbox teardown kills the exec'd agent-server without SIGTERM, so the
// trace's root span only exports if telemetry is shut down at the run's
// in-process terminal points.
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index dc6c2e437744..6a5bb2dec5d4 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -242,6 +242,21 @@ function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+function budgetSnapshotFromUsageUpdate(
+ message: unknown,
+): Record<string, unknown> | undefined {
+ if (typeof message !== "object" || message === null) return undefined;
+ const { method, params } = message as {
+ method?: unknown;
+ params?: { budget?: unknown };
+ };
+ if (method !== POSTHOG_NOTIFICATIONS.USAGE_UPDATE) return undefined;
+ const budget = params?.budget;
+ return typeof budget === "object" && budget !== null
+ ? (budget as Record<string, unknown>)
+ : undefined;
+}
+
export function isTurnCompleteNotification(message: unknown): boolean {
return (
typeof message === "object" &&
@@ -1370,6 +1385,7 @@ export class AgentServer {
const promptMeta: Record<string, unknown> = {
...(builtPrompt.meta ?? {}),
...(messageId ? { messageId } : {}),
+ budgetSteerMode: this.budgetSteerMode(),
...(hostContext.length > 0
? { prContext: hostContext.join("\n\n") }
: {}),
@@ -1956,6 +1972,9 @@ export class AgentServer {
this.runUsage = new RunUsageAccumulator();
this.runUsageRunId = payload.run_id;
+ this.lastBudgetSnapshot = undefined;
+ this.lastPersistedBudgetKey = undefined;
+ this.budgetPersistInFlightKey = undefined;
seedRunUsage(this.runUsage, preTaskRun?.state.token_usage);
this.prewarmedRun = preTaskRun?.state.prewarmed === true;
this.prewarmedStartupTurnPending = this.prewarmedRun;
@@ -2208,6 +2227,7 @@ export class AgentServer {
jsonSchema: preTask?.json_schema ?? null,
permissionMode: initialPermissionMode,
...(channelMode && { channelMode: true }),
+ budgetSteer: { mode: this.budgetSteerMode() },
posthogExecPermissionRegex: this.posthogExecPermissionRegexSource,
...(preTask?.origin_product && {
taskOriginProduct: preTask.origin_product,
@@ -4242,6 +4262,10 @@ export class AgentServer {
);
}
+ private budgetSteerMode(): "publish" | "wrap_up" {
+ return this.shouldAutoPublishCloudChanges() ? "publish" : "wrap_up";
+ }
+
/**
* Apply settings from run state before the first turn when launch config is
* incomplete, and return the host-context blocks that prompt needs for them.
@@ -5444,6 +5468,9 @@ export class AgentServer {
// with a different run_id) must not inherit the previous run's totals.
this.runUsage = new RunUsageAccumulator();
this.runUsageRunId = null;
+ this.lastBudgetSnapshot = undefined;
+ this.lastPersistedBudgetKey = undefined;
+ this.budgetPersistInFlightKey = undefined;
this.session = null;
}
@@ -5491,10 +5518,53 @@ export class AgentServer {
payload.task_id,
payload.run_id,
this.logger,
+ this.lastBudgetSnapshot && { budget_guard: this.lastBudgetSnapshot },
);
}
+ private lastBudgetSnapshot: Record<string, unknown> | undefined;
+ private lastPersistedBudgetKey: string | undefined;
+ private budgetPersistInFlightKey: string | undefined;
+
+ private persistBudgetSnapshotIfChanged(
+ budget: Record<string, unknown>,
+ ): void {
+ const payload = this.session?.payload;
+ if (!payload) return;
+ const key = JSON.stringify([payload.run_id, budget.stage, budget.steers]);
+ if (
+ key === this.lastPersistedBudgetKey ||
+ key === this.budgetPersistInFlightKey
+ ) {
+ return;
+ }
+ this.budgetPersistInFlightKey = key;
+ this.posthogAPI
+ .updateTaskRun(
+ payload.task_id,
+ payload.run_id,
+ { state: { budget_guard: budget } },
+ AbortSignal.timeout(30_000),
+ )
+ .then(() => {
+ this.lastPersistedBudgetKey = key;
+ })
+ .catch((error: unknown) => {
+ this.logger.debug("Failed to persist the budget snapshot", { error });
+ })
+ .finally(() => {
+ if (this.budgetPersistInFlightKey === key) {
+ this.budgetPersistInFlightKey = undefined;
+ }
+ });
+ }
+
private handleAcpTransportMessage(message: unknown, eventId?: string): void {
+ const budget = budgetSnapshotFromUsageUpdate(message);
+ if (budget) {
+ this.lastBudgetSnapshot = budget;
+ this.persistBudgetSnapshotIfChanged(budget);
+ }
if (isTurnCompleteNotification(message)) {
if (this.suppressAdapterTurnComplete) {
return;
diff --git a/products/desktop/packages/agent/src/server/run-usage.test.ts b/products/desktop/packages/agent/src/server/run-usage.test.ts
index cbb98045f6d3..4df82c1252c4 100644
--- a/products/desktop/packages/agent/src/server/run-usage.test.ts
+++ b/products/desktop/packages/agent/src/server/run-usage.test.ts
@@ -131,14 +131,19 @@ describe("RunUsageAccumulator", () => {
acc.add({ inputTokens: 1, outputTokens: 1, totalTokens: 2 });
const first = reportRunUsage(acc, api, "task-1", "run-1", logger);
acc.add({ inputTokens: 1, outputTokens: 1, totalTokens: 2 });
- const second = reportRunUsage(acc, api, "task-1", "run-1", logger);
+ const second = reportRunUsage(acc, api, "task-1", "run-1", logger, {
+ budget_guard: { stage: "warn" },
+ });
expect(updateTaskRun).toHaveBeenCalledTimes(1);
settle[0]();
await first;
expect(updateTaskRun).toHaveBeenCalledTimes(2);
expect(updateTaskRun.mock.calls[1][2]).toEqual({
- state: { token_usage: expect.objectContaining({ turns: 2 }) },
+ state: {
+ token_usage: expect.objectContaining({ turns: 2 }),
+ budget_guard: { stage: "warn" },
+ },
});
settle[1]();
await second;
diff --git a/products/desktop/packages/agent/src/server/run-usage.ts b/products/desktop/packages/agent/src/server/run-usage.ts
index baea9ff43323..ae8ebd228867 100644
--- a/products/desktop/packages/agent/src/server/run-usage.ts
+++ b/products/desktop/packages/agent/src/server/run-usage.ts
@@ -88,11 +88,12 @@ export function reportRunUsage(
taskId: string,
runId: string,
logger: Logger,
+ extraState?: Record<string, unknown> | false,
): Promise<void> {
const send = (): Promise<void> =>
api
.updateTaskRun(taskId, runId, {
- state: { token_usage: accumulator.snapshot() },
+ state: { token_usage: accumulator.snapshot(), ...(extraState || {}) },
})
.then(
() => undefined,
diff --git a/products/desktop/packages/shared/src/transcript-neutral-notifications.ts b/products/desktop/packages/shared/src/transcript-neutral-notifications.ts
index 850563d46e3c..514289b81fb3 100644
--- a/products/desktop/packages/shared/src/transcript-neutral-notifications.ts
+++ b/products/desktop/packages/shared/src/transcript-neutral-notifications.ts
@@ -17,6 +17,7 @@ const TRANSCRIPT_NEUTRAL_NOTIFICATION_METHODS = [
"_posthog/usage_update",
"_posthog/resources_used",
"_posthog/rtk_savings",
+ "_posthog/budget_steer",
"_posthog/codex_goal",
];
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index a780511dfb54..3a2949e9ce08 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -453,6 +453,7 @@ RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset(
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_TOKEN_CAP_USD",
"AI_GATEWAY_PRODUCT",
"AI_GATEWAY_AI_STAGE",
"POSTHOG_RESUME_RUN_ID",
diff --git a/products/tasks/backend/logic/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.py
index 5ef06a71a6fa..295e3a4afbc0 100644
--- a/products/tasks/backend/logic/services/agentsh.py
+++ b/products/tasks/backend/logic/services/agentsh.py
@@ -530,6 +530,7 @@ def generate_policy_yaml(allowed_domains: list[str] | None = None) -> str:
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_TOKEN_CAP_USD",
"AI_GATEWAY_PRODUCT",
"AI_GATEWAY_AI_STAGE",
"IS_SANDBOX",
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 46cd8d0ab4fb..47e1ca7c1d5e 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -15,7 +15,7 @@ import structlog
from asgiref.sync import sync_to_async
from jwt import PyJWTError
-from posthog.ph_client import ph_scoped_capture
+from posthog.ph_client import ph_background_capture, ph_scoped_capture
from products.tasks.backend.facade.api import signal_workflow_completion
from products.tasks.backend.logic.services.connection_token import (
@@ -48,6 +48,9 @@ MAX_EVENTS_PER_REQUEST = 1_000
STREAM_COMPLETE_CONTROL_TYPE = "_posthog/stream_complete"
RTK_SAVINGS_SIDE_EFFECT = "rtk-savings"
RTK_SAVINGS_CAPTURE_LOCK_SECONDS = 60
+BUDGET_STEER_SIDE_EFFECT = "budget-steer"
+BUDGET_STEER_STAGES = frozenset({"warn", "critical"})
+BUDGET_STEER_MODES = frozenset({"publish", "wrap_up"})
ASGIMessage = dict[str, object]
ASGIReceive = Callable[[], Awaitable[ASGIMessage]]
@@ -202,12 +205,17 @@ async def _ingest_event_lines(
sequence = parsed_line.sequence
event = parsed_line.event
rtk_savings_properties = _parse_rtk_savings_properties(claims, event)
+ budget_steer_properties = _parse_budget_steer_properties(claims, event)
+ pending_side_effect = None
+ if rtk_savings_properties is not None:
+ pending_side_effect = RTK_SAVINGS_SIDE_EFFECT
+ elif budget_steer_properties is not None:
+ pending_side_effect = BUDGET_STEER_SIDE_EFFECT
write = await redis_stream.write_event_with_sequence(
- event,
- sequence,
- pending_side_effect=RTK_SAVINGS_SIDE_EFFECT if rtk_savings_properties is not None else None,
+ event, sequence, pending_side_effect=pending_side_effect
)
await _capture_rtk_savings_if_needed(redis_stream, claims, sequence, rtk_savings_properties)
+ await _capture_budget_steer_if_needed(redis_stream, claims, sequence, budget_steer_properties)
if not write.accepted:
result.duplicate += 1
result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())
@@ -265,6 +273,83 @@ def _capture_rtk_savings(team_id: int, event_uuid: str, properties: dict[str, st
)
+async def _capture_budget_steer_if_needed(
+ redis_stream: TaskRunRedisStream,
+ claims: SandboxEventIngestTokenPayload,
+ sequence: int,
+ properties: dict[str, str | int | float | bool] | None,
+) -> None:
+ if properties is None:
+ return
+ capture_claim = await redis_stream.claim_pending_side_effect(
+ BUDGET_STEER_SIDE_EFFECT, sequence, RTK_SAVINGS_CAPTURE_LOCK_SECONDS
+ )
+ if not capture_claim:
+ return
+ try:
+ event_uuid = str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{claims.run_id}:{sequence}"))
+ _capture_budget_steer(claims.team_id, event_uuid, properties)
+ except Exception:
+ await redis_stream.release_pending_side_effect(BUDGET_STEER_SIDE_EFFECT, sequence)
+ logger.warning("task_run_budget_steer_capture_failed", run_id=claims.run_id, exc_info=True)
+ return
+ await redis_stream.complete_pending_side_effect(BUDGET_STEER_SIDE_EFFECT, sequence)
+
+
+def _capture_budget_steer(team_id: int, event_uuid: str, properties: dict[str, str | int | float | bool]) -> None:
+ ph_background_capture()(
+ distinct_id=f"team_{team_id}",
+ event="task run budget steer",
+ properties=properties,
+ uuid=event_uuid,
+ )
+
+
+def _parse_budget_steer_properties(
+ claims: SandboxEventIngestTokenPayload, event: dict
+) -> dict[str, str | int | float | bool] | None:
+ notification = event.get("notification")
+ if not isinstance(notification, dict) or notification.get("method") != "_posthog/budget_steer":
+ return None
+ params = notification.get("params")
+ if not isinstance(params, dict):
+ return None
+ stage = params.get("stage")
+ mode = params.get("mode")
+ delivered = params.get("delivered")
+ if not isinstance(stage, str) or stage not in BUDGET_STEER_STAGES:
+ return None
+ if not isinstance(mode, str) or mode not in BUDGET_STEER_MODES or not isinstance(delivered, bool):
+ return None
+ amounts: dict[str, float] = {}
+ for key in ("spent_usd", "cap_usd"):
+ amount = _parse_usd_amount(params.get(key))
+ if amount is None:
+ return None
+ amounts[key] = amount
+ return {
+ "team_id": claims.team_id,
+ "task_id": claims.task_id,
+ "run_id": claims.run_id,
+ "stage": stage,
+ "mode": mode,
+ "delivered": delivered,
+ **amounts,
+ }
+
+
+def _parse_usd_amount(value: object) -> float | None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ amount = float(value)
+ except OverflowError:
+ return None
+ if not math.isfinite(amount) or amount < 0:
+ return None
+ return amount
+
+
def _parse_rtk_savings_properties(claims: SandboxEventIngestTokenPayload, event: dict) -> dict[str, str | int] | None:
notification = event.get("notification")
if not isinstance(notification, dict) or notification.get("method") != "_posthog/rtk_savings":
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 228f834a3e1b..eb8983797271 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2901,6 +2901,22 @@ class TaskRun(models.Model):
benjamin_version = state.get("benjamin_version")
if isinstance(benjamin_version, str) and benjamin_version:
props["benjamin_version"] = benjamin_version
+ budget = state.get("budget_guard")
+ if isinstance(budget, dict):
+ for key in ("cap_usd", "spent_usd", "estimated_usd", "sdk_total_usd"):
+ value = budget.get(key)
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ props[f"budget_{key}"] = value
+ for key in ("stage", "mode"):
+ value = budget.get(key)
+ if isinstance(value, str) and value:
+ props[f"budget_{key}"] = value
+ steers = budget.get("steers")
+ if isinstance(steers, list):
+ props["budget_steers"] = len(steers)
+ props["budget_steers_delivered"] = sum(
+ 1 for steer in steers if isinstance(steer, dict) and steer.get("delivered") is True
+ )
return props
def analytics_properties(self) -> dict:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index ebee73ee276b..4b084ff9d520 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -247,6 +247,13 @@ class TestUpdateTaskRunStatusActivity:
"benjamin_version": "2026.08.1",
"model": "gpt-5.6-sol",
"runtime_adapter": "codex",
+ "budget_guard": {
+ "cap_usd": 20,
+ "spent_usd": 14.5,
+ "stage": "warn",
+ "mode": "publish",
+ "steers": [{"stage": "warn", "spent_usd": 14.1, "delivered": True}],
+ },
}
test_task_run.save(update_fields=["state"])
@@ -268,6 +275,11 @@ class TestUpdateTaskRunStatusActivity:
assert props["benjamin_version"] == "2026.08.1"
assert props["run_environment"] == test_task_run.environment
assert props["termination_reason"] is None
+ assert props["budget_cap_usd"] == 20
+ assert props["budget_spent_usd"] == 14.5
+ assert props["budget_stage"] == "warn"
+ assert props["budget_steers"] == 1
+ assert props["budget_steers_delivered"] == 1
mock_record.assert_called_once()
assert mock_record.call_args.kwargs["rtk_enabled"] is True
assert mock_record.call_args.kwargs["benjamin_enabled"] is True
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
index c008b339f3dc..96a7b04ddcae 100644
--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
@@ -222,7 +222,7 @@ def _cap_override(raw: str, key: str, setting_name: str) -> str | None:
return f"{cap:f}"
-def _token_cap_usd(team_id: int, ai_product: str) -> str:
+def token_cap_usd(team_id: int, ai_product: str) -> str:
"""Per-run cap: the product override, else the team override, else the default.
The product override wins because run cost tracks the kind of work, not who
@@ -255,7 +255,7 @@ def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None)
return None
body: dict[str, Any] = {
- "cap_usd": _token_cap_usd(team_id, ai_product),
+ "cap_usd": token_cap_usd(team_id, ai_product),
"ttl_seconds": _token_ttl_seconds(ai_product),
"product": ai_product,
"obo": str(team_id),
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index eb76cf22bdd9..d41fc9aad3c2 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -284,6 +284,7 @@ class TestAiGatewayEnvVars:
"AI_GATEWAY_URL": "https://ai-gateway.dev.posthog.dev",
"AI_GATEWAY_PRODUCTS": "signals_scout,signals_research",
"AI_GATEWAY_TOKEN": "phe_abc",
+ "AI_GATEWAY_TOKEN_CAP_USD": "3",
"AI_GATEWAY_PRODUCT": "signals_scout",
"AI_GATEWAY_AI_STAGE": "scout:logs",
}
@@ -311,6 +312,7 @@ class TestAiGatewayEnvVars:
def test_reserved_keys_cover_the_pinned_product_env(self):
assert "AI_GATEWAY_PRODUCT" in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
assert "AI_GATEWAY_AI_STAGE" in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
+ assert "AI_GATEWAY_TOKEN_CAP_USD" in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
def test_skill_qualified_allowlist_still_mints(self, mint_settings):
"""The D4-D6 batched scout flips route by skill-qualified entries alone; a mint
@@ -537,7 +539,12 @@ class TestProvisioningBoundaries:
assert utils.run_gateway_env_vars(self._ctx(), self._task()) == {}
def test_a_pinned_token_the_stamp_could_not_record_is_dropped(self, mint_settings):
- env = {"AI_GATEWAY_URL": "url", "AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "slack_app"}
+ env = {
+ "AI_GATEWAY_URL": "url",
+ "AI_GATEWAY_TOKEN": "phe",
+ "AI_GATEWAY_TOKEN_CAP_USD": "75",
+ "AI_GATEWAY_PRODUCT": "slack_app",
+ }
with (
patch.object(utils, "ai_gateway_env_vars", return_value=env),
patch(
@@ -547,6 +554,7 @@ class TestProvisioningBoundaries:
):
out = utils.run_gateway_env_vars(self._ctx(), self._task())
assert "AI_GATEWAY_TOKEN" not in out
+ assert "AI_GATEWAY_TOKEN_CAP_USD" not in out
assert out["AI_GATEWAY_URL"] == "url"
def test_an_unpinned_token_survives_a_failed_stamp_removal(self, mint_settings):
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 09f3a2e1b4a2..fbba3a37042a 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -57,6 +57,7 @@ from products.tasks.backend.temporal.process_task.ai_gateway_token import (
mint_scoped_token,
resolve_sandbox_ai_product,
sandbox_product_routed,
+ token_cap_usd,
)
if TYPE_CHECKING:
@@ -1374,6 +1375,7 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:
if not _record_pinned_gateway_product(ctx.run_id, ctx.state, env_vars.get("AI_GATEWAY_PRODUCT")):
# The model-change guard reads that stamp; unstamped, a run can move off its pin with no fallback.
env_vars.pop("AI_GATEWAY_TOKEN", None)
+ env_vars.pop("AI_GATEWAY_TOKEN_CAP_USD", None)
return env_vars
@@ -1442,6 +1444,7 @@ def ai_gateway_env_vars(
token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id)
if token:
env_vars["AI_GATEWAY_TOKEN"] = token
+ env_vars["AI_GATEWAY_TOKEN_CAP_USD"] = token_cap_usd(team_id, ai_product)
env_vars["AI_GATEWAY_PRODUCT"] = ai_product
if ai_stage:
env_vars["AI_GATEWAY_AI_STAGE"] = ai_stage
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index 01831cbba05e..0106be028483 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -151,6 +151,7 @@ class TestGeneratePolicyYaml(TestCase):
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_PRODUCT",
"AI_GATEWAY_AI_STAGE",
+ "AI_GATEWAY_TOKEN_CAP_USD",
):
self.assertIn(key, policy["env_policy"]["allow"])
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index 6c81d37bb590..86a8320f8412 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -336,6 +336,83 @@ class TestTaskRunEventIngest(TestCase):
},
)
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_budget_steer_capture_uses_authenticated_ids_and_rejects_malformed_params(self) -> None:
+ token = self._create_token()
+
+ def event(seq: int, params: dict) -> dict:
+ return {
+ "seq": seq,
+ "event": {
+ "type": "notification",
+ "notification": {"method": "_posthog/budget_steer", "params": params},
+ },
+ }
+
+ good = event(
+ 1,
+ {
+ "sessionId": "spoofed-run",
+ "stage": "warn",
+ "mode": "publish",
+ "delivered": True,
+ "spent_usd": 14.1,
+ "cap_usd": 20,
+ },
+ )
+ bad_stage = event(2, {"stage": "later", "mode": "publish", "delivered": True, "spent_usd": 1, "cap_usd": 2})
+ bad_amount = event(3, {"stage": "warn", "mode": "publish", "delivered": True, "spent_usd": -1, "cap_usd": 2})
+ list_stage = event(4, {"stage": ["warn"], "mode": "publish", "delivered": True, "spent_usd": 1, "cap_usd": 2})
+ huge_amount = event(
+ 5, {"stage": "warn", "mode": "publish", "delivered": True, "spent_usd": 10**400, "cap_usd": 2}
+ )
+
+ with patch("products.tasks.backend.logic.stream.event_ingest._capture_budget_steer") as capture_budget_steer:
+ first_status, _ = self._call_ingest(token, [good, bad_stage, bad_amount, list_stage, huge_amount])
+ duplicate_status, duplicate_body = self._call_ingest(token, [good])
+
+ self.assertEqual(first_status, 200)
+ self.assertEqual(duplicate_status, 200)
+ self.assertEqual(duplicate_body["duplicate"], 1)
+ capture_budget_steer.assert_called_once_with(
+ self.team.id,
+ str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{self.task_run.id}:1")),
+ {
+ "team_id": self.team.id,
+ "task_id": str(self.task.id),
+ "run_id": str(self.task_run.id),
+ "stage": "warn",
+ "mode": "publish",
+ "delivered": True,
+ "spent_usd": 14.1,
+ "cap_usd": 20.0,
+ },
+ )
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_budget_steer_capture_failure_does_not_block_the_stream(self) -> None:
+ token = self._create_token()
+ event = {
+ "seq": 1,
+ "event": {
+ "type": "notification",
+ "notification": {
+ "method": "_posthog/budget_steer",
+ "params": {"stage": "warn", "mode": "publish", "delivered": True, "spent_usd": 7, "cap_usd": 10},
+ },
+ },
+ }
+
+ with patch(
+ "products.tasks.backend.logic.stream.event_ingest._capture_budget_steer",
+ side_effect=RuntimeError("capture failed"),
+ ):
+ status, body = self._call_ingest(token, [event])
+
+ self.assertEqual(status, 200)
+ self.assertEqual(body["accepted"], 1)
+ self.assertEqual(self._read_notification_methods(), ["_posthog/budget_steer"])
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_rtk_savings_capture_failure_can_be_retried(self) -> None:
token = self._create_token()