: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): fire the budget guard early enough to survive the cap (#105038)
posthog[bot]d999759f9054
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.mdindex 3c3f1a432ed3..69fe2cfbf30c 100644--- a/docs/internal/task-run-api.md+++ b/docs/internal/task-run-api.md@@ -52,6 +52,13 @@ When event ingest is enabled, the agent server does not also retain events for aAn attached SSE client still receives live events.Runs without event ingest buffer events until an SSE client attaches.The Claude adapter forwards partial tool inputs without retaining each intermediate snapshot in session history.+Budget-steer notifications remain in the event stream.+The standalone agent-proxy asks the authenticated Django callback to queue each steer for analytics and retries a failed dispatch.+Direct Django ingest queues the same work without a callback, so analytics delivery does not delay later stream events.+A Celery task captures the event and retries upload failures up to five times with backoff.+Both paths preserve the event timestamp and derive the analytics event ID from the run and event sequence.+If an older payload has no timestamp, Django stores its first received time for retries and replays.+Successful captures are recorded for the event ingest token's lifetime so completed work is skipped on replay.## Run summariesdiff --git a/posthog/ph_client.py b/posthog/ph_client.pyindex cc6573af3f12..b3c37fe7b414 100644--- a/posthog/ph_client.py+++ b/posthog/ph_client.py@@ -1,7 +1,7 @@import osimport atexitimport threading-from collections.abc import Mapping+from collections.abc import Iterator, Mappingfrom contextlib import contextmanagerfrom numbers import Numberfrom typing import Any, cast@@ -133,7 +133,7 @@ class ScopedCapture:@contextmanager-def ph_scoped_capture(region: str = "US"):+def ph_scoped_capture(region: str = "US", *, raise_on_error: bool = False) -> Iterator[ScopedCapture]:"""Use this instead of posthoganalytics.capture() in Celery tasks — the globalclient's background flush may never run before the worker exits, silently losing events.This creates a dedicated client and flushes on context-manager exit.@@ -147,7 +147,12 @@ def ph_scoped_capture(region: str = "US"):with ph_scoped_capture() as capture:capture(distinct_id="...", event="my_event", properties={...})"""- ph_client = get_client(region)+ errors: list[Exception] = []++ def on_error(error: Exception, _batch: object) -> None:+ errors.append(error)++ ph_client = get_client(region, on_error=on_error) if raise_on_error else get_client(region)# Flush even when the caller's block raises — events already captured# before the exception shouldn't be dropped with the buffer.@@ -155,6 +160,8 @@ def ph_scoped_capture(region: str = "US"):yield ScopedCapture(ph_client)finally:ph_client.shutdown()+ if errors:+ raise errors[0]_background_client: Any = Nonediff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.mdindex 83aa9b0f3fcf..ccd65b58e8de 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 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_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_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.@@ -264,7 +264,7 @@ ACP defines standard methods like `session/prompt`, `session/update`, and `sessi- `_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+- `_posthog/budget_steer` — `{ sessionId, stage, delivered, spent_usd, threshold_spent_usd, threshold_at, delivered_at?, cap_usd, mode }` — the run budget guard steered the model at the `warn` (50% of the cap) or `critical` (70%) stage. `threshold_spent_usd` and `threshold_at` record when the stage was reached; `spent_usd` and `delivered_at` record the cost and time when the model received the steer. `delivered_at` is absent if delivery failed. Django captures the notification as a `task run budget steer` event through the direct ingest path or an authenticated agent-proxy callback.**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/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex cc543ddf915b..10ef1cb976a4 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -735,6 +735,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {stage,delivered,spent_usd: record.spent_usd,+ threshold_spent_usd: record.threshold_spent_usd,+ threshold_at: record.threshold_at,+ ...(record.delivered_at ? { delivered_at: record.delivered_at } : {}),cap_usd: guard.capUsd,mode: guard.mode,});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.tsindex c91b6f6e803b..75edb5fbf988 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@@ -1,5 +1,5 @@import type { HookInput } from "@anthropic-ai/claude-agent-sdk";-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import { Logger } from "../../../utils/logger";import {BUDGET_CAP_ENV,@@ -173,14 +173,14 @@ describe("RunBudgetGuard", () => {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);+ record("m1", 800_000);+ record("m1", 800_000);+ expect(guard.spentUsd).toBeCloseTo(0.41126, 4);expect(events).toEqual([]);- record("m2", 500_000);+ record("m2", 200_000);expect(events).toEqual(["warn"]);record("m3", 100_000);- record("m4", 200_000);+ record("m4", 300_000);expect(events).toEqual(["warn", "critical"]);record("m5", 1_000_000);expect(events).toEqual(["warn", "critical"]);@@ -188,7 +188,7 @@ describe("RunBudgetGuard", () => {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));+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));expect(guard.takePendingSteer()).toBe("warn");expect(guard.takePendingSteer()).toBeNull();guard.markUndelivered("warn");@@ -281,12 +281,12 @@ describe("RunBudgetGuard", () => {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",+ test.each(["Agent", "Task", "Workflow", "WebFetch", "WebSearch"])(+ "denies a %s call 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));+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));expect(guard.currentStage).toBe("warn");expect(await hook(spawn(toolName), undefined, hookOptions())).toEqual({continue: true,@@ -336,7 +336,7 @@ describe("RunBudgetGuard", () => {logger,"publish",);- guard.recordAssistantMessage(opusCall("m1", 1_500_000));+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));guard.recordSteer("warn", false);guard.recordSteer("warn", true);expect(guard.snapshot()).toMatchObject({@@ -349,4 +349,33 @@ describe("RunBudgetGuard", () => {],});});++ test("records what a steer cost between the threshold and its delivery", () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));+ const guard = new RunBudgetGuard(1, DEFAULT_MODEL_PRICES, logger);+ guard.recordAssistantMessage(opusCall("m1", 1_000_000));+ const threshold = guard.spentUsd;+ guard.recordAssistantMessage(opusCall("m2", 200_000));+ vi.advanceTimersByTime(5000);+ const record = guard.recordSteer("warn", true);+ expect(record.threshold_spent_usd).toBeCloseTo(threshold, 6);+ expect(record.threshold_at).toBe("2026-01-01T00:00:00.000Z");+ expect(record.delivered_at).toBe("2026-01-01T00:00:05.000Z");+ expect(record.spent_usd - record.threshold_spent_usd).toBeCloseTo(+ 0.11126,+ 4,+ );+ } finally {+ vi.useRealTimers();+ }+ });++ 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));+ expect(guard.currentStage).toBe("critical");+ expect(guard.capUsd - guard.spentUsd).toBeGreaterThan(0.25);+ });});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.tsindex a51dfda7d02a..f7e149de7073 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@@ -3,8 +3,8 @@ 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 BUDGET_WARN_RATIO = 0.5;+export const BUDGET_CRITICAL_RATIO = 0.7;export const FAST_MODE_PRICE_MULTIPLIER = 2;export const ONE_HOUR_CACHE_WRITE_INPUT_MULTIPLIER = 2;@@ -34,6 +34,9 @@ export interface BudgetThresholdEvent {export interface BudgetSteerRecord {stage: BudgetSteerStage;spent_usd: number;+ threshold_spent_usd: number;+ threshold_at: string;+ delivered_at: string | null;delivered: boolean;}@@ -106,7 +109,13 @@ export const DEFAULT_MODEL_PRICES: readonly ModelPriceRule[] = [},];-const FAN_OUT_TOOL_NAMES = new Set(["Agent", "Task", "Workflow"]);+const CRITICAL_BLOCKED_TOOL_NAMES = new Set([+ "Agent",+ "Task",+ "Workflow",+ "WebFetch",+ "WebSearch",+]);const STAGE_RANK: Record<BudgetStage, number> = { ok: 0, warn: 1, critical: 2 };@@ -187,6 +196,10 @@ export class RunBudgetGuard {private sdkTotalUsd = 0;private estimatedAtSdkTotal = 0;private stage: BudgetStage = "ok";+ private readonly thresholds = new Map<+ BudgetSteerStage,+ { spentUsd: number; at: string }+ >();private deliveredStage: BudgetStage = "ok";private pendingSteer: BudgetSteerStage | null = null;private steerMode: BudgetSteerMode;@@ -309,7 +322,17 @@ export class RunBudgetGuard {}recordSteer(stage: BudgetSteerStage, delivered: boolean): BudgetSteerRecord {- const record = { stage, spent_usd: this.spentUsd, delivered };+ const spent = this.spentUsd;+ const deliveredAt = new Date().toISOString();+ const threshold = this.thresholds.get(stage);+ const record = {+ stage,+ spent_usd: spent,+ threshold_spent_usd: threshold?.spentUsd ?? spent,+ threshold_at: threshold?.at ?? deliveredAt,+ delivered_at: delivered ? deliveredAt : null,+ delivered,+ };this.steers.push(record);if (delivered && STAGE_RANK[stage] > STAGE_RANK[this.deliveredStage]) {this.deliveredStage = stage;@@ -375,10 +398,12 @@ export class RunBudgetGuard {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 (!CRITICAL_BLOCKED_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)}`,+ `[BudgetGuard] Blocking ${input.tool_name} at ${formatUsd(this.spentUsd)} of ${formatUsd(this.capUsd)}`,);const next =this.mode === "publish"@@ -391,7 +416,7 @@ export class RunBudgetGuard {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}`,+ `so no new subagents, workflows, or web lookups can start. ${next}`,},};};@@ -407,6 +432,8 @@ export class RunBudgetGuard {}this.stage = next;this.pendingSteer = next;- return { stage: next, spentUsd: this.spentUsd, capUsd: this.capUsd };+ const spentUsd = this.spentUsd;+ this.thresholds.set(next, { spentUsd, at: new Date().toISOString() });+ return { stage: next, spentUsd, capUsd: this.capUsd };}}diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.pyindex 0467cd0a3d43..613695a8e150 100644--- a/products/tasks/backend/agent_proxy_callback.py+++ b/products/tasks/backend/agent_proxy_callback.py@@ -9,6 +9,8 @@ from drf_spectacular.utils import OpenApiResponse, extend_schemafrom jwt import PyJWTErrorfrom products.tasks.backend.facade.api import signal_workflow_completion+from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapture+from products.tasks.backend.logic.stream.event_ingest import _parse_budget_steer_propertiesfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.presentation.serializers import (AgentProxyCallbackRequestSerializer,@@ -40,15 +42,17 @@ logger = logging.getLogger(__name__)400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request body"),401: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Missing or invalid JWT"),403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="JWT claims do not match URL"),+ 503: OpenApiResponse(response=AgentProxyCallbackResponseSerializer, description="Budget steer dispatch failed"),},summary="Agent-proxy side-effect callback",description=("Internal endpoint called by the standalone Node agent-proxy after accepting an ingest event ""that requires a Django-side side effect. Dispatches a Temporal heartbeat, a boot milestone, "- "an awaiting-input mobile push notification, or a failed-run completion depending on `kind`. "+ "an awaiting-input mobile push notification, a failed-run completion, or budget-steer analytics "+ "depending on `kind`. ""Authenticated with the forwarded sandbox event ingest JWT plus the X-Agent-Proxy-Secret ""shared secret (required outside local dev/test) — no session or API key involved. "- "Best-effort: always returns 200 when auth passes; side-effect failures are logged, not surfaced."+ "Budget steers are queued for capture, with 503 on dispatch failure so the proxy can retry."),)def agent_proxy_callback(request, run_id: str) -> JsonResponse:@@ -162,4 +166,18 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:except Exception:logger.exception("agent_proxy_callback.turn_failed_failed", extra={"run_id": run_id})+ elif kind == "budget_steer":+ properties = _parse_budget_steer_properties(+ claims, {"notification": {"method": "_posthog/budget_steer", "params": body}}+ )+ sequence = data.get("sequence")+ if sequence is None or properties is None:+ return JsonResponse({"error": "Invalid budget steer"}, status=400)+ try:+ BudgetSteerCapture.enqueue(team_id, run_id, sequence, properties, body.get("timestamp"))+ dispatched = True+ except Exception:+ logger.exception("agent_proxy_callback.budget_steer_failed", extra={"run_id": run_id})+ return JsonResponse({"dispatched": False}, status=503)+return JsonResponse(AgentProxyCallbackResponseSerializer({"dispatched": dispatched}).data)diff --git a/products/tasks/backend/logic/stream/budget_steer.py b/products/tasks/backend/logic/stream/budget_steer.pynew file mode 100644index 000000000000..6f6bdb232962--- /dev/null+++ b/products/tasks/backend/logic/stream/budget_steer.py@@ -0,0 +1,76 @@+from datetime import datetime+from uuid import NAMESPACE_URL, uuid5++from django.utils import timezone++from celery import current_app++from posthog.ph_client import ph_scoped_capture++from products.tasks.backend.logic.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL+from products.tasks.backend.redis import get_tasks_stream_redis_sync++BudgetSteerProperties = dict[str, str | int | float | bool]+BUDGET_STEER_CAPTURE_TASK = "products.tasks.backend.tasks.tasks.capture_budget_steer"+BUDGET_STEER_RETENTION_SECONDS = int(SANDBOX_EVENT_INGEST_TOKEN_TTL.total_seconds())+++class BudgetSteerCapture:+ @staticmethod+ def _parse_timestamp(value: object) -> datetime | None:+ if not isinstance(value, str) or len(value) > 40:+ return None+ try:+ timestamp = datetime.fromisoformat(value)+ except ValueError:+ return None+ return timestamp if timestamp.tzinfo is not None else None++ @classmethod+ def enqueue(+ cls,+ team_id: int,+ run_id: str,+ sequence: int,+ properties: BudgetSteerProperties,+ event_timestamp: object = None,+ ) -> None:+ event_uuid = str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{run_id}:{sequence}"))+ redis = get_tasks_stream_redis_sync()+ if redis.exists(f"task-run-budget-steer:{event_uuid}:captured"):+ return+ timestamp = (+ cls._parse_timestamp(event_timestamp)+ or cls._parse_timestamp(properties.get("delivered_at"))+ or cls._parse_timestamp(properties.get("threshold_at"))+ or timezone.now()+ ).isoformat()+ original_timestamp = redis.set(+ f"task-run-budget-steer:{event_uuid}:timestamp",+ timestamp,+ nx=True,+ get=True,+ ex=BUDGET_STEER_RETENTION_SECONDS,+ )+ if original_timestamp is not None:+ timestamp = original_timestamp.decode() if isinstance(original_timestamp, bytes) else original_timestamp+ current_app.send_task(+ BUDGET_STEER_CAPTURE_TASK,+ kwargs={"team_id": team_id, "event_uuid": event_uuid, "timestamp": timestamp, "properties": properties},+ )++ @staticmethod+ def capture(team_id: int, event_uuid: str, timestamp: str, properties: BudgetSteerProperties) -> None:+ redis = get_tasks_stream_redis_sync()+ captured_key = f"task-run-budget-steer:{event_uuid}:captured"+ if redis.exists(captured_key):+ return+ with ph_scoped_capture(raise_on_error=True) as capture:+ capture(+ distinct_id=f"team_{team_id}",+ event="task run budget steer",+ properties=properties,+ uuid=event_uuid,+ timestamp=datetime.fromisoformat(timestamp),+ )+ redis.set(captured_key, "1", ex=BUDGET_STEER_RETENTION_SECONDS)diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex 8015fc759237..d3bed06654a3 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -5,6 +5,7 @@ import jsonimport mathfrom collections.abc import AsyncGenerator, Awaitable, Callablefrom dataclasses import dataclass+from datetime import datetimefrom typing import Literal, castfrom uuid import NAMESPACE_URL, uuid5@@ -15,7 +16,7 @@ import structlogfrom asgiref.sync import sync_to_asyncfrom jwt import PyJWTError-from posthog.ph_client import ph_background_capture, ph_scoped_capture+from posthog.ph_client import ph_scoped_capturefrom products.tasks.backend.facade.api import signal_workflow_completionfrom products.tasks.backend.logic.services.connection_token import (@@ -23,6 +24,7 @@ from products.tasks.backend.logic.services.connection_token import (validate_sandbox_event_ingest_token,)from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_event+from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapturefrom products.tasks.backend.logic.stream.redis_stream import (TaskRunRedisStream,TaskRunStreamAlreadyCompleted,@@ -221,7 +223,9 @@ async def _ingest_event_lines(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)+ await _capture_budget_steer_if_needed(+ redis_stream, claims, sequence, budget_steer_properties, event.get("timestamp")+ )if not write.accepted:result.duplicate += 1result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())@@ -284,6 +288,7 @@ async def _capture_budget_steer_if_needed(claims: SandboxEventIngestTokenPayload,sequence: int,properties: dict[str, str | int | float | bool] | None,+ event_timestamp: object = None,) -> None:if properties is None:return@@ -293,8 +298,9 @@ async def _capture_budget_steer_if_needed(if not capture_claim:returntry:- event_uuid = str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{claims.run_id}:{sequence}"))- _capture_budget_steer(claims.team_id, event_uuid, properties)+ await sync_to_async(BudgetSteerCapture.enqueue, thread_sensitive=False)(+ claims.team_id, claims.run_id, sequence, properties, event_timestamp+ )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)@@ -302,15 +308,6 @@ async def _capture_budget_steer_if_needed(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:@@ -333,6 +330,19 @@ def _parse_budget_steer_properties(if amount is None:return Noneamounts[key] = amount+ threshold = _parse_usd_amount(params.get("threshold_spent_usd"))+ if threshold is not None:+ amounts["threshold_spent_usd"] = threshold+ timestamps: dict[str, str] = {}+ for key in ("threshold_at", "delivered_at"):+ value = params.get(key)+ if isinstance(value, str) and len(value) <= 40:+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError:+ continue+ if parsed.tzinfo is not None:+ timestamps[key] = valuereturn {"team_id": claims.team_id,"task_id": claims.task_id,@@ -341,6 +351,7 @@ def _parse_budget_steer_properties("mode": mode,"delivered": delivered,**amounts,+ **timestamps,}diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex ab6e496f9c63..996b52e75753 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -4755,13 +4755,13 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):"""kind = serializers.ChoiceField(- choices=["heartbeat", "awaiting_input", "turn_failed", "command_dispatched", "agent_activity"],+ choices=["heartbeat", "awaiting_input", "turn_failed", "command_dispatched", "agent_activity", "budget_steer"],help_text=("Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its ""inactivity timer. 'awaiting_input' fires a mobile push notification when an ""interactive run finishes a turn and is waiting for user input. 'turn_failed' fails ""the run outright when a pi turn ends in a runtime error. 'command_dispatched' "- "and 'agent_activity' record boot milestones."+ "and 'agent_activity' record boot milestones. 'budget_steer' captures the agent's budget warning."),)agent_active = serializers.BooleanField(@@ -4786,6 +4786,22 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):min_value=1,help_text="Numeric team (project) ID. Must match the JWT claim.",)+ sequence = serializers.IntegerField(+ required=False, min_value=1, help_text="Event sequence used to deduplicate a budget steer."+ )+ timestamp = serializers.DateTimeField(required=False, help_text="Original event time, preserved across retries.")+ stage = serializers.CharField(required=False, help_text="Budget stage: warn or critical.")+ mode = serializers.CharField(required=False, help_text="Budget steer mode: publish or wrap_up.")+ delivered = serializers.BooleanField(required=False, help_text="Whether the steer reached the agent.")+ spent_usd = serializers.FloatField(+ required=False, min_value=0, help_text="Estimated spend when the steer was sent."+ )+ cap_usd = serializers.FloatField(required=False, min_value=0, help_text="Gateway spending cap for this run.")+ threshold_spent_usd = serializers.FloatField(+ required=False, min_value=0, help_text="Estimated spend when the budget stage was reached."+ )+ threshold_at = serializers.DateTimeField(required=False, help_text="Time when the budget stage was reached.")+ delivered_at = serializers.DateTimeField(required=False, help_text="Time when the steer reached the agent.")class AgentProxyCallbackResponseSerializer(serializers.Serializer):diff --git a/products/tasks/backend/tasks/tasks.py b/products/tasks/backend/tasks/tasks.pyindex 25e965b1475e..855bf36c2e46 100644--- a/products/tasks/backend/tasks/tasks.py+++ b/products/tasks/backend/tasks/tasks.py@@ -6,6 +6,12 @@ from celery import shared_taskfrom products.tasks.backend.facade.api import record_comment_activityfrom products.tasks.backend.logic.services.comment_slack_dm import send_comment_slack_dmsfrom products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_run_id+from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapture, BudgetSteerProperties+++@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5, acks_late=True)+def capture_budget_steer(*, team_id: int, event_uuid: str, timestamp: str, properties: BudgetSteerProperties) -> None:+ BudgetSteerCapture.capture(team_id, event_uuid, timestamp, properties)@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.pyindex dff434371e78..24b6e86347dc 100644--- a/products/tasks/backend/tests/test_agent_proxy_callback.py+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py@@ -1,5 +1,6 @@import jsonfrom typing import Any+from uuid import NAMESPACE_URL, uuid5from unittest.mock import patch@@ -130,6 +131,93 @@ class TestAgentProxyCallback(TestCase):response = self._post({"kind": "heartbeat"}, token=self._token())self.assertEqual(response.status_code, 400)+ def test_budget_steer_capture_uses_token_identity_and_stable_event_id(self) -> None:+ body = self._body(+ kind="budget_steer",+ agent_active=False,+ sequence=7,+ timestamp="2026-01-01T00:00:06.000Z",+ stage="critical",+ mode="publish",+ delivered=True,+ spent_usd=7,+ cap_usd=10,+ threshold_spent_usd=6.5,+ threshold_at="2026-01-01T00:00:00.000Z",+ delivered_at="2026-01-01T00:00:05.000Z",+ run_id="spoofed-run",+ )+ token = self._token()+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") as capture:+ responses = [self._post(body, token=token), self._post(body, token=token)]++ self.assertTrue(all(response.status_code == 200 and response.json()["dispatched"] for response in responses))+ expected = {+ "team_id": self.team.id,+ "event_uuid": str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{self.task_run.id}:7")),+ "timestamp": "2026-01-01T00:00:06+00:00",+ "properties": {+ "team_id": self.team.id,+ "task_id": str(self.task.id),+ "run_id": str(self.task_run.id),+ "stage": "critical",+ "mode": "publish",+ "delivered": True,+ "spent_usd": 7.0,+ "cap_usd": 10.0,+ "threshold_spent_usd": 6.5,+ "threshold_at": "2026-01-01T00:00:00.000Z",+ "delivered_at": "2026-01-01T00:00:05.000Z",+ },+ }+ self.assertEqual([call.kwargs["kwargs"] for call in capture.call_args_list], [expected, expected])++ @parameterized.expand(+ [+ ("missing_sequence", {"sequence": None}),+ ("invalid_stage", {"stage": "other"}),+ ("negative_spend", {"spent_usd": -1}),+ ]+ )+ def test_invalid_budget_steer_is_rejected(self, _name: str, overrides: dict[str, Any]) -> None:+ body = self._body(+ kind="budget_steer",+ agent_active=False,+ sequence=7,+ stage="warn",+ mode="wrap_up",+ delivered=True,+ spent_usd=5,+ cap_usd=10,+ )+ body.update(overrides)+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") as capture:+ response = self._post(body, token=self._token())+ self.assertEqual(response.status_code, 400)+ capture.assert_not_called()++ def test_budget_steer_dispatch_failure_can_retry(self) -> None:+ body = self._body(+ kind="budget_steer",+ agent_active=False,+ sequence=7,+ stage="warn",+ mode="wrap_up",+ delivered=True,+ spent_usd=5,+ cap_usd=10,+ )+ with patch(+ "products.tasks.backend.logic.stream.budget_steer.current_app.send_task",+ side_effect=[RuntimeError("down"), None],+ ) as dispatch:+ response = self._post(body, token=self._token())+ retried = self._post(body, token=self._token())+ self.assertEqual(response.status_code, 503)+ self.assertEqual(retried.status_code, 200)+ self.assertTrue(retried.json()["dispatched"])+ self.assertEqual(dispatch.call_args_list[0], dispatch.call_args_list[1])+def test_heartbeat_dispatches_when_active(self) -> None:with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:response = self._post(self._body(kind="heartbeat", agent_active=True), token=self._token())diff --git a/products/tasks/backend/tests/test_budget_steer.py b/products/tasks/backend/tests/test_budget_steer.pynew file mode 100644index 000000000000..fc74ffe4ddfa--- /dev/null+++ b/products/tasks/backend/tests/test_budget_steer.py@@ -0,0 +1,76 @@+from uuid import uuid4++import time_machine+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.ph_client import get_client+from posthog.redis import TEST_clear_clients++from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapture, BudgetSteerProperties+from products.tasks.backend.tasks.tasks import capture_budget_steer+++class TestBudgetSteerCapture(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ TEST_clear_clients()+ self.run_id = str(uuid4())+ self.properties: BudgetSteerProperties = {+ "team_id": 1,+ "run_id": self.run_id,+ "stage": "warn",+ "mode": "publish",+ "delivered": True,+ "spent_usd": 5.0,+ "cap_usd": 10.0,+ }++ @parameterized.expand(+ [+ (None, "2026-01-01T23:59:59+00:00"),+ ("2026-01-01T23:59:58.000Z", "2026-01-01T23:59:58+00:00"),+ ]+ )+ def test_replays_preserve_timestamp_across_midnight(self, event_timestamp: str | None, expected: str) -> None:+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") as dispatch:+ with time_machine.travel("2026-01-01T23:59:59Z", tick=False):+ BudgetSteerCapture.enqueue(1, self.run_id, 7, self.properties, event_timestamp)+ with time_machine.travel("2026-01-02T00:00:01Z", tick=False):+ BudgetSteerCapture.enqueue(1, self.run_id, 7, self.properties, event_timestamp)++ self.assertEqual(dispatch.call_count, 2)+ self.assertEqual(dispatch.call_args_list[0], dispatch.call_args_list[1])+ self.assertEqual(dispatch.call_args.kwargs["kwargs"]["timestamp"], expected)++ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_upload_failure_is_retried_before_marking_capture_complete(self) -> None:+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") as dispatch:+ BudgetSteerCapture.enqueue(1, self.run_id, 7, self.properties, "2026-01-01T00:00:00Z")+ payload = dispatch.call_args.kwargs["kwargs"]++ with (+ patch(+ "posthoganalytics.consumer.Consumer.request", side_effect=[RuntimeError("upload failed"), None]+ ) as upload,+ patch(+ "posthog.ph_client.get_client",+ side_effect=lambda region, **kwargs: get_client(region, disabled=False, max_retries=0, **kwargs),+ ),+ ):+ with self.assertRaisesRegex(RuntimeError, "upload failed"):+ capture_budget_steer.run(**payload)+ capture_budget_steer.run(**payload)+ capture_budget_steer.run(**payload)++ self.assertEqual(upload.call_count, 2)+ first_event = upload.call_args_list[0].args[0][0]+ retried_event = upload.call_args_list[1].args[0][0]+ self.assertEqual(first_event["timestamp"], retried_event["timestamp"])+ self.assertEqual(first_event["uuid"], retried_event["uuid"])+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") as dispatch:+ BudgetSteerCapture.enqueue(1, self.run_id, 7, self.properties)+ dispatch.assert_not_called()diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex b3d25bf2d6fb..8378bd06151a 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -357,6 +357,9 @@ class TestTaskRunEventIngest(TestCase):"mode": "publish","delivered": True,"spent_usd": 14.1,+ "threshold_spent_usd": 14.0,+ "threshold_at": "2026-01-01T00:00:00.000Z",+ "delivered_at": "2026-01-01T00:00:05.000Z","cap_usd": 20,},)@@ -367,30 +370,39 @@ class TestTaskRunEventIngest(TestCase):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:+ with patch("products.tasks.backend.logic.stream.budget_steer.current_app.send_task") 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")),+ self.assertEqual(capture_budget_steer.call_count, 1)+ self.assertEqual(+ capture_budget_steer.call_args.kwargs["kwargs"],{"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,+ "event_uuid": str(uuid5(NAMESPACE_URL, f"posthog-task-budget-steer:{self.task_run.id}:1")),+ "timestamp": "2026-01-01T00:00:05+00:00",+ "properties": {+ "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,+ "threshold_spent_usd": 14.0,+ "threshold_at": "2026-01-01T00:00:00.000Z",+ "delivered_at": "2026-01-01T00:00:05.000Z",+ },},)+ @parameterized.expand([(False,), (True,)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)- def test_budget_steer_capture_failure_does_not_block_the_stream(self) -> None:+ def test_budget_steer_delivery_does_not_block_the_stream(self, dispatch_fails: bool) -> None:token = self._create_token()event = {"seq": 1,@@ -402,16 +414,25 @@ class TestTaskRunEventIngest(TestCase):},},}+ following_event = {+ "seq": 2,+ "event": {"type": "notification", "notification": {"method": "_posthog/usage_update", "params": {}}},+ }- with patch(- "products.tasks.backend.logic.stream.event_ingest._capture_budget_steer",- side_effect=RuntimeError("capture failed"),+ with (+ patch(+ "products.tasks.backend.logic.stream.budget_steer.current_app.send_task",+ side_effect=RuntimeError("dispatch failed") if dispatch_fails else None,+ ) as dispatch,+ patch("posthoganalytics.consumer.Consumer.request") as upload,):- status, body = self._call_ingest(token, [event])+ status, body = self._call_ingest(token, [event, following_event])+ dispatch.assert_called_once()+ upload.assert_not_called()self.assertEqual(status, 200)- self.assertEqual(body["accepted"], 1)- self.assertEqual(self._read_notification_methods(), ["_posthog/budget_steer"])+ self.assertEqual(body["accepted"], 2)+ self.assertEqual(self._read_notification_methods(), ["_posthog/budget_steer", "_posthog/usage_update"])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_rtk_savings_capture_failure_can_be_retried(self) -> None:diff --git a/services/agent-proxy/README.md b/services/agent-proxy/README.mdindex 3f6e4b0f3692..1576e89fc32a 100644--- a/services/agent-proxy/README.md+++ b/services/agent-proxy/README.md@@ -6,8 +6,12 @@ SSE stream reads for browsers and NDJSON event ingest from sandboxes, bothbacked by the same Redis streams that Django writes.No Postgres, no Temporal client, no Celery — the service is a pure streaming-plane. Side effects (Temporal heartbeats, awaiting-input push notifications)+plane. Side effects (Temporal heartbeats, awaiting-input push notifications,+budget-steer analytics capture)are delegated to a single internal Django callback endpoint.+Budget steer callbacks preserve the original event timestamp and queue analytics delivery in Celery.+Django returns 503 if dispatch fails, and the proxy retries the callback once.+The capture worker retries analytics upload failures independently of event streaming.## Routes@@ -36,7 +40,7 @@ the durable run log when its cursor has been trimmed out of Redis.| --------------------------------- | ---------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `TASKS_REDIS_URL` | yes (prod) | `localhost:6379` | Redis connection URL (unencrypted local Redis by default; use a TLS URL in production) || `SANDBOX_JWT_PUBLIC_KEY` | yes | — | RS256 public key PEM (`\n` literals in env vars are normalized to real newlines before use) |-| `AGENT_PROXY_DJANGO_CALLBACK_URL` | yes (prod) | — | Base URL of the Django service for side-effect callbacks (Temporal heartbeat, awaiting-input push), e.g. `http://web:8000` |+| `AGENT_PROXY_DJANGO_CALLBACK_URL` | yes (prod) | — | Base URL of the Django service for side-effect callbacks (heartbeats, push notifications, budget steers), e.g. `http://web:8000` || `AGENT_PROXY_CALLBACK_SECRET` | no | `''` | Shared secret sent as `X-Agent-Proxy-Secret` on the Django callback; Django enforces it when the same value is set on both sides, so a sandbox cannot call the callback directly || `TASKS_AGENT_PROXY_CORS_ORIGINS` | no | `''` | Comma-separated allowed CORS origins; `*` allows all || `PORT` | no | `8003` | HTTP listen port |diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex d04d1c37d069..feccf07f2024 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -27,7 +27,7 @@ import {import { validateSandboxEventIngestToken } from '../lib/jwt.js'import { logger } from '../lib/logging.js'import { TaskRunRedisStream, getStreamKey } from '../lib/redis-stream.js'-import { heartbeatWorkflowIfNeeded } from '../lib/side-effects.js'+import { captureBudgetSteerIfNeeded, heartbeatWorkflowIfNeeded } from '../lib/side-effects.js'import {ClientDisconnected,EventIngestBadRequest,@@ -248,6 +248,7 @@ async function ingestEventLines(const { seq, event } = eventLineconst write = await redisStream.writeEventWithSequence(event, seq)+ captureBudgetSteerIfNeeded(claims.runId, seq, event, claims.taskId, claims.teamId, originalToken, config)if (!write.accepted) {// Duplicate: advance last_accepted_seq to whatever Redis has.diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.tsindex b44c786aaf2d..1279c8efe37d 100644--- a/services/agent-proxy/src/lib/side-effects.ts+++ b/services/agent-proxy/src/lib/side-effects.ts@@ -163,7 +163,7 @@ export function isAgentGenerationEvent(event: Record<string, unknown>): booleanconst CALLBACK_TIMEOUT_MS = 10_000const RETRY_DELAY_MS = 1000-const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input', 'turn_failed'])+const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input', 'turn_failed', 'budget_steer'])function fetchErrorCode(err: unknown): string | undefined {if (!(err instanceof Error)) {@@ -209,9 +209,13 @@ function fireCallback(teamId: number,originalToken: string,config: Config,- options: { releaseClaim?: () => Promise<void>; turnCompleted?: boolean } = {}+ options: {+ releaseClaim?: () => Promise<void>+ turnCompleted?: boolean+ budgetSteer?: { sequence: number; timestamp?: string; params: Record<string, unknown> }+ } = {}): void {- const { releaseClaim, turnCompleted } = options+ const { releaseClaim, turnCompleted, budgetSteer } = optionsif (!config.djangoCallbackBaseUrl) {// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.void releaseMilestoneClaim(releaseClaim, runId, kind)@@ -220,6 +224,20 @@ function fireCallback(const url = `${config.djangoCallbackBaseUrl}/internal/tasks/runs/${runId}/agent-proxy-callback/`const body = JSON.stringify({+ ...(budgetSteer+ ? {+ sequence: budgetSteer.sequence,+ timestamp: budgetSteer.timestamp,+ stage: budgetSteer.params['stage'],+ mode: budgetSteer.params['mode'],+ delivered: budgetSteer.params['delivered'],+ spent_usd: budgetSteer.params['spent_usd'],+ cap_usd: budgetSteer.params['cap_usd'],+ threshold_spent_usd: budgetSteer.params['threshold_spent_usd'],+ threshold_at: budgetSteer.params['threshold_at'],+ delivered_at: budgetSteer.params['delivered_at'],+ }+ : {}),kind,agent_active: agentActive,task_id: taskId,@@ -256,6 +274,9 @@ function fireCallback('dispatched' in payload &&payload.dispatched === trueif (!dispatched) {+ if (kind === 'budget_steer') {+ logger.warn('side_effect:budget_steer_not_captured', { run: runId })+ }await releaseMilestoneClaim(releaseClaim, runId, kind)}})@@ -266,6 +287,35 @@ function fireCallback(})}+export function captureBudgetSteerIfNeeded(+ runId: string,+ sequence: number,+ event: Record<string, unknown>,+ taskId: string,+ teamId: number,+ originalToken: string,+ config: Config+): void {+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {+ return+ }+ const notification = event['notification']+ if (typeof notification !== 'object' || notification === null || Array.isArray(notification)) {+ return+ }+ const { method, params } = notification as Record<string, unknown>+ if (method !== '_posthog/budget_steer' || typeof params !== 'object' || params === null || Array.isArray(params)) {+ return+ }+ fireCallback(runId, 'budget_steer', false, taskId, teamId, originalToken, config, {+ budgetSteer: {+ sequence,+ ...(typeof event['timestamp'] === 'string' ? { timestamp: event['timestamp'] } : {}),+ params: params as Record<string, unknown>,+ },+ })+}+async function releaseMilestoneClaim(release: (() => Promise<void>) | undefined,runId: string,diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex fe26801f13bd..a540c8aa478b 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -171,7 +171,13 @@ export type IngestLine = IngestEventLine | IngestCompleteLine// Side-effect callback kind (matches Python callback contract in docs/DESIGN.md)// ----------------------------------------------------------------------------export type SideEffectKind = 'heartbeat' | 'awaiting_input' | 'turn_failed' | 'command_dispatched' | 'agent_activity'+export type SideEffectKind =+ | 'heartbeat'+ | 'awaiting_input'+ | 'turn_failed'+ | 'command_dispatched'+ | 'agent_activity'+ | 'budget_steer'// ---------------------------------------------------------------------------// TaskRunRedisStream method interfacediff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 34f9c7b65212..5204f57ea57a 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -581,6 +581,102 @@ describe('ingest-handler', () => {expect(body.last_accepted_seq).toBe(1)})+ it('sends budget steers through the authenticated callback on accepted and replayed events', async () => {+ const callback = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(JSON.stringify({ dispatched: true }), { status: 200 }))+ try {+ const config = makeConfig({+ djangoCallbackBaseUrl: 'http://django.example.com',+ agentProxyCallbackSecret: 'proxy-secret',+ })+ const event = {+ type: 'notification',+ timestamp: '2026-01-01T00:00:06.000Z',+ notification: {+ method: '_posthog/budget_steer',+ params: {+ stage: 'critical',+ mode: 'publish',+ delivered: true,+ spent_usd: 7,+ cap_usd: 10,+ threshold_spent_usd: 6.5,+ threshold_at: '2026-01-01T00:00:00.000Z',+ delivered_at: '2026-01-01T00:00:05.000Z',+ team_id: 999,+ secret: 'not-for-analytics',+ },+ },+ }+ const body = makeStringBody(JSON.stringify({ seq: 1, event }) + '\n')+ const first = await handleIngest(+ makeContext({ body }),+ fakeRedis as unknown as Redis,+ config,+ [] as CryptoKey[]+ )+ expect(first.status).toBe(200)+ const retry = await handleIngest(+ makeContext({ body: makeStringBody(JSON.stringify({ seq: 1, event }) + '\n') }),+ fakeRedis as unknown as Redis,+ config,+ [] as CryptoKey[]+ )+ expect(await decodeJson(retry)).toMatchObject({ accepted: 0, duplicate: 1 })+ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(2))+ const [url, request] = callback.mock.calls[0]!+ expect(url).toBe('http://django.example.com/internal/tasks/runs/run-123/agent-proxy-callback/')+ expect(request?.headers).toMatchObject({+ Authorization: 'Bearer test-token',+ 'X-Agent-Proxy-Secret': 'proxy-secret',+ })+ expect(JSON.parse(String(request?.body))).toMatchObject({+ kind: 'budget_steer',+ task_id: TASK_ID,+ team_id: TEAM_ID,+ sequence: 1,+ timestamp: '2026-01-01T00:00:06.000Z',+ stage: 'critical',+ mode: 'publish',+ delivered: true,+ threshold_spent_usd: 6.5,+ threshold_at: '2026-01-01T00:00:00.000Z',+ delivered_at: '2026-01-01T00:00:05.000Z',+ })+ expect(String(request?.body)).not.toContain('not-for-analytics')+ expect(callback.mock.calls[1]![1]?.body).toBe(request?.body)+ } finally {+ callback.mockRestore()+ }+ })++ it('retries a budget steer callback after a temporary capture failure', async () => {+ const callback = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValueOnce(new Response('', { status: 503 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({ dispatched: true }), { status: 200 }))+ try {+ const event = {+ type: 'notification',+ notification: {+ method: '_posthog/budget_steer',+ params: { stage: 'warn', mode: 'publish', delivered: true, spent_usd: 5, cap_usd: 10 },+ },+ }+ const response = await handleIngest(+ makeContext({ body: makeStringBody(JSON.stringify({ seq: 1, event }) + '\n') }),+ fakeRedis as unknown as Redis,+ makeConfig({ djangoCallbackBaseUrl: 'http://django.example.com' }),+ [] as CryptoKey[]+ )+ expect(response.status).toBe(200)+ await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(2), { timeout: 3000 })+ } finally {+ callback.mockRestore()+ }+ })+it('mixes accepted and duplicate when some events are re-sent', async () => {const config = makeConfig()// Seed seq 1 via a prior request