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): secrets per revision (encrypted_env app→revision) (#64812)

Ben White50b2d9a538ac
diff --git a/products/agent_platform/backend/migrations/0004_agentrevision_encrypted_env.py b/products/agent_platform/backend/migrations/0004_agentrevision_encrypted_env.py
new file mode 100644
index 000000000000..04ab8e9f1e74
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0004_agentrevision_encrypted_env.py
@@ -0,0 +1,31 @@
+# Step 1 of 3: add the new column on the revision.
+#
+# `encrypted_env` is moving from `agent_application` (one shared secret bag for
+# the live revision and every draft) to `agent_revision` so a draft can be
+# previewed with its own secret values without touching the live revision's,
+# and a promote carries the secrets it was tested with.
+#
+# This is split across three migrations so the data copy runs in its own step
+# (the analyzer blocks RunPython combined with schema changes — schema locks
+# during data migrations are how prod outages happen):
+# 0004 add agent_revision.encrypted_env
+# 0005 copy agent_application.encrypted_env onto its non-archived revisions
+# 0006 drop agent_application.encrypted_env
+
+from django.db import migrations
+
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0003_agentapplication_global_slug_unique"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="agentrevision",
+ name="encrypted_env",
+ field=posthog.helpers.encrypted_fields.EncryptedTextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/0005_copy_encrypted_env_to_revisions.py b/products/agent_platform/backend/migrations/0005_copy_encrypted_env_to_revisions.py
new file mode 100644
index 000000000000..b0b7fdb82789
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0005_copy_encrypted_env_to_revisions.py
@@ -0,0 +1,44 @@
+# Step 2 of 3: copy the application's ciphertext verbatim onto its non-archived
+# revisions. Same Fernet key schedule + text format, so a raw column copy is
+# lossless and doesn't depend on the encryption key being importable at migrate
+# time.
+#
+# This runs as one UPDATE inside the default per-migration atomic transaction.
+# At current scale (low hundreds of revisions) row locks held for the duration
+# are not a concern. If `agent_revision` ever grows past ~10k rows, switch to
+# `atomic = False` and a chunked loop (e.g. `UPDATE ... WHERE id IN (SELECT id
+# ... LIMIT 1000 FOR UPDATE SKIP LOCKED)` driven by Python) so the migration
+# doesn't hold a long-running transaction.
+
+from django.db import migrations
+
+
+def copy_env_to_revisions(apps, schema_editor):
+ with schema_editor.connection.cursor() as cursor:
+ cursor.execute(
+ """
+ UPDATE agent_revision r
+ SET encrypted_env = a.encrypted_env
+ FROM agent_application a
+ WHERE r.application_id = a.id
+ AND a.encrypted_env IS NOT NULL
+ AND r.state <> 'archived'
+ """
+ )
+
+
+def noop(apps, schema_editor):
+ # Reverse is a no-op: the application column is still present at this point
+ # (0006 hasn't run yet), so the source of truth is intact and there's
+ # nothing meaningful to clear on the revision side.
+ pass
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0004_agentrevision_encrypted_env"),
+ ]
+
+ operations = [
+ migrations.RunPython(copy_env_to_revisions, noop),
+ ]
diff --git a/products/agent_platform/backend/migrations/0006_remove_agentapplication_encrypted_env.py b/products/agent_platform/backend/migrations/0006_remove_agentapplication_encrypted_env.py
new file mode 100644
index 000000000000..312c9f3cbc01
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0006_remove_agentapplication_encrypted_env.py
@@ -0,0 +1,35 @@
+# Step 3 of 3: remove `encrypted_env` from `agent_application` in Django state
+# only — the column stays in the DB.
+#
+# A bare `RemoveField` would `DROP COLUMN` immediately, which (a) can't be
+# rolled back if the deploy is reverted and (b) breaks any in-flight web/worker
+# process still running the old code. The migration risk analyzer blocks
+# unstaged column drops for that reason.
+#
+# Multi-phase pattern (see safe-django-migrations.md `#dropping-columns`):
+# 1. This migration: drop the field from Django state; column persists.
+# 2. Deploy and let one full deploy cycle pass — old code with the field is
+# retired, every reader has moved to the revision-level column.
+# 3. Follow-up migration: `RunSQL("ALTER TABLE agent_application DROP COLUMN
+# IF EXISTS encrypted_env")` — the analyzer recognizes this as a properly
+# staged drop because of the state removal here.
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0005_copy_encrypted_env_to_revisions"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="agentapplication",
+ name="encrypted_env",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
index aea5f89493e9..f72a31583ed5 100644
--- a/products/agent_platform/backend/migrations/max_migration.txt
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_agentapplication_global_slug_unique
+0006_remove_agentapplication_encrypted_env
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
index d0b1d2540bea..1911e49b95a3 100644
--- a/products/agent_platform/backend/models.py
+++ b/products/agent_platform/backend/models.py
@@ -62,10 +62,6 @@ class AgentApplication(ProductTeamModel, UUIDModel):
slug = models.SlugField(max_length=63)
description = models.TextField(blank=True, default="", db_default="")
- # Encrypted JSON env block. Decrypted at runtime by the worker via
- # `EncryptedFields` (see services/agent-shared/src/runtime/encryption.ts).
- encrypted_env: EncryptedTextField = EncryptedTextField(null=True, blank=True)
-
live_revision = models.ForeignKey(
"AgentRevision",
on_delete=models.SET_NULL,
@@ -130,6 +126,16 @@ class AgentRevision(ProductTeamModel, UUIDModel):
spec = models.JSONField(default=dict)
+ # Encrypted JSON env block — the secret values this revision runs with.
+ # Decrypted at runtime by the worker via `EncryptedFields` (see
+ # services/agent-shared/src/runtime/encryption.ts). Lives on the revision
+ # (not the application) so a draft can be previewed with its own secret
+ # values without touching the live revision's, and a promote carries the
+ # secrets it was tested with. Mutable in place (key rotation must not
+ # require cutting a new revision) and copied forward when a new draft is
+ # forked from a parent. NULL means "no secrets set".
+ encrypted_env: EncryptedTextField = EncryptedTextField(null=True, blank=True)
+
created_by_id = models.BigIntegerField(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())
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index edff9570579b..2bd0446c0aeb 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -116,6 +116,24 @@ def _janitor() -> JanitorClient:
return default_client()
+def _decode_env_map(raw: str | None) -> dict[str, str]:
+ """Decode a decrypted `encrypted_env` JSON blob into a `{KEY: value}` map.
+
+ Tolerates empty / null / corrupt blocks by returning `{}` — the worker
+ treats those as "no env set" too. Secrets live on the revision, so callers
+ pass `revision.encrypted_env` (decrypted by `EncryptedTextField` on read).
+ """
+ if not raw:
+ return {}
+ try:
+ parsed = json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ if not isinstance(parsed, dict):
+ return {}
+ return {str(k): str(v) for k, v in parsed.items()}
+
+
class JanitorUpstreamError(APIException):
"""DRF-friendly wrapper for non-2xx janitor responses. We forward the
status code where it makes sense (404 stays 404, 409 stays 409) and
@@ -507,11 +525,6 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"update",
"partial_update",
"destroy",
- "set_env",
- # env_keys_key handles GET/PUT/DELETE on /env_keys/<KEY>/ — bundled
- # under :write because PUT/DELETE are the load-bearing ops and we
- # don't want the scope to drift between methods.
- "env_keys_key",
"approvals_decide",
# POST `preview_proxy` forwards `run`/`send`/`cancel` — each starts,
# feeds, or kills a draft session, driving the agent's configured
@@ -527,7 +540,6 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"sessions_retrieve",
"session_logs",
"stats",
- "env_keys_list",
# 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;
# the mutating POST sibling (`preview_proxy`) is a write action above.
@@ -560,166 +572,6 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
instance.archived_at = timezone.now()
instance.save(update_fields=["archived", "archived_at", "updated_at"])
- @extend_schema(request=SetEnvRequestSerializer)
- @action(detail=True, methods=["post"], url_path="set_env")
- def set_env(self, request: Request, **kwargs) -> Response:
- """Replace the agent's encrypted env block.
-
- The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
- text gets stored on AgentApplication.encrypted_env; the worker
- decrypts it at session start via the same Fernet schedule (see
- agent-shared/src/runtime/encryption.ts).
- """
- application = self.get_object()
- if application is None:
- raise NotFound("Application not found")
-
- body = SetEnvRequestSerializer(data=request.data)
- body.is_valid(raise_exception=True)
- env_map = body.validated_data["env"]
-
- # EncryptedTextField encrypts on assignment when saved.
- # We serialize the env dict as JSON before encryption so the worker
- # gets a JSON object back out.
- application.encrypted_env = json.dumps(env_map)
- application.save(update_fields=["encrypted_env", "updated_at"])
- return Response({"ok": True})
-
- # ── Per-key env management ───────────────────────────────────────
- # Set-replace via `set_env` is fine for bulk sync (CI pushes the
- # whole env file) but useless for a "set one secret" UI: the caller
- # can't read existing values out, so they'd wipe the rest on every
- # save. The four routes below let the UI (and the concierge agent's
- # client tool) inspect + mutate one key at a time without ever
- # exposing decrypted values across the wire.
-
- @staticmethod
- def _load_env_map(application: AgentApplication) -> dict[str, str]:
- """Decode the encrypted env JSON into a `{KEY: value}` map.
-
- Tolerates empty / null / corrupt blocks by returning `{}` — the
- worker treats those as "no env set" too.
- """
- raw = application.encrypted_env or ""
- if not raw:
- return {}
- try:
- parsed = json.loads(raw)
- except (TypeError, ValueError):
- return {}
- if not isinstance(parsed, dict):
- return {}
- return {str(k): str(v) for k, v in parsed.items()}
-
- _ENV_KEY_NAME = OpenApiParameter(
- "key",
- OpenApiTypes.STR,
- OpenApiParameter.PATH,
- required=True,
- description="The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.",
- )
-
- @extend_schema(
- operation_id="agent_applications_env_keys_list",
- request=None,
- responses=OpenApiResponse(
- response=inline_serializer(
- name="AgentApplicationEnvKeysResponse",
- fields={
- "keys": drf_serializers.ListField(
- child=drf_serializers.CharField(),
- help_text="Names of env variables currently set on the application. Values are never returned.",
- ),
- },
- ),
- ),
- )
- @action(detail=True, methods=["get"], url_path="env_keys")
- def env_keys_list(self, request: Request, **kwargs) -> Response:
- """List the names of secrets currently set on the application.
-
- Returns names only — values stay server-side under
- `EncryptedTextField`. Use this to drive the "set / unset" badge
- next to a declared secret in the editor UI.
- """
- application = self.get_object()
- if application is None:
- raise NotFound("Application not found")
- env_map = self._load_env_map(application)
- # Sort for stable UI ordering; the encrypted JSON has no
- # meaningful order of its own.
- return Response({"keys": sorted(env_map.keys())})
-
- # One inline status serializer reused by all three method schemas so
- # drf-spectacular emits a single named component instead of three
- # near-identical ones.
- _ENV_KEY_STATUS_RESPONSE = OpenApiResponse(
- response=inline_serializer(
- name="AgentApplicationEnvKeyStatus",
- fields={
- "key": drf_serializers.CharField(),
- "is_set": drf_serializers.BooleanField(
- help_text="True if the key is present in the env block. The value itself is never returned.",
- ),
- },
- ),
- )
-
- @extend_schema(
- methods=["GET"],
- operation_id="agent_applications_env_keys_get",
- parameters=[_ENV_KEY_NAME],
- request=None,
- responses=_ENV_KEY_STATUS_RESPONSE,
- )
- @extend_schema(
- methods=["PUT"],
- operation_id="agent_applications_env_keys_set",
- parameters=[_ENV_KEY_NAME],
- request=SetEnvKeyRequestSerializer,
- responses=_ENV_KEY_STATUS_RESPONSE,
- )
- @extend_schema(
- methods=["DELETE"],
- operation_id="agent_applications_env_keys_clear",
- parameters=[_ENV_KEY_NAME],
- request=None,
- responses=_ENV_KEY_STATUS_RESPONSE,
- )
- @action(detail=True, methods=["get", "put", "delete"], url_path="env_keys/(?P<key>[^/.]+)")
- def env_keys_key(self, request: Request, key: str, **kwargs) -> Response:
- """GET / PUT / DELETE one secret by name.
-
- - `GET` → `{ key, is_set }` (never returns the value).
- - `PUT` → upserts `{ value }` into the env block.
- - `DELETE` → removes the key. No-op when it wasn't set.
-
- Per-method scope: GET is treated as a write action so the
- single action name maps to one consistent scope; reading whether
- a secret is set is restricted to writers in any case.
- """
- application = self.get_object()
- if application is None:
- raise NotFound("Application not found")
- env_map = self._load_env_map(application)
-
- if request.method == "GET":
- return Response({"key": key, "is_set": key in env_map})
-
- if request.method == "DELETE":
- env_map.pop(key, None)
- application.encrypted_env = json.dumps(env_map)
- application.save(update_fields=["encrypted_env", "updated_at"])
- return Response({"key": key, "is_set": False})
-
- # PUT
- body = SetEnvKeyRequestSerializer(data=request.data)
- body.is_valid(raise_exception=True)
- env_map[key] = body.validated_data["value"]
- application.encrypted_env = json.dumps(env_map)
- application.save(update_fields=["encrypted_env", "updated_at"])
- return Response({"key": key, "is_set": True})
-
# Ingress trigger paths the preview-proxy is allowed to forward to. Keeping
# this an allowlist (vs an arbitrary passthrough) gives us a single place
# to audit what's reachable through the authoring-side trust boundary.
@@ -1496,21 +1348,20 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
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 an
- # OAuth bearer carrying the dedicated `agent_approvals:write` scope —
- # the scope is intentionally separate from `agents:write` so a generic
- # agent token cannot decide its own approval, and is hidden from the
- # personal-API-key flow so only OAuth clients (e.g. PostHog Code) that
- # put a human in the loop at decide time can request it via consent.
+ # 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.
authenticator = request.successful_authenticator
is_session = isinstance(authenticator, SessionAuthentication)
- is_oauth_with_decide_scope = isinstance(authenticator, OAuthAccessTokenAuthentication) and (
- "agent_approvals:write" in (getattr(authenticator.access_token, "scope", "") or "").split()
+ 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_oauth_with_decide_scope
+ and not is_first_party_oauth
):
raise NotFound("Approval not found")
try:
@@ -1581,6 +1432,11 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"put_tool",
"delete_tool",
"cron_fire",
+ "set_env",
+ # env_keys_key handles GET/PUT/DELETE on /env_keys/<KEY>/ — bundled
+ # under :write because PUT/DELETE are the load-bearing ops and we
+ # don't want the scope to drift between methods.
+ "env_keys_key",
]
scope_object_read_actions = [
"list",
@@ -1590,6 +1446,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"get_bundle",
"validate",
"system_prompt",
+ "env_keys_list",
]
serializer_class = AgentRevisionSerializer
queryset = AgentRevision.all_teams.all()
@@ -1673,10 +1530,12 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# Trigger types declare the secrets they need via
# `TRIGGER_REQUIRED_SECRETS` (see spec_schema.py). Each required key
- # must be set in `application.encrypted_env` before promote, otherwise
- # the ingress would 500 on the first inbound webhook for the trigger.
- # Per-key gate, not per-trigger — multiple triggers can share a key.
- env_map = AgentApplicationViewSet._load_env_map(application)
+ # must be set in this revision's `encrypted_env` before promote,
+ # otherwise the ingress would 500 on the first inbound webhook for the
+ # trigger. Per-key gate, not per-trigger — multiple triggers can share
+ # a key. Secrets are per-revision, so the gate reads the revision being
+ # promoted (not the application).
+ env_map = _decode_env_map(revision.encrypted_env)
missing = missing_required_secrets(revision.spec or {}, env_map)
if missing:
details = ", ".join(f"{m['key']} (for {m['trigger']} trigger)" for m in missing)
@@ -1727,6 +1586,140 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
application.save(update_fields=["live_revision", "updated_at"])
return Response({"ok": True, "state": "archived"})
+ # ── Per-revision env / secrets ──────────────────────────────────────────
+ # Secrets live on the revision (each revision runs against its own
+ # `encrypted_env`). Set-replace via `set_env` is fine for bulk sync; the
+ # per-key routes below let the UI inspect + mutate one secret at a time
+ # without ever exposing decrypted values across the wire. Editing is
+ # allowed in ANY state (not just draft) — rotating a leaked/expired key on
+ # a live revision must not require cutting a new one. Spec edits stay
+ # draft-only; secrets are operational, not structural.
+
+ @extend_schema(request=SetEnvRequestSerializer)
+ @action(detail=True, methods=["post"], url_path="set_env")
+ def set_env(self, request: Request, **kwargs) -> Response:
+ """Replace this revision's encrypted env block.
+
+ The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
+ text is stored on `AgentRevision.encrypted_env`; the worker decrypts it
+ at session start via the same Fernet schedule (see
+ agent-shared/src/runtime/encryption.ts).
+ """
+ revision: AgentRevision = self.get_object()
+ body = SetEnvRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ # EncryptedTextField encrypts on assignment when saved. Serialize the
+ # env dict as JSON before encryption so the worker gets a JSON object
+ # back out.
+ revision.encrypted_env = json.dumps(body.validated_data["env"])
+ revision.save(update_fields=["encrypted_env", "updated_at"])
+ return Response({"ok": True})
+
+ _ENV_KEY_NAME = OpenApiParameter(
+ "key",
+ OpenApiTypes.STR,
+ OpenApiParameter.PATH,
+ required=True,
+ description="The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.",
+ )
+
+ @extend_schema(
+ operation_id="agent_revisions_env_keys_list",
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionEnvKeysResponse",
+ fields={
+ "keys": drf_serializers.ListField(
+ child=drf_serializers.CharField(),
+ help_text="Names of env variables currently set on the revision. Values are never returned.",
+ ),
+ },
+ ),
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="env_keys")
+ def env_keys_list(self, request: Request, **kwargs) -> Response:
+ """List the names of secrets currently set on this revision.
+
+ Returns names only — values stay server-side under
+ `EncryptedTextField`. Use this to drive the "set / unset" badge next to
+ a declared secret in the editor UI.
+ """
+ revision: AgentRevision = self.get_object()
+ env_map = _decode_env_map(revision.encrypted_env)
+ # Sort for stable UI ordering; the encrypted JSON has no meaningful
+ # order of its own.
+ return Response({"keys": sorted(env_map.keys())})
+
+ # One inline status serializer reused by all three method schemas so
+ # drf-spectacular emits a single named component instead of three
+ # near-identical ones.
+ _ENV_KEY_STATUS_RESPONSE = OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionEnvKeyStatus",
+ fields={
+ "key": drf_serializers.CharField(),
+ "is_set": drf_serializers.BooleanField(
+ help_text="True if the key is present in the env block. The value itself is never returned.",
+ ),
+ },
+ ),
+ )
+
+ @extend_schema(
+ methods=["GET"],
+ operation_id="agent_revisions_env_keys_get",
+ parameters=[_ENV_KEY_NAME],
+ request=None,
+ responses=_ENV_KEY_STATUS_RESPONSE,
+ )
+ @extend_schema(
+ methods=["PUT"],
+ operation_id="agent_revisions_env_keys_set",
+ parameters=[_ENV_KEY_NAME],
+ request=SetEnvKeyRequestSerializer,
+ responses=_ENV_KEY_STATUS_RESPONSE,
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ operation_id="agent_revisions_env_keys_clear",
+ parameters=[_ENV_KEY_NAME],
+ request=None,
+ responses=_ENV_KEY_STATUS_RESPONSE,
+ )
+ @action(detail=True, methods=["get", "put", "delete"], url_path="env_keys/(?P<key>[^/.]+)")
+ def env_keys_key(self, request: Request, key: str, **kwargs) -> Response:
+ """GET / PUT / DELETE one secret by name on this revision.
+
+ - `GET` → `{ key, is_set }` (never returns the value).
+ - `PUT` → upserts `{ value }` into the env block.
+ - `DELETE` → removes the key. No-op when it wasn't set.
+
+ Per-method scope: GET is treated as a write action so the single action
+ name maps to one consistent scope; reading whether a secret is set is
+ restricted to writers in any case.
+ """
+ revision: AgentRevision = self.get_object()
+ env_map = _decode_env_map(revision.encrypted_env)
+
+ if request.method == "GET":
+ return Response({"key": key, "is_set": key in env_map})
+
+ if request.method == "DELETE":
+ env_map.pop(key, None)
+ revision.encrypted_env = json.dumps(env_map)
+ revision.save(update_fields=["encrypted_env", "updated_at"])
+ return Response({"key": key, "is_set": False})
+
+ # PUT
+ body = SetEnvKeyRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ env_map[key] = body.validated_data["value"]
+ revision.encrypted_env = json.dumps(env_map)
+ revision.save(update_fields=["encrypted_env", "updated_at"])
+ return Response({"key": key, "is_set": True})
+
# ── Bundle proxy actions ───────────────────────────────────────────────
def _call(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
@@ -1897,22 +1890,14 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Pre-flight checks before freeze + promote: entrypoint file exists,
every native tool id is registered, every custom tool has its
compiled.js + schema.json, every skill path exists, every declared
- secret has a value set in the application's env block. Returns
+ secret has a value set in this revision's env block. Returns
`{ ok, errors: [...] }`. Works on any revision state."""
revision: AgentRevision = self.get_object()
report = self._call(_janitor().validate, str(revision.id))
errors = list(report.get("errors", []))
- application = revision.application
- decrypted = application.encrypted_env or ""
- available_keys: set[str] = set()
- if decrypted:
- try:
- env_map = json.loads(decrypted)
- if isinstance(env_map, dict):
- available_keys = {str(k) for k in env_map}
- except (ValueError, TypeError):
- pass
+ # Secrets are per-revision now, so check this revision's own env block.
+ available_keys = set(_decode_env_map(revision.encrypted_env).keys())
for i, secret_entry in enumerate(revision.spec.get("secrets") or []):
# spec.secrets[] entries are either bare strings (back-compat,
# resolvable but no host binding) or {name, allowed_hosts}.
@@ -1929,7 +1914,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
errors.append(
{
"code": "missing_secret",
- "message": f'secret "{secret_name}" is not set in the application env',
+ "message": f'secret "{secret_name}" is not set in this revision\'s env',
"pointer": f"spec.secrets[{i}]",
}
)
@@ -2135,6 +2120,11 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
state="draft",
bundle_uri=source.bundle_uri, # same bundle root; janitor scopes by revision_id
spec=source.spec,
+ # Secrets are per-revision: carry the parent's encrypted env forward
+ # so the author isn't forced to re-enter every secret on each new
+ # draft. The ciphertext copies verbatim (same EncryptedFields key
+ # schedule); editing one revision's env never touches another's.
+ encrypted_env=source.encrypted_env,
)
# The janitor clone is the side effect that gives the row meaning —
# without it, the draft is an empty pointer. If it fails, drop the
diff --git a/products/agent_platform/backend/tests/test_approvals_api.py b/products/agent_platform/backend/tests/test_approvals_api.py
index 935b89dfa8f9..731f52da43a4 100644
--- a/products/agent_platform/backend/tests/test_approvals_api.py
+++ b/products/agent_platform/backend/tests/test_approvals_api.py
@@ -191,7 +191,7 @@ class TestApprovalEndpointsAuth(APIBaseTest):
else:
mock_janitor.return_value.decide_approval.assert_not_called()
- def _make_oauth_token(self, *, scope: str, token: str) -> OAuthAccessToken:
+ def _make_oauth_token(self, *, scope: str, token: str, is_first_party: bool = False) -> OAuthAccessToken:
oauth_application = OAuthApplication.objects.create(
name=f"App {token}",
client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
@@ -199,6 +199,7 @@ class TestApprovalEndpointsAuth(APIBaseTest):
redirect_uris="https://example.com/callback",
algorithm="RS256",
skip_authorization=False,
+ is_first_party=is_first_party,
organization=self.organization,
user=self.user,
)
@@ -210,24 +211,21 @@ class TestApprovalEndpointsAuth(APIBaseTest):
scope=scope,
)
- # The dedicated `agent_approvals:write` scope is the only OAuth path past
- # the `allow_agent_approver: False` gate. A token carrying only the broad
- # `agents:write` scope is intentionally insufficient — the gate exists
- # precisely to stop an agent token from approving its own paused tool
- # call. Wildcard `*` is treated the same as `agents:write` here: it
- # satisfies the viewset's scope check but does not grant decide rights.
+ # 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.
@parameterized.expand(
[
- ("with_decide_scope", "agents:write agent_approvals:write", status.HTTP_200_OK, True),
- ("without_decide_scope", "agents:write", status.HTTP_404_NOT_FOUND, False),
- ("wildcard_does_not_grant_decide", "*", status.HTTP_404_NOT_FOUND, False),
+ ("first_party_app", True, status.HTTP_200_OK, True),
+ ("third_party_app", False, status.HTTP_404_NOT_FOUND, False),
]
)
@patch("products.agent_platform.backend.presentation.views._janitor")
- def test_oauth_bearer_can_decide_human_only_approval_with_dedicated_scope(
+ def test_oauth_bearer_can_decide_human_only_approval_only_when_first_party(
self,
label: str,
- scope: str,
+ is_first_party: bool,
expected_status: int,
decide_called: bool,
mock_janitor,
@@ -239,7 +237,9 @@ class TestApprovalEndpointsAuth(APIBaseTest):
"approver_scope": {"allow_agent_approver": False},
}
mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
- access_token = self._make_oauth_token(scope=scope, token=f"pha_test_{label}")
+ # `*` satisfies the viewset scope check for both; the first-party flag is
+ # the only thing that differs.
+ access_token = self._make_oauth_token(scope="*", token=f"pha_test_{label}", is_first_party=is_first_party)
resp = self.client.post(
self.url_decide,
{"decision": "approve"},
diff --git a/products/agent_platform/backend/tests/test_env_keys.py b/products/agent_platform/backend/tests/test_env_keys.py
index 7c72e1bfe388..9cd738f215a8 100644
--- a/products/agent_platform/backend/tests/test_env_keys.py
+++ b/products/agent_platform/backend/tests/test_env_keys.py
@@ -1,21 +1,24 @@
"""
-Tests for the per-key env management endpoints on AgentApplicationViewSet.
+Tests for the per-key env management endpoints on AgentRevisionViewSet.
-Covers list / status / set / clear without ever returning decrypted
-values across the wire, and verifies that merging behaviour preserves
-unrelated keys.
+Secrets live on the revision (each revision runs against its own
+`encrypted_env`), so these endpoints are nested under a revision. Covers list /
+status / set / clear without ever returning decrypted values across the wire,
+verifies merges preserve unrelated keys, and that editing one revision's env
+never touches another's.
"""
from __future__ import annotations
import json
+from typing import Any
from posthog.test.base import APIBaseTest
-from ..models import AgentApplication
+from ..models import AgentApplication, AgentRevision
-class TestAgentApplicationEnvKeys(APIBaseTest):
+class TestAgentRevisionEnvKeys(APIBaseTest):
databases = {
"default",
"persons_db_writer",
@@ -24,24 +27,40 @@ class TestAgentApplicationEnvKeys(APIBaseTest):
"agent_platform_db_reader",
}
- def _app(self) -> AgentApplication:
- app = AgentApplication.all_teams.create(
+ def _app(self, slug: str = "secrets-agent") -> AgentApplication:
+ return AgentApplication.all_teams.create(
team_id=self.team.id,
- slug="secrets-agent",
+ slug=slug,
name="Secrets agent",
description="",
)
+
+ def _revision(self, app: AgentApplication, env: dict[str, Any] | None = None) -> AgentRevision:
+ rev = AgentRevision.all_teams.create(
+ application=app,
+ team_id=app.team_id,
+ state="draft",
+ bundle_uri=f"local://{app.slug}/v1",
+ spec={"model": "anthropic/claude-sonnet-4-6"},
+ )
+ if env is not None:
+ # EncryptedTextField encrypts on assignment+save.
+ rev.encrypted_env = json.dumps(env)
+ rev.save(update_fields=["encrypted_env"])
+ return rev
+
+ def _seeded(self) -> tuple[AgentApplication, AgentRevision]:
+ app = self._app()
# Seed two existing keys so we can verify merges don't wipe siblings.
- app.encrypted_env = json.dumps({"ANTHROPIC_KEY": "sk-old", "SLACK_TOKEN": "xoxb-old"})
- app.save(update_fields=["encrypted_env"])
- return app
+ rev = self._revision(app, {"ANTHROPIC_KEY": "sk-old", "SLACK_TOKEN": "xoxb-old"})
+ return app, rev
- def _url(self, app: AgentApplication, suffix: str = "") -> str:
- return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/{suffix}"
+ def _url(self, app: AgentApplication, rev: AgentRevision, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/revisions/{rev.id}/{suffix}"
def test_list_returns_keys_sorted_no_values(self) -> None:
- app = self._app()
- res = self.client.get(self._url(app, "env_keys/"))
+ app, rev = self._seeded()
+ res = self.client.get(self._url(app, rev, "env_keys/"))
assert res.status_code == 200, res.content
body = res.json()
assert body == {"keys": ["ANTHROPIC_KEY", "SLACK_TOKEN"]}
@@ -50,79 +69,117 @@ class TestAgentApplicationEnvKeys(APIBaseTest):
assert "xoxb-old" not in res.content.decode()
def test_list_on_unset_env_returns_empty(self) -> None:
- app = AgentApplication.all_teams.create(team_id=self.team.id, slug="fresh-agent", name="Fresh", description="")
- res = self.client.get(self._url(app, "env_keys/"))
+ app = self._app("fresh-agent")
+ rev = self._revision(app)
+ res = self.client.get(self._url(app, rev, "env_keys/"))
assert res.status_code == 200
assert res.json() == {"keys": []}
def test_per_key_get_reports_status_no_value(self) -> None:
- app = self._app()
- res = self.client.get(self._url(app, "env_keys/ANTHROPIC_KEY/"))
+ app, rev = self._seeded()
+ res = self.client.get(self._url(app, rev, "env_keys/ANTHROPIC_KEY/"))
assert res.status_code == 200
assert res.json() == {"key": "ANTHROPIC_KEY", "is_set": True}
- res = self.client.get(self._url(app, "env_keys/UNSET_KEY/"))
+ res = self.client.get(self._url(app, rev, "env_keys/UNSET_KEY/"))
assert res.status_code == 200
assert res.json() == {"key": "UNSET_KEY", "is_set": False}
def test_put_upserts_one_key_and_preserves_siblings(self) -> None:
- app = self._app()
+ app, rev = self._seeded()
res = self.client.put(
- self._url(app, "env_keys/NEW_KEY/"),
+ self._url(app, rev, "env_keys/NEW_KEY/"),
data={"value": "new-secret"},
content_type="application/json",
)
assert res.status_code == 200, res.content
assert res.json() == {"key": "NEW_KEY", "is_set": True}
- app.refresh_from_db()
- stored = json.loads(app.encrypted_env)
+ rev.refresh_from_db()
+ stored = json.loads(rev.encrypted_env)
assert stored == {
"ANTHROPIC_KEY": "sk-old",
"SLACK_TOKEN": "xoxb-old",
"NEW_KEY": "new-secret",
}
- def test_put_rotates_existing_key(self) -> None:
- app = self._app()
+ def test_put_allowed_on_live_revision(self) -> None:
+ """Editing secrets is allowed in ANY state — rotating a key on a live
+ revision must not require cutting a new one (spec edits stay draft-only,
+ secrets are operational)."""
+ app, rev = self._seeded()
+ rev.state = "live"
+ rev.save(update_fields=["state"])
res = self.client.put(
- self._url(app, "env_keys/ANTHROPIC_KEY/"),
+ self._url(app, rev, "env_keys/ANTHROPIC_KEY/"),
data={"value": "sk-rotated"},
content_type="application/json",
)
- assert res.status_code == 200
- app.refresh_from_db()
- stored = json.loads(app.encrypted_env)
- assert stored["ANTHROPIC_KEY"] == "sk-rotated"
- # Siblings untouched.
- assert stored["SLACK_TOKEN"] == "xoxb-old"
+ assert res.status_code == 200, res.content
+ rev.refresh_from_db()
+ # Rotating an existing key must replace just that key — sibling keys
+ # are a separate codepath in the merge (update vs insert) and the
+ # upserts-and-preserves-siblings test only covers the insert case.
+ assert json.loads(rev.encrypted_env) == {
+ "ANTHROPIC_KEY": "sk-rotated",
+ "SLACK_TOKEN": "xoxb-old",
+ }
def test_delete_removes_one_key_and_preserves_siblings(self) -> None:
- app = self._app()
- res = self.client.delete(self._url(app, "env_keys/ANTHROPIC_KEY/"))
+ app, rev = self._seeded()
+ res = self.client.delete(self._url(app, rev, "env_keys/ANTHROPIC_KEY/"))
assert res.status_code == 200
assert res.json() == {"key": "ANTHROPIC_KEY", "is_set": False}
- app.refresh_from_db()
- stored = json.loads(app.encrypted_env)
- assert stored == {"SLACK_TOKEN": "xoxb-old"}
+ rev.refresh_from_db()
+ assert json.loads(rev.encrypted_env) == {"SLACK_TOKEN": "xoxb-old"}
def test_delete_unset_key_is_idempotent(self) -> None:
- app = self._app()
- res = self.client.delete(self._url(app, "env_keys/NEVER_SET/"))
+ """`pop(key, None)` is a no-op when the key isn't there — DELETE on a
+ never-set key still returns the standard `{is_set: False}` shape and
+ leaves every other key untouched."""
+ app, rev = self._seeded()
+ res = self.client.delete(self._url(app, rev, "env_keys/NEVER_SET/"))
assert res.status_code == 200
assert res.json() == {"key": "NEVER_SET", "is_set": False}
- app.refresh_from_db()
- # Original siblings untouched.
- assert json.loads(app.encrypted_env) == {
+
+ rev.refresh_from_db()
+ assert json.loads(rev.encrypted_env) == {
"ANTHROPIC_KEY": "sk-old",
"SLACK_TOKEN": "xoxb-old",
}
- def test_put_rejects_when_value_missing(self) -> None:
+ def test_editing_one_revision_does_not_touch_another(self) -> None:
app = self._app()
+ rev_a = self._revision(app, {"SHARED": "a-value"})
+ rev_b = self._revision(app, {"SHARED": "b-value"})
res = self.client.put(
- self._url(app, "env_keys/X/"),
+ self._url(app, rev_a, "env_keys/SHARED/"),
+ data={"value": "a-rotated"},
+ content_type="application/json",
+ )
+ assert res.status_code == 200
+ rev_a.refresh_from_db()
+ rev_b.refresh_from_db()
+ assert json.loads(rev_a.encrypted_env)["SHARED"] == "a-rotated"
+ # The sibling revision is untouched — secrets are per-revision.
+ assert json.loads(rev_b.encrypted_env)["SHARED"] == "b-value"
+
+ def test_set_env_replaces_whole_block(self) -> None:
+ app, rev = self._seeded()
+ res = self.client.post(
+ self._url(app, rev, "set_env/"),
+ data={"env": {"ONLY_KEY": "only-value"}},
+ content_type="application/json",
+ )
+ assert res.status_code == 200, res.content
+ rev.refresh_from_db()
+ assert json.loads(rev.encrypted_env) == {"ONLY_KEY": "only-value"}
+
+ def test_put_rejects_when_value_missing(self) -> None:
+ app, rev = self._seeded()
+ res = self.client.put(
+ self._url(app, rev, "env_keys/X/"),
data={},
content_type="application/json",
)
@@ -131,22 +188,23 @@ class TestAgentApplicationEnvKeys(APIBaseTest):
def test_put_allows_blank_value(self) -> None:
"""Blank values are valid — some integrations use empty strings as
an explicit "clear, but keep the key registered" marker."""
- app = self._app()
+ app, rev = self._seeded()
res = self.client.put(
- self._url(app, "env_keys/BLANK/"),
+ self._url(app, rev, "env_keys/BLANK/"),
data={"value": ""},
content_type="application/json",
)
assert res.status_code == 200
- app.refresh_from_db()
- assert json.loads(app.encrypted_env)["BLANK"] == ""
+ rev.refresh_from_db()
+ assert json.loads(rev.encrypted_env)["BLANK"] == ""
def test_list_recovers_from_corrupt_env_block(self) -> None:
- app = AgentApplication.all_teams.create(team_id=self.team.id, slug="corrupt", name="Corrupt", description="")
+ app = self._app("corrupt")
+ rev = self._revision(app)
# Simulate a corrupt env block — historic bug or manual tampering.
- app.encrypted_env = "not json"
- app.save(update_fields=["encrypted_env"])
+ rev.encrypted_env = "not json"
+ rev.save(update_fields=["encrypted_env"])
- res = self.client.get(self._url(app, "env_keys/"))
+ res = self.client.get(self._url(app, rev, "env_keys/"))
assert res.status_code == 200
assert res.json() == {"keys": []}
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 86787cbd9cd5..043155423c67 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -1026,6 +1026,40 @@ export interface AgentRevisionCronFireResponseApi {
request_id: string
}
+export interface AgentRevisionEnvKeysResponseApi {
+ /** Names of env variables currently set on the revision. Values are never returned. */
+ keys: string[]
+}
+
+export interface AgentRevisionEnvKeyStatusApi {
+ key: string
+ /** True if the key is present in the env block. The value itself is never returned. */
+ is_set: boolean
+}
+
+/**
+ * Body shape for AgentApplicationViewSet.env_keys_set — single secret upsert.
+ *
+ * The view merges `{KEY: value}` into the existing encrypted env block
+ * without touching other keys, so callers can set or rotate one secret
+ * without needing to read the whole block back.
+ */
+export interface SetEnvKeyRequestApi {
+ value: string
+}
+
+export type SetEnvRequestApiEnv = { [key: string]: string }
+
+/**
+ * Body shape for AgentApplicationViewSet.set_env.
+ *
+ * `env` is a JSON object of string→string. The view encrypts it via the
+ * same Fernet schedule the worker uses to decrypt.
+ */
+export interface SetEnvRequestApi {
+ env: SetEnvRequestApiEnv
+}
+
export interface AgentRevisionSlackManifestResponseApi {
revision_id: string
/** Slack app manifest (JSON) ready to paste into https://api.slack.com/apps?new_app=1 → 'From an app manifest'. Scopes and event subscriptions are derived from the agent's slack trigger config + tools. */
@@ -1294,28 +1328,6 @@ export interface AgentApprovalsDecideResponseApi {
state: string
}
-export interface AgentApplicationEnvKeysResponseApi {
- /** Names of env variables currently set on the application. Values are never returned. */
- keys: string[]
-}
-
-export interface AgentApplicationEnvKeyStatusApi {
- key: string
- /** True if the key is present in the env block. The value itself is never returned. */
- is_set: boolean
-}
-
-/**
- * Body shape for AgentApplicationViewSet.env_keys_set — single secret upsert.
- *
- * The view merges `{KEY: value}` into the existing encrypted env block
- * without touching other keys, so callers can set or rotate one secret
- * without needing to read the whole block back.
- */
-export interface SetEnvKeyRequestApi {
- value: string
-}
-
/**
* Body forwarded verbatim to the agent ingress for a *preview* invoke of a
* non-live revision. The meaningful shape depends on the `rest` path segment:
@@ -1576,18 +1588,6 @@ export interface AgentApplicationSessionLogsResponseApi {
results: LogEntryApi[]
}
-export type SetEnvRequestApiEnv = { [key: string]: string }
-
-/**
- * Body shape for AgentApplicationViewSet.set_env.
- *
- * `env` is a JSON object of string→string. The view encrypts it via the
- * same Fernet schedule the worker uses to decrypt.
- */
-export interface SetEnvRequestApi {
- env: SetEnvRequestApiEnv
-}
-
export interface AgentAggregateStatsApi {
/** Sessions currently in a live state (queued / running). */
liveCount: number
diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.ts
index f4ac6be99067..f985712addb8 100644
--- a/products/agent_platform/frontend/generated/api.ts
+++ b/products/agent_platform/frontend/generated/api.ts
@@ -12,8 +12,6 @@ import type {
AgentAggregateStatsApi,
AgentApplicationApi,
AgentApplicationApprovalsListResponseApi,
- AgentApplicationEnvKeyStatusApi,
- AgentApplicationEnvKeysResponseApi,
AgentApplicationPreviewTokenResponseApi,
AgentApplicationSessionLogsResponseApi,
AgentApplicationSessionsListResponseApi,
@@ -48,6 +46,8 @@ import type {
AgentRevisionApi,
AgentRevisionCronFireRequestApi,
AgentRevisionCronFireResponseApi,
+ AgentRevisionEnvKeyStatusApi,
+ AgentRevisionEnvKeysResponseApi,
AgentRevisionSlackManifestResponseApi,
AgentRevisionSystemPromptResponseApi,
AgentRevisionValidateResponseApi,
@@ -868,6 +868,116 @@ export const agentApplicationsRevisionsCronFireCreate = async (
)
}
+export const getAgentRevisionsEnvKeysListUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/env_keys/`
+}
+
+/**
+ * List the names of secrets currently set on this revision.
+ *
+ * Returns names only — values stay server-side under
+ * `EncryptedTextField`. Use this to drive the "set / unset" badge next to
+ * a declared secret in the editor UI.
+ */
+export const agentRevisionsEnvKeysList = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionEnvKeysResponseApi> => {
+ return apiMutator<AgentRevisionEnvKeysResponseApi>(getAgentRevisionsEnvKeysListUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentRevisionsEnvKeysGetUrl = (projectId: string, applicationId: string, id: string, key: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/env_keys/${key}/`
+}
+
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const agentRevisionsEnvKeysGet = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ key: string,
+ options?: RequestInit
+): Promise<AgentRevisionEnvKeyStatusApi> => {
+ return apiMutator<AgentRevisionEnvKeyStatusApi>(getAgentRevisionsEnvKeysGetUrl(projectId, applicationId, id, key), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentRevisionsEnvKeysSetUrl = (projectId: string, applicationId: string, id: string, key: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/env_keys/${key}/`
+}
+
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const agentRevisionsEnvKeysSet = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ key: string,
+ setEnvKeyRequestApi: SetEnvKeyRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionEnvKeyStatusApi> => {
+ return apiMutator<AgentRevisionEnvKeyStatusApi>(getAgentRevisionsEnvKeysSetUrl(projectId, applicationId, id, key), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(setEnvKeyRequestApi),
+ })
+}
+
+export const getAgentRevisionsEnvKeysClearUrl = (projectId: string, applicationId: string, id: string, key: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/env_keys/${key}/`
+}
+
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const agentRevisionsEnvKeysClear = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ key: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentRevisionsEnvKeysClearUrl(projectId, applicationId, id, key), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getAgentApplicationsRevisionsFreezeCreateUrl = (projectId: string, applicationId: string, id: string) => {
return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/freeze/`
}
@@ -943,6 +1053,33 @@ export const agentApplicationsRevisionsPromoteCreate = async (
})
}
+export const getAgentApplicationsRevisionsSetEnvCreateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/set_env/`
+}
+
+/**
+ * Replace this revision's encrypted env block.
+ *
+ * The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
+ * text is stored on `AgentRevision.encrypted_env`; the worker decrypts it
+ * at session start via the same Fernet schedule (see
+ * agent-shared/src/runtime/encryption.ts).
+ */
+export const agentApplicationsRevisionsSetEnvCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ setEnvRequestApi: SetEnvRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsSetEnvCreateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(setEnvRequestApi),
+ })
+}
+
export const getAgentApplicationsRevisionsSkillsUpdateUrl = (
projectId: string,
applicationId: string,
@@ -1265,7 +1402,7 @@ export const getAgentApplicationsRevisionsValidateCreateUrl = (
* Pre-flight checks before freeze + promote: entrypoint file exists,
* every native tool id is registered, every custom tool has its
* compiled.js + schema.json, every skill path exists, every declared
- * secret has a value set in the application's env block. Returns
+ * secret has a value set in this revision's env block. Returns
* `{ ok, errors: [...] }`. Works on any revision state.
*/
export const agentApplicationsRevisionsValidateCreate = async (
@@ -1515,112 +1652,6 @@ export const agentApplicationsApprovalsDecide = async (
)
}
-export const getAgentApplicationsEnvKeysListUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/agent_applications/${id}/env_keys/`
-}
-
-/**
- * List the names of secrets currently set on the application.
- *
- * Returns names only — values stay server-side under
- * `EncryptedTextField`. Use this to drive the "set / unset" badge
- * next to a declared secret in the editor UI.
- */
-export const agentApplicationsEnvKeysList = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<AgentApplicationEnvKeysResponseApi> => {
- return apiMutator<AgentApplicationEnvKeysResponseApi>(getAgentApplicationsEnvKeysListUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getAgentApplicationsEnvKeysGetUrl = (projectId: string, id: string, key: string) => {
- return `/api/projects/${projectId}/agent_applications/${id}/env_keys/${key}/`
-}
-
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const agentApplicationsEnvKeysGet = async (
- projectId: string,
- id: string,
- key: string,
- options?: RequestInit
-): Promise<AgentApplicationEnvKeyStatusApi> => {
- return apiMutator<AgentApplicationEnvKeyStatusApi>(getAgentApplicationsEnvKeysGetUrl(projectId, id, key), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getAgentApplicationsEnvKeysSetUrl = (projectId: string, id: string, key: string) => {
- return `/api/projects/${projectId}/agent_applications/${id}/env_keys/${key}/`
-}
-
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const agentApplicationsEnvKeysSet = async (
- projectId: string,
- id: string,
- key: string,
- setEnvKeyRequestApi: SetEnvKeyRequestApi,
- options?: RequestInit
-): Promise<AgentApplicationEnvKeyStatusApi> => {
- return apiMutator<AgentApplicationEnvKeyStatusApi>(getAgentApplicationsEnvKeysSetUrl(projectId, id, key), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(setEnvKeyRequestApi),
- })
-}
-
-export const getAgentApplicationsEnvKeysClearUrl = (projectId: string, id: string, key: string) => {
- return `/api/projects/${projectId}/agent_applications/${id}/env_keys/${key}/`
-}
-
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const agentApplicationsEnvKeysClear = async (
- projectId: string,
- id: string,
- key: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getAgentApplicationsEnvKeysClearUrl(projectId, id, key), {
- ...options,
- method: 'DELETE',
- })
-}
-
export const getAgentApplicationsPreviewProxyGetUrl = (
projectId: string,
id: string,
@@ -1883,32 +1914,6 @@ export const agentApplicationsSessionLogs = async (
)
}
-export const getAgentApplicationsSetEnvCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/agent_applications/${id}/set_env/`
-}
-
-/**
- * Replace the agent's encrypted env block.
- *
- * The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
- * text gets stored on AgentApplication.encrypted_env; the worker
- * decrypts it at session start via the same Fernet schedule (see
- * agent-shared/src/runtime/encryption.ts).
- */
-export const agentApplicationsSetEnvCreate = async (
- projectId: string,
- id: string,
- setEnvRequestApi: SetEnvRequestApi,
- options?: RequestInit
-): Promise<AgentApplicationApi> => {
- return apiMutator<AgentApplicationApi>(getAgentApplicationsSetEnvCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(setEnvRequestApi),
- })
-}
-
export const getAgentApplicationsStatsUrl = (projectId: string, id: string, params?: AgentApplicationsStatsParams) => {
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 101630dd3428..bfb703b0155e 100644
--- a/products/agent_platform/frontend/generated/api.zod.ts
+++ b/products/agent_platform/frontend/generated/api.zod.ts
@@ -1995,6 +1995,41 @@ export const AgentApplicationsRevisionsCronFireCreateBody = /* @__PURE__ */ zod.
),
})
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const AgentRevisionsEnvKeysSetBody = /* @__PURE__ */ zod
+ .object({
+ value: zod.string(),
+ })
+ .describe(
+ 'Body shape for AgentApplicationViewSet.env_keys_set — single secret upsert.\n\nThe view merges `{KEY: value}` into the existing encrypted env block\nwithout touching other keys, so callers can set or rotate one secret\nwithout needing to read the whole block back.'
+ )
+
+/**
+ * Replace this revision's encrypted env block.
+ *
+ * The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
+ * text is stored on `AgentRevision.encrypted_env`; the worker decrypts it
+ * at session start via the same Fernet schedule (see
+ * agent-shared/src/runtime/encryption.ts).
+ */
+export const AgentApplicationsRevisionsSetEnvCreateBody = /* @__PURE__ */ zod
+ .object({
+ env: zod.record(zod.string(), zod.string()),
+ })
+ .describe(
+ 'Body shape for AgentApplicationViewSet.set_env.\n\n`env` is a JSON object of string→string. The view encrypts it via the\nsame Fernet schedule the worker uses to decrypt.'
+ )
+
/**
* Revisions of an agent. Created in `draft`, promoted through
* `ready → live` once the bundle has been uploaded + frozen.
@@ -2215,25 +2250,6 @@ export const AgentApplicationsApprovalsDecideBody = /* @__PURE__ */ zod
})
.describe('Body shape for POST \/agent_applications\/<id>\/approvals\/<approval_id>\/decide\/.')
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const AgentApplicationsEnvKeysSetBody = /* @__PURE__ */ zod
- .object({
- value: zod.string(),
- })
- .describe(
- 'Body shape for AgentApplicationViewSet.env_keys_set — single secret upsert.\n\nThe view merges `{KEY: value}` into the existing encrypted env block\nwithout touching other keys, so callers can set or rotate one secret\nwithout needing to read the whole block back.'
- )
-
/**
* Authoring-side proxy for invoking a *draft* (or any non-live) revision.
*
@@ -2263,19 +2279,3 @@ export const AgentApplicationsPreviewProxyBody = /* @__PURE__ */ zod
.describe(
'Body forwarded verbatim to the agent ingress for a \*preview\* invoke of a\nnon-live revision. The meaningful shape depends on the `rest` path segment:\n\n- `run` — `{ message }`: the user message that starts a new session.\n- `send` — `{ session_id, message }`: append a message to a running session.\n- `cancel` \/ `listen` — no body.\n\nDocuments `message` \/ `session_id` so the generated MCP tool exposes them;\nany extra keys are still forwarded as-is to ingress.'
)
-
-/**
- * Replace the agent's encrypted env block.
- *
- * The body is `{ "env": { "<KEY>": "<value>", ... } }`. The encrypted
- * text gets stored on AgentApplication.encrypted_env; the worker
- * decrypts it at session start via the same Fernet schedule (see
- * agent-shared/src/runtime/encryption.ts).
- */
-export const AgentApplicationsSetEnvCreateBody = /* @__PURE__ */ zod
- .object({
- env: zod.record(zod.string(), zod.string()),
- })
- .describe(
- 'Body shape for AgentApplicationViewSet.set_env.\n\n`env` is a JSON object of string→string. The view encrypts it via the\nsame Fernet schedule the worker uses to decrypt.'
- )
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/auth.ts b/products/agent_platform/services/agent-ingress/src/enqueue/auth.ts
index b58ab7b279a9..fb72a6c0bd10 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/auth.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/auth.ts
@@ -34,6 +34,7 @@ import { Request } from 'express'
import {
AgentApplication,
+ AgentRevision,
AuthConfig,
AuthMode,
AuthModeType,
@@ -76,7 +77,7 @@ export type VerifyResult = VerifyOk | VerifyFail
*/
export interface AuthVerifier {
readonly modeType: AuthModeType
- verify(req: Request, mode: AuthMode, application: AgentApplication): Promise<VerifyResult>
+ verify(req: Request, mode: AuthMode, application: AgentApplication, revision: AgentRevision): Promise<VerifyResult>
}
export interface AuthProvider {
@@ -148,6 +149,7 @@ export function readBearer(req: Request): string | null {
export async function authorize(
req: Request,
application: AgentApplication,
+ revision: AgentRevision,
authConfig: AuthConfig,
provider: AuthProvider
): Promise<VerifyResult> {
@@ -161,7 +163,7 @@ export async function authorize(
if (!verifier) {
continue
}
- const result = await verifier.verify(req, mode, application)
+ const result = await verifier.verify(req, mode, application, revision)
if (result.ok) {
return result
}
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
index 01961327974a..d3bc1c4c9a36 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
@@ -45,6 +45,7 @@ function makePair(): { app: AgentApplication; rev: AgentRevision } {
bundle_uri: 's3://x/',
bundle_sha256: null,
spec: AgentSpecSchema.parse({ model: 'x' }),
+ encrypted_env: null,
}
return { app, rev }
}
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts
index 294059c7a624..f4c3a6bfe532 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.test.ts
@@ -8,7 +8,7 @@
import type { Request } from 'express'
import { describe, expect, it } from 'vitest'
-import { AgentApplication, AuthModeSchema } from '@posthog/agent-shared'
+import { AgentApplication, AgentRevision, AuthModeSchema } from '@posthog/agent-shared'
import {
buildDefaultVerifiers,
@@ -28,6 +28,22 @@ const APP: AgentApplication = {
description: '',
live_revision_id: null,
archived: false,
+}
+
+// The jwt + shared_secret verifiers resolve their secret from the revision's
+// `encrypted_env`. The fake `secretResolver` below keys only on the secret
+// name, so the env value itself is irrelevant here — but the verifier
+// signature requires a revision.
+const REV: AgentRevision = {
+ id: 'rev-1',
+ application_id: APP.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ created_at: 'now',
+ state: 'live',
+ bundle_uri: 's3://x/',
+ bundle_sha256: null,
+ spec: { model: 'claude-sonnet-4-6' } as unknown as AgentRevision['spec'],
encrypted_env: null,
}
@@ -88,7 +104,8 @@ describe('buildDefaultVerifiers', () => {
const res = await posthogVerifier(introspector, teamOrg).verify(
req({ authorization: 'Bearer good-token' }),
PROJECT_MODE,
- APP
+ APP,
+ REV
)
expect(res.ok).toBe(true)
if (res.ok) {
@@ -103,7 +120,8 @@ describe('buildDefaultVerifiers', () => {
const res = await posthogVerifier(introspector, teamOrg).verify(
req({ authorization: 'Bearer org-peer-token' }),
PROJECT_MODE,
- APP
+ APP,
+ REV
)
expect(res).toMatchObject({ ok: false, status: 403, reason: 'not_in_project' })
})
@@ -114,7 +132,8 @@ describe('buildDefaultVerifiers', () => {
const res = await posthogVerifier(introspector, teamOrg).verify(
req({ authorization: 'Bearer org-peer-token' }),
ORG_MODE,
- APP
+ APP,
+ REV
)
expect(res.ok).toBe(true)
if (res.ok) {
@@ -126,7 +145,8 @@ describe('buildDefaultVerifiers', () => {
const res = await posthogVerifier(introspector, teamOrg).verify(
req({ authorization: 'Bearer outsider-token' }),
ORG_MODE,
- APP
+ APP,
+ REV
)
expect(res).toMatchObject({ ok: false, status: 403, reason: 'not_in_org' })
})
@@ -135,20 +155,20 @@ describe('buildDefaultVerifiers', () => {
['missing bearer → skip', {}, { status: 0 }],
['bad bearer → 401', { authorization: 'Bearer nope' }, { status: 401 }],
])('posthog mode: %s', async (_label, headers, expected) => {
- const res = await posthogVerifier(introspector, teamOrg).verify(req(headers), PROJECT_MODE, APP)
+ const res = await posthogVerifier(introspector, teamOrg).verify(req(headers), PROJECT_MODE, APP, REV)
expect(res).toMatchObject({ ok: false, ...expected })
})
it('shared_secret: matches resolved encrypted_env secret, 401 on mismatch, 500 when unset', async () => {
const v = sharedSecretVerifier(secretResolver)
const mode = { type: 'shared_secret' as const, header: 'X-WH', secret_ref: 'WH' }
- expect(await v.verify(req({ 'x-wh': 's3cret' }), mode, APP)).toMatchObject({ ok: true })
- expect(await v.verify(req({ 'x-wh': 'wrong' }), mode, APP)).toMatchObject({ ok: false, status: 401 })
- expect(await v.verify(req({ 'x-wh': 's3cret' }), { ...mode, secret_ref: 'MISSING' }, APP)).toMatchObject({
+ expect(await v.verify(req({ 'x-wh': 's3cret' }), mode, APP, REV)).toMatchObject({ ok: true })
+ expect(await v.verify(req({ 'x-wh': 'wrong' }), mode, APP, REV)).toMatchObject({ ok: false, status: 401 })
+ expect(await v.verify(req({ 'x-wh': 's3cret' }), { ...mode, secret_ref: 'MISSING' }, APP, REV)).toMatchObject({
ok: false,
status: 500,
})
- expect(await v.verify(req({}), mode, APP)).toMatchObject({ ok: false, status: 0 })
+ expect(await v.verify(req({}), mode, APP, REV)).toMatchObject({ ok: false, status: 0 })
})
it('shared_secret: yields a single team-scoped principal (no per-caller discriminator)', async () => {
@@ -156,7 +176,7 @@ describe('buildDefaultVerifiers', () => {
// is the same principal; per-caller isolation belongs to `jwt`.
const v = sharedSecretVerifier(secretResolver)
const mode = { type: 'shared_secret' as const, header: 'X-WH', secret_ref: 'WH' }
- const res = await v.verify(req({ 'x-wh': 's3cret', 'x-posthog-caller-id': 'alice' }), mode, APP)
+ const res = await v.verify(req({ 'x-wh': 's3cret', 'x-posthog-caller-id': 'alice' }), mode, APP, REV)
expect(res.ok).toBe(true)
if (res.ok) {
expect(res.principal).toEqual({ kind: 'shared_secret', team_id: 7 })
@@ -169,19 +189,20 @@ describe('buildDefaultVerifiers', () => {
await posthogInternalVerifier('internal-xyz').verify(
req({ 'x-posthog-internal': 'internal-xyz' }),
mode,
- APP
+ APP,
+ REV
)
).toMatchObject({
ok: true,
})
expect(
- await posthogInternalVerifier('internal-xyz').verify(req({ 'x-posthog-internal': 'no' }), mode, APP)
+ await posthogInternalVerifier('internal-xyz').verify(req({ 'x-posthog-internal': 'no' }), mode, APP, REV)
).toMatchObject({
ok: false,
status: 403,
})
expect(
- await posthogInternalVerifier('').verify(req({ 'x-posthog-internal': 'anything' }), mode, APP)
+ await posthogInternalVerifier('').verify(req({ 'x-posthog-internal': 'anything' }), mode, APP, REV)
).toMatchObject({
ok: false,
status: 500,
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts
index edf14c7ac669..9c1f131bb5e2 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/verifiers.ts
@@ -14,6 +14,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto'
import {
AgentApplication,
+ AgentRevision,
AuthMode,
CredentialMap,
DirectHttpClient,
@@ -145,7 +146,12 @@ function posthogPrincipalFrom(me: PosthogMeResponse): SessionPrincipal {
export function posthogVerifier(introspector: PosthogIdentityIntrospector, teamOrg: TeamOrgLookup): AuthVerifier {
return {
modeType: 'posthog',
- async verify(req: Request, mode: AuthMode, application: AgentApplication): Promise<VerifyResult> {
+ async verify(
+ req: Request,
+ mode: AuthMode,
+ application: AgentApplication,
+ _revision: AgentRevision
+ ): Promise<VerifyResult> {
if (mode.type !== 'posthog') {
return { ok: false, status: 0, reason: 'skip' }
}
@@ -192,13 +198,18 @@ export function posthogVerifier(introspector: PosthogIdentityIntrospector, teamO
* the claim shape; we just prove possession.
*/
export interface JwtSecretResolver {
- resolve(secretRef: string, application: AgentApplication): Promise<string | null>
+ resolve(secretRef: string, source: { encrypted_env: string | null }): Promise<string | null>
}
export function jwtVerifier(resolver: JwtSecretResolver): AuthVerifier {
return {
modeType: 'jwt',
- async verify(req: Request, mode: AuthMode, application: AgentApplication): Promise<VerifyResult> {
+ async verify(
+ req: Request,
+ mode: AuthMode,
+ _application: AgentApplication,
+ revision: AgentRevision
+ ): Promise<VerifyResult> {
if (mode.type !== 'jwt') {
return { ok: false, status: 0, reason: 'skip' }
}
@@ -211,7 +222,7 @@ export function jwtVerifier(resolver: JwtSecretResolver): AuthVerifier {
return { ok: false, status: 401, reason: 'malformed_jwt' }
}
const [headerB64, payloadB64, sigB64] = segments
- const secret = await resolver.resolve(mode.issuer_secret_ref, application)
+ const secret = await resolver.resolve(mode.issuer_secret_ref, revision)
if (!secret) {
return { ok: false, status: 500, reason: 'jwt_secret_not_set' }
}
@@ -286,7 +297,12 @@ function secretsMatch(provided: string, expected: string): boolean {
export function sharedSecretVerifier(resolver: SecretResolver): AuthVerifier {
return {
modeType: 'shared_secret',
- async verify(req: Request, mode: AuthMode, application: AgentApplication): Promise<VerifyResult> {
+ async verify(
+ req: Request,
+ mode: AuthMode,
+ application: AgentApplication,
+ revision: AgentRevision
+ ): Promise<VerifyResult> {
if (mode.type !== 'shared_secret') {
return { ok: false, status: 0, reason: 'skip' }
}
@@ -294,7 +310,7 @@ export function sharedSecretVerifier(resolver: SecretResolver): AuthVerifier {
if (typeof provided !== 'string') {
return { ok: false, status: 0, reason: 'skip' }
}
- const expected = await resolver.resolve(mode.secret_ref, application)
+ const expected = await resolver.resolve(mode.secret_ref, revision)
if (!expected) {
return { ok: false, status: 500, reason: 'shared_secret_not_set' }
}
@@ -315,7 +331,12 @@ export function sharedSecretVerifier(resolver: SecretResolver): AuthVerifier {
export function posthogInternalVerifier(internalSecret: string): AuthVerifier {
return {
modeType: 'posthog_internal',
- async verify(req: Request, _mode: AuthMode, application: AgentApplication): Promise<VerifyResult> {
+ async verify(
+ req: Request,
+ _mode: AuthMode,
+ application: AgentApplication,
+ _revision: AgentRevision
+ ): Promise<VerifyResult> {
const provided = req.headers['x-posthog-internal']
if (typeof provided !== 'string') {
return { ok: false, status: 0, reason: 'skip' }
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/mount.ts b/products/agent_platform/services/agent-ingress/src/triggers/mount.ts
index fb7d374ad88e..5bf4fbc23766 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/mount.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/mount.ts
@@ -76,10 +76,7 @@ async function runGuardedRoute(
res.status(404).json({ error: `no_${type}_trigger` })
return
}
- const signingSecret = await deps.signingSecretResolver.resolve(
- SLACK_SIGNING_SECRET_KEY,
- resolved.application
- )
+ const signingSecret = await deps.signingSecretResolver.resolve(SLACK_SIGNING_SECRET_KEY, resolved.revision)
if (!signingSecret) {
res.status(500).json({ error: 'signing_secret_unresolved' })
return
@@ -101,7 +98,13 @@ async function runGuardedRoute(
...base,
authConfig,
authorize: () =>
- authorize(req, resolved.application, authConfig, deps.authProvider ?? PUBLIC_ONLY_AUTH_PROVIDER),
+ authorize(
+ req,
+ resolved.application,
+ resolved.revision,
+ authConfig,
+ deps.authProvider ?? PUBLIC_ONLY_AUTH_PROVIDER
+ ),
}
break
}
@@ -114,6 +117,7 @@ async function runGuardedRoute(
const auth = await authorize(
req,
resolved.application,
+ resolved.revision,
authConfig,
deps.authProvider ?? PUBLIC_ONLY_AUTH_PROVIDER
)
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 06d6ecdd3bc1..74aafc6a1d45 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,7 @@ import { createLogger } from '@posthog/agent-shared'
const log = createLogger('slack-trigger')
-import { AgentApplication, SessionPrincipal, SLACK_BOT_TOKEN_KEY } from '@posthog/agent-shared'
+import { AgentApplication, AgentRevision, SessionPrincipal, SLACK_BOT_TOKEN_KEY } from '@posthog/agent-shared'
import { bridgeSlackToPosthogUser } from '../auth/slack-posthog-bridge'
import { applyElevationDecline, applyElevationGrant, authorizeGrant } from '../enqueue/acl'
@@ -170,7 +170,7 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// window. Fails open: a revoked/missing bot token, a slack.com 5xx, an
// `already_reacted`, or a missing channel must NOT break the handler.
if (ackReaction) {
- void postAckReaction(deps, resolved.application, {
+ void postAckReaction(deps, resolved.application, resolved.revision, {
channel: event.channel,
ts: event.ts,
name: ackReaction,
@@ -273,7 +273,7 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// own. The message is parked as an elevation request; tell them
// in-thread why nothing happened. Awaited so the reply lands before we
// ack, but error-swallowed so it can never break the 200 Slack needs.
- await postThreadMessage(deps, resolved.application, {
+ await postThreadMessage(deps, resolved.application, resolved.revision, {
channel: event.channel,
thread_ts: event.thread_ts ?? event.ts,
text:
@@ -421,9 +421,10 @@ interface SlackInteractivityPayload {
async function postAckReaction(
deps: TriggerDeps,
application: AgentApplication,
+ revision: AgentRevision,
opts: { channel: string; ts: string; name: string }
): Promise<void> {
- const token = await deps.signingSecretResolver.resolve(SLACK_BOT_TOKEN_KEY, application)
+ const token = await deps.signingSecretResolver.resolve(SLACK_BOT_TOKEN_KEY, revision)
if (!token) {
log.warn({ slug: application.slug, reaction: opts.name }, 'ack_reaction_no_bot_token')
return
@@ -483,9 +484,10 @@ async function postAckReaction(
async function postThreadMessage(
deps: TriggerDeps,
application: AgentApplication,
+ revision: AgentRevision,
opts: { channel: string; thread_ts: string; text: string }
): Promise<boolean> {
- const token = await deps.signingSecretResolver.resolve(SLACK_BOT_TOKEN_KEY, application)
+ const token = await deps.signingSecretResolver.resolve(SLACK_BOT_TOKEN_KEY, revision)
if (!token || !deps.http) {
log.warn(
{ slug: application.slug, has_token: Boolean(token), has_http: Boolean(deps.http) },
diff --git a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts b/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
index db5b69258c3c..e0749ac32356 100644
--- a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
@@ -52,6 +52,7 @@ function mkRev(spec: Partial<z.input<typeof AgentSpecSchema>> = {}): AgentRevisi
],
...spec,
}),
+ encrypted_env: null,
}
}
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 7c17e871d969..5754bf60c26b 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
@@ -59,6 +59,7 @@ function makeRev(
bundle_uri: 's3://',
bundle_sha256: null,
spec: AgentSpecSchema.parse({ model: 'x', tools: toolRefs, skills, mcps }),
+ encrypted_env: null,
}
}
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 156517dfb161..efe6c17dde5f 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
@@ -444,11 +444,17 @@ function buildToolContext(deps: AgentToolDeps): ToolContext {
log: deps.log,
skillIndex: deps.rev.spec.skills.map((s) => ({ id: s.id, description: s.description, path: s.path })),
readBundleFile: async (path: string): Promise<string | null> => {
- try {
- return await deps.bundle.readText(deps.rev.id, path)
- } catch {
+ // `null` is the "file genuinely absent" signal (load-skill renders
+ // it as "not found in the bundle"). An operational failure —
+ // transient S3 error, auth, network blip — must NOT collapse into
+ // that same null: it looks identical to a missing file, so the
+ // agent reports a confident "not found" and gives up instead of
+ // retrying. `exists` returns false only on a real 404 and rethrows
+ // anything else, so the true cause propagates to the caller.
+ if (!(await deps.bundle.exists(deps.rev.id, path))) {
return null
}
+ return deps.bundle.readText(deps.rev.id, path)
},
memoryStore: deps.memoryStore,
tabularStore: deps.tabularStore,
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 e40c7297ada7..fd43911e3a1c 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
@@ -72,6 +72,7 @@ function makeRev(spec: Partial<Parameters<typeof AgentSpecSchema.parse>[0]> = {}
bundle_uri: 's3://x/',
bundle_sha256: null,
spec: AgentSpecSchema.parse({ model: FAUX_MODEL_ID, ...spec }),
+ encrypted_env: null,
}
}
diff --git a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
index c6ca392e175e..2eadb8527931 100644
--- a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
+++ b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.test.ts
@@ -1,6 +1,6 @@
import { Pool } from 'pg'
-import { EMPTY_USAGE_TOTAL, EncryptedFields, PgRevisionStore } from '@posthog/agent-shared'
+import { AgentSpecSchema, EMPTY_USAGE_TOTAL, EncryptedFields, PgRevisionStore } from '@posthog/agent-shared'
import { reset } from '@posthog/agent-shared/testing'
import { makeEncryptedEnvResolver } from './encrypted-env-resolver'
@@ -50,33 +50,43 @@ describe('makeEncryptedEnvResolver', () => {
encryption = new EncryptedFields(KEY)
})
- async function seedApp(encryptedEnv: string | null): Promise<string> {
+ // Seed an application + a revision carrying `encrypted_env`. Secrets live on
+ // the REVISION now, so the resolver reads them off `session.revision_id`.
+ // Returns the revision id to stamp onto the session under test.
+ async function seedRevision(encryptedEnv: string | null): Promise<string> {
const app = await revisions.createApplication({
team_id: 1,
slug: 'a',
name: 'A',
description: '',
+ })
+ const rev = await revisions.createRevision({
+ application_id: app.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ bundle_uri: 's3://x/',
+ spec: AgentSpecSchema.parse({ model: 'x' }),
encrypted_env: encryptedEnv,
})
- return app.id
+ return rev.id
}
- it('returns {} when no encrypted_env is set on the application', async () => {
- const appId = await seedApp(null)
+ it('returns {} when no encrypted_env is set on the revision', async () => {
+ const revId = await seedRevision(null)
const resolve = makeEncryptedEnvResolver({ revisions, encryption })
- expect(await resolve(freshSession({ application_id: appId }))).toEqual({})
+ expect(await resolve(freshSession({ revision_id: revId }))).toEqual({})
})
- it('returns {} when the application is unknown (revision_store returns null)', async () => {
+ it('returns {} when the revision is unknown (revision_store returns null)', async () => {
const resolve = makeEncryptedEnvResolver({ revisions, encryption })
- expect(await resolve(freshSession({ application_id: '00000000-0000-4000-8000-000000000666' }))).toEqual({})
+ expect(await resolve(freshSession({ revision_id: '00000000-0000-4000-8000-000000000666' }))).toEqual({})
})
- it('decrypts a JSON env block into a string-only map', async () => {
+ it("decrypts the revision's JSON env block into a string-only map", async () => {
const ct = encryption.encrypt(JSON.stringify({ STRIPE_KEY: 'sk_test_x', PORT: 8080 }))
- const appId = await seedApp(ct)
+ const revId = await seedRevision(ct)
const resolve = makeEncryptedEnvResolver({ revisions, encryption })
- expect(await resolve(freshSession({ application_id: appId }))).toEqual({
+ expect(await resolve(freshSession({ revision_id: revId }))).toEqual({
STRIPE_KEY: 'sk_test_x',
PORT: '8080',
})
@@ -85,8 +95,8 @@ describe('makeEncryptedEnvResolver', () => {
it('returns {} (not throw) when decryption fails — keeps the session alive', async () => {
const otherKey = new EncryptedFields('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
const ct = otherKey.encrypt(JSON.stringify({ X: 'y' }))
- const appId = await seedApp(ct)
+ const revId = await seedRevision(ct)
const resolve = makeEncryptedEnvResolver({ revisions, encryption })
- expect(await resolve(freshSession({ application_id: appId }))).toEqual({})
+ expect(await resolve(freshSession({ revision_id: revId }))).toEqual({})
})
})
diff --git a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.ts b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.ts
index b249a1a57a32..f2585397f133 100644
--- a/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.ts
+++ b/products/agent_platform/services/agent-runner/src/resolvers/encrypted-env-resolver.ts
@@ -1,10 +1,16 @@
/**
- * Default `resolveSecrets` impl for production: read the AgentApplication
- * row, decrypt `encrypted_env` (Django's `EncryptedJSONStringField`), return
- * a plaintext `Record<string, string>`. The runner hands that to
+ * Default `resolveSecrets` impl for production: read the AgentRevision row,
+ * decrypt `encrypted_env` (Django's `EncryptedTextField`), return a plaintext
+ * `Record<string, string>`. The runner hands that to
* `SecretBroker.mintSessionMap()` which nonce-wraps the values for the
* sandbox.
*
+ * Secrets live on the revision (not the application), so resolving off
+ * `session.revision_id` gives each session exactly the secrets its revision
+ * was configured with — a draft preview runs against the draft's own secrets,
+ * isolated from the live revision by construction. No per-session override
+ * needed.
+ *
* Pass an `EncryptedFields` constructed from `ENCRYPTION_SALT_KEYS` (same
* env var Django reads from). Missing / empty env → returns `{}` so an
* agent without configured secrets just gets no nonces — no crash.
@@ -19,20 +25,21 @@ export function makeEncryptedEnvResolver(deps: {
encryption: EncryptedFields
}): (session: AgentSession) => Promise<Record<string, string>> {
return async (session) => {
- const app = await deps.revisions.getApplication(session.application_id)
- if (!app?.encrypted_env) {
- return {}
- }
- try {
- return deps.encryption.decryptJsonEnv(app.encrypted_env)
- } catch (err) {
- // Don't crash the session — log and continue with empty secrets.
- // The agent will see undefined values and can react accordingly.
- log.error(
- { err: (err as Error).message, session_id: session.id, application_id: session.application_id },
- 'encrypted_env.decrypt_failed'
- )
- return {}
- }
+ const revision = await deps.revisions.getRevision(session.revision_id)
+ return revision?.encrypted_env ? safeDecrypt(deps.encryption, revision.encrypted_env, session) : {}
+ }
+}
+
+function safeDecrypt(encryption: EncryptedFields, encrypted: string, session: AgentSession): Record<string, string> {
+ try {
+ return encryption.decryptJsonEnv(encrypted)
+ } catch (err) {
+ // Don't crash the session — log and continue with empty secrets. The
+ // agent will see undefined values and can react accordingly.
+ log.error(
+ { err: (err as Error).message, session_id: session.id, revision_id: session.revision_id },
+ 'encrypted_env.decrypt_failed'
+ )
+ return {}
}
}
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 c1657132ec9a..67bebb12427a 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts
@@ -665,12 +665,29 @@ export class Worker {
sLog.warn({ err: (appErr as Error).message }, 'session.failure_notifier_app_load_failed')
return null
})
- if (application) {
+ // The notifier resolves its outbound secret (e.g. Slack bot
+ // token) from the revision's `encrypted_env`, so load the
+ // session's revision here — the pre-runSession `rev` may never
+ // have loaded (a revision_missing failure is one path into this
+ // catch). Best-effort: a missing revision just means no notice.
+ const revision = await this.deps.revisions.getRevision(session.revision_id).catch((revErr) => {
+ sLog.warn({ err: (revErr as Error).message }, 'session.failure_notifier_revision_load_failed')
+ return null
+ })
+ if (application && revision) {
await this.deps.failureNotifier
- .notify({ session, application, reason, category })
+ .notify({ session, application, revision, reason, category })
.catch((notifyErr) =>
sLog.warn({ err: (notifyErr as Error).message }, 'session.failure_notifier_threw')
)
+ } else if (application && !revision) {
+ // Revision didn't load (deleted, or this catch was entered
+ // before the revision ever loaded — a revision_missing
+ // failure is one path in). The notifier resolves its
+ // outbound secret off the revision, so it can't send without
+ // one; log at error so the skipped notice is observable
+ // rather than a silent drop.
+ sLog.error({ revision_id: session.revision_id }, 'session.failure_notifier_skipped_no_revision')
}
}
} finally {
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.test.ts
index 8e3fccfc1a6a..bb44d41b26aa 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.test.ts
@@ -15,6 +15,7 @@ const baseRow = {
state: 'live',
bundle_uri: 's3://x/',
bundle_sha256: null,
+ encrypted_env: null,
}
describe('safeRowToRev', () => {
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.ts
index aa389dc6a284..bb098f87627c 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-revision-store.ts
@@ -25,7 +25,7 @@ export class PgRevisionStore implements RevisionStore {
async getApplication(applicationId: string): Promise<AgentApplication | null> {
const r = await this.pool.query(
- `SELECT id, team_id, slug, name, description, encrypted_env, live_revision_id, archived
+ `SELECT id, team_id, slug, name, description, live_revision_id, archived
FROM agent_application WHERE id = $1`,
[applicationId]
)
@@ -37,7 +37,7 @@ export class PgRevisionStore implements RevisionStore {
// archived = FALSE guarantees at most one row. LIMIT 1 is belt-and-
// braces against a stray duplicate, never a real disambiguation.
const r = await this.pool.query(
- `SELECT id, team_id, slug, name, description, encrypted_env, live_revision_id, archived
+ `SELECT id, team_id, slug, name, description, live_revision_id, archived
FROM agent_application WHERE slug = $1 AND archived = FALSE LIMIT 1`,
[slug]
)
@@ -46,7 +46,7 @@ export class PgRevisionStore implements RevisionStore {
async listApplications(teamId: number): Promise<AgentApplication[]> {
const r = await this.pool.query(
- `SELECT id, team_id, slug, name, description, encrypted_env, live_revision_id, archived
+ `SELECT id, team_id, slug, name, description, live_revision_id, archived
FROM agent_application WHERE team_id = $1 AND archived = FALSE
ORDER BY created_at ASC`,
[teamId]
@@ -57,9 +57,9 @@ export class PgRevisionStore implements RevisionStore {
async createApplication(input: NewApplication): Promise<AgentApplication> {
const id = uuidv4()
await this.pool.query(
- `INSERT INTO agent_application (id, team_id, slug, name, description, encrypted_env)
- VALUES ($1, $2, $3, $4, $5, $6)`,
- [id, input.team_id, input.slug, input.name, input.description, input.encrypted_env ?? null]
+ `INSERT INTO agent_application (id, team_id, slug, name, description)
+ VALUES ($1, $2, $3, $4, $5)`,
+ [id, input.team_id, input.slug, input.name, input.description]
)
const r = await this.getApplication(id)
if (!r) {
@@ -77,7 +77,7 @@ export class PgRevisionStore implements RevisionStore {
async getRevision(revisionId: string): Promise<AgentRevision | null> {
const r = await this.pool.query(
`SELECT id, application_id, parent_revision_id, created_by_id, created_at, state,
- bundle_uri, bundle_sha256, spec
+ bundle_uri, bundle_sha256, spec, encrypted_env
FROM agent_revision WHERE id = $1`,
[revisionId]
)
@@ -90,7 +90,7 @@ export class PgRevisionStore implements RevisionStore {
// resolve another tenant's revision. Returns null on app mismatch.
const r = await this.pool.query(
`SELECT id, application_id, parent_revision_id, created_by_id, created_at, state,
- bundle_uri, bundle_sha256, spec
+ bundle_uri, bundle_sha256, spec, encrypted_env
FROM agent_revision WHERE id = $1 AND application_id = $2`,
[revisionId, applicationId]
)
@@ -100,7 +100,7 @@ export class PgRevisionStore implements RevisionStore {
async getRevisionRaw(revisionId: string): Promise<AgentRevisionRaw | null> {
const r = await this.pool.query(
`SELECT id, application_id, parent_revision_id, created_by_id, created_at, state,
- bundle_uri, bundle_sha256, spec
+ bundle_uri, bundle_sha256, spec, encrypted_env
FROM agent_revision WHERE id = $1`,
[revisionId]
)
@@ -110,7 +110,7 @@ export class PgRevisionStore implements RevisionStore {
async listRevisions(applicationId: string): Promise<AgentRevision[]> {
const r = await this.pool.query(
`SELECT id, application_id, parent_revision_id, created_by_id, created_at, state,
- bundle_uri, bundle_sha256, spec
+ bundle_uri, bundle_sha256, spec, encrypted_env
FROM agent_revision WHERE application_id = $1
ORDER BY created_at ASC`,
[applicationId]
@@ -131,7 +131,7 @@ export class PgRevisionStore implements RevisionStore {
}
const r = await this.pool.query(
`SELECT id, application_id, parent_revision_id, created_by_id, created_at, state,
- bundle_uri, bundle_sha256, spec
+ bundle_uri, bundle_sha256, spec, encrypted_env
FROM agent_revision
WHERE application_id = $1
AND replace(lower(id::text), '-', '') LIKE $2 || '%'`,
@@ -144,8 +144,8 @@ export class PgRevisionStore implements RevisionStore {
const id = uuidv4()
await this.pool.query(
`INSERT INTO agent_revision
- (id, application_id, parent_revision_id, created_by_id, bundle_uri, spec)
- VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,
+ (id, application_id, parent_revision_id, created_by_id, bundle_uri, spec, encrypted_env)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)`,
[
id,
input.application_id,
@@ -153,6 +153,7 @@ export class PgRevisionStore implements RevisionStore {
input.created_by_id,
input.bundle_uri,
JSON.stringify(input.spec),
+ input.encrypted_env ?? null,
]
)
const r = await this.getRevision(id)
@@ -209,7 +210,7 @@ export class PgRevisionStore implements RevisionStore {
// gets hot.
const r = await this.pool.query(
`SELECT r.id, r.application_id, r.parent_revision_id, r.created_by_id,
- r.created_at, r.state, r.bundle_uri, r.bundle_sha256, r.spec
+ r.created_at, r.state, r.bundle_uri, r.bundle_sha256, r.spec, r.encrypted_env
FROM agent_revision r
JOIN agent_application a ON a.live_revision_id = r.id
WHERE a.archived = false`
@@ -230,7 +231,6 @@ function rowToApp(row: {
slug: string
name: string
description: string
- encrypted_env: string | null
live_revision_id: string | null
archived: boolean
}): AgentApplication {
@@ -242,7 +242,6 @@ function rowToApp(row: {
description: row.description,
live_revision_id: row.live_revision_id,
archived: row.archived,
- encrypted_env: row.encrypted_env,
}
}
@@ -256,6 +255,7 @@ type RevisionRow = {
bundle_uri: string
bundle_sha256: string | null
spec: unknown
+ encrypted_env: string | null
}
function rowToRev(row: RevisionRow): AgentRevision {
@@ -276,6 +276,7 @@ function rowToRevRaw(row: RevisionRow): AgentRevisionRaw {
bundle_uri: row.bundle_uri,
bundle_sha256: row.bundle_sha256,
spec: row.spec ?? {},
+ encrypted_env: row.encrypted_env ?? null,
}
}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/revision-store.ts b/products/agent_platform/services/agent-shared/src/persistence/revision-store.ts
index d434d4db127b..52b0a0d00e0d 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/revision-store.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/revision-store.ts
@@ -66,7 +66,6 @@ export interface NewApplication {
slug: string
name: string
description: string
- encrypted_env?: string | null
}
export interface NewRevision {
@@ -75,4 +74,10 @@ export interface NewRevision {
created_by_id: number | null
bundle_uri: string
spec: AgentSpec
+ /**
+ * Optional encrypted env block. Copied forward from a parent revision when
+ * forking a new draft so authors don't re-enter secrets per iteration.
+ * Omit (or null) for a revision with no secrets.
+ */
+ encrypted_env?: string | null
}
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 346753d5927d..507da89cc38f 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
@@ -35,8 +35,8 @@ const AGENT_TABLES = [
// 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, "encrypted_env" text 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);
+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);
diff --git a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
index 663062ef8421..93fe854ac112 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
-import { AgentApplication, AgentSession } from '../spec/spec'
+import { AgentApplication, AgentRevision, AgentSession } from '../spec/spec'
import {
categorize,
FailureNotifier,
@@ -17,6 +17,18 @@ const APP: AgentApplication = {
description: '',
live_revision_id: null,
archived: false,
+}
+
+const REV: AgentRevision = {
+ id: 'rev-1',
+ application_id: APP.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ created_at: new Date().toISOString(),
+ state: 'live',
+ bundle_uri: 's3://x/',
+ bundle_sha256: null,
+ spec: { model: 'claude-sonnet-4-6' } as unknown as AgentRevision['spec'],
encrypted_env: null,
}
@@ -100,7 +112,7 @@ describe('NoopFailureNotifier', () => {
it('returns without doing anything', async () => {
const n = new NoopFailureNotifier()
await expect(
- n.notify({ session: makeSession(null), application: APP, reason: 'x', category: 'unknown' })
+ n.notify({ session: makeSession(null), application: APP, revision: REV, reason: 'x', category: 'unknown' })
).resolves.toBeUndefined()
})
})
@@ -119,6 +131,7 @@ describe('TriggerAwareFailureNotifier', () => {
await n.notify({
session: makeSession({ type: 'slack', channel: 'C1', thread_ts: '123' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -129,7 +142,13 @@ describe('TriggerAwareFailureNotifier', () => {
it('no-ops when trigger_metadata is null', async () => {
const slack = makeSub()
const n = new TriggerAwareFailureNotifier({ slack })
- await n.notify({ session: makeSession(null), application: APP, reason: 'x', category: 'unknown' })
+ await n.notify({
+ session: makeSession(null),
+ application: APP,
+ revision: REV,
+ reason: 'x',
+ category: 'unknown',
+ })
expect(slack.notify).not.toHaveBeenCalled()
})
@@ -139,12 +158,14 @@ describe('TriggerAwareFailureNotifier', () => {
await n.notify({
session: makeSession({ channel: 'C1' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
await n.notify({
session: makeSession({ type: 'discord' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -163,6 +184,7 @@ describe('TriggerAwareFailureNotifier', () => {
n.notify({
session: makeSession({ type: 'slack' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
index 63072072db01..ae43eb1e85ff 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
@@ -20,7 +20,7 @@
* per category. Owner-facing debug stays in log_entries.
*/
-import { AgentApplication, AgentSession } from '../spec/spec'
+import { AgentApplication, AgentRevision, AgentSession } from '../spec/spec'
/**
* Coarse, user-facing buckets the notifier maps every failure to. The bus
@@ -32,6 +32,9 @@ export type FailureCategory = 'transient_infra' | 'configuration' | 'quota_exhau
export interface FailureNotifierInput {
session: AgentSession
application: AgentApplication
+ /** The resolved/hit revision this session ran. Carries the `encrypted_env`
+ * the notifier resolves its outbound secret (e.g. Slack bot token) from. */
+ revision: AgentRevision
/** Raw reason — owner-facing only. Never reaches the notifier's output channel. */
reason: string
category: FailureCategory
diff --git a/products/agent_platform/services/agent-shared/src/runtime/secret-resolver.ts b/products/agent_platform/services/agent-shared/src/runtime/secret-resolver.ts
index 6c464d168582..70d2d979c818 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/secret-resolver.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/secret-resolver.ts
@@ -1,28 +1,27 @@
/**
- * Resolves a named entry from an agent's `AgentApplication.encrypted_env`.
- * Used by the Slack trigger (signing secret, bot token), the shared_secret auth
- * verifier, and the runner's failure notifier — anything needing a per-agent
- * secret decrypted at request time.
+ * Resolves a named entry from a source's `encrypted_env` (an `AgentRevision`).
+ * Used by the Slack trigger (signing secret, bot token), the jwt + shared_secret
+ * auth verifiers, and the runner's failure notifier — anything needing a
+ * per-revision secret decrypted at request time.
*/
-import { AgentApplication } from '../spec/spec'
import { EncryptedFields } from './encryption'
export interface SecretResolver {
- /** Resolve a named entry from the application's `encrypted_env`. Returns null
+ /** Resolve a named entry from the source's `encrypted_env`. Returns null
* on missing env, decrypt failure, or absent / empty value. Never throws. */
- resolve(secretKey: string, application: AgentApplication): Promise<string | null>
+ resolve(secretKey: string, source: { encrypted_env: string | null }): Promise<string | null>
}
export class EncryptedEnvSecretResolver implements SecretResolver {
constructor(private readonly encryption: EncryptedFields) {}
- async resolve(secretKey: string, application: AgentApplication): Promise<string | null> {
- if (!application.encrypted_env) {
+ async resolve(secretKey: string, source: { encrypted_env: string | null }): Promise<string | null> {
+ if (!source.encrypted_env) {
return null
}
try {
- const env = this.encryption.decryptJsonEnv(application.encrypted_env)
+ const env = this.encryption.decryptJsonEnv(source.encrypted_env)
const value = env[secretKey]
return typeof value === 'string' && value.length > 0 ? value : null
} catch {
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
index f550c84eb006..967f482a16f7 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
-import { AgentApplication, AgentSession } from '../spec/spec'
+import { AgentApplication, AgentRevision, AgentSession } from '../spec/spec'
import { HttpFetcher } from './http-client'
import { SecretResolver } from './secret-resolver'
import { SlackFailureNotifier } from './slack-failure-notifier'
@@ -13,6 +13,19 @@ const APP: AgentApplication = {
description: '',
live_revision_id: null,
archived: false,
+}
+
+// The notifier resolves the bot token from the revision's `encrypted_env`.
+const REV: AgentRevision = {
+ id: 'rev-1',
+ application_id: APP.id,
+ parent_revision_id: null,
+ created_by_id: null,
+ created_at: new Date().toISOString(),
+ state: 'live',
+ bundle_uri: 's3://x/',
+ bundle_sha256: null,
+ spec: { model: 'claude-sonnet-4-6' } as unknown as AgentRevision['spec'],
encrypted_env: 'fernet-blob',
}
@@ -60,6 +73,7 @@ describe('SlackFailureNotifier', () => {
await n.notify({
session: makeSession(SLACK_META),
application: APP,
+ revision: REV,
reason: 'docker run failed: Unable to find image',
category: 'transient_infra',
})
@@ -86,6 +100,7 @@ describe('SlackFailureNotifier', () => {
await n.notify({
session: makeSession({ type: 'webhook', url: 'https://example.com' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -101,6 +116,7 @@ describe('SlackFailureNotifier', () => {
await n.notify({
session: makeSession({ type: 'slack', channel: 'C1' }),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -117,6 +133,7 @@ describe('SlackFailureNotifier', () => {
await n.notify({
session: makeSession(SLACK_META),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -138,6 +155,7 @@ describe('SlackFailureNotifier', () => {
n.notify({
session: makeSession(SLACK_META),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -161,6 +179,7 @@ describe('SlackFailureNotifier', () => {
await n.notify({
session: makeSession(SLACK_META),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
@@ -185,6 +204,7 @@ describe('SlackFailureNotifier', () => {
n.notify({
session: makeSession(SLACK_META),
application: APP,
+ revision: REV,
reason: 'x',
category: 'unknown',
})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
index 6f7e9f13f940..5aeb9fc474e0 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
@@ -4,7 +4,7 @@
*
* Reads channel + thread coordinates off `session.trigger_metadata` (stamped
* by the slack trigger at enqueue) and resolves the bot token from the
- * application's `encrypted_env` via the shared `SecretResolver`.
+ * revision's `encrypted_env` via the shared `SecretResolver`.
*
* Failure modes are all silent (logged at warn, returned without throwing) —
* the dispatcher already does an outer catch but the notifier's own contract
@@ -12,7 +12,7 @@
* `session.crashed`.
*/
-import { AgentApplication } from '../spec/spec'
+import { AgentApplication, AgentRevision } from '../spec/spec'
import { SLACK_BOT_TOKEN_KEY } from '../spec/trigger-secrets'
import { FailureNotifier, FailureNotifierInput, userFacingMessage } from './failure-notifier'
import { HttpFetcher } from './http-client'
@@ -36,7 +36,7 @@ export class SlackFailureNotifier implements FailureNotifier {
if (!isSlackTriggerMetadata(meta)) {
return
}
- const token = await this.resolveTokenSafely(input.application, input.session.id)
+ const token = await this.resolveTokenSafely(input.revision, input.application, input.session.id)
if (!token) {
return
}
@@ -67,9 +67,13 @@ export class SlackFailureNotifier implements FailureNotifier {
}
}
- private async resolveTokenSafely(application: AgentApplication, sessionId: string): Promise<string | null> {
+ private async resolveTokenSafely(
+ revision: AgentRevision,
+ application: AgentApplication,
+ sessionId: string
+ ): Promise<string | null> {
try {
- const token = await this.deps.resolver.resolve(SLACK_BOT_TOKEN_KEY, application)
+ const token = await this.deps.resolver.resolve(SLACK_BOT_TOKEN_KEY, revision)
if (!token) {
this.deps.logger?.warn(
{ session_id: sessionId, application_id: application.id },
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 1a1558b926fb..d5b2880dc0fb 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -833,7 +833,6 @@ export interface AgentApplication {
description: string
live_revision_id: string | null
archived: boolean
- encrypted_env: string | null
}
export interface AgentRevision {
@@ -847,6 +846,14 @@ export interface AgentRevision {
bundle_uri: string
bundle_sha256: string | null
spec: AgentSpec
+ /**
+ * Encrypted JSON env block — the secret values this revision runs with.
+ * Decrypted at session start by the runner's secret resolver (same
+ * `EncryptedFields` key schedule as before). Lives on the revision (not
+ * the application) so a draft preview runs against its own secrets,
+ * isolated from the live revision. NULL means "no secrets set".
+ */
+ encrypted_env: string | null
}
/**
diff --git a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts
index 7cd0da1607db..420796121384 100644
--- a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts
@@ -53,7 +53,6 @@ async function newDraft(c: Cluster, slug = 'tba-test'): Promise<string> {
slug: `${slug}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
name: slug,
description: '',
- encrypted_env: null,
})
const spec = AgentSpecSchema.parse(defaultSpec())
const rev = await c.revisions.createRevision({
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 18892990404d..d3a8cfa07ce0 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
@@ -165,6 +165,7 @@ 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. |
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 0e6b1502d6b6..3645cb441c24 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,8 +37,9 @@ will throw away.
## Phase 1 — discover
```text
-@posthog/agent-applications-native-tools-list → built-in tool catalog
-agent-applications-list → existing agents (clone target?)
+@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?)
```
If the user describes something close to an existing agent,
@@ -52,6 +53,10 @@ 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_.
+
Sketch the spec in your head / out loud with the user, BEFORE
calling any create endpoint. Cover:
@@ -70,16 +75,13 @@ calling any create endpoint. Cover:
- **`integrations[]`** — list any team-wide OAuth integrations
(e.g. `"slack"`).
- **`secrets[]`** — list any per-application keys the agent's tools
- read (e.g. `"STRIPE_API_KEY"`). **Don't** list trigger-required
- keys like `SLACK_SIGNING_SECRET` here — those come from the
- platform-wide `TRIGGER_REQUIRED_SECRETS` registry, not the spec.
- See `skills/secrets-and-integrations` → "Trigger-required secrets".
+ read (e.g. `"STRIPE_API_KEY"`). Trigger-required keys are handled
+ separately — see the note after this list.
- **`limits`** — usually defaults are fine. Tighten if the user
needs a hard cost cap.
-- **`auth`** — per-trigger (`triggers[].auth.modes`). For chat/mcp
- triggers, almost always `posthog` or `posthog_internal`. For webhook
- triggers, usually `shared_secret`. `public` is unsafe unless the
- agent is genuinely B2C.
+- **`auth`** — for chat/mcp triggers, almost always `posthog` or
+ `posthog_internal`; webhook usually `shared_secret`. `public` is
+ unsafe unless the agent is genuinely B2C.
- **`reasoning`** — start unset (provider default). Bump to
`medium` if the agent reasons hard; `high` if it does long
triage; rarely `xhigh`.
@@ -87,67 +89,29 @@ calling any create endpoint. Cover:
Show the proposed spec to the user before creating. They will
catch things you missed.
-### Worked example — known-good minimal spec
+### Get the shape from the tool, not from memory
-Copy this and edit; **don't invent shapes** for `auth` / tool refs /
-limits. The validator's error messages are vague ("not valid under
-any of the given schemas") and the field defaults are unintuitive —
-trial-and-error costs 5-10 turns per session. This is what passes
-on the first try.
+`@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).
-```json
-{
- "model": "anthropic/claude-sonnet-4-6",
- "triggers": [
- {
- "type": "chat",
- "config": { "allow_restart": true },
- "auth": { "modes": [{ "type": "posthog", "scopes": ["agent:read"] }] }
- }
- ],
- "tools": [
- { "kind": "native", "id": "@posthog/http-request" },
- { "kind": "custom", "id": "my-tool", "path": "tools/my-tool" }
- ],
- "skills": [{ "id": "my-skill", "path": "skills/my-skill.md", "description": "When to load it." }],
- "secrets": ["MY_API_KEY"],
- "integrations": [],
- "limits": { "max_turns": 40, "max_tool_calls": 80, "max_wall_seconds": 600 },
- "entrypoint": "agent.md"
-}
-```
+Two facts the schema can't give you, because they aren't part of the
+spec:
-Field gotchas the model gets wrong every time:
-
-- **`auth`** is per-trigger: `triggers[].auth` is
- `{"modes": [{"type": "<mode>"}]}`, NOT `{"mode": "..."}`,
- NOT `{"kind": "..."}`, NOT `"none"`. There is no top-level
- `spec.auth`. Valid types: `posthog` (with optional `scopes`),
- `posthog_internal`, `shared_secret` (with `header`), `jwt`
- (with `issuer_secret_ref`), `public` (with
- `acknowledge_public_exposure: true`).
-- **Custom tool refs** require `{kind: "custom", id, path}` — all
- three fields. The `path` points at a directory under the bundle
- containing `source.ts` + `schema.json`. Without `path` the validator
- rejects with the same opaque "not valid under any of the given
- schemas" the model often misreads as a `kind` problem.
-- **Native tool refs** are `{kind: "native", id: "@posthog/foo"}`.
- Never include a `path` here.
- **Trigger-required secrets** (`SLACK_SIGNING_SECRET`,
`SLACK_BOT_TOKEN` for `slack` triggers) are NOT listed in
- `spec.secrets[]`. They come from the platform registry; the
- promote endpoint refuses if they're missing from `encrypted_env`.
-- **`entrypoint`** defaults to `"agent.md"` but the validator
- requires it explicitly on writes. Include it.
-
-For a slack-triggered agent, swap the trigger:
-
-```json
-{ "type": "slack", "config": { "trusted_workspaces": ["T01XXXXXX"] } }
-```
-
-`trusted_workspaces` is required — pass `["*"]` for "any workspace"
-or the literal Slack team id string.
+ `spec.secrets[]`. They come from the platform-wide
+ `TRIGGER_REQUIRED_SECRETS` registry and live in `encrypted_env`;
+ 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.
## Phase 3 — create
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 ef52372f0ade..95f37c7a4de8 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
@@ -67,6 +67,11 @@ 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.
+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.
+
For each edit, surface to the user:
- What file changed
@@ -93,7 +98,8 @@ Common errors:
- `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; fix it.
+ field; if its shape is unclear, call
+ `@posthog/agent-applications-spec-schema` rather than guessing.
## Step 5 — freeze
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 87e3d536ddc9..fb27618c0d4e 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
@@ -49,10 +49,14 @@ the revision row. It declares:
- `secrets[]` — names of encrypted env keys the agent uses
- `limits` — per-session caps (`max_turns`, `max_tool_calls`,
`max_wall_seconds`)
-- `auth` — how a connecting client authenticates (`public`, `pat`,
- `shared_secret`, `posthog_internal`)
+- `auth` — per-trigger (`triggers[].auth`); how a connecting client
+ authenticates
- `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.
+
A **bundle** is the content layer of a revision. A filesystem-like
tree stored in S3, with a manifest in Postgres. Always contains
`agent.md` (the system prompt). Usually contains `skills/*.md` and
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 de0206b80f6f..ebc31c5cf6df 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
@@ -37,6 +37,10 @@
"kind": "native",
"id": "@posthog/agent-applications-native-tools-list"
},
+ {
+ "kind": "native",
+ "id": "@posthog/agent-applications-spec-schema"
+ },
{
"kind": "native",
"id": "@posthog/agent-applications-retrieve"
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 0d9c78527a25..026bd013c182 100644
--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts
+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
@@ -189,6 +189,13 @@ export interface Cluster {
* so teardown wipes both at once.
*/
tabularStore: S3JsonlTabularStore
+ /**
+ * The `EncryptedFields` instance the harness encrypts agent env with (and
+ * the runner's secret resolver decrypts). Exposed so cases can encrypt a
+ * value to stamp onto a revision's `encrypted_env`, or decrypt one to
+ * assert a round-trip.
+ */
+ encryption: EncryptedFields
/** The faux pi-ai Model the runner is wired with. */
model: Model<string>
ingress: Express
@@ -493,6 +500,7 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
credentialBroker,
memoryStore,
tabularStore,
+ encryption,
model,
ingress,
janitor,
@@ -528,7 +536,6 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
slug: input.slug,
name: input.name ?? input.slug,
description: input.description ?? '',
- encrypted_env,
})
const rawSpec: Record<string, unknown> = {
// Default model is "faux/<name>"; tests can override via spec.model.
@@ -567,6 +574,7 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
created_by_id: null,
bundle_uri: `s3://${TEST_S3_BUCKET}/${bundlePrefix}/${app.id}/`,
spec,
+ encrypted_env,
})
for (const [p, content] of Object.entries(input.files ?? {})) {
await bundle.write(rev.id, p, content)
diff --git a/products/agent_platform/services/agent-tools/src/registry.ts b/products/agent_platform/services/agent-tools/src/registry.ts
index c54d7f700773..d55347665306 100644
--- a/products/agent_platform/services/agent-tools/src/registry.ts
+++ b/products/agent_platform/services/agent-tools/src/registry.ts
@@ -54,6 +54,7 @@ import {
} from './tools/posthog-agent-management.v1'
import { posthogListProjectsV1 } from './tools/posthog-projects.v1'
import { posthogQueryV1 } from './tools/posthog-query.v1'
+import { posthogAgentApplicationsSpecSchemaV1 } from './tools/posthog-spec-schema.v1'
import {
slackPostMessageV1,
slackReactV1,
@@ -147,6 +148,7 @@ export const ALL_TOOLS: NativeTool[] = [
posthogAgentApplicationsSessionsRetrieveV1,
posthogAgentApplicationsSessionLogsV1,
nativeToolsCatalogV1,
+ posthogAgentApplicationsSpecSchemaV1,
slackPostMessageV1,
slackUpdateMessageV1,
slackReadChannelV1,
diff --git a/products/agent_platform/services/agent-tools/src/tools/load-skill.test.ts b/products/agent_platform/services/agent-tools/src/tools/load-skill.test.ts
index 7dff6a531f48..7c50eea6c70c 100644
--- a/products/agent_platform/services/agent-tools/src/tools/load-skill.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/load-skill.test.ts
@@ -1,4 +1,12 @@
-import { resolveSkillFile } from './load-skill'
+import type { ToolContext } from '@posthog/agent-shared'
+
+import { loadSkill, resolveSkillFile } from './load-skill'
+
+const SKILL_INDEX = [{ id: 'research', path: 'skills/research/SKILL.md', description: 'x' }]
+
+function ctxWith(readBundleFile: ToolContext['readBundleFile']): ToolContext {
+ return { skillIndex: SKILL_INDEX, readBundleFile, log: () => {} } as unknown as ToolContext
+}
describe('resolveSkillFile', () => {
it('resolves a companion file relative to the skill folder', () => {
@@ -41,3 +49,38 @@ describe('resolveSkillFile', () => {
expect(() => resolveSkillFile('skills/research.md', 'sibling/SKILL.md')).toThrow(/no companion files/)
})
})
+
+describe('loadSkill.run', () => {
+ it('returns the skill body on a successful read', async () => {
+ const res = await loadSkill.run(
+ { id: 'research' },
+ ctxWith(async () => '# body')
+ )
+ expect(res).toEqual({ id: 'research', path: 'skills/research/SKILL.md', body: '# body' })
+ })
+
+ it('reports a genuinely-absent file as "not found in the bundle"', async () => {
+ await expect(
+ loadSkill.run(
+ { id: 'research' },
+ ctxWith(async () => null)
+ )
+ ).rejects.toThrow(/not found in the bundle/)
+ })
+
+ it('reports an operational read failure as retryable, not "not found"', async () => {
+ const ctx = ctxWith(async () => {
+ throw new Error('S3 timeout')
+ })
+ await expect(loadSkill.run({ id: 'research' }, ctx)).rejects.toThrow(/transient error.*S3 timeout.*Retry/s)
+ })
+
+ it('rejects an unknown skill id', async () => {
+ await expect(
+ loadSkill.run(
+ { id: 'nope' },
+ ctxWith(async () => '# body')
+ )
+ ).rejects.toThrow(/unknown skill id/)
+ })
+})
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 77ee3a86305e..bba947174494 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
@@ -78,7 +78,17 @@ export const loadSkill = defineNativeTool({
)
}
const path = args.file ? resolveSkillFile(entry.path, args.file) : entry.path
- const body = await ctx.readBundleFile(path)
+ let body: string | null
+ try {
+ body = await ctx.readBundleFile(path)
+ } catch (err) {
+ // readBundleFile returns null for a genuinely-absent file and only
+ // throws on an operational read failure (transient store error,
+ // auth, network). Surface that as retryable instead of a permanent
+ // "not found" so the model tries again rather than proceeding blind.
+ const reason = err instanceof Error ? err.message : String(err)
+ throw new Error(`load-skill: transient error reading skill "${args.id}" (${reason}). Retry the call.`)
+ }
if (body === null) {
throw new Error(`load-skill: skill "${args.id}" path "${path}" not found in the bundle`)
}
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts
new file mode 100644
index 000000000000..54be17fc2d15
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+
+import type { ToolContext } from '@posthog/agent-shared'
+
+import { getNativeTool } from '../registry'
+import { posthogAgentApplicationsSpecSchemaV1 } from './posthog-spec-schema.v1'
+
+describe('@posthog/agent-applications-spec-schema', () => {
+ it('is registered and resolvable by id', () => {
+ expect(getNativeTool('@posthog/agent-applications-spec-schema')).toBe(posthogAgentApplicationsSpecSchemaV1)
+ })
+
+ it('returns the spec JSON Schema generated from the canonical AgentSpecSchema', async () => {
+ const result = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
+ const schema = result.spec_json_schema as Record<string, unknown>
+ // `model` is the only always-required field; everything else has a default.
+ expect(schema.type).toBe('object')
+ expect((schema.required as string[]) ?? []).toContain('model')
+ expect(schema.properties).toHaveProperty('triggers')
+ expect(schema.properties).toHaveProperty('tools')
+ expect(schema.properties).toHaveProperty('secrets')
+ })
+
+ it('encodes the exact constructs that trip up authoring', async () => {
+ const { spec_json_schema } = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
+ // One serialized blob is the simplest way to assert the union/enum shapes
+ // survive the JSON-Schema conversion (chat-trigger auth, reasoning enum,
+ // the secrets string|object union with required allowed_hosts).
+ const blob = JSON.stringify(spec_json_schema)
+ expect(blob).toContain('acknowledge_public_exposure')
+ expect(blob).toContain('allowed_hosts')
+ expect(blob).toContain('xhigh')
+ expect(blob).toContain('trusted_workspaces')
+ })
+
+ it('returns orientation notes', async () => {
+ const { notes } = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
+ expect(notes.length).toBeGreaterThan(0)
+ expect(notes.every((n) => typeof n === 'string' && n.length > 0)).toBe(true)
+ })
+})
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts
new file mode 100644
index 000000000000..70f44f81671c
--- /dev/null
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts
@@ -0,0 +1,55 @@
+/**
+ * `@posthog/agent-applications-spec-schema` — the authoring concierge's
+ * ground-truth view of the agent `spec` shape, so it stops guessing the
+ * structure from (drift-prone) skill docs or reverse-engineering other
+ * agents' revisions.
+ *
+ * Sibling of `@posthog/agent-applications-native-tools-list`: that tool
+ * discovers valid tool *ids*; this one discovers the spec *shape* those ids
+ * slot into. The JSON Schema is generated at call time from the canonical Zod
+ * `AgentSpecSchema` (the same schema the runner parses and the Django write
+ * path mirrors), so it cannot drift from what the API actually validates.
+ *
+ * Defined as a static, no-arg, no-auth read — like the catalog tool, it
+ * computes its result in-process with no API round-trip.
+ */
+
+import { z } from 'zod'
+
+import { AgentSpecSchema, defineNativeTool, Type } from '@posthog/agent-shared'
+
+/**
+ * Orientation the bare JSON Schema doesn't make obvious. Kept short on purpose
+ * — the schema is authoritative; these only point at the surrounding tools and
+ * the two discriminated unions that are the usual source of validation errors.
+ */
+const SPEC_NOTES: readonly string[] = [
+ 'This is the canonical agent `spec` schema, generated from the source the API validates writes against. Pass a spec matching this shape to `agent-applications-revisions-create` / `-partial-update`.',
+ 'Fields that carry a JSON Schema `default` are optional on write — omit them to take the default. `model` is the only always-required field.',
+ '`triggers[]` is a discriminated union on `type`. `chat`, `mcp`, and `webhook` carry an `auth` block; `slack` and `cron` do not (they authenticate via their own protocol).',
+ '`tools[]` is a discriminated union on `kind` (`native` | `custom` | `client`). For valid `native` tool ids call `@posthog/agent-applications-native-tools-list` — the validator rejects unknown ids.',
+ '`secrets[]` entries are either a bare string (resolvable, no network-egress authority) or `{ name, allowed_hosts }` (required to let `@posthog/http-request` send the secret to those hosts).',
+ 'Skill and custom-tool *content* (SKILL.md bodies, tool source/schema) is uploaded via the bundle file tools (`-skills-update` / `-tools-update`), not inline in the spec.',
+]
+
+// Pure derivation from the canonical schema — compute once at module load.
+const SPEC_JSON_SCHEMA = z.toJSONSchema(AgentSpecSchema) as Record<string, unknown>
+
+export const posthogAgentApplicationsSpecSchemaV1 = defineNativeTool({
+ id: '@posthog/agent-applications-spec-schema',
+ description: [
+ 'Return the JSON Schema for an agent `spec` — every field, type, enum, default, and the',
+ 'discriminated unions for `triggers[]` / `tools[]` / `secrets[]`. Call this BEFORE writing or',
+ 'editing a spec (create / partial-update a revision) instead of guessing the shape or copying',
+ 'another agent. Generated from the canonical schema the API validates against, so it never drifts.',
+ ].join(' '),
+ args: Type.Object({}),
+ returns: Type.Object({
+ spec_json_schema: Type.Record(Type.String(), Type.Unknown()),
+ notes: Type.Array(Type.String()),
+ }),
+ cost_hint: 'cheap',
+ async run() {
+ return { spec_json_schema: SPEC_JSON_SCHEMA, notes: [...SPEC_NOTES] }
+ },
+})
diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yaml
index 19699addbedf..6fcb569751ad 100644
--- a/services/mcp/definitions/agent_platform.yaml
+++ b/services/mcp/definitions/agent_platform.yaml
@@ -49,7 +49,7 @@ tools:
CRUD on this app is blocked until you create a new app with the same slug (the unique constraint is scoped
to `archived=false`).
agent-applications-env-keys-clear:
- operation: agent_applications_env_keys_clear
+ operation: agent_revisions_env_keys_clear
enabled: true
scopes:
- agents:write
@@ -64,7 +64,7 @@ tools:
in-flight sessions keep the value they resolved at start. Playbook: read the `secrets-and-integrations`
playbook via `agent-resolve-resource` for the credential punch-out flow.
agent-applications-env-keys-get:
- operation: agent_applications_env_keys_get
+ operation: agent_revisions_env_keys_get
enabled: true
scopes:
- agents:read
@@ -79,7 +79,7 @@ tools:
landed. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the
credential punch-out flow.
agent-applications-env-keys-list:
- operation: agent_applications_env_keys_list
+ operation: agent_revisions_env_keys_list
enabled: true
scopes:
- agents:read
@@ -95,7 +95,7 @@ tools:
Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential
punch-out flow.
agent-applications-env-keys-set:
- operation: agent_applications_env_keys_set
+ operation: agent_revisions_env_keys_set
enabled: false
scopes:
- agents:write
@@ -398,6 +398,9 @@ tools:
id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` /
`agent-applications-revisions-bundle-retrieve`. Playbook: read the `reading-an-agent` playbook via
`agent-resolve-resource` for how to inspect and summarize an agent.
+ agent-applications-revisions-set-env-create:
+ operation: agent_applications_revisions_set_env_create
+ enabled: false
agent-applications-revisions-skills-destroy:
operation: agent_applications_revisions_skills_destroy
enabled: true
@@ -567,24 +570,6 @@ tools:
`conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full
untrimmed conversation so cost reporting stays accurate. Playbook: read the `debugging-sessions` playbook
via `agent-resolve-resource` for the failure taxonomy and how to read the logs.
- agent-applications-set-env-create:
- operation: agent_applications_set_env_create
- enabled: false
- scopes:
- - agents:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: true
- title: Replace the application's env block (raw values — disabled by default)
- description: >
- Body `{ env: { KEY: "value", … } }` — the whole env is replaced (not patched). **Disabled for the standard
- MCP surface** — the body carries raw secret values, which would land in the agent's tool-call history. Raw
- secret entry goes through the agent console's secret editor instead (deep-link flow; see the
- secrets-and-integrations skill). Values are encrypted at rest with the team's Fernet keys and never leave
- Django; this endpoint stays available on the REST API for the console / CI that already hold the values.
- Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential
- punch-out flow.
agent-applications-stats:
operation: agent_applications_stats
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ef772c8a1805..b7d67ba5c754 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7586,17 +7586,6 @@ export namespace Schemas {
results: AgentApprovalRequest[];
}
- export interface AgentApplicationEnvKeyStatus {
- key: string;
- /** True if the key is present in the env block. The value itself is never returned. */
- is_set: boolean;
- }
-
- export interface AgentApplicationEnvKeysResponse {
- /** Names of env variables currently set on the application. Values are never returned. */
- keys: string[];
- }
-
export interface AgentApplicationPreviewTokenResponse {
/** HS256 JWT bound to (app, rev) with a short TTL. Attach as the `x-agent-preview-token` header (POST/DELETE) or `preview_token` query param (GET, including EventSource) when calling ingress directly. */
token: string;
@@ -8414,6 +8403,17 @@ export namespace Schemas {
request_id: string;
}
+ export interface AgentRevisionEnvKeyStatus {
+ key: string;
+ /** True if the key is present in the env block. The value itself is never returned. */
+ is_set: boolean;
+ }
+
+ export interface AgentRevisionEnvKeysResponse {
+ /** Names of env variables currently set on the revision. Values are never returned. */
+ keys: string[];
+ }
+
export interface AgentRevisionSlackManifestResponse {
revision_id: string;
/** Slack app manifest (JSON) ready to paste into https://api.slack.com/apps?new_app=1 → 'From an app manifest'. Scopes and event subscriptions are derived from the agent's slack trigger config + tools. */
diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.ts
index 43a98cccf31c..c55b1bfa11aa 100644
--- a/services/mcp/src/generated/agent_platform/api.ts
+++ b/services/mcp/src/generated/agent_platform/api.ts
@@ -1578,6 +1578,71 @@ export const AgentApplicationsRevisionsCronFireCreateBody = /* @__PURE__ */ zod.
),
})
+/**
+ * List the names of secrets currently set on this revision.
+ *
+ * Returns names only — values stay server-side under
+ * `EncryptedTextField`. Use this to drive the "set / unset" badge next to
+ * a declared secret in the editor UI.
+ */
+export const AgentRevisionsEnvKeysListParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ id: zod.string().describe('A UUID string identifying this agent revision.'),
+ 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/."
+ ),
+})
+
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const AgentRevisionsEnvKeysGetParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ id: zod.string().describe('A UUID string identifying this agent revision.'),
+ key: zod
+ .string()
+ .describe('The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.'),
+ 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/."
+ ),
+})
+
+/**
+ * GET / PUT / DELETE one secret by name on this revision.
+ *
+ * - `GET` → `{ key, is_set }` (never returns the value).
+ * - `PUT` → upserts `{ value }` into the env block.
+ * - `DELETE` → removes the key. No-op when it wasn't set.
+ *
+ * Per-method scope: GET is treated as a write action so the single action
+ * name maps to one consistent scope; reading whether a secret is set is
+ * restricted to writers in any case.
+ */
+export const AgentRevisionsEnvKeysClearParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ id: zod.string().describe('A UUID string identifying this agent revision.'),
+ key: zod
+ .string()
+ .describe('The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.'),
+ 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/."
+ ),
+})
+
/**
* Freeze the bundle: draft → ready, stamps sha256 on the row.
*
@@ -1894,7 +1959,7 @@ export const AgentApplicationsRevisionsToolsDestroyParams = /* @__PURE__ */ zod.
* Pre-flight checks before freeze + promote: entrypoint file exists,
* every native tool id is registered, every custom tool has its
* compiled.js + schema.json, every skill path exists, every declared
- * secret has a value set in the application's env block. Returns
+ * secret has a value set in this revision's env block. Returns
* `{ ok, errors: [...] }`. Works on any revision state.
*/
export const AgentApplicationsRevisionsValidateCreateParams = /* @__PURE__ */ zod.object({
@@ -2022,68 +2087,6 @@ export const AgentApplicationsDestroyParams = /* @__PURE__ */ zod.object({
),
})
-/**
- * List the names of secrets currently set on the application.
- *
- * Returns names only — values stay server-side under
- * `EncryptedTextField`. Use this to drive the "set / unset" badge
- * next to a declared secret in the editor UI.
- */
-export const AgentApplicationsEnvKeysListParams = /* @__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/."
- ),
-})
-
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const AgentApplicationsEnvKeysGetParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this agent application.'),
- key: zod
- .string()
- .describe('The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.'),
- 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/."
- ),
-})
-
-/**
- * GET / PUT / DELETE one secret by name.
- *
- * - `GET` → `{ key, is_set }` (never returns the value).
- * - `PUT` → upserts `{ value }` into the env block.
- * - `DELETE` → removes the key. No-op when it wasn't set.
- *
- * Per-method scope: GET is treated as a write action so the
- * single action name maps to one consistent scope; reading whether
- * a secret is set is restricted to writers in any case.
- */
-export const AgentApplicationsEnvKeysClearParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this agent application.'),
- key: zod
- .string()
- .describe('The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.'),
- 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/."
- ),
-})
-
/**
* Authoring-side proxy for invoking a *draft* (or any non-live) revision.
*
diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.ts
index 28a32b726ef4..1cda46cc8628 100644
--- a/services/mcp/src/tools/generated/agent_platform.ts
+++ b/services/mcp/src/tools/generated/agent_platform.ts
@@ -5,9 +5,6 @@ import type { Schemas } from '@/api/generated'
import {
AgentApplicationsCreateBody,
AgentApplicationsDestroyParams,
- AgentApplicationsEnvKeysClearParams,
- AgentApplicationsEnvKeysGetParams,
- AgentApplicationsEnvKeysListParams,
AgentApplicationsListQueryParams,
AgentApplicationsPartialUpdateBody,
AgentApplicationsPartialUpdateParams,
@@ -52,6 +49,9 @@ import {
AgentApplicationsSessionsListQueryParams,
AgentApplicationsSessionsRetrieveParams,
AgentApplicationsSessionsRetrieveQueryParams,
+ AgentRevisionsEnvKeysClearParams,
+ AgentRevisionsEnvKeysGetParams,
+ AgentRevisionsEnvKeysListParams,
} from '@/generated/agent_platform/api'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -99,7 +99,7 @@ const agentApplicationsDestroy = (): ToolBase<typeof AgentApplicationsDestroySch
},
})
-const AgentApplicationsEnvKeysClearSchema = AgentApplicationsEnvKeysClearParams.omit({ project_id: true })
+const AgentApplicationsEnvKeysClearSchema = AgentRevisionsEnvKeysClearParams.omit({ project_id: true })
const agentApplicationsEnvKeysClear = (): ToolBase<typeof AgentApplicationsEnvKeysClearSchema, unknown> => ({
name: 'agent-applications-env-keys-clear',
@@ -108,43 +108,43 @@ const agentApplicationsEnvKeysClear = (): ToolBase<typeof AgentApplicationsEnvKe
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<unknown>({
method: 'DELETE',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/env_keys/${encodeURIComponent(String(params.key))}/`,
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/env_keys/${encodeURIComponent(String(params.key))}/`,
})
return result
},
})
-const AgentApplicationsEnvKeysGetSchema = AgentApplicationsEnvKeysGetParams.omit({ project_id: true })
+const AgentApplicationsEnvKeysGetSchema = AgentRevisionsEnvKeysGetParams.omit({ project_id: true })
const agentApplicationsEnvKeysGet = (): ToolBase<
typeof AgentApplicationsEnvKeysGetSchema,
- Schemas.AgentApplicationEnvKeyStatus
+ Schemas.AgentRevisionEnvKeyStatus
> => ({
name: 'agent-applications-env-keys-get',
schema: AgentApplicationsEnvKeysGetSchema,
handler: async (context: Context, params: z.infer<typeof AgentApplicationsEnvKeysGetSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.AgentApplicationEnvKeyStatus>({
+ const result = await context.api.request<Schemas.AgentRevisionEnvKeyStatus>({
method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/env_keys/${encodeURIComponent(String(params.key))}/`,
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/env_keys/${encodeURIComponent(String(params.key))}/`,
})
return result
},
})
-const AgentApplicationsEnvKeysListSchema = AgentApplicationsEnvKeysListParams.omit({ project_id: true })
+const AgentApplicationsEnvKeysListSchema = AgentRevisionsEnvKeysListParams.omit({ project_id: true })
const agentApplicationsEnvKeysList = (): ToolBase<
typeof AgentApplicationsEnvKeysListSchema,
- Schemas.AgentApplicationEnvKeysResponse
+ Schemas.AgentRevisionEnvKeysResponse
> => ({
name: 'agent-applications-env-keys-list',
schema: AgentApplicationsEnvKeysListSchema,
handler: async (context: Context, params: z.infer<typeof AgentApplicationsEnvKeysListSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.AgentApplicationEnvKeysResponse>({
+ const result = await context.api.request<Schemas.AgentRevisionEnvKeysResponse>({
method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/env_keys/`,
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/env_keys/`,
})
return result
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-clear.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-clear.json
index c9d7b369bbb2..0ca8d22c151b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-clear.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-clear.json
@@ -1,8 +1,11 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "application_id": {
+ "type": "string"
+ },
"id": {
- "description": "A UUID string identifying this agent application.",
+ "description": "A UUID string identifying this agent revision.",
"type": "string"
},
"key": {
@@ -10,6 +13,6 @@
"type": "string"
}
},
- "required": ["id", "key"],
+ "required": ["application_id", "id", "key"],
"type": "object"
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-get.json
index c9d7b369bbb2..0ca8d22c151b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-get.json
@@ -1,8 +1,11 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "application_id": {
+ "type": "string"
+ },
"id": {
- "description": "A UUID string identifying this agent application.",
+ "description": "A UUID string identifying this agent revision.",
"type": "string"
},
"key": {
@@ -10,6 +13,6 @@
"type": "string"
}
},
- "required": ["id", "key"],
+ "required": ["application_id", "id", "key"],
"type": "object"
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-list.json
index fc56ff7565a4..ca7afd5be5fd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-list.json
@@ -1,11 +1,14 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "application_id": {
+ "type": "string"
+ },
"id": {
- "description": "A UUID string identifying this agent application.",
+ "description": "A UUID string identifying this agent revision.",
"type": "string"
}
},
- "required": ["id"],
+ "required": ["application_id", "id"],
"type": "object"
}