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(signals): name the agent on its runs and generation events (#97453)

posthog[bot]1c2a670ade69
diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
index 6118f91839d7..cc5d9bbc3808 100644
--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts
@@ -9,6 +9,7 @@ interface TestableServer {
originProduct?: Task["origin_product"] | null;
signalReportId?: string | null;
aiStage?: string | null;
+ aiAgentName?: string | null;
taskId?: string | null;
taskRunId?: string | null;
taskUserId?: number | null;
@@ -212,6 +213,7 @@ describe("AgentServer.configureEnvironment", () => {
originProduct: "signal_report",
signalReportId: "report-123",
aiStage: "research",
+ aiAgentName: "signals-scout-errors",
taskId: "task-abc",
taskRunId: "run-xyz",
taskUserId: 42,
@@ -229,6 +231,7 @@ describe("AgentServer.configureEnvironment", () => {
"x-posthog-property-task_internal": "true",
"x-posthog-property-signal_report_id": "report-123",
"x-posthog-property-ai_stage": "research",
+ "x-posthog-property-ai_agent_name": "signals-scout-errors",
"x-posthog-property-task_id": "task-abc",
"x-posthog-property-task_run_id": "run-xyz",
"x-posthog-property-task_user_id": "42",
@@ -253,6 +256,7 @@ describe("AgentServer.configureEnvironment", () => {
originProduct: "signal_report",
signalReportId: "report-123",
aiStage: "research",
+ aiAgentName: "signals-scout-errors",
taskId: "task-abc",
taskRunId: "run-xyz",
taskUserId: 42,
@@ -271,6 +275,7 @@ describe("AgentServer.configureEnvironment", () => {
"x-posthog-property-task_internal: true",
"x-posthog-property-signal_report_id: report-123",
"x-posthog-property-ai_stage: research",
+ "x-posthog-property-ai_agent_name: signals-scout-errors",
"x-posthog-property-task_id: task-abc",
"x-posthog-property-task_run_id: run-xyz",
"x-posthog-property-task_user_id: 42",
@@ -287,13 +292,15 @@ describe("AgentServer.configureEnvironment", () => {
);
});
- it("omits ai_stage from anthropicCustomHeaders when not provided", () => {
+ // A run with neither value in its state must send no header, not an empty one.
+ it("omits ai_stage and ai_agent_name from anthropicCustomHeaders when not provided", () => {
const env = buildServer("background").configureEnvironment({
isInternal: false,
taskId: "task-abc",
});
expect(env.anthropicCustomHeaders).not.toContain("ai_stage");
+ expect(env.anthropicCustomHeaders).not.toContain("ai_agent_name");
});
// A signals_scout title is multi-line; it must not inject extra header lines.
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 96de00f64be0..4817fb2d8a66 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -1953,6 +1953,7 @@ export class AgentServer {
originProduct: preTask?.origin_product,
signalReportId: preTask?.signal_report,
aiStage: getTaskRunStateString(preTaskRun, "ai_stage"),
+ aiAgentName: getTaskRunStateString(preTaskRun, "ai_agent_name"),
taskId: payload.task_id,
taskRunId: payload.run_id,
taskUserId: payload.user_id || preTask?.created_by?.id || null,
@@ -5071,6 +5072,7 @@ ${commonInstructions}
originProduct,
signalReportId,
aiStage,
+ aiAgentName,
taskId,
taskRunId,
taskUserId,
@@ -5087,6 +5089,7 @@ ${commonInstructions}
originProduct?: Task["origin_product"] | null;
signalReportId?: string | null;
aiStage?: string | null;
+ aiAgentName?: string | null;
taskId?: string | null;
taskRunId?: string | null;
taskUserId?: number | null;
@@ -5143,6 +5146,8 @@ ${commonInstructions}
task_internal: isInternal,
signal_report_id: signalReportId,
ai_stage: resolvedStage,
+ // The team-scoped agent name; `ai_stage` stays a bounded fleet-wide tag.
+ ai_agent_name: aiAgentName,
task_id: taskId,
task_run_id: taskRunId,
task_user_id: taskUserId,
diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.ts
index ed8b64313a87..1f285616c9b4 100644
--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts
+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts
@@ -649,6 +649,10 @@ export class PiAgentServer {
task_prewarmed: taskRun ? runState?.prewarmed === true : null,
ai_stage:
typeof runState?.ai_stage === "string" ? runState.ai_stage : null,
+ ai_agent_name:
+ typeof runState?.ai_agent_name === "string"
+ ? runState.ai_agent_name
+ : null,
task_execution_environment: "cloud",
});
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index ca11bda4b803..c44c86ab61f5 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -337,6 +337,7 @@ const storeSkillStubSchema = z.object({
export type StoreSkillStub = z.infer<typeof storeSkillStubSchema>;
const taskRunStateFields = {
+ ai_agent_name: optionalField(z.string()),
ai_stage: optionalField(z.string()),
auto_publish: optionalField(z.boolean()),
benjamin_version: optionalField(z.string()),
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index ea91f7164292..cab23a8b994b 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -795,10 +795,12 @@ async def _spawn_and_run(
mcp_gateway_server_ids=[str(server_id) for server_id in (config.mcp_gateway_server_ids or [])],
# Tag every scout $ai_generation with its stage AND its scout, so scout spend is both
# splittable out of the ai_product='signals' bucket (scouts carry no signal_report_id)
- # and attributable to one scout. `ai_stage` is the only run-shaped value the harness
- # controls that reaches $ai_generation — the rest of the properties there are stamped
- # by the agent server off the task row. Team attribution rides along as `team_id`.
+ # and attributable to one scout. Team attribution rides along as `team_id`.
ai_stage=_ai_stage(skill),
+ # `ai_stage` collapses team-authored scouts to `scout:custom` to bound a fleet-wide tag's
+ # cardinality, so it cannot name one. `ai_agent_name` is read per team and carries the
+ # full skill name for canonical and custom scouts alike.
+ ai_agent_name=skill.name,
on_task_run_created=_create_bridge_row,
# Keep the per-turn poll budget at the run's runtime cap so the dropped-finalization
# salvage fires before the activity's `start_to_close_timeout` (DEFAULT_MAX_RUNTIME_S +
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index d69112eb3597..dadef2a49e7b 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1219,10 +1219,11 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(ateam, aer
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):
+async def test_run_tags_session_with_scout_attribution(ateam, aerrors_skill):
# Scouts pass a `scout:<skill>` ai_stage to the sandbox session so every $ai_generation
# carries it, letting scout spend be split out of the ai_product='signals' bucket (scouts
- # have no report id) and attributed to one scout.
+ # have no report id) and attributed to one scout. The full skill name rides alongside it,
+ # because ai_stage collapses every team-authored scout to one value.
session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
captured: dict = {}
@@ -1245,8 +1246,9 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):
):
await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
- # `signals-scout-errors` is not a canonical scout, so its team-authored name is withheld.
+ # `signals-scout-errors` is not canonical, so only `ai_agent_name` can name it.
assert captured["ai_stage"] == "scout:custom"
+ assert captured["ai_agent_name"] == "signals-scout-errors"
@pytest.mark.asyncio
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2b960c630d05..9c204ad30be9 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -420,6 +420,7 @@ _TASK_RUN_LOG_URL_CACHE_TTL = 55 * 60
_TASK_RUN_PUBLIC_STATE_KEYS = frozenset(
{
+ "ai_agent_name",
"ai_stage",
"auto_publish",
"benjamin_enabled",
@@ -2267,6 +2268,9 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
# is_interactive_signals_run reads it the same way, so forging it would move the run off
# the interactive budget and out of its per-run spend ceiling.
"ai_stage",
+ # Names the agent (scout, custom agent, workflow) the run executes, lifted onto its
+ # $ai_generation events. A PATCHable value would bill a caller's spend to another agent.
+ "ai_agent_name",
# The server-generated head branch the run->PR link is keyed on (find_signal_implementation_run).
# A PATCHable value would let a caller re-aim the approve-first carve-out at any App-authored
# PR, which is the exact forgery the stamp exists to prevent.
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index c400532b18d2..952f4fd74b8c 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -211,6 +211,7 @@ async def create_task_and_trigger(
origin_product: Task.OriginProduct | None = None,
signal_report_id: str | None = None,
ai_stage: str | None = None,
+ ai_agent_name: str | None = None,
internal: bool = False,
workflow_id_prefix: str | None = None,
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
@@ -236,6 +237,7 @@ async def create_task_and_trigger(
branch=branch,
signal_report_id=signal_report_id,
ai_stage=ai_stage,
+ ai_agent_name=ai_agent_name,
posthog_mcp_scopes=posthog_mcp_scopes,
sandbox_environment_id=context.sandbox_environment_id,
model=context.model,
diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index 090a5e2814aa..fcc95612597b 100644
--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -68,6 +68,7 @@ class MultiTurnSession:
origin_product: Task.OriginProduct | None = None,
signal_report_id: str | None = None,
ai_stage: str | None = None,
+ ai_agent_name: str | None = None,
internal: bool = False,
on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,
max_poll_seconds: int | None = None,
@@ -105,6 +106,7 @@ class MultiTurnSession:
origin_product=origin_product,
signal_report_id=signal_report_id,
ai_stage=ai_stage,
+ ai_agent_name=ai_agent_name,
internal=internal,
on_task_run_created=on_task_run_created,
max_poll_seconds=max_poll_seconds,
@@ -162,6 +164,7 @@ class MultiTurnSession:
origin_product: Task.OriginProduct | None = None,
signal_report_id: str | None = None,
ai_stage: str | None = None,
+ ai_agent_name: str | None = None,
internal: bool = False,
on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,
max_poll_seconds: int | None = None,
@@ -193,6 +196,7 @@ class MultiTurnSession:
origin_product=origin_product,
signal_report_id=signal_report_id,
ai_stage=ai_stage,
+ ai_agent_name=ai_agent_name,
internal=internal,
workflow_id_prefix=workflow_id_prefix,
mcp_builtin_agent_key=mcp_builtin_agent_key,
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index c8265be2c75c..3aa41387a167 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -925,6 +925,7 @@ class Task(DeletedMetaFields, models.Model):
hog_flow_id: uuid.UUID | None = None,
origin_key: str | None = None,
ai_stage: str | None = None,
+ ai_agent_name: str | None = None,
sandbox_environment_id: str | None = None,
internal: bool = False,
output_schema: type[BaseModel] | dict | None = None,
@@ -1121,6 +1122,11 @@ class Task(DeletedMetaFields, models.Model):
if ai_stage:
extra_state["ai_stage"] = ai_stage
+ # The team-scoped name of the agent this run executes. `ai_stage` is a fleet-wide tag with
+ # bounded cardinality, so callers that run team-authored agents cannot name them there.
+ if ai_agent_name:
+ extra_state["ai_agent_name"] = ai_agent_name
+
if initial_permission_mode:
extra_state["initial_permission_mode"] = initial_permission_mode
@@ -1271,6 +1277,7 @@ class Task(DeletedMetaFields, models.Model):
sandbox_timeout_seconds: int | None = None,
inactivity_timeout_seconds: int | None = None,
ai_stage: str | None = None,
+ ai_agent_name: str | None = None,
wizard_config: dict | None = None,
wizard_head_branch: str | None = None,
self_driving_head_branch: str | None = None,
@@ -1318,6 +1325,7 @@ class Task(DeletedMetaFields, models.Model):
sandbox_timeout_seconds=sandbox_timeout_seconds,
inactivity_timeout_seconds=inactivity_timeout_seconds,
ai_stage=ai_stage,
+ ai_agent_name=ai_agent_name,
wizard_config=wizard_config,
wizard_head_branch=wizard_head_branch,
self_driving_head_branch=self_driving_head_branch,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index dee00c1871f6..144d40f8f21c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -5639,6 +5639,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"pending_external_followups_generation": 7,
"sandbox_gone": False,
"ai_stage": "research",
+ "ai_agent_name": "signals-scout-errors",
"self_driving_head_branch": "posthog-self-driving/real-3f9a2c",
"runtime_adapter": "claude",
"provider": "anthropic",
@@ -5706,6 +5707,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
"sandbox_gone": True,
# implementation provenance is what the self-driving review carve-outs trust
"ai_stage": "implementation",
+ # a forged agent name bills this run's spend to another agent
+ "ai_agent_name": "signals-scout-general",
# the stamped branch is the unforgeable run->PR link; a writable value re-aims it
"self_driving_head_branch": "posthog-self-driving/attacker-000000",
"runtime_adapter": "codex",
@@ -5753,6 +5756,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["same_run_resume_idle"] is False
assert run.state["handoff_resumed"] is True
assert run.state["handoff_resume_idle"] is False
+ assert run.state["ai_agent_name"] == "signals-scout-errors"
assert run.state["workflow_id"] == "wf-real"
assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}
assert run.state["pending_external_followups"] == pending_external_followups
@@ -6131,6 +6135,29 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertIsNotNone(data["log_url"])
self.assertTrue(data["log_url"].startswith("http"))
+ def test_retrieve_run_serves_the_sandbox_its_attribution_stamps(self):
+ # The in-sandbox agent server reads run state back off this endpoint, so a stamp the
+ # public filter drops never reaches the gateway. Sandbox credentials share that state.
+ task = self.create_task()
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={
+ "ai_stage": "scout:custom",
+ "ai_agent_name": "signals-scout-errors",
+ "sandbox_connect_token": "connect-token",
+ },
+ )
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ state = response.json()["state"]
+ self.assertEqual(state["ai_stage"], "scout:custom")
+ self.assertEqual(state["ai_agent_name"], "signals-scout-errors")
+ self.assertNotIn("sandbox_connect_token", state)
+
def test_list_runs_only_returns_task_runs(self):
task1 = self.create_task("Task 1")
task2 = self.create_task("Task 2")
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index f9abc9f00cae..aad4d670861e 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -196,7 +196,7 @@ class TestTask(TestCase):
self.assertEqual(task.origin_product, Task.OriginProduct.SLACK)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_create_and_run_threads_ai_stage_into_state(self, mock_execute_workflow):
+ def test_create_and_run_threads_attribution_stamps_into_state(self, mock_execute_workflow):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
@@ -209,14 +209,16 @@ class TestTask(TestCase):
user_id=user.id,
repository="posthog/posthog",
ai_stage="research",
+ ai_agent_name="signals-scout-errors",
)
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
self.assertEqual(task_run.state["ai_stage"], "research")
+ self.assertEqual(task_run.state["ai_agent_name"], "signals-scout-errors")
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_create_and_run_omits_ai_stage_when_not_provided(self, mock_execute_workflow):
+ def test_create_and_run_omits_attribution_stamps_when_not_provided(self, mock_execute_workflow):
user = User.objects.create(email="[email protected]")
Integration.objects.create(team=self.team, kind="github", config={})
@@ -233,6 +235,7 @@ class TestTask(TestCase):
run_id = mock_execute_workflow.call_args.kwargs["run_id"]
task_run = TaskRun.objects.get(id=run_id)
self.assertNotIn("ai_stage", task_run.state)
+ self.assertNotIn("ai_agent_name", task_run.state)
def test_create_run_stamps_inbox_on_a_report_linked_signal_report_task(self):
from products.signals.backend.models import SignalReport
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index d2ff659f09ab..b17eb8b4a227 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -1414,8 +1414,16 @@ class TestCreateTaskAndTriggerForwardsContext:
assert kwargs["posthog_mcp_scopes"] == expected_scopes
@pytest.mark.asyncio
- @pytest.mark.parametrize("ai_stage, expected", [("research", "research"), (None, None)])
- async def test_forwards_ai_stage(self, ai_stage, expected):
+ @pytest.mark.parametrize(
+ "stamp, value",
+ [
+ ("ai_stage", "research"),
+ ("ai_stage", None),
+ ("ai_agent_name", "signals-scout-errors"),
+ ("ai_agent_name", None),
+ ],
+ )
+ async def test_forwards_attribution_stamps(self, stamp, value):
team, user = await sync_to_async(self._setup_team_and_user)()
context = CustomPromptSandboxContext(team_id=team.id, user_id=user.id, repository="posthog/posthog")
@@ -1425,9 +1433,9 @@ class TestCreateTaskAndTriggerForwardsContext:
"products.tasks.backend.logic.services.custom_prompt_internals.Task.create_and_run",
return_value=mock_task,
) as mock_create:
- await create_task_and_trigger("prompt", context, ai_stage=ai_stage)
+ await create_task_and_trigger("prompt", context, **{stamp: value})
- assert mock_create.call_args.kwargs["ai_stage"] == expected
+ assert mock_create.call_args.kwargs[stamp] == value
@pytest.mark.asyncio
@pytest.mark.parametrize(("runtime", "expected_pending_message"), [("acp", None), ("pi", "prompt")])