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): report implementation (#84066)

Georgiy Tarasov1b05c6e23ccd
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index e6be21c00639..d07d7c716d41 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -2139,7 +2139,7 @@
"label": "MCP client version"
},
"$mcp_consumer": {
- "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' means the request came through PostHog Desktop; 'slack' means it was triggered from Slack.",
+ "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' is the catch-all every sandbox agent sends, so it covers Signals runs as well as PostHog Desktop; break down by `source` to separate them. 'slack' means it was triggered from Slack.",
"examples": [
"posthog-code",
"slack"
@@ -3770,7 +3770,7 @@
"label": "sccid"
},
"source": {
- "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
+ "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent and the local agent. 'self_driving' is Signals: scouts, report implementations, and scout chat. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
"examples": [
"web",
"posthog_ai",
@@ -4320,7 +4320,7 @@
"label": "MCP client version"
},
"$mcp_consumer": {
- "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' means the request came through PostHog Desktop; 'slack' means it was triggered from Slack.",
+ "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' is the catch-all every sandbox agent sends, so it covers Signals runs as well as PostHog Desktop; break down by `source` to separate them. 'slack' means it was triggered from Slack.",
"examples": [
"posthog-code",
"slack"
@@ -7079,7 +7079,7 @@
"label": "MCP client version"
},
"$mcp_consumer": {
- "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' means the request came through PostHog Desktop; 'slack' means it was triggered from Slack.",
+ "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' is the catch-all every sandbox agent sends, so it covers Signals runs as well as PostHog Desktop; break down by `source` to separate them. 'slack' means it was triggered from Slack.",
"examples": [
"posthog-code",
"slack"
@@ -8705,7 +8705,7 @@
"label": "Latest sccid"
},
"source": {
- "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
+ "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent and the local agent. 'self_driving' is Signals: scouts, report implementations, and scout chat. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
"examples": [
"web",
"posthog_ai",
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index 50fc3d5422fe..615bedc555e2 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -21,7 +21,7 @@ from posthog.models.team import Team
from posthog.oauth_provenance import get_oauth_client_id, is_first_party_oauth_client, is_interactive_desktop_grant
from posthog.settings import SITE_URL
from posthog.synthetic_user import SyntheticUser
-from posthog.temporal.oauth import POSTHOG_AI_OAUTH_APP_CLIENT_IDS
+from posthog.temporal.oauth import POSTHOG_AI_OAUTH_APP_CLIENT_IDS, SIGNALS_OAUTH_APP_CLIENT_IDS
from posthog.utils import get_instance_realm
if TYPE_CHECKING:
@@ -286,9 +286,13 @@ class EventSource(StrEnum):
API = "api"
CLI = "cli"
POSTHOG_AI = "posthog_ai"
- # Headless coding agents: the cloud agent, the local agent, signals scouts. Distinct from
- # DESKTOP and MOBILE, which are apps a person is sitting in front of.
+ # Headless coding agents: the cloud agent and the local agent. Distinct from DESKTOP and
+ # MOBILE, which are apps a person is sitting in front of.
POSTHOG_CODE = "posthog_code"
+ # Signals: scouts, report implementations, and scout chat. Every one of them mints under the
+ # Signals OAuth application, which is what tells them apart from the coding agents they
+ # otherwise look identical to.
+ SELF_DRIVING = "self_driving"
DESKTOP = "desktop"
MOBILE = "mobile"
SLACK = "slack"
@@ -313,6 +317,7 @@ AGENT_EVENT_SOURCES = frozenset(
{
EventSource.MCP,
EventSource.POSTHOG_CODE,
+ EventSource.SELF_DRIVING,
EventSource.DESKTOP,
EventSource.MOBILE,
EventSource.SLACK,
@@ -337,6 +342,7 @@ MCP_TRANSPORT_EVENT_SOURCES = frozenset(
EventSource.MOBILE,
EventSource.SLACK,
EventSource.POSTHOG_CODE,
+ EventSource.SELF_DRIVING,
}
)
@@ -427,8 +433,14 @@ def get_event_source(request) -> EventSource:
# A token minted against the PostHog AI OAuth app is authoritative — the auth
# credential can't be spoofed the way UA tokens and X-PostHog-Client can, so it
# wins over every header-based branch below.
- if get_oauth_client_id(request) in POSTHOG_AI_OAUTH_APP_CLIENT_IDS:
+ client_id = get_oauth_client_id(request)
+ if client_id in POSTHOG_AI_OAUTH_APP_CLIENT_IDS:
return EventSource.POSTHOG_AI
+ # Same reasoning, and it has to sit above the user-agent branches for the same reason: a
+ # Signals run is a sandbox coding agent, so it carries the posthog-code user-agent and
+ # declares the posthog-code MCP consumer. Only the application it minted under separates it.
+ if client_id in SIGNALS_OAUTH_APP_CLIENT_IDS:
+ return EventSource.SELF_DRIVING
user_agent = request.headers.get("user-agent", "") or ""
if not isinstance(user_agent, str):
user_agent = ""
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 01f8f3c958d6..0af6f874fc2a 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -65,6 +65,7 @@ APIScopeObject = Literal[
"insight",
"insight_variable",
"integration",
+ "interactive_run",
"internal_run",
"legal_document",
"link",
@@ -151,6 +152,12 @@ API_SCOPE_ACTIONS: tuple[APIScopeActions, ...] = get_args(APIScopeActions)
INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
{
"clickhouse_test_cluster_perf",
+ # Narrows `internal_run`: the run behind this token was started by a person
+ # pressing a button, not by one of PostHog's own schedulers. Both markers are
+ # minted server-side, so neither can be self-granted; the LLM gateway meters
+ # user-started runs against their own, much smaller budget because their volume
+ # is chosen by the customer rather than by us.
+ "interactive_run",
# Provenance marker on tokens minted server-side for a sandbox/agent run
# (never via the consent flow or a personal API key). The LLM gateway requires
# it on the internal products that share the PostHog Desktop OAuth app so a user's
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 09262d5331a7..547e86ed8637 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2870,7 +2870,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$mcp_consumer": {
"label": "MCP consumer",
- "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' means the request came through PostHog Desktop; 'slack' means it was triggered from Slack.",
+ "description": "The upstream surface that initiated the MCP request, supplied via the `x-posthog-mcp-consumer` header. 'posthog-code' is the catch-all every sandbox agent sends, so it covers Signals runs as well as PostHog Desktop; break down by `source` to separate them. 'slack' means it was triggered from Slack.",
"examples": ["posthog-code", "slack"],
},
"$mcp_mode": {
@@ -2986,8 +2986,9 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server "
"instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop "
"request can still show as 'mcp' on those. "
- "'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and "
- "signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. "
+ "'posthog_code' covers the headless coding agents: the cloud agent and the local agent. "
+ "'self_driving' is Signals: scouts, report implementations, and scout chat. "
+ "'wizard' is the setup agent and 'terraform' is the Terraform provider. "
"Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and "
"'subscription'. "
"Two unrelated properties share this name, so filter to a specific event before breaking "
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 87a2ee0c6c7a..c173c8d784a5 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -5,6 +5,8 @@ from uuid import UUID
from django.conf import settings
from django.utils import timezone
+import structlog
+
from posthog.models import OAuthAccessToken, OAuthApplication
from posthog.models.utils import generate_random_oauth_access_token
from posthog.scopes import (
@@ -16,6 +18,8 @@ from posthog.scopes import (
)
from posthog.utils import get_instance_region
+logger = structlog.get_logger(__name__)
+
ARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"
ARRAY_APP_CLIENT_ID_EU = "AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9"
ARRAY_APP_CLIENT_ID_DEV = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ"
@@ -24,11 +28,16 @@ POSTHOG_DESKTOP_MOBILE_APP_CLIENT_ID_EU = "1A7vO138Fh5sYmJislicN4F5HnttI6urmFttx
POSTHOG_AI_APP_CLIENT_ID_US = "N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu"
POSTHOG_AI_APP_CLIENT_ID_EU = "0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi"
POSTHOG_AI_APP_CLIENT_ID_DEV = "DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1"
+SIGNALS_APP_CLIENT_ID_US = "jpSRPhGBBbDGpKprit9bgJEuo6oUTa8ULymqf8PE"
+SIGNALS_APP_CLIENT_ID_EU = "nqZsiFEbu1fCWDK3r8QtSGwKmmANxVIgfZmTXywk"
+SIGNALS_APP_CLIENT_ID_DEV = "xMT3Nejjbi4lUdhJLkzmCVJKFsx0JsHXdU0pIjl8"
# The LLM gateway authorizes by application id, so these must stay equal to
-# POSTHOG_CODE_DEV_APP_ID / POSTHOG_AI_DEV_APP_ID in llm_gateway/products/config.py.
+# POSTHOG_CODE_DEV_APP_ID / POSTHOG_AI_DEV_APP_ID / SIGNALS_DEV_APP_ID in
+# llm_gateway/products/config.py.
ARRAY_APP_ID_DEV = "019ebb47-c750-0000-e1ea-723a6ff112d3"
POSTHOG_AI_APP_ID_DEV = "019edb1a-cce4-0000-1f6d-682061862da9"
+SIGNALS_APP_ID_DEV = "019fb2ee-9d54-0000-61d9-faf825230d44"
POSTHOG_DESKTOP_OAUTH_CLIENT_IDS = frozenset(
{
@@ -44,12 +53,37 @@ POSTHOG_DESKTOP_OAUTH_CLIENT_IDS = frozenset(
# issue interactive Desktop grants, so membership in this set does not prove sandbox origin.
POSTHOG_CODE_OAUTH_APP_CLIENT_IDS = frozenset({ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU, ARRAY_APP_CLIENT_ID_DEV})
+# The dedicated "Signals" OAuth app, minted for every Signals sandbox run (scouts and
+# report-driven tasks alike). Held apart from the Array app so the LLM gateway can pin the
+# `signals` product to it: while the two share an app, a Signals token also satisfies every
+# other product that app is authorized for, and the product a caller declares is a path
+# segment it chooses, so a per-product budget on a shared app is advisory rather than binding.
+SIGNALS_OAUTH_APP_CLIENT_IDS = frozenset(
+ {
+ SIGNALS_APP_CLIENT_ID_US,
+ SIGNALS_APP_CLIENT_ID_EU,
+ SIGNALS_APP_CLIENT_ID_DEV,
+ }
+)
+
+# Apps that mint tokens for a cloud task's own coding agent, which is what the task-comment
+# channel is restricted to. Signals joined when its runs moved off the Array app; PostHog AI is
+# deliberately absent, as it was before. The `sandbox_task_id` binding on the token is what
+# actually scopes access to one task — this set only keeps unrelated first-party tokens out.
+TASK_AGENT_OAUTH_APP_CLIENT_IDS = frozenset(
+ {
+ *POSTHOG_CODE_OAUTH_APP_CLIENT_IDS,
+ *SIGNALS_OAUTH_APP_CLIENT_IDS,
+ }
+)
+
SANDBOX_OAUTH_APP_CLIENT_IDS = frozenset(
{
*POSTHOG_CODE_OAUTH_APP_CLIENT_IDS,
POSTHOG_AI_APP_CLIENT_ID_US,
POSTHOG_AI_APP_CLIENT_ID_EU,
POSTHOG_AI_APP_CLIENT_ID_DEV,
+ *SIGNALS_OAUTH_APP_CLIENT_IDS,
}
)
@@ -65,7 +99,11 @@ POSTHOG_AI_OAUTH_APP_CLIENT_IDS = frozenset(
)
McpScopePreset = Literal["read_only", "full", "signals_scout", "signals_scout_reports", "report_canvas"]
-SandboxOAuthApplication = Literal["array", "posthog_ai"]
+SandboxOAuthApplication = Literal["array", "posthog_ai", "signals"]
+
+# Granted only to sandbox runs a person started by hand (see `interactive_run` in
+# posthog/scopes.py). Kept out of `INTERNAL_SCOPES` so a scheduled run never carries it.
+INTERACTIVE_RUN_SCOPE = "interactive_run:read"
INTERNAL_SCOPES: list[str] = [
@@ -240,9 +278,35 @@ def get_posthog_ai_app() -> OAuthApplication:
return _get_oauth_app_for_client_id(client_id, "PostHog AI", region)
+def get_signals_app() -> OAuthApplication | None:
+ """The Signals sandbox app for this region, or None when it isn't provisioned here.
+
+ Unlike the Array and PostHog AI resolvers this one never raises: the application rows are
+ created per region out of band, so callers fall back to the Array app until the row exists
+ rather than failing every Signals run in a region that hasn't been provisioned yet.
+ """
+ region = get_instance_region()
+ client_id = _get_client_id_for_region(
+ region=region,
+ us=SIGNALS_APP_CLIENT_ID_US,
+ eu=SIGNALS_APP_CLIENT_ID_EU,
+ dev=SIGNALS_APP_CLIENT_ID_DEV,
+ )
+ if not client_id:
+ return None
+ return OAuthApplication.objects.filter(client_id=client_id).first()
+
+
def get_sandbox_oauth_app(application: SandboxOAuthApplication = "array") -> OAuthApplication:
if application == "posthog_ai":
return get_posthog_ai_app()
+ if application == "signals":
+ signals_app = get_signals_app()
+ if signals_app is not None:
+ return signals_app
+ # Array still authorizes the `signals` gateway product, so the run works; it just
+ # isn't isolated yet. Loud enough to notice, since the isolation is the point.
+ logger.warning("signals_oauth_app_missing_falling_back_to_array", region=get_instance_region())
return get_array_app()
@@ -271,6 +335,7 @@ def create_oauth_access_token_for_user(
scopes: PosthogMcpScopes = "read_only",
include_internal_scopes: bool = True,
include_mcp_builtin_agent_scope: bool = False,
+ include_interactive_run_scope: bool = False,
application: SandboxOAuthApplication = "array",
sandbox_task_id: UUID | None = None,
) -> str:
@@ -280,6 +345,10 @@ def create_oauth_access_token_for_user(
# surface and route the agent through its explicit gateway grants. It
# does not narrow the token's other scopes.
resolved.append(MCP_BUILT_IN_AGENT_SCOPE)
+ if include_interactive_run_scope:
+ # Provenance marker only — it grants no access. The LLM gateway meters a run
+ # carrying it against the interactive budget instead of the pipeline's.
+ resolved.append(INTERACTIVE_RUN_SCOPE)
app = get_sandbox_oauth_app(application)
return _mint_oauth_access_token(user, team_id, app=app, scopes=list(resolved), sandbox_task_id=sandbox_task_id)
diff --git a/posthog/test/test_event_usage.py b/posthog/test/test_event_usage.py
index 8f3c4cf396a3..6bb84ca78fcf 100644
--- a/posthog/test/test_event_usage.py
+++ b/posthog/test/test_event_usage.py
@@ -20,7 +20,7 @@ from posthog.event_usage import (
sanitize_header_value,
)
from posthog.models.oauth import OAuthAccessToken
-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV, SIGNALS_APP_CLIENT_ID_DEV
# The MCP server's catch-all consumer, sent by every sandbox agent and by the agent PostHog
# Desktop hosts locally.
@@ -327,6 +327,25 @@ class TestGetEventSource(BaseTest):
)
assert get_event_source(request) == EventSource.POSTHOG_AI
+ @parameterized.expand(
+ [
+ # Signals runs are sandbox coding agents, so they carry the posthog-code user-agent and
+ # declare the posthog-code consumer. Both would otherwise resolve to POSTHOG_CODE, which
+ # makes the Signals application the only thing that keeps them out of that bucket.
+ ("user_agent", {"user-agent": "posthog/code 1.0"}),
+ ("mcp_consumer", {"X-Posthog-Client": "mcp", "X-Posthog-Mcp-Consumer": _POSTHOG_CODE_CONSUMER}),
+ ]
+ )
+ def test_signals_oauth_app_beats_the_posthog_code_signals(self, _name, headers):
+ request = SimpleNamespace(
+ META={},
+ headers=headers,
+ successful_authenticator=_oauth_authenticator(
+ SIGNALS_APP_CLIENT_ID_DEV, scope="insight:read internal_run:read"
+ ),
+ )
+ assert get_event_source(request) == EventSource.SELF_DRIVING
+
@parameterized.expand(
[
# A first-party caller that declares no consumer is resolved from the grant alone, and
@@ -385,7 +404,7 @@ class TestGetEventSource(BaseTest):
# that is not an EventSource drops out of every breakdown that joins the two. This list is
# EVENT_SOURCE in `services/mcp/src/lib/event-source.ts`, which its own test pins; removing
# a surface here without removing it there fails this.
- mcp_server_sources = {"mcp", "cli", "wizard", "slack", "posthog_ai", "posthog_code"}
+ mcp_server_sources = {"mcp", "cli", "wizard", "slack", "posthog_ai", "posthog_code", "self_driving"}
assert mcp_server_sources <= {source.value for source in EventSource}
@parameterized.expand(
diff --git a/products/tasks/backend/management/commands/setup_tasks_oauth.py b/products/tasks/backend/management/commands/setup_tasks_oauth.py
index 567c7800e5a1..138622a862f3 100644
--- a/products/tasks/backend/management/commands/setup_tasks_oauth.py
+++ b/products/tasks/backend/management/commands/setup_tasks_oauth.py
@@ -7,11 +7,16 @@ from posthog.temporal.oauth import (
ARRAY_APP_ID_DEV,
POSTHOG_AI_APP_CLIENT_ID_DEV,
POSTHOG_AI_APP_ID_DEV,
+ SIGNALS_APP_CLIENT_ID_DEV,
+ SIGNALS_APP_ID_DEV,
)
from posthog.utils import get_instance_region
ARRAY_REDIRECT_URIS = "http://localhost:8237/callback http://localhost:8239/callback"
POSTHOG_AI_REDIRECT_URIS = "http://localhost:8000/authorize"
+# Server-minted only: no interactive grant is ever issued against the Signals app, so it has
+# no real callback. Django requires a redirect URI for the authorization-code grant type.
+SIGNALS_REDIRECT_URIS = "http://localhost:8000/authorize"
# Skipped rather than failed, so the unconditional call in bin/migrate is safe.
PRODUCTION_REGIONS = frozenset({"US", "EU"})
@@ -51,6 +56,20 @@ class Command(BaseCommand):
"is_first_party": True,
},
)
+ self._setup_app(
+ SIGNALS_APP_CLIENT_ID_DEV,
+ {
+ "id": SIGNALS_APP_ID_DEV,
+ "name": "Signals Dev App",
+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": SIGNALS_REDIRECT_URIS,
+ "algorithm": "RS256",
+ "auth_brand": OAuthApplicationAuthBrand.POSTHOG.value,
+ "is_verified": True,
+ "is_first_party": True,
+ },
+ )
def _setup_app(self, client_id: str, defaults: dict[str, object]) -> None:
if not client_id:
diff --git a/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py
index 88ee73e9ebb8..ad72e1c130e9 100644
--- a/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py
+++ b/products/tasks/backend/management/commands/test/test_setup_tasks_oauth.py
@@ -12,9 +12,11 @@ from posthog.temporal.oauth import (
ARRAY_APP_ID_DEV,
POSTHOG_AI_APP_CLIENT_ID_DEV,
POSTHOG_AI_APP_ID_DEV,
+ SIGNALS_APP_CLIENT_ID_DEV,
+ SIGNALS_APP_ID_DEV,
)
-DEV_CLIENT_IDS = [ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV]
+DEV_CLIENT_IDS = [ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV, SIGNALS_APP_CLIENT_ID_DEV]
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="DEV")
@@ -46,6 +48,20 @@ class TestSetupTasksOAuth(TestCase):
"is_first_party": True,
},
),
+ (
+ "signals",
+ SIGNALS_APP_CLIENT_ID_DEV,
+ SIGNALS_APP_ID_DEV,
+ {
+ "name": "Signals Dev App",
+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": "http://localhost:8000/authorize",
+ "auth_brand": OAuthApplicationAuthBrand.POSTHOG.value,
+ "is_verified": True,
+ "is_first_party": True,
+ },
+ ),
]
)
def test_creates_dev_oauth_app_and_reruns_cleanly(
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index b3eaa8c88844..052ef7ed60c9 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -47,7 +47,7 @@ from posthog.permissions import APIScopePermission, get_authenticator_scoped_tea
from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.schema_migrations.upgrade import upgrade
-from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDS, SANDBOX_OAUTH_APP_CLIENT_IDS
+from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS, TASK_AGENT_OAUTH_APP_CLIENT_IDS
from posthog.utils import absolute_uri
from products.exports.backend.facade.api import render_png_export
@@ -313,7 +313,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not isinstance(authenticator, OAuthAccessTokenAuthentication):
raise PermissionDenied("Task comments are available only to the current task agent.")
application = authenticator.access_token.application
- if application is None or application.client_id not in POSTHOG_CODE_OAUTH_APP_CLIENT_IDS:
+ if application is None or application.client_id not in TASK_AGENT_OAUTH_APP_CLIENT_IDS:
raise PermissionDenied("Task comments are available only to the current task agent.")
try:
parsed_task_id = UUID(task_id)
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 6643da8e72bd..8f0270e18784 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -45,12 +45,42 @@ __all__ = [
LOOP_FIRED_RUN_EXCLUDED_SCOPES = frozenset({"loop:write"})
+# Every Signals sandbox surface mints under the dedicated Signals OAuth app, so the LLM
+# gateway can pin the `signals` product to that app alone. Sharing the Array app would leave
+# a Signals token equally valid for `posthog_code` and `background_agents`, and the product
+# is a path segment the caller picks, so any per-product budget would be self-selected.
+SIGNALS_ORIGIN_PRODUCTS = frozenset(
+ {
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.SIGNALS_SCOUT,
+ Task.OriginProduct.SIGNALS_CHAT,
+ }
+)
+
+# Signals surfaces a person drives by hand: the Inbox report CTAs ("Create PR" / "Discuss")
+# and scout chat. Scheduled scouts and auto-started implementations are excluded — they carry
+# `internal=True`, and their volume is chosen by our own pipeline rather than by a customer.
+INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS = frozenset(
+ {
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.SIGNALS_CHAT,
+ }
+)
+
+
def _oauth_application_for_task(task: Task) -> SandboxOAuthApplication:
if task.origin_product == Task.OriginProduct.POSTHOG_AI:
return "posthog_ai"
+ if task.origin_product in SIGNALS_ORIGIN_PRODUCTS:
+ return "signals"
return "array"
+def _is_interactive_signals_task(task: Task) -> bool:
+ """Whether this run exists because a person pressed something, not because we scheduled it."""
+ return task.origin_product in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS and not task.internal
+
+
def _scopes_for_loop_fired_run(scopes: PosthogMcpScopes) -> list[str]:
resolved = resolve_scopes(scopes, include_internal_scopes=True)
return [scope for scope in resolved if scope not in LOOP_FIRED_RUN_EXCLUDED_SCOPES]
@@ -94,6 +124,8 @@ def create_oauth_access_token(
# task needs a member-capable token, or every member-proxy call it was
# just granted would 403.
token_options["include_mcp_builtin_agent_scope"] = True
+ if _is_interactive_signals_task(task):
+ token_options["include_interactive_run_scope"] = True
return create_oauth_access_token_for_user(actor, task.team_id, **token_options)
@@ -171,6 +203,7 @@ def create_oauth_access_token_for_user(
scopes: PosthogMcpScopes = "read_only",
application: SandboxOAuthApplication = "array",
include_mcp_builtin_agent_scope: bool = False,
+ include_interactive_run_scope: bool = False,
sandbox_task_id: UUID | None = None,
) -> str:
"""Create an OAuth access token for a sandbox app, scoped to a specific team."""
@@ -182,6 +215,8 @@ def create_oauth_access_token_for_user(
}
if include_mcp_builtin_agent_scope:
token_options["include_mcp_builtin_agent_scope"] = True
+ if include_interactive_run_scope:
+ token_options["include_interactive_run_scope"] = True
return _create_oauth_access_token_for_user(user, team_id, **token_options)
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from err
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 18848bf7c7e1..9678f5efbe05 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -12,7 +12,7 @@ from products.tasks.backend.temporal.oauth import create_oauth_access_token, cre
@pytest.mark.parametrize(
("origin_product", "application"),
[
- (Task.OriginProduct.SIGNALS_SCOUT, "array"),
+ (Task.OriginProduct.SIGNALS_SCOUT, "signals"),
(Task.OriginProduct.SUPPORT_REPLY, "array"),
],
)
@@ -111,6 +111,46 @@ def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> No
)
+ ("origin_product", "internal", "application", "interactive"),
+ [
+ (Task.OriginProduct.SIGNAL_REPORT, False, "signals", True),
+ (Task.OriginProduct.SIGNAL_REPORT, True, "signals", False),
+ (Task.OriginProduct.SIGNALS_CHAT, False, "signals", True),
+ (Task.OriginProduct.SIGNALS_SCOUT, True, "signals", False),
+ (Task.OriginProduct.USER_CREATED, False, "array", False),
+ ],
+)
+@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_signals_origins_mint_under_the_signals_app_and_mark_only_user_started_runs(
+ mock_create: MagicMock,
+ mock_enforcement: MagicMock,
+ origin_product: Task.OriginProduct,
+ internal: bool,
+ application: str,
+ interactive: bool,
+) -> None:
+ task = MagicMock(
+ id="task-id",
+ created_by=MagicMock(),
+ team_id=123,
+ origin_product=origin_product,
+ internal=internal,
+ )
+
+ assert create_oauth_access_token(task) == "token"
+
+ expected: dict = {
+ "scopes": "read_only",
+ "application": application,
+ "sandbox_task_id": task.id,
+ }
+ if interactive:
+ expected["include_interactive_run_scope"] = True
+ mock_create.assert_called_once_with(task.created_by, 123, **expected)
+
+
def test_oauth_token_can_disable_task_creator_fallback() -> None:
task = MagicMock(
id="task-id",
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 6f34e212a06f..07a08a004942 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -2209,6 +2209,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
EventSource.DESKTOP: ExternalDataSource.CreatedVia.SELF_DRIVING,
EventSource.MOBILE: ExternalDataSource.CreatedVia.SELF_DRIVING,
EventSource.POSTHOG_CODE: ExternalDataSource.CreatedVia.SELF_DRIVING,
+ EventSource.SELF_DRIVING: ExternalDataSource.CreatedVia.SELF_DRIVING,
}
created_via = transport_created_via.get(get_event_source(request), created_via)
# The wizard's `self-driving` onboarding program shares the generic `posthog/wizard`
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index e6f4c2dde555..bcfc7470cdd4 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -39,6 +39,7 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_cl
| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, free-tier model allowlists, and product billing or unbilled policy are not available together in Go. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control. An `ai_product` event property is not an authorization or billing boundary. |
| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |
+| Agent runs a customer can start on demand | Python bounds one run's total spend against the task its credential was minted for, and picks the budget from the token's provenance rather than from the product the caller declares. Go has neither, so both the per-run ceiling and the pipeline-versus-user-started split would be lost on migration. |
| OpenRouter, Fireworks, Cloudflare Workers AI, or Baseten | These provider paths are not available in Go. |
| OpenAI audio transcription | Go has no transcription endpoint. |
| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |
@@ -59,19 +60,19 @@ These are compatibility checks, not automatic blockers:
## Parity map
-| Contract | Go gateway today | Python-only behavior that can block migration |
-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
-| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, model policy, and the PostHog Desktop entitlement check on `posthog_code` (Django `has_tasks_access`, since an OAuth app allowlist alone does not prove beta membership). |
-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |
-| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, plans, quota buckets, product-specific free-tier model allowlists, unbilled products, and product usage status. |
-| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
-| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
-| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |
-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |
-| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
-| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
-| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |
+| Contract | Go gateway today | Python-only behavior that can block migration |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |
+| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, model policy, and the PostHog Desktop entitlement check on `posthog_code` (Django `has_tasks_access`, since an OAuth app allowlist alone does not prove beta membership). |
+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |
+| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, per-sandbox-run ceilings keyed on the credential's task binding, budget keys derived from token scopes rather than the declared product, plans, quota buckets, product-specific free-tier model allowlists, unbilled products, and product usage status. |
+| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |
+| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |
+| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |
+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |
+| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |
+| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |
+| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |
## Migration checklist
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 392e3edc8d6a..5e8f7b790e1a 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -275,6 +275,10 @@ cold-cache requests. Grants cache for 15 minutes and denials for 60 seconds, so
locks an entitled user out for at most a minute after their cached grant expires.
`LLM_GATEWAY_DESKTOP_ACCESS_GATE_ENABLED=false` disables the gate entirely.
+`signals` is authorized for its own OAuth application, so a Signals run's token cannot be spent as `posthog_code` or `background_agents` by declaring a different product in the path.
+Its US, EU, and dev application ids are pinned in `products/config.py` alongside every other first-party app.
+The PostHog Code application ids stay listed on `signals` until every region mints under the new app; removing them completes the isolation.
+
### Adding a new product
1. **Add to `PRODUCTS`** in `src/llm_gateway/products/config.py`:
@@ -324,6 +328,25 @@ Products without an explicit entry fall back to the **default: $100/24h burst, $
User-level limits only apply when an `end_user_id` is present (OAuth token holder, or `user` param in the request body).
+### Per-run limits
+
+A sandbox agent run can spend a whole window's budget in one conversation, because the person driving it decides when it ends.
+`DEFAULT_SANDBOX_TASK_COST_LIMITS` caps the total spend of a single run, keyed on the task the token was minted for (`posthog_oauthaccesstoken.sandbox_task_id`), not on anything the caller sends:
+
+```python
+"my_budget": ProductCostLimit(limit_usd=50.0, window_seconds=604800) # $50 per run
+```
+
+Opt-in — a budget with no entry has no per-run ceiling, and a token with no task binding is never metered here.
+
+### Budget keys
+
+The three limits above are usually keyed by product, but a product that serves both our own scheduled work and a button a customer can press needs two budgets rather than one.
+`resolve_cost_key` picks the budget from the token's scopes, which are minted server-side, instead of from the product in the URL, which the caller chooses.
+
+Today that splits `signals`: a run started from the Inbox carries `interactive_run:read` and meters against `signals_interactive`, while the scheduled pipeline keeps `signals`.
+`signals_interactive` is a budget name only — it is not in `PRODUCTS`, so no caller can request it.
+
## Error handling
Errors follow OpenAI's format:
diff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.py
index 98e0b36d014b..34c286255242 100644
--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py
+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py
@@ -110,6 +110,7 @@ class OAuthAccessTokenAuthenticator(Authenticator):
"""
SELECT oat.id, oat.user_id, oat.scope, oat.expires,
oat.application_id, oat.scoped_teams, oat.scoped_organizations,
+ oat.sandbox_task_id,
u.current_team_id, u.distinct_id, u.is_staff
FROM posthog_oauthaccesstoken oat
JOIN posthog_user u ON oat.user_id = u.id
@@ -143,4 +144,5 @@ class OAuthAccessTokenAuthenticator(Authenticator):
is_staff=row["is_staff"],
scoped_teams=row.get("scoped_teams"),
scoped_organizations=row.get("scoped_organizations"),
+ sandbox_task_id=str(row["sandbox_task_id"]) if row.get("sandbox_task_id") else None,
)
diff --git a/services/llm-gateway/src/llm_gateway/auth/models.py b/services/llm-gateway/src/llm_gateway/auth/models.py
index a34fc477a5e7..df51d6bc4c53 100644
--- a/services/llm-gateway/src/llm_gateway/auth/models.py
+++ b/services/llm-gateway/src/llm_gateway/auth/models.py
@@ -14,6 +14,10 @@ class AuthenticatedUser:
is_staff: bool = False
scoped_teams: list[int] | None = None
scoped_organizations: list[str] | None = None
+ # The sandbox run this token was minted for, stamped server-side at mint time. Unlike the
+ # attribution headers a caller sends, a sandbox can't rewrite it, so it's the one identifier
+ # a per-run budget can safely key on.
+ sandbox_task_id: str | None = None
def resolve_distinct_id(auth_user: AuthenticatedUser, end_user_id: str | None) -> str:
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index 5b85145277a2..6ef4e23e804b 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -34,6 +34,10 @@ DEFAULT_PRODUCT_COST_LIMITS: dict[str, "ProductCostLimit"] = {
"django": ProductCostLimit(limit_usd=5000.0, window_seconds=86400),
"custom_image_scans": ProductCostLimit(limit_usd=1000.0, window_seconds=86400),
"signals": ProductCostLimit(limit_usd=25000.0, window_seconds=86400),
+ # Signals runs a customer started by hand (Inbox "Create PR" / "Discuss", scout chat).
+ # Held apart from the scheduled pipeline's pool so a customer burning this budget can't
+ # stall scouts and report research for every other customer.
+ "signals_interactive": ProductCostLimit(limit_usd=10000.0, window_seconds=86400),
"posthog_ai": ProductCostLimit(limit_usd=5000.0, window_seconds=86400),
"changelog_bot": ProductCostLimit(limit_usd=500.0, window_seconds=86400),
# Path-cleaning suggestions: haiku-only, a few short calls per team per week. The product is
@@ -61,6 +65,15 @@ DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {
sustained_limit_usd=10000.0,
sustained_window_seconds=2592000,
),
+ # The Inbox CTAs and scout chat. Sized for one person's hands-on use, not for the
+ # scheduled pipeline: the `signals` limit above has to cover fleet-wide scout and research
+ # work for a whole team, so a surface a person drives one run at a time needs far less.
+ "signals_interactive": UserCostLimit(
+ burst_limit_usd=250.0,
+ burst_window_seconds=604800,
+ sustained_limit_usd=750.0,
+ sustained_window_seconds=2592000,
+ ),
# Nobody is billed for onboarding (credit_bucket=None), so this bounds blast radius rather than
# spend: the route's server-credential marker proves a token was minted server-side, not that it
# belongs to a wizard run, and INTERNAL_SCOPES in posthog/temporal/oauth.py grants that marker to
@@ -76,6 +89,14 @@ DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {
),
}
+# Per-sandbox-run ceilings, keyed the same way as the cost limits above. Opt-in: a key with no
+# entry has no per-run ceiling, so adding one here is the only way a product gains one. The
+# window is a floor on how long a single run's spend is remembered, not a refill schedule —
+# runs are far shorter than this, so in practice each task gets one budget for its lifetime.
+DEFAULT_SANDBOX_TASK_COST_LIMITS: dict[str, "ProductCostLimit"] = {
+ "signals_interactive": ProductCostLimit(limit_usd=50.0, window_seconds=604800),
+}
+
_COST_LIMIT_KEY_ALIASES: dict[str, str] = {
"array": "posthog_code",
"twig": "posthog_code",
@@ -201,6 +222,11 @@ class Settings(BaseSettings):
user_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITS
user_cost_limits_disabled: bool = False
+ # Per-sandbox-run ceiling, keyed on the task the token was minted for. Product and user
+ # budgets are windowed, so neither bounds one runaway conversation inside its window.
+ sandbox_task_cost_limits: dict[str, ProductCostLimit] = DEFAULT_SANDBOX_TASK_COST_LIMITS
+ sandbox_task_cost_limits_disabled: bool = False
+
posthog_code_free_tier_models: list[str] = [
"@cf/zai-org/glm-5.2",
"deepseek-ai/deepseek-v4-flash-0731",
@@ -236,6 +262,11 @@ class Settings(BaseSettings):
def parse_product_cost_limits(cls, v: str | dict | None) -> dict[str, ProductCostLimit]:
return _parse_model_dict(v, ProductCostLimit, DEFAULT_PRODUCT_COST_LIMITS, "product_cost_limits")
+ @field_validator("sandbox_task_cost_limits", mode="before")
+ @classmethod
+ def parse_sandbox_task_cost_limits(cls, v: str | dict | None) -> dict[str, ProductCostLimit]:
+ return _parse_model_dict(v, ProductCostLimit, DEFAULT_SANDBOX_TASK_COST_LIMITS, "sandbox_task_cost_limits")
+
@field_validator("user_cost_limits", mode="before")
@classmethod
def parse_user_cost_limits(cls, v: str | dict | None) -> dict[str, UserCostLimit]:
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index accbeca3f496..7e46843ee9f8 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -337,6 +337,7 @@ async def enforce_throttles(
code_usage_billed=quota_status.code_usage_billing_active,
billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,
credits_exhausted=quota_status.limited,
+ sandbox_task_id=user.sandbox_task_id,
)
request.state.throttle_context = context
set_throttle_context(runner, context)
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index 300e54d67800..50c97dcdf57b 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -33,6 +33,7 @@ from llm_gateway.rate_limiting.cost_gauge_publisher import publish_product_cost_
from llm_gateway.rate_limiting.cost_refresh import ensure_costs_fresh
from llm_gateway.rate_limiting.cost_throttles import (
ProductCostThrottle,
+ SandboxTaskCostThrottle,
UserCostBurstThrottle,
UserCostSustainedThrottle,
)
@@ -199,6 +200,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
product_throttle,
UserCostBurstThrottle(redis=app.state.redis),
UserCostSustainedThrottle(redis=app.state.redis),
+ SandboxTaskCostThrottle(redis=app.state.redis),
],
denial_capturer=denial_capturer,
)
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 09e49562e4f2..7caf96de18e2 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -63,6 +63,9 @@ WIZARD_EU_APP_ID = "019a12d0-6edd-0000-0458-86616af3a3db"
POSTHOG_AI_US_APP_ID = "019ee060-3a0e-0000-7e9c-4e6b48dfae66"
POSTHOG_AI_EU_APP_ID = "019ee061-5620-0000-1a0d-ab1160fceeb1"
POSTHOG_AI_DEV_APP_ID = "019edb1a-cce4-0000-1f6d-682061862da9"
+SIGNALS_US_APP_ID = "01a01611-1dc2-0000-61ea-c4c8322e8936"
+SIGNALS_EU_APP_ID = "01a01613-c382-0000-1472-f7881db30f4f"
+SIGNALS_DEV_APP_ID = "019fb2ee-9d54-0000-61d9-faf825230d44"
# Shared by `posthog_code` and `slack_app` — the agent that runs in the sandbox
# is the same code regardless of where the task was initiated, so the model
@@ -240,7 +243,19 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allow_api_keys=True,
),
"signals": ProductConfig(
- allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),
+ # Dual-accept during the app migration: the PostHog Code ids stay listed until every
+ # region has a Signals application row and its runs mint under it. Dropping them is
+ # what finally makes this product unreachable from a Desktop-app token.
+ allowed_application_ids=frozenset(
+ {
+ POSTHOG_CODE_US_APP_ID,
+ POSTHOG_CODE_EU_APP_ID,
+ POSTHOG_CODE_DEV_APP_ID,
+ SIGNALS_US_APP_ID,
+ SIGNALS_EU_APP_ID,
+ SIGNALS_DEV_APP_ID,
+ }
+ ),
allowed_models=None, # any model — the signals pipeline picks models per stage (haiku, sonnet, ...)
allow_api_keys=True,
credit_bucket=None,
@@ -416,6 +431,17 @@ FREE_TIER_RESTRICTION_REASON: Final[str] = "paid_plan_required"
# rather than held by a user. Products with requires_server_credential demand it from OAuth callers.
INTERNAL_RUN_SCOPE: Final[str] = "internal_run:read"
+# Narrower marker on the same tokens: the run was started by a person, not by one of our
+# schedulers (INTERACTIVE_RUN_SCOPE in posthog/temporal/oauth.py). Also an internal scope, so
+# it can't be self-granted. Used to pick the budget, never to grant access.
+INTERACTIVE_RUN_SCOPE: Final[str] = "interactive_run:read"
+
+SIGNALS_PRODUCT: Final[str] = "signals"
+
+# Not a product: no caller can declare it, and it never appears in PRODUCTS. It only names a
+# budget in product_cost_limits / user_cost_limits, resolved from the token by resolve_cost_key.
+SIGNALS_INTERACTIVE_COST_KEY: Final[str] = "signals_interactive"
+
def check_free_tier_model_access(
product: str,
@@ -477,6 +503,20 @@ def is_model_restricted_for_product(model: str, product: str) -> bool:
return allowed_products is not None and resolve_product_alias(product) not in allowed_products
+def resolve_cost_key(product: str, scopes: list[str] | None) -> str:
+ """The budget a request meters against, which is not always its product.
+
+ Signals runs a scheduled pipeline and a set of buttons in the Inbox through one product.
+ Their volume has different owners — ours and the customer's — so they get separate budgets,
+ resolved from the token's own provenance marker rather than from the product the caller
+ declared, which a sandbox is free to choose.
+ """
+ resolved = resolve_product_alias(product)
+ if resolved == SIGNALS_PRODUCT and INTERACTIVE_RUN_SCOPE in (scopes or []):
+ return SIGNALS_INTERACTIVE_COST_KEY
+ return resolved
+
+
def check_product_access(
product: str,
auth_method: str,
@@ -502,8 +542,7 @@ def check_product_access(
is_oauth = auth_method == "oauth_access_token"
if is_oauth and not settings.debug:
# Skip application ID checks in debug mode
- allowed_application_ids = config.allowed_application_ids or frozenset()
- if application_id not in allowed_application_ids:
+ if application_id not in (config.allowed_application_ids or frozenset()):
return False, f"OAuth application not authorized for product '{product}'"
# Internal products that share the PostHog Desktop OAuth app are only ever driven by
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
index e4d85ad3e2fc..f113cf565f48 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py
@@ -8,6 +8,7 @@ import structlog
from redis.asyncio import Redis
from llm_gateway.config import DEFAULT_USER_COST_LIMIT, get_settings
+from llm_gateway.products.config import resolve_cost_key
if TYPE_CHECKING:
from llm_gateway.config import UserCostLimit
@@ -43,6 +44,10 @@ class CostThrottle(Throttle):
def _get_multiplier(self, context: ThrottleContext) -> int:
return get_rate_limit_multiplier(context.user)
+ def _cost_key(self, context: ThrottleContext) -> str:
+ """The budget this request meters against — usually its product, see `resolve_cost_key`."""
+ return resolve_cost_key(context.product, context.user.scopes)
+
@abstractmethod
def _get_cache_key(self, context: ThrottleContext) -> str: ...
@@ -162,14 +167,14 @@ class ProductCostThrottle(CostThrottle):
def _get_cache_key(self, context: ThrottleContext) -> str:
mult = self._get_multiplier(context)
- base = f"cost:product:{context.product}"
+ base = f"cost:product:{self._cost_key(context)}"
if mult == 1:
return base
return f"{base}:m{mult}"
def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:
settings = get_settings()
- product_config = settings.product_cost_limits.get(context.product)
+ product_config = settings.product_cost_limits.get(self._cost_key(context))
if product_config:
base_limit = product_config.limit_usd
window = product_config.window_seconds
@@ -229,20 +234,21 @@ class _UserCostThrottleBase(CostThrottle):
if not context.end_user_id:
return ""
mult = self._get_multiplier(context)
- base = f"cost:user:{self.scope}:{context.product}:{context.end_user_id}"
+ base = f"cost:user:{self.scope}:{self._cost_key(context)}:{context.end_user_id}"
if mult == 1:
return base
return f"{base}:m{mult}"
def _get_config(self, context: ThrottleContext) -> UserCostLimit:
- config = get_settings().user_cost_limits.get(context.product)
+ cost_key = self._cost_key(context)
+ config = get_settings().user_cost_limits.get(cost_key)
if not config:
- if context.end_user_id and context.product not in self._warned_products:
- self._warned_products.add(context.product)
+ if context.end_user_id and cost_key not in self._warned_products:
+ self._warned_products.add(cost_key)
logger.info(
"user_cost_limits_using_default",
- product=context.product,
- message=f"No user_cost_limits config for product '{context.product}' — using default limits",
+ product=cost_key,
+ message=f"No user_cost_limits config for product '{cost_key}' — using default limits",
)
return DEFAULT_USER_COST_LIMIT
return config
@@ -280,6 +286,51 @@ class _UserCostThrottleBase(CostThrottle):
await super().record_cost(context, cost)
+class SandboxTaskCostThrottle(CostThrottle):
+ """Total spend ceiling for one sandbox run, keyed on the task its token was minted for.
+
+ The product and per-user budgets are windowed, so a single conversation can spend a window's
+ worth of budget before either notices — and a user-started agent run has no natural end, since
+ the person can keep replying to it. This bounds the run itself. The key comes from the token
+ row rather than from request attribution, which the sandbox writes and could vary per call.
+
+ Opt-in: a cost key absent from `sandbox_task_cost_limits` has no ceiling, so this is inert for
+ every product that hasn't configured one.
+ """
+
+ scope = "sandbox_task_cost"
+
+ def _get_limit_exceeded_detail(self) -> str:
+ return "This agent run reached its spend limit"
+
+ def _get_cache_key(self, context: ThrottleContext) -> str:
+ if not context.sandbox_task_id:
+ return ""
+ # Deliberately not multiplied by the staff/team rate-limit multiplier: this is a
+ # per-run circuit breaker, and an elevated fleet-wide multiplier shouldn't widen it.
+ return f"cost:task:{context.sandbox_task_id}"
+
+ def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:
+ config = get_settings().sandbox_task_cost_limits.get(self._cost_key(context))
+ if config is None:
+ return 0.0, 0
+ return config.limit_usd, config.window_seconds
+
+ def _is_configured(self, context: ThrottleContext) -> bool:
+ return bool(context.sandbox_task_id) and self._cost_key(context) in get_settings().sandbox_task_cost_limits
+
+ async def allow_request(self, context: ThrottleContext) -> ThrottleResult:
+ if not self._is_configured(context) or get_settings().sandbox_task_cost_limits_disabled:
+ return ThrottleResult.allow()
+ return await super().allow_request(context)
+
+ async def record_cost(self, context: ThrottleContext, cost: float) -> None:
+ if not self._is_configured(context):
+ return
+ # Recorded even when enforcement is off, so a dark launch measures what it would block.
+ await super().record_cost(context, cost)
+
+
class UserCostBurstThrottle(_UserCostThrottleBase):
scope = "user_cost_burst"
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
index f7c229be2d9c..62b435fce778 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
@@ -51,6 +51,8 @@ class ThrottleContext:
code_usage_billed: bool = False
billing_period_start: str | None = None
credits_exhausted: bool = False
+ # Set only for sandbox-run tokens; see AuthenticatedUser.sandbox_task_id.
+ sandbox_task_id: str | None = None
@dataclass
diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.py
index de09adc1d12b..6c8eef114013 100644
--- a/services/llm-gateway/tests/test_cost_throttles.py
+++ b/services/llm-gateway/tests/test_cost_throttles.py
@@ -2,8 +2,10 @@ import pytest
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.config import get_settings
+from llm_gateway.products.config import resolve_cost_key
from llm_gateway.rate_limiting.cost_throttles import (
CostThrottle,
+ SandboxTaskCostThrottle,
UserCostBurstThrottle,
UserCostSustainedThrottle,
_UserCostThrottleBase,
@@ -24,6 +26,16 @@ def make_user(
)
+def make_signals_user(interactive: bool, user_id: int = 1) -> AuthenticatedUser:
+ """A Signals sandbox token. `interactive` is the marker a user-started run carries."""
+ user = make_user(user_id=user_id)
+ scopes = ["llm_gateway:read", "internal_run:read"]
+ if interactive:
+ scopes.append("interactive_run:read")
+ user.scopes = scopes
+ return user
+
+
def make_context(
user: AuthenticatedUser | None = None,
product: str = "posthog_code",
@@ -33,6 +45,7 @@ def make_context(
seat_missing: bool = False,
code_usage_billed: bool = False,
billing_period_start: str | None = None,
+ sandbox_task_id: str | None = None,
) -> ThrottleContext:
user = user or make_user()
if end_user_id is None and user.auth_method == "oauth_access_token":
@@ -46,6 +59,7 @@ def make_context(
seat_missing=seat_missing,
code_usage_billed=code_usage_billed,
billing_period_start=billing_period_start,
+ sandbox_task_id=sandbox_task_id,
)
@@ -1259,3 +1273,65 @@ class TestCostAccumulatorTTL:
assert accumulator.get_current("user1") == 5.0
assert accumulator.get_current("user2") == 3.0
+
+
+class TestSignalsInteractiveCostKey:
+ @pytest.mark.parametrize(
+ ("product", "scopes", "expected"),
+ [
+ ("signals", ["llm_gateway:read", "interactive_run:read"], "signals_interactive"),
+ ("signals", ["llm_gateway:read"], "signals"),
+ ("posthog_code", ["llm_gateway:read", "interactive_run:read"], "posthog_code"),
+ ("background_agents", ["llm_gateway:read", "interactive_run:read"], "background_agents"),
+ ],
+ )
+ def test_only_a_marked_signals_token_meters_against_the_interactive_budget(
+ self, product: str, scopes: list[str], expected: str
+ ) -> None:
+ assert resolve_cost_key(product, scopes) == expected
+
+ @pytest.mark.asyncio
+ async def test_marked_and_unmarked_signals_runs_bill_to_separate_user_keys(self) -> None:
+ throttle = UserCostBurstThrottle(redis=None)
+ pipeline = make_context(product="signals", user=make_signals_user(interactive=False))
+ interactive = make_context(product="signals", user=make_signals_user(interactive=True))
+
+ await throttle.record_cost(pipeline, 5.0)
+
+ assert await recorded_cost(throttle, pipeline) == 5.0
+ assert await recorded_cost(throttle, interactive) == 0.0
+
+
+class TestSandboxTaskCostThrottle:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("product", "sandbox_task_id"),
+ [
+ ("posthog_code", "task-1"), # product without a configured per-run ceiling
+ ("signals", None), # not a sandbox token, so there is no run to meter
+ ],
+ )
+ async def test_is_inert_without_a_configured_ceiling_and_a_run_to_charge(
+ self, product: str, sandbox_task_id: str | None
+ ) -> None:
+ throttle = SandboxTaskCostThrottle(redis=None)
+ context = make_context(
+ product=product,
+ user=make_signals_user(interactive=True),
+ sandbox_task_id=sandbox_task_id,
+ )
+
+ assert (await throttle.allow_request(context)).allowed is True
+
+ @pytest.mark.asyncio
+ async def test_denies_the_run_that_exhausts_its_ceiling_and_leaves_its_siblings_alone(self) -> None:
+ throttle = SandboxTaskCostThrottle(redis=None)
+ user = make_signals_user(interactive=True)
+ spent = make_context(product="signals", user=user, sandbox_task_id="task-1")
+ sibling = make_context(product="signals", user=user, sandbox_task_id="task-2")
+ limit, _ = throttle._get_limit_and_window(spent)
+
+ await throttle.record_cost(spent, limit)
+
+ assert (await throttle.allow_request(spent)).allowed is False
+ assert (await throttle.allow_request(sibling)).allowed is True
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 30c47b8ae685..abaa2c7748d6 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -19,6 +19,7 @@ from llm_gateway.products.config import (
POSTHOG_CODE_US_APP_ID,
PRODUCT_ALIASES,
PRODUCTS,
+ SIGNALS_DEV_APP_ID,
TWIG_EU_APP_ID,
TWIG_US_APP_ID,
WIZARD_EU_APP_ID,
@@ -734,3 +735,24 @@ class TestModelAccessFlag:
assert suffixed not in BASETEN_MODELS
assert not is_modal_served_model(suffixed)
assert suffixed not in CLOUDFLARE_ALLOWED_MODELS
+
+
+class TestSignalsApplicationIsolation:
+ @pytest.mark.parametrize(
+ ("product", "expected_allowed"),
+ [
+ ("signals", True),
+ ("posthog_code", False),
+ ("background_agents", False),
+ ("slack_app", False),
+ ],
+ )
+ @patch("llm_gateway.products.config.get_settings", return_value=MagicMock(debug=False))
+ def test_signals_app_reaches_only_the_signals_product(
+ self, mock_get_settings: MagicMock, product: str, expected_allowed: bool
+ ):
+ # The point of the separate application: a Signals run's token must not be spendable as
+ # posthog_code (which bills the customer) or as background_agents (a looser budget), both
+ # of which it could reach while Signals shared the Desktop app.
+ allowed, _ = check_product_access(product, "oauth_access_token", SIGNALS_DEV_APP_ID, None)
+ assert allowed is expected_allowed
diff --git a/services/mcp/src/lib/event-source.ts b/services/mcp/src/lib/event-source.ts
index 06bc81b24154..a77c36606760 100644
--- a/services/mcp/src/lib/event-source.ts
+++ b/services/mcp/src/lib/event-source.ts
@@ -15,6 +15,7 @@ export const EVENT_SOURCE = {
SLACK: 'slack',
POSTHOG_AI: 'posthog_ai',
POSTHOG_CODE: 'posthog_code',
+ SELF_DRIVING: 'self_driving',
} as const
export type EventSource = (typeof EVENT_SOURCE)[keyof typeof EVENT_SOURCE]
@@ -27,16 +28,23 @@ const WIZARD_USER_AGENT_FRAGMENT = 'posthog/wizard'
// itself one. See INTERNAL_SCOPES in `posthog/temporal/oauth.py`.
const INTERNAL_RUN_SCOPE = 'internal_run:read'
-// The OAuth applications PostHog controls, mirroring POSTHOG_DESKTOP_OAUTH_CLIENT_IDS and
-// POSTHOG_AI_OAUTH_APP_CLIENT_IDS in `posthog/temporal/oauth.py`, which owns them. A client id
-// reaches this server through token introspection rather than a header, so unlike
-// `x-posthog-mcp-consumer` the caller cannot set it for itself.
+// The OAuth applications PostHog controls, mirroring POSTHOG_DESKTOP_OAUTH_CLIENT_IDS,
+// POSTHOG_AI_OAUTH_APP_CLIENT_IDS and SIGNALS_OAUTH_APP_CLIENT_IDS in
+// `posthog/temporal/oauth.py`, which owns them. A client id reaches this server through token
+// introspection rather than a header, so unlike `x-posthog-mcp-consumer` the caller cannot set
+// it for itself.
const POSTHOG_AI_OAUTH_CLIENT_IDS = new Set([
'N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu',
'0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi',
'DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1',
])
+const SIGNALS_OAUTH_CLIENT_IDS = new Set([
+ 'jpSRPhGBBbDGpKprit9bgJEuo6oUTa8ULymqf8PE',
+ 'nqZsiFEbu1fCWDK3r8QtSGwKmmANxVIgfZmTXywk',
+ 'xMT3Nejjbi4lUdhJLkzmCVJKFsx0JsHXdU0pIjl8',
+])
+
const FIRST_PARTY_OAUTH_CLIENT_IDS = new Set([
'HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W',
'AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9',
@@ -95,6 +103,12 @@ export function resolveEventSource(input: EventSourceInput): EventSource {
if (input.oauthClientId && POSTHOG_AI_OAUTH_CLIENT_IDS.has(input.oauthClientId)) {
return EVENT_SOURCE.POSTHOG_AI
}
+ // Signals resolves the same way, and has to be settled before the consumer branches: a
+ // Signals run declares the `posthog-code` consumer, so the application it minted under is
+ // the only thing separating it from a coding agent.
+ if (input.oauthClientId && SIGNALS_OAUTH_CLIENT_IDS.has(input.oauthClientId)) {
+ return EVENT_SOURCE.SELF_DRIVING
+ }
// Matches Django: the outer caller's user-agent wins over anything the MCP layer says.
if (input.clientUserAgent?.includes(WIZARD_USER_AGENT_FRAGMENT)) {
return EVENT_SOURCE.WIZARD
diff --git a/services/mcp/tests/event-source.test.ts b/services/mcp/tests/event-source.test.ts
index 7285d34f2d53..4c7820271ff0 100644
--- a/services/mcp/tests/event-source.test.ts
+++ b/services/mcp/tests/event-source.test.ts
@@ -5,7 +5,7 @@ import { EVENT_SOURCE, resolveEventSource } from '@/lib/event-source'
// Every surface this server is allowed to stamp. `test_mcp_server_only_emits_sources_this_enum_knows`
// in `posthog/test/test_event_usage.py` holds the same list against Django's EventSource, so adding
// one here without adding it there fails on that side.
-const SURFACES_THE_API_KNOWS = ['mcp', 'cli', 'wizard', 'slack', 'posthog_ai', 'posthog_code']
+const SURFACES_THE_API_KNOWS = ['mcp', 'cli', 'wizard', 'slack', 'posthog_ai', 'posthog_code', 'self_driving']
const SANDBOX_SCOPES = ['insight:read', 'internal_run:read']
const CONSENTED_SCOPES = ['insight:read']
@@ -13,6 +13,7 @@ const CONSENTED_SCOPES = ['insight:read']
// Mirrors ARRAY_APP_CLIENT_ID_DEV and POSTHOG_AI_APP_CLIENT_ID_DEV in `posthog/temporal/oauth.py`.
const ARRAY_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ'
const POSTHOG_AI_CLIENT_ID = 'DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1'
+const SIGNALS_CLIENT_ID = 'xMT3Nejjbi4lUdhJLkzmCVJKFsx0JsHXdU0pIjl8'
describe('resolveEventSource', () => {
it.each([
@@ -54,6 +55,13 @@ describe('resolveEventSource', () => {
{ mcpConsumer: 'cursor', oauthClientId: POSTHOG_AI_CLIENT_ID },
EVENT_SOURCE.POSTHOG_AI,
],
+ [
+ // Every Signals run declares the posthog-code consumer, so this row is what keeps it
+ // from reading as a coding agent once it mints under the Signals application.
+ 'a Signals run, which declares the posthog-code consumer',
+ { mcpConsumer: 'posthog-code', apiKeyScopes: SANDBOX_SCOPES, oauthClientId: SIGNALS_CLIENT_ID },
+ EVENT_SOURCE.SELF_DRIVING,
+ ],
[
'a third-party application declaring a first-party consumer',
{ mcpConsumer: 'slack', apiKeyScopes: CONSENTED_SCOPES, oauthClientId: 'some-third-party-client-id' },