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(agents): add agent platform Django product (models, API, config) (#62616)

Ben White9c7cf03c62e9
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index a462d1ed980c..3d4ae559159f 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -57,7 +57,14 @@ rules:
AccessControl
|Account
|Action
+ |AgentApplication
|AgentArtifact
+ |AgentRevision
+ |AgentSandboxInstance
+ |AgentSession
+ |AgentSessionCredential
+ |AgentToolApprovalRequest
+ |AgentUser
|Alert
|AlertConfiguration
|Annotation
@@ -305,7 +312,14 @@ rules:
AccessControl
|Account
|Action
+ |AgentApplication
|AgentArtifact
+ |AgentRevision
+ |AgentSandboxInstance
+ |AgentSession
+ |AgentSessionCredential
+ |AgentToolApprovalRequest
+ |AgentUser
|Alert
|AlertConfiguration
|Annotation
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 17c2d988c104..34293a982457 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -170,6 +170,7 @@ export const FEATURE_FLAGS = {
UX_HIDE_PROJECT_NOTICE: 'ux-hide-project-notice', // owner: #team-platform-ux, hides the project notice banner across all scenes
// Feature flags used to control opt-in for different behaviors, should not be removed
+ AGENT_PLATFORM_MCP: 'agent-platform-mcp', // owner: @benwhite #team-agents, gates the agent-platform MCP tool surface (hidden until GA; product DB is dev-only)
AI_TRAINING: 'ai-training', // owner: @nicowaltz #team-replay #ai-research, gates the AI training opt-out UI and API enforcement
AUDIT_LOGS_ACCESS: 'audit-logs-access', // owner: #team-platform-features, used to control access to audit logs
AUTH_FLOW_VARIANT: 'auth-flow-variant', // owner: @fercgomes #team-growth multivariate=legacy,redesign-2026-06-02 — selects the signin/signup experience (login, signup, invited signup); legacy is the existing design
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 4c4508cf1d78..72afaf2e3c1e 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -18,6 +18,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'access_control', objectName: 'Access control', objectPlural: 'access controls' },
{ key: 'account', objectName: 'Account', objectPlural: 'accounts' },
{ key: 'activity_log', objectName: 'Activity log', objectPlural: 'activity logs' },
+ { key: 'agents', objectName: 'Agent', objectPlural: 'agents' },
{ key: 'alert', objectName: 'Alert', objectPlural: 'alerts' },
{ key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },
{ key: 'approvals', objectName: 'Approvals', objectPlural: 'approvals' },
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
index b625cc31b2a6..aeb9abad376b 100644
--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx
@@ -169,6 +169,11 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
scopes = scopes.filter((scope) => scope.key !== 'llm_gateway')
}
+ // Hide agents scope unless the agent platform flag is enabled (hidden until GA)
+ if (!featureFlags[FEATURE_FLAGS.AGENT_PLATFORM_MCP]) {
+ scopes = scopes.filter((scope) => scope.key !== 'agents')
+ }
+
// Hide approvals scope unless the org has the APPROVALS feature
if (!hasAvailableFeature(AvailableFeature.APPROVALS)) {
scopes = scopes.filter((scope) => scope.key !== 'approvals')
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index f3154bf1342e..53a62d94ae0d 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5488,6 +5488,7 @@ export type APIScopeObject =
| 'access_control'
| 'account'
| 'activity_log'
+ | 'agents'
| 'alert'
| 'annotation'
| 'approvals'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5b58a9f01499..192775690c44 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2198,6 +2198,8 @@ importers:
specifier: 'catalog:'
+ products/agent_platform: {}
+
products/ai_observability:
dependencies:
'@posthog/icons':
diff --git a/posthog/scopes.py b/posthog/scopes.py
index ff05db8ef85a..ed1592b4400d 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -19,6 +19,7 @@ APIScopeObject = Literal[
"access_control",
"account",
"activity_log",
+ "agents",
"alert",
"annotation",
"approvals",
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index d8ba1c2f5072..3f30cf3cf3cb 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -22,6 +22,7 @@ from posthog.settings.base_variables import *
from posthog.settings.access import *
from posthog.settings.activity_log import *
+from posthog.settings.agents import *
from posthog.settings.async_migrations import *
from posthog.settings.batch_exports import *
from posthog.settings.celery import *
diff --git a/posthog/settings/agents.py b/posthog/settings/agents.py
new file mode 100644
index 000000000000..bbb7df780af8
--- /dev/null
+++ b/posthog/settings/agents.py
@@ -0,0 +1,37 @@
+from django.core.exceptions import ImproperlyConfigured
+
+from posthog.settings.utils import get_from_env, get_list
+
+# Agent janitor service — Django proxies session list/detail/cancel requests here.
+AGENT_JANITOR_BASE_URL = get_from_env("AGENT_JANITOR_BASE_URL", "http://localhost:3031")
+
+# How agent-ingress addresses agents externally; must match the ingress's own
+# ROUTING_MODE. "domain": slug in the host (<slug><suffix>); "path": slug in the
+# path (<base>/agents/<slug>/...), used in local dev via bin/agent-tunnel.
+AGENT_INGRESS_ROUTING_MODE = get_from_env("AGENT_INGRESS_ROUTING_MODE", "path")
+if AGENT_INGRESS_ROUTING_MODE not in ("domain", "path"):
+ raise ImproperlyConfigured(
+ f"AGENT_INGRESS_ROUTING_MODE must be 'domain' or 'path', got '{AGENT_INGRESS_ROUTING_MODE}'"
+ )
+
+# Domain suffix for "domain" mode (e.g. .agents.us.posthog.com); empty → agent
+# URLs are omitted (not externally reachable).
+AGENT_INGRESS_DOMAIN_SUFFIX = get_from_env("AGENT_INGRESS_DOMAIN_SUFFIX", "")
+
+# Public base URL for agent-ingress in "path" mode (Slack callbacks, webhooks);
+# empty → the slack_events_url field is omitted from API responses.
+AGENT_INGRESS_PUBLIC_URL = get_from_env("AGENT_INGRESS_PUBLIC_URL", "")
+
+# Shared HMAC key for trusted-service JWTs across the agent platform. Empty
+# default fails safe: the janitor client skips the mint and the receiver 401s,
+# surfacing the misconfig instead of signing with a baked-in dev string.
+AGENT_INTERNAL_SIGNING_KEY = get_from_env("AGENT_INTERNAL_SIGNING_KEY", "")
+
+# Teams allowed to set an agent's slug explicitly on create. Everyone else gets
+# a server-minted globally-unique slug (the slug is a single global namespace —
+# see AgentApplication). This is our escape hatch so first-party agents (e.g.
+# the concierge) keep a stable, human-readable slug across environments.
+# Comma-separated team ids; empty (default) → no team may set an explicit slug.
+AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS: set[int] = {
+ int(team_id) for team_id in get_list(get_from_env("AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS", ""))
+}
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index d8b9b446892d..9941ea0e4bbf 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -190,6 +190,21 @@ product_routes = load_product_db_routes(Path(__file__).resolve().parents[2])
configured_product_databases: set[str] = set()
PRODUCT_DB_WRITER_URLS: dict[str, str] = {}
+
+# Per-product SSL for the migration DIRECT_URL only. Runtime writer/reader route
+# through PgBouncer (in-cluster, plaintext, no SSL); only the direct migration
+# connection reaches Aurora, whose pg_hba requires SSL (hostssl). dj_database_url
+# sets only connect_timeout, so set sslmode here. Scoped per product (e.g.
+# PRODUCT_DB_AGENT_PLATFORM_SSL_MODE); unset for local dev/test (plain Postgres).
+def _apply_product_db_ssl_options(db: str, options: dict) -> None:
+ ssl_mode = os.getenv(f"PRODUCT_DB_{db.upper()}_SSL_MODE")
+ ssl_root_cert = os.getenv(f"PRODUCT_DB_{db.upper()}_SSL_ROOT_CERT")
+ if ssl_mode:
+ options["sslmode"] = ssl_mode
+ if ssl_root_cert:
+ options["sslrootcert"] = ssl_root_cert
+
+
# Fail-fast circuit breaker for product databases. When a product DB is
# unreachable, the custom backend raises immediately on connect instead of
# blocking the worker on `connect_timeout`, so one product's outage can't
@@ -273,6 +288,7 @@ for route in product_routes:
direct_alias = f"{db}_db_direct"
DATABASES[direct_alias] = dict(dj_database_url.parse(direct_url, conn_max_age=0))
DATABASES[direct_alias].setdefault("OPTIONS", {})["connect_timeout"] = 10
+ _apply_product_db_ssl_options(db, DATABASES[direct_alias]["OPTIONS"])
if DISABLE_SERVER_SIDE_CURSORS:
DATABASES[direct_alias]["DISABLE_SERVER_SIDE_CURSORS"] = True
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 1e17bada83dd..9c29ac1daf48 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -46,3 +46,8 @@ VIDEO_SEGMENT_CLUSTERING_S3_BUCKET = os.getenv("VIDEO_SEGMENT_CLUSTERING_S3_BUCK
# service consumes. Falls back to the general bucket if not set so dev /
# self-hosted continue to work without extra configuration.
BILLING_USAGE_REPORTS_S3_BUCKET = os.getenv("BILLING_USAGE_REPORTS_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+
+# Agent platform bundle bucket — stores `ass deploy` bundles. Lifecycle should
+# expire non-`ready` bundles after a grace period (handled by infra). Falls
+# back to the general bucket in dev / self-hosted.
+AGENT_BUNDLES_S3_BUCKET = os.getenv("AGENT_BUNDLES_S3_BUCKET") or OBJECT_STORAGE_BUCKET
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 7b11fc6e6004..b8b52c6f9b7b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -77,6 +77,7 @@ PRODUCTS_APPS = [
"products.access_control.backend.apps.AccessControlConfig",
"products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",
"products.business_knowledge.backend.apps.BusinessKnowledgeConfig",
+ "products.agent_platform.backend.apps.AgentPlatformConfig",
"products.web_analytics.backend.apps.WebAnalyticsConfig",
"products.warehouse_sources.backend.apps.WarehouseSourcesConfig",
"products.data_tools.backend.apps.DataToolsConfig",
@@ -522,6 +523,7 @@ SPECTACULAR_SETTINGS = {
"workflow_variable",
],
"AssigneeTypeEnum": ["user", "role"],
+ "AgentSessionStateEnum": ["queued", "running", "completed", "closed", "cancelled", "failed"],
"ScoutOriginEnum": ["canonical", "custom"],
"FileFormatEnum": ["Parquet", "JSONLines"],
"ErrorTrackingIssueOrderByEnum": ["last_seen", "first_seen", "occurrences", "users", "sessions"],
diff --git a/products/agent_platform/AGENTS.md b/products/agent_platform/AGENTS.md
new file mode 100644
index 000000000000..81574f183965
--- /dev/null
+++ b/products/agent_platform/AGENTS.md
@@ -0,0 +1,76 @@
+# agent_platform — Django side of the v2 agent platform
+
+This product is the **authoring + control-plane half** of the agent
+platform. The runtime is in node services at `services/agent-{ingress,runner,janitor}`.
+You will almost always need both sides in your head — read the
+[local-dev guide](../../docs/agent-platform/docs/local-dev.md) before
+making non-trivial changes.
+
+## What lives here
+
+- [models.py](backend/models.py) — `AgentApplication`, `AgentApplicationRevision`.
+ These are the **v2 shapes** (the file was renamed back from `models_v2.py`
+ post-cutover). Both tables live in the main posthog DB and are read by
+ every node service.
+- [serializers.py](backend/serializers.py) / [api.py](backend/api.py) — the
+ authoring REST surface (`/api/projects/<team>/agent_applications/...`).
+- [janitor_client.py](backend/janitor_client.py) — thin HTTP client into the
+ janitor for bundle reads/writes and the native_tools listing. **Django
+ never touches the bundle filesystem directly** — always proxy through
+ here. Auth is an audience-bound JWT (`aud = agent-janitor.rpc`) signed
+ with the shared `AGENT_INTERNAL_SIGNING_KEY` and sent as
+ `x-internal-secret`.
+
+## Rules of engagement
+
+1. **Anything that changes a serializer or viewset shape → rerun
+ `hogli build:openapi`** before testing or pushing. The MCP tool
+ surface ([services/mcp/src/tools/generated/agent_platform.ts](../../services/mcp/src/tools/generated/agent_platform.ts))
+ and the frontend types ([frontend/generated/api.schemas.ts](frontend/generated/api.schemas.ts))
+ both regenerate from the OpenAPI spec. Skip this and the MCP tool
+ schemas silently drift.
+
+2. **Never query the runtime tables from Django.** `agent_session`,
+ `agent_user`, `agent_sandbox_instance` live in `AGENT_DB` and are
+ owned by the node side. If Django needs runtime info, add a
+ janitor endpoint and call it via `janitor_client`.
+
+3. **Spec edits must round-trip through the node-side schema.** The
+ `revision.spec` JSONB is validated by
+ [`AgentSpecSchema`](../../services/agent-shared/src/spec/) on the
+ node side; Django passes it through. If you tighten a constraint
+ server-side, mirror it in the zod schema (or vice versa), otherwise
+ the janitor's `/revisions/:id/validate` will start rejecting things
+ Django happily wrote.
+
+4. **Encrypted env (`AgentApplication.encrypted_env`) uses
+ `ENCRYPTION_SALT_KEYS`.** The same keys must be present on the
+ runner so it can decrypt at session start. Don't add a second
+ encryption mechanism — extend `EncryptedTextField`'s key set.
+
+5. **Isolation: not yet enforced.** There's no `backend/facade/` or
+ `backend/presentation/` boundary yet, so no `backend:contract-check`.
+ Don't add new cross-product imports into here — when isolation lands
+ a facade will be the only allowed entry point.
+
+## When you change something here
+
+Vital changes need an e2e case in [services/agent-tests/](../../services/agent-tests/)
+— the harness drives the full Django-shaped flow against in-process
+ingress + runner + janitor. A change to the authoring API that doesn't
+have a case will silently regress when the node side evolves. See
+[agent-tests/CLAUDE.md](../../services/agent-tests/CLAUDE.md) for the
+pattern.
+
+## Pointers
+
+- **Local dev + MCP local + e2e overview** —
+ [docs/agent-platform/docs/local-dev.md](../../docs/agent-platform/docs/local-dev.md).
+- **Prod env vars per service** —
+ [docs/agent-platform/docs/deploy-runbook.md](../../docs/agent-platform/docs/deploy-runbook.md).
+- **What we're building next** —
+ [docs/agent-platform/plans/\_ROADMAP.md](../../docs/agent-platform/plans/_ROADMAP.md).
+- **Janitor HTTP surface** —
+ [services/agent-janitor/src/server.ts](../../services/agent-janitor/src/server.ts).
+- **Spec shape (source of truth)** —
+ [services/agent-shared/src/spec/](../../services/agent-shared/src/spec/).
diff --git a/products/agent_platform/CLAUDE.md b/products/agent_platform/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/agent_platform/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/agent_platform/README.md b/products/agent_platform/README.md
new file mode 100644
index 000000000000..2cf66ee817b7
--- /dev/null
+++ b/products/agent_platform/README.md
@@ -0,0 +1,40 @@
+# agent_platform v2 backend
+
+This is the Django-side data layer for the v2 agent platform refactor (see
+[docs/native-refactor.md](../../../docs/native-refactor.md)).
+
+## What's here
+
+- `models_v2.py` — new `AgentApplicationV2`, `AgentRevisionV2`, `AgentSessionV2`
+ shapes. Replaces `models.py`'s `AgentApplication` + `AgentApplicationRevision`.
+
+## Cutover plan (pre-prod — DB gets dropped)
+
+1. Add `models_v2` to `apps.py`'s migrations target.
+2. Generate a migration that drops the v1 tables and creates the v2 tables.
+3. Wire `api.py` to read/write the v2 models. (Existing `api.py` becomes
+ reference-only and is deleted post-cutover.)
+4. Internal endpoints for `agent-ingress-v2` and `agent-runner-v2` consume the
+ v2 tables directly.
+5. After step 9 of the refactor sequence, drop `models.py`, rename
+ `models_v2.py` → `models.py`, drop the `V2` suffixes from class names.
+
+## The shape
+
+```text
+AgentApplicationV2
+ team_id, slug, name, description, encrypted_env, live_revision_id, archived
+ (unique on slug while archived=false)
+
+AgentRevisionV2
+ application_id, parent_revision_id, state, bundle_uri, bundle_sha256, spec(JSONB)
+ state: draft → ready → live | archived
+
+AgentSessionV2
+ application_id, revision_id, team_id, state, external_key, conversation(JSONB), metadata
+ (unique on (application, external_key) while state in queued/running/waiting)
+```
+
+The `spec` JSONB is the structural truth — model, triggers, tools, mcps,
+skills, integrations, secrets, limits, entrypoint. See `@posthog/agent-shared-v2`
+for the canonical TypeScript shape (`AgentSpec`).
diff --git a/products/agent_platform/__init__.py b/products/agent_platform/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/__init__.py b/products/agent_platform/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/apps.py b/products/agent_platform/backend/apps.py
new file mode 100644
index 000000000000..03131efb2163
--- /dev/null
+++ b/products/agent_platform/backend/apps.py
@@ -0,0 +1,26 @@
+"""Django app configuration for agent_platform."""
+
+from django.apps import AppConfig
+from django.conf import settings
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+
+class AgentPlatformConfig(AppConfig):
+ name = "products.agent_platform.backend"
+ label = "agent_platform"
+
+ def ready(self) -> None:
+ # Operators-facing nudge: when the signing key is unset outside
+ # DEBUG, every Django→janitor call will 401 (the client skips the
+ # JWT mint, the janitor rejects the missing header). Log loudly at
+ # startup so the misconfiguration is caught before the first
+ # authoring request lands rather than via a flood of 401 traces.
+ if not settings.DEBUG and not settings.AGENT_INTERNAL_SIGNING_KEY:
+ logger.warning(
+ "agent_platform_internal_signing_key_unset",
+ hint="Set AGENT_INTERNAL_SIGNING_KEY (32+ bytes from `openssl rand -hex 32`). "
+ "Django→janitor calls will 401 until configured.",
+ )
diff --git a/products/agent_platform/backend/db.py b/products/agent_platform/backend/db.py
new file mode 100644
index 000000000000..5ec7db79d51b
--- /dev/null
+++ b/products/agent_platform/backend/db.py
@@ -0,0 +1,15 @@
+from django.conf import settings
+
+_APP_LABEL = "agent_platform"
+_WRITER_ALIAS = f"{_APP_LABEL}_db_writer"
+_READER_ALIAS = f"{_APP_LABEL}_db_reader"
+WRITER_DB: str = _WRITER_ALIAS if _WRITER_ALIAS in settings.DATABASES else "default"
+# In tests reads must hit the writer alias — both aliases connect to the same
+# physical test DB but run independent transactions, so without this the
+# reader can't see writes made earlier in the same test (mirrors the rule in
+# `posthog/product_db_router.py`).
+READER_DB: str = (
+ _WRITER_ALIAS
+ if getattr(settings, "TEST", False) and _WRITER_ALIAS in settings.DATABASES
+ else (_READER_ALIAS if _READER_ALIAS in settings.DATABASES else "default")
+)
diff --git a/products/agent_platform/backend/logic/__init__.py b/products/agent_platform/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/logic/internal_jwt.py b/products/agent_platform/backend/logic/internal_jwt.py
new file mode 100644
index 000000000000..af9a69fb858d
--- /dev/null
+++ b/products/agent_platform/backend/logic/internal_jwt.py
@@ -0,0 +1,41 @@
+from datetime import UTC, datetime, timedelta
+from enum import Enum
+from typing import Any
+
+from django.conf import settings
+
+import jwt
+
+# Trusted-service ↔ trusted-service JWTs for the agent platform. Signed with
+# AGENT_INTERNAL_SIGNING_KEY (the key the node services verify against) — distinct
+# from posthog.jwt's SECRET_KEY-signed tokens, which the node services can't verify.
+
+JWT_ALGORITHM = "HS256"
+
+
+class AgentInternalAudience(Enum):
+ """`aud` scopes a token to one receiving service, so a token minted for the
+ janitor can't be replayed against the ingress. Mirror these in
+ services/agent-shared/src/runtime/internal-jwt.ts — add to both sides.
+ """
+
+ INGRESS_PREVIEW = "agent-ingress.preview"
+ JANITOR_RPC = "agent-janitor.rpc"
+
+
+def encode_agent_internal_jwt(payload: dict[str, Any], expiry_delta: timedelta, audience: AgentInternalAudience) -> str:
+ key = settings.AGENT_INTERNAL_SIGNING_KEY
+ if not key:
+ raise RuntimeError("AGENT_INTERNAL_SIGNING_KEY is not configured")
+ return jwt.encode(
+ {**payload, "exp": datetime.now(tz=UTC) + expiry_delta, "aud": audience.value},
+ key,
+ algorithm=JWT_ALGORITHM,
+ )
+
+
+def decode_agent_internal_jwt(token: str, audience: AgentInternalAudience) -> dict[str, Any]:
+ key = settings.AGENT_INTERNAL_SIGNING_KEY
+ if not key:
+ raise RuntimeError("AGENT_INTERNAL_SIGNING_KEY is not configured")
+ return jwt.decode(token, key, audience=audience.value, algorithms=[JWT_ALGORITHM])
diff --git a/products/agent_platform/backend/logic/janitor_client.py b/products/agent_platform/backend/logic/janitor_client.py
new file mode 100644
index 000000000000..edaf42d03f67
--- /dev/null
+++ b/products/agent_platform/backend/logic/janitor_client.py
@@ -0,0 +1,397 @@
+"""
+Thin HTTP client for the agent-janitor service. The Django API uses this to
+proxy bundle reads/writes through to the node side, which is the layer that
+actually owns BundleStore (FS in dev, S3 in prod).
+
+Auth is a short-lived, audience-bound HS256 JWT minted per call and sent as
+`x-internal-secret`. Signed with `settings.AGENT_INTERNAL_SIGNING_KEY` (the
+same key Django uses for ingress preview tokens, scoped by `aud`). Endpoints
+are documented in services/agent-janitor/src/server.ts.
+
+Base URL comes from `settings.AGENT_JANITOR_BASE_URL` (env var of the same
+name, default http://localhost:3031).
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import timedelta
+from typing import Any
+
+from django.conf import settings
+
+import requests
+
+from posthog.security.outbound_proxy import internal_requests
+
+from .internal_jwt import AgentInternalAudience, encode_agent_internal_jwt
+
+logger = logging.getLogger(__name__)
+
+
+class JanitorClientError(Exception):
+ """Wraps non-2xx janitor responses + transport failures so view code can
+ map them to DRF responses with a single except clause."""
+
+ def __init__(self, status_code: int, message: str, body: Any | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+ self.message = message
+ self.body = body
+
+
+class JanitorClient:
+ def __init__(self, base_url: str | None = None, timeout: float = 120.0) -> None:
+ # Single source of truth: `settings.AGENT_JANITOR_BASE_URL` (default
+ # http://localhost:3031, matching `bin/mprocs.yaml`'s janitor PORT).
+ # Django + janitor must agree on the URL for the bundle proxy to work.
+ self.base_url = (base_url or settings.AGENT_JANITOR_BASE_URL).rstrip("/")
+ self.timeout = timeout
+
+ def _headers(self) -> dict[str, str]:
+ h = {"content-type": "application/json"}
+ if settings.AGENT_INTERNAL_SIGNING_KEY:
+ token = encode_agent_internal_jwt(
+ {"sub": "django"},
+ timedelta(seconds=60),
+ AgentInternalAudience.JANITOR_RPC,
+ )
+ h["x-internal-secret"] = token
+ return h
+
+ def _call(self, method: str, path: str, **kwargs: Any) -> Any:
+ url = f"{self.base_url}{path}"
+ try:
+ # The janitor is an in-cluster service — use the internal session so the
+ # call bypasses HTTP(S)_PROXY (smokescreen blocks private IPs → 407).
+ resp = internal_requests.request(method, url, headers=self._headers(), timeout=self.timeout, **kwargs)
+ except requests.RequestException as e:
+ logger.exception("janitor request failed")
+ raise JanitorClientError(502, f"janitor unreachable: {e}") from e
+ if resp.status_code >= 400:
+ try:
+ body = resp.json()
+ except ValueError:
+ body = None
+ raise JanitorClientError(resp.status_code, f"janitor returned {resp.status_code}", body=body)
+ if not resp.content:
+ return {}
+ return resp.json()
+
+ # ── revisions ──────────────────────────────────────────────────────────
+
+ def manifest(self, revision_id: str) -> dict:
+ return self._call("GET", f"/revisions/{revision_id}/manifest")
+
+ def slack_manifest(self, revision_id: str, *, events_url: str | None, interactivity_url: str | None) -> dict:
+ params: dict[str, str] = {}
+ if events_url:
+ params["events_url"] = events_url
+ if interactivity_url:
+ params["interactivity_url"] = interactivity_url
+ return self._call("GET", f"/revisions/{revision_id}/slack-manifest", params=params)
+
+ # ── typed bundle authoring API ─────────────────────────────────────────
+ # See docs/agent-platform/plans/typed-bundle-authoring-api.md.
+ # The legacy file-grain methods (get_file / put_file / delete_file /
+ # put_bundle with mode) were removed; authors now write typed resources
+ # (agent_md, skills/<id>, tools/<id>) and the janitor translates to
+ # canonical S3 paths under the hood.
+
+ def get_bundle(self, revision_id: str) -> dict:
+ """Read the full typed bundle: { agent_md, skills, tools, spec }."""
+ return self._call("GET", f"/revisions/{revision_id}/bundle")
+
+ def put_bundle(self, revision_id: str, bundle: dict) -> dict:
+ """Full-replace the typed bundle. `bundle` carries agent_md, skills,
+ tools, spec — resources NOT in the payload are deleted."""
+ return self._call("PUT", f"/revisions/{revision_id}/bundle", json=bundle)
+
+ def put_agent_md(self, revision_id: str, content: str) -> dict:
+ return self._call("PUT", f"/revisions/{revision_id}/agent_md", json={"content": content})
+
+ def put_spec(self, revision_id: str, spec: dict) -> dict:
+ """Replace the author-facing spec slice (no skills[] / tools[])."""
+ return self._call("PUT", f"/revisions/{revision_id}/spec", json={"spec": spec})
+
+ def put_skill(self, revision_id: str, skill_id: str, skill: dict) -> dict:
+ """Upsert one skill. `skill` carries { description, body }; stored at skills/<id>/SKILL.md."""
+ return self._call("PUT", f"/revisions/{revision_id}/skills/{skill_id}", json=skill)
+
+ def delete_skill(self, revision_id: str, skill_id: str) -> dict:
+ return self._call("DELETE", f"/revisions/{revision_id}/skills/{skill_id}")
+
+ def put_tool(self, revision_id: str, tool_id: str, tool: dict) -> dict:
+ """Upsert one tool. Triggers AST shape check + esbuild compile on
+ the janitor side. `tool` carries { description, args_schema, source }."""
+ return self._call("PUT", f"/revisions/{revision_id}/tools/{tool_id}", json=tool)
+
+ def delete_tool(self, revision_id: str, tool_id: str) -> dict:
+ return self._call("DELETE", f"/revisions/{revision_id}/tools/{tool_id}")
+
+ def freeze(self, revision_id: str) -> dict:
+ return self._call("POST", f"/revisions/{revision_id}/freeze")
+
+ def validate(self, revision_id: str) -> dict:
+ return self._call("POST", f"/revisions/{revision_id}/validate")
+
+ def cron_fire(self, revision_id: str, *, cron_name: str, request_id: str | None = None) -> dict:
+ """Manually fire one cron job, bypassing the scheduler's window logic.
+
+ Same execution path a scheduled firing walks — authoring surface so
+ the user can iterate on a cron prompt without waiting for the next
+ real firing. `request_id` makes repeat clicks idempotent (the
+ janitor uses `cron-manual:<rev>:<name>:<request_id>` as the dedupe
+ key); pass a stable id per logical click. Plan §9 "Manual fire."
+ """
+ body: dict[str, str] = {"cron_name": cron_name}
+ if request_id is not None:
+ body["request_id"] = request_id
+ return self._call("POST", f"/revisions/{revision_id}/cron/fire", json=body)
+
+ def get_system_prompt(self, revision_id: str) -> dict:
+ """Return the fully-assembled system prompt for a revision.
+
+ The runner builds this same prompt at session start — framework
+ preamble + agent.md + skills index. Authoring tools surface it so
+ the author can inspect what the model will actually see. See
+ docs/agent-platform/plans/framework-system-prompt.md §4.
+ """
+ return self._call("GET", f"/revisions/{revision_id}/system-prompt")
+
+ # ── sessions ───────────────────────────────────────────────────────────
+
+ def list_sessions(
+ self,
+ application_id: str,
+ *,
+ limit: int | None = None,
+ offset: int | None = None,
+ state: str | None = None,
+ revision_id: str | None = None,
+ created_after: str | None = None,
+ created_before: str | None = None,
+ ) -> dict:
+ params: dict[str, Any] = {"application_id": application_id}
+ if limit is not None:
+ params["limit"] = limit
+ if offset is not None:
+ params["offset"] = offset
+ if state:
+ # Comma-separated list (e.g. "completed,failed"). Pass through
+ # verbatim — the janitor parses.
+ params["state"] = state
+ if revision_id:
+ params["revision_id"] = revision_id
+ if created_after:
+ params["created_after"] = created_after
+ if created_before:
+ params["created_before"] = created_before
+ return self._call("GET", "/sessions", params=params)
+
+ def get_session(self, session_id: str, *, last_n: int | None = None) -> dict:
+ params: dict[str, Any] = {}
+ if last_n is not None:
+ params["last_n"] = last_n
+ return self._call("GET", f"/sessions/{session_id}", params=params)
+
+ # ── fleet stats ────────────────────────────────────────────────────────
+ # Roll-up endpoints powering the agent-console overview tiles. The
+ # janitor side owns the JSONB read so Django doesn't reach across DBs.
+
+ def aggregate_for_application(self, application_id: str, *, since: str | None = None) -> dict:
+ params: dict[str, Any] = {"application_id": application_id}
+ if since:
+ params["since"] = since
+ return self._call("GET", "/sessions/stats", params=params)
+
+ def aggregate_for_team(self, team_id: int, *, since: str | None = None) -> dict:
+ params: dict[str, Any] = {"team_id": team_id}
+ if since:
+ params["since"] = since
+ return self._call("GET", "/fleet/stats", params=params)
+
+ def list_live_for_team(self, team_id: int, *, limit: int | None = None) -> dict:
+ params: dict[str, Any] = {"team_id": team_id}
+ if limit is not None:
+ params["limit"] = limit
+ return self._call("GET", "/sessions/live", params=params)
+
+ def clone_from(self, target_revision_id: str, source_revision_id: str) -> dict:
+ return self._call(
+ "POST",
+ f"/revisions/{target_revision_id}/clone_from",
+ json={"source_revision_id": source_revision_id},
+ )
+
+ # ── approvals ──────────────────────────────────────────────────────────
+ # See docs/agent-platform/plans/approval-gated-tools.md.
+
+ def list_approvals(
+ self,
+ application_id: str,
+ *,
+ state: str | None = None,
+ limit: int | None = None,
+ offset: int | None = None,
+ ) -> dict:
+ params: dict[str, Any] = {"application_id": application_id}
+ if state:
+ params["state"] = state
+ if limit is not None:
+ params["limit"] = limit
+ if offset is not None:
+ params["offset"] = offset
+ return self._call("GET", "/approvals", params=params)
+
+ def list_approvals_for_team(
+ self,
+ team_id: int,
+ *,
+ application_id: str | None = None,
+ state: str | None = None,
+ limit: int | None = None,
+ offset: int | None = None,
+ ) -> dict:
+ params: dict[str, Any] = {"team_id": team_id}
+ if application_id:
+ params["application_id"] = application_id
+ if state:
+ params["state"] = state
+ if limit is not None:
+ params["limit"] = limit
+ if offset is not None:
+ params["offset"] = offset
+ return self._call("GET", "/fleet/approvals", params=params)
+
+ def get_approval(self, approval_id: str) -> dict:
+ return self._call("GET", f"/approvals/{approval_id}")
+
+ def decide_approval(
+ self,
+ approval_id: str,
+ *,
+ decision: str,
+ decided_by: str,
+ edited_args: dict[str, Any] | None = None,
+ reason: str | None = None,
+ ) -> dict:
+ body: dict[str, Any] = {"decision": decision, "decided_by": decided_by}
+ if edited_args is not None:
+ body["edited_args"] = edited_args
+ if reason is not None:
+ body["reason"] = reason
+ return self._call("POST", f"/approvals/{approval_id}/decide", json=body)
+
+ # ── catalog ────────────────────────────────────────────────────────────
+
+ def native_tools(self) -> dict:
+ return self._call("GET", "/native_tools")
+
+ # ── memory ─────────────────────────────────────────────────────────────
+ # S3-backed memory files surface. Each agent has its own prefix; the
+ # runner writes via the @posthog/memory-* tools, humans write via these
+ # endpoints. Both share the same bucket — see
+ # services/agent-shared/src/memory/store.ts for the key layout.
+
+ def list_memory_files(self, team_id: int, application_id: str, *, prefix: str | None = None) -> dict:
+ params: dict[str, Any] = {}
+ if prefix:
+ params["prefix"] = prefix
+ return self._call(
+ "GET",
+ f"/memory/team/{team_id}/agent/{application_id}/files",
+ params=params,
+ )
+
+ def get_memory_tree(self, team_id: int, application_id: str) -> dict:
+ return self._call("GET", f"/memory/team/{team_id}/agent/{application_id}/tree")
+
+ # Tabular reference (the @posthog/table-* tools' JSONL tables) — read-only,
+ # surfaced in the console's memory tab alongside the markdown files.
+ def list_tables(self, team_id: int, application_id: str) -> dict:
+ return self._call("GET", f"/tables/team/{team_id}/agent/{application_id}")
+
+ def read_table(self, team_id: int, application_id: str, name: str, *, limit: int | None = None) -> dict:
+ params: dict[str, Any] = {}
+ if limit:
+ params["limit"] = limit
+ return self._call("GET", f"/tables/team/{team_id}/agent/{application_id}/{name}", params=params)
+
+ def read_memory_file(self, team_id: int, application_id: str, path: str) -> dict:
+ # The janitor uses the URL tail (Express `:path(.*)`) for the file path,
+ # so `incidents/db.md` becomes `/files/incidents/db.md`. We don't
+ # url-encode the slashes — the slash IS the path separator, and the
+ # janitor's `validateMemoryPath` rejects anything dodgy.
+ return self._call(
+ "GET",
+ f"/memory/team/{team_id}/agent/{application_id}/files/{path.lstrip('/')}",
+ )
+
+ def write_memory_file(
+ self,
+ team_id: int,
+ application_id: str,
+ *,
+ path: str,
+ description: str,
+ content: str,
+ tags: list[str] | None = None,
+ ) -> dict:
+ body: dict[str, Any] = {"path": path, "description": description, "content": content}
+ if tags is not None:
+ body["tags"] = tags
+ return self._call("POST", f"/memory/team/{team_id}/agent/{application_id}/files", json=body)
+
+ def update_memory_file(
+ self,
+ team_id: int,
+ application_id: str,
+ path: str,
+ *,
+ description: str | None = None,
+ content: str | None = None,
+ tags: list[str] | None = None,
+ ) -> dict:
+ body: dict[str, Any] = {}
+ if description is not None:
+ body["description"] = description
+ if content is not None:
+ body["content"] = content
+ if tags is not None:
+ body["tags"] = tags
+ return self._call(
+ "PATCH",
+ f"/memory/team/{team_id}/agent/{application_id}/files/{path.lstrip('/')}",
+ json=body,
+ )
+
+ def delete_memory_file(self, team_id: int, application_id: str, path: str) -> dict:
+ return self._call(
+ "DELETE",
+ f"/memory/team/{team_id}/agent/{application_id}/files/{path.lstrip('/')}",
+ )
+
+ def search_memory(
+ self,
+ team_id: int,
+ application_id: str,
+ *,
+ q: str,
+ prefix: str | None = None,
+ limit: int | None = None,
+ ) -> dict:
+ params: dict[str, Any] = {"q": q}
+ if prefix:
+ params["prefix"] = prefix
+ if limit is not None:
+ params["limit"] = limit
+ return self._call("GET", f"/memory/team/{team_id}/agent/{application_id}/search", params=params)
+
+
+def default_client() -> JanitorClient:
+ """One module-level singleton. Tests inject by monkey-patching this."""
+ return _CLIENT
+
+
+_CLIENT = JanitorClient()
diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.py
new file mode 100644
index 000000000000..bdf04ab3feec
--- /dev/null
+++ b/products/agent_platform/backend/logic/spec_schema.py
@@ -0,0 +1,642 @@
+"""
+JSON Schema for `AgentSpec`, copy-pasted from the canonical zod schema at
+`services/agent-shared/src/spec/spec.ts` (`AgentSpecSchema`).
+
+The zod schema is the source of truth — every other consumer (janitor at read
+time, runner at session start, this file at write time) must agree on its
+shape. We copy rather than codegen because the zod surface is small enough
+that drift is caught loudly by `test_spec_schema.py` (which re-emits the zod
+schema and diffs it against the embedded copy).
+
+## When zod changes
+
+1. Run the regen one-liner from `test_spec_schema.test_no_drift_vs_zod` (the
+ test prints it on failure).
+2. Replace `_AGENT_SPEC_JSON_SCHEMA_RAW` below with the new output.
+3. Re-run the test; it should pass.
+
+## Why two schemas
+
+zod's `.default([...])` makes a field optional at parse time — you can omit
+`triggers` and zod fills it in. JSON Schema's `required` doesn't respect
+defaults; if `triggers` is in `required`, every Django write needs to send
+the full empty list. To preserve zod semantics on the Django side, the
+`_relax_required_for_defaults` pass strips fields with `default` from the
+top-level `required` array.
+
+- `AGENT_SPEC_JSON_SCHEMA` — full shape, used for OpenAPI annotation so the
+ MCP tool surface advertises every field plus its default.
+- `AGENT_SPEC_JSON_SCHEMA_FOR_WRITE` — relaxed required list, used for
+ Django `validate_spec` so the same `{"model": "x"}` that zod accepts also
+ passes Django.
+"""
+
+from __future__ import annotations
+
+import copy
+from typing import Any
+
+# Shared `approval_policy` block — referenced from every tool variant that
+# can be approval-gated (native + custom + MCP entries). Mirror
+# `ApprovalPolicySchema` in services/agent-shared/src/spec/spec.ts.
+_APPROVAL_POLICY_JSON_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "approvers": {
+ "type": "array",
+ "minItems": 1,
+ "items": {"type": "string", "enum": ["team_admins", "session_principal"]},
+ "default": ["team_admins"],
+ },
+ "allow_edit": {"type": "boolean", "default": False},
+ "ttl_ms": {
+ "type": "integer",
+ "minimum": 60000,
+ "maximum": 7 * 24 * 60 * 60 * 1000,
+ "default": 24 * 60 * 60 * 1000,
+ },
+ "allow_agent_approver": {"type": "boolean", "default": False},
+ },
+ "additionalProperties": False,
+}
+
+# Shared `auth` block — referenced from every declarative trigger (webhook /
+# chat / mcp). Mirror `AuthConfigSchema` / `AuthModeSchema` in
+# services/agent-shared/src/spec/spec.ts. No default on `modes` here on purpose:
+# Orval emits a default as a plain TS literal that widens the discriminated
+# union and breaks the generated zod. The runtime default still applies node-side.
+_AUTH_CONFIG_JSON_SCHEMA: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "modes": {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "public"},
+ "acknowledge_public_exposure": {"type": "boolean", "const": True},
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "posthog"},
+ "scopes": {"default": [], "type": "array", "items": {"type": "string"}},
+ },
+ "required": ["type"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "jwt"},
+ "issuer_secret_ref": {"type": "string", "minLength": 1},
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "shared_secret"},
+ "header": {"type": "string", "minLength": 1},
+ "secret_ref": {"type": "string", "minLength": 1},
+ },
+ "required": ["type", "header", "secret_ref"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {"type": {"type": "string", "const": "posthog_internal"}},
+ "required": ["type"],
+ "additionalProperties": False,
+ },
+ ]
+ },
+ },
+ },
+ "additionalProperties": False,
+}
+
+_AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "properties": {
+ "model": {"type": "string", "minLength": 1},
+ "triggers": {
+ "default": [],
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "slack"},
+ "config": {
+ "type": "object",
+ "properties": {
+ "channel_id": {"type": "string"},
+ "mention_only": {"default": False, "type": "boolean"},
+ "auto_resume_threads": {"default": False, "type": "boolean"},
+ "allow_workspace_participants": {"default": False, "type": "boolean"},
+ "ack_reaction": {"type": "string"},
+ "trusted_workspaces": {
+ "anyOf": [
+ {"minItems": 1, "type": "array", "items": {"type": "string"}},
+ {"type": "string", "const": "*"},
+ ]
+ },
+ },
+ "required": [
+ "mention_only",
+ "auto_resume_threads",
+ "allow_workspace_participants",
+ "trusted_workspaces",
+ ],
+ "additionalProperties": False,
+ },
+ },
+ "required": ["type", "config"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "webhook"},
+ "config": {
+ "type": "object",
+ "properties": {
+ "path": {"type": "string"},
+ },
+ "required": ["path"],
+ "additionalProperties": False,
+ },
+ "auth": _AUTH_CONFIG_JSON_SCHEMA,
+ },
+ "required": ["type", "config", "auth"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "cron"},
+ # Mirror of the node cron config (services/agent-shared
+ # spec.ts, added by the cron scheduler PR #61028). The
+ # upstream Django mirror lagged at {schedule, timezone};
+ # synced here so cron-triggered agents validate.
+ "config": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "minLength": 1},
+ "schedule": {"type": "string", "minLength": 1},
+ "timezone": {"default": "UTC", "type": "string"},
+ "prompt": {"type": "string", "minLength": 1, "maxLength": 4096},
+ "external_key": {"type": "string"},
+ "catch_up": {
+ "enum": ["all", "most_recent", "skip"],
+ "default": "most_recent",
+ },
+ "max_catch_up_age_seconds": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 604800,
+ "default": 3600,
+ },
+ },
+ "required": ["name", "schedule", "prompt"],
+ "additionalProperties": False,
+ },
+ },
+ "required": ["type", "config"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "chat"},
+ "config": {
+ # Fully-resolved default (not {}): allow_restart has its own
+ # default, so the generated zod `.default(...)` must carry it or
+ # the Orval-emitted object fails strict typecheck.
+ "default": {"allow_restart": False},
+ "type": "object",
+ "properties": {"allow_restart": {"default": False, "type": "boolean"}},
+ "additionalProperties": False,
+ },
+ "auth": _AUTH_CONFIG_JSON_SCHEMA,
+ },
+ "required": ["type", "auth"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string", "const": "mcp"},
+ "config": {
+ # Fully-resolved default (not {}) — see the chat trigger above.
+ "default": {"allow_restart": False},
+ "type": "object",
+ "properties": {"allow_restart": {"default": False, "type": "boolean"}},
+ "additionalProperties": False,
+ },
+ "auth": _AUTH_CONFIG_JSON_SCHEMA,
+ },
+ "required": ["type", "auth"],
+ "additionalProperties": False,
+ },
+ ]
+ },
+ },
+ "tools": {
+ "default": [],
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ # Native + custom tool variants accept the same
+ # inline approval-gating fields as MCP tool
+ # entries (below) — see `ToolRefSchema` in
+ # services/agent-shared/src/spec/spec.ts. Mirror
+ # any changes there.
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "native"},
+ "id": {"type": "string"},
+ "requires_approval": {"type": "boolean", "default": False},
+ "approval_policy": _APPROVAL_POLICY_JSON_SCHEMA,
+ },
+ "required": ["kind", "id"],
+ "additionalProperties": False,
+ },
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "custom"},
+ "id": {"type": "string"},
+ "path": {"type": "string"},
+ "requires_approval": {"type": "boolean", "default": False},
+ "approval_policy": _APPROVAL_POLICY_JSON_SCHEMA,
+ },
+ "required": ["kind", "id", "path"],
+ "additionalProperties": False,
+ },
+ {
+ # Registry-pinned custom tool — draft-only shape.
+ # Freeze resolves `from_template` at `version`, writes
+ # `tools/<alias>/…`, and reshapes this into the
+ # `custom` variant above before the runner sees it.
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "custom_template"},
+ "from_template": {"type": "string"},
+ "alias": {"type": "string"},
+ "version": {"type": "integer", "minimum": 0},
+ },
+ "required": ["kind", "from_template", "alias"],
+ "additionalProperties": False,
+ },
+ {
+ # Client-fulfilled tool — implementation lives in the
+ # connecting client (browser dock, IDE MCP host), not
+ # in the runner. See `AgentSpecSchema.tools.client`
+ # in services/agent-shared/src/spec/spec.ts for the
+ # full contract + dispatch model.
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "const": "client"},
+ "id": {"type": "string", "minLength": 1},
+ "description": {"type": "string", "minLength": 1},
+ "args_schema": {"type": "object", "default": {}},
+ "required": {"type": "boolean", "default": False},
+ "timeout_ms": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 600000,
+ "default": 5000,
+ },
+ "interactive": {"type": "boolean", "default": False},
+ },
+ "required": ["kind", "id", "description"],
+ "additionalProperties": False,
+ },
+ ]
+ },
+ },
+ "mcps": {
+ "default": [],
+ "type": "array",
+ # Single flat shape — third-party MCP server reachable over HTTP.
+ # The `kind: 'agent'` agent-to-agent variant was removed; see
+ # `docs/agent-platform/plans/agent-as-mcp-server.md` for re-add.
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string", "minLength": 1},
+ "url": {"type": "string", "format": "uri"},
+ "auth": {
+ "type": "object",
+ "properties": {"integration": {"type": "string"}},
+ "additionalProperties": False,
+ },
+ "secrets": {
+ "default": [],
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ # Author-supplied request headers stamped on every outgoing
+ # MCP request. Values may reference `${NAME}` from
+ # `secrets[]`; the runner substitutes the plaintext value
+ # before opening the MCP client. Same substitution shape as
+ # `@posthog/http-request`'s `headers` — the parallel is
+ # intentional. Use for the bring-your-own-token case
+ # (paste a PAT once, reference it as `${TOKEN}` in
+ # `Authorization: 'Bearer ${TOKEN}'`).
+ "headers": {
+ "type": "object",
+ "additionalProperties": {"type": "string"},
+ },
+ # Per-tool selection + approval gating. Bare string
+ # = inclusion only (was allowlist[] pre-PR-7);
+ # object form adds requires_approval +
+ # approval_policy. See `McpToolEntrySchema` in
+ # services/agent-shared/src/spec/spec.ts.
+ "tools": {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {"type": "string", "minLength": 1},
+ {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "minLength": 1},
+ "requires_approval": {"type": "boolean", "default": False},
+ "approval_policy": {
+ "type": "object",
+ "properties": {
+ "approvers": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "string",
+ "enum": ["team_admins", "session_principal"],
+ },
+ "default": ["team_admins"],
+ },
+ "allow_edit": {"type": "boolean", "default": False},
+ "ttl_ms": {
+ "type": "integer",
+ "minimum": 60000,
+ "maximum": 7 * 24 * 60 * 60 * 1000,
+ "default": 24 * 60 * 60 * 1000,
+ },
+ "allow_agent_approver": {
+ "type": "boolean",
+ "default": False,
+ },
+ },
+ "additionalProperties": False,
+ },
+ },
+ "required": ["name"],
+ "additionalProperties": False,
+ },
+ ],
+ },
+ },
+ },
+ "required": ["id", "url"],
+ "additionalProperties": False,
+ },
+ },
+ "skills": {
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string"},
+ "path": {"type": "string"},
+ "description": {"type": "string"},
+ # Registry lineage for a skill pinned from a template.
+ # Present on a draft spec; freeze resolves `from_template`,
+ # assembles `skills/<alias>/SKILL.md`, and stamps id/path.
+ "from_template": {"type": "string"},
+ "alias": {"type": "string"},
+ "version": {"type": "integer", "minimum": 0},
+ },
+ "required": ["id", "path"],
+ "additionalProperties": False,
+ },
+ },
+ "integrations": {"default": [], "type": "array", "items": {"type": "string"}},
+ "secrets": {"default": [], "type": "array", "items": {"type": "string"}},
+ "limits": {
+ "default": {"max_turns": 50, "max_tool_calls": 200, "max_wall_seconds": 900},
+ "type": "object",
+ "properties": {
+ "max_turns": {"default": 50, "type": "integer", "exclusiveMinimum": 0, "maximum": 9007199254740991},
+ "max_tool_calls": {
+ "default": 200,
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ },
+ "max_wall_seconds": {
+ "default": 900,
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ },
+ "max_output_tokens": {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 200000,
+ },
+ },
+ "required": ["max_turns", "max_tool_calls", "max_wall_seconds"],
+ "additionalProperties": False,
+ },
+ "entrypoint": {"default": "agent.md", "type": "string"},
+ "reasoning": {"type": "string", "enum": ["minimal", "low", "medium", "high", "xhigh"]},
+ },
+ "required": [
+ "model",
+ "triggers",
+ "tools",
+ "mcps",
+ "skills",
+ "integrations",
+ "secrets",
+ "limits",
+ "entrypoint",
+ ],
+ "additionalProperties": False,
+}
+
+
+def _relax_required_for_defaults(schema: dict[str, Any]) -> dict[str, Any]:
+ """Recursively strip `required` entries whose property schema has a default.
+
+ Mirrors zod's `.default()` semantics: a field with a default is optional
+ at parse time. JSON Schema's `required` doesn't infer this from `default`,
+ so we transform it here. The walk covers every object node reachable via
+ `properties`, `items`, `oneOf`/`anyOf`/`allOf`, `additionalProperties`,
+ and `propertyNames` — i.e. every nested schema zod emits, including the
+ discriminated trigger union (`triggers[].config.mention_only`,
+ `triggers[].config.timezone`, …).
+ """
+ out = copy.deepcopy(schema)
+ _relax_node(out)
+ return out
+
+
+def _relax_node(node: Any) -> None:
+ if not isinstance(node, dict):
+ return
+
+ # Strip required entries whose property is defaulted.
+ props = node.get("properties")
+ required = node.get("required")
+ if isinstance(props, dict) and isinstance(required, list):
+ node["required"] = [r for r in required if not (isinstance(props.get(r), dict) and "default" in props[r])]
+
+ # Recurse through every schema-bearing child.
+ if isinstance(props, dict):
+ for v in props.values():
+ _relax_node(v)
+ items = node.get("items")
+ if isinstance(items, dict):
+ _relax_node(items)
+ elif isinstance(items, list):
+ for v in items:
+ _relax_node(v)
+ for key in ("oneOf", "anyOf", "allOf"):
+ sub = node.get(key)
+ if isinstance(sub, list):
+ for v in sub:
+ _relax_node(v)
+ add_props = node.get("additionalProperties")
+ if isinstance(add_props, dict):
+ _relax_node(add_props)
+ prop_names = node.get("propertyNames")
+ if isinstance(prop_names, dict):
+ _relax_node(prop_names)
+
+
+AGENT_SPEC_JSON_SCHEMA: dict[str, Any] = _AGENT_SPEC_JSON_SCHEMA_RAW
+AGENT_SPEC_JSON_SCHEMA_FOR_WRITE: dict[str, Any] = _relax_required_for_defaults(_AGENT_SPEC_JSON_SCHEMA_RAW)
+
+
+# ── Per-trigger-type required secrets ──────────────────────────────────────
+#
+# Mirrors `services/agent-shared/src/spec/trigger-secrets.ts` for the
+# Django-side validation path. Keep the two in lockstep — the slack trigger
+# handler in agent-ingress reads `SLACK_SIGNING_SECRET_KEY` and the freeze /
+# promote gate here rejects revisions whose agent's `encrypted_env` is missing
+# the same key.
+
+SLACK_SIGNING_SECRET_KEY = "SLACK_SIGNING_SECRET"
+SLACK_BOT_TOKEN_KEY = "SLACK_BOT_TOKEN"
+
+TRIGGER_REQUIRED_SECRETS: dict[str, list[dict[str, Any]]] = {
+ "chat": [],
+ "webhook": [],
+ "cron": [],
+ "mcp": [],
+ "slack": [
+ {
+ "key": SLACK_SIGNING_SECRET_KEY,
+ "label": "Slack signing secret",
+ "description": (
+ "Your Slack app's signing secret. Find it under Settings → Basic Information → "
+ "Signing Secret. Required to verify inbound Slack event signatures."
+ ),
+ "required": True,
+ },
+ {
+ "key": SLACK_BOT_TOKEN_KEY,
+ "label": "Slack bot user OAuth token",
+ "description": (
+ "Your Slack app's bot token (starts with `xoxb-`). Find it under Settings → "
+ "Install App → Bot User OAuth Token after installing the app to your workspace. "
+ "Used by native slack tools to call the Slack API."
+ ),
+ "required": True,
+ },
+ ],
+}
+
+
+def _auth_mode_secret_requirement(mode: dict[str, Any]) -> dict[str, Any] | None:
+ """The `encrypted_env` key an auth mode references, or None. Mirrors the
+ `secret_ref` / `issuer_secret_ref` fields on `AuthModeSchema`."""
+ mtype = mode.get("type")
+ if mtype == "shared_secret":
+ key = mode.get("secret_ref")
+ if isinstance(key, str) and key:
+ header = mode.get("header") or ""
+ return {
+ "key": key,
+ "label": "Webhook shared secret",
+ "description": f"Expected value for the `{header}` header. Callers must send this exact secret.",
+ "required": True,
+ }
+ elif mtype == "jwt":
+ key = mode.get("issuer_secret_ref")
+ if isinstance(key, str) and key:
+ return {
+ "key": key,
+ "label": "JWT signing secret",
+ "description": "HMAC secret used to verify inbound JWT signatures for this trigger.",
+ "required": True,
+ }
+ return None
+
+
+def missing_required_secrets(spec: dict[str, Any], env_map: dict[str, str]) -> list[dict[str, Any]]:
+ """Walk `spec.triggers` and return the required-secret entries whose keys
+ aren't present in `env_map`. Covers both the per-trigger-type registry
+ (`TRIGGER_REQUIRED_SECRETS`) and the per-trigger `auth.modes[]` secret refs
+ (`shared_secret.secret_ref`, `jwt.issuer_secret_ref`). Empty list = OK to
+ promote. Each entry carries the trigger type under `trigger`.
+
+ Pure / side-effect-free so the same helper can drive both the promote-time
+ gate and the "what's still missing?" UI hint."""
+ out: list[dict[str, Any]] = []
+ triggers = spec.get("triggers") or []
+ if not isinstance(triggers, list):
+ return out
+ seen_keys: set[str] = set()
+
+ def consider(requirement: dict[str, Any], trigger_type: str) -> None:
+ if not requirement.get("required"):
+ return
+ key = requirement["key"]
+ if key in seen_keys:
+ return
+ seen_keys.add(key)
+ if not env_map.get(key):
+ out.append({**requirement, "trigger": trigger_type})
+
+ for trigger in triggers:
+ if not isinstance(trigger, dict):
+ continue
+ trigger_type = trigger.get("type")
+ if not isinstance(trigger_type, str):
+ continue
+ for requirement in TRIGGER_REQUIRED_SECRETS.get(trigger_type, []):
+ consider(requirement, trigger_type)
+ auth = trigger.get("auth")
+ modes = auth.get("modes") if isinstance(auth, dict) else None
+ if isinstance(modes, list):
+ for mode in modes:
+ if not isinstance(mode, dict):
+ continue
+ auth_requirement = _auth_mode_secret_requirement(mode)
+ if auth_requirement is not None:
+ consider(auth_requirement, trigger_type)
+ return out
diff --git a/products/agent_platform/backend/migrations/0001_initial.py b/products/agent_platform/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..2c46e954bdae
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0001_initial.py
@@ -0,0 +1,455 @@
+# Generated by Django 5.2.14 on 2026-06-09 13:52
+
+import django.db.models.manager
+import django.db.models.deletion
+import django.db.models.functions.datetime
+import django.db.models.functions.comparison
+from django.db import migrations, models
+
+import posthog.models.utils
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="AgentApplication",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("name", models.CharField(max_length=255)),
+ ("slug", models.CharField(max_length=63)),
+ (
+ "description",
+ models.TextField(blank=True, db_default="", default=""),
+ ),
+ (
+ "encrypted_env",
+ posthog.helpers.encrypted_fields.EncryptedTextField(blank=True, null=True),
+ ),
+ ("archived", models.BooleanField(db_default=False, default=False)),
+ ("archived_at", models.DateTimeField(blank=True, null=True)),
+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ (
+ "updated_at",
+ models.DateTimeField(
+ auto_now=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ],
+ options={
+ "db_table": "agent_application",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentRevision",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True, null=True)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("draft", "draft"),
+ ("ready", "ready"),
+ ("live", "live"),
+ ("archived", "archived"),
+ ],
+ db_default="draft",
+ default="draft",
+ max_length=16,
+ ),
+ ),
+ ("bundle_uri", models.TextField()),
+ (
+ "bundle_sha256",
+ models.CharField(blank=True, max_length=64, null=True),
+ ),
+ ("spec", models.JSONField(default=dict)),
+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ (
+ "updated_at",
+ models.DateTimeField(
+ auto_now=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ (
+ "application",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="revisions",
+ to="agent_platform.agentapplication",
+ ),
+ ),
+ (
+ "parent_revision",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="children",
+ to="agent_platform.agentrevision",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "agent_revision",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddField(
+ model_name="agentapplication",
+ name="live_revision",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="live_for",
+ to="agent_platform.agentrevision",
+ ),
+ ),
+ migrations.CreateModel(
+ name="AgentSandboxInstance",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("application_id", models.UUIDField()),
+ ("revision_id", models.UUIDField()),
+ ("session_id", models.UUIDField(blank=True, null=True)),
+ ("provider_kind", models.TextField()),
+ ("provider_sandbox_id", models.TextField(db_default="", default="")),
+ (
+ "state",
+ models.TextField(db_default="provisioning", default="provisioning"),
+ ),
+ ("error_message", models.TextField(db_default="", default="")),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ("last_used_at", models.DateTimeField(blank=True, null=True)),
+ ("terminated_at", models.DateTimeField(blank=True, null=True)),
+ ],
+ options={
+ "db_table": "agent_sandbox_instance",
+ "indexes": [
+ models.Index(
+ django.db.models.functions.comparison.Coalesce("last_used_at", "created_at"),
+ models.F("state"),
+ name="asi_state_idx",
+ ),
+ models.Index(
+ condition=models.Q(("session_id__isnull", False)),
+ fields=["session_id"],
+ name="asi_session_idx",
+ ),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentSession",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("application_id", models.UUIDField()),
+ ("revision_id", models.UUIDField()),
+ ("external_key", models.TextField(blank=True, null=True)),
+ ("idempotency_key", models.TextField(blank=True, null=True)),
+ ("trigger_metadata", models.JSONField(blank=True, null=True)),
+ ("state", models.TextField(db_default="queued", default="queued")),
+ (
+ "conversation",
+ models.JSONField(db_default=models.Value("[]"), default=list),
+ ),
+ (
+ "pending_inputs",
+ models.JSONField(db_default=models.Value("[]"), default=list),
+ ),
+ ("principal", models.JSONField(blank=True, null=True)),
+ ("acl", models.JSONField(db_default=models.Value("[]"), default=list)),
+ (
+ "pending_elevation_requests",
+ models.JSONField(db_default=models.Value("[]"), default=list),
+ ),
+ ("claimed_at", models.DateTimeField(blank=True, null=True)),
+ ("retry_count", models.IntegerField(db_default=0, default=0)),
+ (
+ "usage_total",
+ models.JSONField(
+ db_default=models.Value(
+ '{"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}'
+ ),
+ default=dict,
+ ),
+ ),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ (
+ "updated_at",
+ models.DateTimeField(
+ auto_now=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ],
+ options={
+ "db_table": "agent_session",
+ "indexes": [
+ models.Index(fields=["state", "created_at"], name="agent_sess_created_idx"),
+ models.Index(fields=["state", "updated_at"], name="agent_sess_updated_idx"),
+ models.Index(
+ condition=models.Q(("external_key__isnull", False)),
+ fields=["application_id", "external_key"],
+ name="agent_sess_extkey_idx",
+ ),
+ ],
+ "constraints": [
+ models.UniqueConstraint(
+ condition=models.Q(("idempotency_key__isnull", False)),
+ fields=("application_id", "idempotency_key"),
+ name="agent_session_idempotency_key_unique",
+ )
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentSessionCredential",
+ fields=[
+ ("team_id", models.BigIntegerField(db_index=True, null=True)),
+ ("session_id", models.UUIDField(primary_key=True, serialize=False)),
+ ("encrypted_credentials", models.TextField()),
+ ("expires_at", models.DateTimeField()),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ (
+ "updated_at",
+ models.DateTimeField(
+ auto_now=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ],
+ options={
+ "db_table": "agent_session_credential",
+ "indexes": [models.Index(fields=["expires_at"], name="asc_expires_idx")],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentToolApprovalRequest",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("session_id", models.UUIDField()),
+ ("application_id", models.UUIDField()),
+ ("revision_id", models.UUIDField()),
+ ("turn", models.IntegerField()),
+ ("tool_call_id", models.TextField()),
+ ("tool_name", models.TextField()),
+ ("proposed_args", models.JSONField()),
+ ("args_hash", models.BinaryField()),
+ ("assistant_message", models.JSONField()),
+ ("approver_scope", models.JSONField()),
+ ("state", models.TextField()),
+ ("decision_by", models.UUIDField(blank=True, null=True)),
+ ("decision_at", models.DateTimeField(blank=True, null=True)),
+ ("decision_reason", models.TextField(blank=True, null=True)),
+ ("decided_args", models.JSONField(blank=True, null=True)),
+ ("dispatch_outcome", models.JSONField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ("expires_at", models.DateTimeField()),
+ ],
+ options={
+ "db_table": "agent_tool_approval_request",
+ "indexes": [
+ models.Index(fields=["state", "expires_at"], name="atar_expiry_idx"),
+ models.Index(fields=["team_id", "state", "-created_at"], name="atar_team_idx"),
+ models.Index(
+ fields=["application_id", "state", "-created_at"],
+ name="atar_app_idx",
+ ),
+ models.Index(fields=["session_id", "-created_at"], name="atar_session_idx"),
+ ],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ (
+ "state__in",
+ [
+ "queued",
+ "approving",
+ "dispatched",
+ "dispatched_failed",
+ "rejected",
+ "expired",
+ ],
+ )
+ ),
+ name="agent_tool_approval_request_state_valid",
+ ),
+ models.UniqueConstraint(
+ condition=models.Q(("state", "queued")),
+ fields=("session_id", "tool_name", "args_hash"),
+ name="agent_tool_approval_request_queued_unique",
+ ),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AgentUser",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("application_id", models.UUIDField()),
+ ("principal_kind", models.TextField()),
+ ("principal_id", models.TextField()),
+ (
+ "metadata",
+ models.JSONField(db_default=models.Value("{}"), default=dict),
+ ),
+ ("posthog_user_id", models.IntegerField(blank=True, null=True)),
+ (
+ "created_at",
+ models.DateTimeField(
+ auto_now_add=True,
+ db_default=django.db.models.functions.datetime.Now(),
+ ),
+ ),
+ ],
+ options={
+ "db_table": "agent_user",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("application_id", "principal_kind", "principal_id"),
+ name="agent_user_unique_natural_key",
+ )
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddIndex(
+ model_name="agentrevision",
+ index=models.Index(fields=["application", "state"], name="agent_revis_applica_de45c8_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="agentrevision",
+ index=models.Index(fields=["state", "created_at"], name="agent_revis_state_b8bd5c_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="agentapplication",
+ index=models.Index(fields=["team_id", "archived"], name="agent_appli_team_id_8edb60_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="agentapplication",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("archived", False)),
+ fields=("team_id", "slug"),
+ name="agent_application_unique_active_slug",
+ ),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/0002_alter_agentapplication_slug.py b/products/agent_platform/backend/migrations/0002_alter_agentapplication_slug.py
new file mode 100644
index 000000000000..5909dce52813
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0002_alter_agentapplication_slug.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-06-10 10:30
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="agentapplication",
+ name="slug",
+ field=models.SlugField(max_length=63),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/0003_agentapplication_global_slug_unique.py b/products/agent_platform/backend/migrations/0003_agentapplication_global_slug_unique.py
new file mode 100644
index 000000000000..4be28d2c39ef
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0003_agentapplication_global_slug_unique.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.14 on 2026-06-12 10:34
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0002_alter_agentapplication_slug"),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="agentapplication",
+ name="agent_application_unique_active_slug",
+ ),
+ migrations.AddConstraint(
+ model_name="agentapplication",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("archived", False)),
+ fields=("slug",),
+ name="agent_application_unique_active_slug",
+ ),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/__init__.py b/products/agent_platform/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..aea5f89493e9
--- /dev/null
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0003_agentapplication_global_slug_unique
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
new file mode 100644
index 000000000000..d0b1d2540bea
--- /dev/null
+++ b/products/agent_platform/backend/models.py
@@ -0,0 +1,320 @@
+"""
+Django models for the agent platform.
+
+All agent-platform tables — authoring **and** runtime — live in a single
+dedicated product database (`agent_platform`, routed via
+`products/db_routing.yaml`). Django owns the schema and every migration; the
+node services (`agent-{ingress,runner,janitor}`) are pure clients that connect
+to this DB and run raw SQL — they no longer manage schema.
+
+Because the DB is separate from the main posthog DB, models here cannot
+ForeignKey `Team`/`User` (no cross-database FKs). They use plain id columns
+(`team_id` via `ProductTeamModel`, `created_by_id`) and resolve those entities
+through the facade when needed. ForeignKeys *between* agent models are fine —
+they're all in the same DB.
+
+NOTE: the skill / custom-tool template registry models (and their API surface)
+were dropped pending a rethink — see the commented-out routes in `routes.py`.
+"""
+
+from __future__ import annotations
+
+from django.db import models
+from django.db.models import Q, Value
+from django.db.models.functions import Coalesce, Now
+
+from posthog.helpers.encrypted_fields import EncryptedTextField
+from posthog.models.scoping.product_mixin import ProductTeamModel
+from posthog.models.utils import UUIDModel
+
+REVISION_STATE_CHOICES = [
+ ("draft", "draft"),
+ ("ready", "ready"),
+ ("live", "live"),
+ ("archived", "archived"),
+]
+
+# Mirrors the JSONB default the node session writer relies on.
+USAGE_TOTAL_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,
+}
+
+
+# ─── Authoring ────────────────────────────────────────────────────────
+
+
+class AgentApplication(ProductTeamModel, UUIDModel):
+ """One agent. Slug is a single global namespace (server-minted on create,
+ globally unique) so domain-mode ingress routing — `<slug>.agents.<suffix>`,
+ which carries no team — resolves without knowing the team up front."""
+
+ name = models.CharField(max_length=255)
+ # SlugField adds Django's validate_slug ([a-zA-Z0-9_-]) so node-side writers
+ # can't land a slug that later builds an unsafe preview-proxy URL.
+ 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,
+ null=True,
+ blank=True,
+ related_name="live_for",
+ )
+
+ archived = models.BooleanField(default=False, db_default=False)
+ archived_at = models.DateTimeField(null=True, blank=True)
+
+ # No cross-DB FK to posthog.User — plain id, resolved via the facade.
+ 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())
+
+ class Meta:
+ db_table = "agent_application"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["slug"],
+ condition=Q(archived=False),
+ name="agent_application_unique_active_slug",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["team_id", "archived"]),
+ ]
+
+ def __str__(self) -> str:
+ return self.slug
+
+
+class AgentRevision(ProductTeamModel, UUIDModel):
+ """One revision of an agent. `spec` is structural; the bundle is content.
+
+ State machine: draft → ready → live | archived.
+ """
+
+ # Django (authoring API) sets team_id on create; the node-side createRevision
+ # (test harness) omits it, so allow null rather than force every node writer
+ # to thread it. Django-created rows always carry it.
+ team_id = models.BigIntegerField(db_index=True, null=True) # type: ignore[assignment] # nullable override of ProductTeamModel.team_id (node writers omit it)
+
+ application = models.ForeignKey(
+ AgentApplication,
+ on_delete=models.CASCADE,
+ related_name="revisions",
+ )
+ parent_revision = models.ForeignKey(
+ "self",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="children",
+ )
+
+ state = models.CharField(max_length=16, choices=REVISION_STATE_CHOICES, default="draft", db_default="draft")
+
+ bundle_uri = models.TextField()
+ bundle_sha256 = models.CharField(max_length=64, null=True, blank=True)
+
+ spec = models.JSONField(default=dict)
+
+ 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())
+
+ class Meta:
+ db_table = "agent_revision"
+ indexes = [
+ models.Index(fields=["application", "state"]),
+ models.Index(fields=["state", "created_at"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.application_id}@{str(self.id)[:8]} ({self.state})"
+
+
+# ─── Runtime ──────────────────────────────────────────────────────────
+#
+# Written by the node services via raw SQL (PgSessionQueue, etc.). Django
+# owns the schema; `db_default` reproduces the Postgres-level defaults the
+# node inserts may omit. Cross-table refs to authoring use plain UUID columns
+# (no FK) so authoring and runtime stay loosely coupled even though they're
+# co-located.
+
+
+class AgentSession(ProductTeamModel, UUIDModel):
+ """A single agent run. High-churn — claimed, driven, persisted by the runner."""
+
+ application_id = models.UUIDField()
+ revision_id = models.UUIDField()
+ external_key = models.TextField(null=True, blank=True)
+ idempotency_key = models.TextField(null=True, blank=True)
+ trigger_metadata = models.JSONField(null=True, blank=True)
+ state = models.TextField(default="queued", db_default="queued")
+ conversation = models.JSONField(default=list, db_default=Value("[]"))
+ pending_inputs = models.JSONField(default=list, db_default=Value("[]"))
+ principal = models.JSONField(null=True, blank=True)
+ acl = models.JSONField(default=list, db_default=Value("[]"))
+ pending_elevation_requests = models.JSONField(default=list, db_default=Value("[]"))
+ claimed_at = models.DateTimeField(null=True, blank=True)
+ retry_count = models.IntegerField(default=0, db_default=0)
+ usage_total = models.JSONField(
+ default=dict,
+ db_default=Value(
+ '{"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}'
+ ),
+ )
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ updated_at = models.DateTimeField(auto_now=True, db_default=Now())
+
+ class Meta:
+ db_table = "agent_session"
+ indexes = [
+ models.Index(fields=["state", "created_at"], name="agent_sess_created_idx"),
+ models.Index(fields=["state", "updated_at"], name="agent_sess_updated_idx"),
+ models.Index(
+ fields=["application_id", "external_key"],
+ name="agent_sess_extkey_idx",
+ condition=Q(external_key__isnull=False),
+ ),
+ ]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["application_id", "idempotency_key"],
+ condition=Q(idempotency_key__isnull=False),
+ name="agent_session_idempotency_key_unique",
+ ),
+ ]
+
+
+class AgentUser(ProductTeamModel, UUIDModel):
+ """External principal an agent has talked to (Slack user, etc.)."""
+
+ application_id = models.UUIDField()
+ principal_kind = models.TextField()
+ principal_id = models.TextField()
+ metadata = models.JSONField(default=dict, db_default=Value("{}"))
+ posthog_user_id = models.IntegerField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+
+ class Meta:
+ db_table = "agent_user"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["application_id", "principal_kind", "principal_id"],
+ name="agent_user_unique_natural_key",
+ ),
+ ]
+
+
+class AgentSandboxInstance(ProductTeamModel, UUIDModel):
+ """A provisioned sandbox (Docker/Modal) backing a session's tool execution."""
+
+ application_id = models.UUIDField()
+ revision_id = models.UUIDField()
+ session_id = models.UUIDField(null=True, blank=True)
+ provider_kind = models.TextField()
+ provider_sandbox_id = models.TextField(default="", db_default="")
+ state = models.TextField(default="provisioning", db_default="provisioning")
+ error_message = models.TextField(default="", db_default="")
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ last_used_at = models.DateTimeField(null=True, blank=True)
+ terminated_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ db_table = "agent_sandbox_instance"
+ indexes = [
+ models.Index(
+ Coalesce("last_used_at", "created_at"),
+ "state",
+ name="asi_state_idx",
+ ),
+ models.Index(
+ fields=["session_id"],
+ name="asi_session_idx",
+ condition=Q(session_id__isnull=False),
+ ),
+ ]
+
+
+class AgentToolApprovalRequest(ProductTeamModel, UUIDModel):
+ """One intercepted approval-gated tool call awaiting a decision."""
+
+ session_id = models.UUIDField()
+ application_id = models.UUIDField()
+ revision_id = models.UUIDField()
+ turn = models.IntegerField()
+ tool_call_id = models.TextField()
+ tool_name = models.TextField()
+ proposed_args = models.JSONField()
+ args_hash = models.BinaryField()
+ assistant_message = models.JSONField()
+ approver_scope = models.JSONField()
+ state = models.TextField()
+ decision_by = models.UUIDField(null=True, blank=True)
+ decision_at = models.DateTimeField(null=True, blank=True)
+ decision_reason = models.TextField(null=True, blank=True)
+ decided_args = models.JSONField(null=True, blank=True)
+ dispatch_outcome = models.JSONField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ expires_at = models.DateTimeField()
+
+ class Meta:
+ db_table = "agent_tool_approval_request"
+ constraints = [
+ models.CheckConstraint(
+ name="agent_tool_approval_request_state_valid",
+ condition=Q(
+ state__in=[
+ "queued",
+ "approving",
+ "dispatched",
+ "dispatched_failed",
+ "rejected",
+ "expired",
+ ]
+ ),
+ ),
+ models.UniqueConstraint(
+ fields=["session_id", "tool_name", "args_hash"],
+ condition=Q(state="queued"),
+ name="agent_tool_approval_request_queued_unique",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["state", "expires_at"], name="atar_expiry_idx"),
+ models.Index(fields=["team_id", "state", "-created_at"], name="atar_team_idx"),
+ models.Index(fields=["application_id", "state", "-created_at"], name="atar_app_idx"),
+ models.Index(fields=["session_id", "-created_at"], name="atar_session_idx"),
+ ]
+
+
+class AgentSessionCredential(ProductTeamModel):
+ """Per-session, TTL'd, encrypted-at-rest credential bag. Keyed 1:1 by session."""
+
+ # The node credential broker upserts by session_id only (no team_id in hand);
+ # the row is already team-scoped via its session. Allow null.
+ team_id = models.BigIntegerField(db_index=True, null=True) # type: ignore[assignment] # nullable override of ProductTeamModel.team_id (node writers omit it)
+ session_id = models.UUIDField(primary_key=True)
+ encrypted_credentials = models.TextField()
+ expires_at = models.DateTimeField()
+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
+ updated_at = models.DateTimeField(auto_now=True, db_default=Now())
+
+ class Meta:
+ db_table = "agent_session_credential"
+ indexes = [
+ models.Index(fields=["expires_at"], name="asc_expires_idx"),
+ ]
diff --git a/products/agent_platform/backend/presentation/__init__.py b/products/agent_platform/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.py
new file mode 100644
index 000000000000..f9e9c22aa703
--- /dev/null
+++ b/products/agent_platform/backend/presentation/serializers.py
@@ -0,0 +1,442 @@
+"""
+DRF serializers for the agent_platform authoring API.
+
+Two model serializers (Application, Revision) + a few request-body serializers
+for non-CRUD actions (set_env, promote). Bundle-upload + presigned-URL flow is
+deferred to the eventual MCP redesign (see TODO B5 in agent-shared).
+"""
+
+from __future__ import annotations
+
+import string
+import secrets
+from typing import Any
+
+from django.conf import settings
+from django.db import IntegrityError
+
+import jsonschema
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from posthog.models import User
+
+from ..logic.spec_schema import AGENT_SPEC_JSON_SCHEMA, AGENT_SPEC_JSON_SCHEMA_FOR_WRITE
+from ..models import AgentApplication, AgentRevision
+
+# Opaque random slug: leading letter (DNS-label-safe) + lowercase alphanumerics.
+# No dashes, so it can't be misread as the `<slug>-<revHex>` revision form, and
+# no name prefix — human-readable slugs are reserved for the explicit allowlist.
+_SLUG_ALPHABET = string.ascii_lowercase + string.digits
+_SLUG_LENGTH = 12
+
+
+def _mint_unique_slug() -> str:
+ """Mint a globally-unique opaque slug. The global partial unique index on
+ `slug` is the final guard; this pre-check keeps the common path off the
+ IntegrityError retry."""
+ for _ in range(10):
+ candidate = secrets.choice(string.ascii_lowercase) + "".join(
+ secrets.choice(_SLUG_ALPHABET) for _ in range(_SLUG_LENGTH - 1)
+ )
+ if not AgentApplication.all_teams.filter(slug=candidate, archived=False).exists():
+ return candidate
+ raise serializers.ValidationError("could not generate a unique slug; retry")
+
+
+# Shape of the resolved `created_by` object — exactly the fields the agent
+# console renders. Nullable: `created_by_id` may be unset (system rows) or
+# point at a since-deleted user.
+_CREATED_BY_SCHEMA = {
+ "type": "object",
+ "nullable": True,
+ "properties": {
+ "id": {"type": "integer"},
+ "first_name": {"type": "string"},
+ "email": {"type": "string", "format": "email"},
+ },
+}
+
+
+def _resolve_created_by(context: dict[str, Any], user_id: int | None) -> dict[str, Any] | None:
+ """Resolve a `created_by_id` (plain int — these are product-DB models with
+ no cross-DB FK to User) into a minimal user object. Cached per serializer
+ context so a list endpoint resolves each distinct user once."""
+ if not user_id:
+ return None
+ cache: dict[int, dict[str, Any] | None] = context.setdefault("_created_by_cache", {})
+ if user_id not in cache:
+ user = User.objects.filter(pk=user_id).only("id", "first_name", "email").first()
+ cache[user_id] = (
+ {"id": user.id, "first_name": user.first_name, "email": user.email} if user is not None else None
+ )
+ return cache[user_id]
+
+
+def _validate_mcp_tool_names_unique(spec: Any) -> None:
+ # JSON Schema's `uniqueItems` only compares whole-value equality, so it
+ # can't catch a bare string colliding with an object of the same `name`
+ # in `mcps[].external.tools[]`. Mirror the zod `.refine()` (same message)
+ # so the API rejects duplicates here instead of letting the runner blow up
+ # with a confusing Zod error at session open.
+ if not isinstance(spec, dict):
+ return
+ mcps = spec.get("mcps")
+ if not isinstance(mcps, list):
+ return
+ for i, mcp in enumerate(mcps):
+ if not isinstance(mcp, dict):
+ continue
+ tools = mcp.get("tools")
+ if not isinstance(tools, list):
+ continue
+ seen: set[str] = set()
+ for entry in tools:
+ name = entry if isinstance(entry, str) else entry.get("name") if isinstance(entry, dict) else None
+ if not isinstance(name, str):
+ continue
+ if name in seen:
+ raise serializers.ValidationError(f"spec.mcps.{i}.tools: mcps[].tools[] entries must have unique names")
+ seen.add(name)
+
+
+class AgentApplicationSerializer(serializers.ModelSerializer):
+ slack_events_url = serializers.SerializerMethodField(
+ help_text=(
+ "Public URL to paste into the Slack app dashboard under Event Subscriptions → Request URL. "
+ "Computed from the agent slug and the deployment's ingress routing mode "
+ "(`AGENT_INGRESS_DOMAIN_SUFFIX` in domain mode, `AGENT_INGRESS_PUBLIC_URL` in path mode). "
+ "Null when no public agent-ingress URL is configured (e.g. local dev without a tunnel)."
+ ),
+ )
+ slack_interactivity_url = serializers.SerializerMethodField(
+ help_text=(
+ "Public URL to paste into the Slack app dashboard under Interactivity & Shortcuts → Request URL. "
+ "Same source + null behaviour as `slack_events_url`."
+ ),
+ )
+ ingress_base_url = serializers.SerializerMethodField(
+ help_text=(
+ "Mode-aware base URL the agent's trigger routes hang off — append `/webhook`, `/run`, `/mcp`, etc. "
+ "Domain mode: `https://<slug><suffix>`; path mode: `<public_url>/agents/<slug>`. Same source + null "
+ "behaviour as `slack_events_url` (null when no public ingress URL is configured)."
+ ),
+ )
+ created_by = serializers.SerializerMethodField(
+ help_text="Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.",
+ )
+ # Optional on write: the server mints a globally-unique opaque slug unless
+ # the team is on AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS and supplies one.
+ # Always present on read.
+ slug = serializers.SlugField(
+ max_length=63,
+ required=False,
+ help_text=(
+ "Globally-unique URL identifier. Server-minted as an opaque random slug on create; "
+ "only allowlisted first-party teams may set it explicitly. Slugs live in one "
+ "global namespace (domain-mode ingress routing carries no team)."
+ ),
+ )
+
+ class Meta:
+ model = AgentApplication
+ fields = [
+ "id",
+ "team_id",
+ "name",
+ "slug",
+ "description",
+ "live_revision",
+ "archived",
+ "archived_at",
+ "created_by_id",
+ "created_by",
+ "created_at",
+ "updated_at",
+ "slack_events_url",
+ "slack_interactivity_url",
+ "ingress_base_url",
+ ]
+ # encrypted_env is set/cleared via the dedicated `set_env` action;
+ # never round-tripped through the standard CRUD payload.
+ read_only_fields = [
+ "id",
+ "team_id",
+ "live_revision",
+ "archived_at",
+ "created_by_id",
+ "created_at",
+ "updated_at",
+ "slack_events_url",
+ "slack_interactivity_url",
+ "ingress_base_url",
+ ]
+
+ @extend_schema_field(_CREATED_BY_SCHEMA)
+ def get_created_by(self, obj: AgentApplication) -> dict[str, Any] | None:
+ return _resolve_created_by(self.context, obj.created_by_id)
+
+ @extend_schema_field({"type": "string", "format": "uri", "nullable": True})
+ def get_slack_events_url(self, obj: AgentApplication) -> str | None:
+ return _slack_path_url(obj.slug, "events")
+
+ @extend_schema_field({"type": "string", "format": "uri", "nullable": True})
+ def get_slack_interactivity_url(self, obj: AgentApplication) -> str | None:
+ return _slack_path_url(obj.slug, "interactivity")
+
+ @extend_schema_field({"type": "string", "format": "uri", "nullable": True})
+ def get_ingress_base_url(self, obj: AgentApplication) -> str | None:
+ # Empty path → the base the routes hang off (`…/agents/<slug>` in path
+ # mode, `https://<slug><suffix>` in domain mode).
+ return agent_ingress_route_url(obj.slug, "")
+
+ def _explicit_slug_allowed(self, team_id: int | None) -> bool:
+ return team_id is not None and team_id in settings.AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS
+
+ def create(self, validated_data: dict[str, Any]) -> AgentApplication:
+ team_id = validated_data.get("team_id")
+ explicit_slug = validated_data.pop("slug", None)
+ if explicit_slug and self._explicit_slug_allowed(team_id):
+ validated_data["slug"] = explicit_slug
+ else:
+ validated_data["slug"] = _mint_unique_slug()
+ try:
+ return super().create(validated_data)
+ except IntegrityError as e:
+ raise serializers.ValidationError({"slug": "An agent with this slug already exists."}) from e
+
+ def update(self, instance: AgentApplication, validated_data: dict[str, Any]) -> AgentApplication:
+ # Slug is immutable except for allowlisted teams — renaming it would
+ # break the live agent's routing URLs. Drop any other team's attempt.
+ explicit_slug = validated_data.pop("slug", None)
+ if explicit_slug and explicit_slug != instance.slug and self._explicit_slug_allowed(instance.team_id):
+ validated_data["slug"] = explicit_slug
+ try:
+ return super().update(instance, validated_data)
+ except IntegrityError as e:
+ raise serializers.ValidationError({"slug": "An agent with this slug already exists."}) from e
+
+
+def agent_ingress_route_url(slug: str, path: str) -> str | None:
+ """Absolute URL of an agent's ingress route, matching what the deployed
+ ingress actually serves. Mode mirrors `AGENT_INGRESS_ROUTING_MODE` (and the
+ ingress's own `ROUTING_MODE`):
+
+ domain → ``https://<slug><suffix><path>`` (slug in host, routes at root)
+ path → ``<public_url>/agents/<slug><path>`` (slug in path)
+
+ `path` is the leading-slash route (e.g. `/slack/events`). Returns None when
+ the active mode's required setting is unset or `slug` is empty — the caller
+ omits the field, signalling "not externally reachable".
+ """
+ if not slug:
+ return None
+ if settings.AGENT_INGRESS_ROUTING_MODE == "domain":
+ suffix = (settings.AGENT_INGRESS_DOMAIN_SUFFIX or "").strip()
+ return f"https://{slug}{suffix}{path}" if suffix else None
+ base = (settings.AGENT_INGRESS_PUBLIC_URL or "").rstrip("/")
+ return f"{base}/agents/{slug}{path}" if base else None
+
+
+def _slack_path_url(slug: str, suffix: str) -> str | None:
+ return agent_ingress_route_url(slug, f"/slack/{suffix}")
+
+
+@extend_schema_field(AGENT_SPEC_JSON_SCHEMA)
+class AgentSpecField(serializers.JSONField):
+ """Spec JSON typed against `AGENT_SPEC_JSON_SCHEMA` so drf-spectacular
+ publishes the real shape downstream — generated TS types, MCP tool
+ descriptions, and the OpenAPI doc all see real fields instead of an
+ opaque `{}`."""
+
+
+class AgentRevisionSerializer(serializers.ModelSerializer):
+ spec = AgentSpecField(required=False, default=dict)
+ created_by = serializers.SerializerMethodField(
+ help_text="Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.",
+ )
+
+ @extend_schema_field(_CREATED_BY_SCHEMA)
+ def get_created_by(self, obj: AgentRevision) -> dict[str, Any] | None:
+ return _resolve_created_by(self.context, obj.created_by_id)
+
+ def validate_spec(self, value: Any) -> Any:
+ # Same shape the janitor's `AgentSpecSchema.parse` will reject on
+ # read. Catching it here turns a future 500 / process-level surprise
+ # into a clean 400 at write time.
+ try:
+ jsonschema.validate(value, AGENT_SPEC_JSON_SCHEMA_FOR_WRITE)
+ except jsonschema.ValidationError as e:
+ path = ".".join(str(p) for p in e.absolute_path) or "<root>"
+ raise serializers.ValidationError(f"spec.{path}: {e.message}") from e
+ _validate_mcp_tool_names_unique(value)
+ return value
+
+ class Meta:
+ model = AgentRevision
+ fields = [
+ "id",
+ "application",
+ "parent_revision",
+ "state",
+ "bundle_uri",
+ "bundle_sha256",
+ "spec",
+ "created_by_id",
+ "created_by",
+ "created_at",
+ "updated_at",
+ ]
+ # state transitions happen through promote / archive actions; spec is
+ # mutable only while state='draft' (enforced in the view).
+ read_only_fields = [
+ "id",
+ "application",
+ "state",
+ "bundle_sha256",
+ "created_by_id",
+ "created_at",
+ "updated_at",
+ ]
+ extra_kwargs = {
+ # The runner / janitor address bundles by revision_id; bundle_uri is
+ # the storage-prefix metadata. We default it server-side so MCP
+ # callers (and humans) creating a draft don't need to know about it.
+ "bundle_uri": {"required": False, "default": ""},
+ }
+
+
+class SetEnvRequestSerializer(serializers.Serializer):
+ """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.
+ """
+
+ env = serializers.DictField(child=serializers.CharField(allow_blank=True), allow_empty=True)
+
+
+class SetEnvKeyRequestSerializer(serializers.Serializer):
+ """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.
+ """
+
+ value = serializers.CharField(allow_blank=True, trim_whitespace=False)
+
+
+class PromoteRevisionRequestSerializer(serializers.Serializer):
+ """Body shape for AgentRevisionViewSet.promote.
+
+ Empty today — promote takes the calling revision's id from the URL and
+ flips it `ready → live`, updating the parent application's
+ `live_revision`. Left as a body-bearing endpoint so we can add fields
+ later (rollback target, audit comment) without changing the URL shape.
+ """
+
+
+class WriteAgentMdRequestSerializer(serializers.Serializer):
+ """Body shape for PUT /revisions/<id>/agent_md/."""
+
+ content = serializers.CharField(allow_blank=True, trim_whitespace=False)
+
+
+class WriteSpecRequestSerializer(serializers.Serializer):
+ """Body shape for PUT /revisions/<id>/spec/. The body's `spec` object
+ is the author-facing slice (skills/tools are server-derived at freeze)."""
+
+ spec = serializers.DictField(child=serializers.JSONField())
+
+
+class WriteSkillRequestSerializer(serializers.Serializer):
+ """Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored
+ at the canonical `skills/<skill_id>/SKILL.md` path in the bundle."""
+
+ description = serializers.CharField(
+ allow_blank=False,
+ trim_whitespace=False,
+ help_text="One-line summary shown in the skill index; the model uses it to decide when to load the skill.",
+ )
+ body = serializers.CharField(
+ allow_blank=True,
+ trim_whitespace=False,
+ help_text="The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",
+ )
+
+
+class WriteToolRequestSerializer(serializers.Serializer):
+ """Body shape for PUT /revisions/<id>/tools/<tool_id>/."""
+
+ description = serializers.CharField(allow_blank=False, trim_whitespace=False)
+ args_schema = serializers.DictField(child=serializers.JSONField())
+ source = serializers.CharField(allow_blank=False, trim_whitespace=False) # type: ignore[assignment] # field named `source` shadows DRF Field.source
+
+
+class WriteTypedBundleRequestSerializer(serializers.Serializer):
+ """Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed
+ payload. See docs/agent-platform/plans/typed-bundle-authoring-api.md §3."""
+
+ agent_md = serializers.CharField(allow_blank=True, trim_whitespace=False)
+ skills = serializers.ListField(child=WriteSkillRequestSerializer(), required=False, default=list)
+ tools = serializers.ListField(child=WriteToolRequestSerializer(), required=False, default=list)
+ spec = serializers.DictField(child=serializers.JSONField())
+
+ def to_internal_value(self, data: dict) -> dict:
+ """Skill / tool items carry an `id` field that the nested serializer
+ doesn't declare (it lives in the URL for the single-resource PUTs).
+ Stash + restore so the per-item validation still passes."""
+ skills = data.get("skills", [])
+ tools = data.get("tools", [])
+ skill_ids = [s.get("id") for s in skills]
+ tool_ids = [t.get("id") for t in tools]
+ # Strip ids so the inner serializers don't complain about unknowns.
+ stripped = {
+ **data,
+ "skills": [{k: v for k, v in s.items() if k != "id"} for s in skills],
+ "tools": [{k: v for k, v in t.items() if k != "id"} for t in tools],
+ }
+ out = super().to_internal_value(stripped)
+ # Reattach ids — janitor wants them.
+ out["skills"] = [{**s, "id": skill_ids[i]} for i, s in enumerate(out.get("skills", []))]
+ out["tools"] = [{**t, "id": tool_ids[i]} for i, t in enumerate(out.get("tools", []))]
+ return out
+
+
+class CloneFromRequestSerializer(serializers.Serializer):
+ """Body shape for POST /revisions/<id>/clone_from/ — copy every file
+ from `source_revision_id` into this (draft) revision."""
+
+ source_revision_id = serializers.UUIDField()
+
+
+class NewDraftRevisionRequestSerializer(serializers.Serializer):
+ """Body shape for POST /revisions/clone_from/ — atomically create a new
+ draft revision under `application_id` and clone its initial bundle from
+ `source_revision_id`. Convenience for the "edit live" flow so the MCP
+ doesn't have to do create-then-clone-from in two calls."""
+
+ application_id = serializers.UUIDField()
+ source_revision_id = serializers.UUIDField()
+
+
+class DecideApprovalRequestSerializer(serializers.Serializer):
+ """Body shape for POST /agent_applications/<id>/approvals/<approval_id>/decide/.
+
+ See docs/agent-platform/plans/approval-gated-tools.md."""
+
+ decision = serializers.ChoiceField(
+ choices=["approve", "reject"],
+ help_text="The approver's decision. `approve` runs the tool platform-side with the (possibly edited) args; `reject` records a terminal rejection and wakes the session with a synthetic rejected tool_result.",
+ )
+ edited_args = serializers.DictField(
+ child=serializers.JSONField(),
+ required=False,
+ help_text="Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422.",
+ )
+ reason = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Free-form approver note. Surfaces in the session's synthetic tool_result so the model can communicate the reason back to the user.",
+ )
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
new file mode 100644
index 000000000000..7c02d1b1c33a
--- /dev/null
+++ b/products/agent_platform/backend/presentation/views.py
@@ -0,0 +1,2791 @@
+"""
+DRF viewsets for agent_platform — the authoring surface.
+
+Two model viewsets + one catalog viewset:
+
+ AgentApplicationViewSet list / retrieve / create / update / destroy /
+ set_env
+ AgentRevisionViewSet list / retrieve / create (draft) / update_spec /
+ promote / archive + bundle proxy actions
+ (manifest, file, bundle, freeze, clone_from)
+ AgentNativeToolsViewSet list (read-only catalog of native tools)
+
+Bundle reads/writes are proxied to the agent-janitor node service which
+owns the actual BundleStore (FS in dev, S3 in prod). The Django layer keeps
+its team / scope / draft-only checks and forwards the body. See
+janitor_client.py for the wire protocol.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import json
+import logging
+from collections.abc import AsyncIterator, Callable
+from datetime import timedelta
+from functools import cached_property
+from typing import Any, cast
+from urllib.parse import urlencode
+from uuid import UUID
+
+from django.conf import settings
+from django.db import transaction
+from django.db.models import QuerySet
+from django.http import StreamingHttpResponse
+from django.utils import timezone
+
+import requests
+from asgiref.sync import sync_to_async
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import (
+ OpenApiParameter,
+ OpenApiResponse,
+ PolymorphicProxySerializer,
+ extend_schema,
+ extend_schema_field,
+ inline_serializer,
+)
+from rest_framework import (
+ renderers,
+ serializers as drf_serializers,
+ status,
+ viewsets,
+)
+from rest_framework.decorators import action
+from rest_framework.exceptions import APIException, NotFound, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.settings import api_settings
+
+from posthog.schema import ProductKey
+
+from posthog.api.log_entries import LogEntryRequestSerializer, LogEntrySerializer, fetch_log_entries
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.helpers.encrypted_fields import EncryptedTextField
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+from posthog.security.outbound_proxy import internal_requests
+
+from ..db import WRITER_DB
+from ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwt
+from ..logic.janitor_client import JanitorClient, JanitorClientError, default_client
+from ..logic.spec_schema import missing_required_secrets
+from ..models import AgentApplication, AgentRevision
+from .serializers import (
+ AgentApplicationSerializer,
+ AgentRevisionSerializer,
+ CloneFromRequestSerializer,
+ DecideApprovalRequestSerializer,
+ NewDraftRevisionRequestSerializer,
+ PromoteRevisionRequestSerializer,
+ SetEnvKeyRequestSerializer,
+ SetEnvRequestSerializer,
+ WriteAgentMdRequestSerializer,
+ WriteSkillRequestSerializer,
+ WriteSpecRequestSerializer,
+ WriteToolRequestSerializer,
+ WriteTypedBundleRequestSerializer,
+ agent_ingress_route_url,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _resolve_application(queryset: QuerySet, lookup_value: str | None) -> AgentApplication | None:
+ """Look up by UUID if the URL value parses as one, otherwise by slug.
+
+ Lets API consumers reference an application either by its stable id or by
+ the human-readable slug — both are unique within a team.
+ """
+ if lookup_value is None:
+ return None
+ try:
+ UUID(str(lookup_value))
+ field = "pk"
+ except (ValueError, TypeError):
+ field = "slug"
+ return queryset.filter(**{field: lookup_value}).first()
+
+
+def _janitor() -> JanitorClient:
+ """Indirection so tests can monkey-patch."""
+ return default_client()
+
+
+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
+ surface the janitor's body as the API response."""
+
+ status_code: int = status.HTTP_502_BAD_GATEWAY
+ default_detail = "Upstream janitor service error"
+ default_code = "janitor_upstream"
+
+ def __init__(self, e: JanitorClientError) -> None:
+ # Preserve 4xx mappings; clamp 5xx to a single 502 so we never leak
+ # the janitor's internal status (some are nominal like 503 = not
+ # configured, but the caller experience is "this isn't available").
+ upstream_code = e.status_code
+ if 400 <= upstream_code < 500:
+ self.status_code = upstream_code
+ # Flatten the body to a string. exceptions_hog's `_get_detail` walks
+ # `dict` details via `exception_key` and falls through to `value[0]`
+ # otherwise — passing a dict here raises `KeyError: 0` at render time.
+ # Prefer common janitor error fields; otherwise JSON-dump so callers
+ # still see the upstream payload.
+ if isinstance(e.body, dict):
+ msg = e.body.get("error") or e.body.get("detail") or e.body.get("message")
+ detail_str: str = msg if isinstance(msg, str) else json.dumps(e.body)
+ elif isinstance(e.body, str):
+ detail_str = e.body
+ else:
+ detail_str = e.message
+ super().__init__(detail=detail_str)
+
+
+# The `log_source` tag the agent runner stamps on every log_entries row.
+# Mirrors `AGENT_SESSION_LOG_SOURCE` in services/agent-shared/src/runtime/
+# log-sink.ts — keep both sides in sync.
+AGENT_SESSION_LOG_SOURCE = "agent_session"
+
+
+def _mint_preview_jwt(application: AgentApplication, revision: AgentRevision, user: Any) -> tuple[str, int] | None:
+ """Mint a short-lived HS256 JWT scoped to (app, rev) for non-live invokes.
+
+ Returns `(token, ttl_seconds)` or `None` when no shared signing key is
+ configured (dev / harness path — ingress's gate is then also bypassed).
+
+ Bound to (app, rev) so a captured token can't be replayed against a
+ different draft, and to `aud = agent-ingress.preview` so it can't be
+ replayed against any other agent-platform service. See
+ docs/agent-platform/plans/draft-preview-auth.md.
+ """
+ if not settings.AGENT_INTERNAL_SIGNING_KEY:
+ return None
+ ttl_seconds = 60
+ payload: dict[str, Any] = {
+ "app": str(application.id),
+ "rev": str(revision.id),
+ }
+ if user and getattr(user, "is_authenticated", False):
+ payload["sub"] = f"user:{user.id}"
+ token = encode_agent_internal_jwt(
+ payload,
+ timedelta(seconds=ttl_seconds),
+ AgentInternalAudience.INGRESS_PREVIEW,
+ )
+ return token, ttl_seconds
+
+
+# Per-trigger route catalogue. Mirrors the `path:` arrays in each
+# `services/agent-ingress/src/triggers/<type>.ts` `routes` export — keep
+# these tables in sync (a sibling test validates the chat one). Source of
+# truth is still the ingress; this is here so the preview-token caller
+# doesn't have to grep the ingress source to know which path to hit.
+_TRIGGER_ROUTES: dict[str, dict[str, str]] = {
+ "chat": {
+ "run": "/run",
+ "send": "/send",
+ "cancel": "/cancel",
+ "listen": "/listen",
+ "client_tool_result": "/client_tool_result",
+ },
+ "mcp": {
+ "rpc": "/mcp",
+ "stream": "/mcp/stream",
+ "connect_info": "/mcp/connect-info",
+ },
+ "slack": {
+ "events": "/slack/events",
+ "interactivity": "/slack/interactivity",
+ },
+ "webhook": {
+ "post": "/webhook",
+ },
+ # `cron` triggers have no externally-callable ingress endpoint —
+ # they fire from the janitor's scheduler. Omit from the catalogue
+ # so the preview response doesn't advertise a URL the caller can't
+ # actually hit.
+}
+
+
+def _build_preview_endpoints(ingress_slug: str, spec: dict[str, Any]) -> dict[str, dict[str, str]]:
+ """Return `{trigger_type: {route_name: absolute_url}}` for every
+ trigger the spec declares that has a public ingress route in
+ `_TRIGGER_ROUTES`. Empty when no public agent-ingress URL is configured
+ for the active routing mode (local dev without `bin/agent-tunnel`)."""
+ triggers = spec.get("triggers") or []
+ if not isinstance(triggers, list):
+ return {}
+ out: dict[str, dict[str, str]] = {}
+ for trigger in triggers:
+ if not isinstance(trigger, dict):
+ continue
+ ttype = trigger.get("type")
+ if not isinstance(ttype, str):
+ continue
+ routes = _TRIGGER_ROUTES.get(ttype)
+ if not routes:
+ continue
+ # First trigger of a given type wins; spec-side validation
+ # should already enforce uniqueness, but be defensive.
+ if ttype in out:
+ continue
+ urls = {name: agent_ingress_route_url(ingress_slug, path) for name, path in routes.items()}
+ if any(url is None for url in urls.values()):
+ return {}
+ out[ttype] = {name: url for name, url in urls.items() if url is not None}
+ return out
+
+
+def _build_preview_auth_info(spec: dict[str, Any]) -> dict[str, Any]:
+ """Surface the auth contract the caller has to satisfy when hitting
+ the endpoints above. Auth is per-trigger now, so report the accepted
+ modes keyed by trigger type. The preview-token gate is separate — the
+ caller almost always needs both."""
+ trigger_modes: dict[str, list[str]] = {}
+ triggers = spec.get("triggers") or []
+ if isinstance(triggers, list):
+ for trigger in triggers:
+ if not isinstance(trigger, dict):
+ continue
+ ttype = trigger.get("type")
+ auth = trigger.get("auth")
+ if not isinstance(ttype, str) or not isinstance(auth, dict):
+ continue
+ modes = auth.get("modes")
+ if not isinstance(modes, list):
+ continue
+ trigger_modes[ttype] = [m["type"] for m in modes if isinstance(m, dict) and isinstance(m.get("type"), str)]
+ return {
+ "preview_token_header": "x-agent-preview-token",
+ "preview_token_query": "preview_token",
+ "trigger_modes": trigger_modes,
+ "notes": (
+ "The preview-token in `token` gates revision routing only (it admits non-live "
+ "revisions). The ingress then ALSO enforces the auth modes declared on the trigger "
+ "you're hitting — look up the trigger in `trigger_modes`, pick one of its modes, and "
+ "attach the matching credential (Authorization: Bearer for posthog, x-posthog-internal "
+ "for posthog_internal, the named header for shared_secret). Public-auth triggers accept "
+ "anonymous; everything else needs a real credential alongside the preview-token."
+ ),
+ }
+
+
+def _build_preview_proxy_info(request: Request, application: AgentApplication) -> dict[str, Any]:
+ """Same-origin Django-side proxy. Convenient for browser SSE flows
+ where attaching preview-tokens to EventSource is awkward; not a
+ full replacement for the direct path because the proxy strips
+ caller Authorization (so it can't satisfy a trigger's non-public
+ auth modes)."""
+ team_id = application.team_id
+ proxy_base = (
+ f"{request.scheme}://{request.get_host()}"
+ f"/api/projects/{team_id}/agent_applications/{application.slug}/preview-proxy"
+ )
+ return {
+ "base": proxy_base,
+ "allowed_paths": sorted(AgentApplicationViewSet._PREVIEW_PROXY_ALLOWED_PATHS),
+ "notes": (
+ "Server-side proxy that mints the preview-token for you and forwards to ingress. "
+ "Strips caller Authorization / Cookie before forwarding, so it works for agents "
+ "whose hit trigger accepts anonymous (public) auth. Triggers with required auth "
+ "(`posthog` / `posthog_internal` / `shared_secret`) need the direct endpoints "
+ "above with a real credential attached."
+ ),
+ }
+
+
+class EventStreamRenderer(renderers.BaseRenderer):
+ """Lets DRF's content negotiation accept `Accept: text/event-stream`
+ requests (browser EventSource sends this) so they reach the view
+ instead of 406-ing in the negotiator. The streaming view returns
+ `StreamingHttpResponse` directly so this renderer's `render()` is
+ never actually invoked — its job is just to claim the media type."""
+
+ media_type = "text/event-stream"
+ format = "sse"
+ charset = "utf-8"
+
+ def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:
+ # StreamingHttpResponse path bypasses this, but if a non-streaming
+ # response ever lands here (e.g. an error), keep it valid SSE.
+ return str(data).encode(self.charset or "utf-8")
+
+
+# ── Conversation message variants ────────────────────────────────────
+# Module-level so `@extend_schema_field` can reference them. Mirrors
+# `ConversationMessage` (UserMessage | AssistantMessageRecord |
+# ToolResultMessage) in services/agent-shared/src/spec/spec.ts. Each
+# variant becomes its own named component in the generated TS; the
+# parent `_AgentConversationMessageField` ties them into a discriminated
+# union on `role`.
+
+_AGENT_USER_MESSAGE = inline_serializer(
+ name="AgentConversationUserMessage",
+ fields={
+ "role": drf_serializers.ChoiceField(choices=["user"]),
+ # Wire is `string | (TextContent|ImageContent)[]`. DRF can't
+ # express that as a single field — surface it as JSONField so
+ # the generated TS gets `unknown`; consumers narrow on read.
+ "content": drf_serializers.JSONField(
+ help_text="String shorthand, or array of {type:'text'|'image', ...} parts.",
+ ),
+ "timestamp": drf_serializers.IntegerField(help_text="Epoch milliseconds."),
+ },
+)
+_AGENT_ASSISTANT_MESSAGE = inline_serializer(
+ name="AgentConversationAssistantMessage",
+ fields={
+ "role": drf_serializers.ChoiceField(choices=["assistant"]),
+ "content": drf_serializers.ListField(
+ child=drf_serializers.JSONField(),
+ help_text="Array of text/thinking/toolCall parts.",
+ ),
+ "timestamp": drf_serializers.IntegerField(help_text="Epoch milliseconds."),
+ "api": drf_serializers.CharField(required=False),
+ "provider": drf_serializers.CharField(required=False),
+ "model": drf_serializers.CharField(required=False),
+ "usage": drf_serializers.DictField(child=drf_serializers.JSONField(), required=False),
+ "stopReason": drf_serializers.ChoiceField(
+ choices=["stop", "length", "toolUse", "error", "aborted"],
+ required=False,
+ ),
+ "errorMessage": drf_serializers.CharField(required=False),
+ },
+)
+_AGENT_TOOL_RESULT_MESSAGE = inline_serializer(
+ name="AgentConversationToolResultMessage",
+ fields={
+ "role": drf_serializers.ChoiceField(choices=["toolResult"]),
+ "toolCallId": drf_serializers.CharField(),
+ "toolName": drf_serializers.CharField(),
+ "content": drf_serializers.ListField(
+ child=drf_serializers.JSONField(),
+ help_text="Array of {type:'text'|'image', ...} parts.",
+ ),
+ "isError": drf_serializers.BooleanField(),
+ "timestamp": drf_serializers.IntegerField(help_text="Epoch milliseconds."),
+ },
+)
+
+
+@extend_schema_field(
+ PolymorphicProxySerializer(
+ component_name="AgentConversationMessage",
+ resource_type_field_name="role",
+ serializers={
+ "user": _AGENT_USER_MESSAGE,
+ "assistant": _AGENT_ASSISTANT_MESSAGE,
+ "toolResult": _AGENT_TOOL_RESULT_MESSAGE,
+ },
+ )
+)
+class _AgentConversationMessageField(drf_serializers.JSONField):
+ """JSONField whose OpenAPI schema is the discriminated union of the
+ three conversation-message variants. Runtime validation is JSONField's
+ default (any JSON); the typing only shapes the generated TS so the
+ frontend's `conversationToTurns` mapper gets a real narrowing on `role`."""
+
+ pass
+
+
+# Mirrors `SessionUsageTotal` in services/agent-shared/src/spec/spec.ts.
+# When that widens, widen this — MCP + frontend codegen pulls from here.
+_AGENT_SESSION_USAGE_TOTAL = inline_serializer(
+ name="AgentSessionUsageTotal",
+ fields={
+ "tokens_in": drf_serializers.IntegerField(),
+ "tokens_out": drf_serializers.IntegerField(),
+ "cache_read": drf_serializers.IntegerField(),
+ "cache_write": drf_serializers.IntegerField(),
+ "cost_input": drf_serializers.FloatField(),
+ "cost_output": drf_serializers.FloatField(),
+ "cost_cache_read": drf_serializers.FloatField(),
+ "cost_cache_write": drf_serializers.FloatField(),
+ "cost_total": drf_serializers.FloatField(),
+ },
+)
+
+# Principal kinds the runner stamps onto a session. Mirrors
+# `SessionPrincipal` in services/agent-shared/src/spec/spec.ts.
+_AGENT_SESSION_PRINCIPAL_KINDS = ["anonymous", "service", "internal", "shared_secret", "slack"]
+
+_AGENT_SESSION_PRINCIPAL = inline_serializer(
+ name="AgentSessionPrincipal",
+ fields={
+ "kind": drf_serializers.ChoiceField(
+ choices=_AGENT_SESSION_PRINCIPAL_KINDS,
+ help_text="What kind of principal authenticated the session start.",
+ ),
+ "id": drf_serializers.CharField(
+ required=False,
+ help_text="Stable identifier for the principal (PAT id, slack user id, etc). Absent for anonymous sessions.",
+ ),
+ "team_id": drf_serializers.IntegerField(
+ required=False,
+ help_text="Team the principal belongs to. Absent for anonymous sessions.",
+ ),
+ },
+ allow_null=True,
+)
+
+# Runtime `AgentSession.state` enum. Mirrors agent-shared spec.ts.
+_AGENT_SESSION_STATE_VALUES = ["queued", "running", "completed", "closed", "cancelled", "failed"]
+
+# Roll-up shape returned by the janitor's `/sessions/stats` and `/fleet/stats`
+# endpoints. Used both by the per-application action and the fleet viewset.
+_AGENT_AGGREGATE_STATS = inline_serializer(
+ name="AgentAggregateStats",
+ fields={
+ "liveCount": drf_serializers.IntegerField(
+ help_text="Sessions currently in a live state (queued / running).",
+ ),
+ "sessionsInWindowCount": drf_serializers.IntegerField(
+ help_text="Sessions created within the `since` window across all states.",
+ ),
+ "spendInWindowUsd": drf_serializers.FloatField(
+ help_text="Sum of `usage_total.cost_total` across sessions in the window.",
+ ),
+ "lastActivityAt": drf_serializers.DateTimeField(
+ allow_null=True,
+ help_text="ISO timestamp of the most recent session update — null when there are no sessions.",
+ ),
+ "failedInWindowCount": drf_serializers.IntegerField(
+ help_text="Sessions in `failed` state created within the window.",
+ ),
+ "pendingApprovalsCount": drf_serializers.IntegerField(
+ help_text=(
+ "Approval-gated tool requests across the team currently awaiting a decision. "
+ "0 on the per-application aggregate (which doesn't roll up approvals)."
+ ),
+ ),
+ },
+)
+
+
+@extend_schema(tags=["agent_platform"])
+class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """Agent applications — the deployable unit of the platform.
+
+ URLs:
+ GET /api/projects/<team>/agent_applications/ list
+ POST /api/projects/<team>/agent_applications/ create
+ GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ """
+
+ scope_object = "agents"
+ scope_object_write_actions = [
+ "create",
+ "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",
+ ]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "sessions_list",
+ "sessions_retrieve",
+ "session_logs",
+ "stats",
+ "env_keys_list",
+ # POST → `preview_proxy`, GET (SSE `listen`) → `preview_proxy_get`.
+ # DRF uses the bound function name as `view.action`, so the GET
+ # variant is its own entry in the scope-check map.
+ "preview_proxy",
+ "preview_proxy_get",
+ "preview_token",
+ "approvals_list",
+ "approvals_retrieve",
+ ]
+ serializer_class = AgentApplicationSerializer
+ queryset = AgentApplication.all_teams.all()
+
+ def _should_skip_parents_filter(self) -> bool:
+ # agent_platform is a product DB — models carry a plain `team_id` (no
+ # `team` FK), so the mixin's `project_id` → `team__project_id` rewrite
+ # can't resolve. Scope by `team_id` directly in safely_get_queryset.
+ return True
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return queryset.filter(team_id=self.team_id, archived=False)
+
+ def safely_get_object(self, queryset: QuerySet) -> AgentApplication | None:
+ return _resolve_application(queryset, self.kwargs[self.lookup_url_kwarg or self.lookup_field])
+
+ def perform_create(self, serializer: drf_serializers.BaseSerializer[Any]) -> None:
+ serializer.save(team_id=self.team_id, created_by_id=self.request.user.id)
+
+ def perform_destroy(self, instance: AgentApplication) -> None:
+ """Soft-delete: archived=True, archived_at=NOW. Preserves audit history."""
+ instance.archived = True
+ instance.archived_at = timezone.now()
+ instance.save(update_fields=["archived", "archived_at", "updated_at"])
+
+ @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.
+ # `webhook/<path>` and `slack/events` aren't included — those triggers
+ # need stable public URLs and don't fit a Django-mediated preview.
+ _PREVIEW_PROXY_ALLOWED_PATHS = frozenset({"run", "send", "cancel", "listen"})
+
+ _PREVIEW_PROXY_PARAMETERS = [
+ OpenApiParameter(
+ "rest",
+ OpenApiTypes.STR,
+ OpenApiParameter.PATH,
+ required=True,
+ description="Ingress sub-path under the agent slug. One of: `run`, `send`, `cancel`, `listen`.",
+ ),
+ OpenApiParameter(
+ "revision_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Target draft revision. Must belong to this application and not be live.",
+ ),
+ ]
+
+ @extend_schema(
+ operation_id="agent_applications_preview_proxy",
+ parameters=_PREVIEW_PROXY_PARAMETERS,
+ request=None,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path=r"preview-proxy/(?P<rest>[^/]+)",
+ # Include EventStreamRenderer so browser EventSource (Accept:
+ # text/event-stream) gets past DRF content negotiation and into
+ # the streaming view. The GET counterpart (`preview_proxy_get`)
+ # inherits this via `@preview_proxy.mapping.get`.
+ renderer_classes=[*api_settings.DEFAULT_RENDERER_CLASSES, EventStreamRenderer],
+ )
+ def preview_proxy(self, request: Request, rest: str = "", **kwargs) -> StreamingHttpResponse | Response:
+ """Authoring-side proxy for invoking a *draft* (or any non-live) revision.
+
+ Closes the anonymous-draft-invoke gap: the public ingress URL refuses
+ non-live invokes that don't carry the `x-agent-preview-secret` header;
+ this proxy attaches it after authenticating the Django caller. See
+ docs/agent-platform/plans/draft-preview-auth.md.
+
+ URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`
+ Auth: standard PAT / session — `agents:read` scope.
+ """
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+
+ if rest not in self._PREVIEW_PROXY_ALLOWED_PATHS:
+ raise ValidationError(
+ f"preview-proxy path '{rest}' is not allowed. Allowed: {sorted(self._PREVIEW_PROXY_ALLOWED_PATHS)}."
+ )
+
+ revision_id = request.query_params.get("revision_id")
+ if not revision_id:
+ raise ValidationError("revision_id query parameter is required for preview-proxy")
+ revision = AgentRevision.all_teams.filter(application=application, pk=revision_id).first()
+ if not revision:
+ raise NotFound("Revision not found in this application")
+ if application.live_revision_id == revision.id:
+ raise ValidationError(
+ "preview-proxy is for non-live revisions only; invoke the live revision via its public ingress URL"
+ )
+
+ ingress_base = os.environ.get("AGENT_INGRESS_URL", "http://localhost:3030").rstrip("/")
+ # Single URL contract for revision routing: `<slug>-<rev-hex>` in path
+ # mode (dev), `<rev-hex>.<slug>.<suffix>` in domain mode (prod). Django
+ # proxies via the path form using the full UUID hex (32 chars) so the
+ # ingress prefix lookup is unambiguous. See revision-routing.md.
+ rev_hex = revision.id.hex
+ # Defence-in-depth: the slug is interpolated into the upstream URL path,
+ # so reject anything that isn't a strict lowercase slug before building
+ # it — guards against a slug that reached the DB without the model /
+ # serializer validators (e.g. a raw node-side write).
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,61}[a-z0-9]?", application.slug):
+ raise ValidationError("Application slug contains unsafe characters")
+ forwarded_query = {k: v for k, v in request.query_params.items() if k != "revision_id"}
+ query_string = f"?{urlencode(forwarded_query)}" if forwarded_query else ""
+ upstream_url = f"{ingress_base}/agents/{application.slug}-{rev_hex}/{rest}{query_string}"
+
+ # Header set kept tight — caller's Authorization / Cookie / Host
+ # identify the *Django* caller, not the agent's caller. Don't leak.
+ skip_headers = {"host", "authorization", "cookie", "content-length"}
+ forwarded_headers: dict[str, str] = {k: v for k, v in request.headers.items() if k.lower() not in skip_headers}
+ # Same JWT the standalone `preview_token` action returns — pulled
+ # out into a helper so the two paths can't drift.
+ token_pair = _mint_preview_jwt(application, revision, request.user)
+ if token_pair is not None:
+ forwarded_headers["x-agent-preview-token"] = token_pair[0]
+
+ # DRF's parser already consumed request.body via request.data — we
+ # re-serialize the parsed payload so requests can ship a fresh body.
+ # Cheaper than re-reading the raw stream (which the parser exhausted).
+ body_bytes: bytes | None = None
+ if request.method in ("POST", "PUT", "PATCH"):
+ body_bytes = json.dumps(request.data).encode("utf-8") if request.data else b""
+ forwarded_headers["content-type"] = "application/json"
+ try:
+ # The ingress is an in-cluster service — use the internal session so the
+ # call bypasses HTTP(S)_PROXY (smokescreen blocks private IPs → 407).
+ upstream = internal_requests.request(
+ method=request.method or "GET",
+ url=upstream_url,
+ headers=forwarded_headers,
+ data=body_bytes,
+ stream=True,
+ timeout=30.0,
+ )
+ except requests.RequestException as e:
+ logger.exception("preview-proxy upstream call failed")
+ raise APIException(detail=f"preview-proxy upstream unreachable: {e}") from e
+
+ # Async iterator so Django's ASGI handler doesn't warn about consuming
+ # a sync generator. `requests` is blocking, so each chunk pull hops to
+ # a thread via sync_to_async.
+ async def _stream() -> AsyncIterator[bytes]:
+ sync_iter = upstream.iter_content(chunk_size=None)
+ sentinel = object()
+
+ def _next_chunk() -> object:
+ return next(sync_iter, sentinel)
+
+ try:
+ while True:
+ chunk = await sync_to_async(_next_chunk, thread_sensitive=False)()
+ if chunk is sentinel:
+ break
+ if chunk:
+ yield cast(bytes, chunk)
+ finally:
+ await sync_to_async(upstream.close, thread_sensitive=False)()
+
+ resp = StreamingHttpResponse(
+ _stream(),
+ status=upstream.status_code,
+ content_type=upstream.headers.get("Content-Type", "application/octet-stream"),
+ )
+ # Forward upstream response headers verbatim minus connection-control
+ # ones that Django handles itself.
+ skip_resp = {"content-length", "transfer-encoding", "connection", "content-type"}
+ for k, v in upstream.headers.items():
+ if k.lower() not in skip_resp:
+ resp[k] = v
+ return resp
+
+ # Same proxy, GET counterpart. Used for SSE (`listen`). Same body, just a
+ # different verb so drf-spectacular emits a distinct operation_id.
+ # Renderer set inherits from the parent `@action` (includes
+ # `EventStreamRenderer` so EventSource requests negotiate cleanly).
+ @extend_schema(
+ operation_id="agent_applications_preview_proxy_get",
+ parameters=_PREVIEW_PROXY_PARAMETERS,
+ request=None,
+ )
+ @preview_proxy.mapping.get
+ def preview_proxy_get(self, request: Request, rest: str = "", **kwargs) -> StreamingHttpResponse | Response:
+ """GET passthrough for the preview-proxy — used for `/listen` SSE."""
+ # `@action`-decorated method confuses mypy about the bound-method signature.
+ return self.preview_proxy(request, rest=rest, **kwargs) # type: ignore[arg-type]
+
+ # ── Preview token (direct-to-ingress flow) ───────────────────────
+ # Alternative to `preview_proxy`: returns a short-lived JWT the
+ # browser can attach to direct ingress calls. Console uses this
+ # for chat hops (SSE through the Django proxy is awkward — DRF
+ # content negotiation, redirects, body buffering all bite). The
+ # proxy action stays for non-browser callers that prefer
+ # server-side mediation. Both share `_mint_preview_jwt` so the
+ # JWT payload + secret can't drift between paths.
+
+ @extend_schema(
+ operation_id="agent_applications_preview_token",
+ parameters=[
+ OpenApiParameter(
+ "revision_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Target draft revision. Must belong to this application and not be live.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationPreviewTokenResponse",
+ fields={
+ "token": drf_serializers.CharField(
+ help_text="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.",
+ ),
+ "expires_in": drf_serializers.IntegerField(
+ help_text="Token TTL in seconds from issue. Clients should refresh before this elapses.",
+ ),
+ "ingress_slug": drf_serializers.CharField(
+ help_text="Slug to use in the ingress URL — `<application_slug>-<revision_uuid_hex>`. Identifies the exact revision, placed in the host (domain mode) or path (path mode) routing prefix.",
+ ),
+ "endpoints": drf_serializers.JSONField(
+ help_text="Per-trigger ingress URLs the caller can hit directly, derived from the revision's `spec.triggers[]`. Shape: `{<trigger_type>: {<route_name>: <absolute_url>}}`. Only includes triggers the spec actually declares. Empty when no public agent-ingress URL is configured for the active routing mode.",
+ ),
+ "auth": drf_serializers.JSONField(
+ help_text="How to attach credentials to those endpoints: preview-token header/query names, the per-trigger accepted auth modes (`trigger_modes`), and a note about the live vs preview-mode gate split. Lets the caller wire auth without grepping the ingress source.",
+ ),
+ "preview_proxy": drf_serializers.JSONField(
+ help_text="Server-side alternative — `/api/projects/<team>/agent_applications/<slug>/preview-proxy/<path>` mints the JWT for you. Strips caller Authorization, so it works for public-auth agents; agents with required auth need the direct endpoints above.",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="preview-token")
+ def preview_token(self, request: Request, **kwargs) -> Response:
+ """Mint a short-lived JWT for talking to a non-live revision
+ directly via the public ingress URL. The caller attaches it as
+ the `x-agent-preview-token` header (or `?preview_token=` query
+ param for `EventSource`). See `_mint_preview_jwt` for the
+ payload + claim binding.
+
+ The response also includes `endpoints`, `auth`, and
+ `preview_proxy` blocks so the caller can wire a preview
+ invocation without grepping the agent-ingress source for which
+ path each trigger exposes or which header name carries the
+ token. This is the "self-describing" half of preview-mode —
+ every piece of info you need to hit ingress is in one response.
+ """
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ revision_id = request.query_params.get("revision_id")
+ if not revision_id:
+ raise ValidationError("revision_id query parameter is required")
+ revision = AgentRevision.all_teams.filter(application=application, pk=revision_id).first()
+ if not revision:
+ raise NotFound("Revision not found in this application")
+ if application.live_revision_id == revision.id:
+ raise ValidationError(
+ "preview-token is for non-live revisions only; the live revision is reachable without a token via its public ingress URL"
+ )
+ token_pair = _mint_preview_jwt(application, revision, request.user)
+ ingress_slug = f"{application.slug}-{revision.id.hex}"
+ spec = revision.spec if isinstance(revision.spec, dict) else {}
+ body: dict[str, Any] = {
+ "token": token_pair[0] if token_pair is not None else "",
+ "expires_in": token_pair[1] if token_pair is not None else 0,
+ "ingress_slug": ingress_slug,
+ "endpoints": _build_preview_endpoints(ingress_slug, spec),
+ "auth": _build_preview_auth_info(spec),
+ "preview_proxy": _build_preview_proxy_info(request, application),
+ }
+ return Response(body)
+
+ @extend_schema(
+ operation_id="agent_applications_stats",
+ parameters=[
+ OpenApiParameter(
+ "since",
+ OpenApiTypes.DATETIME,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_AGENT_AGGREGATE_STATS),
+ description="Roll-up stats for the agent — drives the agent-detail overview tiles.",
+ )
+ @action(detail=True, methods=["get"], url_path="stats")
+ def stats(self, request: Request, **kwargs) -> Response:
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ try:
+ payload = _janitor().aggregate_for_application(
+ str(application.id),
+ since=request.query_params.get("since") or None,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_applications_sessions_list",
+ parameters=[
+ OpenApiParameter("limit", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ OpenApiParameter("offset", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ OpenApiParameter(
+ "state",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Filter by session state. Comma-separated list accepted "
+ "(e.g. `completed,failed`). Valid values: queued, running, "
+ "completed, closed, cancelled, failed."
+ ),
+ ),
+ OpenApiParameter(
+ "revision_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Only return sessions started against this specific revision.",
+ ),
+ OpenApiParameter(
+ "created_after",
+ OpenApiTypes.DATETIME,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="ISO datetime — return sessions with created_at >= this.",
+ ),
+ OpenApiParameter(
+ "created_before",
+ OpenApiTypes.DATETIME,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="ISO datetime — return sessions with created_at <= this.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationSessionsListResponse",
+ fields={
+ "results": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentSessionSummary",
+ fields={
+ "id": drf_serializers.UUIDField(),
+ "application_id": drf_serializers.UUIDField(),
+ "revision_id": drf_serializers.UUIDField(),
+ "state": drf_serializers.ChoiceField(choices=_AGENT_SESSION_STATE_VALUES),
+ "external_key": drf_serializers.CharField(allow_null=True),
+ "trigger_metadata": drf_serializers.DictField(
+ allow_null=True,
+ required=False,
+ help_text=(
+ "Trigger-specific metadata stamped at session creation. Shape varies "
+ "by trigger kind; cron firings carry "
+ "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
+ "Render this on session-detail so the operator can tell at a glance "
+ "that a session was fired by which cron / when."
+ ),
+ ),
+ "principal": _AGENT_SESSION_PRINCIPAL,
+ "turns": drf_serializers.IntegerField(
+ help_text="Count of messages in the conversation — the full transcript ships on the detail endpoint.",
+ ),
+ "preview": drf_serializers.CharField(
+ allow_null=True,
+ help_text="Last assistant text (~120 chars). Null for sessions with no assistant turns yet.",
+ ),
+ "usage_total": _AGENT_SESSION_USAGE_TOTAL,
+ "retry_count": drf_serializers.IntegerField(),
+ "created_at": drf_serializers.DateTimeField(),
+ "updated_at": drf_serializers.DateTimeField(),
+ },
+ ),
+ ),
+ "count": drf_serializers.IntegerField(help_text="Total matching sessions before pagination."),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="sessions")
+ def sessions_list(self, request: Request, **kwargs) -> Response:
+ """List sessions for this application, newest first. Strips the
+ conversation transcript from each summary, but includes a `preview`
+ (last assistant text, ~120 chars) and `usage_total` (token + cost
+ aggregate). Use `agent-applications-sessions-retrieve` for the full
+ transcript of a single session."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ limit_param = request.query_params.get("limit")
+ offset_param = request.query_params.get("offset")
+ try:
+ limit = int(limit_param) if limit_param is not None else None
+ offset = int(offset_param) if offset_param is not None else None
+ except ValueError:
+ raise ValidationError("limit and offset must be integers")
+ try:
+ payload = _janitor().list_sessions(
+ str(application.id),
+ limit=limit,
+ offset=offset,
+ state=request.query_params.get("state") or None,
+ revision_id=request.query_params.get("revision_id") or None,
+ created_after=request.query_params.get("created_after") or None,
+ created_before=request.query_params.get("created_before") or None,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_applications_sessions_retrieve",
+ parameters=[
+ OpenApiParameter(
+ "session_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.PATH,
+ required=True,
+ description="UUID of the session to fetch (must belong to this application).",
+ ),
+ OpenApiParameter(
+ "last_n",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "If set, return only the most recent N messages from the "
+ "conversation. `usage_total` is still computed over the "
+ "full session — only the transcript is trimmed. The "
+ "response includes `conversation_trimmed: true` and "
+ "`conversation_total_turns` so the caller knows how much "
+ "was hidden."
+ ),
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationSessionsRetrieveResponse",
+ fields={
+ "id": drf_serializers.UUIDField(),
+ "application_id": drf_serializers.UUIDField(),
+ "revision_id": drf_serializers.UUIDField(),
+ "team_id": drf_serializers.IntegerField(),
+ "external_key": drf_serializers.CharField(allow_null=True),
+ "trigger_metadata": drf_serializers.DictField(
+ allow_null=True,
+ required=False,
+ help_text=(
+ "Trigger-specific metadata stamped at session creation. Shape varies "
+ "by trigger kind; cron firings carry "
+ "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
+ "Render this on session-detail so the operator can tell at a glance "
+ "that a session was fired by which cron / when."
+ ),
+ ),
+ "state": drf_serializers.ChoiceField(choices=_AGENT_SESSION_STATE_VALUES),
+ "principal": _AGENT_SESSION_PRINCIPAL,
+ "conversation": drf_serializers.ListField(
+ child=_AgentConversationMessageField(),
+ help_text="Full transcript, or the trailing `last_n` messages if `?last_n=` was supplied.",
+ ),
+ "pending_inputs": drf_serializers.ListField(
+ child=_AgentConversationMessageField(),
+ help_text="Messages that arrived while a turn was in flight; drained into `conversation` at the start of the next turn.",
+ ),
+ "retry_count": drf_serializers.IntegerField(
+ help_text="Times the janitor has re-queued this session after a stuck-running detection.",
+ ),
+ "usage_total": _AGENT_SESSION_USAGE_TOTAL,
+ "created_at": drf_serializers.DateTimeField(),
+ "updated_at": drf_serializers.DateTimeField(),
+ "conversation_trimmed": drf_serializers.BooleanField(
+ help_text="True when `?last_n=` was supplied AND the full conversation exceeded it.",
+ ),
+ "conversation_total_turns": drf_serializers.IntegerField(
+ required=False,
+ help_text="Total messages in the untrimmed conversation. Present only when `conversation_trimmed=true`.",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="sessions/(?P<session_id>[^/.]+)")
+ def sessions_retrieve(self, request: Request, session_id: str = "", **kwargs) -> Response:
+ """Fetch one session's state — full conversation by default, or just
+ the trailing N messages with `?last_n=`. Always returns a
+ `usage_total` block aggregated over the entire session, regardless of
+ trim. The runner-side queue DB is the source of truth."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ last_n_param = request.query_params.get("last_n")
+ try:
+ last_n = int(last_n_param) if last_n_param is not None else None
+ except ValueError:
+ raise ValidationError("last_n must be a non-negative integer")
+ if last_n is not None and last_n < 0:
+ raise ValidationError("last_n must be a non-negative integer")
+ try:
+ payload = _janitor().get_session(session_id, last_n=last_n)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ # Cross-check ownership: the janitor doesn't know about teams. Reject
+ # if the session belongs to a different application than the URL says.
+ if payload.get("application_id") != str(application.id):
+ raise NotFound("Session not found")
+ return Response(payload)
+
+ # ── Per-session logs (ClickHouse) ────────────────────────────────
+ # The runner writes structured events via `KafkaLogSink` into the
+ # `log_entries` CH table, tagged with:
+ # log_source = "agent_session" (constant; see agent-shared/runtime/log-sink.ts)
+ # log_source_id = <application_id>
+ # instance_id = <session_id>
+ # We use the shared `fetch_log_entries` helper (also used by hog_function,
+ # hog_flow, batch_exports) for filter / paginate semantics.
+
+ @extend_schema(
+ operation_id="agent_applications_session_logs",
+ parameters=[
+ OpenApiParameter(
+ "session_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.PATH,
+ required=True,
+ description="UUID of the session whose logs to fetch.",
+ ),
+ LogEntryRequestSerializer,
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationSessionLogsResponse",
+ fields={
+ "results": LogEntrySerializer(many=True),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="sessions/(?P<session_id>[^/.]+)/logs")
+ def session_logs(self, request: Request, session_id: str = "", **kwargs) -> Response:
+ """Read the runner's structured event log for one session from
+ ClickHouse. Filters (limit / after / before / level / search)
+ match the shared `LogEntryMixin` helper used by hog_function +
+ hog_flow."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ # Every CH query needs `tag_queries(product, feature)` — without
+ # it the query layer raises `UntaggedQueryError`. There's no
+ # agent-specific ProductKey yet; LOGS is the closest fit.
+ tag_queries(product=ProductKey.LOGS, feature=Feature.QUERY)
+ params = LogEntryRequestSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ p = params.validated_data
+ rows = fetch_log_entries(
+ team_id=self.team_id,
+ log_source=AGENT_SESSION_LOG_SOURCE,
+ log_source_id=str(application.id),
+ instance_id=session_id,
+ limit=p["limit"],
+ after=p.get("after"),
+ before=p.get("before"),
+ search=p.get("search"),
+ level=p["level"].split(",") if p.get("level") else None,
+ )
+ return Response({"results": LogEntrySerializer(rows, many=True).data})
+
+ # ──────────────────────────── approval-gated tools ────────────────────────
+ # See docs/agent-platform/plans/approval-gated-tools.md.
+ #
+ # AGENT_DB is node-owned (per CLAUDE.md rule #2 in products/agent_platform).
+ # Django never queries `agent_tool_approval_request` directly — these
+ # actions auth-check on the Django side, then proxy through
+ # janitor_client. The janitor owns the wake path (markApproving + write
+ # marker into pending_inputs); the runner picks up on its next claim.
+
+ _APPROVAL_RESPONSE_FIELDS: dict[str, drf_serializers.Field] = {
+ "id": drf_serializers.UUIDField(help_text="Approval request UUID — stable, used in /approvals/<id>/decide."),
+ "session_id": drf_serializers.UUIDField(help_text="UUID of the session that proposed the gated call."),
+ "application_id": drf_serializers.UUIDField(help_text="UUID of the parent agent application."),
+ "team_id": drf_serializers.IntegerField(help_text="Team that owns the agent."),
+ "revision_id": drf_serializers.UUIDField(help_text="Revision the gated call was proposed against."),
+ "turn": drf_serializers.IntegerField(help_text="Turn number within the session that emitted the call."),
+ "tool_call_id": drf_serializers.CharField(
+ help_text="pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result."
+ ),
+ "tool_name": drf_serializers.CharField(help_text="Tool id the model invoked (e.g. `@posthog/team-delete`)."),
+ "proposed_args": drf_serializers.DictField(
+ child=drf_serializers.JSONField(),
+ help_text="Arguments the model proposed. Frozen at intercept time.",
+ ),
+ "decided_args": drf_serializers.DictField(
+ child=drf_serializers.JSONField(),
+ allow_null=True,
+ help_text="Approver-edited arguments. Present iff `approval_policy.allow_edit` was true and the approver supplied edits.",
+ ),
+ "assistant_message": drf_serializers.DictField(
+ child=drf_serializers.JSONField(),
+ help_text="Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning.",
+ ),
+ "approver_scope": drf_serializers.DictField(
+ child=drf_serializers.JSONField(),
+ help_text="Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.",
+ ),
+ "state": drf_serializers.ChoiceField(
+ choices=[
+ "queued",
+ "approving",
+ "dispatched",
+ "dispatched_failed",
+ "rejected",
+ "expired",
+ ],
+ help_text="Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.",
+ ),
+ "decision_by": drf_serializers.CharField(
+ allow_null=True,
+ help_text="UUID of the user who decided. Null while queued or expired.",
+ ),
+ "decision_at": drf_serializers.DateTimeField(
+ allow_null=True,
+ help_text="ISO timestamp of the decision. Null while queued.",
+ ),
+ "decision_reason": drf_serializers.CharField(
+ allow_null=True,
+ help_text="Free-form reason supplied by the approver. Optional.",
+ ),
+ "dispatch_outcome": drf_serializers.DictField(
+ child=drf_serializers.JSONField(),
+ allow_null=True,
+ help_text='`{result: ...}` on a successful approved dispatch, `{error: "..."}` when the tool threw. Null until the runner has finalised.',
+ ),
+ "created_at": drf_serializers.DateTimeField(help_text="When the model proposed the gated call."),
+ "expires_at": drf_serializers.DateTimeField(
+ help_text="When the queued request auto-rejects if no decision arrives."
+ ),
+ }
+
+ def _require_team_admin(self) -> None:
+ """Approval decisions are an admin-only surface in v0 (plan §6.1).
+ Listing / retrieving approvals does the same check so non-admins
+ can't browse what they can't act on.
+ """
+ membership = OrganizationMembership.objects.filter(
+ user=cast(User, self.request.user), organization_id=self.organization_id
+ ).first()
+ if membership is None or membership.level < OrganizationMembership.Level.ADMIN:
+ raise NotFound("Application not found")
+
+ @extend_schema(
+ operation_id="agent_applications_approvals_list",
+ parameters=[
+ OpenApiParameter(
+ "state",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Filter by approval state. Comma-separated list accepted. "
+ "Valid values: queued, approving, dispatched, "
+ "dispatched_failed, rejected, expired. Defaults to all states."
+ ),
+ ),
+ OpenApiParameter("limit", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ OpenApiParameter("offset", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApplicationApprovalsListResponse",
+ fields={
+ "results": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentApprovalRequest",
+ fields=_APPROVAL_RESPONSE_FIELDS,
+ ),
+ help_text="Approval requests for this application, newest first.",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="approvals")
+ def approvals_list(self, request: Request, **kwargs) -> Response:
+ """List approval-gated tool requests for this application. Team-admin
+ only (per plan §6.1). Default returns all states — pass `?state=queued`
+ for the inbox view."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ self._require_team_admin()
+ limit_param = request.query_params.get("limit")
+ offset_param = request.query_params.get("offset")
+ try:
+ limit = int(limit_param) if limit_param is not None else None
+ offset = int(offset_param) if offset_param is not None else None
+ except ValueError:
+ raise ValidationError("limit and offset must be integers")
+ try:
+ payload = _janitor().list_approvals(
+ str(application.id),
+ state=request.query_params.get("state") or None,
+ limit=limit,
+ offset=offset,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_applications_approvals_retrieve",
+ parameters=[
+ OpenApiParameter(
+ "approval_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.PATH,
+ required=True,
+ description="UUID of the approval request (must belong to this application).",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApprovalRequestDetail",
+ fields=_APPROVAL_RESPONSE_FIELDS,
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="approvals/(?P<approval_id>[^/.]+)")
+ def approvals_retrieve(self, request: Request, approval_id: str = "", **kwargs) -> Response:
+ """Single approval request — full proposed args, assistant snapshot,
+ decision metadata, dispatch outcome. Team-admin only (plan §6.1)."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ self._require_team_admin()
+ try:
+ payload = _janitor().get_approval(approval_id)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ # Cross-check ownership: the janitor doesn't know about teams.
+ if payload.get("application_id") != str(application.id):
+ raise NotFound("Approval not found")
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_applications_approvals_decide",
+ parameters=[
+ OpenApiParameter(
+ "approval_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.PATH,
+ required=True,
+ description="UUID of the approval request to decide.",
+ ),
+ ],
+ request=DecideApprovalRequestSerializer,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentApprovalsDecideResponse",
+ fields={
+ "ok": drf_serializers.BooleanField(help_text="Always `true` on a successful decision."),
+ "state": drf_serializers.CharField(
+ help_text="The approval row's new state — `approving` for approve, `rejected` for reject."
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="approvals/(?P<approval_id>[^/.]+)/decide")
+ def approvals_decide(self, request: Request, approval_id: str = "", **kwargs) -> Response:
+ """Approve or reject a queued tool-approval request. Team-admin only
+ (plan §6.1). The runtime side runs the tool platform-side on approve
+ and wakes the session with a synthetic tool_result either way."""
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ self._require_team_admin()
+ body = DecideApprovalRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ # Cross-check ownership before forwarding.
+ try:
+ existing = _janitor().get_approval(approval_id)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ if existing.get("application_id") != str(application.id):
+ raise NotFound("Approval not found")
+ if existing.get("approver_scope", {}).get("allow_agent_approver") is False and not getattr(
+ request.user, "is_authenticated", False
+ ):
+ # PATs / service tokens are rejected unless the spec opts in.
+ # Real PAT-vs-user discrimination would go here; for v0 we rely
+ # on Django auth + the admin check above as a coarse filter.
+ raise NotFound("Approval not found")
+ try:
+ payload = _janitor().decide_approval(
+ approval_id,
+ decision=body.validated_data["decision"],
+ # decision_by is a UUID column — send the user's uuid, not the
+ # integer pk (which fails as "invalid input syntax for type uuid").
+ decided_by=str(request.user.uuid) if request.user and request.user.is_authenticated else "",
+ edited_args=body.validated_data.get("edited_args"),
+ reason=body.validated_data.get("reason"),
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+
+@extend_schema(tags=["agent_platform"])
+class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """Revisions of an agent. Created in `draft`, promoted through
+ `ready → live` once the bundle has been uploaded + frozen.
+
+ URLs (nested under an application):
+
+ Model CRUD:
+ GET .../revisions/ list
+ POST .../revisions/ create draft
+ GET .../revisions/<id>/ retrieve
+ PATCH .../revisions/<id>/ update spec (draft only)
+
+ Lifecycle:
+ POST .../revisions/<id>/promote/ ready → live
+ POST .../revisions/<id>/archive/ → archived
+ POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ POST .../revisions/new_draft/ create draft + clone_from atomically
+
+ Bundle authoring (proxied to the janitor):
+ GET .../revisions/<id>/manifest/ list paths + sha256
+ GET .../revisions/<id>/file/?path=… read one file
+ PUT .../revisions/<id>/file/?path=… write one file (draft)
+ DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ GET .../revisions/<id>/bundle/ bulk pull all files
+ PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ """
+
+ scope_object = "agents" # share the parent's scope
+ # AgentRevision is tenant-scoped via its parent application, not directly.
+ # The URL kwarg `project_id` from the parent router defaults to filtering
+ # `team__project_id` on the queryset, but AgentRevision only has
+ # `application__team__project_id`. Rewrite the parent lookup accordingly.
+ filter_rewrite_rules = {"project_id": "application__team__project_id"}
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "promote",
+ "archive",
+ "freeze",
+ "clone_from",
+ "new_draft",
+ "put_bundle",
+ "put_agent_md",
+ "put_spec",
+ "put_skill",
+ "delete_skill",
+ "put_tool",
+ "delete_tool",
+ "cron_fire",
+ ]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "manifest",
+ "slack_manifest",
+ "get_bundle",
+ "validate",
+ "system_prompt",
+ ]
+ serializer_class = AgentRevisionSerializer
+ queryset = AgentRevision.all_teams.all()
+
+ def get_application(self) -> AgentApplication:
+ # drf-extensions nested routing passes the parent URL kwarg as
+ # `parent_lookup_application_id` (see `parents_query_lookups` in the
+ # nested router registration in posthog/api/__init__.py).
+ app = _resolve_application(
+ AgentApplication.all_teams.filter(team_id=self.team_id, archived=False),
+ self.kwargs.get("parent_lookup_application_id") or self.kwargs.get("application_id"),
+ )
+ if app is None:
+ raise NotFound("Application not found")
+ return app
+
+ def _should_skip_parents_filter(self) -> bool:
+ # Product-DB model (plain team_id, no team FK). Scoping is via the
+ # application filter below — get_application() resolves it team-scoped.
+ return True
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return queryset.filter(application=self.get_application())
+
+ @cached_property
+ def parents_query_dict(self) -> dict[str, Any]:
+ # The mixin auto-filters by every parent URL kwarg as a literal value
+ # (e.g. `application_id="hello"`). Our parent supports slug-or-UUID
+ # via `_resolve_application`, so a slug in the URL otherwise blows up
+ # with "'hello' is not a valid UUID". Override the cached lookup dict
+ # to substitute the resolved PK before super filters.
+ result = super().parents_query_dict
+ raw = result.get("application_id")
+ if raw is None:
+ return result
+ try:
+ UUID(str(raw))
+ return result
+ except (ValueError, TypeError):
+ return {**result, "application_id": str(self.get_application().id)}
+
+ def perform_create(self, serializer: drf_serializers.BaseSerializer[Any]) -> None:
+ application = self.get_application()
+ # Fresh revisions start in `draft`. Parent revision is optional — if
+ # set, this revision can later be diff'd against it for review.
+ serializer.save(
+ application=application,
+ team_id=application.team_id,
+ state="draft",
+ created_by_id=self.request.user.id,
+ )
+
+ def update(self, request: Request, *args, **kwargs) -> Response:
+ """Spec edits are only allowed while state='draft'. Once promoted to
+ ready/live the spec is frozen — change requires a new revision."""
+ instance: AgentRevision = self.get_object()
+ if instance.state != "draft":
+ raise ValidationError(f"Cannot edit spec on a {instance.state} revision; create a new draft instead.")
+ return super().update(request, *args, **kwargs)
+
+ @extend_schema(request=PromoteRevisionRequestSerializer)
+ @action(detail=True, methods=["post"], url_path="promote")
+ def promote(self, request: Request, **kwargs) -> Response:
+ """ready → live. Sets the parent application's live_revision."""
+ revision: AgentRevision = self.get_object()
+ body = PromoteRevisionRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+
+ if revision.state == "live":
+ return Response({"ok": True, "state": "live", "no_op": True})
+ if revision.state != "ready":
+ raise ValidationError(f"Revision is in state '{revision.state}'; only 'ready' can be promoted.")
+ if not revision.bundle_sha256:
+ raise ValidationError("Revision has no frozen bundle (bundle_sha256 is null).")
+
+ application = revision.application
+
+ # 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)
+ missing = missing_required_secrets(revision.spec or {}, env_map)
+ if missing:
+ details = ", ".join(f"{m['key']} (for {m['trigger']} trigger)" for m in missing)
+ raise ValidationError(
+ f"Cannot promote: agent is missing required encrypted_env entries: {details}. "
+ f"Set the value(s) via the env editor then retry."
+ )
+
+ # All three writes — demote previous live, set this live, point the
+ # application — must succeed or fail together. select_for_update on
+ # the application row serializes concurrent promotes so two callers
+ # can't both archive the same predecessor or land both revisions in
+ # state="live" with the application pointing at only one.
+ with transaction.atomic(using=WRITER_DB):
+ application = (
+ AgentApplication.all_teams.using(WRITER_DB).select_for_update().get(pk=revision.application_id)
+ )
+ previously_live = application.live_revision
+ if previously_live and previously_live.id != revision.id:
+ previously_live.state = "archived"
+ previously_live.save(update_fields=["state", "updated_at"])
+ revision.state = "live"
+ revision.save(update_fields=["state", "updated_at"])
+ application.live_revision = revision
+ application.save(update_fields=["live_revision", "updated_at"])
+ return Response({"ok": True, "state": "live"})
+
+ @extend_schema(request=None)
+ @action(detail=True, methods=["post"], url_path="archive")
+ def archive(self, request: Request, **kwargs) -> Response:
+ """Mark a revision archived. If it was the live one, clear the
+ application's live_revision pointer (the app effectively has no
+ deployable version until another revision is promoted)."""
+ revision: AgentRevision = self.get_object()
+ if revision.state == "archived":
+ return Response({"ok": True, "no_op": True})
+ # Same atomic+lock shape as promote — without it, a concurrent
+ # promote could read the pre-archive `live_revision` and overwrite
+ # our clear, leaving the application pointed at an archived row.
+ with transaction.atomic(using=WRITER_DB):
+ application = (
+ AgentApplication.all_teams.using(WRITER_DB).select_for_update().get(pk=revision.application_id)
+ )
+ revision.state = "archived"
+ revision.save(update_fields=["state", "updated_at"])
+ if application.live_revision_id == revision.id:
+ application.live_revision = None
+ application.save(update_fields=["live_revision", "updated_at"])
+ return Response({"ok": True, "state": "archived"})
+
+ # ── Bundle proxy actions ───────────────────────────────────────────────
+
+ def _call(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
+ """Wrap a janitor call: map upstream errors into DRF responses."""
+ try:
+ return fn(*args, **kwargs)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+
+ @extend_schema(request=None)
+ @action(detail=True, methods=["get"], url_path="manifest")
+ def manifest(self, request: Request, **kwargs) -> Response:
+ """List every file in this revision's bundle (path, size, sha256)."""
+ revision: AgentRevision = self.get_object()
+ return Response(self._call(_janitor().manifest, str(revision.id)))
+
+ @extend_schema(
+ operation_id="agent_applications_revisions_slack_manifest",
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionSlackManifestResponse",
+ fields={
+ "revision_id": drf_serializers.UUIDField(),
+ "manifest": drf_serializers.JSONField(
+ help_text=(
+ "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."
+ )
+ ),
+ "notes": drf_serializers.ListField(
+ child=drf_serializers.CharField(),
+ help_text="Reminders the manifest can't enforce (e.g. invite the bot to its channels).",
+ ),
+ "events_url": drf_serializers.CharField(
+ allow_null=True, help_text="The Event Subscriptions Request URL baked into the manifest."
+ ),
+ "interactivity_url": drf_serializers.CharField(
+ allow_null=True, help_text="The Interactivity Request URL (used by approval-gated tools)."
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="slack_manifest")
+ def slack_manifest(self, request: Request, **kwargs) -> Response:
+ """Build a Slack app manifest for this revision's slack trigger.
+
+ Deterministic: the OAuth scopes and bot event subscriptions are derived
+ from the slack trigger config (`mention_only` / `auto_resume_threads` /
+ `ack_reaction`) and the agent's Slack tools, so the manifest already
+ subscribes to exactly the events the config needs. 400 if the revision
+ has no slack trigger.
+ """
+ revision: AgentRevision = self.get_object()
+ slug = revision.application.slug
+ events_url = agent_ingress_route_url(slug, "/slack/events")
+ interactivity_url = agent_ingress_route_url(slug, "/slack/interactivity")
+ result = self._call(
+ _janitor().slack_manifest,
+ str(revision.id),
+ events_url=events_url,
+ interactivity_url=interactivity_url,
+ )
+ return Response({**result, "events_url": events_url, "interactivity_url": interactivity_url})
+
+ # DRF routes the typed bundle verbs across @action + .mapping.<verb>
+ # chains. Three separate @action decorators with the same url_path
+ # don't merge — the last one registered wins and the others 405. So
+ # GET+PUT under /bundle/, PUT+DELETE under /skills/<id>/ and
+ # /tools/<id>/ share a single @action with mapping chains below.
+
+ # ── typed bundle authoring API ──────────────────────────────────────
+ # See docs/agent-platform/plans/typed-bundle-authoring-api.md. Django
+ # is a thin proxy: every byte of the payload flows through to the
+ # janitor unchanged. The legacy file-grain endpoints (file/, bundle/
+ # with mode) were removed.
+
+ @extend_schema(request=None)
+ @action(detail=True, methods=["get"], url_path="bundle")
+ def get_bundle(self, request: Request, **kwargs) -> Response:
+ """Read the full typed bundle: `{ agent_md, skills, tools, spec }`."""
+ revision: AgentRevision = self.get_object()
+ return Response(self._call(_janitor().get_bundle, str(revision.id)))
+
+ @extend_schema(request=WriteTypedBundleRequestSerializer)
+ @get_bundle.mapping.put
+ def put_bundle(self, request: Request, **kwargs) -> Response:
+ """Full-replace the typed bundle. Anything not in the payload is
+ deleted. Tool sources are AST-checked + esbuild-compiled by the
+ janitor before any S3 writes."""
+ revision: AgentRevision = self.get_object()
+ body = WriteTypedBundleRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ return Response(self._call(_janitor().put_bundle, str(revision.id), body.validated_data))
+
+ @extend_schema(request=WriteAgentMdRequestSerializer)
+ @action(detail=True, methods=["put"], url_path="agent_md")
+ def put_agent_md(self, request: Request, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ body = WriteAgentMdRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ return Response(self._call(_janitor().put_agent_md, str(revision.id), body.validated_data["content"]))
+
+ @extend_schema(request=WriteSpecRequestSerializer)
+ @action(detail=True, methods=["put"], url_path="spec")
+ def put_spec(self, request: Request, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ body = WriteSpecRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ return Response(self._call(_janitor().put_spec, str(revision.id), body.validated_data["spec"]))
+
+ @extend_schema(request=WriteSkillRequestSerializer)
+ @action(detail=True, methods=["put"], url_path=r"skills/(?P<skill_id>[a-z0-9][a-z0-9_-]*)")
+ def put_skill(self, request: Request, skill_id: str, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ body = WriteSkillRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ return Response(self._call(_janitor().put_skill, str(revision.id), skill_id, body.validated_data))
+
+ @extend_schema(request=None)
+ @put_skill.mapping.delete
+ def delete_skill(self, request: Request, skill_id: str, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ return Response(self._call(_janitor().delete_skill, str(revision.id), skill_id))
+
+ @extend_schema(request=WriteToolRequestSerializer)
+ @action(detail=True, methods=["put"], url_path=r"tools/(?P<tool_id>[a-z0-9][a-z0-9_-]*)")
+ def put_tool(self, request: Request, tool_id: str, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ body = WriteToolRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ return Response(self._call(_janitor().put_tool, str(revision.id), tool_id, body.validated_data))
+
+ @extend_schema(request=None)
+ @put_tool.mapping.delete
+ def delete_tool(self, request: Request, tool_id: str, **kwargs) -> Response:
+ revision: AgentRevision = self.get_object()
+ return Response(self._call(_janitor().delete_tool, str(revision.id), tool_id))
+
+ @extend_schema(
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionValidateResponse",
+ fields={
+ "ok": drf_serializers.BooleanField(),
+ "revision_id": drf_serializers.UUIDField(),
+ "revision_state": drf_serializers.CharField(),
+ "errors": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentRevisionValidationError",
+ fields={
+ "code": drf_serializers.CharField(),
+ "message": drf_serializers.CharField(),
+ "pointer": drf_serializers.CharField(),
+ },
+ ),
+ ),
+ "resolved_natives": drf_serializers.ListField(child=drf_serializers.CharField()),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="validate")
+ def validate(self, request: Request, **kwargs) -> Response:
+ """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
+ `{ 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
+ for i, secret_name in enumerate(revision.spec.get("secrets") or []):
+ if secret_name not in available_keys:
+ errors.append(
+ {
+ "code": "missing_secret",
+ "message": f'secret "{secret_name}" is not set in the application env',
+ "pointer": f"spec.secrets[{i}]",
+ }
+ )
+ report["errors"] = errors
+ report["ok"] = len(errors) == 0
+ return Response(report)
+
+ @extend_schema(
+ request=inline_serializer(
+ name="AgentRevisionCronFireRequest",
+ fields={
+ "cron_name": drf_serializers.CharField(
+ help_text="`name` of the cron trigger in `spec.triggers[]` to fire.",
+ ),
+ "request_id": drf_serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Stable client-supplied id so repeated clicks of the same UI 'Fire now' "
+ "button resolve to the same session id rather than firing twice. The "
+ "janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit "
+ "to fire unconditionally — every call generates a fresh UUID."
+ ),
+ ),
+ },
+ ),
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionCronFireResponse",
+ fields={
+ "ok": drf_serializers.BooleanField(),
+ "session_id": drf_serializers.UUIDField(
+ help_text="ID of the session the cron firing created (or returned, on dedupe).",
+ ),
+ "fired_at": drf_serializers.CharField(
+ help_text="ISO-8601 timestamp the firing was attributed to.",
+ ),
+ "idempotency_key": drf_serializers.CharField(
+ help_text=(
+ "Composed dedupe key — `cron-manual:<rev>:<name>:<request_id>`. "
+ "Returned so the UI can correlate."
+ ),
+ ),
+ "request_id": drf_serializers.CharField(
+ help_text="The request id the firing used (echoed back, or freshly minted).",
+ ),
+ },
+ ),
+ description="Cron job was fired (or deduped to an existing session).",
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="cron/fire")
+ def cron_fire(self, request: Request, **kwargs) -> Response:
+ """Fire one cron job out-of-band — the same execution path the
+ scheduler walks, but on demand. Authoring UX: the user iterates on
+ a cron prompt by clicking 'Fire now' rather than waiting for the
+ next scheduled firing. Without this, 'did my prompt do the right
+ thing?' is unanswerable until the cron actually fires.
+
+ Idempotent via `request_id`: repeat clicks with the same id resolve
+ to the same session id rather than firing N times. See
+ `docs/agent-platform/plans/cron-trigger-scheduler.md` §9.
+ """
+ revision: AgentRevision = self.get_object()
+ cron_name = request.data.get("cron_name")
+ if not isinstance(cron_name, str) or not cron_name:
+ raise ValidationError({"cron_name": "required"})
+ request_id_raw = request.data.get("request_id")
+ request_id = request_id_raw if isinstance(request_id_raw, str) and request_id_raw else None
+ return Response(self._call(_janitor().cron_fire, str(revision.id), cron_name=cron_name, request_id=request_id))
+
+ @extend_schema(
+ operation_id="agent_applications_revisions_system_prompt",
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentRevisionSystemPromptResponse",
+ fields={
+ "revision_id": drf_serializers.UUIDField(
+ help_text="UUID of the revision the prompt was rendered for.",
+ ),
+ "framework_prompt_version": drf_serializers.IntegerField(
+ help_text=(
+ "Active framework preamble version. Bumps when the "
+ "platform's `# Platform guidance` content changes "
+ "meaningfully (decision rules, sections renamed, "
+ "behavioural defaults flipped). Authors can pin to "
+ "a specific version via `spec.framework_prompt.version_pin`."
+ ),
+ ),
+ "system_prompt": drf_serializers.CharField(
+ help_text=(
+ "Fully-assembled system prompt the runner would pass "
+ "to pi-ai for a session against this revision. "
+ "Concatenates the platform framework preamble, the "
+ "bundle's `agent.md` (or `spec.entrypoint`), and the "
+ "skills index. Inspect before promotion to confirm "
+ "the model will see what you expect — see "
+ "docs/agent-platform/plans/framework-system-prompt.md §4."
+ ),
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="system_prompt")
+ def system_prompt(self, request: Request, **kwargs) -> Response:
+ """Return the fully-assembled system prompt for this revision.
+
+ Authoring tools call this to preview what the model will actually
+ see at session start — the platform framework preamble plus the
+ bundle's `agent.md` plus the skills index. Useful for debugging
+ author-vs-framework precedence conflicts and verifying
+ `spec.framework_prompt.omit` overrides took effect.
+ """
+ revision: AgentRevision = self.get_object()
+ result = self._call(_janitor().get_system_prompt, str(revision.id))
+ return Response(result)
+
+ @extend_schema(request=None)
+ @action(detail=True, methods=["post"], url_path="freeze")
+ def freeze(self, request: Request, **kwargs) -> Response:
+ """Freeze the bundle: draft → ready, stamps sha256 on the row.
+
+ Django is a thin proxy here: resolve template refs into the
+ bundle, ask the janitor to seal it (the janitor returns the sha
+ + the spec it derived from the typed resources), then stamp the
+ row. No `transaction.atomic()` — the janitor's freeze is idempotent
+ (on retry it re-reads the existing `.frozen` marker + re-derives
+ spec), so a partial failure here is recoverable by re-calling
+ freeze, not by transactional rollback. Holding an atomic block
+ across the janitor HTTP call previously deadlocked the
+ agent_revision row against the janitor's spec write — that's
+ moved off the janitor side as part of the same fix.
+ """
+ revision: AgentRevision = self.get_object()
+ # Only a draft can be frozen. Without this guard a freeze against an
+ # archived/live revision would overwrite its state to "ready" — leaving
+ # `application.live_revision` pointing at a now-"ready" row, which the
+ # promote path doesn't expect. Mirrors the `update()` non-draft guard.
+ if revision.state != "draft":
+ raise ValidationError(f"Cannot freeze a {revision.state} revision; only 'draft' can be frozen.")
+ janitor_client = _janitor()
+ # Skill / custom-tool template pinning (freeze_templates_into_bundle) is
+ # disabled pending a registry rethink — see the commented-out template
+ # routes in routes.py.
+ result = self._call(janitor_client.freeze, str(revision.id))
+ revision.state = "ready"
+ revision.bundle_sha256 = result["bundle_sha256"]
+ derived_spec = result.get("derived_spec")
+ if derived_spec is not None:
+ revision.spec = derived_spec
+ revision.save(update_fields=["state", "bundle_sha256", "spec"])
+ else:
+ revision.save(update_fields=["state", "bundle_sha256"])
+ revision.refresh_from_db()
+ return Response(
+ {
+ **result,
+ "revision": AgentRevisionSerializer(revision).data,
+ }
+ )
+
+ @extend_schema(request=CloneFromRequestSerializer)
+ @action(detail=True, methods=["post"], url_path="clone_from")
+ def clone_from(self, request: Request, **kwargs) -> Response:
+ """Copy every file from `source_revision_id` into this revision."""
+ revision: AgentRevision = self.get_object()
+ body = CloneFromRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ source_id = str(body.validated_data["source_revision_id"])
+ # Guard against cross-app cloning — the source must belong to the same
+ # team. The janitor doesn't enforce this since it trusts Django.
+ source = AgentRevision.all_teams.filter(application__team_id=self.team_id, pk=source_id).first()
+ if source is None:
+ raise NotFound("Source revision not found in this team.")
+ return Response(self._call(_janitor().clone_from, str(revision.id), source_id))
+
+ @extend_schema(request=NewDraftRevisionRequestSerializer)
+ @action(detail=False, methods=["post"], url_path="new_draft")
+ def new_draft(self, request: Request, **kwargs) -> Response:
+ """Create a fresh draft revision under `application_id` and seed it
+ from `source_revision_id`. Saves the MCP one round-trip vs the
+ explicit create + clone_from sequence."""
+ body = NewDraftRevisionRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ application_id = str(body.validated_data["application_id"])
+ source_id = str(body.validated_data["source_revision_id"])
+
+ application = AgentApplication.all_teams.filter(team_id=self.team_id, pk=application_id, archived=False).first()
+ if application is None:
+ raise NotFound("Application not found in this team.")
+ source = AgentRevision.all_teams.filter(application__team_id=self.team_id, pk=source_id).first()
+ if source is None:
+ raise NotFound("Source revision not found in this team.")
+
+ # bundle_uri convention: the runner-side bundle store resolves this.
+ # In dev/CI we use a filesystem prefix derived from the app + new
+ # revision id; prod swaps in the team's S3 prefix at deploy time.
+ draft = AgentRevision.all_teams.create(
+ application=application,
+ team_id=application.team_id,
+ parent_revision=source,
+ created_by_id=self.request.user.id,
+ state="draft",
+ bundle_uri=source.bundle_uri, # same bundle root; janitor scopes by revision_id
+ spec=source.spec,
+ )
+ # 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
+ # row so retries don't accumulate orphans. We can't wrap in
+ # transaction.atomic() because the HTTP call is the failure mode
+ # we're guarding against; the row is committed first, then cleaned
+ # up explicitly on error.
+ try:
+ self._call(_janitor().clone_from, str(draft.id), source_id)
+ except Exception:
+ draft.delete()
+ raise
+ return Response(
+ {
+ "revision": AgentRevisionSerializer(draft).data,
+ "source_revision_id": source_id,
+ },
+ status=status.HTTP_201_CREATED,
+ )
+
+
+_MEMORY_HEADER_FIELDS: dict[str, drf_serializers.Field] = {
+ "path": drf_serializers.CharField(help_text="Relative path within the agent's memory, e.g. 'incidents/db.md'."),
+ "description": drf_serializers.CharField(help_text="One-line summary from the file's frontmatter."),
+ "tags": drf_serializers.ListField(
+ child=drf_serializers.CharField(),
+ help_text="Frontmatter tags (lowercase a-z 0-9 _ - only).",
+ ),
+ "created_at": drf_serializers.CharField(
+ allow_null=True,
+ help_text="ISO-8601 timestamp stamped on create. Null for files written before this field was introduced.",
+ ),
+ "updated_at": drf_serializers.CharField(
+ allow_null=True,
+ help_text="ISO-8601 timestamp stamped on every write.",
+ ),
+}
+
+_MEMORY_LIST_RESPONSE = inline_serializer(
+ name="AgentMemoryListResponse",
+ fields={
+ "count": drf_serializers.IntegerField(help_text="Number of entries returned."),
+ "entries": drf_serializers.ListField(
+ child=inline_serializer(name="AgentMemoryHeader", fields=_MEMORY_HEADER_FIELDS),
+ help_text="Headers (frontmatter only) — no file bodies. Use the read endpoint for the body.",
+ ),
+ },
+)
+
+_MEMORY_FILE_RESPONSE = inline_serializer(
+ name="AgentMemoryFile",
+ fields={
+ **_MEMORY_HEADER_FIELDS,
+ "content": drf_serializers.CharField(help_text="Full markdown body."),
+ },
+)
+
+_AGENT_TABLES_LIST_RESPONSE = inline_serializer(
+ name="AgentTablesListResponse",
+ fields={
+ "count": drf_serializers.IntegerField(help_text="Number of tables."),
+ "tables": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentTableHeader",
+ fields={
+ "name": drf_serializers.CharField(help_text="Table name."),
+ "size": drf_serializers.IntegerField(help_text="Object size in bytes."),
+ },
+ ),
+ help_text="Tabular-reference tables for this agent (the @posthog/table-* JSONL tables).",
+ ),
+ },
+)
+
+_AGENT_TABLE_ROWS_RESPONSE = inline_serializer(
+ name="AgentTableRowsResponse",
+ fields={
+ "name": drf_serializers.CharField(),
+ "total": drf_serializers.IntegerField(help_text="Total rows in the table."),
+ "returned": drf_serializers.IntegerField(help_text="Rows in this response (capped by limit)."),
+ "limit": drf_serializers.IntegerField(),
+ "rows": drf_serializers.ListField(
+ child=drf_serializers.DictField(),
+ help_text="The rows (arbitrary JSON objects).",
+ ),
+ },
+)
+
+_MEMORY_TREE_RESPONSE = inline_serializer(
+ name="AgentMemoryTreeResponse",
+ fields={
+ # Tree shape is recursive; declared loosely so OpenAPI doesn't need a
+ # self-reference. The frontend types use a hand-typed shape.
+ "root": drf_serializers.DictField(
+ help_text="Folder tree rooted at the agent's memory prefix. Each node is "
+ "{name, type: 'folder'|'file', path?, description?, tags?, children?}.",
+ ),
+ },
+)
+
+_MEMORY_SEARCH_RESULT = inline_serializer(
+ name="AgentMemorySearchResult",
+ fields={
+ "path": drf_serializers.CharField(),
+ "description": drf_serializers.CharField(),
+ "tags": drf_serializers.ListField(child=drf_serializers.CharField()),
+ "score": drf_serializers.FloatField(help_text="BM25 relevance score."),
+ "snippet": drf_serializers.CharField(
+ allow_null=True,
+ help_text="Body snippet around the earliest match. Null when only the header matched.",
+ ),
+ },
+)
+
+_MEMORY_SEARCH_RESPONSE = inline_serializer(
+ name="AgentMemorySearchResponse",
+ fields={
+ "cue": drf_serializers.CharField(help_text="The original search cue, echoed back."),
+ "count": drf_serializers.IntegerField(),
+ "results": drf_serializers.ListField(child=_MEMORY_SEARCH_RESULT),
+ },
+)
+
+
+class AgentMemoryWriteRequest(drf_serializers.Serializer):
+ """Body shape for AgentMemoryViewSet.write_file (create)."""
+
+ path = drf_serializers.CharField(
+ help_text="Where to store the file. Lowercase a-z 0-9 _ - / only, must end in .md."
+ )
+ description = drf_serializers.CharField(
+ max_length=280,
+ help_text="One-line summary, max 280 chars. Surfaces in list/search results.",
+ )
+ content = drf_serializers.CharField(help_text="Full markdown body.")
+ tags = drf_serializers.ListField(
+ child=drf_serializers.CharField(),
+ required=False,
+ help_text="Optional flat tags for search ranking. Lowercase a-z 0-9 _ - only.",
+ )
+
+
+class AgentMemoryUpdateRequest(drf_serializers.Serializer):
+ """Body shape for AgentMemoryViewSet.update_file. Omitted fields preserve the existing value."""
+
+ description = drf_serializers.CharField(max_length=280, required=False)
+ content = drf_serializers.CharField(required=False)
+ tags = drf_serializers.ListField(child=drf_serializers.CharField(), required=False)
+
+
+@extend_schema(tags=["agent_platform"])
+class AgentMemoryViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """S3-backed memory files for a single agent (application).
+
+ URLs (nested under an application):
+
+ GET .../memory/files/ list headers under the agent's prefix (?prefix=…)
+ GET .../memory/tree/ pre-aggregated folder tree
+ GET .../memory/files/by_path/?path=… read one file in full
+ POST .../memory/files/ create — body {path, description, content, tags?}
+ PATCH .../memory/files/by_path/?path=… update fields on an existing file
+ DELETE .../memory/files/by_path/?path=… hard delete
+ GET .../memory/search/?q=… BM25 search across files
+
+ Every endpoint proxies the janitor, which owns the S3MemoryStore. The
+ runner writes the same bucket directly via `@posthog/memory-*` tools —
+ one bucket, two callers, one source-of-truth code path.
+
+ Activity logging: create/update/delete log under scope='AgentApplication'
+ so memory edits surface in the agent's audit trail.
+ """
+
+ scope_object = "agents" # share the parent's scope
+ scope_object_read_actions = ["list_files", "tree", "get_file", "search", "tables", "table_rows"]
+ scope_object_write_actions = ["create_file", "update_file", "delete_file"]
+ # The parent URL kwarg is `application_id`; we override resolution to
+ # accept slug-or-UUID via _resolve_application.
+ filter_rewrite_rules: dict[str, str] = {}
+
+ def _get_application(self) -> AgentApplication:
+ app = _resolve_application(
+ AgentApplication.all_teams.filter(team_id=self.team_id, archived=False),
+ self.kwargs.get("parent_lookup_application_id") or self.kwargs.get("application_id"),
+ )
+ if app is None:
+ raise NotFound("Application not found")
+ # This is a plain ViewSet, so it bypasses the mixin's get_object() and
+ # the object-level RBAC it runs. Enforce per-application access control
+ # explicitly (mirrors TeamAndOrgViewSetMixin.get_object) — otherwise a
+ # user with team access but no access to THIS application could read its
+ # memory files / tables by guessing the slug or UUID.
+ self.check_object_permissions(self.request, app)
+ return app
+
+ # ── list / tree ────────────────────────────────────────────────────────
+
+ @extend_schema(
+ operation_id="agent_memory_list_files",
+ parameters=[
+ OpenApiParameter(
+ "prefix",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Optional path prefix to scope the list, e.g. 'incidents/'.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_MEMORY_LIST_RESPONSE),
+ description="List memory file headers under the agent's prefix. Headers only — no bodies.",
+ )
+ @action(detail=False, methods=["get"], url_path="files")
+ def list_files(self, request: Request, **kwargs) -> Response:
+ application = self._get_application()
+ try:
+ payload = _janitor().list_memory_files(
+ int(self.team_id),
+ str(application.id),
+ prefix=request.query_params.get("prefix") or None,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_memory_list_tables",
+ request=None,
+ responses=OpenApiResponse(response=_AGENT_TABLES_LIST_RESPONSE),
+ description="List the agent's tabular-reference tables (the @posthog/table-* JSONL tables): name + byte size.",
+ )
+ @action(detail=False, methods=["get"], url_path="tables")
+ def tables(self, request: Request, **kwargs) -> Response:
+ application = self._get_application()
+ try:
+ payload = _janitor().list_tables(int(self.team_id), str(application.id))
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_memory_read_table",
+ parameters=[
+ OpenApiParameter(
+ "limit",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Max rows to return (default 500, max 5000).",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_AGENT_TABLE_ROWS_RESPONSE),
+ description="Read rows from one tabular-reference table (capped via ?limit).",
+ )
+ @action(detail=False, methods=["get"], url_path="tables/(?P<name>[^/]+)")
+ def table_rows(self, request: Request, name: str | None = None, **kwargs) -> Response:
+ application = self._get_application()
+ limit_raw = request.query_params.get("limit")
+ limit: int | None = None
+ if limit_raw:
+ try:
+ limit = int(limit_raw)
+ except ValueError:
+ raise ValidationError("limit must be an integer")
+ try:
+ payload = _janitor().read_table(int(self.team_id), str(application.id), str(name), limit=limit)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_memory_tree",
+ request=None,
+ responses=OpenApiResponse(response=_MEMORY_TREE_RESPONSE),
+ description="Pre-aggregated folder tree of memory files. Saves the frontend re-derivation work.",
+ )
+ @action(detail=False, methods=["get"], url_path="tree")
+ def tree(self, request: Request, **kwargs) -> Response:
+ application = self._get_application()
+ try:
+ payload = _janitor().get_memory_tree(int(self.team_id), str(application.id))
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ # ── read / write / delete one file ─────────────────────────────────────
+
+ @extend_schema(
+ operation_id="agent_memory_get_file",
+ parameters=[
+ OpenApiParameter(
+ "path",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Memory path returned by the list endpoint, e.g. 'incidents/db.md'.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_MEMORY_FILE_RESPONSE),
+ description="Read one memory file in full (frontmatter + markdown body).",
+ )
+ @action(detail=False, methods=["get"], url_path="files/by_path")
+ def get_file(self, request: Request, **kwargs) -> Response:
+ path = request.query_params.get("path")
+ if not path:
+ raise ValidationError("missing required query param: path")
+ application = self._get_application()
+ try:
+ payload = _janitor().read_memory_file(int(self.team_id), str(application.id), path)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_memory_create_file",
+ request=AgentMemoryWriteRequest,
+ responses=OpenApiResponse(response=_MEMORY_FILE_RESPONSE),
+ description="Create a memory file. Fails if the path already exists — use the update endpoint to overwrite.",
+ )
+ # Chained off `list_files` via `@list_files.mapping.post` rather than its
+ # own `@action(url_path="files")` — DRF only registers one action per
+ # url_path, so two separate decorators leave the loser unrouted
+ # (the symptom is `405 Method Not Allowed: Allow: <whatever-loser>`).
+ @list_files.mapping.post
+ def create_file(self, request: Request, **kwargs) -> Response:
+ serializer = AgentMemoryWriteRequest(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ body = serializer.validated_data
+ application = self._get_application()
+ try:
+ payload = _janitor().write_memory_file(
+ int(self.team_id),
+ str(application.id),
+ path=body["path"],
+ description=body["description"],
+ content=body["content"],
+ tags=body.get("tags"),
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ operation_id="agent_memory_update_file",
+ parameters=[
+ OpenApiParameter(
+ "path",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Memory path to update.",
+ ),
+ ],
+ request=AgentMemoryUpdateRequest,
+ responses=OpenApiResponse(response=_MEMORY_FILE_RESPONSE),
+ description="Update a memory file. Any field omitted is preserved from the existing file.",
+ )
+ # Chained off `get_file` — see comment on `create_file` above.
+ @get_file.mapping.patch
+ def update_file(self, request: Request, **kwargs) -> Response:
+ path = request.query_params.get("path")
+ if not path:
+ raise ValidationError("missing required query param: path")
+ serializer = AgentMemoryUpdateRequest(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ body = serializer.validated_data
+ application = self._get_application()
+ try:
+ payload = _janitor().update_memory_file(
+ int(self.team_id),
+ str(application.id),
+ path,
+ description=body.get("description"),
+ content=body.get("content"),
+ tags=body.get("tags"),
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_memory_delete_file",
+ parameters=[
+ OpenApiParameter(
+ "path",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Memory path to delete.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentMemoryDeleteResponse",
+ fields={
+ "path": drf_serializers.CharField(),
+ "deleted": drf_serializers.BooleanField(),
+ },
+ ),
+ ),
+ description="Hard-delete a memory file. Activity log captures the action against the agent.",
+ )
+ # Chained off `get_file` — see comment on `create_file` above.
+ @get_file.mapping.delete
+ def delete_file(self, request: Request, **kwargs) -> Response:
+ path = request.query_params.get("path")
+ if not path:
+ raise ValidationError("missing required query param: path")
+ application = self._get_application()
+ try:
+ payload = _janitor().delete_memory_file(int(self.team_id), str(application.id), path)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ # ── search ─────────────────────────────────────────────────────────────
+
+ @extend_schema(
+ operation_id="agent_memory_search",
+ parameters=[
+ OpenApiParameter(
+ "q",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Search cue — plain natural language is fine.",
+ ),
+ OpenApiParameter(
+ "prefix",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Optional path prefix to scope the search.",
+ ),
+ OpenApiParameter(
+ "limit",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Max results (default 10, max 100).",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_MEMORY_SEARCH_RESPONSE),
+ description="BM25 search across the agent's memory files. Ranks by description+tags+path+body with field weighting.",
+ )
+ @action(detail=False, methods=["get"], url_path="search")
+ def search(self, request: Request, **kwargs) -> Response:
+ q = request.query_params.get("q")
+ if not q:
+ raise ValidationError("missing required query param: q")
+ prefix = request.query_params.get("prefix") or None
+ limit_param = request.query_params.get("limit")
+ try:
+ limit = int(limit_param) if limit_param is not None else None
+ except ValueError:
+ raise ValidationError("limit must be an integer")
+ application = self._get_application()
+ try:
+ payload = _janitor().search_memory(
+ int(self.team_id),
+ str(application.id),
+ q=q,
+ prefix=prefix,
+ limit=limit,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+
+@extend_schema(tags=["agent_platform"])
+class AgentNativeToolsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Read-only catalog of every `@posthog/*` native tool the runner knows.
+
+ URLs:
+ GET /api/projects/<team>/agent_native_tools/ — list
+
+ Backed by the janitor (which imports `listNativeTools()` from
+ `@posthog/agent-tools`). Keeps a single source of truth for what tools
+ exist — agents can't put unknown tool ids in their spec, and the MCP /
+ wizard show this list to humans + models when picking what to wire up.
+ """
+
+ scope_object = "agents"
+ scope_object_read_actions = ["list"]
+
+ @extend_schema(
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentNativeToolsListResponse",
+ fields={
+ "tools": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentNativeToolEntry",
+ fields={
+ "id": drf_serializers.CharField(),
+ "schema": drf_serializers.DictField(),
+ },
+ ),
+ ),
+ },
+ )
+ ),
+ description="Read-only catalog of every @posthog/* native tool the runner knows.",
+ )
+ def list(self, request: Request, **kwargs) -> Response:
+ try:
+ return Response(_janitor().native_tools())
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+
+
+@extend_schema(tags=["agent_platform"])
+class AgentFleetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Team-wide agent fleet rollups.
+
+ URLs:
+ GET /api/projects/<team>/agent_fleet/stats/ — aggregate counts + spend across every agent in the team
+ GET /api/projects/<team>/agent_fleet/live_sessions/ — live sessions for every agent in the team
+ GET /api/projects/<team>/agent_fleet/approvals/ — approval-gated tool requests across every agent in the team
+
+ All three endpoints proxy the janitor (which owns the runtime DB). Used
+ by the agent-console "fleet" overview to render the cards on the agents
+ list without per-agent N+1.
+ """
+
+ scope_object = "agents"
+ scope_object_read_actions = ["stats", "live_sessions", "approvals"]
+
+ def _require_team_admin(self) -> None:
+ """Mirror AgentApplicationViewSet — approvals are an admin-only surface."""
+ membership = OrganizationMembership.objects.filter(
+ user=cast(User, self.request.user), organization_id=self.organization_id
+ ).first()
+ if membership is None or membership.level < OrganizationMembership.Level.ADMIN:
+ raise NotFound("Not found")
+
+ @extend_schema(
+ operation_id="agent_fleet_stats",
+ parameters=[
+ OpenApiParameter(
+ "since",
+ OpenApiTypes.DATETIME,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(response=_AGENT_AGGREGATE_STATS),
+ description="Roll-up stats across every agent owned by this team.",
+ )
+ @action(detail=False, methods=["get"], url_path="stats")
+ def stats(self, request: Request, **kwargs) -> Response:
+ try:
+ payload = _janitor().aggregate_for_team(
+ int(self.team_id),
+ since=request.query_params.get("since") or None,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_fleet_live_sessions",
+ parameters=[
+ OpenApiParameter(
+ "limit",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Cap on returned sessions (default 100, max 500).",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentFleetLiveSessionsResponse",
+ fields={
+ "results": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentFleetLiveSessionSummary",
+ fields={
+ "id": drf_serializers.UUIDField(),
+ "application_id": drf_serializers.UUIDField(),
+ "revision_id": drf_serializers.UUIDField(),
+ "team_id": drf_serializers.IntegerField(),
+ "state": drf_serializers.ChoiceField(choices=_AGENT_SESSION_STATE_VALUES),
+ "external_key": drf_serializers.CharField(allow_null=True),
+ "trigger_metadata": drf_serializers.DictField(
+ allow_null=True,
+ required=False,
+ help_text=(
+ "Trigger-specific metadata stamped at session creation. Shape varies "
+ "by trigger kind; cron firings carry "
+ "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
+ "Render this on session-detail so the operator can tell at a glance "
+ "that a session was fired by which cron / when."
+ ),
+ ),
+ "principal": _AGENT_SESSION_PRINCIPAL,
+ "turns": drf_serializers.IntegerField(
+ help_text="Messages in the conversation so far.",
+ ),
+ "preview": drf_serializers.CharField(
+ allow_null=True,
+ help_text="Last assistant text (~120 chars). Null when no assistant turns yet.",
+ ),
+ "usage_total": _AGENT_SESSION_USAGE_TOTAL,
+ "created_at": drf_serializers.DateTimeField(),
+ "updated_at": drf_serializers.DateTimeField(),
+ },
+ ),
+ ),
+ },
+ ),
+ ),
+ description="Live (non-terminal) sessions across every agent owned by this team, newest activity first.",
+ )
+ @action(detail=False, methods=["get"], url_path="live_sessions")
+ def live_sessions(self, request: Request, **kwargs) -> Response:
+ limit_param = request.query_params.get("limit")
+ try:
+ limit = int(limit_param) if limit_param is not None else None
+ except ValueError:
+ raise ValidationError("limit must be an integer")
+ try:
+ payload = _janitor().list_live_for_team(int(self.team_id), limit=limit)
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+ @extend_schema(
+ operation_id="agent_fleet_approvals_list",
+ parameters=[
+ OpenApiParameter(
+ "state",
+ OpenApiTypes.STR,
+ OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Filter by approval state. Comma-separated list accepted. "
+ "Valid values: queued, approving, dispatched, "
+ "dispatched_failed, rejected, expired. Defaults to all states."
+ ),
+ ),
+ OpenApiParameter(
+ "agent_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Optional agent UUID — narrows the listing to one application.",
+ ),
+ OpenApiParameter("limit", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ OpenApiParameter("offset", OpenApiTypes.INT, OpenApiParameter.QUERY, required=False),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentFleetApprovalsListResponse",
+ fields={
+ "results": drf_serializers.ListField(
+ child=inline_serializer(
+ name="AgentFleetApprovalRequest",
+ fields=AgentApplicationViewSet._APPROVAL_RESPONSE_FIELDS,
+ ),
+ help_text="Approval requests across every agent in the team, newest first.",
+ ),
+ },
+ )
+ ),
+ description="Approval-gated tool requests across every agent in this team. Team-admin only.",
+ )
+ @action(detail=False, methods=["get"], url_path="approvals")
+ def approvals(self, request: Request, **kwargs) -> Response:
+ self._require_team_admin()
+ limit_param = request.query_params.get("limit")
+ offset_param = request.query_params.get("offset")
+ try:
+ limit = int(limit_param) if limit_param is not None else None
+ offset = int(offset_param) if offset_param is not None else None
+ except ValueError:
+ raise ValidationError("limit and offset must be integers")
+ try:
+ payload = _janitor().list_approvals_for_team(
+ int(self.team_id),
+ application_id=request.query_params.get("agent_id") or None,
+ state=request.query_params.get("state") or None,
+ limit=limit,
+ offset=offset,
+ )
+ except JanitorClientError as e:
+ raise JanitorUpstreamError(e) from e
+ return Response(payload)
+
+
+# Suppress unused-import warning for the type re-export below.
+_ = EncryptedTextField
diff --git a/products/agent_platform/backend/routes.py b/products/agent_platform/backend/routes.py
new file mode 100644
index 000000000000..a483615c5af8
--- /dev/null
+++ b/products/agent_platform/backend/routes.py
@@ -0,0 +1,54 @@
+from posthog.api.routing import RouterRegistry
+
+from products.agent_platform.backend.presentation.views import (
+ AgentApplicationViewSet,
+ AgentFleetViewSet,
+ AgentMemoryViewSet,
+ AgentNativeToolsViewSet,
+ AgentRevisionViewSet,
+)
+
+# Skill / custom-tool template registry is disabled pending a rethink.
+# from products.agent_platform.backend.registry_api import AgentCustomToolTemplateViewSet, AgentSkillTemplateViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ agent_applications = routers.projects.register(
+ r"agent_applications",
+ AgentApplicationViewSet,
+ "project_agent_applications",
+ ["project_id"],
+ )
+ agent_applications.register(
+ r"revisions",
+ AgentRevisionViewSet,
+ "project_agent_application_revisions",
+ ["project_id", "application_id"],
+ )
+ agent_applications.register(
+ r"memory",
+ AgentMemoryViewSet,
+ "project_agent_application_memory",
+ ["project_id", "application_id"],
+ )
+ routers.projects.register(
+ r"agent_native_tools",
+ AgentNativeToolsViewSet,
+ "project_agent_native_tools",
+ ["project_id"],
+ )
+ # Skill / custom-tool template routes disabled pending a registry rethink.
+ # routers.projects.register(
+ # r"agent_skill_templates", AgentSkillTemplateViewSet,
+ # "project_agent_skill_templates", ["project_id"],
+ # )
+ # routers.projects.register(
+ # r"agent_custom_tool_templates", AgentCustomToolTemplateViewSet,
+ # "project_agent_custom_tool_templates", ["project_id"],
+ # )
+ routers.projects.register(
+ r"agent_fleet",
+ AgentFleetViewSet,
+ "project_agent_fleet",
+ ["project_id"],
+ )
diff --git a/products/agent_platform/backend/tests/__init__.py b/products/agent_platform/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/agent_platform/backend/tests/test_approvals_api.py b/products/agent_platform/backend/tests/test_approvals_api.py
new file mode 100644
index 000000000000..a7af3218e455
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_approvals_api.py
@@ -0,0 +1,136 @@
+"""
+Focused tests for the AgentApplicationViewSet approval-gated endpoints.
+
+The runtime side (intercept, store, wake, sweep) is covered by the e2e
+harness in services/agent-tests/src/cases/approval-gated.test.ts. These
+tests guard the Django-side concerns that don't go through the harness:
+
+ - Team-admin-only auth on list / retrieve / decide (plan §6.1).
+ - The Django view forwards body + path params to the janitor and
+ surfaces the upstream response intact.
+ - Ownership cross-check rejects approval ids that belong to a sibling
+ application.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from posthog.models.organization import OrganizationMembership
+
+from ..models import AgentApplication
+
+
+class TestApprovalEndpointsAuth(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="gated-agent",
+ name="Gated Agent",
+ description="",
+ )
+ self.url_list = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/approvals/"
+ self.approval_id = "00000000-0000-4000-8000-000000000001"
+ self.url_detail = f"{self.url_list}{self.approval_id}/"
+ self.url_decide = f"{self.url_list}{self.approval_id}/decide/"
+
+ def _set_org_level(self, level: OrganizationMembership.Level) -> None:
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = level
+ membership.save()
+
+ def test_non_admin_cannot_list_approvals(self) -> None:
+ self._set_org_level(OrganizationMembership.Level.MEMBER)
+ resp = self.client.get(self.url_list)
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_non_admin_cannot_decide(self) -> None:
+ self._set_org_level(OrganizationMembership.Level.MEMBER)
+ resp = self.client.post(
+ self.url_decide,
+ {"decision": "approve"},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_admin_list_forwards_to_janitor(self, mock_janitor) -> None:
+ self._set_org_level(OrganizationMembership.Level.ADMIN)
+ mock_janitor.return_value.list_approvals.return_value = {"results": []}
+ resp = self.client.get(self.url_list, {"state": "queued"})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.list_approvals.assert_called_once_with(
+ str(self.application.id),
+ state="queued",
+ limit=None,
+ offset=None,
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_admin_decide_forwards_decision_payload(self, mock_janitor) -> None:
+ self._set_org_level(OrganizationMembership.Level.ADMIN)
+ mock_janitor.return_value.get_approval.return_value = {
+ "id": self.approval_id,
+ "application_id": str(self.application.id),
+ "approver_scope": {"allow_agent_approver": False},
+ }
+ mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}
+ resp = self.client.post(
+ self.url_decide,
+ {"decision": "approve", "reason": "looks good"},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.decide_approval.assert_called_once_with(
+ self.approval_id,
+ decision="approve",
+ decided_by=str(self.user.uuid),
+ edited_args=None,
+ reason="looks good",
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_admin_cannot_decide_approval_for_other_application(self, mock_janitor) -> None:
+ self._set_org_level(OrganizationMembership.Level.ADMIN)
+ other_app = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="other-agent",
+ name="Other Agent",
+ description="",
+ )
+ # Janitor reports the approval belongs to `other_app`, but we asked
+ # via the URL for `self.application`. The view must reject — otherwise
+ # an admin on team A could decide approvals on any agent in the same
+ # janitor DB just by mutating the URL.
+ mock_janitor.return_value.get_approval.return_value = {
+ "id": self.approval_id,
+ "application_id": str(other_app.id),
+ "approver_scope": {"allow_agent_approver": False},
+ }
+ resp = self.client.post(
+ self.url_decide,
+ {"decision": "approve"},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+ mock_janitor.return_value.decide_approval.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_decide_validates_required_fields(self, mock_janitor) -> None:
+ self._set_org_level(OrganizationMembership.Level.ADMIN)
+ resp = self.client.post(self.url_decide, {}, format="json")
+ # `decision` is required → 400.
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_janitor.return_value.decide_approval.assert_not_called()
diff --git a/products/agent_platform/backend/tests/test_cron_fire.py b/products/agent_platform/backend/tests/test_cron_fire.py
new file mode 100644
index 000000000000..6feadc10b630
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_cron_fire.py
@@ -0,0 +1,104 @@
+"""
+Integration test: AgentRevision cron_fire action ↔ janitor proxy.
+
+Mocks the janitor HTTP client at the boundary so we don't need a live
+janitor process — the action's contract is "call janitor_client.cron_fire
+with the right args and pass its response through unchanged." The runtime
+side (real PG, real session creation) is exercised in
+`services/agent-tests/src/cases/cron-trigger.test.ts`.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from ..models import AgentApplication, AgentRevision
+
+
+class TestCronFireAction(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="cron-fire-agent",
+ name="Cron fire agent",
+ description="",
+ )
+ self.revision = AgentRevision.all_teams.create(
+ application=self.application,
+ spec={
+ "model": "x",
+ "triggers": [
+ {
+ "type": "cron",
+ "config": {
+ "name": "digest",
+ "schedule": "0 9 * * MON",
+ "prompt": "Run.",
+ },
+ }
+ ],
+ },
+ state="ready",
+ bundle_uri="fs://test/",
+ )
+ self.url = (
+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"
+ f"/revisions/{self.revision.id}/cron/fire/"
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_cron_fire_passes_cron_name_to_janitor_and_returns_response(self, mock_janitor: MagicMock) -> None:
+ mock_janitor.return_value.cron_fire.return_value = {
+ "ok": True,
+ "session_id": "11111111-1111-1111-1111-111111111111",
+ "fired_at": "2026-06-01T16:00:00.000Z",
+ "idempotency_key": f"cron-manual:{self.revision.id}:digest:click-1",
+ "request_id": "click-1",
+ }
+ res = self.client.post(self.url, {"cron_name": "digest", "request_id": "click-1"}, format="json")
+ self.assertEqual(res.status_code, 200)
+ self.assertEqual(res.json()["session_id"], "11111111-1111-1111-1111-111111111111")
+ self.assertEqual(res.json()["idempotency_key"], f"cron-manual:{self.revision.id}:digest:click-1")
+ mock_janitor.return_value.cron_fire.assert_called_once_with(
+ str(self.revision.id), cron_name="digest", request_id="click-1"
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_cron_fire_request_id_is_optional(self, mock_janitor: MagicMock) -> None:
+ # Without request_id the janitor mints a UUID; verify we forward None
+ # so the janitor falls through to its own generator rather than us
+ # silently passing an empty string.
+ mock_janitor.return_value.cron_fire.return_value = {
+ "ok": True,
+ "session_id": "22222222-2222-2222-2222-222222222222",
+ "fired_at": "2026-06-01T16:00:00.000Z",
+ "idempotency_key": f"cron-manual:{self.revision.id}:digest:generated",
+ "request_id": "generated",
+ }
+ res = self.client.post(self.url, {"cron_name": "digest"}, format="json")
+ self.assertEqual(res.status_code, 200)
+ mock_janitor.return_value.cron_fire.assert_called_once_with(
+ str(self.revision.id), cron_name="digest", request_id=None
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_cron_fire_rejects_missing_cron_name(self, mock_janitor: MagicMock) -> None:
+ res = self.client.post(self.url, {}, format="json")
+ self.assertEqual(res.status_code, 400)
+ mock_janitor.return_value.cron_fire.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_cron_fire_rejects_empty_cron_name(self, mock_janitor: MagicMock) -> None:
+ res = self.client.post(self.url, {"cron_name": ""}, format="json")
+ self.assertEqual(res.status_code, 400)
+ mock_janitor.return_value.cron_fire.assert_not_called()
diff --git a/products/agent_platform/backend/tests/test_env_keys.py b/products/agent_platform/backend/tests/test_env_keys.py
new file mode 100644
index 000000000000..7c72e1bfe388
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_env_keys.py
@@ -0,0 +1,152 @@
+"""
+Tests for the per-key env management endpoints on AgentApplicationViewSet.
+
+Covers list / status / set / clear without ever returning decrypted
+values across the wire, and verifies that merging behaviour preserves
+unrelated keys.
+"""
+
+from __future__ import annotations
+
+import json
+
+from posthog.test.base import APIBaseTest
+
+from ..models import AgentApplication
+
+
+class TestAgentApplicationEnvKeys(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self) -> AgentApplication:
+ app = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="secrets-agent",
+ name="Secrets agent",
+ description="",
+ )
+ # 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
+
+ def _url(self, app: AgentApplication, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/{suffix}"
+
+ def test_list_returns_keys_sorted_no_values(self) -> None:
+ app = self._app()
+ res = self.client.get(self._url(app, "env_keys/"))
+ assert res.status_code == 200, res.content
+ body = res.json()
+ assert body == {"keys": ["ANTHROPIC_KEY", "SLACK_TOKEN"]}
+ # Defensively check no value leaks into the response.
+ assert "sk-old" not in res.content.decode()
+ 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/"))
+ 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/"))
+ 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/"))
+ 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()
+ res = self.client.put(
+ self._url(app, "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)
+ 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()
+ res = self.client.put(
+ self._url(app, "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"
+
+ 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/"))
+ 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"}
+
+ def test_delete_unset_key_is_idempotent(self) -> None:
+ app = self._app()
+ res = self.client.delete(self._url(app, "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) == {
+ "ANTHROPIC_KEY": "sk-old",
+ "SLACK_TOKEN": "xoxb-old",
+ }
+
+ def test_put_rejects_when_value_missing(self) -> None:
+ app = self._app()
+ res = self.client.put(
+ self._url(app, "env_keys/X/"),
+ data={},
+ content_type="application/json",
+ )
+ assert res.status_code == 400
+
+ 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()
+ res = self.client.put(
+ self._url(app, "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"] == ""
+
+ 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="")
+ # Simulate a corrupt env block — historic bug or manual tampering.
+ app.encrypted_env = "not json"
+ app.save(update_fields=["encrypted_env"])
+
+ res = self.client.get(self._url(app, "env_keys/"))
+ assert res.status_code == 200
+ assert res.json() == {"keys": []}
diff --git a/products/agent_platform/backend/tests/test_fleet_stats.py b/products/agent_platform/backend/tests/test_fleet_stats.py
new file mode 100644
index 000000000000..57b8be6324c8
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_fleet_stats.py
@@ -0,0 +1,135 @@
+"""
+Focused tests for the fleet-stats endpoints (per-application `stats` action
+and the team-wide AgentFleetViewSet). The aggregation itself happens on the
+janitor side — these guards make sure Django proxies the right arguments,
+surfaces the upstream response intact, and keeps the scope action map in
+sync so the new endpoints don't silently regress to "personal API keys can
+read team fleet data".
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from ..models import AgentApplication
+from ..presentation.views import AgentApplicationViewSet, AgentFleetViewSet
+
+
+class TestAgentApplicationStats(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="stats-agent",
+ name="Stats Agent",
+ description="",
+ )
+ self.url = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/stats/"
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_stats_forwards_to_janitor_with_since(self, mock_janitor) -> None:
+ mock_janitor.return_value.aggregate_for_application.return_value = {
+ "liveCount": 2,
+ "sessionsInWindowCount": 5,
+ "spendInWindowUsd": 1.23,
+ "lastActivityAt": "2026-05-29T00:00:00Z",
+ "failedInWindowCount": 1,
+ }
+ resp = self.client.get(self.url, {"since": "2026-05-28T00:00:00Z"})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.json()["liveCount"], 2)
+ mock_janitor.return_value.aggregate_for_application.assert_called_once_with(
+ str(self.application.id),
+ since="2026-05-28T00:00:00Z",
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_stats_omits_since_when_not_supplied(self, mock_janitor) -> None:
+ # The janitor side picks the default `since` window (24h) when the
+ # query param is absent — Django shouldn't fabricate one and shouldn't
+ # forward an empty string either.
+ mock_janitor.return_value.aggregate_for_application.return_value = {}
+ resp = self.client.get(self.url)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.aggregate_for_application.assert_called_once_with(
+ str(self.application.id),
+ since=None,
+ )
+
+ def test_stats_is_a_declared_read_action(self) -> None:
+ # If the action name slips out of `scope_object_read_actions`, the
+ # scope check denies personal-API-key reads (correct behavior, but
+ # silently breaks any read tooling) — guard against drift.
+ self.assertIn("stats", AgentApplicationViewSet.scope_object_read_actions)
+
+
+class TestAgentFleetViewSet(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.url_stats = f"/api/projects/{self.team.id}/agent_fleet/stats/"
+ self.url_live = f"/api/projects/{self.team.id}/agent_fleet/live_sessions/"
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_stats_forwards_team_id_and_since(self, mock_janitor) -> None:
+ mock_janitor.return_value.aggregate_for_team.return_value = {
+ "liveCount": 1,
+ "sessionsInWindowCount": 3,
+ "spendInWindowUsd": 4.5,
+ "lastActivityAt": "2026-05-29T00:00:00Z",
+ "failedInWindowCount": 0,
+ }
+ resp = self.client.get(self.url_stats, {"since": "2026-05-28T00:00:00Z"})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.aggregate_for_team.assert_called_once_with(
+ self.team.id,
+ since="2026-05-28T00:00:00Z",
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_live_sessions_forwards_team_id_and_limit(self, mock_janitor) -> None:
+ mock_janitor.return_value.list_live_for_team.return_value = {"results": []}
+ resp = self.client.get(self.url_live, {"limit": 25})
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.list_live_for_team.assert_called_once_with(
+ self.team.id,
+ limit=25,
+ )
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_live_sessions_without_limit_defaults_to_none(self, mock_janitor) -> None:
+ # The janitor picks its own 100-default; Django shouldn't impose a
+ # different one.
+ mock_janitor.return_value.list_live_for_team.return_value = {"results": []}
+ resp = self.client.get(self.url_live)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ mock_janitor.return_value.list_live_for_team.assert_called_once_with(
+ self.team.id,
+ limit=None,
+ )
+
+ def test_live_sessions_rejects_non_integer_limit(self) -> None:
+ resp = self.client.get(self.url_live, {"limit": "banana"})
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_actions_are_declared_read_actions(self) -> None:
+ self.assertIn("stats", AgentFleetViewSet.scope_object_read_actions)
+ self.assertIn("live_sessions", AgentFleetViewSet.scope_object_read_actions)
diff --git a/products/agent_platform/backend/tests/test_memory_authz.py b/products/agent_platform/backend/tests/test_memory_authz.py
new file mode 100644
index 000000000000..4067cfac8c14
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_memory_authz.py
@@ -0,0 +1,60 @@
+"""
+Object-level access control on the agent memory / table endpoints.
+
+`AgentMemoryViewSet` is a plain `ViewSet`, so it resolves the application via
+its own `_get_application()` rather than the mixin's `get_object()`. That
+helper must still run `check_object_permissions`, or a user with team access
+but no access to a specific application could read its memory files / tables
+by guessing the slug or UUID. These tests pin the team-scoping boundary and
+that the authorized path is not over-blocked by the added check.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import Organization, Team
+
+from ..models import AgentApplication
+
+
+class TestMemoryViewSetAuthz(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id, slug="memo-agent", name="Memo agent", description=""
+ )
+ self.tables_url = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/memory/tables/"
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_authorized_member_can_list_tables(self, mock_janitor: MagicMock) -> None:
+ # The added object-permission check must not over-block or crash the
+ # normal path: a team member resolves the app and proxies to the janitor.
+ mock_janitor.return_value.list_tables.return_value = {"tables": []}
+ res = self.client.get(self.tables_url)
+ self.assertEqual(res.status_code, 200, res.content)
+ mock_janitor.return_value.list_tables.assert_called_once()
+
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_application_from_another_team_is_not_readable(self, mock_janitor: MagicMock) -> None:
+ # An application owned by a different team must not be reachable through
+ # this team's URL — resolution is team-scoped, so the janitor is never
+ # called and no rows leak across the tenant boundary.
+ other_org = Organization.objects.create(name="other-org")
+ other_team = Team.objects.create(organization=other_org, name="other-team")
+ foreign = AgentApplication.all_teams.create(
+ team_id=other_team.id, slug="foreign", name="Foreign", description=""
+ )
+ url = f"/api/projects/{self.team.id}/agent_applications/{foreign.id}/memory/tables/"
+ res = self.client.get(url)
+ self.assertEqual(res.status_code, 404, res.content)
+ mock_janitor.return_value.list_tables.assert_not_called()
diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.py
new file mode 100644
index 000000000000..65970c64e3e3
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_preview_proxy.py
@@ -0,0 +1,75 @@
+"""
+Regression: AgentApplicationViewSet.preview_proxy — scope + renderer hygiene.
+
+Locks down the two classes of bug we shipped landing the draft-preview
+playground flow:
+
+ * 403 `This action does not support personal API key access` —
+ happened because the GET variant maps to a separate `view.action`
+ name (`preview_proxy_get`) and we only had the POST one
+ (`preview_proxy`) listed in `scope_object_read_actions`. Both names
+ must be declared or OAuth/PAT callers get bounced.
+
+ * 406 `Could not satisfy the request Accept header` — happened
+ because browser `EventSource` sends `Accept: text/event-stream` and
+ DRF's default renderer set doesn't claim that media type, so the
+ request 406s before reaching the streaming view. The action's
+ `renderer_classes` must include `EventStreamRenderer`.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from ..presentation.views import AgentApplicationViewSet, EventStreamRenderer
+
+
+class TestPreviewProxyScope(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ @parameterized.expand(
+ [
+ # POST verbs (run / send / cancel) route through `preview_proxy`.
+ ("preview_proxy",),
+ # GET (SSE listen) routes through `preview_proxy_get` —
+ # `view.action` resolves to the bound function name on the
+ # `@preview_proxy.mapping.get` handler.
+ ("preview_proxy_get",),
+ ]
+ )
+ def test_action_is_a_declared_read_action(self, action_name: str) -> None:
+ self.assertIn(action_name, AgentApplicationViewSet.scope_object_read_actions)
+
+
+class TestPreviewProxyRendering(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def test_event_stream_renderer_claims_text_event_stream(self) -> None:
+ # The renderer doesn't render — it only needs to win DRF's
+ # content negotiation when `Accept: text/event-stream` arrives.
+ self.assertEqual(EventStreamRenderer.media_type, "text/event-stream")
+
+ def test_preview_proxy_renderers_include_event_stream(self) -> None:
+ # The renderer set is attached to the `@action` (POST handler);
+ # the GET via `@preview_proxy.mapping.get` inherits the same set
+ # (`mapping.get` doesn't take its own kwargs).
+ # DRF stashes action kwargs on `.kwargs` not on direct attributes.
+ action_kwargs = getattr(AgentApplicationViewSet.preview_proxy, "kwargs", {})
+ renderer_classes = action_kwargs.get("renderer_classes")
+ self.assertIsNotNone(renderer_classes, "preview_proxy action should declare renderer_classes")
+ assert renderer_classes is not None # type narrowing for mypy
+ self.assertIn(EventStreamRenderer, renderer_classes)
diff --git a/products/agent_platform/backend/tests/test_preview_token.py b/products/agent_platform/backend/tests/test_preview_token.py
new file mode 100644
index 000000000000..fba84faaba91
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_preview_token.py
@@ -0,0 +1,293 @@
+"""
+Tests for AgentApplicationViewSet.preview_token — the self-describing
+response shape.
+
+Verifies:
+
+ * `endpoints` contains the right routes for each declared trigger and
+ omits routes for triggers the spec doesn't list (so the caller
+ doesn't see URLs that 404 at ingress).
+ * `auth.trigger_modes` mirrors each trigger's `auth.modes[].type` in order so
+ the caller knows which credential to attach alongside the preview-token.
+ * `preview_proxy` advertises the Django-side proxy URL + its allowed
+ paths so callers can pick between direct ingress and the
+ auth-stripping proxy.
+ * Empty `endpoints` when `AGENT_INGRESS_PUBLIC_URL` is unset (local
+ dev without the tunnel).
+ * Domain routing mode (`AGENT_INGRESS_ROUTING_MODE=domain`): URLs put
+ the slug in the host (`https://<slug><suffix>/...`), matching what the
+ domain-mode ingress serves; empty when the suffix is unset.
+ * Hard requirements that already existed: live revision rejected,
+ cross-app revision rejected, missing query param rejected.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from django.test import override_settings
+
+from ..models import AgentApplication, AgentRevision
+
+
+def _base_spec(triggers: list[dict[str, Any]] | None = None, modes: list[str] | None = None) -> dict[str, Any]:
+ # Auth is per-trigger now — `modes` is distributed onto each declarative
+ # trigger (webhook/chat/mcp) that doesn't already carry its own.
+ auth = {"modes": [{"type": m, "scopes": []} if m == "posthog" else {"type": m} for m in (modes or ["posthog"])]}
+ trigs = triggers if triggers is not None else [{"type": "chat", "config": {}}]
+ trigs = [
+ {**t, "auth": auth} if t.get("type") in ("webhook", "chat", "mcp") and "auth" not in t else t for t in trigs
+ ]
+ return {
+ "model": "anthropic/claude-sonnet-4-6",
+ "triggers": trigs,
+ "tools": [],
+ "mcps": [],
+ "skills": [],
+ "integrations": [],
+ "secrets": [],
+ "limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},
+ "entrypoint": "agent.md",
+ }
+
+
+@override_settings(AGENT_INGRESS_PUBLIC_URL="https://ingress.example.com")
+class TestPreviewTokenResponse(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str = "preview-bot") -> AgentApplication:
+ return AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug=slug,
+ name="Preview bot",
+ description="",
+ )
+
+ def _revision(self, app: AgentApplication, spec: dict[str, Any]) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=app,
+ state="draft",
+ bundle_uri=f"local://{app.slug}/v1",
+ spec=spec,
+ )
+
+ def _url(self, app: AgentApplication, rev: AgentRevision) -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/preview-token/?revision_id={rev.id}"
+
+ def test_endpoints_advertises_only_declared_triggers(self) -> None:
+ app = self._app()
+ spec = _base_spec(
+ triggers=[
+ {"type": "chat", "config": {}},
+ {
+ "type": "slack",
+ "config": {"mention_only": True, "trusted_workspaces": ["T01ABC"]},
+ },
+ ]
+ )
+ rev = self._revision(app, spec)
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ body = res.json()
+
+ # ingress_slug is the rev-hex form Django builds (32-char hex,
+ # no dashes — see _build_preview_endpoints for the contract).
+ expected_slug = f"{app.slug}-{rev.id.hex}"
+ assert body["ingress_slug"] == expected_slug
+
+ endpoints = body["endpoints"]
+ # chat and slack both declared → both present.
+ assert set(endpoints.keys()) == {"chat", "slack"}
+ # Spot-check one URL from each — full URL means the caller
+ # doesn't have to know the base or path layout.
+ assert endpoints["chat"]["run"] == f"https://ingress.example.com/agents/{expected_slug}/run"
+ assert endpoints["slack"]["events"] == f"https://ingress.example.com/agents/{expected_slug}/slack/events"
+ # mcp / webhook not declared → not in response. Prevents the
+ # caller from hitting a URL that 404s at ingress.
+ assert "mcp" not in endpoints
+ assert "webhook" not in endpoints
+
+ def test_auth_block_mirrors_per_trigger_modes_in_order(self) -> None:
+ app = self._app()
+ rev = self._revision(app, _base_spec(modes=["posthog", "posthog_internal"]))
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ auth = res.json()["auth"]
+
+ # Auth is per-trigger now — the chat trigger's modes are reported under
+ # its type. Order matters: the caller picks the first mode its
+ # credential satisfies, so mirroring spec order keeps the contract stable.
+ assert auth["trigger_modes"] == {"chat": ["posthog", "posthog_internal"]}
+ # Header / query names match what ingress's resolver reads.
+ assert auth["preview_token_header"] == "x-agent-preview-token"
+ assert auth["preview_token_query"] == "preview_token"
+ # Notes must mention that preview-token alone isn't enough — the caller
+ # still has to satisfy the trigger's auth modes.
+ assert "trigger_modes" in auth["notes"]
+
+ def test_preview_proxy_block_advertises_django_url(self) -> None:
+ app = self._app("proxy-bot")
+ rev = self._revision(app, _base_spec())
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ proxy = res.json()["preview_proxy"]
+
+ # The proxy base must point at THIS application — pasting a
+ # different slug would invoke a different agent. Verify the
+ # URL is rooted in the team + slug the request was for.
+ assert f"/api/projects/{self.team.id}/agent_applications/proxy-bot/preview-proxy" in proxy["base"]
+ # `allowed_paths` must be a sorted list (deterministic for the
+ # caller's UI / docs) covering the four chat-trigger paths the
+ # proxy passes through today.
+ assert proxy["allowed_paths"] == ["cancel", "listen", "run", "send"]
+ # Notes call out the auth-stripping limitation so the caller
+ # doesn't try to use the proxy for an oauth-required agent.
+ assert "Authorization" in proxy["notes"]
+
+ @override_settings(AGENT_INGRESS_PUBLIC_URL=None)
+ def test_endpoints_empty_when_public_url_unset(self) -> None:
+ app = self._app()
+ rev = self._revision(app, _base_spec())
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ body = res.json()
+ # No public URL → no externally-reachable endpoints. Empty
+ # rather than partial — the caller can detect the unconfigured
+ # state by `endpoints == {}` and tell the user to set the env
+ # var rather than handing them a broken URL.
+ assert body["endpoints"] == {}
+ # auth / preview_proxy blocks still present — they don't need
+ # the ingress URL to be useful (proxy is same-origin Django).
+ assert "auth" in body
+ assert "preview_proxy" in body
+
+ def test_live_revision_rejected(self) -> None:
+ app = self._app()
+ rev = self._revision(app, _base_spec())
+ # Promote the revision so it's live; preview-token then refuses.
+ app.live_revision = rev
+ app.save(update_fields=["live_revision"])
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 400, res.content
+ assert "non-live revisions only" in res.content.decode()
+
+ def test_revision_id_required(self) -> None:
+ app = self._app()
+ res = self.client.get(f"/api/projects/{self.team.id}/agent_applications/{app.slug}/preview-token/")
+ assert res.status_code == 400, res.content
+ assert "revision_id" in res.content.decode()
+
+
+@override_settings(
+ AGENT_INGRESS_ROUTING_MODE="domain",
+ AGENT_INGRESS_DOMAIN_SUFFIX=".agents.dev.posthog.dev",
+ AGENT_INGRESS_PUBLIC_URL="https://ignored-in-domain-mode.example.com",
+)
+class TestPreviewTokenDomainMode(APIBaseTest):
+ """Domain-mode URL shape for `endpoints`: slug in the host, routes mounted
+ at root. `AGENT_INGRESS_PUBLIC_URL` is deliberately set to prove domain mode
+ ignores it. Standalone (not a subclass of the path-mode suite) so the
+ path-mode assertions don't re-run under these settings."""
+
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str = "preview-bot") -> AgentApplication:
+ return AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name="Preview bot", description="")
+
+ def _revision(self, app: AgentApplication, spec: dict[str, Any]) -> AgentRevision:
+ return AgentRevision.all_teams.create(
+ application=app, state="draft", bundle_uri=f"local://{app.slug}/v1", spec=spec
+ )
+
+ def _url(self, app: AgentApplication, rev: AgentRevision) -> str:
+ return f"/api/projects/{self.team.id}/agent_applications/{app.slug}/preview-token/?revision_id={rev.id}"
+
+ def test_endpoints_use_host_routing(self) -> None:
+ app = self._app()
+ spec = _base_spec(
+ triggers=[
+ {"type": "chat", "config": {}},
+ {"type": "slack", "config": {"mention_only": True, "trusted_workspaces": ["T01ABC"]}},
+ ]
+ )
+ rev = self._revision(app, spec)
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ endpoints = res.json()["endpoints"]
+
+ expected_slug = f"{app.slug}-{rev.id.hex}"
+ # Slug in the host, route at root — what the domain-mode ingress
+ # actually serves. The path-mode `/agents/<slug>/...` shape would
+ # 404 here, which is the bug this whole change fixes.
+ assert endpoints["chat"]["run"] == f"https://{expected_slug}.agents.dev.posthog.dev/run"
+ assert endpoints["slack"]["events"] == f"https://{expected_slug}.agents.dev.posthog.dev/slack/events"
+
+ @override_settings(AGENT_INGRESS_DOMAIN_SUFFIX="")
+ def test_endpoints_empty_when_suffix_unset(self) -> None:
+ app = self._app()
+ rev = self._revision(app, _base_spec())
+
+ res = self.client.get(self._url(app, rev))
+ assert res.status_code == 200, res.content
+ # Domain mode selected but no suffix → not externally reachable.
+ # Same fail-closed empty as path mode without a public URL.
+ assert res.json()["endpoints"] == {}
+
+
+class TestSlackUrlSerializer(APIBaseTest):
+ """`slack_events_url` / `slack_interactivity_url` on the application
+ retrieve serializer, across both routing modes."""
+
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def _app(self, slug: str = "slack-bot") -> AgentApplication:
+ return AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name="Slack bot", description="")
+
+ def _retrieve(self, app: AgentApplication) -> dict[str, Any]:
+ res = self.client.get(f"/api/projects/{self.team.id}/agent_applications/{app.slug}/")
+ assert res.status_code == 200, res.content
+ return res.json()
+
+ @override_settings(AGENT_INGRESS_ROUTING_MODE="path", AGENT_INGRESS_PUBLIC_URL="https://ingress.example.com")
+ def test_path_mode_urls(self) -> None:
+ body = self._retrieve(self._app())
+ assert body["slack_events_url"] == "https://ingress.example.com/agents/slack-bot/slack/events"
+ assert body["slack_interactivity_url"] == "https://ingress.example.com/agents/slack-bot/slack/interactivity"
+
+ @override_settings(AGENT_INGRESS_ROUTING_MODE="domain", AGENT_INGRESS_DOMAIN_SUFFIX=".agents.dev.posthog.dev")
+ def test_domain_mode_urls(self) -> None:
+ body = self._retrieve(self._app())
+ assert body["slack_events_url"] == "https://slack-bot.agents.dev.posthog.dev/slack/events"
+ assert body["slack_interactivity_url"] == "https://slack-bot.agents.dev.posthog.dev/slack/interactivity"
+
+ @override_settings(AGENT_INGRESS_ROUTING_MODE="path", AGENT_INGRESS_PUBLIC_URL=None)
+ def test_null_when_unconfigured(self) -> None:
+ body = self._retrieve(self._app())
+ assert body["slack_events_url"] is None
+ assert body["slack_interactivity_url"] is None
diff --git a/products/agent_platform/backend/tests/test_promote_archive.py b/products/agent_platform/backend/tests/test_promote_archive.py
new file mode 100644
index 000000000000..04a676467e27
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_promote_archive.py
@@ -0,0 +1,85 @@
+"""
+Regression: promote/archive run select_for_update inside transaction.atomic
+against the agent_platform product DB.
+
+Both actions lock the parent application row to serialize concurrent
+promotes. Because the agent models live in a dedicated product DB, the
+atomic block and the locking query must target that DB's writer alias
+(`transaction.atomic(using=WRITER_DB)` + `.using(WRITER_DB)`), otherwise
+they bind to `default` and 500 with "select_for_update cannot be used
+outside of a transaction".
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from ..models import AgentApplication, AgentRevision
+
+
+class TestPromoteArchive(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="weekly-digest",
+ name="Weekly digest",
+ description="",
+ )
+
+ def _ready_revision(self) -> AgentRevision:
+ # promote() requires a frozen bundle and `ready` state.
+ return AgentRevision.all_teams.create(
+ application=self.application,
+ team_id=self.team.id,
+ state="ready",
+ spec={},
+ bundle_sha256="a" * 64,
+ )
+
+ def _url(self, revision: AgentRevision, action: str) -> str:
+ return (
+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/{revision.id}/{action}/"
+ )
+
+ def test_promote_sets_application_live_revision(self) -> None:
+ revision = self._ready_revision()
+ resp = self.client.post(self._url(revision, "promote"))
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ self.assertEqual(resp.json()["state"], "live")
+ revision.refresh_from_db()
+ self.application.refresh_from_db()
+ self.assertEqual(revision.state, "live")
+ self.assertEqual(self.application.live_revision_id, revision.id)
+
+ def test_promote_archives_previous_live(self) -> None:
+ first = self._ready_revision()
+ self.client.post(self._url(first, "promote"))
+ second = self._ready_revision()
+ resp = self.client.post(self._url(second, "promote"))
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ first.refresh_from_db()
+ self.application.refresh_from_db()
+ self.assertEqual(first.state, "archived")
+ self.assertEqual(self.application.live_revision_id, second.id)
+
+ def test_archive_clears_live_pointer(self) -> None:
+ revision = self._ready_revision()
+ self.client.post(self._url(revision, "promote"))
+ resp = self.client.post(self._url(revision, "archive"))
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ self.assertEqual(resp.json()["state"], "archived")
+ revision.refresh_from_db()
+ self.application.refresh_from_db()
+ self.assertEqual(revision.state, "archived")
+ self.assertIsNone(self.application.live_revision_id)
diff --git a/products/agent_platform/backend/tests/test_revisions_slug_lookup.py b/products/agent_platform/backend/tests/test_revisions_slug_lookup.py
new file mode 100644
index 000000000000..ebd7a1a19111
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_revisions_slug_lookup.py
@@ -0,0 +1,79 @@
+"""
+Regression: AgentRevisionViewSet — nested routes accept slug for parent lookup.
+
+The TeamAndOrgViewSetMixin auto-filters by every parent URL kwarg as a
+literal value (e.g. `application_id="<slug>"`). AgentApplication uses a
+UUID primary key, so a slug in the URL would otherwise blow up at the
+queryset filter with "'<slug>' is not a valid UUID". `AgentRevisionViewSet`
+overrides `parents_query_dict` to resolve slug → UUID via the existing
+`_resolve_application` helper before the mixin's filter runs.
+
+These tests assert the contract: revisions are reachable by **either**
+the application id or the application slug, and a missing slug returns
+404 cleanly.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from ..models import AgentApplication, AgentRevision
+
+
+class TestRevisionsSlugLookup(APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="weekly-digest",
+ name="Weekly digest",
+ description="",
+ )
+ # Two revisions so a list call returns >0 and we can tell the slug
+ # path is actually resolving the right application.
+ self.revision_a = AgentRevision.all_teams.create(application=self.application, state="draft", spec={})
+ self.revision_b = AgentRevision.all_teams.create(application=self.application, state="draft", spec={})
+
+ def test_revisions_list_accepts_slug(self) -> None:
+ resp = self.client.get(f"/api/projects/{self.team.id}/agent_applications/{self.application.slug}/revisions/")
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ ids = {rev["id"] for rev in resp.json()["results"]}
+ self.assertEqual(ids, {str(self.revision_a.id), str(self.revision_b.id)})
+
+ def test_revisions_list_accepts_uuid(self) -> None:
+ # Slug + UUID must reach the same revisions.
+ resp = self.client.get(f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/")
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ ids = {rev["id"] for rev in resp.json()["results"]}
+ self.assertEqual(ids, {str(self.revision_a.id), str(self.revision_b.id)})
+
+ def test_revisions_list_unknown_slug_404s(self) -> None:
+ # Used to 500 with a ValidationError before the slug-resolution
+ # override landed. Now it 404s cleanly.
+ resp = self.client.get(f"/api/projects/{self.team.id}/agent_applications/does-not-exist/revisions/")
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_revision_retrieve_via_slug(self) -> None:
+ resp = self.client.get(
+ f"/api/projects/{self.team.id}/agent_applications/{self.application.slug}/revisions/{self.revision_a.id}/"
+ )
+ self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.json()["id"], str(self.revision_a.id))
+
+ def test_revisions_list_archived_application_404s(self) -> None:
+ # Archived applications shouldn't be reachable by slug either —
+ # the lookup queryset filters `archived=False`.
+ self.application.archived = True
+ self.application.save(update_fields=["archived"])
+ resp = self.client.get(f"/api/projects/{self.team.id}/agent_applications/{self.application.slug}/revisions/")
+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/agent_platform/backend/tests/test_session_logs.py b/products/agent_platform/backend/tests/test_session_logs.py
new file mode 100644
index 000000000000..4d7989355234
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_session_logs.py
@@ -0,0 +1,153 @@
+"""
+Regression: AgentApplicationViewSet.session_logs — per-session log fetch.
+
+Exercises the full Django → ClickHouse path so the class of bugs we hit
+landing this endpoint (PAT scope missing, untagged CH query, wrong
+default CH database) all get caught by CI:
+
+ * inserts a real row into the `log_entries` CH table
+ * hits `/agent_applications/<slug>/sessions/<session_id>/logs/`
+ * asserts 200 + the row comes back
+ * also asserts the action is declared as a scoped read action so
+ PAT / OAuth callers with `agents:read` aren't rejected
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from rest_framework import status
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQL
+
+from ..models import AgentApplication
+from ..presentation.views import AGENT_SESSION_LOG_SOURCE, AgentApplicationViewSet
+
+
+def _insert_log(
+ team_id: int,
+ application_id: str,
+ session_id: str,
+ level: str = "INFO",
+ message: str = "[meta] session_started",
+ when: str | None = None,
+) -> None:
+ sync_execute(
+ INSERT_LOG_ENTRY_SQL,
+ {
+ "team_id": team_id,
+ "log_source": AGENT_SESSION_LOG_SOURCE,
+ "log_source_id": application_id,
+ "instance_id": session_id,
+ "timestamp": when or datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "level": level,
+ "message": message,
+ },
+ )
+
+
+class TestSessionLogs(ClickhouseTestMixin, APIBaseTest):
+ databases = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="hello",
+ name="Hello agent",
+ description="",
+ )
+ self.session_id = str(uuid4())
+
+ def _url(self, session_id: str | None = None) -> str:
+ sid = session_id or self.session_id
+ return f"/api/projects/{self.team.id}/agent_applications/{self.application.slug}/sessions/{sid}/logs/"
+
+ # ── happy path ──────────────────────────────────────────────────
+
+ def test_returns_empty_when_no_logs(self) -> None:
+ # Sanity: the endpoint reaches CH and returns a cleanly empty
+ # result rather than 404/500 when the session has no logs yet.
+ res = self.client.get(self._url())
+ self.assertEqual(res.status_code, status.HTTP_200_OK)
+ self.assertEqual(res.json(), {"results": []})
+
+ def test_returns_inserted_rows_for_session(self) -> None:
+ # Inserts two rows for the target session + one decoy for a
+ # different session and asserts only the target's land back.
+ _insert_log(
+ self.team.id,
+ str(self.application.id),
+ self.session_id,
+ level="INFO",
+ message="[meta] session_started",
+ when="2026-05-29 12:00:00.000000",
+ )
+ _insert_log(
+ self.team.id,
+ str(self.application.id),
+ self.session_id,
+ level="INFO",
+ message="[event] completed",
+ when="2026-05-29 12:00:01.000000",
+ )
+ _insert_log(
+ self.team.id,
+ str(self.application.id),
+ "00000000-0000-0000-0000-000000000099", # different session
+ level="INFO",
+ message="should not appear",
+ )
+
+ res = self.client.get(self._url())
+ self.assertEqual(res.status_code, status.HTTP_200_OK)
+ results = res.json()["results"]
+ self.assertEqual(len(results), 2)
+ # Newest first — `fetch_log_entries` does `ORDER BY timestamp DESC`.
+ messages = [r["message"] for r in results]
+ self.assertEqual(messages, ["[event] completed", "[meta] session_started"])
+
+ def test_filter_by_level(self) -> None:
+ _insert_log(self.team.id, str(self.application.id), self.session_id, level="INFO", message="info row")
+ _insert_log(self.team.id, str(self.application.id), self.session_id, level="ERROR", message="error row")
+
+ res = self.client.get(self._url(), {"level": "ERROR"})
+ self.assertEqual(res.status_code, status.HTTP_200_OK)
+ messages = [r["message"] for r in res.json()["results"]]
+ self.assertEqual(messages, ["error row"])
+
+ def test_search_substring(self) -> None:
+ _insert_log(self.team.id, str(self.application.id), self.session_id, message="[tool] assistant_text foo")
+ _insert_log(self.team.id, str(self.application.id), self.session_id, message="[meta] session_started")
+
+ res = self.client.get(self._url(), {"search": "foo"})
+ self.assertEqual(res.status_code, status.HTTP_200_OK)
+ messages = [r["message"] for r in res.json()["results"]]
+ self.assertEqual(messages, ["[tool] assistant_text foo"])
+
+ # ── 404s + cross-team isolation ─────────────────────────────────
+
+ def test_unknown_application_slug_404s(self) -> None:
+ res = self.client.get(
+ f"/api/projects/{self.team.id}/agent_applications/does-not-exist/sessions/{self.session_id}/logs/"
+ )
+ self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND)
+
+ # ── PAT / OAuth scope hygiene ───────────────────────────────────
+
+ def test_session_logs_is_a_declared_read_action(self) -> None:
+ # Regression for the 403 we shipped — the PAT/OAuth scope check
+ # rejects any action not listed in `scope_object_read_actions`
+ # or `_write_actions` with "This action does not support
+ # personal API key access". Lock the membership down.
+ self.assertIn("session_logs", AgentApplicationViewSet.scope_object_read_actions)
diff --git a/products/agent_platform/backend/tests/test_slug_minting.py b/products/agent_platform/backend/tests/test_slug_minting.py
new file mode 100644
index 000000000000..81cc7782bab0
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_slug_minting.py
@@ -0,0 +1,76 @@
+"""
+Slug ownership: the server mints a globally-unique slug on create, and only
+teams on AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS may set one explicitly. Slugs
+live in one global namespace (domain-mode ingress routing carries no team).
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from django.test import override_settings
+
+from rest_framework import status
+
+from posthog.models import Organization, Team
+
+from ..models import AgentApplication
+
+_DBS = {
+ "default",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+}
+
+
+class TestSlugMinting(APIBaseTest):
+ databases = _DBS
+
+ def _create(self, body: dict) -> tuple[int, dict]:
+ resp = self.client.post(f"/api/projects/{self.team.id}/agent_applications/", body)
+ return resp.status_code, resp.json()
+
+ def test_non_allowlisted_team_gets_minted_slug_ignoring_input(self) -> None:
+ status_code, body = self._create({"name": "Weekly digest", "slug": "weekly-digest"})
+ self.assertEqual(status_code, status.HTTP_201_CREATED, body)
+ # Explicit slug ignored; an opaque random slug is minted instead — no
+ # name prefix, leading letter, lowercase alphanumeric, no dashes.
+ self.assertNotIn("weekly", body["slug"])
+ self.assertRegex(body["slug"], r"^[a-z][a-z0-9]{11}$")
+
+ def test_minted_slug_without_input(self) -> None:
+ status_code, body = self._create({"name": "Support bot"})
+ self.assertEqual(status_code, status.HTTP_201_CREATED, body)
+ self.assertNotIn("support", body["slug"])
+ self.assertRegex(body["slug"], r"^[a-z][a-z0-9]{11}$")
+
+ @override_settings(AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS=set())
+ def test_minted_slugs_are_globally_unique_across_teams(self) -> None:
+ # Two agents with the same name on the same team still get distinct slugs.
+ _, first = self._create({"name": "Concierge"})
+ _, second = self._create({"name": "Concierge"})
+ self.assertNotEqual(first["slug"], second["slug"])
+
+ def test_allowlisted_team_may_set_explicit_slug(self) -> None:
+ with override_settings(AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS={self.team.id}):
+ status_code, body = self._create({"name": "Agent concierge", "slug": "agent-concierge"})
+ self.assertEqual(status_code, status.HTTP_201_CREATED, body)
+ self.assertEqual(body["slug"], "agent-concierge")
+
+ def test_explicit_slug_collision_is_a_clean_400(self) -> None:
+ with override_settings(AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS={self.team.id}):
+ self._create({"name": "Agent concierge", "slug": "agent-concierge"})
+ status_code, body = self._create({"name": "Imposter", "slug": "agent-concierge"})
+ self.assertEqual(status_code, status.HTTP_400_BAD_REQUEST, body)
+ self.assertEqual(body["attr"], "slug")
+
+ def test_explicit_slug_global_collision_across_teams(self) -> None:
+ # A slug taken by another team blocks an allowlisted explicit set —
+ # the namespace is global, not per-team.
+ other_org = Organization.objects.create(name="other-org")
+ other_team = Team.objects.create(organization=other_org, name="other-team")
+ AgentApplication.all_teams.create(team_id=other_team.id, slug="taken", name="other")
+ with override_settings(AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS={self.team.id}):
+ status_code, body = self._create({"name": "Mine", "slug": "taken"})
+ self.assertEqual(status_code, status.HTTP_400_BAD_REQUEST, body)
+ self.assertEqual(body["attr"], "slug")
diff --git a/products/agent_platform/backend/tests/test_slug_validation.py b/products/agent_platform/backend/tests/test_slug_validation.py
new file mode 100644
index 000000000000..e0ba3e8672ec
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_slug_validation.py
@@ -0,0 +1,70 @@
+"""
+Security: the agent slug is interpolated into the preview-proxy upstream URL, so
+it's constrained to a strict slug at three layers — the model SlugField, the
+serializer SlugField, and a defence-in-depth runtime check in preview_proxy that
+guards against a slug which reached the DB without the Django validators (e.g. a
+raw node-side write).
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from ..models import AgentApplication, AgentRevision
+
+_DBS = {
+ "default",
+ "persons_db_writer",
+ "persons_db_reader",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+}
+
+
+class TestSlugValidation(APIBaseTest):
+ databases = _DBS
+
+ @parameterized.expand(
+ [
+ ("space", "has spaces"),
+ ("slash", "bad/slash"),
+ ("dot", "dot.dot"),
+ ("unicode", "ünïcode"),
+ ]
+ )
+ def test_create_rejects_unsafe_slug(self, _name: str, slug: str) -> None:
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/agent_applications/",
+ {"name": "X", "slug": slug},
+ )
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content)
+
+ def test_create_accepts_valid_slug(self) -> None:
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/agent_applications/",
+ {"name": "Weekly digest", "slug": "weekly-digest"},
+ )
+ self.assertEqual(resp.status_code, status.HTTP_201_CREATED, resp.content)
+
+ @parameterized.expand(
+ [
+ # Slash → SSRF/path-traversal into the upstream URL.
+ ("slash", "evil/path"),
+ # Uppercase passes the model/serializer SlugField but the runtime
+ # check is stricter (lowercase only) — proves it's an independent layer.
+ ("uppercase", "MixedCase"),
+ ]
+ )
+ def test_preview_proxy_rejects_unsafe_slug_in_db(self, _name: str, slug: str) -> None:
+ # Simulate a write that bypassed the Django validators (e.g. raw node SQL):
+ # .create() does not run model field validators.
+ app = AgentApplication.all_teams.create(team_id=self.team.id, slug=slug, name="X")
+ rev = AgentRevision.all_teams.create(application=app, team_id=self.team.id, state="draft", spec={})
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/agent_applications/{app.id}/preview-proxy/run?revision_id={rev.id}"
+ )
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content)
+ self.assertIn("unsafe", str(resp.content).lower())
diff --git a/products/agent_platform/backend/tests/test_spec_schema.py b/products/agent_platform/backend/tests/test_spec_schema.py
new file mode 100644
index 000000000000..bd9468878a96
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_spec_schema.py
@@ -0,0 +1,294 @@
+"""
+Sanity tests for `validate_spec` on AgentRevisionSerializer.
+
+The JSON Schema in `spec_schema.py` is a hand-copied snapshot of the zod
+`AgentSpecSchema`. These tests cover the cases that matter for the
+authoring flow — known-bad specs that should be rejected before they hit
+the DB, and the minimal valid spec that should pass.
+
+Drift against zod is checked the next time someone touches the spec, not
+on every test run — the cost of a more aggressive check isn't worth it
+for a small surface that moves rarely.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from rest_framework.exceptions import ValidationError
+
+from ..logic.spec_schema import SLACK_BOT_TOKEN_KEY, SLACK_SIGNING_SECRET_KEY, missing_required_secrets
+from ..presentation.serializers import AgentRevisionSerializer
+
+# Auth is per-trigger now (no top-level spec.auth). These fixtures focus on
+# other fields, so give every declarative trigger a minimal public auth block
+# rather than repeat it in each case. Public exposure carries the explicit ack
+# field per AuthModeSchema in services/agent-shared/src/spec/spec.ts.
+_PUBLIC_AUTH = {"modes": [{"type": "public", "acknowledge_public_exposure": True}]}
+
+
+def _with_auth(spec: dict) -> dict:
+ triggers = spec.get("triggers")
+ if not isinstance(triggers, list):
+ return spec
+ patched = [
+ {**t, "auth": _PUBLIC_AUTH}
+ if isinstance(t, dict) and t.get("type") in ("webhook", "chat", "mcp") and "auth" not in t
+ else t
+ for t in triggers
+ ]
+ return {**spec, "triggers": patched}
+
+
+ ("name", "spec"),
+ [
+ ("minimal", {"model": "anthropic/claude-haiku-4-5"}),
+ (
+ "with_chat_trigger",
+ {
+ "model": "x",
+ "triggers": [{"type": "chat", "config": {}}],
+ },
+ ),
+ (
+ "kitchen_sink",
+ {
+ "model": "x",
+ "triggers": [
+ {"type": "chat", "config": {}},
+ {"type": "webhook", "config": {"path": "/hook"}},
+ ],
+ "tools": [{"kind": "native", "id": "@posthog/query"}],
+ "skills": [{"id": "research", "path": "skills/research.md"}],
+ "entrypoint": "agent.md",
+ },
+ ),
+ # Nested defaults must mirror zod: omitting fields with defaults at
+ # any depth is fine. These were the rough edges I hit when I first
+ # tried to spec the slack / cron triggers — both have config fields
+ # with `.default(...)` in zod that the JSON Schema lists as required.
+ (
+ "slack_omits_mention_only",
+ {
+ "model": "x",
+ "triggers": [{"type": "slack", "config": {"trusted_workspaces": "*"}}],
+ },
+ ),
+ (
+ "cron_omits_timezone",
+ {
+ "model": "x",
+ "triggers": [
+ {"type": "cron", "config": {"name": "hourly", "schedule": "0 * * * *", "prompt": "run it"}}
+ ],
+ },
+ ),
+ (
+ "mcp_omits_config",
+ {
+ "model": "x",
+ "triggers": [{"type": "mcp", "config": {}}],
+ },
+ ),
+ # External MCP ref with a mix of bare-string and object tool entries,
+ # all distinct names — accepted.
+ (
+ "external_mcp_unique_tools",
+ {
+ "model": "x",
+ "mcps": [
+ {
+ "id": "linear",
+ "url": "https://mcp.linear.app/sse",
+ "tools": ["list-issues", {"name": "create-issue", "requires_approval": True}],
+ }
+ ],
+ },
+ ),
+ # BYO bearer token: author drops a PAT into spec.secrets, references
+ # it from mcps[].headers. Mirrors @posthog/http-request's shape; the
+ # runner walks `headers` and substitutes `${NAME}` at session start.
+ (
+ "external_mcp_byo_headers_with_secret",
+ {
+ "model": "x",
+ "secrets": ["GITHUB_TOKEN"],
+ "mcps": [
+ {
+ "id": "github",
+ "url": "https://api.githubcopilot.com/mcp",
+ "secrets": ["GITHUB_TOKEN"],
+ "headers": {
+ "Authorization": "Bearer ${GITHUB_TOKEN}",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ }
+ ],
+ },
+ ),
+ # Registry-pin shapes the freeze pipeline resolves: a skill carrying
+ # `from_template` + `alias` (+ optional `version`) alongside the
+ # runtime id/path, and a `custom_template` tool ref. Before these
+ # were added to the schema, authoring either was rejected.
+ (
+ "skill_from_template",
+ {
+ "model": "x",
+ "skills": [
+ {
+ "id": "research",
+ "path": "skills/research/SKILL.md",
+ "from_template": "019e7fb7-f4c0-75e2-9055-7c29a5cbb923",
+ "alias": "research",
+ "version": 3,
+ }
+ ],
+ },
+ ),
+ (
+ "custom_template_tool",
+ {
+ "model": "x",
+ "tools": [
+ {
+ "kind": "custom_template",
+ "from_template": "019e7fb7-f4c0-75e2-9055-7c29a5cbb924",
+ "alias": "stripe_lookup",
+ "version": 4,
+ }
+ ],
+ },
+ ),
+ # max_output_tokens is optional; runner picks a reasoning-aware default.
+ (
+ "limits_max_output_tokens",
+ {"model": "x", "limits": {"max_output_tokens": 16384}},
+ ),
+ ],
+)
+def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:
+ AgentRevisionSerializer().validate_spec(_with_auth(spec))
+
+
+ ("name", "spec", "expected_substring"),
+ [
+ # The exact case we hit today: a spec that looks like an application
+ # row (name/description) instead of a runtime config (model).
+ ("missing_model", {"name": "Hedgebox Helper"}, "model"),
+ # `model` must be a non-empty string. zod uses min(1); JSON Schema
+ # mirrors that via minLength.
+ ("empty_model", {"model": ""}, "model"),
+ # `triggers` must be an array if present, not a string.
+ ("triggers_wrong_type", {"model": "x", "triggers": "all"}, "triggers"),
+ # Discriminated union: an unknown trigger type doesn't match any of
+ # the chat/slack/webhook/cron/mcp variants.
+ (
+ "unknown_trigger_type",
+ {"model": "x", "triggers": [{"type": "carrier_pigeon", "config": {}}]},
+ "triggers",
+ ),
+ # Top-level `additionalProperties: false` should reject extra keys —
+ # exactly the `name` / `description` case I tripped earlier.
+ ("extra_top_level_key", {"model": "x", "description": "agent"}, "description"),
+ # Non-defaulted nested fields must still be rejected when missing —
+ # the relaxation only removes required-with-defaults, not all required.
+ # jsonschema's `oneOf` error doesn't surface which arm failed for what
+ # reason; we just assert the trigger element itself is flagged.
+ (
+ "slack_missing_trusted_workspaces",
+ {"model": "x", "triggers": [{"type": "slack", "config": {"mention_only": False}}]},
+ "triggers.0",
+ ),
+ (
+ "cron_missing_schedule",
+ {"model": "x", "triggers": [{"type": "cron", "config": {"timezone": "UTC"}}]},
+ "triggers.0",
+ ),
+ # Duplicate tool names in `mcps[].external.tools[]` — JSON Schema can't
+ # express this across the string/object union, so the Python-level
+ # check mirrors the zod `.refine()`. Bare-string vs bare-string.
+ (
+ "external_mcp_duplicate_tool_strings",
+ {
+ "model": "x",
+ "mcps": [
+ {
+ "id": "linear",
+ "url": "https://mcp.linear.app/sse",
+ "tools": ["create-issue", "create-issue"],
+ }
+ ],
+ },
+ "unique names",
+ ),
+ # Bare-string colliding with an object of the same name — the case
+ # JSON Schema's `uniqueItems` would miss entirely.
+ (
+ "external_mcp_duplicate_tool_string_and_object",
+ {
+ "model": "x",
+ "mcps": [
+ {
+ "id": "linear",
+ "url": "https://mcp.linear.app/sse",
+ "tools": ["create-issue", {"name": "create-issue", "requires_approval": True}],
+ }
+ ],
+ },
+ "unique names",
+ ),
+ # The exact drift that poisoned the cron sweep: a cron trigger without
+ # the now-required `prompt` (or `name`). The node schema rejects these
+ # at freeze; the Django mirror must reject them at write so a poisoned
+ # spec never reaches the DB in the first place.
+ (
+ "cron_missing_prompt",
+ {"model": "x", "triggers": [{"type": "cron", "config": {"name": "sweep", "schedule": "0 9 * * *"}}]},
+ "triggers.0",
+ ),
+ (
+ "cron_missing_name",
+ {"model": "x", "triggers": [{"type": "cron", "config": {"schedule": "0 9 * * *", "prompt": "go"}}]},
+ "triggers.0",
+ ),
+ ],
+)
+def test_validate_spec_rejects_invalid_payloads(name: str, spec: dict, expected_substring: str) -> None:
+ with pytest.raises(ValidationError) as exc_info:
+ AgentRevisionSerializer().validate_spec(_with_auth(spec))
+ assert expected_substring in str(exc_info.value)
+
+
+_SLACK_SPEC = {
+ "model": "x",
+ "triggers": [{"type": "slack", "config": {"trusted_workspaces": "*"}}],
+}
+
+
+ ("name", "env", "expected_missing_keys"),
+ [
+ ("none_set", {}, {SLACK_SIGNING_SECRET_KEY, SLACK_BOT_TOKEN_KEY}),
+ ("only_signing_set", {SLACK_SIGNING_SECRET_KEY: "shh"}, {SLACK_BOT_TOKEN_KEY}),
+ ("only_bot_set", {SLACK_BOT_TOKEN_KEY: "xoxb-abc"}, {SLACK_SIGNING_SECRET_KEY}),
+ ("both_set", {SLACK_SIGNING_SECRET_KEY: "shh", SLACK_BOT_TOKEN_KEY: "xoxb-abc"}, set()),
+ (
+ "blank_treated_as_missing",
+ {SLACK_SIGNING_SECRET_KEY: "", SLACK_BOT_TOKEN_KEY: ""},
+ {SLACK_SIGNING_SECRET_KEY, SLACK_BOT_TOKEN_KEY},
+ ),
+ ],
+)
+def test_missing_required_secrets_for_slack_trigger(name: str, env: dict, expected_missing_keys: set) -> None:
+ missing = missing_required_secrets(_SLACK_SPEC, env)
+ assert {entry["key"] for entry in missing} == expected_missing_keys
+ for entry in missing:
+ assert entry["trigger"] == "slack"
+ assert entry["required"] is True
+
+
+def test_missing_required_secrets_skips_triggers_without_requirements() -> None:
+ spec = {"model": "x", "triggers": [{"type": "chat", "config": {}}]}
+ assert missing_required_secrets(spec, {}) == []
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..e44a624fc510
--- /dev/null
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -0,0 +1,1766 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+export type AgentApplicationApiCreatedBy = {
+ readonly id?: number
+ readonly first_name?: string
+ readonly email?: string
+} | null
+
+export interface AgentApplicationApi {
+ readonly id: string
+ readonly team_id: number
+ /** @maxLength 255 */
+ name: string
+ /**
+ * Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).
+ * @maxLength 63
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string
+ description?: string
+ /** @nullable */
+ readonly live_revision: string | null
+ archived?: boolean
+ /** @nullable */
+ readonly archived_at: string | null
+ /** @nullable */
+ readonly created_by_id: number | null
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by: AgentApplicationApiCreatedBy
+ readonly created_at: string
+ readonly updated_at: string
+ /**
+ * Public URL to paste into the Slack app dashboard under Event Subscriptions → Request URL. Computed from the agent slug and the deployment's ingress routing mode (`AGENT_INGRESS_DOMAIN_SUFFIX` in domain mode, `AGENT_INGRESS_PUBLIC_URL` in path mode). Null when no public agent-ingress URL is configured (e.g. local dev without a tunnel).
+ * @nullable
+ */
+ readonly slack_events_url: string | null
+ /**
+ * Public URL to paste into the Slack app dashboard under Interactivity & Shortcuts → Request URL. Same source + null behaviour as `slack_events_url`.
+ * @nullable
+ */
+ readonly slack_interactivity_url: string | null
+ /**
+ * Mode-aware base URL the agent's trigger routes hang off — append `/webhook`, `/run`, `/mcp`, etc. Domain mode: `https://<slug><suffix>`; path mode: `<public_url>/agents/<slug>`. Same source + null behaviour as `slack_events_url` (null when no public ingress URL is configured).
+ * @nullable
+ */
+ readonly ingress_base_url: string | null
+}
+
+export interface PaginatedAgentApplicationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AgentApplicationApi[]
+}
+
+export interface AgentMemoryHeaderApi {
+ /** Relative path within the agent's memory, e.g. 'incidents/db.md'. */
+ path: string
+ /** One-line summary from the file's frontmatter. */
+ description: string
+ /** Frontmatter tags (lowercase a-z 0-9 _ - only). */
+ tags: string[]
+ /**
+ * ISO-8601 timestamp stamped on create. Null for files written before this field was introduced.
+ * @nullable
+ */
+ created_at: string | null
+ /**
+ * ISO-8601 timestamp stamped on every write.
+ * @nullable
+ */
+ updated_at: string | null
+}
+
+export interface AgentMemoryListResponseApi {
+ /** Number of entries returned. */
+ count: number
+ /** Headers (frontmatter only) — no file bodies. Use the read endpoint for the body. */
+ entries: AgentMemoryHeaderApi[]
+}
+
+/**
+ * Body shape for AgentMemoryViewSet.write_file (create).
+ */
+export interface AgentMemoryWriteRequestApi {
+ /** Where to store the file. Lowercase a-z 0-9 _ - / only, must end in .md. */
+ path: string
+ /**
+ * One-line summary, max 280 chars. Surfaces in list/search results.
+ * @maxLength 280
+ */
+ description: string
+ /** Full markdown body. */
+ content: string
+ /** Optional flat tags for search ranking. Lowercase a-z 0-9 _ - only. */
+ tags?: string[]
+}
+
+export interface AgentMemoryFileApi {
+ /** Full markdown body. */
+ content: string
+}
+
+/**
+ * Body shape for AgentMemoryViewSet.update_file. Omitted fields preserve the existing value.
+ */
+export interface PatchedAgentMemoryUpdateRequestApi {
+ /** @maxLength 280 */
+ description?: string
+ content?: string
+ tags?: string[]
+}
+
+export interface AgentMemorySearchResultApi {
+ path: string
+ description: string
+ tags: string[]
+ /** BM25 relevance score. */
+ score: number
+ /**
+ * Body snippet around the earliest match. Null when only the header matched.
+ * @nullable
+ */
+ snippet: string | null
+}
+
+export interface AgentMemorySearchResponseApi {
+ /** The original search cue, echoed back. */
+ cue: string
+ count: number
+ results: AgentMemorySearchResultApi[]
+}
+
+export interface AgentTableHeaderApi {
+ /** Table name. */
+ name: string
+ /** Object size in bytes. */
+ size: number
+}
+
+export interface AgentTablesListResponseApi {
+ /** Number of tables. */
+ count: number
+ /** Tabular-reference tables for this agent (the @posthog/table-* JSONL tables). */
+ tables: AgentTableHeaderApi[]
+}
+
+export type AgentTableRowsResponseApiRowsItem = { [key: string]: unknown }
+
+export interface AgentTableRowsResponseApi {
+ name: string
+ /** Total rows in the table. */
+ total: number
+ /** Rows in this response (capped by limit). */
+ returned: number
+ limit: number
+ /** The rows (arbitrary JSON objects). */
+ rows: AgentTableRowsResponseApiRowsItem[]
+}
+
+/**
+ * Folder tree rooted at the agent's memory prefix. Each node is {name, type: 'folder'|'file', path?, description?, tags?, children?}.
+ */
+export type AgentMemoryTreeResponseApiRoot = { [key: string]: unknown }
+
+export interface AgentMemoryTreeResponseApi {
+ /** Folder tree rooted at the agent's memory prefix. Each node is {name, type: 'folder'|'file', path?, description?, tags?, children?}. */
+ root: AgentMemoryTreeResponseApiRoot
+}
+
+/**
+ * * `draft` - draft
+ * * `ready` - ready
+ * * `live` - live
+ * * `archived` - archived
+ */
+export type AgentRevisionStateEnumApi = (typeof AgentRevisionStateEnumApi)[keyof typeof AgentRevisionStateEnumApi]
+
+export const AgentRevisionStateEnumApi = {
+ Draft: 'draft',
+ Ready: 'ready',
+ Live: 'live',
+ Archived: 'archived',
+} as const
+
+export type AgentRevisionApiSpecReasoning =
+ (typeof AgentRevisionApiSpecReasoning)[keyof typeof AgentRevisionApiSpecReasoning]
+
+export const AgentRevisionApiSpecReasoning = {
+ Minimal: 'minimal',
+ Low: 'low',
+ Medium: 'medium',
+ High: 'high',
+ Xhigh: 'xhigh',
+} as const
+
+export type AgentRevisionApiSpecTriggersItem =
+ | {
+ type: 'slack'
+ config: {
+ channel_id?: string
+ mention_only: boolean
+ auto_resume_threads: boolean
+ allow_workspace_participants: boolean
+ ack_reaction?: string
+ trusted_workspaces: string[] | '*'
+ }
+ }
+ | {
+ type: 'webhook'
+ config: {
+ path: string
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+ | {
+ type: 'cron'
+ config: {
+ /** @minLength 1 */
+ name: string
+ /** @minLength 1 */
+ schedule: string
+ timezone?: string
+ /**
+ * @minLength 1
+ * @maxLength 4096
+ */
+ prompt: string
+ external_key?: string
+ catch_up?: 'all' | 'most_recent' | 'skip'
+ /**
+ * @minimum 1
+ * @maximum 604800
+ */
+ max_catch_up_age_seconds?: number
+ }
+ }
+ | {
+ type: 'chat'
+ config?: {
+ allow_restart?: boolean
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+ | {
+ type: 'mcp'
+ config?: {
+ allow_restart?: boolean
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+
+export type AgentRevisionApiSpecToolsItem =
+ | {
+ kind: 'native'
+ id: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+ | {
+ kind: 'custom'
+ id: string
+ path: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+ | {
+ kind: 'custom_template'
+ from_template: string
+ alias: string
+ /** @minimum 0 */
+ version?: number
+ }
+ | {
+ kind: 'client'
+ /** @minLength 1 */
+ id: string
+ /** @minLength 1 */
+ description: string
+ args_schema?: { [key: string]: unknown }
+ required?: boolean
+ /**
+ * @minimum 1
+ * @maximum 600000
+ */
+ timeout_ms?: number
+ interactive?: boolean
+ }
+
+export type AgentRevisionApiSpecMcpsItemAuth = {
+ integration?: string
+}
+
+export type AgentRevisionApiSpecMcpsItemHeaders = { [key: string]: string }
+
+export type AgentRevisionApiSpecMcpsItemToolsItem =
+ | string
+ | {
+ /** @minLength 1 */
+ name: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+
+export type AgentRevisionApiSpecMcpsItem = {
+ /** @minLength 1 */
+ id: string
+ url: string
+ auth?: AgentRevisionApiSpecMcpsItemAuth
+ secrets?: string[]
+ headers?: AgentRevisionApiSpecMcpsItemHeaders
+ tools?: AgentRevisionApiSpecMcpsItemToolsItem[]
+}
+
+export type AgentRevisionApiSpecSkillsItem = {
+ id: string
+ path: string
+ description?: string
+ from_template?: string
+ alias?: string
+ /** @minimum 0 */
+ version?: number
+}
+
+export type AgentRevisionApiSpecLimits = {
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_turns: number
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_tool_calls: number
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_wall_seconds: number
+ /**
+ * @maximum 200000
+ * @exclusiveMinimum 0
+ */
+ max_output_tokens?: number
+}
+
+export type AgentRevisionApiSpec = {
+ /** @minLength 1 */
+ model: string
+ triggers: AgentRevisionApiSpecTriggersItem[]
+ tools: AgentRevisionApiSpecToolsItem[]
+ mcps: AgentRevisionApiSpecMcpsItem[]
+ skills: AgentRevisionApiSpecSkillsItem[]
+ integrations: string[]
+ secrets: string[]
+ limits: AgentRevisionApiSpecLimits
+ entrypoint: string
+ reasoning?: AgentRevisionApiSpecReasoning
+}
+
+/**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+export type AgentRevisionApiCreatedBy = {
+ readonly id?: number
+ readonly first_name?: string
+ readonly email?: string
+} | null
+
+export interface AgentRevisionApi {
+ readonly id: string
+ readonly application: string
+ /** @nullable */
+ parent_revision?: string | null
+ readonly state: AgentRevisionStateEnumApi
+ bundle_uri?: string
+ /** @nullable */
+ readonly bundle_sha256: string | null
+ spec?: AgentRevisionApiSpec
+ /** @nullable */
+ readonly created_by_id: number | null
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by: AgentRevisionApiCreatedBy
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedAgentRevisionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AgentRevisionApi[]
+}
+
+export type PatchedAgentRevisionApiSpecTriggersItem =
+ | {
+ type: 'slack'
+ config: {
+ channel_id?: string
+ mention_only: boolean
+ auto_resume_threads: boolean
+ allow_workspace_participants: boolean
+ ack_reaction?: string
+ trusted_workspaces: string[] | '*'
+ }
+ }
+ | {
+ type: 'webhook'
+ config: {
+ path: string
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+ | {
+ type: 'cron'
+ config: {
+ /** @minLength 1 */
+ name: string
+ /** @minLength 1 */
+ schedule: string
+ timezone?: string
+ /**
+ * @minLength 1
+ * @maxLength 4096
+ */
+ prompt: string
+ external_key?: string
+ catch_up?: 'all' | 'most_recent' | 'skip'
+ /**
+ * @minimum 1
+ * @maximum 604800
+ */
+ max_catch_up_age_seconds?: number
+ }
+ }
+ | {
+ type: 'chat'
+ config?: {
+ allow_restart?: boolean
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+ | {
+ type: 'mcp'
+ config?: {
+ allow_restart?: boolean
+ }
+ auth: {
+ modes?: (
+ | {
+ type: 'public'
+ acknowledge_public_exposure: true
+ }
+ | {
+ type: 'posthog'
+ scopes?: string[]
+ }
+ | {
+ type: 'jwt'
+ /** @minLength 1 */
+ issuer_secret_ref: string
+ }
+ | {
+ type: 'shared_secret'
+ /** @minLength 1 */
+ header: string
+ /** @minLength 1 */
+ secret_ref: string
+ }
+ | {
+ type: 'posthog_internal'
+ }
+ )[]
+ }
+ }
+
+export type PatchedAgentRevisionApiSpecToolsItem =
+ | {
+ kind: 'native'
+ id: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+ | {
+ kind: 'custom'
+ id: string
+ path: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+ | {
+ kind: 'custom_template'
+ from_template: string
+ alias: string
+ /** @minimum 0 */
+ version?: number
+ }
+ | {
+ kind: 'client'
+ /** @minLength 1 */
+ id: string
+ /** @minLength 1 */
+ description: string
+ args_schema?: { [key: string]: unknown }
+ required?: boolean
+ /**
+ * @minimum 1
+ * @maximum 600000
+ */
+ timeout_ms?: number
+ interactive?: boolean
+ }
+
+export type PatchedAgentRevisionApiSpecMcpsItemAuth = {
+ integration?: string
+}
+
+export type PatchedAgentRevisionApiSpecMcpsItemHeaders = { [key: string]: string }
+
+export type PatchedAgentRevisionApiSpecMcpsItemToolsItem =
+ | string
+ | {
+ /** @minLength 1 */
+ name: string
+ requires_approval?: boolean
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[]
+ allow_edit?: boolean
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number
+ allow_agent_approver?: boolean
+ }
+ }
+
+export type PatchedAgentRevisionApiSpecMcpsItem = {
+ /** @minLength 1 */
+ id: string
+ url: string
+ auth?: PatchedAgentRevisionApiSpecMcpsItemAuth
+ secrets?: string[]
+ headers?: PatchedAgentRevisionApiSpecMcpsItemHeaders
+ tools?: PatchedAgentRevisionApiSpecMcpsItemToolsItem[]
+}
+
+export type PatchedAgentRevisionApiSpecSkillsItem = {
+ id: string
+ path: string
+ description?: string
+ from_template?: string
+ alias?: string
+ /** @minimum 0 */
+ version?: number
+}
+
+export type PatchedAgentRevisionApiSpecLimits = {
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_turns: number
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_tool_calls: number
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_wall_seconds: number
+ /**
+ * @maximum 200000
+ * @exclusiveMinimum 0
+ */
+ max_output_tokens?: number
+}
+
+export type PatchedAgentRevisionApiSpecReasoning =
+ (typeof PatchedAgentRevisionApiSpecReasoning)[keyof typeof PatchedAgentRevisionApiSpecReasoning]
+
+export const PatchedAgentRevisionApiSpecReasoning = {
+ Minimal: 'minimal',
+ Low: 'low',
+ Medium: 'medium',
+ High: 'high',
+ Xhigh: 'xhigh',
+} as const
+
+export type PatchedAgentRevisionApiSpec = {
+ /** @minLength 1 */
+ model: string
+ triggers: PatchedAgentRevisionApiSpecTriggersItem[]
+ tools: PatchedAgentRevisionApiSpecToolsItem[]
+ mcps: PatchedAgentRevisionApiSpecMcpsItem[]
+ skills: PatchedAgentRevisionApiSpecSkillsItem[]
+ integrations: string[]
+ secrets: string[]
+ limits: PatchedAgentRevisionApiSpecLimits
+ entrypoint: string
+ reasoning?: PatchedAgentRevisionApiSpecReasoning
+}
+
+/**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+export type PatchedAgentRevisionApiCreatedBy = {
+ readonly id?: number
+ readonly first_name?: string
+ readonly email?: string
+} | null
+
+export interface PatchedAgentRevisionApi {
+ readonly id?: string
+ readonly application?: string
+ /** @nullable */
+ parent_revision?: string | null
+ readonly state?: AgentRevisionStateEnumApi
+ bundle_uri?: string
+ /** @nullable */
+ readonly bundle_sha256?: string | null
+ spec?: PatchedAgentRevisionApiSpec
+ /** @nullable */
+ readonly created_by_id?: number | null
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by?: PatchedAgentRevisionApiCreatedBy
+ readonly created_at?: string
+ readonly updated_at?: string
+}
+
+/**
+ * Body shape for PUT /revisions/<id>/agent_md/.
+ */
+export interface WriteAgentMdRequestApi {
+ content: string
+}
+
+export type WriteTypedBundleRequestApiSpec = { [key: string]: unknown }
+
+/**
+ * Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored
+ * at the canonical `skills/<skill_id>/SKILL.md` path in the bundle.
+ */
+export interface WriteSkillRequestApi {
+ /** One-line summary shown in the skill index; the model uses it to decide when to load the skill. */
+ description: string
+ /** The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`. */
+ body: string
+}
+
+export type WriteToolRequestApiArgsSchema = { [key: string]: unknown }
+
+/**
+ * Body shape for PUT /revisions/<id>/tools/<tool_id>/.
+ */
+export interface WriteToolRequestApi {
+ description: string
+ args_schema: WriteToolRequestApiArgsSchema
+ source: string
+}
+
+/**
+ * Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed
+ * payload. See docs/agent-platform/plans/typed-bundle-authoring-api.md §3.
+ */
+export interface WriteTypedBundleRequestApi {
+ agent_md: string
+ skills?: WriteSkillRequestApi[]
+ tools?: WriteToolRequestApi[]
+ spec: WriteTypedBundleRequestApiSpec
+}
+
+/**
+ * Body shape for POST /revisions/<id>/clone_from/ — copy every file
+ * from `source_revision_id` into this (draft) revision.
+ */
+export interface CloneFromRequestApi {
+ source_revision_id: string
+}
+
+export interface AgentRevisionCronFireRequestApi {
+ /** `name` of the cron trigger in `spec.triggers[]` to fire. */
+ cron_name: string
+ /**
+ * Stable client-supplied id so repeated clicks of the same UI 'Fire now' button resolve to the same session id rather than firing twice. The janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit to fire unconditionally — every call generates a fresh UUID.
+ * @nullable
+ */
+ request_id?: string | null
+}
+
+export interface AgentRevisionCronFireResponseApi {
+ ok: boolean
+ /** ID of the session the cron firing created (or returned, on dedupe). */
+ session_id: string
+ /** ISO-8601 timestamp the firing was attributed to. */
+ fired_at: string
+ /** Composed dedupe key — `cron-manual:<rev>:<name>:<request_id>`. Returned so the UI can correlate. */
+ idempotency_key: string
+ /** The request id the firing used (echoed back, or freshly minted). */
+ request_id: string
+}
+
+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. */
+ manifest: unknown
+ /** Reminders the manifest can't enforce (e.g. invite the bot to its channels). */
+ notes: string[]
+ /**
+ * The Event Subscriptions Request URL baked into the manifest.
+ * @nullable
+ */
+ events_url: string | null
+ /**
+ * The Interactivity Request URL (used by approval-gated tools).
+ * @nullable
+ */
+ interactivity_url: string | null
+}
+
+export type WriteSpecRequestApiSpec = { [key: string]: unknown }
+
+/**
+ * Body shape for PUT /revisions/<id>/spec/. The body's `spec` object
+ * is the author-facing slice (skills/tools are server-derived at freeze).
+ */
+export interface WriteSpecRequestApi {
+ spec: WriteSpecRequestApiSpec
+}
+
+export interface AgentRevisionSystemPromptResponseApi {
+ /** UUID of the revision the prompt was rendered for. */
+ revision_id: string
+ /** Active framework preamble version. Bumps when the platform's `# Platform guidance` content changes meaningfully (decision rules, sections renamed, behavioural defaults flipped). Authors can pin to a specific version via `spec.framework_prompt.version_pin`. */
+ framework_prompt_version: number
+ /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md` (or `spec.entrypoint`), and the skills index. Inspect before promotion to confirm the model will see what you expect — see docs/agent-platform/plans/framework-system-prompt.md §4. */
+ system_prompt: string
+}
+
+export interface AgentRevisionValidationErrorApi {
+ code: string
+ message: string
+ pointer: string
+}
+
+export interface AgentRevisionValidateResponseApi {
+ ok: boolean
+ revision_id: string
+ revision_state: string
+ errors: AgentRevisionValidationErrorApi[]
+ resolved_natives: string[]
+}
+
+/**
+ * Body shape for POST /revisions/clone_from/ — atomically create a new
+ * draft revision under `application_id` and clone its initial bundle from
+ * `source_revision_id`. Convenience for the "edit live" flow so the MCP
+ * doesn't have to do create-then-clone-from in two calls.
+ */
+export interface NewDraftRevisionRequestApi {
+ application_id: string
+ source_revision_id: string
+}
+
+/**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+export type PatchedAgentApplicationApiCreatedBy = {
+ readonly id?: number
+ readonly first_name?: string
+ readonly email?: string
+} | null
+
+export interface PatchedAgentApplicationApi {
+ readonly id?: string
+ readonly team_id?: number
+ /** @maxLength 255 */
+ name?: string
+ /**
+ * Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).
+ * @maxLength 63
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string
+ description?: string
+ /** @nullable */
+ readonly live_revision?: string | null
+ archived?: boolean
+ /** @nullable */
+ readonly archived_at?: string | null
+ /** @nullable */
+ readonly created_by_id?: number | null
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by?: PatchedAgentApplicationApiCreatedBy
+ readonly created_at?: string
+ readonly updated_at?: string
+ /**
+ * Public URL to paste into the Slack app dashboard under Event Subscriptions → Request URL. Computed from the agent slug and the deployment's ingress routing mode (`AGENT_INGRESS_DOMAIN_SUFFIX` in domain mode, `AGENT_INGRESS_PUBLIC_URL` in path mode). Null when no public agent-ingress URL is configured (e.g. local dev without a tunnel).
+ * @nullable
+ */
+ readonly slack_events_url?: string | null
+ /**
+ * Public URL to paste into the Slack app dashboard under Interactivity & Shortcuts → Request URL. Same source + null behaviour as `slack_events_url`.
+ * @nullable
+ */
+ readonly slack_interactivity_url?: string | null
+ /**
+ * Mode-aware base URL the agent's trigger routes hang off — append `/webhook`, `/run`, `/mcp`, etc. Domain mode: `https://<slug><suffix>`; path mode: `<public_url>/agents/<slug>`. Same source + null behaviour as `slack_events_url` (null when no public ingress URL is configured).
+ * @nullable
+ */
+ readonly ingress_base_url?: string | null
+}
+
+/**
+ * * `queued` - queued
+ * * `approving` - approving
+ * * `dispatched` - dispatched
+ * * `dispatched_failed` - dispatched_failed
+ * * `rejected` - rejected
+ * * `expired` - expired
+ */
+export type AgentApprovalRequestStateEnumApi =
+ (typeof AgentApprovalRequestStateEnumApi)[keyof typeof AgentApprovalRequestStateEnumApi]
+
+export const AgentApprovalRequestStateEnumApi = {
+ Queued: 'queued',
+ Approving: 'approving',
+ Dispatched: 'dispatched',
+ DispatchedFailed: 'dispatched_failed',
+ Rejected: 'rejected',
+ Expired: 'expired',
+} as const
+
+/**
+ * Arguments the model proposed. Frozen at intercept time.
+ */
+export type AgentApprovalRequestApiProposedArgs = { [key: string]: unknown }
+
+/**
+ * Approver-edited arguments. Present iff `approval_policy.allow_edit` was true and the approver supplied edits.
+ * @nullable
+ */
+export type AgentApprovalRequestApiDecidedArgs = { [key: string]: unknown } | null
+
+/**
+ * Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning.
+ */
+export type AgentApprovalRequestApiAssistantMessage = { [key: string]: unknown }
+
+/**
+ * Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.
+ */
+export type AgentApprovalRequestApiApproverScope = { [key: string]: unknown }
+
+/**
+ * `{result: ...}` on a successful approved dispatch, `{error: "..."}` when the tool threw. Null until the runner has finalised.
+ * @nullable
+ */
+export type AgentApprovalRequestApiDispatchOutcome = { [key: string]: unknown } | null
+
+export interface AgentApprovalRequestApi {
+ /** Approval request UUID — stable, used in /approvals/<id>/decide. */
+ id: string
+ /** UUID of the session that proposed the gated call. */
+ session_id: string
+ /** UUID of the parent agent application. */
+ application_id: string
+ /** Team that owns the agent. */
+ team_id: number
+ /** Revision the gated call was proposed against. */
+ revision_id: string
+ /** Turn number within the session that emitted the call. */
+ turn: number
+ /** pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result. */
+ tool_call_id: string
+ /** Tool id the model invoked (e.g. `@posthog/team-delete`). */
+ tool_name: string
+ /** Arguments the model proposed. Frozen at intercept time. */
+ proposed_args: AgentApprovalRequestApiProposedArgs
+ /**
+ * Approver-edited arguments. Present iff `approval_policy.allow_edit` was true and the approver supplied edits.
+ * @nullable
+ */
+ decided_args: AgentApprovalRequestApiDecidedArgs
+ /** Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning. */
+ assistant_message: AgentApprovalRequestApiAssistantMessage
+ /** Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time. */
+ approver_scope: AgentApprovalRequestApiApproverScope
+ /** Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.
+ *
+ * * `queued` - queued
+ * * `approving` - approving
+ * * `dispatched` - dispatched
+ * * `dispatched_failed` - dispatched_failed
+ * * `rejected` - rejected
+ * * `expired` - expired */
+ state: AgentApprovalRequestStateEnumApi
+ /**
+ * UUID of the user who decided. Null while queued or expired.
+ * @nullable
+ */
+ decision_by: string | null
+ /**
+ * ISO timestamp of the decision. Null while queued.
+ * @nullable
+ */
+ decision_at: string | null
+ /**
+ * Free-form reason supplied by the approver. Optional.
+ * @nullable
+ */
+ decision_reason: string | null
+ /**
+ * `{result: ...}` on a successful approved dispatch, `{error: "..."}` when the tool threw. Null until the runner has finalised.
+ * @nullable
+ */
+ dispatch_outcome: AgentApprovalRequestApiDispatchOutcome
+ /** When the model proposed the gated call. */
+ created_at: string
+ /** When the queued request auto-rejects if no decision arrives. */
+ expires_at: string
+}
+
+export interface AgentApplicationApprovalsListResponseApi {
+ /** Approval requests for this application, newest first. */
+ results: AgentApprovalRequestApi[]
+}
+
+/**
+ * Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422.
+ */
+export type DecideApprovalRequestApiEditedArgs = { [key: string]: unknown }
+
+/**
+ * * `approve` - approve
+ * * `reject` - reject
+ */
+export type DecisionEnumApi = (typeof DecisionEnumApi)[keyof typeof DecisionEnumApi]
+
+export const DecisionEnumApi = {
+ Approve: 'approve',
+ Reject: 'reject',
+} as const
+
+/**
+ * Body shape for POST /agent_applications/<id>/approvals/<approval_id>/decide/.
+ *
+ * See docs/agent-platform/plans/approval-gated-tools.md.
+ */
+export interface DecideApprovalRequestApi {
+ /** The approver's decision. `approve` runs the tool platform-side with the (possibly edited) args; `reject` records a terminal rejection and wakes the session with a synthetic rejected tool_result.
+ *
+ * * `approve` - approve
+ * * `reject` - reject */
+ decision: DecisionEnumApi
+ /** Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422. */
+ edited_args?: DecideApprovalRequestApiEditedArgs
+ /** Free-form approver note. Surfaces in the session's synthetic tool_result so the model can communicate the reason back to the user. */
+ reason?: string
+}
+
+export interface AgentApprovalsDecideResponseApi {
+ /** Always `true` on a successful decision. */
+ ok: boolean
+ /** The approval row's new state — `approving` for approve, `rejected` for reject. */
+ 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
+}
+
+export interface AgentApplicationPreviewTokenResponseApi {
+ /** 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
+ /** Token TTL in seconds from issue. Clients should refresh before this elapses. */
+ expires_in: number
+ /** Slug to use in the ingress URL — `<application_slug>-<revision_uuid_hex>`. Identifies the exact revision, placed in the host (domain mode) or path (path mode) routing prefix. */
+ ingress_slug: string
+ /** Per-trigger ingress URLs the caller can hit directly, derived from the revision's `spec.triggers[]`. Shape: `{<trigger_type>: {<route_name>: <absolute_url>}}`. Only includes triggers the spec actually declares. Empty when no public agent-ingress URL is configured for the active routing mode. */
+ endpoints: unknown
+ /** How to attach credentials to those endpoints: preview-token header/query names, the per-trigger accepted auth modes (`trigger_modes`), and a note about the live vs preview-mode gate split. Lets the caller wire auth without grepping the ingress source. */
+ auth: unknown
+ /** Server-side alternative — `/api/projects/<team>/agent_applications/<slug>/preview-proxy/<path>` mints the JWT for you. Strips caller Authorization, so it works for public-auth agents; agents with required auth need the direct endpoints above. */
+ preview_proxy: unknown
+}
+
+export interface AgentSessionUsageTotalApi {
+ tokens_in: number
+ tokens_out: number
+ cache_read: number
+ cache_write: number
+ cost_input: number
+ cost_output: number
+ cost_cache_read: number
+ cost_cache_write: number
+ cost_total: number
+}
+
+/**
+ * * `anonymous` - anonymous
+ * * `service` - service
+ * * `internal` - internal
+ * * `shared_secret` - shared_secret
+ * * `slack` - slack
+ */
+export type AgentSessionPrincipalKindEnumApi =
+ (typeof AgentSessionPrincipalKindEnumApi)[keyof typeof AgentSessionPrincipalKindEnumApi]
+
+export const AgentSessionPrincipalKindEnumApi = {
+ Anonymous: 'anonymous',
+ Service: 'service',
+ Internal: 'internal',
+ SharedSecret: 'shared_secret',
+ Slack: 'slack',
+} as const
+
+export interface AgentSessionPrincipalApi {
+ /** What kind of principal authenticated the session start.
+ *
+ * * `anonymous` - anonymous
+ * * `service` - service
+ * * `internal` - internal
+ * * `shared_secret` - shared_secret
+ * * `slack` - slack */
+ kind: AgentSessionPrincipalKindEnumApi
+ /** Stable identifier for the principal (PAT id, slack user id, etc). Absent for anonymous sessions. */
+ id?: string
+ /** Team the principal belongs to. Absent for anonymous sessions. */
+ team_id?: number
+}
+
+/**
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed
+ */
+export type AgentSessionStateEnumApi = (typeof AgentSessionStateEnumApi)[keyof typeof AgentSessionStateEnumApi]
+
+export const AgentSessionStateEnumApi = {
+ Queued: 'queued',
+ Running: 'running',
+ Completed: 'completed',
+ Closed: 'closed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+} as const
+
+/**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+export type AgentSessionSummaryApiTriggerMetadata = { [key: string]: unknown } | null
+
+export interface AgentSessionSummaryApi {
+ usage_total: AgentSessionUsageTotalApi
+ principal: AgentSessionPrincipalApi | null
+ id: string
+ application_id: string
+ revision_id: string
+ state: AgentSessionStateEnumApi
+ /** @nullable */
+ external_key: string | null
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentSessionSummaryApiTriggerMetadata
+ /** Count of messages in the conversation — the full transcript ships on the detail endpoint. */
+ turns: number
+ /**
+ * Last assistant text (~120 chars). Null for sessions with no assistant turns yet.
+ * @nullable
+ */
+ preview: string | null
+ retry_count: number
+ created_at: string
+ updated_at: string
+}
+
+export interface AgentApplicationSessionsListResponseApi {
+ results: AgentSessionSummaryApi[]
+ /** Total matching sessions before pagination. */
+ count: number
+}
+
+/**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+export type AgentApplicationSessionsRetrieveResponseApiTriggerMetadata = { [key: string]: unknown } | null
+
+export type AgentConversationUserMessageApiRole =
+ (typeof AgentConversationUserMessageApiRole)[keyof typeof AgentConversationUserMessageApiRole]
+
+export const AgentConversationUserMessageApiRole = {
+ User: 'user',
+} as const
+
+export interface AgentConversationUserMessageApi {
+ role: AgentConversationUserMessageApiRole
+ /** String shorthand, or array of {type:'text'|'image', ...} parts. */
+ content: unknown
+ /** Epoch milliseconds. */
+ timestamp: number
+}
+
+export type AgentConversationAssistantMessageApiRole =
+ (typeof AgentConversationAssistantMessageApiRole)[keyof typeof AgentConversationAssistantMessageApiRole]
+
+export const AgentConversationAssistantMessageApiRole = {
+ Assistant: 'assistant',
+} as const
+
+/**
+ * * `stop` - stop
+ * * `length` - length
+ * * `toolUse` - toolUse
+ * * `error` - error
+ * * `aborted` - aborted
+ */
+export type StopReasonEnumApi = (typeof StopReasonEnumApi)[keyof typeof StopReasonEnumApi]
+
+export const StopReasonEnumApi = {
+ Stop: 'stop',
+ Length: 'length',
+ ToolUse: 'toolUse',
+ Error: 'error',
+ Aborted: 'aborted',
+} as const
+
+export type AgentConversationAssistantMessageApiUsage = { [key: string]: unknown }
+
+export interface AgentConversationAssistantMessageApi {
+ role: AgentConversationAssistantMessageApiRole
+ /** Array of text/thinking/toolCall parts. */
+ content: unknown[]
+ /** Epoch milliseconds. */
+ timestamp: number
+ api?: string
+ provider?: string
+ model?: string
+ usage?: AgentConversationAssistantMessageApiUsage
+ stopReason?: StopReasonEnumApi
+ errorMessage?: string
+}
+
+export type AgentConversationToolResultMessageApiRole =
+ (typeof AgentConversationToolResultMessageApiRole)[keyof typeof AgentConversationToolResultMessageApiRole]
+
+export const AgentConversationToolResultMessageApiRole = {
+ ToolResult: 'toolResult',
+} as const
+
+export interface AgentConversationToolResultMessageApi {
+ role: AgentConversationToolResultMessageApiRole
+ toolCallId: string
+ toolName: string
+ /** Array of {type:'text'|'image', ...} parts. */
+ content: unknown[]
+ isError: boolean
+ /** Epoch milliseconds. */
+ timestamp: number
+}
+
+export type AgentConversationMessageApi =
+ | AgentConversationUserMessageApi
+ | AgentConversationAssistantMessageApi
+ | AgentConversationToolResultMessageApi
+
+export interface AgentApplicationSessionsRetrieveResponseApi {
+ usage_total: AgentSessionUsageTotalApi
+ principal: AgentSessionPrincipalApi | null
+ id: string
+ application_id: string
+ revision_id: string
+ team_id: number
+ /** @nullable */
+ external_key: string | null
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentApplicationSessionsRetrieveResponseApiTriggerMetadata
+ state: AgentSessionStateEnumApi
+ /** Full transcript, or the trailing `last_n` messages if `?last_n=` was supplied. */
+ conversation: AgentConversationMessageApi[]
+ /** Messages that arrived while a turn was in flight; drained into `conversation` at the start of the next turn. */
+ pending_inputs: AgentConversationMessageApi[]
+ /** Times the janitor has re-queued this session after a stuck-running detection. */
+ retry_count: number
+ created_at: string
+ updated_at: string
+ /** True when `?last_n=` was supplied AND the full conversation exceeded it. */
+ conversation_trimmed: boolean
+ /** Total messages in the untrimmed conversation. Present only when `conversation_trimmed=true`. */
+ conversation_total_turns?: number
+}
+
+export interface LogEntryApi {
+ log_source_id: string
+ instance_id: string
+ timestamp: string
+ level: string
+ message: string
+}
+
+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
+ /** Sessions created within the `since` window across all states. */
+ sessionsInWindowCount: number
+ /** Sum of `usage_total.cost_total` across sessions in the window. */
+ spendInWindowUsd: number
+ /**
+ * ISO timestamp of the most recent session update — null when there are no sessions.
+ * @nullable
+ */
+ lastActivityAt: string | null
+ /** Sessions in `failed` state created within the window. */
+ failedInWindowCount: number
+ /** Approval-gated tool requests across the team currently awaiting a decision. 0 on the per-application aggregate (which doesn't roll up approvals). */
+ pendingApprovalsCount: number
+}
+
+/**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+export type AgentFleetLiveSessionSummaryApiTriggerMetadata = { [key: string]: unknown } | null
+
+export interface AgentFleetLiveSessionSummaryApi {
+ usage_total: AgentSessionUsageTotalApi
+ principal: AgentSessionPrincipalApi | null
+ id: string
+ application_id: string
+ revision_id: string
+ team_id: number
+ state: AgentSessionStateEnumApi
+ /** @nullable */
+ external_key: string | null
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentFleetLiveSessionSummaryApiTriggerMetadata
+ /** Messages in the conversation so far. */
+ turns: number
+ /**
+ * Last assistant text (~120 chars). Null when no assistant turns yet.
+ * @nullable
+ */
+ preview: string | null
+ created_at: string
+ updated_at: string
+}
+
+export interface AgentFleetLiveSessionsResponseApi {
+ results: AgentFleetLiveSessionSummaryApi[]
+}
+
+export type AgentNativeToolEntryApiSchema = { [key: string]: unknown }
+
+export interface AgentNativeToolEntryApi {
+ id: string
+ schema: AgentNativeToolEntryApiSchema
+}
+
+export interface AgentNativeToolsListResponseApi {
+ tools: AgentNativeToolEntryApi[]
+}
+
+/**
+ * * `user` - user
+ */
+export type AgentConversationUserMessageRoleEnumApi =
+ (typeof AgentConversationUserMessageRoleEnumApi)[keyof typeof AgentConversationUserMessageRoleEnumApi]
+
+export const AgentConversationUserMessageRoleEnumApi = {
+ User: 'user',
+} as const
+
+/**
+ * * `assistant` - assistant
+ */
+export type AgentConversationAssistantMessageRoleEnumApi =
+ (typeof AgentConversationAssistantMessageRoleEnumApi)[keyof typeof AgentConversationAssistantMessageRoleEnumApi]
+
+export const AgentConversationAssistantMessageRoleEnumApi = {
+ Assistant: 'assistant',
+} as const
+
+/**
+ * * `toolResult` - toolResult
+ */
+export type AgentConversationToolResultMessageRoleEnumApi =
+ (typeof AgentConversationToolResultMessageRoleEnumApi)[keyof typeof AgentConversationToolResultMessageRoleEnumApi]
+
+export const AgentConversationToolResultMessageRoleEnumApi = {
+ ToolResult: 'toolResult',
+} as const
+
+export type AgentApplicationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type AgentMemoryListFilesParams = {
+ /**
+ * Optional path prefix to scope the list, e.g. 'incidents/'.
+ */
+ prefix?: string
+}
+
+export type AgentMemoryGetFileParams = {
+ /**
+ * Memory path returned by the list endpoint, e.g. 'incidents/db.md'.
+ */
+ path: string
+}
+
+export type AgentMemoryUpdateFileParams = {
+ /**
+ * Memory path to update.
+ */
+ path: string
+}
+
+export type AgentMemoryDeleteFileParams = {
+ /**
+ * Memory path to delete.
+ */
+ path: string
+}
+
+export type AgentMemorySearchParams = {
+ /**
+ * Max results (default 10, max 100).
+ */
+ limit?: number
+ /**
+ * Optional path prefix to scope the search.
+ */
+ prefix?: string
+ /**
+ * Search cue — plain natural language is fine.
+ */
+ q: string
+}
+
+export type AgentMemoryReadTableParams = {
+ /**
+ * Max rows to return (default 500, max 5000).
+ */
+ limit?: number
+}
+
+export type AgentApplicationsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type AgentApplicationsApprovalsListParams = {
+ limit?: number
+ offset?: number
+ /**
+ * Filter by approval state. Comma-separated list accepted. Valid values: queued, approving, dispatched, dispatched_failed, rejected, expired. Defaults to all states.
+ */
+ state?: string
+}
+
+export type AgentApplicationsPreviewProxyGetParams = {
+ format?: AgentApplicationsPreviewProxyGetFormat
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string
+}
+
+export type AgentApplicationsPreviewProxyGetFormat =
+ (typeof AgentApplicationsPreviewProxyGetFormat)[keyof typeof AgentApplicationsPreviewProxyGetFormat]
+
+export const AgentApplicationsPreviewProxyGetFormat = {
+ Json: 'json',
+ Sse: 'sse',
+} as const
+
+export type AgentApplicationsPreviewProxyParams = {
+ format?: AgentApplicationsPreviewProxyFormat
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string
+}
+
+export type AgentApplicationsPreviewProxyFormat =
+ (typeof AgentApplicationsPreviewProxyFormat)[keyof typeof AgentApplicationsPreviewProxyFormat]
+
+export const AgentApplicationsPreviewProxyFormat = {
+ Json: 'json',
+ Sse: 'sse',
+} as const
+
+export type AgentApplicationsPreviewTokenParams = {
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string
+}
+
+export type AgentApplicationsSessionsListParams = {
+ /**
+ * ISO datetime — return sessions with created_at >= this.
+ */
+ created_after?: string
+ /**
+ * ISO datetime — return sessions with created_at <= this.
+ */
+ created_before?: string
+ limit?: number
+ offset?: number
+ /**
+ * Only return sessions started against this specific revision.
+ */
+ revision_id?: string
+ /**
+ * Filter by session state. Comma-separated list accepted (e.g. `completed,failed`). Valid values: queued, running, completed, closed, cancelled, failed.
+ */
+ state?: string
+}
+
+export type AgentApplicationsSessionsRetrieveParams = {
+ /**
+ * If set, return only the most recent N messages from the conversation. `usage_total` is still computed over the full session — only the transcript is trimmed. The response includes `conversation_trimmed: true` and `conversation_total_turns` so the caller knows how much was hidden.
+ */
+ last_n?: number
+}
+
+export type AgentApplicationsSessionLogsParams = {
+ /**
+ * Only return entries after this ISO 8601 timestamp.
+ */
+ after?: string
+ /**
+ * Only return entries before this ISO 8601 timestamp.
+ */
+ before?: string
+ /**
+ * Filter logs to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string
+ /**
+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.
+ * @minLength 1
+ */
+ level?: string
+ /**
+ * Maximum number of log entries to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+ /**
+ * Case-insensitive substring search across log messages.
+ * @minLength 1
+ */
+ search?: string
+}
+
+export type AgentApplicationsStatsParams = {
+ /**
+ * ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.
+ */
+ since?: string
+}
+
+export type AgentFleetApprovalsListParams = {
+ /**
+ * Optional agent UUID — narrows the listing to one application.
+ */
+ agent_id?: string
+ limit?: number
+ offset?: number
+ /**
+ * Filter by approval state. Comma-separated list accepted. Valid values: queued, approving, dispatched, dispatched_failed, rejected, expired. Defaults to all states.
+ */
+ state?: string
+}
+
+export type AgentFleetLiveSessionsParams = {
+ /**
+ * Cap on returned sessions (default 100, max 500).
+ */
+ limit?: number
+}
+
+export type AgentFleetStatsParams = {
+ /**
+ * ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.
+ */
+ since?: string
+}
diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.ts
new file mode 100644
index 000000000000..71c493e4c80b
--- /dev/null
+++ b/products/agent_platform/frontend/generated/api.ts
@@ -0,0 +1,2045 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ AgentAggregateStatsApi,
+ AgentApplicationApi,
+ AgentApplicationApprovalsListResponseApi,
+ AgentApplicationEnvKeyStatusApi,
+ AgentApplicationEnvKeysResponseApi,
+ AgentApplicationPreviewTokenResponseApi,
+ AgentApplicationSessionLogsResponseApi,
+ AgentApplicationSessionsListResponseApi,
+ AgentApplicationSessionsRetrieveResponseApi,
+ AgentApplicationsApprovalsListParams,
+ AgentApplicationsListParams,
+ AgentApplicationsPreviewProxyGetParams,
+ AgentApplicationsPreviewProxyParams,
+ AgentApplicationsPreviewTokenParams,
+ AgentApplicationsRevisionsListParams,
+ AgentApplicationsSessionLogsParams,
+ AgentApplicationsSessionsListParams,
+ AgentApplicationsSessionsRetrieveParams,
+ AgentApplicationsStatsParams,
+ AgentApprovalsDecideResponseApi,
+ AgentFleetApprovalsListParams,
+ AgentFleetLiveSessionsParams,
+ AgentFleetLiveSessionsResponseApi,
+ AgentFleetStatsParams,
+ AgentMemoryDeleteFileParams,
+ AgentMemoryFileApi,
+ AgentMemoryGetFileParams,
+ AgentMemoryListFilesParams,
+ AgentMemoryListResponseApi,
+ AgentMemoryReadTableParams,
+ AgentMemorySearchParams,
+ AgentMemorySearchResponseApi,
+ AgentMemoryTreeResponseApi,
+ AgentMemoryUpdateFileParams,
+ AgentMemoryWriteRequestApi,
+ AgentNativeToolsListResponseApi,
+ AgentRevisionApi,
+ AgentRevisionCronFireRequestApi,
+ AgentRevisionCronFireResponseApi,
+ AgentRevisionSlackManifestResponseApi,
+ AgentRevisionSystemPromptResponseApi,
+ AgentRevisionValidateResponseApi,
+ AgentTableRowsResponseApi,
+ AgentTablesListResponseApi,
+ CloneFromRequestApi,
+ DecideApprovalRequestApi,
+ NewDraftRevisionRequestApi,
+ PaginatedAgentApplicationListApi,
+ PaginatedAgentRevisionListApi,
+ PatchedAgentApplicationApi,
+ PatchedAgentMemoryUpdateRequestApi,
+ PatchedAgentRevisionApi,
+ SetEnvKeyRequestApi,
+ SetEnvRequestApi,
+ WriteAgentMdRequestApi,
+ WriteSkillRequestApi,
+ WriteSpecRequestApi,
+ WriteToolRequestApi,
+ WriteTypedBundleRequestApi,
+} from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getAgentApplicationsListUrl = (projectId: string, params?: AgentApplicationsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsList = async (
+ projectId: string,
+ params?: AgentApplicationsListParams,
+ options?: RequestInit
+): Promise<PaginatedAgentApplicationListApi> => {
+ return apiMutator<PaginatedAgentApplicationListApi>(getAgentApplicationsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/agent_applications/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsCreate = async (
+ projectId: string,
+ agentApplicationApi: NonReadonly<AgentApplicationApi>,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentApplicationApi),
+ })
+}
+
+export const getAgentMemoryListFilesUrl = (
+ projectId: string,
+ applicationId: string,
+ params?: AgentMemoryListFilesParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/`
+}
+
+/**
+ * List memory file headers under the agent's prefix. Headers only — no bodies.
+ */
+export const agentMemoryListFiles = async (
+ projectId: string,
+ applicationId: string,
+ params?: AgentMemoryListFilesParams,
+ options?: RequestInit
+): Promise<AgentMemoryListResponseApi> => {
+ return apiMutator<AgentMemoryListResponseApi>(getAgentMemoryListFilesUrl(projectId, applicationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentMemoryCreateFileUrl = (projectId: string, applicationId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/`
+}
+
+/**
+ * Create a memory file. Fails if the path already exists — use the update endpoint to overwrite.
+ */
+export const agentMemoryCreateFile = async (
+ projectId: string,
+ applicationId: string,
+ agentMemoryWriteRequestApi: AgentMemoryWriteRequestApi,
+ options?: RequestInit
+): Promise<AgentMemoryFileApi> => {
+ return apiMutator<AgentMemoryFileApi>(getAgentMemoryCreateFileUrl(projectId, applicationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentMemoryWriteRequestApi),
+ })
+}
+
+export const getAgentMemoryGetFileUrl = (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryGetFileParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/`
+}
+
+/**
+ * Read one memory file in full (frontmatter + markdown body).
+ */
+export const agentMemoryGetFile = async (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryGetFileParams,
+ options?: RequestInit
+): Promise<AgentMemoryFileApi> => {
+ return apiMutator<AgentMemoryFileApi>(getAgentMemoryGetFileUrl(projectId, applicationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentMemoryUpdateFileUrl = (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryUpdateFileParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/`
+}
+
+/**
+ * Update a memory file. Any field omitted is preserved from the existing file.
+ */
+export const agentMemoryUpdateFile = async (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryUpdateFileParams,
+ patchedAgentMemoryUpdateRequestApi?: PatchedAgentMemoryUpdateRequestApi,
+ options?: RequestInit
+): Promise<AgentMemoryFileApi> => {
+ return apiMutator<AgentMemoryFileApi>(getAgentMemoryUpdateFileUrl(projectId, applicationId, params), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedAgentMemoryUpdateRequestApi),
+ })
+}
+
+export const getAgentMemoryDeleteFileUrl = (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryDeleteFileParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/files/by_path/`
+}
+
+/**
+ * Hard-delete a memory file. Activity log captures the action against the agent.
+ */
+export const agentMemoryDeleteFile = async (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemoryDeleteFileParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentMemoryDeleteFileUrl(projectId, applicationId, params), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getAgentMemorySearchUrl = (projectId: string, applicationId: string, params: AgentMemorySearchParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/search/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/search/`
+}
+
+/**
+ * BM25 search across the agent's memory files. Ranks by description+tags+path+body with field weighting.
+ */
+export const agentMemorySearch = async (
+ projectId: string,
+ applicationId: string,
+ params: AgentMemorySearchParams,
+ options?: RequestInit
+): Promise<AgentMemorySearchResponseApi> => {
+ return apiMutator<AgentMemorySearchResponseApi>(getAgentMemorySearchUrl(projectId, applicationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentMemoryListTablesUrl = (projectId: string, applicationId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/memory/tables/`
+}
+
+/**
+ * List the agent's tabular-reference tables (the @posthog/table-* JSONL tables): name + byte size.
+ */
+export const agentMemoryListTables = async (
+ projectId: string,
+ applicationId: string,
+ options?: RequestInit
+): Promise<AgentTablesListResponseApi> => {
+ return apiMutator<AgentTablesListResponseApi>(getAgentMemoryListTablesUrl(projectId, applicationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentMemoryReadTableUrl = (
+ projectId: string,
+ applicationId: string,
+ name: string,
+ params?: AgentMemoryReadTableParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/memory/tables/${name}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/memory/tables/${name}/`
+}
+
+/**
+ * Read rows from one tabular-reference table (capped via ?limit).
+ */
+export const agentMemoryReadTable = async (
+ projectId: string,
+ applicationId: string,
+ name: string,
+ params?: AgentMemoryReadTableParams,
+ options?: RequestInit
+): Promise<AgentTableRowsResponseApi> => {
+ return apiMutator<AgentTableRowsResponseApi>(getAgentMemoryReadTableUrl(projectId, applicationId, name, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentMemoryTreeUrl = (projectId: string, applicationId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/memory/tree/`
+}
+
+/**
+ * Pre-aggregated folder tree of memory files. Saves the frontend re-derivation work.
+ */
+export const agentMemoryTree = async (
+ projectId: string,
+ applicationId: string,
+ options?: RequestInit
+): Promise<AgentMemoryTreeResponseApi> => {
+ return apiMutator<AgentMemoryTreeResponseApi>(getAgentMemoryTreeUrl(projectId, applicationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsRevisionsListUrl = (
+ projectId: string,
+ applicationId: string,
+ params?: AgentApplicationsRevisionsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsList = async (
+ projectId: string,
+ applicationId: string,
+ params?: AgentApplicationsRevisionsListParams,
+ options?: RequestInit
+): Promise<PaginatedAgentRevisionListApi> => {
+ return apiMutator<PaginatedAgentRevisionListApi>(
+ getAgentApplicationsRevisionsListUrl(projectId, applicationId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsCreateUrl = (projectId: string, applicationId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsCreate = async (
+ projectId: string,
+ applicationId: string,
+ agentRevisionApi?: NonReadonly<AgentRevisionApi>,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsCreateUrl(projectId, applicationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentRevisionApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsRetrieveUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsRetrieve = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsRetrieveUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsRevisionsUpdateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/`
+}
+
+/**
+ * Spec edits are only allowed while state='draft'. Once promoted to
+ * ready/live the spec is frozen — change requires a new revision.
+ */
+export const agentApplicationsRevisionsUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ agentRevisionApi?: NonReadonly<AgentRevisionApi>,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsUpdateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentRevisionApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsPartialUpdateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsPartialUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ patchedAgentRevisionApi?: NonReadonly<PatchedAgentRevisionApi>,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsPartialUpdateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedAgentRevisionApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsDestroyUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsDestroy = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsRevisionsDestroyUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getAgentApplicationsRevisionsAgentMdUpdateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/agent_md/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsAgentMdUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ writeAgentMdRequestApi: WriteAgentMdRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsAgentMdUpdateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(writeAgentMdRequestApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsArchiveCreateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/archive/`
+}
+
+/**
+ * Mark a revision archived. If it was the live one, clear the
+ * application's live_revision pointer (the app effectively has no
+ * deployable version until another revision is promoted).
+ */
+export const agentApplicationsRevisionsArchiveCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsArchiveCreateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAgentApplicationsRevisionsBundleRetrieveUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/bundle/`
+}
+
+/**
+ * Read the full typed bundle: `{ agent_md, skills, tools, spec }`.
+ */
+export const agentApplicationsRevisionsBundleRetrieve = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsBundleRetrieveUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsRevisionsBundleUpdateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/bundle/`
+}
+
+/**
+ * Full-replace the typed bundle. Anything not in the payload is
+ * deleted. Tool sources are AST-checked + esbuild-compiled by the
+ * janitor before any S3 writes.
+ */
+export const agentApplicationsRevisionsBundleUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ writeTypedBundleRequestApi: WriteTypedBundleRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsBundleUpdateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(writeTypedBundleRequestApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsCloneFromCreateUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/clone_from/`
+}
+
+/**
+ * Copy every file from `source_revision_id` into this revision.
+ */
+export const agentApplicationsRevisionsCloneFromCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ cloneFromRequestApi: CloneFromRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsCloneFromCreateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(cloneFromRequestApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsCronFireCreateUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/cron/fire/`
+}
+
+/**
+ * Fire one cron job out-of-band — the same execution path the
+ * scheduler walks, but on demand. Authoring UX: the user iterates on
+ * a cron prompt by clicking 'Fire now' rather than waiting for the
+ * next scheduled firing. Without this, 'did my prompt do the right
+ * thing?' is unanswerable until the cron actually fires.
+ *
+ * Idempotent via `request_id`: repeat clicks with the same id resolve
+ * to the same session id rather than firing N times. See
+ * `docs/agent-platform/plans/cron-trigger-scheduler.md` §9.
+ */
+export const agentApplicationsRevisionsCronFireCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ agentRevisionCronFireRequestApi: AgentRevisionCronFireRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionCronFireResponseApi> => {
+ return apiMutator<AgentRevisionCronFireResponseApi>(
+ getAgentApplicationsRevisionsCronFireCreateUrl(projectId, applicationId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentRevisionCronFireRequestApi),
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsFreezeCreateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/freeze/`
+}
+
+/**
+ * Freeze the bundle: draft → ready, stamps sha256 on the row.
+ *
+ * Django is a thin proxy here: resolve template refs into the
+ * bundle, ask the janitor to seal it (the janitor returns the sha
+ * + the spec it derived from the typed resources), then stamp the
+ * row. No `transaction.atomic()` — the janitor's freeze is idempotent
+ * (on retry it re-reads the existing `.frozen` marker + re-derives
+ * spec), so a partial failure here is recoverable by re-calling
+ * freeze, not by transactional rollback. Holding an atomic block
+ * across the janitor HTTP call previously deadlocked the
+ * agent_revision row against the janitor's spec write — that's
+ * moved off the janitor side as part of the same fix.
+ */
+export const agentApplicationsRevisionsFreezeCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsFreezeCreateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAgentApplicationsRevisionsManifestRetrieveUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/manifest/`
+}
+
+/**
+ * List every file in this revision's bundle (path, size, sha256).
+ */
+export const agentApplicationsRevisionsManifestRetrieve = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(
+ getAgentApplicationsRevisionsManifestRetrieveUrl(projectId, applicationId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsPromoteCreateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/promote/`
+}
+
+/**
+ * ready → live. Sets the parent application's live_revision.
+ */
+export const agentApplicationsRevisionsPromoteCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsPromoteCreateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAgentApplicationsRevisionsSkillsUpdateUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ skillId: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/skills/${skillId}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsSkillsUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ skillId: string,
+ writeSkillRequestApi: WriteSkillRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(
+ getAgentApplicationsRevisionsSkillsUpdateUrl(projectId, applicationId, id, skillId),
+ {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(writeSkillRequestApi),
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsSkillsDestroyUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ skillId: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/skills/${skillId}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsSkillsDestroy = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ skillId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsRevisionsSkillsDestroyUrl(projectId, applicationId, id, skillId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getAgentApplicationsRevisionsSlackManifestUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/slack_manifest/`
+}
+
+/**
+ * Build a Slack app manifest for this revision's slack trigger.
+ *
+ * Deterministic: the OAuth scopes and bot event subscriptions are derived
+ * from the slack trigger config (`mention_only` / `auto_resume_threads` /
+ * `ack_reaction`) and the agent's Slack tools, so the manifest already
+ * subscribes to exactly the events the config needs. 400 if the revision
+ * has no slack trigger.
+ */
+export const agentApplicationsRevisionsSlackManifest = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionSlackManifestResponseApi> => {
+ return apiMutator<AgentRevisionSlackManifestResponseApi>(
+ getAgentApplicationsRevisionsSlackManifestUrl(projectId, applicationId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsSpecUpdateUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/spec/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsSpecUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ writeSpecRequestApi: WriteSpecRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsSpecUpdateUrl(projectId, applicationId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(writeSpecRequestApi),
+ })
+}
+
+export const getAgentApplicationsRevisionsSystemPromptUrl = (projectId: string, applicationId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/system_prompt/`
+}
+
+/**
+ * Return the fully-assembled system prompt for this revision.
+ *
+ * Authoring tools call this to preview what the model will actually
+ * see at session start — the platform framework preamble plus the
+ * bundle's `agent.md` plus the skills index. Useful for debugging
+ * author-vs-framework precedence conflicts and verifying
+ * `spec.framework_prompt.omit` overrides took effect.
+ */
+export const agentApplicationsRevisionsSystemPrompt = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionSystemPromptResponseApi> => {
+ return apiMutator<AgentRevisionSystemPromptResponseApi>(
+ getAgentApplicationsRevisionsSystemPromptUrl(projectId, applicationId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsToolsUpdateUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ toolId: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/tools/${toolId}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsToolsUpdate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ toolId: string,
+ writeToolRequestApi: WriteToolRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(
+ getAgentApplicationsRevisionsToolsUpdateUrl(projectId, applicationId, id, toolId),
+ {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(writeToolRequestApi),
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsToolsDestroyUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ toolId: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/tools/${toolId}/`
+}
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsToolsDestroy = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ toolId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsRevisionsToolsDestroyUrl(projectId, applicationId, id, toolId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getAgentApplicationsRevisionsValidateCreateUrl = (
+ projectId: string,
+ applicationId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/validate/`
+}
+
+/**
+ * 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
+ * `{ ok, errors: [...] }`. Works on any revision state.
+ */
+export const agentApplicationsRevisionsValidateCreate = async (
+ projectId: string,
+ applicationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentRevisionValidateResponseApi> => {
+ return apiMutator<AgentRevisionValidateResponseApi>(
+ getAgentApplicationsRevisionsValidateCreateUrl(projectId, applicationId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getAgentApplicationsRevisionsNewDraftCreateUrl = (projectId: string, applicationId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/new_draft/`
+}
+
+/**
+ * Create a fresh draft revision under `application_id` and seed it
+ * from `source_revision_id`. Saves the MCP one round-trip vs the
+ * explicit create + clone_from sequence.
+ */
+export const agentApplicationsRevisionsNewDraftCreate = async (
+ projectId: string,
+ applicationId: string,
+ newDraftRevisionRequestApi: NewDraftRevisionRequestApi,
+ options?: RequestInit
+): Promise<AgentRevisionApi> => {
+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsNewDraftCreateUrl(projectId, applicationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(newDraftRevisionRequestApi),
+ })
+}
+
+export const getAgentApplicationsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsUpdate = async (
+ projectId: string,
+ id: string,
+ agentApplicationApi: NonReadonly<AgentApplicationApi>,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentApplicationApi),
+ })
+}
+
+export const getAgentApplicationsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedAgentApplicationApi?: NonReadonly<PatchedAgentApplicationApi>,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedAgentApplicationApi),
+ })
+}
+
+export const getAgentApplicationsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/`
+}
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getAgentApplicationsApprovalsListUrl = (
+ projectId: string,
+ id: string,
+ params?: AgentApplicationsApprovalsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/approvals/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/approvals/`
+}
+
+/**
+ * List approval-gated tool requests for this application. Team-admin
+ * only (per plan §6.1). Default returns all states — pass `?state=queued`
+ * for the inbox view.
+ */
+export const agentApplicationsApprovalsList = async (
+ projectId: string,
+ id: string,
+ params?: AgentApplicationsApprovalsListParams,
+ options?: RequestInit
+): Promise<AgentApplicationApprovalsListResponseApi> => {
+ return apiMutator<AgentApplicationApprovalsListResponseApi>(
+ getAgentApplicationsApprovalsListUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsApprovalsRetrieveUrl = (projectId: string, id: string, approvalId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/approvals/${approvalId}/`
+}
+
+/**
+ * Single approval request — full proposed args, assistant snapshot,
+ * decision metadata, dispatch outcome. Team-admin only (plan §6.1).
+ */
+export const agentApplicationsApprovalsRetrieve = async (
+ projectId: string,
+ id: string,
+ approvalId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentApplicationsApprovalsRetrieveUrl(projectId, id, approvalId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsApprovalsDecideUrl = (projectId: string, id: string, approvalId: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/approvals/${approvalId}/decide/`
+}
+
+/**
+ * Approve or reject a queued tool-approval request. Team-admin only
+ * (plan §6.1). The runtime side runs the tool platform-side on approve
+ * and wakes the session with a synthetic tool_result either way.
+ */
+export const agentApplicationsApprovalsDecide = async (
+ projectId: string,
+ id: string,
+ approvalId: string,
+ decideApprovalRequestApi: DecideApprovalRequestApi,
+ options?: RequestInit
+): Promise<AgentApprovalsDecideResponseApi> => {
+ return apiMutator<AgentApprovalsDecideResponseApi>(
+ getAgentApplicationsApprovalsDecideUrl(projectId, id, approvalId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(decideApprovalRequestApi),
+ }
+ )
+}
+
+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,
+ rest: string,
+ params: AgentApplicationsPreviewProxyGetParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/preview-proxy/${rest}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/preview-proxy/${rest}/`
+}
+
+/**
+ * GET passthrough for the preview-proxy — used for `/listen` SSE.
+ */
+export const agentApplicationsPreviewProxyGet = async (
+ projectId: string,
+ id: string,
+ rest: string,
+ params: AgentApplicationsPreviewProxyGetParams,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsPreviewProxyGetUrl(projectId, id, rest, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentApplicationsPreviewProxyUrl = (
+ projectId: string,
+ id: string,
+ rest: string,
+ params: AgentApplicationsPreviewProxyParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/preview-proxy/${rest}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/preview-proxy/${rest}/`
+}
+
+/**
+ * Authoring-side proxy for invoking a *draft* (or any non-live) revision.
+ *
+ * Closes the anonymous-draft-invoke gap: the public ingress URL refuses
+ * non-live invokes that don't carry the `x-agent-preview-secret` header;
+ * this proxy attaches it after authenticating the Django caller. See
+ * docs/agent-platform/plans/draft-preview-auth.md.
+ *
+ * URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`
+ * Auth: standard PAT / session — `agents:read` scope.
+ */
+export const agentApplicationsPreviewProxy = async (
+ projectId: string,
+ id: string,
+ rest: string,
+ params: AgentApplicationsPreviewProxyParams,
+ options?: RequestInit
+): Promise<AgentApplicationApi> => {
+ return apiMutator<AgentApplicationApi>(getAgentApplicationsPreviewProxyUrl(projectId, id, rest, params), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getAgentApplicationsPreviewTokenUrl = (
+ projectId: string,
+ id: string,
+ params: AgentApplicationsPreviewTokenParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/preview-token/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/preview-token/`
+}
+
+/**
+ * Mint a short-lived JWT for talking to a non-live revision
+ * directly via the public ingress URL. The caller attaches it as
+ * the `x-agent-preview-token` header (or `?preview_token=` query
+ * param for `EventSource`). See `_mint_preview_jwt` for the
+ * payload + claim binding.
+ *
+ * The response also includes `endpoints`, `auth`, and
+ * `preview_proxy` blocks so the caller can wire a preview
+ * invocation without grepping the agent-ingress source for which
+ * path each trigger exposes or which header name carries the
+ * token. This is the "self-describing" half of preview-mode —
+ * every piece of info you need to hit ingress is in one response.
+ */
+export const agentApplicationsPreviewToken = async (
+ projectId: string,
+ id: string,
+ params: AgentApplicationsPreviewTokenParams,
+ options?: RequestInit
+): Promise<AgentApplicationPreviewTokenResponseApi> => {
+ return apiMutator<AgentApplicationPreviewTokenResponseApi>(
+ getAgentApplicationsPreviewTokenUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsSessionsListUrl = (
+ projectId: string,
+ id: string,
+ params?: AgentApplicationsSessionsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/sessions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/sessions/`
+}
+
+/**
+ * List sessions for this application, newest first. Strips the
+ * conversation transcript from each summary, but includes a `preview`
+ * (last assistant text, ~120 chars) and `usage_total` (token + cost
+ * aggregate). Use `agent-applications-sessions-retrieve` for the full
+ * transcript of a single session.
+ */
+export const agentApplicationsSessionsList = async (
+ projectId: string,
+ id: string,
+ params?: AgentApplicationsSessionsListParams,
+ options?: RequestInit
+): Promise<AgentApplicationSessionsListResponseApi> => {
+ return apiMutator<AgentApplicationSessionsListResponseApi>(
+ getAgentApplicationsSessionsListUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsSessionsRetrieveUrl = (
+ projectId: string,
+ id: string,
+ sessionId: string,
+ params?: AgentApplicationsSessionsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/sessions/${sessionId}/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/sessions/${sessionId}/`
+}
+
+/**
+ * Fetch one session's state — full conversation by default, or just
+ * the trailing N messages with `?last_n=`. Always returns a
+ * `usage_total` block aggregated over the entire session, regardless of
+ * trim. The runner-side queue DB is the source of truth.
+ */
+export const agentApplicationsSessionsRetrieve = async (
+ projectId: string,
+ id: string,
+ sessionId: string,
+ params?: AgentApplicationsSessionsRetrieveParams,
+ options?: RequestInit
+): Promise<AgentApplicationSessionsRetrieveResponseApi> => {
+ return apiMutator<AgentApplicationSessionsRetrieveResponseApi>(
+ getAgentApplicationsSessionsRetrieveUrl(projectId, id, sessionId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getAgentApplicationsSessionLogsUrl = (
+ projectId: string,
+ id: string,
+ sessionId: string,
+ params?: AgentApplicationsSessionLogsParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/sessions/${sessionId}/logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/sessions/${sessionId}/logs/`
+}
+
+/**
+ * Read the runner's structured event log for one session from
+ * ClickHouse. Filters (limit / after / before / level / search)
+ * match the shared `LogEntryMixin` helper used by hog_function +
+ * hog_flow.
+ */
+export const agentApplicationsSessionLogs = async (
+ projectId: string,
+ id: string,
+ sessionId: string,
+ params?: AgentApplicationsSessionLogsParams,
+ options?: RequestInit
+): Promise<AgentApplicationSessionLogsResponseApi> => {
+ return apiMutator<AgentApplicationSessionLogsResponseApi>(
+ getAgentApplicationsSessionLogsUrl(projectId, id, sessionId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+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()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/stats/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/stats/`
+}
+
+/**
+ * Roll-up stats for the agent — drives the agent-detail overview tiles.
+ */
+export const agentApplicationsStats = async (
+ projectId: string,
+ id: string,
+ params?: AgentApplicationsStatsParams,
+ options?: RequestInit
+): Promise<AgentAggregateStatsApi> => {
+ return apiMutator<AgentAggregateStatsApi>(getAgentApplicationsStatsUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentFleetApprovalsListUrl = (projectId: string, params?: AgentFleetApprovalsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_fleet/approvals/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_fleet/approvals/`
+}
+
+/**
+ * Approval-gated tool requests across every agent in this team. Team-admin only.
+ */
+export const agentFleetApprovalsList = async (
+ projectId: string,
+ params?: AgentFleetApprovalsListParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getAgentFleetApprovalsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentFleetLiveSessionsUrl = (projectId: string, params?: AgentFleetLiveSessionsParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_fleet/live_sessions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_fleet/live_sessions/`
+}
+
+/**
+ * Live (non-terminal) sessions across every agent owned by this team, newest activity first.
+ */
+export const agentFleetLiveSessions = async (
+ projectId: string,
+ params?: AgentFleetLiveSessionsParams,
+ options?: RequestInit
+): Promise<AgentFleetLiveSessionsResponseApi> => {
+ return apiMutator<AgentFleetLiveSessionsResponseApi>(getAgentFleetLiveSessionsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentFleetStatsUrl = (projectId: string, params?: AgentFleetStatsParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_fleet/stats/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_fleet/stats/`
+}
+
+/**
+ * Roll-up stats across every agent owned by this team.
+ */
+export const agentFleetStats = async (
+ projectId: string,
+ params?: AgentFleetStatsParams,
+ options?: RequestInit
+): Promise<AgentAggregateStatsApi> => {
+ return apiMutator<AgentAggregateStatsApi>(getAgentFleetStatsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAgentNativeToolsListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/agent_native_tools/`
+}
+
+/**
+ * Read-only catalog of every @posthog/* native tool the runner knows.
+ */
+export const agentNativeToolsList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<AgentNativeToolsListResponseApi[]> => {
+ return apiMutator<AgentNativeToolsListResponseApi[]>(getAgentNativeToolsListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..4e3b943d3c8f
--- /dev/null
+++ b/products/agent_platform/frontend/generated/api.zod.ts
@@ -0,0 +1,1962 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsCreateBodyNameMax = 255
+
+export const agentApplicationsCreateBodySlugMax = 63
+
+export const agentApplicationsCreateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+
+export const AgentApplicationsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(agentApplicationsCreateBodyNameMax),
+ slug: zod
+ .string()
+ .max(agentApplicationsCreateBodySlugMax)
+ .regex(agentApplicationsCreateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).'
+ ),
+ description: zod.string().optional(),
+ archived: zod.boolean().optional(),
+})
+
+/**
+ * Create a memory file. Fails if the path already exists — use the update endpoint to overwrite.
+ */
+export const agentMemoryCreateFileBodyDescriptionMax = 280
+
+export const AgentMemoryCreateFileBody = /* @__PURE__ */ zod
+ .object({
+ path: zod.string().describe('Where to store the file. Lowercase a-z 0-9 _ - \/ only, must end in .md.'),
+ description: zod
+ .string()
+ .max(agentMemoryCreateFileBodyDescriptionMax)
+ .describe('One-line summary, max 280 chars. Surfaces in list\/search results.'),
+ content: zod.string().describe('Full markdown body.'),
+ tags: zod
+ .array(zod.string())
+ .optional()
+ .describe('Optional flat tags for search ranking. Lowercase a-z 0-9 _ - only.'),
+ })
+ .describe('Body shape for AgentMemoryViewSet.write_file (create).')
+
+/**
+ * Update a memory file. Any field omitted is preserved from the existing file.
+ */
+export const agentMemoryUpdateFileBodyDescriptionMax = 280
+
+export const AgentMemoryUpdateFileBody = /* @__PURE__ */ zod
+ .object({
+ description: zod.string().max(agentMemoryUpdateFileBodyDescriptionMax).optional(),
+ content: zod.string().optional(),
+ tags: zod.array(zod.string()).optional(),
+ })
+ .describe('Body shape for AgentMemoryViewSet.update_file. Omitted fields preserve the existing value.')
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsCreateBodyBundleUriDefault = ``
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigTimezoneDefault = `UTC`
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigPromptMax = 4096
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigCatchUpDefault = `most_recent`
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault = 3600
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax = 604800
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersDefault = []
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault = 5000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsMax = 600000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourInteractiveDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
+
+export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecSecretsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault = 50
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsDefault = 200
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsDefault = 900
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensMax = 200000
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsDefault = {
+ max_turns: 50,
+ max_tool_calls: 200,
+ max_wall_seconds: 900,
+}
+export const agentApplicationsRevisionsCreateBodySpecEntrypointDefault = `agent.md`
+
+export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
+ parent_revision: zod.uuid().nullish(),
+ bundle_uri: zod.string().default(agentApplicationsRevisionsCreateBodyBundleUriDefault),
+ spec: zod
+ .object({
+ model: zod.string().min(1),
+ triggers: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('slack'),
+ config: zod.object({
+ channel_id: zod.string().optional(),
+ mention_only: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault
+ ),
+ auto_resume_threads: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault
+ ),
+ allow_workspace_participants: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault
+ ),
+ ack_reaction: zod.string().optional(),
+ trusted_workspaces: zod.union([zod.array(zod.string()).min(1), zod.literal('*')]),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('webhook'),
+ config: zod.object({
+ path: zod.string(),
+ }),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('cron'),
+ config: zod.object({
+ name: zod.string().min(1),
+ schedule: zod.string().min(1),
+ timezone: zod
+ .string()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigTimezoneDefault
+ ),
+ prompt: zod
+ .string()
+ .min(1)
+ .max(agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigPromptMax),
+ external_key: zod.string().optional(),
+ catch_up: zod
+ .enum(['all', 'most_recent', 'skip'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigCatchUpDefault
+ ),
+ max_catch_up_age_seconds: zod
+ .number()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax
+ )
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault
+ ),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('chat'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('mcp'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersDefault),
+ tools: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('native'),
+ id: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom'),
+ id: zod.string(),
+ path: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom_template'),
+ from_template: zod.string(),
+ alias: zod.string(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin)
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('client'),
+ id: zod.string().min(1),
+ description: zod.string().min(1),
+ args_schema: zod
+ .looseObject({})
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault),
+ required: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault),
+ timeout_ms: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault),
+ interactive: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourInteractiveDefault),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecToolsDefault),
+ mcps: zod
+ .array(
+ zod.object({
+ id: zod.string().min(1),
+ url: zod.url(),
+ auth: zod
+ .object({
+ integration: zod.string().optional(),
+ })
+ .optional(),
+ secrets: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault),
+ headers: zod.record(zod.string(), zod.string()).optional(),
+ tools: zod
+ .array(
+ zod.union([
+ zod.string().min(1),
+ zod.object({
+ name: zod.string().min(1),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ ])
+ )
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecMcpsDefault),
+ skills: zod
+ .array(
+ zod.object({
+ id: zod.string(),
+ path: zod.string(),
+ description: zod.string().optional(),
+ from_template: zod.string().optional(),
+ alias: zod.string().optional(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin)
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
+ integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
+ secrets: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecSecretsDefault),
+ limits: zod
+ .object({
+ max_turns: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault),
+ max_tool_calls: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsDefault),
+ max_wall_seconds: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsDefault),
+ max_output_tokens: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensMax)
+ .optional(),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsDefault),
+ entrypoint: zod.string().default(agentApplicationsRevisionsCreateBodySpecEntrypointDefault),
+ reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),
+ })
+ .optional(),
+})
+
+/**
+ * Spec edits are only allowed while state='draft'. Once promoted to
+ * ready/live the spec is frozen — change requires a new revision.
+ */
+export const agentApplicationsRevisionsUpdateBodyBundleUriDefault = ``
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigTimezoneDefault = `UTC`
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigPromptMax = 4096
+
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigCatchUpDefault = `most_recent`
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault = 3600
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax = 604800
+
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFourConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFourConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsUpdateBodySpecTriggersDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemThreeVersionMin = 0
+
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourRequiredDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourTimeoutMsMax = 600000
+
+export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourInteractiveDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecToolsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemSecretsDefault = []
+
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsUpdateBodySpecMcpsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin = 0
+
+export const agentApplicationsRevisionsUpdateBodySpecSkillsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecSecretsDefault = []
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsDefault = 50
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsExclusiveMin = 0
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsMax = 2147483647
+
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsDefault = 200
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsExclusiveMin = 0
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsMax = 2147483647
+
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsDefault = 900
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsExclusiveMin = 0
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsMax = 2147483647
+
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxOutputTokensExclusiveMin = 0
+export const agentApplicationsRevisionsUpdateBodySpecLimitsMaxOutputTokensMax = 200000
+
+export const agentApplicationsRevisionsUpdateBodySpecLimitsDefault = {
+ max_turns: 50,
+ max_tool_calls: 200,
+ max_wall_seconds: 900,
+}
+export const agentApplicationsRevisionsUpdateBodySpecEntrypointDefault = `agent.md`
+
+export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
+ parent_revision: zod.uuid().nullish(),
+ bundle_uri: zod.string().default(agentApplicationsRevisionsUpdateBodyBundleUriDefault),
+ spec: zod
+ .object({
+ model: zod.string().min(1),
+ triggers: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('slack'),
+ config: zod.object({
+ channel_id: zod.string().optional(),
+ mention_only: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault
+ ),
+ auto_resume_threads: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault
+ ),
+ allow_workspace_participants: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault
+ ),
+ ack_reaction: zod.string().optional(),
+ trusted_workspaces: zod.union([zod.array(zod.string()).min(1), zod.literal('*')]),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('webhook'),
+ config: zod.object({
+ path: zod.string(),
+ }),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('cron'),
+ config: zod.object({
+ name: zod.string().min(1),
+ schedule: zod.string().min(1),
+ timezone: zod
+ .string()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigTimezoneDefault
+ ),
+ prompt: zod
+ .string()
+ .min(1)
+ .max(agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigPromptMax),
+ external_key: zod.string().optional(),
+ catch_up: zod
+ .enum(['all', 'most_recent', 'skip'])
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigCatchUpDefault
+ ),
+ max_catch_up_age_seconds: zod
+ .number()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax
+ )
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault
+ ),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('chat'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemFourConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsUpdateBodySpecTriggersItemFourConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('mcp'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsUpdateBodySpecTriggersDefault),
+ tools: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('native'),
+ id: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemOneRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom'),
+ id: zod.string(),
+ path: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemTwoRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom_template'),
+ from_template: zod.string(),
+ alias: zod.string(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsUpdateBodySpecToolsItemThreeVersionMin)
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('client'),
+ id: zod.string().min(1),
+ description: zod.string().min(1),
+ args_schema: zod
+ .looseObject({})
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemFourArgsSchemaDefault),
+ required: zod
+ .boolean()
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemFourRequiredDefault),
+ timeout_ms: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsRevisionsUpdateBodySpecToolsItemFourTimeoutMsMax)
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemFourTimeoutMsDefault),
+ interactive: zod
+ .boolean()
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsItemFourInteractiveDefault),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsUpdateBodySpecToolsDefault),
+ mcps: zod
+ .array(
+ zod.object({
+ id: zod.string().min(1),
+ url: zod.url(),
+ auth: zod
+ .object({
+ integration: zod.string().optional(),
+ })
+ .optional(),
+ secrets: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsUpdateBodySpecMcpsItemSecretsDefault),
+ headers: zod.record(zod.string(), zod.string()).optional(),
+ tools: zod
+ .array(
+ zod.union([
+ zod.string().min(1),
+ zod.object({
+ name: zod.string().min(1),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ ])
+ )
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsUpdateBodySpecMcpsDefault),
+ skills: zod
+ .array(
+ zod.object({
+ id: zod.string(),
+ path: zod.string(),
+ description: zod.string().optional(),
+ from_template: zod.string().optional(),
+ alias: zod.string().optional(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin)
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsUpdateBodySpecSkillsDefault),
+ integrations: zod.array(zod.string()).default(agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault),
+ secrets: zod.array(zod.string()).default(agentApplicationsRevisionsUpdateBodySpecSecretsDefault),
+ limits: zod
+ .object({
+ max_turns: zod
+ .number()
+ .gt(agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsExclusiveMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsMax)
+ .default(agentApplicationsRevisionsUpdateBodySpecLimitsMaxTurnsDefault),
+ max_tool_calls: zod
+ .number()
+ .gt(agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsExclusiveMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsMax)
+ .default(agentApplicationsRevisionsUpdateBodySpecLimitsMaxToolCallsDefault),
+ max_wall_seconds: zod
+ .number()
+ .gt(agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsExclusiveMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsMax)
+ .default(agentApplicationsRevisionsUpdateBodySpecLimitsMaxWallSecondsDefault),
+ max_output_tokens: zod
+ .number()
+ .gt(agentApplicationsRevisionsUpdateBodySpecLimitsMaxOutputTokensExclusiveMin)
+ .max(agentApplicationsRevisionsUpdateBodySpecLimitsMaxOutputTokensMax)
+ .optional(),
+ })
+ .default(agentApplicationsRevisionsUpdateBodySpecLimitsDefault),
+ entrypoint: zod.string().default(agentApplicationsRevisionsUpdateBodySpecEntrypointDefault),
+ reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),
+ })
+ .optional(),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsPartialUpdateBodyBundleUriDefault = ``
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigTimezoneDefault = `UTC`
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigPromptMax = 4096
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigCatchUpDefault = `most_recent`
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault = 3600
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax = 604800
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsMax = 600000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourInteractiveDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault = 50
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsDefault = 200
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsDefault = 900
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensMax = 200000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault = {
+ max_turns: 50,
+ max_tool_calls: 200,
+ max_wall_seconds: 900,
+}
+export const agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault = `agent.md`
+
+export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ parent_revision: zod.uuid().nullish(),
+ bundle_uri: zod.string().default(agentApplicationsRevisionsPartialUpdateBodyBundleUriDefault),
+ spec: zod
+ .object({
+ model: zod.string().min(1),
+ triggers: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('slack'),
+ config: zod.object({
+ channel_id: zod.string().optional(),
+ mention_only: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault
+ ),
+ auto_resume_threads: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault
+ ),
+ allow_workspace_participants: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault
+ ),
+ ack_reaction: zod.string().optional(),
+ trusted_workspaces: zod.union([zod.array(zod.string()).min(1), zod.literal('*')]),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('webhook'),
+ config: zod.object({
+ path: zod.string(),
+ }),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('cron'),
+ config: zod.object({
+ name: zod.string().min(1),
+ schedule: zod.string().min(1),
+ timezone: zod
+ .string()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigTimezoneDefault
+ ),
+ prompt: zod
+ .string()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigPromptMax
+ ),
+ external_key: zod.string().optional(),
+ catch_up: zod
+ .enum(['all', 'most_recent', 'skip'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigCatchUpDefault
+ ),
+ max_catch_up_age_seconds: zod
+ .number()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault
+ ),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('chat'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('mcp'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault),
+ tools: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('native'),
+ id: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom'),
+ id: zod.string(),
+ path: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom_template'),
+ from_template: zod.string(),
+ alias: zod.string(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin)
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('client'),
+ id: zod.string().min(1),
+ description: zod.string().min(1),
+ args_schema: zod
+ .looseObject({})
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault),
+ required: zod
+ .boolean()
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault),
+ timeout_ms: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault),
+ interactive: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourInteractiveDefault
+ ),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault),
+ mcps: zod
+ .array(
+ zod.object({
+ id: zod.string().min(1),
+ url: zod.url(),
+ auth: zod
+ .object({
+ integration: zod.string().optional(),
+ })
+ .optional(),
+ secrets: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault),
+ headers: zod.record(zod.string(), zod.string()).optional(),
+ tools: zod
+ .array(
+ zod.union([
+ zod.string().min(1),
+ zod.object({
+ name: zod.string().min(1),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ ])
+ )
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault),
+ skills: zod
+ .array(
+ zod.object({
+ id: zod.string(),
+ path: zod.string(),
+ description: zod.string().optional(),
+ from_template: zod.string().optional(),
+ alias: zod.string().optional(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin)
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),
+ integrations: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
+ secrets: zod.array(zod.string()).default(agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault),
+ limits: zod
+ .object({
+ max_turns: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault),
+ max_tool_calls: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsDefault),
+ max_wall_seconds: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsDefault),
+ max_output_tokens: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensMax)
+ .optional(),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault),
+ entrypoint: zod.string().default(agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault),
+ reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),
+ })
+ .optional(),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsAgentMdUpdateBody = /* @__PURE__ */ zod
+ .object({
+ content: zod.string(),
+ })
+ .describe('Body shape for PUT \/revisions\/<id>\/agent_md\/.')
+
+/**
+ * Full-replace the typed bundle. Anything not in the payload is
+ * deleted. Tool sources are AST-checked + esbuild-compiled by the
+ * janitor before any S3 writes.
+ */
+export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod
+ .object({
+ agent_md: zod.string(),
+ skills: zod
+ .array(
+ zod
+ .object({
+ description: zod
+ .string()
+ .describe(
+ 'One-line summary shown in the skill index; the model uses it to decide when to load the skill.'
+ ),
+ body: zod
+ .string()
+ .describe("The skill's full markdown body, stored at `skills\/<skill_id>\/SKILL.md`."),
+ })
+ .describe(
+ 'Body shape for PUT \/revisions\/<id>\/skills\/<skill_id>\/. The body is stored\nat the canonical `skills\/<skill_id>\/SKILL.md` path in the bundle.'
+ )
+ )
+ .optional(),
+ tools: zod
+ .array(
+ zod
+ .object({
+ description: zod.string(),
+ args_schema: zod.record(zod.string(), zod.unknown()),
+ source: zod.string(),
+ })
+ .describe('Body shape for PUT \/revisions\/<id>\/tools\/<tool_id>\/.')
+ )
+ .optional(),
+ spec: zod.record(zod.string(), zod.unknown()),
+ })
+ .describe(
+ 'Body shape for PUT \/revisions\/<id>\/bundle\/ — the full-replace typed\npayload. See docs\/agent-platform\/plans\/typed-bundle-authoring-api.md §3.'
+ )
+
+/**
+ * Copy every file from `source_revision_id` into this revision.
+ */
+export const AgentApplicationsRevisionsCloneFromCreateBody = /* @__PURE__ */ zod
+ .object({
+ source_revision_id: zod.uuid(),
+ })
+ .describe(
+ 'Body shape for POST \/revisions\/<id>\/clone_from\/ — copy every file\nfrom `source_revision_id` into this (draft) revision.'
+ )
+
+/**
+ * Fire one cron job out-of-band — the same execution path the
+ * scheduler walks, but on demand. Authoring UX: the user iterates on
+ * a cron prompt by clicking 'Fire now' rather than waiting for the
+ * next scheduled firing. Without this, 'did my prompt do the right
+ * thing?' is unanswerable until the cron actually fires.
+ *
+ * Idempotent via `request_id`: repeat clicks with the same id resolve
+ * to the same session id rather than firing N times. See
+ * `docs/agent-platform/plans/cron-trigger-scheduler.md` §9.
+ */
+export const AgentApplicationsRevisionsCronFireCreateBody = /* @__PURE__ */ zod.object({
+ cron_name: zod.string().describe('`name` of the cron trigger in `spec.triggers[]` to fire.'),
+ request_id: zod
+ .string()
+ .nullish()
+ .describe(
+ "Stable client-supplied id so repeated clicks of the same UI 'Fire now' button resolve to the same session id rather than firing twice. The janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit to fire unconditionally — every call generates a fresh UUID."
+ ),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsSkillsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ description: zod
+ .string()
+ .describe('One-line summary shown in the skill index; the model uses it to decide when to load the skill.'),
+ body: zod.string().describe("The skill's full markdown body, stored at `skills\/<skill_id>\/SKILL.md`."),
+ })
+ .describe(
+ 'Body shape for PUT \/revisions\/<id>\/skills\/<skill_id>\/. The body is stored\nat the canonical `skills\/<skill_id>\/SKILL.md` path in the bundle.'
+ )
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsSpecUpdateBody = /* @__PURE__ */ zod
+ .object({
+ spec: zod.record(zod.string(), zod.unknown()),
+ })
+ .describe(
+ "Body shape for PUT \/revisions\/<id>\/spec\/. The body's `spec` object\nis the author-facing slice (skills\/tools are server-derived at freeze)."
+ )
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsToolsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ description: zod.string(),
+ args_schema: zod.record(zod.string(), zod.unknown()),
+ source: zod.string(),
+ })
+ .describe('Body shape for PUT \/revisions\/<id>\/tools\/<tool_id>\/.')
+
+/**
+ * Create a fresh draft revision under `application_id` and seed it
+ * from `source_revision_id`. Saves the MCP one round-trip vs the
+ * explicit create + clone_from sequence.
+ */
+export const AgentApplicationsRevisionsNewDraftCreateBody = /* @__PURE__ */ zod
+ .object({
+ application_id: zod.uuid(),
+ source_revision_id: zod.uuid(),
+ })
+ .describe(
+ 'Body shape for POST \/revisions\/clone_from\/ — atomically create a new\ndraft revision under `application_id` and clone its initial bundle from\n`source_revision_id`. Convenience for the \"edit live\" flow so the MCP\ndoesn\'t have to do create-then-clone-from in two calls.'
+ )
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsUpdateBodyNameMax = 255
+
+export const agentApplicationsUpdateBodySlugMax = 63
+
+export const agentApplicationsUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+
+export const AgentApplicationsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(agentApplicationsUpdateBodyNameMax),
+ slug: zod
+ .string()
+ .max(agentApplicationsUpdateBodySlugMax)
+ .regex(agentApplicationsUpdateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).'
+ ),
+ description: zod.string().optional(),
+ archived: zod.boolean().optional(),
+})
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const agentApplicationsPartialUpdateBodyNameMax = 255
+
+export const agentApplicationsPartialUpdateBodySlugMax = 63
+
+export const agentApplicationsPartialUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+
+export const AgentApplicationsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(agentApplicationsPartialUpdateBodyNameMax).optional(),
+ slug: zod
+ .string()
+ .max(agentApplicationsPartialUpdateBodySlugMax)
+ .regex(agentApplicationsPartialUpdateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).'
+ ),
+ description: zod.string().optional(),
+ archived: zod.boolean().optional(),
+})
+
+/**
+ * Approve or reject a queued tool-approval request. Team-admin only
+ * (plan §6.1). The runtime side runs the tool platform-side on approve
+ * and wakes the session with a synthetic tool_result either way.
+ */
+export const AgentApplicationsApprovalsDecideBody = /* @__PURE__ */ zod
+ .object({
+ decision: zod
+ .enum(['approve', 'reject'])
+ .describe('\* `approve` - approve\n\* `reject` - reject')
+ .describe(
+ "The approver's decision. `approve` runs the tool platform-side with the (possibly edited) args; `reject` records a terminal rejection and wakes the session with a synthetic rejected tool_result.\n\n\* `approve` - approve\n\* `reject` - reject"
+ ),
+ edited_args: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ "Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422."
+ ),
+ reason: zod
+ .string()
+ .optional()
+ .describe(
+ "Free-form approver note. Surfaces in the session's synthetic tool_result so the model can communicate the reason back to the user."
+ ),
+ })
+ .describe(
+ 'Body shape for POST \/agent_applications\/<id>\/approvals\/<approval_id>\/decide\/.\n\nSee docs\/agent-platform\/plans\/approval-gated-tools.md.'
+ )
+
+/**
+ * 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.'
+ )
+
+/**
+ * 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/package.json b/products/agent_platform/package.json
new file mode 100644
index 000000000000..6654b4b257d9
--- /dev/null
+++ b/products/agent_platform/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-agent-platform",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend -v --tb=short",
+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend"
+ }
+}
diff --git a/products/agent_platform/product.yaml b/products/agent_platform/product.yaml
new file mode 100644
index 000000000000..6a0f1d13f1ae
--- /dev/null
+++ b/products/agent_platform/product.yaml
@@ -0,0 +1,3 @@
+name: Agent stack
+owners:
+ - team-agents
diff --git a/products/agent_platform/turbo.json b/products/agent_platform/turbo.json
new file mode 100644
index 000000000000..44865e1b7931
--- /dev/null
+++ b/products/agent_platform/turbo.json
@@ -0,0 +1,3 @@
+{
+ "extends": ["//"]
+}
diff --git a/products/db_routing.yaml b/products/db_routing.yaml
index baac59dbb2c3..0694aba6ec57 100644
--- a/products/db_routing.yaml
+++ b/products/db_routing.yaml
@@ -3,3 +3,5 @@ routes:
database: visual_review
- app_label: warehouse_sources_queue
database: warehouse_sources_queue
+ - app_label: agent_platform
+ database: agent_platform
diff --git a/pyproject.toml b/pyproject.toml
index fe8308965f0e..e4bc103224c7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -503,6 +503,13 @@ ignore_imports = [
"products.**.backend.presentation.** -> products.**.backend.facade.**",
"products.**.backend.presentation.** -> products.**.backend.presentation.**",
# TODO: existing violations — fix by routing through facade
+ "products.agent_platform.backend.presentation.serializers -> products.agent_platform.backend.logic.spec_schema",
+ "products.agent_platform.backend.presentation.serializers -> products.agent_platform.backend.models",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.db",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.internal_jwt",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.spec_schema",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.models",
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic",
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.models",
"products.mcp_analytics.backend.presentation.serializers -> products.mcp_analytics.backend.models",
diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yaml
new file mode 100644
index 000000000000..ad4c90ccf187
--- /dev/null
+++ b/services/mcp/definitions/agent_platform.yaml
@@ -0,0 +1,604 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Agent stack
+feature: agent_platform
+url_prefix: /agent_applications
+feature_flag: agent-platform-mcp
+ui_apps: {}
+tools:
+ agent-applications-approvals-decide:
+ operation: agent_applications_approvals_decide
+ enabled: false
+ agent-applications-approvals-list:
+ operation: agent_applications_approvals_list
+ enabled: false
+ agent-applications-approvals-retrieve:
+ operation: agent_applications_approvals_retrieve
+ enabled: false
+ agent-applications-create:
+ operation: agent_applications_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create an agent application
+ description: >
+ Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no
+ revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze +
+ promote.
+ agent-applications-destroy:
+ operation: agent_applications_destroy
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Archive an agent application
+ description: >
+ Soft-delete: `archived=true`, `archived_at` stamped. Existing revisions stay queryable for audit; further
+ 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
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Clear one secret
+ description: >
+ Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer
+ required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts —
+ in-flight sessions keep the value they resolved at start.
+ agent-applications-env-keys-get:
+ operation: agent_applications_env_keys_get
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Check whether one secret is set
+ description: >
+ Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the
+ user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write
+ landed.
+ agent-applications-env-keys-list:
+ operation: agent_applications_env_keys_list
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List the names of secrets currently set
+ description: >
+ Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already
+ populated so you don't ask the user to set something that's already set. Pair with
+ `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.
+ agent-applications-env-keys-set:
+ operation: agent_applications_env_keys_set
+ enabled: false
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Set or rotate one secret (raw value — disabled by default)
+ description: >
+ Body `{ value: "…" }`. Merges into the encrypted env without touching siblings. **Disabled for the standard
+ MCP surface** — agents should never see raw secret values in their tool-call history. The standard path is
+ to deep-link the user into the agent console's secret editor (see the `secrets-and-integrations` skill for
+ the URL contract and callback flow); this endpoint exists for CI / scripts that already hold the value
+ out-of-band.
+ agent-applications-list:
+ operation: agent_applications_list
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List agent applications
+ description: >
+ List every agent application in the project. Returns id, slug, name, description, live_revision, archived
+ state. Use the slug to drive subsequent calls — it's stable and human-readable.
+ agent-applications-partial-update:
+ operation: agent_applications_partial_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update an agent application
+ description: >
+ Edit `name` / `description`. The env block is managed separately (raw secret entry goes through the agent
+ console's secret editor, not MCP), and `live_revision` is set by promoting a revision.
+ agent-applications-preview-proxy:
+ operation: agent_applications_preview_proxy
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Invoke a draft revision via the Django preview-proxy
+ description: >
+ Authoring-side proxy for invoking a non-live revision. Closes the anonymous-draft-invoke gap — the public
+ ingress refuses draft invokes that don't carry a valid `x-agent-preview-token` (short-lived JWT bound to
+ (app, revision)), and this proxy mints + attaches the token after authenticating the Django caller. Path
+ `rest` is one of `run` (start a new session), `send` (append to an existing one), `cancel` (kill it),
+ `listen` (SSE tail). `revision_id` query param is required and must be a non-live revision of this
+ application. See docs/agent-platform/plans/draft-preview-auth.md.
+ agent-applications-preview-proxy-get:
+ operation: agent_applications_preview_proxy_get
+ enabled: false
+ agent-applications-preview-token:
+ operation: agent_applications_preview_token
+ enabled: false
+ agent-applications-retrieve:
+ operation: agent_applications_retrieve
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get an agent application
+ description: >
+ Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the
+ running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call
+ `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.
+ agent-applications-revisions-agent-md-update:
+ operation: agent_applications_revisions_agent_md_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Replace agent.md
+ description: >
+ Body `{ content: "…" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves
+ skills, tools, and spec untouched. Draft-only.
+ agent-applications-revisions-archive-create:
+ operation: agent_applications_revisions_archive_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Archive a revision
+ description: >
+ Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the
+ app has no deployable version until another revision is promoted). Idempotent.
+ agent-applications-revisions-bundle-retrieve:
+ operation: agent_applications_revisions_bundle_retrieve
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get the typed bundle
+ description: >
+ Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit
+ the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description`,
+ `body`, and optional `files[]`. Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is
+ the author-facing slice (skills/tools are server-derived at freeze).
+ agent-applications-revisions-bundle-update:
+ operation: agent_applications_revisions_bundle_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Full-replace the typed bundle
+ description: >
+ Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in
+ the payload is deleted. For incremental edits use the single-resource PUTs
+ (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled
+ synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.
+ agent-applications-revisions-clone-from-create:
+ operation: agent_applications_revisions_clone_from_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Clone bundle from another revision
+ description: >
+ Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after
+ `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions
+ must belong to the same team.
+ agent-applications-revisions-create:
+ operation: agent_applications_revisions_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create a draft revision
+ description: >
+ Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields
+ you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what
+ you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or
+ `agent-applications-revisions-new-draft-create` to seed it from an existing revision.
+ agent-applications-revisions-cron-fire-create:
+ operation: agent_applications_revisions_cron_fire_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Manually fire one cron job
+ description: >
+ Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron
+ agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real
+ firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional:
+ `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of
+ stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via
+ `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without
+ this, "did my prompt do the right thing?" is unanswerable until the cron actually fires.
+ agent-applications-revisions-destroy:
+ operation: agent_applications_revisions_destroy
+ enabled: false
+ agent-applications-revisions-freeze-create:
+ operation: agent_applications_revisions_freeze_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Freeze a draft revision
+ description: >
+ Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this
+ the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing
+ sha256.
+ agent-applications-revisions-list:
+ operation: agent_applications_revisions_list
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List revisions of an application
+ description: >
+ List every revision (draft, ready, live, archived) for one application, newest first. Use to find the
+ current live revision id or pick a known-good revision to clone for an edit.
+ agent-applications-revisions-manifest-retrieve:
+ operation: agent_applications_revisions_manifest_retrieve
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List files in a revision's bundle
+ description: >
+ Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's
+ in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last
+ looked.
+ agent-applications-revisions-new-draft-create:
+ operation: agent_applications_revisions_new_draft_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Branch a new draft from an existing revision
+ description: >
+ One-shot helper: creates a draft revision under `application_id` and clones every file from
+ `source_revision_id` into the new bundle in a single round-trip. Use this for the common "edit live"
+ workflow — branch from the current live revision, mutate files, freeze, promote.
+ agent-applications-revisions-partial-update:
+ operation: agent_applications_revisions_partial_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Update a revision's spec
+ description: >
+ Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the
+ revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner
+ side; an invalid spec will surface when the next session starts, not here.
+ agent-applications-revisions-promote-create:
+ operation: agent_applications_revisions_promote_create
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Promote a revision to live
+ description: >
+ Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live
+ revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first).
+ Idempotent: promoting an already-live revision is a no-op.
+ agent-applications-revisions-retrieve:
+ operation: agent_applications_revisions_retrieve
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a revision
+ description: >
+ Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision
+ id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` /
+ `agent-applications-revisions-bundle-retrieve`.
+ agent-applications-revisions-skills-destroy:
+ operation: agent_applications_revisions_skills_destroy
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete one skill
+ description: >
+ Removes the skill body + every companion file under `skills/<id>/files/`. Returns 404 if the skill doesn't
+ exist. Draft-only.
+ agent-applications-revisions-skills-update:
+ operation: agent_applications_revisions_skills_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Upsert one skill
+ description: >
+ Body `{ description, body, files? }`. Creates the skill if it doesn't exist, replaces it if it does.
+ `files[]` is the optional list of companion docs (path relative to `skills/<id>/files/`). Skill id comes
+ from the URL. Draft-only.
+ agent-applications-revisions-slack-manifest:
+ operation: agent_applications_revisions_slack_manifest
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Generate the Slack app manifest for a revision
+ description: >
+ Returns `{ revision_id, manifest, notes, events_url, interactivity_url }` for a revision that has a slack
+ trigger. `manifest` is a ready-to-paste Slack app manifest (JSON) for https://api.slack.com/apps?new_app=1 →
+ "From an app manifest" — its OAuth scopes and bot event subscriptions are derived from the agent's slack
+ trigger config (mention_only / auto_resume_threads / ack_reaction) and its Slack tools, so it subscribes to
+ exactly the events the config needs. Hand the user the manifest plus the create-from-manifest link; surface
+ `notes` (e.g. invite the bot to its channels). 400 if the revision has no slack trigger.
+ agent-applications-revisions-spec-update:
+ operation: agent_applications_revisions_spec_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Replace the author-facing spec
+ description: >
+ Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations,
+ secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're
+ derived at freeze from the typed resources. Draft-only.
+ agent-applications-revisions-system-prompt:
+ operation: agent_applications_revisions_system_prompt
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Preview the assembled system prompt for a revision
+ description: >
+ Returns the fully-assembled system prompt the runner would pass to the model at session start — framework
+ preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before
+ promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for
+ debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell
+ whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.
+ agent-applications-revisions-tools-destroy:
+ operation: agent_applications_revisions_tools_destroy
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete one custom tool
+ description: >
+ Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist.
+ Draft-only.
+ agent-applications-revisions-tools-update:
+ operation: agent_applications_revisions_tools_update
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Upsert one custom tool
+ description: >
+ Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an
+ AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the
+ 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do
+ NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.
+ agent-applications-revisions-update:
+ operation: agent_applications_revisions_update
+ enabled: false
+ agent-applications-revisions-validate-create:
+ operation: agent_applications_revisions_validate_create
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Validate a revision's bundle + spec
+ description: >
+ Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file,
+ unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in
+ the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this
+ on a draft before calling `agent-applications-revisions-freeze-create`.
+ agent-applications-session-logs:
+ operation: agent_applications_session_logs
+ enabled: false
+ agent-applications-sessions-list:
+ operation: agent_applications_sessions_list
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List sessions for an agent
+ description: >
+ Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued /
+ running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count,
+ timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated
+ over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve`
+ for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID),
+ `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) +
+ `offset`. Filters AND together.
+ agent-applications-sessions-retrieve:
+ operation: agent_applications_sessions_retrieve
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get one session
+ description: >
+ Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages),
+ pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated
+ over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for
+ long sessions where you only care about the tail; `conversation_trimmed: true` plus
+ `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.
+ 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.
+ agent-applications-stats:
+ operation: agent_applications_stats
+ enabled: false
+ agent-applications-update:
+ operation: agent_applications_update
+ enabled: false
+ agent-fleet-approvals-list:
+ operation: agent_fleet_approvals_list
+ enabled: false
+ agent-fleet-live-sessions:
+ operation: agent_fleet_live_sessions
+ enabled: false
+ agent-fleet-stats:
+ operation: agent_fleet_stats
+ enabled: false
+ agent-memory-create-file:
+ operation: agent_memory_create_file
+ enabled: false
+ agent-memory-delete-file:
+ operation: agent_memory_delete_file
+ enabled: false
+ agent-memory-get-file:
+ operation: agent_memory_get_file
+ enabled: false
+ agent-memory-list-files:
+ operation: agent_memory_list_files
+ enabled: false
+ agent-memory-list-tables:
+ operation: agent_memory_list_tables
+ enabled: false
+ agent-memory-read-table:
+ operation: agent_memory_read_table
+ enabled: false
+ agent-memory-search:
+ operation: agent_memory_search
+ enabled: false
+ agent-memory-tree:
+ operation: agent_memory_tree
+ enabled: false
+ agent-memory-update-file:
+ operation: agent_memory_update_file
+ enabled: false
+ agent-native-tools-list:
+ operation: agent_native_tools_list
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List native tools the runner knows
+ description: >
+ Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes
+ the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap`
+ / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a
+ revision's spec.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5df2b3c9968d..12dfab2bb9a1 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -246,6 +246,516 @@
"readOnlyHint": true
}
},
+ "agent-applications-create": {
+ "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Create an agent application",
+ "title": "Create an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-destroy": {
+ "description": "Soft-delete: `archived=true`, `archived_at` stamped. Existing revisions stay queryable for audit; further CRUD on this app is blocked until you create a new app with the same slug (the unique constraint is scoped to `archived=false`).",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Archive an agent application",
+ "title": "Archive an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-clear": {
+ "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Clear one secret",
+ "title": "Clear one secret",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-get": {
+ "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Check whether one secret is set",
+ "title": "Check whether one secret is set",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-list": {
+ "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List the names of secrets currently set",
+ "title": "List the names of secrets currently set",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-list": {
+ "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List agent applications",
+ "title": "List agent applications",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-partial-update": {
+ "description": "Edit `name` / `description`. The env block is managed separately (raw secret entry goes through the agent console's secret editor, not MCP), and `live_revision` is set by promoting a revision.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Update an agent application",
+ "title": "Update an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-preview-proxy": {
+ "description": "Authoring-side proxy for invoking a non-live revision. Closes the anonymous-draft-invoke gap — the public ingress refuses draft invokes that don't carry a valid `x-agent-preview-token` (short-lived JWT bound to (app, revision)), and this proxy mints + attaches the token after authenticating the Django caller. Path `rest` is one of `run` (start a new session), `send` (append to an existing one), `cancel` (kill it), `listen` (SSE tail). `revision_id` query param is required and must be a non-live revision of this application. See docs/agent-platform/plans/draft-preview-auth.md.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Invoke a draft revision via the Django preview-proxy",
+ "title": "Invoke a draft revision via the Django preview-proxy",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-retrieve": {
+ "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get an agent application",
+ "title": "Get an agent application",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-agent-md-update": {
+ "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Replace agent.md",
+ "title": "Replace agent.md",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-archive-create": {
+ "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Archive a revision",
+ "title": "Archive a revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-bundle-retrieve": {
+ "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description`, `body`, and optional `files[]`. Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze).",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get the typed bundle",
+ "title": "Get the typed bundle",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-bundle-update": {
+ "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Full-replace the typed bundle",
+ "title": "Full-replace the typed bundle",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-clone-from-create": {
+ "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Clone bundle from another revision",
+ "title": "Clone bundle from another revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-create": {
+ "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Create a draft revision",
+ "title": "Create a draft revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-cron-fire-create": {
+ "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Manually fire one cron job",
+ "title": "Manually fire one cron job",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-freeze-create": {
+ "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Freeze a draft revision",
+ "title": "Freeze a draft revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-list": {
+ "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List revisions of an application",
+ "title": "List revisions of an application",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-manifest-retrieve": {
+ "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List files in a revision's bundle",
+ "title": "List files in a revision's bundle",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-new-draft-create": {
+ "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Branch a new draft from an existing revision",
+ "title": "Branch a new draft from an existing revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-partial-update": {
+ "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Update a revision's spec",
+ "title": "Update a revision's spec",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-promote-create": {
+ "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Promote a revision to live",
+ "title": "Promote a revision to live",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-retrieve": {
+ "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get a revision",
+ "title": "Get a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-skills-destroy": {
+ "description": "Removes the skill body + every companion file under `skills/<id>/files/`. Returns 404 if the skill doesn't exist. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Delete one skill",
+ "title": "Delete one skill",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-skills-update": {
+ "description": "Body `{ description, body, files? }`. Creates the skill if it doesn't exist, replaces it if it does. `files[]` is the optional list of companion docs (path relative to `skills/<id>/files/`). Skill id comes from the URL. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Upsert one skill",
+ "title": "Upsert one skill",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-slack-manifest": {
+ "description": "Returns `{ revision_id, manifest, notes, events_url, interactivity_url }` for a revision that has a slack trigger. `manifest` is a ready-to-paste Slack app manifest (JSON) for https://api.slack.com/apps?new_app=1 → \"From an app manifest\" — its OAuth scopes and bot event subscriptions are derived from the agent's slack trigger config (mention_only / auto_resume_threads / ack_reaction) and its Slack tools, so it subscribes to exactly the events the config needs. Hand the user the manifest plus the create-from-manifest link; surface `notes` (e.g. invite the bot to its channels). 400 if the revision has no slack trigger.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Generate the Slack app manifest for a revision",
+ "title": "Generate the Slack app manifest for a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-spec-update": {
+ "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Replace the author-facing spec",
+ "title": "Replace the author-facing spec",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-system-prompt": {
+ "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Preview the assembled system prompt for a revision",
+ "title": "Preview the assembled system prompt for a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-tools-destroy": {
+ "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Delete one custom tool",
+ "title": "Delete one custom tool",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-tools-update": {
+ "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Upsert one custom tool",
+ "title": "Upsert one custom tool",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-validate-create": {
+ "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Validate a revision's bundle + spec",
+ "title": "Validate a revision's bundle + spec",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-sessions-list": {
+ "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List sessions for an agent",
+ "title": "List sessions for an agent",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-sessions-retrieve": {
+ "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `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.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get one session",
+ "title": "Get one session",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-native-tools-list": {
+ "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List native tools the runner knows",
+ "title": "List native tools the runner knows",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
"alert-create": {
"description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",
"category": "Alerts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 343c1907cea9..77e3e51cf011 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -246,6 +246,501 @@
"readOnlyHint": true
}
},
+ "agent-applications-create": {
+ "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Create an agent application",
+ "title": "Create an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-destroy": {
+ "description": "Soft-delete: `archived=true`, `archived_at` stamped. Existing revisions stay queryable for audit; further CRUD on this app is blocked until you create a new app with the same slug (the unique constraint is scoped to `archived=false`).",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Archive an agent application",
+ "title": "Archive an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-clear": {
+ "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Clear one secret",
+ "title": "Clear one secret",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-get": {
+ "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Check whether one secret is set",
+ "title": "Check whether one secret is set",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-env-keys-list": {
+ "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List the names of secrets currently set",
+ "title": "List the names of secrets currently set",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-list": {
+ "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List agent applications",
+ "title": "List agent applications",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-partial-update": {
+ "description": "Edit `name` / `description`. The env block is managed separately (raw secret entry goes through the agent console's secret editor, not MCP), and `live_revision` is set by promoting a revision.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Update an agent application",
+ "title": "Update an agent application",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-preview-proxy": {
+ "description": "Authoring-side proxy for invoking a non-live revision. Closes the anonymous-draft-invoke gap — the public ingress refuses draft invokes that don't carry a valid `x-agent-preview-token` (short-lived JWT bound to (app, revision)), and this proxy mints + attaches the token after authenticating the Django caller. Path `rest` is one of `run` (start a new session), `send` (append to an existing one), `cancel` (kill it), `listen` (SSE tail). `revision_id` query param is required and must be a non-live revision of this application. See docs/agent-platform/plans/draft-preview-auth.md.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Invoke a draft revision via the Django preview-proxy",
+ "title": "Invoke a draft revision via the Django preview-proxy",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-retrieve": {
+ "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get an agent application",
+ "title": "Get an agent application",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-agent-md-update": {
+ "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Replace agent.md",
+ "title": "Replace agent.md",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-archive-create": {
+ "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Archive a revision",
+ "title": "Archive a revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-bundle-retrieve": {
+ "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description`, `body`, and optional `files[]`. Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze).",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get the typed bundle",
+ "title": "Get the typed bundle",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-bundle-update": {
+ "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Full-replace the typed bundle",
+ "title": "Full-replace the typed bundle",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-clone-from-create": {
+ "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Clone bundle from another revision",
+ "title": "Clone bundle from another revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-create": {
+ "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Create a draft revision",
+ "title": "Create a draft revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-cron-fire-create": {
+ "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Manually fire one cron job",
+ "title": "Manually fire one cron job",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-freeze-create": {
+ "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Freeze a draft revision",
+ "title": "Freeze a draft revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-list": {
+ "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List revisions of an application",
+ "title": "List revisions of an application",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-manifest-retrieve": {
+ "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List files in a revision's bundle",
+ "title": "List files in a revision's bundle",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-new-draft-create": {
+ "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Branch a new draft from an existing revision",
+ "title": "Branch a new draft from an existing revision",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-partial-update": {
+ "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Update a revision's spec",
+ "title": "Update a revision's spec",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-promote-create": {
+ "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Promote a revision to live",
+ "title": "Promote a revision to live",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-retrieve": {
+ "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get a revision",
+ "title": "Get a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-skills-destroy": {
+ "description": "Removes the skill body + every companion file under `skills/<id>/files/`. Returns 404 if the skill doesn't exist. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Delete one skill",
+ "title": "Delete one skill",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-skills-update": {
+ "description": "Body `{ description, body, files? }`. Creates the skill if it doesn't exist, replaces it if it does. `files[]` is the optional list of companion docs (path relative to `skills/<id>/files/`). Skill id comes from the URL. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Upsert one skill",
+ "title": "Upsert one skill",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-slack-manifest": {
+ "description": "Returns `{ revision_id, manifest, notes, events_url, interactivity_url }` for a revision that has a slack trigger. `manifest` is a ready-to-paste Slack app manifest (JSON) for https://api.slack.com/apps?new_app=1 → \"From an app manifest\" — its OAuth scopes and bot event subscriptions are derived from the agent's slack trigger config (mention_only / auto_resume_threads / ack_reaction) and its Slack tools, so it subscribes to exactly the events the config needs. Hand the user the manifest plus the create-from-manifest link; surface `notes` (e.g. invite the bot to its channels). 400 if the revision has no slack trigger.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Generate the Slack app manifest for a revision",
+ "title": "Generate the Slack app manifest for a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-spec-update": {
+ "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Replace the author-facing spec",
+ "title": "Replace the author-facing spec",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-system-prompt": {
+ "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Preview the assembled system prompt for a revision",
+ "title": "Preview the assembled system prompt for a revision",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-tools-destroy": {
+ "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Delete one custom tool",
+ "title": "Delete one custom tool",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-tools-update": {
+ "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Upsert one custom tool",
+ "title": "Upsert one custom tool",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-revisions-validate-create": {
+ "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Validate a revision's bundle + spec",
+ "title": "Validate a revision's bundle + spec",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-sessions-list": {
+ "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List sessions for an agent",
+ "title": "List sessions for an agent",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
+ "agent-applications-sessions-retrieve": {
+ "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `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.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Get one session",
+ "title": "Get one session",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
"agent-feedback": {
"description": "Optional: report a concrete problem with this PostHog MCP server itself — a tool, input schema, response format, error, or these instructions. Keep feedback about the MCP, not the user's task, their data, or your findings. ONLY use this when something went wrong or was missing: friction that slowed you down, a surprise, a missing capability, an unhelpful error, wrong results, or unclear docs. Feedback must be constructive and actionable — point at a specific defect the PostHog team can fix and name the change in `suggested_improvement`. Do NOT submit positive or 'everything worked' reports — they are noise we cannot act on. Skip it entirely for routine tasks where nothing went wrong. Keep `summary` to one sentence and write the free-text fields as clear, concise bullet points, quoting tool names, parameters, and error messages where possible. Do not include user PII or sensitive query content. IMPORTANT: submitting feedback does NOT mean your work is done — keep going and finish the user's task using the other available tools. This tool is for reporting problems to the PostHog team, not for ending the conversation.",
"category": "Feedback",
@@ -262,6 +757,21 @@
"readOnlyHint": true
}
},
+ "agent-native-tools-list": {
+ "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "List native tools the runner knows",
+ "title": "List native tools the runner knows",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform-mcp"
+ },
"alert-create": {
"description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",
"category": "Alerts",
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index 3c514edb52aa..fd857cea275c 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -1608,6 +1608,11 @@ function generateDefinitionsJson(
const baseDescription = resolveDescription(toolConfig, yamlDir, opDescription)
const baseTitle = toolConfig.title || resolved.operation.summary || name
const baseSummary = toolConfig.title || opDescription.split('.')[0] || name
+ // Per-tool feature_flag wins; otherwise inherit the category-level
+ // gate (lets one line gate a whole not-yet-GA product).
+ const featureFlag = toolConfig.feature_flag ?? category.feature_flag
+ const featureFlagBehavior = toolConfig.feature_flag_behavior ?? category.feature_flag_behavior
+ const featureFlagVariant = toolConfig.feature_flag_variant ?? category.feature_flag_variant
if (toolConfig.confirmed_action) {
// Two-tool typed-confirm paradigm: emit `<name>-prepare` and
@@ -1632,13 +1637,9 @@ function generateDefinitionsJson(
readOnlyHint: true,
},
...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),
- ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),
- ...(toolConfig.feature_flag_behavior
- ? { feature_flag_behavior: toolConfig.feature_flag_behavior }
- : {}),
- ...(toolConfig.feature_flag_variant
- ? { feature_flag_variant: toolConfig.feature_flag_variant }
- : {}),
+ ...(featureFlag ? { feature_flag: featureFlag } : {}),
+ ...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
+ ...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
definitions[`${name}-execute`] = {
@@ -1659,13 +1660,9 @@ function generateDefinitionsJson(
readOnlyHint: toolConfig.annotations.readOnly,
},
...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),
- ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),
- ...(toolConfig.feature_flag_behavior
- ? { feature_flag_behavior: toolConfig.feature_flag_behavior }
- : {}),
- ...(toolConfig.feature_flag_variant
- ? { feature_flag_variant: toolConfig.feature_flag_variant }
- : {}),
+ ...(featureFlag ? { feature_flag: featureFlag } : {}),
+ ...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
+ ...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
} else {
@@ -1683,13 +1680,9 @@ function generateDefinitionsJson(
readOnlyHint: toolConfig.annotations.readOnly,
},
...(toolConfig.requires_ai_consent ? { requires_ai_consent: true } : {}),
- ...(toolConfig.feature_flag ? { feature_flag: toolConfig.feature_flag } : {}),
- ...(toolConfig.feature_flag_behavior
- ? { feature_flag_behavior: toolConfig.feature_flag_behavior }
- : {}),
- ...(toolConfig.feature_flag_variant
- ? { feature_flag_variant: toolConfig.feature_flag_variant }
- : {}),
+ ...(featureFlag ? { feature_flag: featureFlag } : {}),
+ ...(featureFlagBehavior ? { feature_flag_behavior: featureFlagBehavior } : {}),
+ ...(featureFlagVariant ? { feature_flag_variant: featureFlagVariant } : {}),
...(toolConfig.system_prompt_hint ? { system_prompt_hint: toolConfig.system_prompt_hint } : {}),
}
}
diff --git a/services/mcp/scripts/scaffold-yaml.ts b/services/mcp/scripts/scaffold-yaml.ts
index 020d41730ead..98f3971b7ed2 100644
--- a/services/mcp/scripts/scaffold-yaml.ts
+++ b/services/mcp/scripts/scaffold-yaml.ts
@@ -294,6 +294,10 @@ function mergeWithExisting(
category: existing.category ?? tag.charAt(0).toUpperCase() + tag.slice(1),
feature: existing.feature ?? tag.replace(/-/g, '_'),
url_prefix: existing.url_prefix ?? `/${tag.replace(/_/g, '-')}`,
+ // Hand-authored category-level gate — sync must not drop it.
+ ...(existing.feature_flag ? { feature_flag: existing.feature_flag } : {}),
+ ...(existing.feature_flag_behavior ? { feature_flag_behavior: existing.feature_flag_behavior } : {}),
+ ...(existing.feature_flag_variant ? { feature_flag_variant: existing.feature_flag_variant } : {}),
ui_apps: existing.ui_apps ?? {},
tools: sortedTools,
}
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index 4bfab5f24f5f..e210c1ae23f8 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -488,6 +488,14 @@ export const CategoryConfigSchema = z
category: z.string(),
feature: z.string().regex(FEATURE_NAME_PATTERN, 'Feature must be lowercase snake_case: [a-z0-9_]'),
url_prefix: z.string(),
+ /**
+ * Category-level feature flag gate, inherited by every tool that doesn't
+ * set its own `feature_flag`. Use to hide a whole not-yet-GA product
+ * from the standard MCP surface in one place. See ToolConfigSchema.feature_flag.
+ */
+ feature_flag: z.string().optional(),
+ feature_flag_behavior: z.enum(['enable', 'disable']).optional(),
+ feature_flag_variant: z.string().optional(),
tools: z.record(
z
.string()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4eb96d18ea51..4d0fb1b2811c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7109,6 +7109,595 @@ export namespace Schemas {
uploads: UploadTarget[];
}
+ export interface AgentAggregateStats {
+ /** Sessions currently in a live state (queued / running). */
+ liveCount: number;
+ /** Sessions created within the `since` window across all states. */
+ sessionsInWindowCount: number;
+ /** Sum of `usage_total.cost_total` across sessions in the window. */
+ spendInWindowUsd: number;
+ /**
+ * ISO timestamp of the most recent session update — null when there are no sessions.
+ * @nullable
+ */
+ lastActivityAt: string | null;
+ /** Sessions in `failed` state created within the window. */
+ failedInWindowCount: number;
+ /** Approval-gated tool requests across the team currently awaiting a decision. 0 on the per-application aggregate (which doesn't roll up approvals). */
+ pendingApprovalsCount: number;
+ }
+
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ export type AgentApplicationCreatedBy = {
+ readonly id?: number;
+ readonly first_name?: string;
+ readonly email?: string;
+ } | null;
+
+ export interface AgentApplication {
+ readonly id: string;
+ readonly team_id: number;
+ /** @maxLength 255 */
+ name: string;
+ /**
+ * Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).
+ * @maxLength 63
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string;
+ description?: string;
+ /** @nullable */
+ readonly live_revision: string | null;
+ archived?: boolean;
+ /** @nullable */
+ readonly archived_at: string | null;
+ /** @nullable */
+ readonly created_by_id: number | null;
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by: AgentApplicationCreatedBy;
+ readonly created_at: string;
+ readonly updated_at: string;
+ /**
+ * Public URL to paste into the Slack app dashboard under Event Subscriptions → Request URL. Computed from the agent slug and the deployment's ingress routing mode (`AGENT_INGRESS_DOMAIN_SUFFIX` in domain mode, `AGENT_INGRESS_PUBLIC_URL` in path mode). Null when no public agent-ingress URL is configured (e.g. local dev without a tunnel).
+ * @nullable
+ */
+ readonly slack_events_url: string | null;
+ /**
+ * Public URL to paste into the Slack app dashboard under Interactivity & Shortcuts → Request URL. Same source + null behaviour as `slack_events_url`.
+ * @nullable
+ */
+ readonly slack_interactivity_url: string | null;
+ /**
+ * Mode-aware base URL the agent's trigger routes hang off — append `/webhook`, `/run`, `/mcp`, etc. Domain mode: `https://<slug><suffix>`; path mode: `<public_url>/agents/<slug>`. Same source + null behaviour as `slack_events_url` (null when no public ingress URL is configured).
+ * @nullable
+ */
+ readonly ingress_base_url: string | null;
+ }
+
+ /**
+ * * `queued` - queued
+ * * `approving` - approving
+ * * `dispatched` - dispatched
+ * * `dispatched_failed` - dispatched_failed
+ * * `rejected` - rejected
+ * * `expired` - expired
+ */
+ export type AgentApprovalRequestStateEnum = typeof AgentApprovalRequestStateEnum[keyof typeof AgentApprovalRequestStateEnum];
+
+
+ export const AgentApprovalRequestStateEnum = {
+ Queued: 'queued',
+ Approving: 'approving',
+ Dispatched: 'dispatched',
+ DispatchedFailed: 'dispatched_failed',
+ Rejected: 'rejected',
+ Expired: 'expired',
+ } as const;
+
+ /**
+ * Arguments the model proposed. Frozen at intercept time.
+ */
+ export type AgentApprovalRequestProposedArgs = { [key: string]: unknown };
+
+ /**
+ * Approver-edited arguments. Present iff `approval_policy.allow_edit` was true and the approver supplied edits.
+ * @nullable
+ */
+ export type AgentApprovalRequestDecidedArgs = { [key: string]: unknown } | null;
+
+ /**
+ * Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning.
+ */
+ export type AgentApprovalRequestAssistantMessage = { [key: string]: unknown };
+
+ /**
+ * Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time.
+ */
+ export type AgentApprovalRequestApproverScope = { [key: string]: unknown };
+
+ /**
+ * `{result: ...}` on a successful approved dispatch, `{error: "..."}` when the tool threw. Null until the runner has finalised.
+ * @nullable
+ */
+ export type AgentApprovalRequestDispatchOutcome = { [key: string]: unknown } | null;
+
+ export interface AgentApprovalRequest {
+ /** Approval request UUID — stable, used in /approvals/<id>/decide. */
+ id: string;
+ /** UUID of the session that proposed the gated call. */
+ session_id: string;
+ /** UUID of the parent agent application. */
+ application_id: string;
+ /** Team that owns the agent. */
+ team_id: number;
+ /** Revision the gated call was proposed against. */
+ revision_id: string;
+ /** Turn number within the session that emitted the call. */
+ turn: number;
+ /** pi-ai ToolCall.id from the original assistant message; matched into the synthetic tool_result. */
+ tool_call_id: string;
+ /** Tool id the model invoked (e.g. `@posthog/team-delete`). */
+ tool_name: string;
+ /** Arguments the model proposed. Frozen at intercept time. */
+ proposed_args: AgentApprovalRequestProposedArgs;
+ /**
+ * Approver-edited arguments. Present iff `approval_policy.allow_edit` was true and the approver supplied edits.
+ * @nullable
+ */
+ decided_args: AgentApprovalRequestDecidedArgs;
+ /** Snapshot of the assistant message that emitted the call (text + thinking blocks) — what the approver sees as the model's reasoning. */
+ assistant_message: AgentApprovalRequestAssistantMessage;
+ /** Resolved approver policy (approvers, allow_edit, allow_agent_approver) at request time. */
+ approver_scope: AgentApprovalRequestApproverScope;
+ /** Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.
+ *
+ * * `queued` - queued
+ * * `approving` - approving
+ * * `dispatched` - dispatched
+ * * `dispatched_failed` - dispatched_failed
+ * * `rejected` - rejected
+ * * `expired` - expired */
+ state: AgentApprovalRequestStateEnum;
+ /**
+ * UUID of the user who decided. Null while queued or expired.
+ * @nullable
+ */
+ decision_by: string | null;
+ /**
+ * ISO timestamp of the decision. Null while queued.
+ * @nullable
+ */
+ decision_at: string | null;
+ /**
+ * Free-form reason supplied by the approver. Optional.
+ * @nullable
+ */
+ decision_reason: string | null;
+ /**
+ * `{result: ...}` on a successful approved dispatch, `{error: "..."}` when the tool threw. Null until the runner has finalised.
+ * @nullable
+ */
+ dispatch_outcome: AgentApprovalRequestDispatchOutcome;
+ /** When the model proposed the gated call. */
+ created_at: string;
+ /** When the queued request auto-rejects if no decision arrives. */
+ expires_at: string;
+ }
+
+ export interface AgentApplicationApprovalsListResponse {
+ /** Approval requests for this application, newest first. */
+ 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;
+ /** Token TTL in seconds from issue. Clients should refresh before this elapses. */
+ expires_in: number;
+ /** Slug to use in the ingress URL — `<application_slug>-<revision_uuid_hex>`. Identifies the exact revision, placed in the host (domain mode) or path (path mode) routing prefix. */
+ ingress_slug: string;
+ /** Per-trigger ingress URLs the caller can hit directly, derived from the revision's `spec.triggers[]`. Shape: `{<trigger_type>: {<route_name>: <absolute_url>}}`. Only includes triggers the spec actually declares. Empty when no public agent-ingress URL is configured for the active routing mode. */
+ endpoints: unknown;
+ /** How to attach credentials to those endpoints: preview-token header/query names, the per-trigger accepted auth modes (`trigger_modes`), and a note about the live vs preview-mode gate split. Lets the caller wire auth without grepping the ingress source. */
+ auth: unknown;
+ /** Server-side alternative — `/api/projects/<team>/agent_applications/<slug>/preview-proxy/<path>` mints the JWT for you. Strips caller Authorization, so it works for public-auth agents; agents with required auth need the direct endpoints above. */
+ preview_proxy: unknown;
+ }
+
+ export interface LogEntry {
+ log_source_id: string;
+ instance_id: string;
+ timestamp: string;
+ level: string;
+ message: string;
+ }
+
+ export interface AgentApplicationSessionLogsResponse {
+ results: LogEntry[];
+ }
+
+ export interface AgentSessionUsageTotal {
+ tokens_in: number;
+ tokens_out: number;
+ cache_read: number;
+ cache_write: number;
+ cost_input: number;
+ cost_output: number;
+ cost_cache_read: number;
+ cost_cache_write: number;
+ cost_total: number;
+ }
+
+ /**
+ * * `anonymous` - anonymous
+ * * `service` - service
+ * * `internal` - internal
+ * * `shared_secret` - shared_secret
+ * * `slack` - slack
+ */
+ export type AgentSessionPrincipalKindEnum = typeof AgentSessionPrincipalKindEnum[keyof typeof AgentSessionPrincipalKindEnum];
+
+
+ export const AgentSessionPrincipalKindEnum = {
+ Anonymous: 'anonymous',
+ Service: 'service',
+ Internal: 'internal',
+ SharedSecret: 'shared_secret',
+ Slack: 'slack',
+ } as const;
+
+ export interface AgentSessionPrincipal {
+ /** What kind of principal authenticated the session start.
+ *
+ * * `anonymous` - anonymous
+ * * `service` - service
+ * * `internal` - internal
+ * * `shared_secret` - shared_secret
+ * * `slack` - slack */
+ kind: AgentSessionPrincipalKindEnum;
+ /** Stable identifier for the principal (PAT id, slack user id, etc). Absent for anonymous sessions. */
+ id?: string;
+ /** Team the principal belongs to. Absent for anonymous sessions. */
+ team_id?: number;
+ }
+
+ /**
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed
+ */
+ export type AgentSessionStateEnum = typeof AgentSessionStateEnum[keyof typeof AgentSessionStateEnum];
+
+
+ export const AgentSessionStateEnum = {
+ Queued: 'queued',
+ Running: 'running',
+ Completed: 'completed',
+ Closed: 'closed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ export type AgentSessionSummaryTriggerMetadata = { [key: string]: unknown } | null;
+
+ export interface AgentSessionSummary {
+ usage_total: AgentSessionUsageTotal;
+ principal: AgentSessionPrincipal | null;
+ id: string;
+ application_id: string;
+ revision_id: string;
+ state: AgentSessionStateEnum;
+ /** @nullable */
+ external_key: string | null;
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentSessionSummaryTriggerMetadata;
+ /** Count of messages in the conversation — the full transcript ships on the detail endpoint. */
+ turns: number;
+ /**
+ * Last assistant text (~120 chars). Null for sessions with no assistant turns yet.
+ * @nullable
+ */
+ preview: string | null;
+ retry_count: number;
+ created_at: string;
+ updated_at: string;
+ }
+
+ export interface AgentApplicationSessionsListResponse {
+ results: AgentSessionSummary[];
+ /** Total matching sessions before pagination. */
+ count: number;
+ }
+
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ export type AgentApplicationSessionsRetrieveResponseTriggerMetadata = { [key: string]: unknown } | null;
+
+ export type AgentConversationUserMessageRole = typeof AgentConversationUserMessageRole[keyof typeof AgentConversationUserMessageRole];
+
+
+ export const AgentConversationUserMessageRole = {
+ User: 'user',
+ } as const;
+
+ export interface AgentConversationUserMessage {
+ role: AgentConversationUserMessageRole;
+ /** String shorthand, or array of {type:'text'|'image', ...} parts. */
+ content: unknown;
+ /** Epoch milliseconds. */
+ timestamp: number;
+ }
+
+ export type AgentConversationAssistantMessageRole = typeof AgentConversationAssistantMessageRole[keyof typeof AgentConversationAssistantMessageRole];
+
+
+ export const AgentConversationAssistantMessageRole = {
+ Assistant: 'assistant',
+ } as const;
+
+ /**
+ * * `stop` - stop
+ * * `length` - length
+ * * `toolUse` - toolUse
+ * * `error` - error
+ * * `aborted` - aborted
+ */
+ export type StopReasonEnum = typeof StopReasonEnum[keyof typeof StopReasonEnum];
+
+
+ export const StopReasonEnum = {
+ Stop: 'stop',
+ Length: 'length',
+ ToolUse: 'toolUse',
+ Error: 'error',
+ Aborted: 'aborted',
+ } as const;
+
+ export type AgentConversationAssistantMessageUsage = { [key: string]: unknown };
+
+ export interface AgentConversationAssistantMessage {
+ role: AgentConversationAssistantMessageRole;
+ /** Array of text/thinking/toolCall parts. */
+ content: unknown[];
+ /** Epoch milliseconds. */
+ timestamp: number;
+ api?: string;
+ provider?: string;
+ model?: string;
+ usage?: AgentConversationAssistantMessageUsage;
+ stopReason?: StopReasonEnum;
+ errorMessage?: string;
+ }
+
+ export type AgentConversationToolResultMessageRole = typeof AgentConversationToolResultMessageRole[keyof typeof AgentConversationToolResultMessageRole];
+
+
+ export const AgentConversationToolResultMessageRole = {
+ ToolResult: 'toolResult',
+ } as const;
+
+ export interface AgentConversationToolResultMessage {
+ role: AgentConversationToolResultMessageRole;
+ toolCallId: string;
+ toolName: string;
+ /** Array of {type:'text'|'image', ...} parts. */
+ content: unknown[];
+ isError: boolean;
+ /** Epoch milliseconds. */
+ timestamp: number;
+ }
+
+ export type AgentConversationMessage = AgentConversationUserMessage | AgentConversationAssistantMessage | AgentConversationToolResultMessage;
+
+ export interface AgentApplicationSessionsRetrieveResponse {
+ usage_total: AgentSessionUsageTotal;
+ principal: AgentSessionPrincipal | null;
+ id: string;
+ application_id: string;
+ revision_id: string;
+ team_id: number;
+ /** @nullable */
+ external_key: string | null;
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentApplicationSessionsRetrieveResponseTriggerMetadata;
+ state: AgentSessionStateEnum;
+ /** Full transcript, or the trailing `last_n` messages if `?last_n=` was supplied. */
+ conversation: AgentConversationMessage[];
+ /** Messages that arrived while a turn was in flight; drained into `conversation` at the start of the next turn. */
+ pending_inputs: AgentConversationMessage[];
+ /** Times the janitor has re-queued this session after a stuck-running detection. */
+ retry_count: number;
+ created_at: string;
+ updated_at: string;
+ /** True when `?last_n=` was supplied AND the full conversation exceeded it. */
+ conversation_trimmed: boolean;
+ /** Total messages in the untrimmed conversation. Present only when `conversation_trimmed=true`. */
+ conversation_total_turns?: number;
+ }
+
+ export interface AgentApprovalsDecideResponse {
+ /** Always `true` on a successful decision. */
+ ok: boolean;
+ /** The approval row's new state — `approving` for approve, `rejected` for reject. */
+ state: string;
+ }
+
+ /**
+ * * `assistant` - assistant
+ */
+ export type AgentConversationAssistantMessageRoleEnum = typeof AgentConversationAssistantMessageRoleEnum[keyof typeof AgentConversationAssistantMessageRoleEnum];
+
+
+ export const AgentConversationAssistantMessageRoleEnum = {
+ Assistant: 'assistant',
+ } as const;
+
+ /**
+ * * `toolResult` - toolResult
+ */
+ export type AgentConversationToolResultMessageRoleEnum = typeof AgentConversationToolResultMessageRoleEnum[keyof typeof AgentConversationToolResultMessageRoleEnum];
+
+
+ export const AgentConversationToolResultMessageRoleEnum = {
+ ToolResult: 'toolResult',
+ } as const;
+
+ /**
+ * * `user` - user
+ */
+ export type AgentConversationUserMessageRoleEnum = typeof AgentConversationUserMessageRoleEnum[keyof typeof AgentConversationUserMessageRoleEnum];
+
+
+ export const AgentConversationUserMessageRoleEnum = {
+ User: 'user',
+ } as const;
+
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ export type AgentFleetLiveSessionSummaryTriggerMetadata = { [key: string]: unknown } | null;
+
+ export interface AgentFleetLiveSessionSummary {
+ usage_total: AgentSessionUsageTotal;
+ principal: AgentSessionPrincipal | null;
+ id: string;
+ application_id: string;
+ revision_id: string;
+ team_id: number;
+ state: AgentSessionStateEnum;
+ /** @nullable */
+ external_key: string | null;
+ /**
+ * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * @nullable
+ */
+ trigger_metadata?: AgentFleetLiveSessionSummaryTriggerMetadata;
+ /** Messages in the conversation so far. */
+ turns: number;
+ /**
+ * Last assistant text (~120 chars). Null when no assistant turns yet.
+ * @nullable
+ */
+ preview: string | null;
+ created_at: string;
+ updated_at: string;
+ }
+
+ export interface AgentFleetLiveSessionsResponse {
+ results: AgentFleetLiveSessionSummary[];
+ }
+
+ export interface AgentMemoryFile {
+ /** Full markdown body. */
+ content: string;
+ }
+
+ export interface AgentMemoryHeader {
+ /** Relative path within the agent's memory, e.g. 'incidents/db.md'. */
+ path: string;
+ /** One-line summary from the file's frontmatter. */
+ description: string;
+ /** Frontmatter tags (lowercase a-z 0-9 _ - only). */
+ tags: string[];
+ /**
+ * ISO-8601 timestamp stamped on create. Null for files written before this field was introduced.
+ * @nullable
+ */
+ created_at: string | null;
+ /**
+ * ISO-8601 timestamp stamped on every write.
+ * @nullable
+ */
+ updated_at: string | null;
+ }
+
+ export interface AgentMemoryListResponse {
+ /** Number of entries returned. */
+ count: number;
+ /** Headers (frontmatter only) — no file bodies. Use the read endpoint for the body. */
+ entries: AgentMemoryHeader[];
+ }
+
+ export interface AgentMemorySearchResult {
+ path: string;
+ description: string;
+ tags: string[];
+ /** BM25 relevance score. */
+ score: number;
+ /**
+ * Body snippet around the earliest match. Null when only the header matched.
+ * @nullable
+ */
+ snippet: string | null;
+ }
+
+ export interface AgentMemorySearchResponse {
+ /** The original search cue, echoed back. */
+ cue: string;
+ count: number;
+ results: AgentMemorySearchResult[];
+ }
+
+ /**
+ * Folder tree rooted at the agent's memory prefix. Each node is {name, type: 'folder'|'file', path?, description?, tags?, children?}.
+ */
+ export type AgentMemoryTreeResponseRoot = { [key: string]: unknown };
+
+ export interface AgentMemoryTreeResponse {
+ /** Folder tree rooted at the agent's memory prefix. Each node is {name, type: 'folder'|'file', path?, description?, tags?, children?}. */
+ root: AgentMemoryTreeResponseRoot;
+ }
+
+ /**
+ * Body shape for AgentMemoryViewSet.write_file (create).
+ */
+ export interface AgentMemoryWriteRequest {
+ /** Where to store the file. Lowercase a-z 0-9 _ - / only, must end in .md. */
+ path: string;
+ /**
+ * One-line summary, max 280 chars. Surfaces in list/search results.
+ * @maxLength 280
+ */
+ description: string;
+ /** Full markdown body. */
+ content: string;
+ /** Optional flat tags for search ranking. Lowercase a-z 0-9 _ - only. */
+ tags?: string[];
+ }
+
/**
* * `product_analytics` - product_analytics
* * `sql` - sql
@@ -7143,6 +7732,409 @@ export namespace Schemas {
CustomerAnalytics: 'customer_analytics',
} as const;
+ export type AgentNativeToolEntrySchema = { [key: string]: unknown };
+
+ export interface AgentNativeToolEntry {
+ id: string;
+ schema: AgentNativeToolEntrySchema;
+ }
+
+ export interface AgentNativeToolsListResponse {
+ tools: AgentNativeToolEntry[];
+ }
+
+ export type AgentRevisionSpecTriggersItem = {
+ type: 'slack';
+ config: {
+ channel_id?: string;
+ mention_only: boolean;
+ auto_resume_threads: boolean;
+ allow_workspace_participants: boolean;
+ ack_reaction?: string;
+ trusted_workspaces: string[] | '*';
+ };
+ } | {
+ type: 'webhook';
+ config: {
+ path: string;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ } | {
+ type: 'cron';
+ config: {
+ /** @minLength 1 */
+ name: string;
+ /** @minLength 1 */
+ schedule: string;
+ timezone?: string;
+ /**
+ * @minLength 1
+ * @maxLength 4096
+ */
+ prompt: string;
+ external_key?: string;
+ catch_up?: 'all' | 'most_recent' | 'skip';
+ /**
+ * @minimum 1
+ * @maximum 604800
+ */
+ max_catch_up_age_seconds?: number;
+ };
+ } | {
+ type: 'chat';
+ config?: {
+ allow_restart?: boolean;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ } | {
+ type: 'mcp';
+ config?: {
+ allow_restart?: boolean;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ };
+
+ export type AgentRevisionSpecToolsItem = {
+ kind: 'native';
+ id: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ } | {
+ kind: 'custom';
+ id: string;
+ path: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ } | {
+ kind: 'custom_template';
+ from_template: string;
+ alias: string;
+ /** @minimum 0 */
+ version?: number;
+ } | {
+ kind: 'client';
+ /** @minLength 1 */
+ id: string;
+ /** @minLength 1 */
+ description: string;
+ args_schema?: { [key: string]: unknown };
+ required?: boolean;
+ /**
+ * @minimum 1
+ * @maximum 600000
+ */
+ timeout_ms?: number;
+ interactive?: boolean;
+ };
+
+ export type AgentRevisionSpecMcpsItemAuth = {
+ integration?: string;
+ };
+
+ export type AgentRevisionSpecMcpsItemHeaders = {[key: string]: string};
+
+ export type AgentRevisionSpecMcpsItemToolsItem = string | {
+ /** @minLength 1 */
+ name: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ };
+
+ export type AgentRevisionSpecMcpsItem = {
+ /** @minLength 1 */
+ id: string;
+ url: string;
+ auth?: AgentRevisionSpecMcpsItemAuth;
+ secrets?: string[];
+ headers?: AgentRevisionSpecMcpsItemHeaders;
+ tools?: AgentRevisionSpecMcpsItemToolsItem[];
+ };
+
+ export type AgentRevisionSpecSkillsItem = {
+ id: string;
+ path: string;
+ description?: string;
+ from_template?: string;
+ alias?: string;
+ /** @minimum 0 */
+ version?: number;
+ };
+
+ export type AgentRevisionSpecLimits = {
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_turns: number;
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_tool_calls: number;
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_wall_seconds: number;
+ /**
+ * @maximum 200000
+ * @exclusiveMinimum 0
+ */
+ max_output_tokens?: number;
+ };
+
+ export type AgentRevisionSpecReasoning = typeof AgentRevisionSpecReasoning[keyof typeof AgentRevisionSpecReasoning];
+
+
+ export const AgentRevisionSpecReasoning = {
+ Minimal: 'minimal',
+ Low: 'low',
+ Medium: 'medium',
+ High: 'high',
+ Xhigh: 'xhigh',
+ } as const;
+
+ export type AgentRevisionSpec = {
+ /** @minLength 1 */
+ model: string;
+ triggers: AgentRevisionSpecTriggersItem[];
+ tools: AgentRevisionSpecToolsItem[];
+ mcps: AgentRevisionSpecMcpsItem[];
+ skills: AgentRevisionSpecSkillsItem[];
+ integrations: string[];
+ secrets: string[];
+ limits: AgentRevisionSpecLimits;
+ entrypoint: string;
+ reasoning?: AgentRevisionSpecReasoning;
+ };
+
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ export type AgentRevisionCreatedBy = {
+ readonly id?: number;
+ readonly first_name?: string;
+ readonly email?: string;
+ } | null;
+
+ /**
+ * * `draft` - draft
+ * * `ready` - ready
+ * * `live` - live
+ * * `archived` - archived
+ */
+ export type AgentRevisionStateEnum = typeof AgentRevisionStateEnum[keyof typeof AgentRevisionStateEnum];
+
+
+ export const AgentRevisionStateEnum = {
+ Draft: 'draft',
+ Ready: 'ready',
+ Live: 'live',
+ Archived: 'archived',
+ } as const;
+
+ export interface AgentRevision {
+ readonly id: string;
+ readonly application: string;
+ /** @nullable */
+ parent_revision?: string | null;
+ readonly state: AgentRevisionStateEnum;
+ bundle_uri?: string;
+ /** @nullable */
+ readonly bundle_sha256: string | null;
+ spec?: AgentRevisionSpec;
+ /** @nullable */
+ readonly created_by_id: number | null;
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by: AgentRevisionCreatedBy;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
+ export interface AgentRevisionCronFireRequest {
+ /** `name` of the cron trigger in `spec.triggers[]` to fire. */
+ cron_name: string;
+ /**
+ * Stable client-supplied id so repeated clicks of the same UI 'Fire now' button resolve to the same session id rather than firing twice. The janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit to fire unconditionally — every call generates a fresh UUID.
+ * @nullable
+ */
+ request_id?: string | null;
+ }
+
+ export interface AgentRevisionCronFireResponse {
+ ok: boolean;
+ /** ID of the session the cron firing created (or returned, on dedupe). */
+ session_id: string;
+ /** ISO-8601 timestamp the firing was attributed to. */
+ fired_at: string;
+ /** Composed dedupe key — `cron-manual:<rev>:<name>:<request_id>`. Returned so the UI can correlate. */
+ idempotency_key: string;
+ /** The request id the firing used (echoed back, or freshly minted). */
+ request_id: 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. */
+ manifest: unknown;
+ /** Reminders the manifest can't enforce (e.g. invite the bot to its channels). */
+ notes: string[];
+ /**
+ * The Event Subscriptions Request URL baked into the manifest.
+ * @nullable
+ */
+ events_url: string | null;
+ /**
+ * The Interactivity Request URL (used by approval-gated tools).
+ * @nullable
+ */
+ interactivity_url: string | null;
+ }
+
+ export interface AgentRevisionSystemPromptResponse {
+ /** UUID of the revision the prompt was rendered for. */
+ revision_id: string;
+ /** Active framework preamble version. Bumps when the platform's `# Platform guidance` content changes meaningfully (decision rules, sections renamed, behavioural defaults flipped). Authors can pin to a specific version via `spec.framework_prompt.version_pin`. */
+ framework_prompt_version: number;
+ /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md` (or `spec.entrypoint`), and the skills index. Inspect before promotion to confirm the model will see what you expect — see docs/agent-platform/plans/framework-system-prompt.md §4. */
+ system_prompt: string;
+ }
+
+ export interface AgentRevisionValidationError {
+ code: string;
+ message: string;
+ pointer: string;
+ }
+
+ export interface AgentRevisionValidateResponse {
+ ok: boolean;
+ revision_id: string;
+ revision_state: string;
+ errors: AgentRevisionValidationError[];
+ resolved_natives: string[];
+ }
+
+ export interface AgentTableHeader {
+ /** Table name. */
+ name: string;
+ /** Object size in bytes. */
+ size: number;
+ }
+
+ export type AgentTableRowsResponseRowsItem = { [key: string]: unknown };
+
+ export interface AgentTableRowsResponse {
+ name: string;
+ /** Total rows in the table. */
+ total: number;
+ /** Rows in this response (capped by limit). */
+ returned: number;
+ limit: number;
+ /** The rows (arbitrary JSON objects). */
+ rows: AgentTableRowsResponseRowsItem[];
+ }
+
+ export interface AgentTablesListResponse {
+ /** Number of tables. */
+ count: number;
+ /** Tabular-reference tables for this agent (the @posthog/table-* JSONL tables). */
+ tables: AgentTableHeader[];
+ }
+
export interface AggregatedSpanRow {
avg_duration_nano: number;
count: number;
@@ -10986,6 +11978,14 @@ export namespace Schemas {
readonly elements_chain: string;
}
+ /**
+ * Body shape for POST /revisions/<id>/clone_from/ — copy every file
+ * from `source_revision_id` into this (draft) revision.
+ */
+ export interface CloneFromRequest {
+ source_revision_id: string;
+ }
+
export interface DiffCluster {
x: number;
y: number;
@@ -14191,6 +15191,40 @@ export namespace Schemas {
value: string | number;
}
+ /**
+ * Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422.
+ */
+ export type DecideApprovalRequestEditedArgs = { [key: string]: unknown };
+
+ /**
+ * * `approve` - approve
+ * * `reject` - reject
+ */
+ export type DecisionEnum = typeof DecisionEnum[keyof typeof DecisionEnum];
+
+
+ export const DecisionEnum = {
+ Approve: 'approve',
+ Reject: 'reject',
+ } as const;
+
+ /**
+ * Body shape for POST /agent_applications/<id>/approvals/<approval_id>/decide/.
+ *
+ * See docs/agent-platform/plans/approval-gated-tools.md.
+ */
+ export interface DecideApprovalRequest {
+ /** The approver's decision. `approve` runs the tool platform-side with the (possibly edited) args; `reject` records a terminal rejection and wakes the session with a synthetic rejected tool_result.
+ *
+ * * `approve` - approve
+ * * `reject` - reject */
+ decision: DecisionEnum;
+ /** Approver-edited tool arguments. Only honoured when the tool's `approval_policy.allow_edit` is `true`; otherwise the janitor returns 422. */
+ edited_args?: DecideApprovalRequestEditedArgs;
+ /** Free-form approver note. Surfaces in the session's synthetic tool_result so the model can communicate the reason back to the user. */
+ reason?: string;
+ }
+
/**
* * `bayesian` - Bayesian
* * `frequentist` - Frequentist
@@ -24082,6 +25116,17 @@ export namespace Schemas {
Custom: 'custom',
} as const;
+ /**
+ * Body shape for POST /revisions/clone_from/ — atomically create a new
+ * draft revision under `application_id` and clone its initial bundle from
+ * `source_revision_id`. Convenience for the "edit live" flow so the MCP
+ * doesn't have to do create-then-clone-from in two calls.
+ */
+ export interface NewDraftRevisionRequest {
+ application_id: string;
+ source_revision_id: string;
+ }
+
/**
* * `table` - Table
* * `view` - View
@@ -25102,6 +26147,24 @@ export namespace Schemas {
results: ActivityLog[];
}
+ export interface PaginatedAgentApplicationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AgentApplication[];
+ }
+
+ export interface PaginatedAgentRevisionList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AgentRevision[];
+ }
+
export interface PaginatedAlertList {
count: number;
/** @nullable */
@@ -29337,6 +30400,355 @@ export namespace Schemas {
person_ids?: string[];
}
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ export type PatchedAgentApplicationCreatedBy = {
+ readonly id?: number;
+ readonly first_name?: string;
+ readonly email?: string;
+ } | null;
+
+ export interface PatchedAgentApplication {
+ readonly id?: string;
+ readonly team_id?: number;
+ /** @maxLength 255 */
+ name?: string;
+ /**
+ * Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).
+ * @maxLength 63
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string;
+ description?: string;
+ /** @nullable */
+ readonly live_revision?: string | null;
+ archived?: boolean;
+ /** @nullable */
+ readonly archived_at?: string | null;
+ /** @nullable */
+ readonly created_by_id?: number | null;
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by?: PatchedAgentApplicationCreatedBy;
+ readonly created_at?: string;
+ readonly updated_at?: string;
+ /**
+ * Public URL to paste into the Slack app dashboard under Event Subscriptions → Request URL. Computed from the agent slug and the deployment's ingress routing mode (`AGENT_INGRESS_DOMAIN_SUFFIX` in domain mode, `AGENT_INGRESS_PUBLIC_URL` in path mode). Null when no public agent-ingress URL is configured (e.g. local dev without a tunnel).
+ * @nullable
+ */
+ readonly slack_events_url?: string | null;
+ /**
+ * Public URL to paste into the Slack app dashboard under Interactivity & Shortcuts → Request URL. Same source + null behaviour as `slack_events_url`.
+ * @nullable
+ */
+ readonly slack_interactivity_url?: string | null;
+ /**
+ * Mode-aware base URL the agent's trigger routes hang off — append `/webhook`, `/run`, `/mcp`, etc. Domain mode: `https://<slug><suffix>`; path mode: `<public_url>/agents/<slug>`. Same source + null behaviour as `slack_events_url` (null when no public ingress URL is configured).
+ * @nullable
+ */
+ readonly ingress_base_url?: string | null;
+ }
+
+ /**
+ * Body shape for AgentMemoryViewSet.update_file. Omitted fields preserve the existing value.
+ */
+ export interface PatchedAgentMemoryUpdateRequest {
+ /** @maxLength 280 */
+ description?: string;
+ content?: string;
+ tags?: string[];
+ }
+
+ export type PatchedAgentRevisionSpecTriggersItem = {
+ type: 'slack';
+ config: {
+ channel_id?: string;
+ mention_only: boolean;
+ auto_resume_threads: boolean;
+ allow_workspace_participants: boolean;
+ ack_reaction?: string;
+ trusted_workspaces: string[] | '*';
+ };
+ } | {
+ type: 'webhook';
+ config: {
+ path: string;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ } | {
+ type: 'cron';
+ config: {
+ /** @minLength 1 */
+ name: string;
+ /** @minLength 1 */
+ schedule: string;
+ timezone?: string;
+ /**
+ * @minLength 1
+ * @maxLength 4096
+ */
+ prompt: string;
+ external_key?: string;
+ catch_up?: 'all' | 'most_recent' | 'skip';
+ /**
+ * @minimum 1
+ * @maximum 604800
+ */
+ max_catch_up_age_seconds?: number;
+ };
+ } | {
+ type: 'chat';
+ config?: {
+ allow_restart?: boolean;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ } | {
+ type: 'mcp';
+ config?: {
+ allow_restart?: boolean;
+ };
+ auth: {
+ modes?: ({
+ type: 'public';
+ acknowledge_public_exposure: true;
+ } | {
+ type: 'posthog';
+ scopes?: string[];
+ } | {
+ type: 'jwt';
+ /** @minLength 1 */
+ issuer_secret_ref: string;
+ } | {
+ type: 'shared_secret';
+ /** @minLength 1 */
+ header: string;
+ /** @minLength 1 */
+ secret_ref: string;
+ } | {
+ type: 'posthog_internal';
+ })[];
+ };
+ };
+
+ export type PatchedAgentRevisionSpecToolsItem = {
+ kind: 'native';
+ id: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ } | {
+ kind: 'custom';
+ id: string;
+ path: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ } | {
+ kind: 'custom_template';
+ from_template: string;
+ alias: string;
+ /** @minimum 0 */
+ version?: number;
+ } | {
+ kind: 'client';
+ /** @minLength 1 */
+ id: string;
+ /** @minLength 1 */
+ description: string;
+ args_schema?: { [key: string]: unknown };
+ required?: boolean;
+ /**
+ * @minimum 1
+ * @maximum 600000
+ */
+ timeout_ms?: number;
+ interactive?: boolean;
+ };
+
+ export type PatchedAgentRevisionSpecMcpsItemAuth = {
+ integration?: string;
+ };
+
+ export type PatchedAgentRevisionSpecMcpsItemHeaders = {[key: string]: string};
+
+ export type PatchedAgentRevisionSpecMcpsItemToolsItem = string | {
+ /** @minLength 1 */
+ name: string;
+ requires_approval?: boolean;
+ approval_policy?: {
+ /** @minItems 1 */
+ approvers?: ('team_admins' | 'session_principal')[];
+ allow_edit?: boolean;
+ /**
+ * @minimum 60000
+ * @maximum 604800000
+ */
+ ttl_ms?: number;
+ allow_agent_approver?: boolean;
+ };
+ };
+
+ export type PatchedAgentRevisionSpecMcpsItem = {
+ /** @minLength 1 */
+ id: string;
+ url: string;
+ auth?: PatchedAgentRevisionSpecMcpsItemAuth;
+ secrets?: string[];
+ headers?: PatchedAgentRevisionSpecMcpsItemHeaders;
+ tools?: PatchedAgentRevisionSpecMcpsItemToolsItem[];
+ };
+
+ export type PatchedAgentRevisionSpecSkillsItem = {
+ id: string;
+ path: string;
+ description?: string;
+ from_template?: string;
+ alias?: string;
+ /** @minimum 0 */
+ version?: number;
+ };
+
+ export type PatchedAgentRevisionSpecLimits = {
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_turns: number;
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_tool_calls: number;
+ /**
+ * @maximum 2147483647
+ * @exclusiveMinimum 0
+ */
+ max_wall_seconds: number;
+ /**
+ * @maximum 200000
+ * @exclusiveMinimum 0
+ */
+ max_output_tokens?: number;
+ };
+
+ export type PatchedAgentRevisionSpecReasoning = typeof PatchedAgentRevisionSpecReasoning[keyof typeof PatchedAgentRevisionSpecReasoning];
+
+
+ export const PatchedAgentRevisionSpecReasoning = {
+ Minimal: 'minimal',
+ Low: 'low',
+ Medium: 'medium',
+ High: 'high',
+ Xhigh: 'xhigh',
+ } as const;
+
+ export type PatchedAgentRevisionSpec = {
+ /** @minLength 1 */
+ model: string;
+ triggers: PatchedAgentRevisionSpecTriggersItem[];
+ tools: PatchedAgentRevisionSpecToolsItem[];
+ mcps: PatchedAgentRevisionSpecMcpsItem[];
+ skills: PatchedAgentRevisionSpecSkillsItem[];
+ integrations: string[];
+ secrets: string[];
+ limits: PatchedAgentRevisionSpecLimits;
+ entrypoint: string;
+ reasoning?: PatchedAgentRevisionSpecReasoning;
+ };
+
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ export type PatchedAgentRevisionCreatedBy = {
+ readonly id?: number;
+ readonly first_name?: string;
+ readonly email?: string;
+ } | null;
+
+ export interface PatchedAgentRevision {
+ readonly id?: string;
+ readonly application?: string;
+ /** @nullable */
+ parent_revision?: string | null;
+ readonly state?: AgentRevisionStateEnum;
+ bundle_uri?: string;
+ /** @nullable */
+ readonly bundle_sha256?: string | null;
+ spec?: PatchedAgentRevisionSpec;
+ /** @nullable */
+ readonly created_by_id?: number | null;
+ /**
+ * Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.
+ * @nullable
+ */
+ readonly created_by?: PatchedAgentRevisionCreatedBy;
+ readonly created_at?: string;
+ readonly updated_at?: string;
+ }
+
export interface PatchedAlert {
readonly id?: string;
readonly created_by?: UserBasic;
@@ -40264,6 +41676,29 @@ export namespace Schemas {
custom_tags?: SessionSummariesConfigCustomTags;
}
+ /**
+ * 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 SetEnvKeyRequest {
+ value: string;
+ }
+
+ export type SetEnvRequestEnv = {[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 SetEnvRequest {
+ env: SetEnvRequestEnv;
+ }
+
/**
* * `trace` - trace
* * `debug` - debug
@@ -43606,6 +45041,58 @@ export namespace Schemas {
failed: number;
}
+ /**
+ * Body shape for PUT /revisions/<id>/agent_md/.
+ */
+ export interface WriteAgentMdRequest {
+ content: string;
+ }
+
+ /**
+ * Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored
+ * at the canonical `skills/<skill_id>/SKILL.md` path in the bundle.
+ */
+ export interface WriteSkillRequest {
+ /** One-line summary shown in the skill index; the model uses it to decide when to load the skill. */
+ description: string;
+ /** The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`. */
+ body: string;
+ }
+
+ export type WriteSpecRequestSpec = { [key: string]: unknown };
+
+ /**
+ * Body shape for PUT /revisions/<id>/spec/. The body's `spec` object
+ * is the author-facing slice (skills/tools are server-derived at freeze).
+ */
+ export interface WriteSpecRequest {
+ spec: WriteSpecRequestSpec;
+ }
+
+ export type WriteToolRequestArgsSchema = { [key: string]: unknown };
+
+ /**
+ * Body shape for PUT /revisions/<id>/tools/<tool_id>/.
+ */
+ export interface WriteToolRequest {
+ description: string;
+ args_schema: WriteToolRequestArgsSchema;
+ source: string;
+ }
+
+ export type WriteTypedBundleRequestSpec = { [key: string]: unknown };
+
+ /**
+ * Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed
+ * payload. See docs/agent-platform/plans/typed-bundle-authoring-api.md §3.
+ */
+ export interface WriteTypedBundleRequest {
+ agent_md: string;
+ skills?: WriteSkillRequest[];
+ tools?: WriteToolRequest[];
+ spec: WriteTypedBundleRequestSpec;
+ }
+
export interface _CompareFilter {
/** When true, also fetch results for a comparison window and return them under `compare`. */
compare?: boolean;
@@ -49520,6 +51007,220 @@ export namespace Schemas {
was_impersonated?: boolean | null;
};
+ export type AgentApplicationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type AgentMemoryListFilesParams = {
+ /**
+ * Optional path prefix to scope the list, e.g. 'incidents/'.
+ */
+ prefix?: string;
+ };
+
+ export type AgentMemoryGetFileParams = {
+ /**
+ * Memory path returned by the list endpoint, e.g. 'incidents/db.md'.
+ */
+ path: string;
+ };
+
+ export type AgentMemoryUpdateFileParams = {
+ /**
+ * Memory path to update.
+ */
+ path: string;
+ };
+
+ export type AgentMemoryDeleteFileParams = {
+ /**
+ * Memory path to delete.
+ */
+ path: string;
+ };
+
+ export type AgentMemorySearchParams = {
+ /**
+ * Max results (default 10, max 100).
+ */
+ limit?: number;
+ /**
+ * Optional path prefix to scope the search.
+ */
+ prefix?: string;
+ /**
+ * Search cue — plain natural language is fine.
+ */
+ q: string;
+ };
+
+ export type AgentMemoryReadTableParams = {
+ /**
+ * Max rows to return (default 500, max 5000).
+ */
+ limit?: number;
+ };
+
+ export type AgentApplicationsRevisionsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type AgentApplicationsApprovalsListParams = {
+ limit?: number;
+ offset?: number;
+ /**
+ * Filter by approval state. Comma-separated list accepted. Valid values: queued, approving, dispatched, dispatched_failed, rejected, expired. Defaults to all states.
+ */
+ state?: string;
+ };
+
+ export type AgentApplicationsPreviewProxyGetParams = {
+ format?: AgentApplicationsPreviewProxyGetFormat;
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string;
+ };
+
+ export type AgentApplicationsPreviewProxyGetFormat = typeof AgentApplicationsPreviewProxyGetFormat[keyof typeof AgentApplicationsPreviewProxyGetFormat];
+
+
+ export const AgentApplicationsPreviewProxyGetFormat = {
+ Json: 'json',
+ Sse: 'sse',
+ } as const;
+
+ export type AgentApplicationsPreviewProxyParams = {
+ format?: AgentApplicationsPreviewProxyFormat;
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string;
+ };
+
+ export type AgentApplicationsPreviewProxyFormat = typeof AgentApplicationsPreviewProxyFormat[keyof typeof AgentApplicationsPreviewProxyFormat];
+
+
+ export const AgentApplicationsPreviewProxyFormat = {
+ Json: 'json',
+ Sse: 'sse',
+ } as const;
+
+ export type AgentApplicationsPreviewTokenParams = {
+ /**
+ * Target draft revision. Must belong to this application and not be live.
+ */
+ revision_id: string;
+ };
+
+ export type AgentApplicationsSessionsListParams = {
+ /**
+ * ISO datetime — return sessions with created_at >= this.
+ */
+ created_after?: string;
+ /**
+ * ISO datetime — return sessions with created_at <= this.
+ */
+ created_before?: string;
+ limit?: number;
+ offset?: number;
+ /**
+ * Only return sessions started against this specific revision.
+ */
+ revision_id?: string;
+ /**
+ * Filter by session state. Comma-separated list accepted (e.g. `completed,failed`). Valid values: queued, running, completed, closed, cancelled, failed.
+ */
+ state?: string;
+ };
+
+ export type AgentApplicationsSessionsRetrieveParams = {
+ /**
+ * If set, return only the most recent N messages from the conversation. `usage_total` is still computed over the full session — only the transcript is trimmed. The response includes `conversation_trimmed: true` and `conversation_total_turns` so the caller knows how much was hidden.
+ */
+ last_n?: number;
+ };
+
+ export type AgentApplicationsSessionLogsParams = {
+ /**
+ * Only return entries after this ISO 8601 timestamp.
+ */
+ after?: string;
+ /**
+ * Only return entries before this ISO 8601 timestamp.
+ */
+ before?: string;
+ /**
+ * Filter logs to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string;
+ /**
+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.
+ * @minLength 1
+ */
+ level?: string;
+ /**
+ * Maximum number of log entries to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Case-insensitive substring search across log messages.
+ * @minLength 1
+ */
+ search?: string;
+ };
+
+ export type AgentApplicationsStatsParams = {
+ /**
+ * ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.
+ */
+ since?: string;
+ };
+
+ export type AgentFleetApprovalsListParams = {
+ /**
+ * Optional agent UUID — narrows the listing to one application.
+ */
+ agent_id?: string;
+ limit?: number;
+ offset?: number;
+ /**
+ * Filter by approval state. Comma-separated list accepted. Valid values: queued, approving, dispatched, dispatched_failed, rejected, expired. Defaults to all states.
+ */
+ state?: string;
+ };
+
+ export type AgentFleetLiveSessionsParams = {
+ /**
+ * Cap on returned sessions (default 100, max 500).
+ */
+ limit?: number;
+ };
+
+ export type AgentFleetStatsParams = {
+ /**
+ * ISO datetime — counts spend + session totals from this point forward. Defaults to 24h ago.
+ */
+ since?: string;
+ };
+
export type AlertsListParams = {
/**
* Optional. Restrict results to alerts created by the user with this UUID.
diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.ts
new file mode 100644
index 000000000000..00277b0168d8
--- /dev/null
+++ b/services/mcp/src/generated/agent_platform/api.ts
@@ -0,0 +1,1990 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 34 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const AgentApplicationsListParams = /* @__PURE__ */ zod.object({
+ 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/."
+ ),
+})
+
+export const AgentApplicationsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const AgentApplicationsCreateParams = /* @__PURE__ */ zod.object({
+ 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/."
+ ),
+})
+
+export const agentApplicationsCreateBodyNameMax = 255
+
+export const agentApplicationsCreateBodySlugMax = 63
+
+export const agentApplicationsCreateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+
+export const AgentApplicationsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(agentApplicationsCreateBodyNameMax),
+ slug: zod
+ .string()
+ .max(agentApplicationsCreateBodySlugMax)
+ .regex(agentApplicationsCreateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).'
+ ),
+ description: zod.string().optional(),
+ archived: zod.boolean().optional(),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsListParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ 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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsCreateParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ 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/."
+ ),
+})
+
+export const agentApplicationsRevisionsCreateBodyBundleUriDefault = ``
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigTimezoneDefault = `UTC`
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigPromptMax = 4096
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigCatchUpDefault = `most_recent`
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault = 3600
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax = 604800
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecTriggersDefault = []
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault = 5000
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsMax = 600000
+
+export const agentApplicationsRevisionsCreateBodySpecToolsItemFourInteractiveDefault = false
+export const agentApplicationsRevisionsCreateBodySpecToolsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault = []
+
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
+
+export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecSecretsDefault = []
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault = 50
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsDefault = 200
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsDefault = 900
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsMax = 2147483647
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensExclusiveMin = 0
+export const agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensMax = 200000
+
+export const agentApplicationsRevisionsCreateBodySpecLimitsDefault = {
+ max_turns: 50,
+ max_tool_calls: 200,
+ max_wall_seconds: 900,
+}
+export const agentApplicationsRevisionsCreateBodySpecEntrypointDefault = `agent.md`
+
+export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
+ parent_revision: zod.uuid().nullish(),
+ bundle_uri: zod.string().default(agentApplicationsRevisionsCreateBodyBundleUriDefault),
+ spec: zod
+ .object({
+ model: zod.string().min(1),
+ triggers: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('slack'),
+ config: zod.object({
+ channel_id: zod.string().optional(),
+ mention_only: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault
+ ),
+ auto_resume_threads: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault
+ ),
+ allow_workspace_participants: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault
+ ),
+ ack_reaction: zod.string().optional(),
+ trusted_workspaces: zod.union([zod.array(zod.string()).min(1), zod.literal('*')]),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('webhook'),
+ config: zod.object({
+ path: zod.string(),
+ }),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('cron'),
+ config: zod.object({
+ name: zod.string().min(1),
+ schedule: zod.string().min(1),
+ timezone: zod
+ .string()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigTimezoneDefault
+ ),
+ prompt: zod
+ .string()
+ .min(1)
+ .max(agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigPromptMax),
+ external_key: zod.string().optional(),
+ catch_up: zod
+ .enum(['all', 'most_recent', 'skip'])
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigCatchUpDefault
+ ),
+ max_catch_up_age_seconds: zod
+ .number()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax
+ )
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault
+ ),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('chat'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersItemFourConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('mcp'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersItemFiveConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsCreateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecTriggersDefault),
+ tools: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('native'),
+ id: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemOneRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom'),
+ id: zod.string(),
+ path: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemTwoRequiresApprovalDefault),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax)
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom_template'),
+ from_template: zod.string(),
+ alias: zod.string(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin)
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('client'),
+ id: zod.string().min(1),
+ description: zod.string().min(1),
+ args_schema: zod
+ .looseObject({})
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault),
+ required: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault),
+ timeout_ms: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault),
+ interactive: zod
+ .boolean()
+ .default(agentApplicationsRevisionsCreateBodySpecToolsItemFourInteractiveDefault),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecToolsDefault),
+ mcps: zod
+ .array(
+ zod.object({
+ id: zod.string().min(1),
+ url: zod.url(),
+ auth: zod
+ .object({
+ integration: zod.string().optional(),
+ })
+ .optional(),
+ secrets: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsCreateBodySpecMcpsItemSecretsDefault),
+ headers: zod.record(zod.string(), zod.string()).optional(),
+ tools: zod
+ .array(
+ zod.union([
+ zod.string().min(1),
+ zod.object({
+ name: zod.string().min(1),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ ])
+ )
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecMcpsDefault),
+ skills: zod
+ .array(
+ zod.object({
+ id: zod.string(),
+ path: zod.string(),
+ description: zod.string().optional(),
+ from_template: zod.string().optional(),
+ alias: zod.string().optional(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin)
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
+ integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
+ secrets: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecSecretsDefault),
+ limits: zod
+ .object({
+ max_turns: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxTurnsDefault),
+ max_tool_calls: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxToolCallsDefault),
+ max_wall_seconds: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsMax)
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsMaxWallSecondsDefault),
+ max_output_tokens: zod
+ .number()
+ .gt(agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensExclusiveMin)
+ .max(agentApplicationsRevisionsCreateBodySpecLimitsMaxOutputTokensMax)
+ .optional(),
+ })
+ .default(agentApplicationsRevisionsCreateBodySpecLimitsDefault),
+ entrypoint: zod.string().default(agentApplicationsRevisionsCreateBodySpecEntrypointDefault),
+ reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),
+ })
+ .optional(),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsRetrieveParams = /* @__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/."
+ ),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsPartialUpdateParams = /* @__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/."
+ ),
+})
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigTimezoneDefault = `UTC`
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigPromptMax = 4096
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigCatchUpDefault = `most_recent`
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault = 3600
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax = 604800
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigDefault = { allow_restart: false }
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsMax = 600000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourInteractiveDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault = []
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault = 86400000
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin = 60000
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault = false
+export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault = []
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault = 50
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsDefault = 200
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsDefault = 900
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsMax = 2147483647
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensExclusiveMin = 0
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensMax = 200000
+
+export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault = {
+ max_turns: 50,
+ max_tool_calls: 200,
+ max_wall_seconds: 900,
+}
+export const agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault = `agent.md`
+
+export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ parent_revision: zod.uuid().nullish(),
+ bundle_uri: zod.string().optional(),
+ spec: zod
+ .object({
+ model: zod.string().min(1),
+ triggers: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('slack'),
+ config: zod.object({
+ channel_id: zod.string().optional(),
+ mention_only: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault
+ ),
+ auto_resume_threads: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault
+ ),
+ allow_workspace_participants: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault
+ ),
+ ack_reaction: zod.string().optional(),
+ trusted_workspaces: zod.union([zod.array(zod.string()).min(1), zod.literal('*')]),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('webhook'),
+ config: zod.object({
+ path: zod.string(),
+ }),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemTwoAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('cron'),
+ config: zod.object({
+ name: zod.string().min(1),
+ schedule: zod.string().min(1),
+ timezone: zod
+ .string()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigTimezoneDefault
+ ),
+ prompt: zod
+ .string()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigPromptMax
+ ),
+ external_key: zod.string().optional(),
+ catch_up: zod
+ .enum(['all', 'most_recent', 'skip'])
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigCatchUpDefault
+ ),
+ max_catch_up_age_seconds: zod
+ .number()
+ .min(1)
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemThreeConfigMaxCatchUpAgeSecondsDefault
+ ),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('chat'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFourAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ zod.object({
+ type: zod.literal('mcp'),
+ config: zod
+ .object({
+ allow_restart: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigAllowRestartDefault
+ ),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveConfigDefault),
+ auth: zod.object({
+ modes: zod
+ .array(
+ zod.union([
+ zod.object({
+ type: zod.literal('public'),
+ acknowledge_public_exposure: zod.boolean(),
+ }),
+ zod.object({
+ type: zod.literal('posthog'),
+ scopes: zod
+ .array(zod.string())
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemFiveAuthModesItemTwoScopesDefault
+ ),
+ }),
+ zod.object({
+ type: zod.literal('jwt'),
+ issuer_secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('shared_secret'),
+ header: zod.string().min(1),
+ secret_ref: zod.string().min(1),
+ }),
+ zod.object({
+ type: zod.literal('posthog_internal'),
+ }),
+ ])
+ )
+ .optional(),
+ }),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecTriggersDefault),
+ tools: zod
+ .array(
+ zod.union([
+ zod.object({
+ kind: zod.literal('native'),
+ id: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemOneApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom'),
+ id: zod.string(),
+ path: zod.string(),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('custom_template'),
+ from_template: zod.string(),
+ alias: zod.string(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin)
+ .optional(),
+ }),
+ zod.object({
+ kind: zod.literal('client'),
+ id: zod.string().min(1),
+ description: zod.string().min(1),
+ args_schema: zod
+ .looseObject({})
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault),
+ required: zod
+ .boolean()
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault),
+ timeout_ms: zod
+ .number()
+ .min(1)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault),
+ interactive: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourInteractiveDefault
+ ),
+ }),
+ ])
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecToolsDefault),
+ mcps: zod
+ .array(
+ zod.object({
+ id: zod.string().min(1),
+ url: zod.url(),
+ auth: zod
+ .object({
+ integration: zod.string().optional(),
+ })
+ .optional(),
+ secrets: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemSecretsDefault),
+ headers: zod.record(zod.string(), zod.string()).optional(),
+ tools: zod
+ .array(
+ zod.union([
+ zod.string().min(1),
+ zod.object({
+ name: zod.string().min(1),
+ requires_approval: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoRequiresApprovalDefault
+ ),
+ approval_policy: zod
+ .object({
+ approvers: zod
+ .array(zod.enum(['team_admins', 'session_principal']))
+ .min(1)
+ .default([`team_admins`]),
+ allow_edit: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowEditDefault
+ ),
+ ttl_ms: zod
+ .number()
+ .min(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMin
+ )
+ .max(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax
+ )
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsDefault
+ ),
+ allow_agent_approver: zod
+ .boolean()
+ .default(
+ agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyAllowAgentApproverDefault
+ ),
+ })
+ .optional(),
+ }),
+ ])
+ )
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault),
+ skills: zod
+ .array(
+ zod.object({
+ id: zod.string(),
+ path: zod.string(),
+ description: zod.string().optional(),
+ from_template: zod.string().optional(),
+ alias: zod.string().optional(),
+ version: zod
+ .number()
+ .min(agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin)
+ .optional(),
+ })
+ )
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),
+ integrations: zod
+ .array(zod.string())
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
+ secrets: zod.array(zod.string()).default(agentApplicationsRevisionsPartialUpdateBodySpecSecretsDefault),
+ limits: zod
+ .object({
+ max_turns: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxTurnsDefault),
+ max_tool_calls: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxToolCallsDefault),
+ max_wall_seconds: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsMax)
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxWallSecondsDefault),
+ max_output_tokens: zod
+ .number()
+ .gt(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensExclusiveMin)
+ .max(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxOutputTokensMax)
+ .optional(),
+ })
+ .default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault),
+ entrypoint: zod.string().default(agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault),
+ reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),
+ })
+ .optional(),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsAgentMdUpdateParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsAgentMdUpdateBody = /* @__PURE__ */ zod
+ .object({
+ content: zod.string(),
+ })
+ .describe('Body shape for PUT /revisions/<id>/agent_md/.')
+
+/**
+ * Mark a revision archived. If it was the live one, clear the
+ * application's live_revision pointer (the app effectively has no
+ * deployable version until another revision is promoted).
+ */
+export const AgentApplicationsRevisionsArchiveCreateParams = /* @__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/."
+ ),
+})
+
+/**
+ * Read the full typed bundle: `{ agent_md, skills, tools, spec }`.
+ */
+export const AgentApplicationsRevisionsBundleRetrieveParams = /* @__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/."
+ ),
+})
+
+/**
+ * Full-replace the typed bundle. Anything not in the payload is
+ * deleted. Tool sources are AST-checked + esbuild-compiled by the
+ * janitor before any S3 writes.
+ */
+export const AgentApplicationsRevisionsBundleUpdateParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod
+ .object({
+ agent_md: zod.string(),
+ skills: zod
+ .array(
+ zod
+ .object({
+ description: zod
+ .string()
+ .describe(
+ 'One-line summary shown in the skill index; the model uses it to decide when to load the skill.'
+ ),
+ body: zod
+ .string()
+ .describe("The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`."),
+ })
+ .describe(
+ 'Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.'
+ )
+ )
+ .optional(),
+ tools: zod
+ .array(
+ zod
+ .object({
+ description: zod.string(),
+ args_schema: zod.record(zod.string(), zod.unknown()),
+ source: zod.string(),
+ })
+ .describe('Body shape for PUT /revisions/<id>/tools/<tool_id>/.')
+ )
+ .optional(),
+ spec: zod.record(zod.string(), zod.unknown()),
+ })
+ .describe(
+ 'Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed\npayload. See docs/agent-platform/plans/typed-bundle-authoring-api.md §3.'
+ )
+
+/**
+ * Copy every file from `source_revision_id` into this revision.
+ */
+export const AgentApplicationsRevisionsCloneFromCreateParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsCloneFromCreateBody = /* @__PURE__ */ zod
+ .object({
+ source_revision_id: zod.string(),
+ })
+ .describe(
+ 'Body shape for POST /revisions/<id>/clone_from/ — copy every file\nfrom `source_revision_id` into this (draft) revision.'
+ )
+
+/**
+ * Fire one cron job out-of-band — the same execution path the
+ * scheduler walks, but on demand. Authoring UX: the user iterates on
+ * a cron prompt by clicking 'Fire now' rather than waiting for the
+ * next scheduled firing. Without this, 'did my prompt do the right
+ * thing?' is unanswerable until the cron actually fires.
+ *
+ * Idempotent via `request_id`: repeat clicks with the same id resolve
+ * to the same session id rather than firing N times. See
+ * `docs/agent-platform/plans/cron-trigger-scheduler.md` §9.
+ */
+export const AgentApplicationsRevisionsCronFireCreateParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsCronFireCreateBody = /* @__PURE__ */ zod.object({
+ cron_name: zod.string().describe('`name` of the cron trigger in `spec.triggers[]` to fire.'),
+ request_id: zod
+ .string()
+ .nullish()
+ .describe(
+ "Stable client-supplied id so repeated clicks of the same UI 'Fire now' button resolve to the same session id rather than firing twice. The janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit to fire unconditionally — every call generates a fresh UUID."
+ ),
+})
+
+/**
+ * Freeze the bundle: draft → ready, stamps sha256 on the row.
+ *
+ * Django is a thin proxy here: resolve template refs into the
+ * bundle, ask the janitor to seal it (the janitor returns the sha
+ * + the spec it derived from the typed resources), then stamp the
+ * row. No `transaction.atomic()` — the janitor's freeze is idempotent
+ * (on retry it re-reads the existing `.frozen` marker + re-derives
+ * spec), so a partial failure here is recoverable by re-calling
+ * freeze, not by transactional rollback. Holding an atomic block
+ * across the janitor HTTP call previously deadlocked the
+ * agent_revision row against the janitor's spec write — that's
+ * moved off the janitor side as part of the same fix.
+ */
+export const AgentApplicationsRevisionsFreezeCreateParams = /* @__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/."
+ ),
+})
+
+/**
+ * List every file in this revision's bundle (path, size, sha256).
+ */
+export const AgentApplicationsRevisionsManifestRetrieveParams = /* @__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/."
+ ),
+})
+
+/**
+ * ready → live. Sets the parent application's live_revision.
+ */
+export const AgentApplicationsRevisionsPromoteCreateParams = /* @__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/."
+ ),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsSkillsUpdatePathSkillIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')
+
+export const AgentApplicationsRevisionsSkillsUpdateParams = /* @__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/."
+ ),
+ skill_id: zod.string().regex(agentApplicationsRevisionsSkillsUpdatePathSkillIdRegExp),
+})
+
+export const AgentApplicationsRevisionsSkillsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ description: zod
+ .string()
+ .describe('One-line summary shown in the skill index; the model uses it to decide when to load the skill.'),
+ body: zod.string().describe("The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`."),
+ })
+ .describe(
+ 'Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.'
+ )
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsSkillsDestroyPathSkillIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')
+
+export const AgentApplicationsRevisionsSkillsDestroyParams = /* @__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/."
+ ),
+ skill_id: zod.string().regex(agentApplicationsRevisionsSkillsDestroyPathSkillIdRegExp),
+})
+
+/**
+ * Build a Slack app manifest for this revision's slack trigger.
+ *
+ * Deterministic: the OAuth scopes and bot event subscriptions are derived
+ * from the slack trigger config (`mention_only` / `auto_resume_threads` /
+ * `ack_reaction`) and the agent's Slack tools, so the manifest already
+ * subscribes to exactly the events the config needs. 400 if the revision
+ * has no slack trigger.
+ */
+export const AgentApplicationsRevisionsSlackManifestParams = /* @__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/."
+ ),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const AgentApplicationsRevisionsSpecUpdateParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsSpecUpdateBody = /* @__PURE__ */ zod
+ .object({
+ spec: zod.record(zod.string(), zod.unknown()),
+ })
+ .describe(
+ "Body shape for PUT /revisions/<id>/spec/. The body's `spec` object\nis the author-facing slice (skills/tools are server-derived at freeze)."
+ )
+
+/**
+ * Return the fully-assembled system prompt for this revision.
+ *
+ * Authoring tools call this to preview what the model will actually
+ * see at session start — the platform framework preamble plus the
+ * bundle's `agent.md` plus the skills index. Useful for debugging
+ * author-vs-framework precedence conflicts and verifying
+ * `spec.framework_prompt.omit` overrides took effect.
+ */
+export const AgentApplicationsRevisionsSystemPromptParams = /* @__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/."
+ ),
+})
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsToolsUpdatePathToolIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')
+
+export const AgentApplicationsRevisionsToolsUpdateParams = /* @__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/."
+ ),
+ tool_id: zod.string().regex(agentApplicationsRevisionsToolsUpdatePathToolIdRegExp),
+})
+
+export const AgentApplicationsRevisionsToolsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ description: zod.string(),
+ args_schema: zod.record(zod.string(), zod.unknown()),
+ source: zod.string(),
+ })
+ .describe('Body shape for PUT /revisions/<id>/tools/<tool_id>/.')
+
+/**
+ * Revisions of an agent. Created in `draft`, promoted through
+ * `ready → live` once the bundle has been uploaded + frozen.
+ *
+ * URLs (nested under an application):
+ *
+ * Model CRUD:
+ * GET .../revisions/ list
+ * POST .../revisions/ create draft
+ * GET .../revisions/<id>/ retrieve
+ * PATCH .../revisions/<id>/ update spec (draft only)
+ *
+ * Lifecycle:
+ * POST .../revisions/<id>/promote/ ready → live
+ * POST .../revisions/<id>/archive/ → archived
+ * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)
+ * POST .../revisions/<id>/clone_from/ copy bundle from another rev
+ * POST .../revisions/new_draft/ create draft + clone_from atomically
+ *
+ * Bundle authoring (proxied to the janitor):
+ * GET .../revisions/<id>/manifest/ list paths + sha256
+ * GET .../revisions/<id>/file/?path=… read one file
+ * PUT .../revisions/<id>/file/?path=… write one file (draft)
+ * DELETE .../revisions/<id>/file/?path=… delete one file (draft)
+ * GET .../revisions/<id>/bundle/ bulk pull all files
+ * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)
+ */
+export const agentApplicationsRevisionsToolsDestroyPathToolIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')
+
+export const AgentApplicationsRevisionsToolsDestroyParams = /* @__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/."
+ ),
+ tool_id: zod.string().regex(agentApplicationsRevisionsToolsDestroyPathToolIdRegExp),
+})
+
+/**
+ * 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
+ * `{ ok, errors: [...] }`. Works on any revision state.
+ */
+export const AgentApplicationsRevisionsValidateCreateParams = /* @__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/."
+ ),
+})
+
+/**
+ * Create a fresh draft revision under `application_id` and seed it
+ * from `source_revision_id`. Saves the MCP one round-trip vs the
+ * explicit create + clone_from sequence.
+ */
+export const AgentApplicationsRevisionsNewDraftCreateParams = /* @__PURE__ */ zod.object({
+ application_id: zod.string(),
+ 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/."
+ ),
+})
+
+export const AgentApplicationsRevisionsNewDraftCreateBody = /* @__PURE__ */ zod
+ .object({
+ application_id: zod.string(),
+ source_revision_id: zod.string(),
+ })
+ .describe(
+ 'Body shape for POST /revisions/clone_from/ — atomically create a new\ndraft revision under `application_id` and clone its initial bundle from\n`source_revision_id`. Convenience for the "edit live" flow so the MCP\ndoesn\'t have to do create-then-clone-from in two calls.'
+ )
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const AgentApplicationsRetrieveParams = /* @__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/."
+ ),
+})
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const AgentApplicationsPartialUpdateParams = /* @__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/."
+ ),
+})
+
+export const agentApplicationsPartialUpdateBodyNameMax = 255
+
+export const agentApplicationsPartialUpdateBodySlugMax = 63
+
+export const agentApplicationsPartialUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+
+export const AgentApplicationsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(agentApplicationsPartialUpdateBodyNameMax).optional(),
+ slug: zod
+ .string()
+ .max(agentApplicationsPartialUpdateBodySlugMax)
+ .regex(agentApplicationsPartialUpdateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).'
+ ),
+ description: zod.string().optional(),
+ archived: zod.boolean().optional(),
+})
+
+/**
+ * Agent applications — the deployable unit of the platform.
+ *
+ * URLs:
+ * GET /api/projects/<team>/agent_applications/ list
+ * POST /api/projects/<team>/agent_applications/ create
+ * GET /api/projects/<team>/agent_applications/<id|slug>/ retrieve
+ * PATCH /api/projects/<team>/agent_applications/<id|slug>/ update
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/ archive
+ * POST /api/projects/<team>/agent_applications/<id|slug>/set_env/ bulk replace env
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/ list set keys
+ * GET /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ is one key set?
+ * PUT /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ set one key
+ * DELETE /api/projects/<team>/agent_applications/<id|slug>/env_keys/<KEY>/ clear one key
+ */
+export const AgentApplicationsDestroyParams = /* @__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/."
+ ),
+})
+
+/**
+ * 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.
+ *
+ * Closes the anonymous-draft-invoke gap: the public ingress URL refuses
+ * non-live invokes that don't carry the `x-agent-preview-secret` header;
+ * this proxy attaches it after authenticating the Django caller. See
+ * docs/agent-platform/plans/draft-preview-auth.md.
+ *
+ * URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`
+ * Auth: standard PAT / session — `agents:read` scope.
+ */
+export const AgentApplicationsPreviewProxyParams = /* @__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/."
+ ),
+ rest: zod.string().describe('Ingress sub-path under the agent slug. One of: `run`, `send`, `cancel`, `listen`.'),
+})
+
+export const AgentApplicationsPreviewProxyQueryParams = /* @__PURE__ */ zod.object({
+ format: zod.enum(['json', 'sse']).optional(),
+ revision_id: zod.string().describe('Target draft revision. Must belong to this application and not be live.'),
+})
+
+/**
+ * List sessions for this application, newest first. Strips the
+ * conversation transcript from each summary, but includes a `preview`
+ * (last assistant text, ~120 chars) and `usage_total` (token + cost
+ * aggregate). Use `agent-applications-sessions-retrieve` for the full
+ * transcript of a single session.
+ */
+export const AgentApplicationsSessionsListParams = /* @__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/."
+ ),
+})
+
+export const AgentApplicationsSessionsListQueryParams = /* @__PURE__ */ zod.object({
+ created_after: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('ISO datetime — return sessions with created_at >= this.'),
+ created_before: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('ISO datetime — return sessions with created_at <= this.'),
+ limit: zod.number().optional(),
+ offset: zod.number().optional(),
+ revision_id: zod.string().optional().describe('Only return sessions started against this specific revision.'),
+ state: zod
+ .string()
+ .optional()
+ .describe(
+ 'Filter by session state. Comma-separated list accepted (e.g. `completed,failed`). Valid values: queued, running, completed, closed, cancelled, failed.'
+ ),
+})
+
+/**
+ * Fetch one session's state — full conversation by default, or just
+ * the trailing N messages with `?last_n=`. Always returns a
+ * `usage_total` block aggregated over the entire session, regardless of
+ * trim. The runner-side queue DB is the source of truth.
+ */
+export const AgentApplicationsSessionsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this agent application.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ session_id: zod.string().describe('UUID of the session to fetch (must belong to this application).'),
+})
+
+export const AgentApplicationsSessionsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ last_n: zod
+ .number()
+ .optional()
+ .describe(
+ 'If set, return only the most recent N messages from the conversation. `usage_total` is still computed over the full session — only the transcript is trimmed. The response includes `conversation_trimmed: true` and `conversation_total_turns` so the caller knows how much was hidden.'
+ ),
+})
+
+/**
+ * Read-only catalog of every @posthog/* native tool the runner knows.
+ */
+export const AgentNativeToolsListParams = /* @__PURE__ */ zod.object({
+ 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/."
+ ),
+})
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index da0358b9dc9f..516b54e61fc6 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -19,6 +19,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'account:write',
'activity_log:read',
'activity_log:write',
+ 'agents:read',
+ 'agents:write',
'alert:read',
'alert:write',
'annotation:read',
diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.ts
new file mode 100644
index 000000000000..63c9a2a5a689
--- /dev/null
+++ b/services/mcp/src/tools/generated/agent_platform.ts
@@ -0,0 +1,879 @@
+// AUTO-GENERATED from services/mcp/definitions/agent_platform.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ AgentApplicationsCreateBody,
+ AgentApplicationsDestroyParams,
+ AgentApplicationsEnvKeysClearParams,
+ AgentApplicationsEnvKeysGetParams,
+ AgentApplicationsEnvKeysListParams,
+ AgentApplicationsListQueryParams,
+ AgentApplicationsPartialUpdateBody,
+ AgentApplicationsPartialUpdateParams,
+ AgentApplicationsPreviewProxyParams,
+ AgentApplicationsPreviewProxyQueryParams,
+ AgentApplicationsRetrieveParams,
+ AgentApplicationsRevisionsAgentMdUpdateBody,
+ AgentApplicationsRevisionsAgentMdUpdateParams,
+ AgentApplicationsRevisionsArchiveCreateParams,
+ AgentApplicationsRevisionsBundleRetrieveParams,
+ AgentApplicationsRevisionsBundleUpdateBody,
+ AgentApplicationsRevisionsBundleUpdateParams,
+ AgentApplicationsRevisionsCloneFromCreateBody,
+ AgentApplicationsRevisionsCloneFromCreateParams,
+ AgentApplicationsRevisionsCreateBody,
+ AgentApplicationsRevisionsCreateParams,
+ AgentApplicationsRevisionsCronFireCreateBody,
+ AgentApplicationsRevisionsCronFireCreateParams,
+ AgentApplicationsRevisionsFreezeCreateParams,
+ AgentApplicationsRevisionsListParams,
+ AgentApplicationsRevisionsListQueryParams,
+ AgentApplicationsRevisionsManifestRetrieveParams,
+ AgentApplicationsRevisionsNewDraftCreateBody,
+ AgentApplicationsRevisionsNewDraftCreateParams,
+ AgentApplicationsRevisionsPartialUpdateBody,
+ AgentApplicationsRevisionsPartialUpdateParams,
+ AgentApplicationsRevisionsPromoteCreateParams,
+ AgentApplicationsRevisionsRetrieveParams,
+ AgentApplicationsRevisionsSkillsDestroyParams,
+ AgentApplicationsRevisionsSkillsUpdateBody,
+ AgentApplicationsRevisionsSkillsUpdateParams,
+ AgentApplicationsRevisionsSlackManifestParams,
+ AgentApplicationsRevisionsSpecUpdateBody,
+ AgentApplicationsRevisionsSpecUpdateParams,
+ AgentApplicationsRevisionsSystemPromptParams,
+ AgentApplicationsRevisionsToolsDestroyParams,
+ AgentApplicationsRevisionsToolsUpdateBody,
+ AgentApplicationsRevisionsToolsUpdateParams,
+ AgentApplicationsRevisionsValidateCreateParams,
+ AgentApplicationsSessionsListParams,
+ AgentApplicationsSessionsListQueryParams,
+ AgentApplicationsSessionsRetrieveParams,
+ AgentApplicationsSessionsRetrieveQueryParams,
+} from '@/generated/agent_platform/api'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const AgentApplicationsCreateSchema = AgentApplicationsCreateBody
+
+const agentApplicationsCreate = (): ToolBase<typeof AgentApplicationsCreateSchema, Schemas.AgentApplication> => ({
+ name: 'agent-applications-create',
+ schema: AgentApplicationsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.slug !== undefined) {
+ body['slug'] = params.slug
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.archived !== undefined) {
+ body['archived'] = params.archived
+ }
+ const result = await context.api.request<Schemas.AgentApplication>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsDestroySchema = AgentApplicationsDestroyParams.omit({ project_id: true })
+
+const agentApplicationsDestroy = (): ToolBase<typeof AgentApplicationsDestroySchema, unknown> => ({
+ name: 'agent-applications-destroy',
+ schema: AgentApplicationsDestroySchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsDestroySchema>) => {
+ 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))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsEnvKeysClearSchema = AgentApplicationsEnvKeysClearParams.omit({ project_id: true })
+
+const agentApplicationsEnvKeysClear = (): ToolBase<typeof AgentApplicationsEnvKeysClearSchema, unknown> => ({
+ name: 'agent-applications-env-keys-clear',
+ schema: AgentApplicationsEnvKeysClearSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsEnvKeysClearSchema>) => {
+ 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))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsEnvKeysGetSchema = AgentApplicationsEnvKeysGetParams.omit({ project_id: true })
+
+const agentApplicationsEnvKeysGet = (): ToolBase<
+ typeof AgentApplicationsEnvKeysGetSchema,
+ Schemas.AgentApplicationEnvKeyStatus
+> => ({
+ 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>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/env_keys/${encodeURIComponent(String(params.key))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsEnvKeysListSchema = AgentApplicationsEnvKeysListParams.omit({ project_id: true })
+
+const agentApplicationsEnvKeysList = (): ToolBase<
+ typeof AgentApplicationsEnvKeysListSchema,
+ Schemas.AgentApplicationEnvKeysResponse
+> => ({
+ 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>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/env_keys/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsListSchema = AgentApplicationsListQueryParams
+
+const agentApplicationsList = (): ToolBase<
+ typeof AgentApplicationsListSchema,
+ Schemas.PaginatedAgentApplicationList
+> => ({
+ name: 'agent-applications-list',
+ schema: AgentApplicationsListSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedAgentApplicationList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return result
+ },
+})
+
+const AgentApplicationsPartialUpdateSchema = AgentApplicationsPartialUpdateParams.omit({ project_id: true }).extend(
+ AgentApplicationsPartialUpdateBody.shape
+)
+
+const agentApplicationsPartialUpdate = (): ToolBase<
+ typeof AgentApplicationsPartialUpdateSchema,
+ Schemas.AgentApplication
+> => ({
+ name: 'agent-applications-partial-update',
+ schema: AgentApplicationsPartialUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsPartialUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.slug !== undefined) {
+ body['slug'] = params.slug
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.archived !== undefined) {
+ body['archived'] = params.archived
+ }
+ const result = await context.api.request<Schemas.AgentApplication>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsPreviewProxySchema = AgentApplicationsPreviewProxyParams.omit({ project_id: true }).extend(
+ AgentApplicationsPreviewProxyQueryParams.omit({ format: true }).shape
+)
+
+const agentApplicationsPreviewProxy = (): ToolBase<
+ typeof AgentApplicationsPreviewProxySchema,
+ Schemas.AgentApplication
+> => ({
+ name: 'agent-applications-preview-proxy',
+ schema: AgentApplicationsPreviewProxySchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsPreviewProxySchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentApplication>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/preview-proxy/${encodeURIComponent(String(params.rest))}/`,
+ query: {
+ revision_id: params.revision_id,
+ },
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRetrieveSchema = AgentApplicationsRetrieveParams.omit({ project_id: true })
+
+const agentApplicationsRetrieve = (): ToolBase<typeof AgentApplicationsRetrieveSchema, Schemas.AgentApplication> => ({
+ name: 'agent-applications-retrieve',
+ schema: AgentApplicationsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentApplication>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsAgentMdUpdateSchema = AgentApplicationsRevisionsAgentMdUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsAgentMdUpdateBody.shape)
+
+const agentApplicationsRevisionsAgentMdUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsAgentMdUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-agent-md-update',
+ schema: AgentApplicationsRevisionsAgentMdUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsAgentMdUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/agent_md/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsArchiveCreateSchema = AgentApplicationsRevisionsArchiveCreateParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsArchiveCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsArchiveCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-archive-create',
+ schema: AgentApplicationsRevisionsArchiveCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsArchiveCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/archive/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsBundleRetrieveSchema = AgentApplicationsRevisionsBundleRetrieveParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsBundleRetrieve = (): ToolBase<
+ typeof AgentApplicationsRevisionsBundleRetrieveSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-bundle-retrieve',
+ schema: AgentApplicationsRevisionsBundleRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsBundleRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/bundle/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsBundleUpdateSchema = AgentApplicationsRevisionsBundleUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsBundleUpdateBody.shape)
+
+const agentApplicationsRevisionsBundleUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsBundleUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-bundle-update',
+ schema: AgentApplicationsRevisionsBundleUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsBundleUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.agent_md !== undefined) {
+ body['agent_md'] = params.agent_md
+ }
+ if (params.skills !== undefined) {
+ body['skills'] = params.skills
+ }
+ if (params.tools !== undefined) {
+ body['tools'] = params.tools
+ }
+ if (params.spec !== undefined) {
+ body['spec'] = params.spec
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/bundle/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsCloneFromCreateSchema = AgentApplicationsRevisionsCloneFromCreateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsCloneFromCreateBody.shape)
+
+const agentApplicationsRevisionsCloneFromCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsCloneFromCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-clone-from-create',
+ schema: AgentApplicationsRevisionsCloneFromCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsCloneFromCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.source_revision_id !== undefined) {
+ body['source_revision_id'] = params.source_revision_id
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/clone_from/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsCreateSchema = AgentApplicationsRevisionsCreateParams.omit({ project_id: true }).extend(
+ AgentApplicationsRevisionsCreateBody.shape
+)
+
+const agentApplicationsRevisionsCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-create',
+ schema: AgentApplicationsRevisionsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.parent_revision !== undefined) {
+ body['parent_revision'] = params.parent_revision
+ }
+ if (params.bundle_uri !== undefined) {
+ body['bundle_uri'] = params.bundle_uri
+ }
+ if (params.spec !== undefined) {
+ body['spec'] = params.spec
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsCronFireCreateSchema = AgentApplicationsRevisionsCronFireCreateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsCronFireCreateBody.shape)
+
+const agentApplicationsRevisionsCronFireCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsCronFireCreateSchema,
+ Schemas.AgentRevisionCronFireResponse
+> => ({
+ name: 'agent-applications-revisions-cron-fire-create',
+ schema: AgentApplicationsRevisionsCronFireCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsCronFireCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.cron_name !== undefined) {
+ body['cron_name'] = params.cron_name
+ }
+ if (params.request_id !== undefined) {
+ body['request_id'] = params.request_id
+ }
+ const result = await context.api.request<Schemas.AgentRevisionCronFireResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/cron/fire/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsFreezeCreateSchema = AgentApplicationsRevisionsFreezeCreateParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsFreezeCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsFreezeCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-freeze-create',
+ schema: AgentApplicationsRevisionsFreezeCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsFreezeCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/freeze/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsListSchema = AgentApplicationsRevisionsListParams.omit({ project_id: true }).extend(
+ AgentApplicationsRevisionsListQueryParams.shape
+)
+
+const agentApplicationsRevisionsList = (): ToolBase<
+ typeof AgentApplicationsRevisionsListSchema,
+ Schemas.PaginatedAgentRevisionList
+> => ({
+ name: 'agent-applications-revisions-list',
+ schema: AgentApplicationsRevisionsListSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedAgentRevisionList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsManifestRetrieveSchema = AgentApplicationsRevisionsManifestRetrieveParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsManifestRetrieve = (): ToolBase<
+ typeof AgentApplicationsRevisionsManifestRetrieveSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-manifest-retrieve',
+ schema: AgentApplicationsRevisionsManifestRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsManifestRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/manifest/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsNewDraftCreateSchema = AgentApplicationsRevisionsNewDraftCreateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsNewDraftCreateBody.shape)
+
+const agentApplicationsRevisionsNewDraftCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsNewDraftCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-new-draft-create',
+ schema: AgentApplicationsRevisionsNewDraftCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsNewDraftCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.application_id !== undefined) {
+ body['application_id'] = params.application_id
+ }
+ if (params.source_revision_id !== undefined) {
+ body['source_revision_id'] = params.source_revision_id
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/new_draft/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsPartialUpdateSchema = AgentApplicationsRevisionsPartialUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsPartialUpdateBody.shape)
+
+const agentApplicationsRevisionsPartialUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsPartialUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-partial-update',
+ schema: AgentApplicationsRevisionsPartialUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsPartialUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.parent_revision !== undefined) {
+ body['parent_revision'] = params.parent_revision
+ }
+ if (params.bundle_uri !== undefined) {
+ body['bundle_uri'] = params.bundle_uri
+ }
+ if (params.spec !== undefined) {
+ body['spec'] = params.spec
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsPromoteCreateSchema = AgentApplicationsRevisionsPromoteCreateParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsPromoteCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsPromoteCreateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-promote-create',
+ schema: AgentApplicationsRevisionsPromoteCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsPromoteCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/promote/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsRetrieveSchema = AgentApplicationsRevisionsRetrieveParams.omit({ project_id: true })
+
+const agentApplicationsRevisionsRetrieve = (): ToolBase<
+ typeof AgentApplicationsRevisionsRetrieveSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-retrieve',
+ schema: AgentApplicationsRevisionsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsSkillsDestroySchema = AgentApplicationsRevisionsSkillsDestroyParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsSkillsDestroy = (): ToolBase<
+ typeof AgentApplicationsRevisionsSkillsDestroySchema,
+ unknown
+> => ({
+ name: 'agent-applications-revisions-skills-destroy',
+ schema: AgentApplicationsRevisionsSkillsDestroySchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSkillsDestroySchema>) => {
+ 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.application_id))}/revisions/${encodeURIComponent(String(params.id))}/skills/${encodeURIComponent(String(params.skill_id))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsSkillsUpdateSchema = AgentApplicationsRevisionsSkillsUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsSkillsUpdateBody.shape)
+
+const agentApplicationsRevisionsSkillsUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsSkillsUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-skills-update',
+ schema: AgentApplicationsRevisionsSkillsUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSkillsUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.body !== undefined) {
+ body['body'] = params.body
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/skills/${encodeURIComponent(String(params.skill_id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsSlackManifestSchema = AgentApplicationsRevisionsSlackManifestParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsSlackManifest = (): ToolBase<
+ typeof AgentApplicationsRevisionsSlackManifestSchema,
+ Schemas.AgentRevisionSlackManifestResponse
+> => ({
+ name: 'agent-applications-revisions-slack-manifest',
+ schema: AgentApplicationsRevisionsSlackManifestSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSlackManifestSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevisionSlackManifestResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/slack_manifest/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsSpecUpdateSchema = AgentApplicationsRevisionsSpecUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsSpecUpdateBody.shape)
+
+const agentApplicationsRevisionsSpecUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsSpecUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-spec-update',
+ schema: AgentApplicationsRevisionsSpecUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSpecUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.spec !== undefined) {
+ body['spec'] = params.spec
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/spec/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsSystemPromptSchema = AgentApplicationsRevisionsSystemPromptParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsSystemPrompt = (): ToolBase<
+ typeof AgentApplicationsRevisionsSystemPromptSchema,
+ Schemas.AgentRevisionSystemPromptResponse
+> => ({
+ name: 'agent-applications-revisions-system-prompt',
+ schema: AgentApplicationsRevisionsSystemPromptSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSystemPromptSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevisionSystemPromptResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/system_prompt/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsToolsDestroySchema = AgentApplicationsRevisionsToolsDestroyParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsToolsDestroy = (): ToolBase<
+ typeof AgentApplicationsRevisionsToolsDestroySchema,
+ unknown
+> => ({
+ name: 'agent-applications-revisions-tools-destroy',
+ schema: AgentApplicationsRevisionsToolsDestroySchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsToolsDestroySchema>) => {
+ 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.application_id))}/revisions/${encodeURIComponent(String(params.id))}/tools/${encodeURIComponent(String(params.tool_id))}/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsToolsUpdateSchema = AgentApplicationsRevisionsToolsUpdateParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsRevisionsToolsUpdateBody.shape)
+
+const agentApplicationsRevisionsToolsUpdate = (): ToolBase<
+ typeof AgentApplicationsRevisionsToolsUpdateSchema,
+ Schemas.AgentRevision
+> => ({
+ name: 'agent-applications-revisions-tools-update',
+ schema: AgentApplicationsRevisionsToolsUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsToolsUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.args_schema !== undefined) {
+ body['args_schema'] = params.args_schema
+ }
+ if (params.source !== undefined) {
+ body['source'] = params.source
+ }
+ const result = await context.api.request<Schemas.AgentRevision>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/tools/${encodeURIComponent(String(params.tool_id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsRevisionsValidateCreateSchema = AgentApplicationsRevisionsValidateCreateParams.omit({
+ project_id: true,
+})
+
+const agentApplicationsRevisionsValidateCreate = (): ToolBase<
+ typeof AgentApplicationsRevisionsValidateCreateSchema,
+ Schemas.AgentRevisionValidateResponse
+> => ({
+ name: 'agent-applications-revisions-validate-create',
+ schema: AgentApplicationsRevisionsValidateCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsValidateCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentRevisionValidateResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/validate/`,
+ })
+ return result
+ },
+})
+
+const AgentApplicationsSessionsListSchema = AgentApplicationsSessionsListParams.omit({ project_id: true }).extend(
+ AgentApplicationsSessionsListQueryParams.shape
+)
+
+const agentApplicationsSessionsList = (): ToolBase<
+ typeof AgentApplicationsSessionsListSchema,
+ Schemas.AgentApplicationSessionsListResponse
+> => ({
+ name: 'agent-applications-sessions-list',
+ schema: AgentApplicationsSessionsListSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsSessionsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentApplicationSessionsListResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/sessions/`,
+ query: {
+ created_after: params.created_after,
+ created_before: params.created_before,
+ limit: params.limit,
+ offset: params.offset,
+ revision_id: params.revision_id,
+ state: params.state,
+ },
+ })
+ return result
+ },
+})
+
+const AgentApplicationsSessionsRetrieveSchema = AgentApplicationsSessionsRetrieveParams.omit({
+ project_id: true,
+}).extend(AgentApplicationsSessionsRetrieveQueryParams.shape)
+
+const agentApplicationsSessionsRetrieve = (): ToolBase<
+ typeof AgentApplicationsSessionsRetrieveSchema,
+ Schemas.AgentApplicationSessionsRetrieveResponse
+> => ({
+ name: 'agent-applications-sessions-retrieve',
+ schema: AgentApplicationsSessionsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsSessionsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentApplicationSessionsRetrieveResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/sessions/${encodeURIComponent(String(params.session_id))}/`,
+ query: {
+ last_n: params.last_n,
+ },
+ })
+ return result
+ },
+})
+
+const AgentNativeToolsListSchema = z.object({})
+
+const agentNativeToolsList = (): ToolBase<
+ typeof AgentNativeToolsListSchema,
+ Schemas.AgentNativeToolsListResponse[]
+> => ({
+ name: 'agent-native-tools-list',
+ schema: AgentNativeToolsListSchema,
+ // eslint-disable-next-line no-unused-vars
+ handler: async (context: Context, params: z.infer<typeof AgentNativeToolsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentNativeToolsListResponse[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_native_tools/`,
+ })
+ return result
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'agent-applications-create': agentApplicationsCreate,
+ 'agent-applications-destroy': agentApplicationsDestroy,
+ 'agent-applications-env-keys-clear': agentApplicationsEnvKeysClear,
+ 'agent-applications-env-keys-get': agentApplicationsEnvKeysGet,
+ 'agent-applications-env-keys-list': agentApplicationsEnvKeysList,
+ 'agent-applications-list': agentApplicationsList,
+ 'agent-applications-partial-update': agentApplicationsPartialUpdate,
+ 'agent-applications-preview-proxy': agentApplicationsPreviewProxy,
+ 'agent-applications-retrieve': agentApplicationsRetrieve,
+ 'agent-applications-revisions-agent-md-update': agentApplicationsRevisionsAgentMdUpdate,
+ 'agent-applications-revisions-archive-create': agentApplicationsRevisionsArchiveCreate,
+ 'agent-applications-revisions-bundle-retrieve': agentApplicationsRevisionsBundleRetrieve,
+ 'agent-applications-revisions-bundle-update': agentApplicationsRevisionsBundleUpdate,
+ 'agent-applications-revisions-clone-from-create': agentApplicationsRevisionsCloneFromCreate,
+ 'agent-applications-revisions-create': agentApplicationsRevisionsCreate,
+ 'agent-applications-revisions-cron-fire-create': agentApplicationsRevisionsCronFireCreate,
+ 'agent-applications-revisions-freeze-create': agentApplicationsRevisionsFreezeCreate,
+ 'agent-applications-revisions-list': agentApplicationsRevisionsList,
+ 'agent-applications-revisions-manifest-retrieve': agentApplicationsRevisionsManifestRetrieve,
+ 'agent-applications-revisions-new-draft-create': agentApplicationsRevisionsNewDraftCreate,
+ 'agent-applications-revisions-partial-update': agentApplicationsRevisionsPartialUpdate,
+ 'agent-applications-revisions-promote-create': agentApplicationsRevisionsPromoteCreate,
+ 'agent-applications-revisions-retrieve': agentApplicationsRevisionsRetrieve,
+ 'agent-applications-revisions-skills-destroy': agentApplicationsRevisionsSkillsDestroy,
+ 'agent-applications-revisions-skills-update': agentApplicationsRevisionsSkillsUpdate,
+ 'agent-applications-revisions-slack-manifest': agentApplicationsRevisionsSlackManifest,
+ 'agent-applications-revisions-spec-update': agentApplicationsRevisionsSpecUpdate,
+ 'agent-applications-revisions-system-prompt': agentApplicationsRevisionsSystemPrompt,
+ 'agent-applications-revisions-tools-destroy': agentApplicationsRevisionsToolsDestroy,
+ 'agent-applications-revisions-tools-update': agentApplicationsRevisionsToolsUpdate,
+ 'agent-applications-revisions-validate-create': agentApplicationsRevisionsValidateCreate,
+ 'agent-applications-sessions-list': agentApplicationsSessionsList,
+ 'agent-applications-sessions-retrieve': agentApplicationsSessionsRetrieve,
+ 'agent-native-tools-list': agentNativeToolsList,
+}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 1215e88ada98..ceabbe93486a 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -2,6 +2,7 @@
import type { ToolBase, ZodObjectAny } from '@/tools/types'
import { GENERATED_TOOLS as actions } from './actions'
+import { GENERATED_TOOLS as agent_platform } from './agent_platform'
import { GENERATED_TOOLS as ai_observability } from './ai_observability'
import { GENERATED_TOOLS as alerts } from './alerts'
import { GENERATED_TOOLS as annotations } from './annotations'
@@ -49,6 +50,7 @@ import { GENERATED_TOOLS as workflows } from './workflows'
export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
...actions,
+ ...agent_platform,
...ai_observability,
...alerts,
...annotations,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-create.json
new file mode 100644
index 000000000000..2071116c8edf
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-create.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "archived": {
+ "type": "boolean"
+ },
+ "description": {
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 255,
+ "type": "string"
+ },
+ "slug": {
+ "description": "Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).",
+ "maxLength": 63,
+ "pattern": "^[-a-zA-Z0-9_]+$",
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-destroy.json
new file mode 100644
index 000000000000..fc56ff7565a4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-destroy.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
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
new file mode 100644
index 000000000000..c9d7b369bbb2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-clear.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "key": {
+ "description": "The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.",
+ "type": "string"
+ }
+ },
+ "required": ["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
new file mode 100644
index 000000000000..c9d7b369bbb2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-get.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "key": {
+ "description": "The env variable name. Conventionally UPPER_SNAKE_CASE; the API does not enforce a shape.",
+ "type": "string"
+ }
+ },
+ "required": ["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
new file mode 100644
index 000000000000..fc56ff7565a4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-env-keys-list.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-list.json
new file mode 100644
index 000000000000..8331b796ac73
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-list.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-partial-update.json
new file mode 100644
index 000000000000..e85618300f3b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-partial-update.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "archived": {
+ "type": "boolean"
+ },
+ "description": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 255,
+ "type": "string"
+ },
+ "slug": {
+ "description": "Globally-unique URL identifier. Server-minted as an opaque random slug on create; only allowlisted first-party teams may set it explicitly. Slugs live in one global namespace (domain-mode ingress routing carries no team).",
+ "maxLength": 63,
+ "pattern": "^[-a-zA-Z0-9_]+$",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json
new file mode 100644
index 000000000000..820a155be082
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "rest": {
+ "description": "Ingress sub-path under the agent slug. One of: `run`, `send`, `cancel`, `listen`.",
+ "type": "string"
+ },
+ "revision_id": {
+ "description": "Target draft revision. Must belong to this application and not be live.",
+ "type": "string"
+ }
+ },
+ "required": ["id", "rest", "revision_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-retrieve.json
new file mode 100644
index 000000000000..fc56ff7565a4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-retrieve.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-agent-md-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-agent-md-update.json
new file mode 100644
index 000000000000..e0be5573122b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-agent-md-update.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "content": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "content"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-archive-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-archive-create.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-archive-create.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-retrieve.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-retrieve.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json
new file mode 100644
index 000000000000..6fa5eaeeef42
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json
@@ -0,0 +1,65 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "agent_md": {
+ "type": "string"
+ },
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "skills": {
+ "items": {
+ "description": "Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.",
+ "properties": {
+ "body": {
+ "description": "The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",
+ "type": "string"
+ },
+ "description": {
+ "description": "One-line summary shown in the skill index; the model uses it to decide when to load the skill.",
+ "type": "string"
+ }
+ },
+ "required": ["description", "body"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "spec": {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "tools": {
+ "items": {
+ "description": "Body shape for PUT /revisions/<id>/tools/<tool_id>/.",
+ "properties": {
+ "args_schema": {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "description": {
+ "type": "string"
+ },
+ "source": {
+ "type": "string"
+ }
+ },
+ "required": ["description", "args_schema", "source"],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["application_id", "id", "agent_md", "spec"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-clone-from-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-clone-from-create.json
new file mode 100644
index 000000000000..b5d7c370a1b0
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-clone-from-create.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "source_revision_id": {
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "source_revision_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
new file mode 100644
index 000000000000..4abf51a7dd16
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
@@ -0,0 +1,793 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "bundle_uri": {
+ "default": "",
+ "type": "string"
+ },
+ "parent_revision": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "spec": {
+ "properties": {
+ "entrypoint": {
+ "default": "agent.md",
+ "type": "string"
+ },
+ "integrations": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "limits": {
+ "default": {
+ "max_tool_calls": 200,
+ "max_turns": 50,
+ "max_wall_seconds": 900
+ },
+ "properties": {
+ "max_output_tokens": {
+ "exclusiveMinimum": 0,
+ "maximum": 200000,
+ "type": "number"
+ },
+ "max_tool_calls": {
+ "default": 200,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ },
+ "max_turns": {
+ "default": 50,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ },
+ "max_wall_seconds": {
+ "default": 900,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "mcps": {
+ "default": [],
+ "items": {
+ "properties": {
+ "auth": {
+ "properties": {
+ "integration": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "headers": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secrets": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "tools": {
+ "items": {
+ "anyOf": [
+ {
+ "minLength": 1,
+ "type": "string"
+ },
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["id", "url"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "model": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "reasoning": {
+ "enum": ["minimal", "low", "medium", "high", "xhigh"],
+ "type": "string"
+ },
+ "secrets": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "skills": {
+ "default": [],
+ "items": {
+ "properties": {
+ "alias": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "from_template": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "version": {
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["id", "path"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "tools": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "native",
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["kind", "id"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom",
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["kind", "id", "path"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "alias": {
+ "type": "string"
+ },
+ "from_template": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom_template",
+ "type": "string"
+ },
+ "version": {
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["kind", "from_template", "alias"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "args_schema": {
+ "additionalProperties": {},
+ "default": {},
+ "properties": {},
+ "type": "object"
+ },
+ "description": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "interactive": {
+ "default": false,
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "client",
+ "type": "string"
+ },
+ "required": {
+ "default": false,
+ "type": "boolean"
+ },
+ "timeout_ms": {
+ "default": 5000,
+ "maximum": 600000,
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["kind", "id", "description"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "triggers": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "config": {
+ "properties": {
+ "ack_reaction": {
+ "type": "string"
+ },
+ "allow_workspace_participants": {
+ "default": false,
+ "type": "boolean"
+ },
+ "auto_resume_threads": {
+ "default": false,
+ "type": "boolean"
+ },
+ "channel_id": {
+ "type": "string"
+ },
+ "mention_only": {
+ "default": false,
+ "type": "boolean"
+ },
+ "trusted_workspaces": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "const": "*",
+ "type": "string"
+ }
+ ]
+ }
+ },
+ "required": ["trusted_workspaces"],
+ "type": "object"
+ },
+ "type": {
+ "const": "slack",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "properties": {
+ "path": {
+ "type": "string"
+ }
+ },
+ "required": ["path"],
+ "type": "object"
+ },
+ "type": {
+ "const": "webhook",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config", "auth"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "config": {
+ "properties": {
+ "catch_up": {
+ "default": "most_recent",
+ "enum": ["all", "most_recent", "skip"],
+ "type": "string"
+ },
+ "external_key": {
+ "type": "string"
+ },
+ "max_catch_up_age_seconds": {
+ "default": 3600,
+ "maximum": 604800,
+ "minimum": 1,
+ "type": "number"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "prompt": {
+ "maxLength": 4096,
+ "minLength": 1,
+ "type": "string"
+ },
+ "schedule": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "timezone": {
+ "default": "UTC",
+ "type": "string"
+ }
+ },
+ "required": ["name", "schedule", "prompt"],
+ "type": "object"
+ },
+ "type": {
+ "const": "cron",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "default": {
+ "allow_restart": false
+ },
+ "properties": {
+ "allow_restart": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "type": {
+ "const": "chat",
+ "type": "string"
+ }
+ },
+ "required": ["type", "auth"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "default": {
+ "allow_restart": false
+ },
+ "properties": {
+ "allow_restart": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "type": {
+ "const": "mcp",
+ "type": "string"
+ }
+ },
+ "required": ["type", "auth"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["model"],
+ "type": "object"
+ }
+ },
+ "required": ["application_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-cron-fire-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-cron-fire-create.json
new file mode 100644
index 000000000000..7a0d4f610180
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-cron-fire-create.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "cron_name": {
+ "description": "`name` of the cron trigger in `spec.triggers[]` to fire.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "request_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Stable client-supplied id so repeated clicks of the same UI 'Fire now' button resolve to the same session id rather than firing twice. The janitor keys dedupe off `cron-manual:<rev>:<name>:<request_id>`. Omit to fire unconditionally — every call generates a fresh UUID."
+ }
+ },
+ "required": ["application_id", "id", "cron_name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-freeze-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-freeze-create.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-freeze-create.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-list.json
new file mode 100644
index 000000000000..53948d37fe40
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-list.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "limit": {
+ "description": "Number of results to return per page.",
+ "type": "number"
+ },
+ "offset": {
+ "description": "The initial index from which to return the results.",
+ "type": "number"
+ }
+ },
+ "required": ["application_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-manifest-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-manifest-retrieve.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-manifest-retrieve.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-new-draft-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-new-draft-create.json
new file mode 100644
index 000000000000..2597fc39e6ec
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-new-draft-create.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "source_revision_id": {
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "source_revision_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
new file mode 100644
index 000000000000..b2ed8658a805
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
@@ -0,0 +1,796 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "bundle_uri": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "parent_revision": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "spec": {
+ "properties": {
+ "entrypoint": {
+ "default": "agent.md",
+ "type": "string"
+ },
+ "integrations": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "limits": {
+ "default": {
+ "max_tool_calls": 200,
+ "max_turns": 50,
+ "max_wall_seconds": 900
+ },
+ "properties": {
+ "max_output_tokens": {
+ "exclusiveMinimum": 0,
+ "maximum": 200000,
+ "type": "number"
+ },
+ "max_tool_calls": {
+ "default": 200,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ },
+ "max_turns": {
+ "default": 50,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ },
+ "max_wall_seconds": {
+ "default": 900,
+ "exclusiveMinimum": 0,
+ "maximum": 2147483647,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "mcps": {
+ "default": [],
+ "items": {
+ "properties": {
+ "auth": {
+ "properties": {
+ "integration": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "headers": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secrets": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "tools": {
+ "items": {
+ "anyOf": [
+ {
+ "minLength": 1,
+ "type": "string"
+ },
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": ["id", "url"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "model": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "reasoning": {
+ "enum": ["minimal", "low", "medium", "high", "xhigh"],
+ "type": "string"
+ },
+ "secrets": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "skills": {
+ "default": [],
+ "items": {
+ "properties": {
+ "alias": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "from_template": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "version": {
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["id", "path"],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "tools": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "native",
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["kind", "id"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "approval_policy": {
+ "properties": {
+ "allow_agent_approver": {
+ "default": false,
+ "type": "boolean"
+ },
+ "allow_edit": {
+ "default": false,
+ "type": "boolean"
+ },
+ "approvers": {
+ "default": ["team_admins"],
+ "items": {
+ "enum": ["team_admins", "session_principal"],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "ttl_ms": {
+ "default": 86400000,
+ "maximum": 604800000,
+ "minimum": 60000,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom",
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "requires_approval": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "required": ["kind", "id", "path"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "alias": {
+ "type": "string"
+ },
+ "from_template": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom_template",
+ "type": "string"
+ },
+ "version": {
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "required": ["kind", "from_template", "alias"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "args_schema": {
+ "additionalProperties": {},
+ "default": {},
+ "properties": {},
+ "type": "object"
+ },
+ "description": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "interactive": {
+ "default": false,
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "client",
+ "type": "string"
+ },
+ "required": {
+ "default": false,
+ "type": "boolean"
+ },
+ "timeout_ms": {
+ "default": 5000,
+ "maximum": 600000,
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["kind", "id", "description"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "triggers": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "config": {
+ "properties": {
+ "ack_reaction": {
+ "type": "string"
+ },
+ "allow_workspace_participants": {
+ "default": false,
+ "type": "boolean"
+ },
+ "auto_resume_threads": {
+ "default": false,
+ "type": "boolean"
+ },
+ "channel_id": {
+ "type": "string"
+ },
+ "mention_only": {
+ "default": false,
+ "type": "boolean"
+ },
+ "trusted_workspaces": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "const": "*",
+ "type": "string"
+ }
+ ]
+ }
+ },
+ "required": ["trusted_workspaces"],
+ "type": "object"
+ },
+ "type": {
+ "const": "slack",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "properties": {
+ "path": {
+ "type": "string"
+ }
+ },
+ "required": ["path"],
+ "type": "object"
+ },
+ "type": {
+ "const": "webhook",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config", "auth"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "config": {
+ "properties": {
+ "catch_up": {
+ "default": "most_recent",
+ "enum": ["all", "most_recent", "skip"],
+ "type": "string"
+ },
+ "external_key": {
+ "type": "string"
+ },
+ "max_catch_up_age_seconds": {
+ "default": 3600,
+ "maximum": 604800,
+ "minimum": 1,
+ "type": "number"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "prompt": {
+ "maxLength": 4096,
+ "minLength": 1,
+ "type": "string"
+ },
+ "schedule": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "timezone": {
+ "default": "UTC",
+ "type": "string"
+ }
+ },
+ "required": ["name", "schedule", "prompt"],
+ "type": "object"
+ },
+ "type": {
+ "const": "cron",
+ "type": "string"
+ }
+ },
+ "required": ["type", "config"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "default": {
+ "allow_restart": false
+ },
+ "properties": {
+ "allow_restart": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "type": {
+ "const": "chat",
+ "type": "string"
+ }
+ },
+ "required": ["type", "auth"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "auth": {
+ "properties": {
+ "modes": {
+ "items": {
+ "anyOf": [
+ {
+ "properties": {
+ "acknowledge_public_exposure": {
+ "type": "boolean"
+ },
+ "type": {
+ "const": "public",
+ "type": "string"
+ }
+ },
+ "required": ["type", "acknowledge_public_exposure"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "scopes": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "posthog",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "issuer_secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "jwt",
+ "type": "string"
+ }
+ },
+ "required": ["type", "issuer_secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "header": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "secret_ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "const": "shared_secret",
+ "type": "string"
+ }
+ },
+ "required": ["type", "header", "secret_ref"],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "const": "posthog_internal",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "config": {
+ "default": {
+ "allow_restart": false
+ },
+ "properties": {
+ "allow_restart": {
+ "default": false,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "type": {
+ "const": "mcp",
+ "type": "string"
+ }
+ },
+ "required": ["type", "auth"],
+ "type": "object"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["model"],
+ "type": "object"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-promote-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-promote-create.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-promote-create.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-retrieve.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-retrieve.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.json
new file mode 100644
index 000000000000..636af44180eb
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "skill_id": {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "skill_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.json
new file mode 100644
index 000000000000..b1c9639705c3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.json
@@ -0,0 +1,26 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "body": {
+ "description": "The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",
+ "type": "string"
+ },
+ "description": {
+ "description": "One-line summary shown in the skill index; the model uses it to decide when to load the skill.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "skill_id": {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "skill_id", "description", "body"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-slack-manifest.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-slack-manifest.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-slack-manifest.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-spec-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-spec-update.json
new file mode 100644
index 000000000000..b61832a323a0
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-spec-update.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "spec": {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ }
+ },
+ "required": ["application_id", "id", "spec"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-system-prompt.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-system-prompt.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-system-prompt.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-destroy.json
new file mode 100644
index 000000000000..86d05f2d5811
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-destroy.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "tool_id": {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "tool_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-update.json
new file mode 100644
index 000000000000..32641930870e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-update.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "args_schema": {
+ "additionalProperties": {},
+ "propertyNames": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "description": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ },
+ "source": {
+ "type": "string"
+ },
+ "tool_id": {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id", "tool_id", "description", "args_schema", "source"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-validate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-validate-create.json
new file mode 100644
index 000000000000..ca7afd5be5fd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-validate-create.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "application_id": {
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent revision.",
+ "type": "string"
+ }
+ },
+ "required": ["application_id", "id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-list.json
new file mode 100644
index 000000000000..dac8314ecdcd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-list.json
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "created_after": {
+ "description": "ISO datetime — return sessions with created_at >= this.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "created_before": {
+ "description": "ISO datetime — return sessions with created_at <= this.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "limit": {
+ "type": "number"
+ },
+ "offset": {
+ "type": "number"
+ },
+ "revision_id": {
+ "description": "Only return sessions started against this specific revision.",
+ "type": "string"
+ },
+ "state": {
+ "description": "Filter by session state. Comma-separated list accepted (e.g. `completed,failed`). Valid values: queued, running, completed, closed, cancelled, failed.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-retrieve.json
new file mode 100644
index 000000000000..00e625f24603
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-sessions-retrieve.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "last_n": {
+ "description": "If set, return only the most recent N messages from the conversation. `usage_total` is still computed over the full session — only the transcript is trimmed. The response includes `conversation_trimmed: true` and `conversation_total_turns` so the caller knows how much was hidden.",
+ "type": "number"
+ },
+ "session_id": {
+ "description": "UUID of the session to fetch (must belong to this application).",
+ "type": "string"
+ }
+ },
+ "required": ["id", "session_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-native-tools-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-native-tools-list.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-native-tools-list.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index cf43e4ef8882..0df3495faae0 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -732,6 +732,7 @@ describe('Tool Filtering - Feature Flags', () => {
// Includes the gating flag for agent-feedback alongside the other gated tools.
expect(flags).toEqual(
expect.arrayContaining([
+ 'agent-platform-mcp',
'logs-alerting',
'replay-video-based-summarization',
'tracing',
@@ -750,7 +751,7 @@ describe('Tool Filtering - Feature Flags', () => {
'field-notes',
])
)
- expect(flags).toHaveLength(16)
+ expect(flags).toHaveLength(17)
})
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index da17c59953be..b4d964768562 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -86,7 +86,13 @@ describe('Tool schema snapshots', () => {
const root = path.resolve(__dirname, '__snapshots__', 'tool-schemas')
// Enable flag-gated tools we snapshot here: agent-feedback, tracing (APM spans), tasks,
// dashboard-widgets. Other flag-gated tools (logs-alerts, visual-review, etc.) stay off to keep the surface stable.
- const featureFlags = { 'mcp-feedback-tool': true, tracing: true, tasks: true, 'dashboard-widgets': true }
+ const featureFlags = {
+ 'mcp-feedback-tool': true,
+ tracing: true,
+ tasks: true,
+ 'dashboard-widgets': true,
+ 'agent-platform-mcp': true,
+ }
const tools = [...(await getToolsFromContext(context, { featureFlags }))].sort((a, b) =>
a.name.localeCompare(b.name)
)
diff --git a/tach.toml b/tach.toml
index a78029e954a0..7ebb7145229b 100644
--- a/tach.toml
+++ b/tach.toml
@@ -128,6 +128,13 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.agent_platform"
+depends_on = [
+ "posthog",
+]
+layer = "modules"
+
[[modules]]
path = "products.alerts"
depends_on = [