: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(agent-platform): custom-tool authoring loop with dry-run (#66584)
Dylan Martinf3c95f2bf1b0
diff --git a/products/agent_platform/AGENTS.md b/products/agent_platform/AGENTS.mdindex c973d3801fd9..4259f8b54613 100644--- a/products/agent_platform/AGENTS.md+++ b/products/agent_platform/AGENTS.md@@ -83,6 +83,7 @@ Each line is a pino JSON record (`name` = subsystem, plus any bindings like- **Local dev + MCP local + e2e overview** —[docs/local-dev.md](docs/local-dev.md).+- **Custom-tool authoring contract** — [docs/custom-tools.md](docs/custom-tools.md).- **Janitor HTTP surface** —[products/agent_platform/services/agent-janitor/src/server.ts](../../products/agent_platform/services/agent-janitor/src/server.ts).- **Spec shape (source of truth)** —diff --git a/products/agent_platform/backend/logic/janitor_client.py b/products/agent_platform/backend/logic/janitor_client.pyindex b7d3ca77b196..d238c48f76fe 100644--- a/products/agent_platform/backend/logic/janitor_client.py+++ b/products/agent_platform/backend/logic/janitor_client.py@@ -128,6 +128,11 @@ class JanitorClient:def delete_tool(self, revision_id: str, tool_id: str) -> dict:return self._call("DELETE", f"/revisions/{revision_id}/tools/{tool_id}")+ def dry_run_tool(self, revision_id: str, tool_id: str, body: dict) -> dict:+ """Single-shot sandbox execution of the persisted compiled.js with+ synthetic args + mock secrets. `body` carries { args, mock_secrets? }."""+ return self._call("POST", f"/revisions/{revision_id}/tools/{tool_id}/dry_run", json=body)+def freeze(self, revision_id: str) -> dict:return self._call("POST", f"/revisions/{revision_id}/freeze")diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.pyindex 72fd7e588268..d6bb502cc4ea 100644--- a/products/agent_platform/backend/presentation/serializers.py+++ b/products/agent_platform/backend/presentation/serializers.py@@ -456,6 +456,25 @@ class WriteToolRequestSerializer(serializers.Serializer):source = serializers.CharField(allow_blank=False, trim_whitespace=False) # type: ignore[assignment] # field named `source` shadows DRF Field.source+class DryRunToolRequestSerializer(serializers.Serializer):+ """Body shape for POST /revisions/<id>/tools/<tool_id>/dry_run/.++ Executes the persisted compiled.js once in the janitor's single-shot+ sandbox with caller-supplied args + a stubbed ctx. No real secrets+ leave Django — `mock_secrets` is a `{name → opaque nonce}` map the+ sandbox plumbs into `ctx.secrets.ref(name)` so the tool body returns+ something deterministic to the author."""++ args = serializers.JSONField(+ help_text="Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync."+ )+ mock_secrets = serializers.DictField(+ child=serializers.CharField(allow_blank=True),+ required=False,+ help_text="Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.",+ )++class WriteTypedBundleRequestSerializer(serializers.Serializer):"""Body shape for PUT /revisions/<id>/bundle/ — the full-replace typedpayload. Skills are not authored here: they come from the llma-skill storediff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex e5f126bcd214..633ba8e82d4f 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -85,6 +85,7 @@ from .serializers import (AgentRevisionSerializer,CloneFromRequestSerializer,DecideApprovalRequestSerializer,+ DryRunToolRequestSerializer,NewDraftRevisionRequestSerializer,PreviewProxyInvokeRequestSerializer,PromoteRevisionRequestSerializer,@@ -1741,6 +1742,10 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"set_skill_refs","put_tool","delete_tool",+ # Dry-run reads the persisted compiled.js but actually executes user+ # code in a sandbox — treat it as a write-scoped op so the scope+ # gates arbitrary compute, not just data reads.+ "dry_run_tool","cron_fire","set_env",# env_keys_key handles GET/PUT/DELETE on /env_keys/<KEY>/ — bundled@@ -2216,6 +2221,61 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):revision: AgentRevision = self.get_object()return Response(self._call(_janitor().delete_tool, str(revision.id), tool_id))+ @extend_schema(+ request=DryRunToolRequestSerializer,+ responses=OpenApiResponse(+ response=inline_serializer(+ name="AgentRevisionDryRunToolResponse",+ fields={+ "ok": drf_serializers.BooleanField(+ help_text="True when the tool's `actions.default` returned without throwing. False when the tool threw or the sandbox rejected the invocation (the structured `error` describes which)."+ ),+ "tool_id": drf_serializers.CharField(help_text="Echo of the tool id from the URL."),+ "result": drf_serializers.JSONField(+ required=False,+ help_text="Present on success — the value the tool's `actions.default` returned.",+ ),+ "error": inline_serializer(+ name="AgentRevisionDryRunToolError",+ fields={+ "code": drf_serializers.CharField(+ help_text=(+ "Stable error code. `sandbox_acquire_failed` — the platform could not start a "+ "sandbox (infrastructure issue, not tool code). `sandbox_invoke_failed` — the "+ "sandbox started but the invoke threw uncaught (problem in the tool body, or a "+ "runtime error). Dispatcher-side codes come through on `ok:false` invoke results: "+ "`timeout`, `secret_not_provisioned`, `action_not_found`, `tool_not_found`."+ )+ ),+ "message": drf_serializers.CharField(help_text="One-line human-readable detail."),+ },+ required=False,+ ),+ "duration_ms": drf_serializers.IntegerField(+ help_text=(+ "Wall-clock duration in milliseconds, measured from sandbox acquire to after release. "+ "Captured consistently across success, tool-throw, and acquire-failure paths so authors "+ "can compare timings between calls. Always present."+ )+ ),+ },+ )+ ),+ )+ @action(detail=True, methods=["post"], url_path=r"tools/(?P<tool_id>[a-z0-9][a-z0-9_-]*)/dry_run")+ def dry_run_tool(self, request: Request, tool_id: str, **kwargs) -> Response:+ """Execute one persisted custom tool in a single-shot sandbox.++ Authoring loop's "test this tool" button. The tool's source must+ already be PUT (compiled.js is what runs); this just invokes it+ with the caller-supplied args and a stubbed ctx. No real secrets+ leave Django — `mock_secrets` is a `{name → placeholder}` map.+ """+ revision: AgentRevision = self.get_object()+ body = DryRunToolRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ return Response(self._call(_janitor().dry_run_tool, str(revision.id), tool_id, body.validated_data))+@extend_schema(request=None,responses=OpenApiResponse(diff --git a/products/agent_platform/docs/README.md b/products/agent_platform/docs/README.mdindex 5a4a84c85220..d4505cc67f08 100644--- a/products/agent_platform/docs/README.md+++ b/products/agent_platform/docs/README.md@@ -8,7 +8,10 @@ Concise, diagram-led docs for the v2 agent platform. Read in this order:Django) owns and how a request flows through them.3. **[identity-and-tools.md](identity-and-tools.md)** — edge identity → agentuser → linked identities → tools, credentials, approvals, and MCP.-4. **[local-dev.md](local-dev.md)** — bringing the stack up locally, driving it,+4. **[custom-tools.md](custom-tools.md)** — authoring user-written sandboxed+ tools: the contract, the minimal `ctx`, the sandbox boundary and+ egress story.+5. **[local-dev.md](local-dev.md)** — bringing the stack up locally, driving it,and the e2e harness.Authoritative sources these summarize: `AgentSpecSchema` indiff --git a/products/agent_platform/docs/custom-tools.md b/products/agent_platform/docs/custom-tools.mdnew file mode 100644index 000000000000..6cd7f7849e89--- /dev/null+++ b/products/agent_platform/docs/custom-tools.md@@ -0,0 +1,256 @@+# Agent platform — custom tools++User-authored TypeScript an agent can call. Sandboxed per session, no+network, deliberately minimal `ctx`. The complement to native+`@posthog/*` tools and MCP servers — when you need behaviour the+platform doesn't ship and an external MCP server isn't the right+abstraction, write a custom tool.++See [identity-and-tools.md](identity-and-tools.md) for the broader tool+taxonomy and the credential model that the runner threads around custom+tools.++## The model++```mermaid+flowchart LR+ spec["spec.tools[]<br/>{kind:'custom', id, path, requires_identity?, requires_approval?}"] --> rev["revision bundle<br/>tools/<id>/{source.ts, schema.json, compiled.js}"]+ rev --> sandbox["sandbox-host<br/>(Docker --network=none / Modal blockNetwork)"]+ sandbox --> ctx["minimal ctx:<br/>secrets.ref(name) · log()"]+ ctx --> action["actions.default(args, ctx)"]+ action --> result["JSON.stringified result<br/>→ tool_result → model"]+```++**The sandbox is the security boundary.** The sandbox runs a Node+process with no outbound network reach (`--network=none` in Docker,+`blockNetwork:true` on Modal) and dropped capabilities. In v1 a custom+tool computes over its `args`, optionally consults secret nonces, logs+what it did, and returns structured data the runner threads back to+the model. `fetch` exists but has nothing to reach; there is no+memory/table store access today.++Two things follow from where the boundary sits:++- **Custom tools are trusted code.** They are human-authored,+ reviewed, and versioned in the revision — the model only ever+ invokes them with arguments. The compile pipeline checks _shape_ (so+ authors get friendly errors at PUT time), not _reach_: there is+ deliberately no source-level allow/deny list of modules or+ constructs. What a tool can reach is an infrastructure decision made+ by the sandbox at runtime, not a lint pass over the source.+- **Egress composes rather than leaking into the model.** When an+ agent needs to call out today, wire a native tool with a host-pinned+ secret (see "Egress, identity, approval" below). The direction of+ travel is a _bridge_ — `ctx.native(...)` / `ctx.mcp(...)` accessors+ that let a custom tool invoke native tools and MCP connections from+ inside the sandbox, so an author can wrap allowlists, audit, and+ business rules around a capability without handing the model the raw+ tool. Not yet wired; see "Coming next."++## The contract++A custom tool source is a single TypeScript file whose default export+is a static object literal:++```ts+import type { CustomTool, CustomToolContext } from '@posthog/agent-shared'++type Args = { name: string; count: number }++export default {+ actions: {+ default: async (args: Args, ctx: CustomToolContext) => {+ ctx.log('info', 'greeting', { name: args.name })+ return { greeting: `hi ${args.name} × ${args.count}` }+ },+ },+} satisfies CustomTool+```++The shape is enforced by the AST check in+[`compile-custom-tools.ts`](../services/agent-janitor/src/compile-custom-tools.ts):+exactly one `export default`, an object literal, an `actions` property+that is itself an object literal, an `actions.default` that is a+function. Anything else gets a structured `ToolCompileError` at+`PUT /revisions/:id/tools/:id` — the bundle is left untouched.++The runner always dispatches `action: "default"` today (see+[`build-agent-tools.ts`](../services/agent-runner/src/loop/build-agent-tools.ts)'s+`makeCustomTool`). Additional named actions are allowed by the schema+but unused; treat them as helpers, not entry points.++Type imports (`import type { ... }`) are stripped by esbuild at compile+time, so nothing reaches the sandbox runtime. **Value imports from+`@posthog/agent-shared` or any other package will fail at runtime** —+the sandbox image doesn't bundle `node_modules`, only the compiled tool+source. Keep the body self-contained.++## The `ctx`++```ts+interface CustomToolContext {+ secrets: { ref(name: string): string }+ log(level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>): void+}+```++Mirrors `buildContext` in+[`agent-sandbox-host/src/dispatch.js`](../services/agent-sandbox-host/src/dispatch.js).+That file is the source of truth — if you're reading this and the+shape has drifted, the dispatch is authoritative.++**`ctx.secrets.ref(name)`** returns an opaque per-session nonce for a+secret declared in `spec.secrets[]`. The plaintext value never enters+the sandbox heap. Throws `secret not provisioned: <name>` if the name+isn't declared on the agent.++> **Nonces are placeholders today.** Runner-side nonce → value+> substitution at egress is not yet wired (see the note in+> `dispatch.js`). A returned nonce won't resolve to the real secret+> if you try to use it in a tool result that the runner forwards+> elsewhere. Practically: secrets aren't usable from custom tools in+> v1. Return values for the runner to act on instead.++**`ctx.log(level, msg, meta?)`** writes a structured line to the+sandbox container's stderr. Ops can read it via the container log+collector; the runner doesn't surface these in the session+conversation. Use it for tracing internal decisions, not for data the+model needs to read — return data from `actions.default` for that.++## The spec entry++```jsonc+{+ "tools": [+ {+ "kind": "custom",+ "id": "format-customer-record",+ "path": "tools/format-customer-record",+ "requires_identity": "posthog", // optional+ "requires_approval": true, // optional+ "approval_policy": {+ // optional, requires_approval=true+ "type": "principal",+ "ttl_ms": 86400000,+ },+ },+ ],+}+```++Authors don't typically write `tools[]` by hand — the typed-bundle+authoring path stamps it at freeze time from the bundle's+`tools/<id>/` contents. See+[`services/agent-janitor/src/api/typed-bundle.ts`](../services/agent-janitor/src/api/typed-bundle.ts)+for the full schema.++## Egress, identity, approval++In v1 custom tools don't make external calls — the sandbox has no+network. When an agent legitimately needs to call out — your CRM, a+webhook, a GitHub API — wire a native tool with a host-pinned secret:++```jsonc+{+ "tools": [{ "kind": "native", "id": "@posthog/http-request" }],+ "secrets": [{ "name": "CRM_TOKEN", "allowed_hosts": ["api.crm.example"] }],+}+```++The `allowed_hosts` binding is enforced at the egress hop — smokescreen+plus secret substitution in+[`http-request.v1.ts`](../services/agent-tools/src/tools/http-request.v1.ts).+A prompt-injected `${CRM_TOKEN}` against `attacker.com` refuses+substitution rather than leaking the credential.++**The bridge (direction, not yet wired).** Custom tools will reach+native tools and MCP connections through prefixed `ctx` accessors —+`ctx.native('@posthog/http-request', args)`,+`ctx.mcp('incident-io', 'create-incident', args)` — instead of raw+network. That keeps the composition property: the tool gets the+capability, the model doesn't. Bridge calls are code-facing, so they+won't inherit the model-facing `requires_approval` gates from the+spec; authors opt into gating specific sub-calls via a planned+`ctx.requestApproval(...)` primitive that reuses the existing approval+queue (same rows, same Slack/console/decision-API surfaces). The+runtime wiring — a call channel out of the one-shot sandbox dispatch —+lands in a follow-up.++**`requires_identity: "posthog"`** on a custom tool fires the identity+gate _before_ the sandbox runs. If the asker hasn't linked PostHog,+the model receives an `auth_required` result with an authorize link+and the tool body never executes. Currently the resolved credential+isn't threaded into the sandbox — the gate is a _precondition_ check+rather than a credential injection point. See the seam comment at+[`build-agent-tools.ts:440-441`](../services/agent-runner/src/loop/build-agent-tools.ts).++**`requires_approval: true`** routes every call through the approval+queue (`agent_tool_approval_request`). The model receives a synthetic+queued envelope and the session keeps going; when an approver decides+(via Slack, the decision API, or the console, depending on+`approval_policy.type`), the result is injected back into the session.+Approved decisions can include `edited_args`. See+[`approval.ts`](../services/agent-runner/src/loop/approval.ts).++## When to use a custom tool++Use a custom tool when:++- You need behaviour the platform doesn't ship and that doesn't fit an+ external MCP server (too small, too coupled to your data, too+ one-off).+- The work is computation: parsing, formatting, score calculation,+ state mutation against the agent's memory/table store (when those+ land for custom tools), shape translation between data the model+ produced and the structure your downstream tool needs.+- You want the agent to combine model output + your business rules+ before another tool acts on it.++Use `@posthog/http-request` or a dedicated native tool when:++- You need to call an external API. In v1 the sandbox has no network;+ until the bridge lands, egress goes through native tools.+- You need to send data anywhere outside the sandbox. Custom tools+ can't today — they return data to the runner.++Use an external MCP server when:++- You already have one (Linear, GitHub, Slack, your internal MCP).+- The capability is reusable across many agents.+- You want the server's owner — not the agent author — to manage+ versions and scopes.++## Authoring today++The janitor exposes per-tool authoring endpoints:++- `GET /revisions/:id/bundle` — read the draft revision's whole typed+ bundle (agent.md, skills, tools, spec slice).+- `PUT /revisions/:id/tools/:id` — body `{description, args_schema, source}`.+ AST check + esbuild compile run synchronously; 422 with structured+ diagnostics on failure; the bundle is untouched on failure.+- `POST /revisions/:id/tools/:id/dry_run` — body `{args, mock_secrets?}`.+ Executes the persisted `compiled.js` once in a single-shot sandbox+ with a stubbed `ctx`; returns `{ok, result?, error?, duration_ms}`.+ `mock_secrets` placeholders come back verbatim from+ `ctx.secrets.ref(name)` so the tool body runs deterministically.+- `DELETE /revisions/:id/tools/:id`.+- `POST /revisions/:id/validate` — pre-flight for entrypoint, tool ids,+ custom-tool files, skill paths.++Django proxies the per-tool endpoints in `AgentRevisionViewSet`+(`backend/presentation/views.py`), and the MCP authoring surface+includes `agent-applications-revisions-tools-update/destroy` generated+from those.++**Coming next** (work in flight): the native/MCP bridge+(`ctx.native` / `ctx.mcp`) with opt-in gating via+`ctx.requestApproval`; an in-app Tools tab on the revision editor;+capability summaries on each tool card; default-on approval for tools+that combine identity-gated access with mutable state.++**Deferred** (explicitly not in v1): nonce → value substitution at+egress (custom tools can prepare authenticated requests for the runner+to dispatch); a cross-agent custom-tool template registry; richer+sandbox capabilities (memory/table stores, identity-resolved+credentials). Re-evaluated after v1 usage signal.diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.tsindex e70417606708..fc3c8bcb0210 100644--- a/products/agent_platform/frontend/generated/api.schemas.ts+++ b/products/agent_platform/frontend/generated/api.schemas.ts@@ -439,6 +439,46 @@ export interface AgentRevisionSystemPromptResponseApi {system_prompt: string}+/**+ * Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.+ */+export type DryRunToolRequestApiMockSecrets = { [key: string]: string }++/**+ * Body shape for POST /revisions/<id>/tools/<tool_id>/dry_run/.+ *+ * Executes the persisted compiled.js once in the janitor's single-shot+ * sandbox with caller-supplied args + a stubbed ctx. No real secrets+ * leave Django — `mock_secrets` is a `{name → opaque nonce}` map the+ * sandbox plumbs into `ctx.secrets.ref(name)` so the tool body returns+ * something deterministic to the author.+ */+export interface DryRunToolRequestApi {+ /** Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync. */+ args: unknown+ /** Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox. */+ mock_secrets?: DryRunToolRequestApiMockSecrets+}++export interface AgentRevisionDryRunToolErrorApi {+ /** Stable error code. `sandbox_acquire_failed` — the platform could not start a sandbox (infrastructure issue, not tool code). `sandbox_invoke_failed` — the sandbox started but the invoke threw uncaught (problem in the tool body, or a runtime error). Dispatcher-side codes come through on `ok:false` invoke results: `timeout`, `secret_not_provisioned`, `action_not_found`, `tool_not_found`. */+ code: string+ /** One-line human-readable detail. */+ message: string+}++export interface AgentRevisionDryRunToolResponseApi {+ /** True when the tool's `actions.default` returned without throwing. False when the tool threw or the sandbox rejected the invocation (the structured `error` describes which). */+ ok: boolean+ /** Echo of the tool id from the URL. */+ tool_id: string+ /** Present on success — the value the tool's `actions.default` returned. */+ result?: unknown+ error?: AgentRevisionDryRunToolErrorApi+ /** Wall-clock duration in milliseconds, measured from sandbox acquire to after release. Captured consistently across success, tool-throw, and acquire-failure paths so authors can compare timings between calls. Always present. */+ duration_ms: number+}+export interface AgentRevisionValidationErrorApi {code: stringmessage: stringdiff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.tsindex 896c87dc2c43..8557f0d32b9a 100644--- a/products/agent_platform/frontend/generated/api.ts+++ b/products/agent_platform/frontend/generated/api.ts@@ -48,6 +48,7 @@ import type {AgentRevisionApi,AgentRevisionCronFireRequestApi,AgentRevisionCronFireResponseApi,+ AgentRevisionDryRunToolResponseApi,AgentRevisionEnvKeyStatusApi,AgentRevisionEnvKeysResponseApi,AgentRevisionSlackManifestResponseApi,@@ -58,6 +59,7 @@ import type {AgentUsersListApi,CloneFromRequestApi,DecideApprovalRequestApi,+ DryRunToolRequestApi,NewDraftRevisionRequestApi,PaginatedAgentApplicationListApi,PaginatedAgentRevisionListApi,@@ -1317,6 +1319,42 @@ export const agentApplicationsRevisionsToolsDestroy = async (})}+export const getAgentApplicationsRevisionsToolsDryRunCreateUrl = (+ projectId: string,+ applicationId: string,+ id: string,+ toolId: string+) => {+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/tools/${toolId}/dry_run/`+}++/**+ * Execute one persisted custom tool in a single-shot sandbox.+ *+ * Authoring loop's "test this tool" button. The tool's source must+ * already be PUT (compiled.js is what runs); this just invokes it+ * with the caller-supplied args and a stubbed ctx. No real secrets+ * leave Django — `mock_secrets` is a `{name → placeholder}` map.+ */+export const agentApplicationsRevisionsToolsDryRunCreate = async (+ projectId: string,+ applicationId: string,+ id: string,+ toolId: string,+ dryRunToolRequestApi: DryRunToolRequestApi,+ options?: RequestInit+): Promise<AgentRevisionDryRunToolResponseApi> => {+ return apiMutator<AgentRevisionDryRunToolResponseApi>(+ getAgentApplicationsRevisionsToolsDryRunCreateUrl(projectId, applicationId, id, toolId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dryRunToolRequestApi),+ }+ )+}+export const getAgentApplicationsRevisionsValidateCreateUrl = (projectId: string,applicationId: string,diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.tsindex f761744382df..f6c29bd5929e 100644--- a/products/agent_platform/frontend/generated/api.zod.ts+++ b/products/agent_platform/frontend/generated/api.zod.ts@@ -416,6 +416,32 @@ export const AgentApplicationsRevisionsToolsUpdateBody = /* @__PURE__ */ zod}).describe('Body shape for PUT \/revisions\/<id>\/tools\/<tool_id>\/.')+/**+ * Execute one persisted custom tool in a single-shot sandbox.+ *+ * Authoring loop's "test this tool" button. The tool's source must+ * already be PUT (compiled.js is what runs); this just invokes it+ * with the caller-supplied args and a stubbed ctx. No real secrets+ * leave Django — `mock_secrets` is a `{name → placeholder}` map.+ */+export const AgentApplicationsRevisionsToolsDryRunCreateBody = /* @__PURE__ */ zod+ .object({+ args: zod+ .unknown()+ .describe(+ "Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync."+ ),+ mock_secrets: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.'+ ),+ })+ .describe(+ "Body shape for POST \/revisions\/<id>\/tools\/<tool_id>\/dry_run\/.\n\nExecutes the persisted compiled.js once in the janitor's single-shot\nsandbox with caller-supplied args + a stubbed ctx. No real secrets\nleave Django — `mock_secrets` is a `{name → opaque nonce}` map the\nsandbox plumbs into `ctx.secrets.ref(name)` so the tool body returns\nsomething deterministic to the author."+ )+/*** Create a fresh draft revision under `application_id` and seed it* from `source_revision_id`. Saves the MCP one round-trip vs thediff --git a/products/agent_platform/services/agent-janitor/src/api/typed-bundle.test.ts b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.test.tsnew file mode 100644index 000000000000..e5f04338924d--- /dev/null+++ b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.test.ts@@ -0,0 +1,135 @@+/**+ * Unit tests for the dry-run admission control in the typed-bundle router.+ *+ * The wire-level dry-run behaviour (real sandbox, real stores) is covered by+ * `agent-tests/src/cases/typed-bundle-authoring.test.ts`; this file pins the+ * in-flight cap, which needs *concurrent* requests held open mid-acquire —+ * deterministic here via deferred promises on a stub pool, flaky there via+ * sleeps in real sandboxes.+ */++import express from 'express'+import request from 'supertest'++import type { BundleStore, RevisionStore, SandboxPool } from '@posthog/agent-shared'++import { buildTypedBundleRouter } from './typed-bundle'++const REV_ID = '00000000-0000-4000-8000-00000000ab01'++function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void } {+ let resolve!: (v: T) => void+ const promise = new Promise<T>((r) => {+ resolve = r+ })+ return { promise, resolve }+}++/** Stores stubbed to the minimal draft-revision surface the dry-run path reads. */+function stubStores(): { revisions: RevisionStore; bundles: BundleStore } {+ const revisions = {+ async getRevisionRaw() {+ return { id: REV_ID, application_id: 'app-1', state: 'draft', spec: {} }+ },+ async getApplication() {+ return { id: 'app-1', team_id: 1 }+ },+ } as unknown as RevisionStore+ const bundles = {+ async isFrozen() {+ return false+ },+ async readText(_rev: string, path: string) {+ return path.endsWith('compiled.js') ? 'module.exports = {}' : '{}'+ },+ } as unknown as BundleStore+ return { revisions, bundles }+}++describe('dry-run sandbox guards', () => {+ it('429s past the cap and frees the slot when the held run finishes', async () => {+ // Pool whose acquire blocks until the test releases it, so requests+ // can be held in flight deterministically.+ const acquireEntered = deferred<void>()+ const acquireGate = deferred<void>()+ const sandboxes = {+ async acquireForSession() {+ acquireEntered.resolve()+ await acquireGate.promise+ return {+ async invoke() {+ return { ok: true, result: { ran: true } }+ },+ }+ },+ async release() {},+ } as unknown as SandboxPool++ const app = express()+ app.use(express.json())+ app.use('/revisions/:id', buildTypedBundleRouter({ ...stubStores(), sandboxes, dryRunMaxConcurrent: 1 }))+ const dryRun = (): request.Test =>+ request(app).post(`/revisions/${REV_ID}/tools/echo/dry_run`).send({ args: {} })++ // A acquires the only slot and parks inside acquireForSession.+ const a = dryRun()+ const aDone = a.then((r) => r)+ await acquireEntered.promise++ // B arrives while A holds the slot → rejected, not queued.+ const b = await dryRun()+ expect(b.status).toBe(429)+ expect(b.body).toEqual({ error: 'dry_run_throttled', max_concurrent: 1 })++ // A completes normally once released.+ acquireGate.resolve()+ const aRes = await aDone+ expect(aRes.status).toBe(200)+ expect(aRes.body).toMatchObject({ ok: true, result: { ran: true } })++ // The slot was freed — a follow-up run is admitted (catches a+ // leaked counter if the finally-decrement is ever dropped).+ const c = await dryRun()+ expect(c.status).toBe(200)+ })++ // The in-sandbox dispatcher timeout is cooperative — a synchronous+ // busy-loop tool body means the backend invoke never resolves. The+ // janitor-side wall clock must return a timeout AND free the slot,+ // or two such calls wedge dry-run for the whole process.+ it('times out a hung invoke janitor-side, destroys the sandbox, and frees the slot', async () => {+ const released = deferred<void>()+ const sandboxes = {+ async acquireForSession() {+ return {+ invoke: () => new Promise(() => {}),+ }+ },+ async release() {+ released.resolve()+ },+ } as unknown as SandboxPool++ const app = express()+ app.use(express.json())+ app.use(+ '/revisions/:id',+ // Tiny wallMs so the test only waits out the fixed grace window.+ buildTypedBundleRouter({ ...stubStores(), sandboxes, dryRunWallMs: 20, dryRunMaxConcurrent: 1 })+ )+ const dryRun = (): request.Test =>+ request(app).post(`/revisions/${REV_ID}/tools/hang/dry_run`).send({ args: {} })++ const hung = await dryRun()+ expect(hung.status).toBe(200)+ expect(hung.body).toMatchObject({ ok: false, error: { code: 'timeout' } })+ // Release ran despite the invoke never resolving — the wedged+ // sandbox is destroyed rather than orphaned.+ await released.promise++ // And the in-flight slot was freed, not pinned forever.+ const next = await dryRun()+ expect(next.status).toBe(200)+ expect(next.body).toMatchObject({ ok: false, error: { code: 'timeout' } })+ })+})diff --git a/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.tsindex d27aacc9b803..33a6c68084a6 100644--- a/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts+++ b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts@@ -23,6 +23,7 @@*/import { Router } from 'express'+import { randomUUID } from 'node:crypto'import { z } from 'zod'import {@@ -34,10 +35,13 @@ import {RESOURCE_ID_REGEX,RevisionState,RevisionStore,+ SandboxPool,skillBodyPath,skillCompanionPath,syncBundleToStore,+ toolCapabilitiesPath,toolCompiledPath,+ toolSchemaPath,TypedBundleSchema,TypedSkillSchema,TypedSpecSchema,@@ -84,8 +88,69 @@ const TypedBundlePutBodySchema = TypedBundleSchema.omit({ skills: true })export interface TypedBundleRouterOpts {revisions: RevisionStorebundles: BundleStore+ /**+ * Single-shot sandbox pool for `POST /tools/:tool_id/dry_run`. Same+ * `selectSandboxPool` impl the runner uses; lifecycle is per-call+ * (acquire → invoke → release) rather than per-session. Omitted →+ * the dry-run route 503s.+ */+ sandboxes?: SandboxPool+ /** Wall-clock cap per dry-run invocation (ms). Default: 10 000. */+ dryRunWallMs?: number+ /** Memory cap per dry-run sandbox (MB). Default: 256. */+ dryRunMemoryMb?: number+ /** Max dry-run sandboxes in flight at once (janitor-wide). Default: 2. */+ dryRunMaxConcurrent?: number}+const DEFAULT_DRY_RUN_WALL_MS = 10_000+const DEFAULT_DRY_RUN_MEMORY_MB = 256+const DEFAULT_DRY_RUN_MAX_CONCURRENT = 2+// Extra headroom past the in-sandbox `timeoutMs` before the janitor-side+// wall clock trips, so the dispatcher's cooperative timeout gets first+// chance to report the friendlier per-tool error.+const DRY_RUN_TIMEOUT_GRACE_MS = 1_000++const WALL_CLOCK_EXCEEDED = Symbol('wall_clock_exceeded')++/**+ * Race a promise against a hard wall clock. The in-sandbox dispatcher+ * enforces `timeoutMs` cooperatively (a Promise.race inside the sandbox+ * process), so a tool whose body is a synchronous busy-loop blocks the+ * sandbox event loop and the invoke never returns — without this outer+ * race the handler would hang, its `finally` would never run, and the+ * in-flight slot would stay pinned until the janitor restarts.+ */+function raceWallClock<T>(promise: Promise<T>, ms: number): Promise<T | typeof WALL_CLOCK_EXCEEDED> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => resolve(WALL_CLOCK_EXCEEDED), ms)+ promise.then(+ (value) => {+ clearTimeout(timer)+ resolve(value)+ },+ (err: unknown) => {+ clearTimeout(timer)+ reject(err)+ }+ )+ })+}++const DryRunBodySchema = z.object({+ /** Synthetic args the tool's `actions.default` is called with. */+ args: z.unknown(),+ /**+ * Optional `{secret_name → opaque_nonce}` map plumbed into the+ * sandbox the same way the runner injects nonces during a real+ * session. The plaintext value never enters the sandbox, so the+ * stub only needs *some* string the tool's `ctx.secrets.ref(name)`+ * can return. Authors typically pass placeholder strings here just+ * to confirm the tool runs without throwing `secret not provisioned`.+ */+ mock_secrets: z.record(z.string(), z.string()).optional(),+})+/*** Build the router that owns the typed-bundle endpoints. Mounted by the main* server under `/revisions/:id`.@@ -147,6 +212,13 @@ export function buildTypedBundleRouter(opts: TypedBundleRouterOpts): Router {for (const { tool, result } of compileResults) {await writeToolSourceAndSchema(req.params.id, opts.bundles, tool)await opts.bundles.write(req.params.id, toolCompiledPath(tool.id), result.compiled_js!)+ if (result.capabilities) {+ await opts.bundles.write(+ req.params.id,+ toolCapabilitiesPath(tool.id),+ JSON.stringify(result.capabilities, null, 2)+ )+ }}// Persist the author-facing spec onto agent_revision.spec.@@ -284,7 +356,14 @@ export function buildTypedBundleRouter(opts: TypedBundleRouterOpts): Router {await writeToolSourceAndSchema(req.params.id, opts.bundles, tool)await opts.bundles.write(req.params.id, toolCompiledPath(id), compile.compiled_js!)- res.json({ ok: true, tool_id: id })+ if (compile.capabilities) {+ await opts.bundles.write(+ req.params.id,+ toolCapabilitiesPath(id),+ JSON.stringify(compile.capabilities, null, 2)+ )+ }+ res.json({ ok: true, tool_id: id, capabilities: compile.capabilities })}))@@ -311,6 +390,180 @@ export function buildTypedBundleRouter(opts: TypedBundleRouterOpts): Router {}))+ // ─── POST /tools/:tool_id/dry_run (single-shot sandbox execution) ──+ //+ // Runs the persisted compiled.js once with caller-supplied args + a+ // stubbed ctx (mock nonces only — no real secrets ever leave Django).+ // Per-call lifecycle (acquire → invoke → release) so we don't carry+ // session-shaped sandbox state. May split out into `agent-exec` later+ // if execution duties grow enough to crowd out CRUD.+ //+ // In-flight cap: dry-run spawns sandboxes outside the session+ // execution queue, so without a bound a caller with agents:write+ // could exhaust the sandbox backend by hammering this route. A+ // process-wide counter is the right scope — this is an availability+ // guard for the janitor host / shared backend, not per-team fairness+ // (revisit if dry-run traffic ever justifies a per-team quota).+ let dryRunsInFlight = 0+ router.post(+ '/tools/:tool_id/dry_run',+ asyncHandler(async (req, res) => {+ const idCheck = ResourceIdParamSchema.safeParse(req.params.tool_id)+ if (!idCheck.success) {+ res.status(400).json({ error: 'invalid_resource_id', issues: idCheck.error.issues })+ return+ }+ if (!opts.sandboxes) {+ res.status(503).json({ error: 'sandbox_pool_not_configured' })+ return+ }+ if (!(await assertDraft(opts, req.params.id, res))) {+ return+ }+ const parsed = DryRunBodySchema.safeParse(req.body)+ if (!parsed.success) {+ res.status(400).json({ error: 'invalid_request', issues: parsed.error.issues })+ return+ }+ const toolId = idCheck.data++ // Confirm the tool exists in the bundle. We could load and pass+ // through the sandbox, but the explicit check produces a 404+ // instead of a cryptic `tool_not_found` runtime error.+ const compiledPath = toolCompiledPath(toolId)+ const compiledJs = await opts.bundles.readText(req.params.id, compiledPath).catch(() => null)+ if (compiledJs === null) {+ res.status(404).json({ error: 'tool_not_found', tool_id: toolId })+ return+ }+ const schemaText = await opts.bundles.readText(req.params.id, toolSchemaPath(toolId)).catch(() => '{}')+ let schemaJson: unknown = {}+ try {+ schemaJson = JSON.parse(schemaText)+ } catch {+ // Schema is informational at the sandbox boundary; carry on.+ schemaJson = {}+ }++ // We need a teamId for the AcquireOpts contract; the dry-run is+ // tied to the revision's owning team. Revisions don't carry+ // team_id directly — resolve it through the parent application.+ const rev = await opts.revisions.getRevisionRaw(req.params.id)+ if (!rev) {+ res.status(404).json({ error: 'revision_not_found' })+ return+ }+ const app = await opts.revisions.getApplication(rev.application_id)+ if (!app) {+ res.status(404).json({ error: 'application_not_found' })+ return+ }++ const wallMs = opts.dryRunWallMs ?? DEFAULT_DRY_RUN_WALL_MS+ const memoryMb = opts.dryRunMemoryMb ?? DEFAULT_DRY_RUN_MEMORY_MB+ const sessionId = `dry-run-${randomUUID()}`+ const startedAt = Date.now()++ // Build the response in stages so `duration_ms` is captured+ // consistently — after `release()` runs in the finally — on+ // every path (acquire failure, invoke throw, invoke not-ok,+ // invoke ok). Each failure mode gets its own stable `code`+ // so authors can tell infrastructure problems+ // (`sandbox_acquire_failed`) from tool-side problems+ // (`sandbox_invoke_failed`, or the dispatcher's own code on+ // an `ok:false` invoke result like `secret_not_provisioned`+ // / `timeout`).+ let status = 200+ let body: {+ ok: boolean+ result?: unknown+ error?: { code: string; message: string }+ } = { ok: false, error: { code: 'dry_run_unknown', message: 'no response produced' } }+ let sandbox: Awaited<ReturnType<SandboxPool['acquireForSession']>> | undefined++ // Admission control before any sandbox is acquired. 429 (not a+ // queue) — dry-run is interactive; the author just retries.+ const maxConcurrent = opts.dryRunMaxConcurrent ?? DEFAULT_DRY_RUN_MAX_CONCURRENT+ if (dryRunsInFlight >= maxConcurrent) {+ res.status(429).json({ error: 'dry_run_throttled', max_concurrent: maxConcurrent })+ return+ }+ dryRunsInFlight+++ try {+ try {+ sandbox = await opts.sandboxes.acquireForSession({+ sessionId,+ teamId: app.team_id,+ tools: [+ {+ id: toolId,+ compiledJs,+ schemaJson,+ },+ ],+ nonces: parsed.data.mock_secrets ?? {},+ sessionTimeoutMs: wallMs,+ limits: { wallMs, memoryMb },+ })+ } catch (err) {+ status = 500+ body = {+ ok: false,+ error: { code: 'sandbox_acquire_failed', message: (err as Error).message },+ }+ }+ if (sandbox) {+ try {+ const invokeResult = await raceWallClock(+ sandbox.invoke({+ toolId,+ action: 'default',+ args: parsed.data.args,+ timeoutMs: wallMs,+ }),+ wallMs + DRY_RUN_TIMEOUT_GRACE_MS+ )+ if (invokeResult === WALL_CLOCK_EXCEEDED) {+ // Same stable code the dispatcher reports for a+ // cooperative timeout, so authors see one shape.+ // The finally's release destroys the wedged+ // sandbox, which also unblocks the abandoned+ // invoke promise.+ body = {+ ok: false,+ error: {+ code: 'timeout',+ message: `tool did not return within ${wallMs}ms (janitor-side wall clock)`,+ },+ }+ } else {+ body = invokeResult.ok+ ? { ok: true, result: invokeResult.result }+ : { ok: false, error: invokeResult.error }+ }+ } catch (err) {+ status = 500+ body = {+ ok: false,+ error: { code: 'sandbox_invoke_failed', message: (err as Error).message },+ }+ }+ }+ } finally {+ if (sandbox) {+ await opts.sandboxes.release(sessionId).catch(() => {+ // Sandbox release is best-effort cleanup; the sweep+ // reaper catches anything we miss. Don't let a slow+ // release surface as a request failure.+ })+ }+ dryRunsInFlight--+ const durationMs = Date.now() - startedAt+ res.status(status).json({ tool_id: toolId, ...body, duration_ms: durationMs })+ }+ })+ )+return router}diff --git a/products/agent_platform/services/agent-janitor/src/compile-custom-tools.test.ts b/products/agent_platform/services/agent-janitor/src/compile-custom-tools.test.tsindex 2a48e84f9b7f..6101ecae9326 100644--- a/products/agent_platform/services/agent-janitor/src/compile-custom-tools.test.ts+++ b/products/agent_platform/services/agent-janitor/src/compile-custom-tools.test.ts@@ -165,4 +165,179 @@ export default async function run() { return {} }expect(r.errors[0].line).toBeGreaterThan(0)expect(r.errors[0].column).toBeGreaterThan(0)})++ // The compile pipeline does NOT police what modules a tool imports —+ // the sandbox is the security boundary and tools are human-authored.+ // This pins the contract: re-introducing a source-level module ban+ // would break legitimate tools (git via child_process, etc.).+ it.each([+ { mod: 'fs' },+ { mod: 'node:fs' },+ { mod: 'crypto' },+ { mod: 'http' },+ { mod: 'node:net' },+ { mod: 'child_process' },+ { mod: 'worker_threads' },+ { mod: 'vm' },+ ])('compiles a tool importing any node stdlib module: $mod', async ({ mod }) => {+ const src = `+import x from '${mod}'+void x+export default { actions: { default: () => ({ ok: true }) } }+ `.trim()+ const r = await compileTypedTool({ tool_id: 'stdlib-import', source: src })+ expect(r.ok).toBe(true)+ expect(r.errors).toEqual([])+ })++ describe('capability extraction', () => {+ it('collects literal secret names from ctx.secrets.ref()', async () => {+ const src = `+export default {+ actions: {+ default: async (_args: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const a = ctx.secrets.ref('FOO_TOKEN')+ const b = ctx.secrets.ref('BAR_KEY')+ const c = ctx.secrets.ref('FOO_TOKEN') // duplicate, deduped+ return { a, b, c }+ }+ }+}+ `.trim()+ const r = await compileTypedTool({ tool_id: 'caps', source: src })+ expect(r.ok).toBe(true)+ expect(r.capabilities).toEqual({+ secret_refs: ['BAR_KEY', 'FOO_TOKEN'],+ dynamic_secret_refs: false,+ })+ })++ it('flags dynamic secret refs when arg is not a literal', async () => {+ const src = `+export default {+ actions: {+ default: async (args: { name: string }, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ return ctx.secrets.ref(args.name)+ }+ }+}+ `.trim()+ const r = await compileTypedTool({ tool_id: 'caps-dyn', source: src })+ expect(r.ok).toBe(true)+ expect(r.capabilities?.secret_refs).toEqual([])+ expect(r.capabilities?.dynamic_secret_refs).toBe(true)+ })++ it('mixes static and dynamic refs', async () => {+ const src = `+export default {+ actions: {+ default: async (args: { name: string }, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const known = ctx.secrets.ref('KNOWN')+ const dyn = ctx.secrets.ref(args.name)+ return { known, dyn }+ }+ }+}+ `.trim()+ const r = await compileTypedTool({ tool_id: 'caps-mix', source: src })+ expect(r.ok).toBe(true)+ expect(r.capabilities?.secret_refs).toEqual(['KNOWN'])+ expect(r.capabilities?.dynamic_secret_refs).toBe(true)+ })++ it('returns empty capabilities for tools that touch no secrets', async () => {+ const r = await compileTypedTool({ tool_id: 'caps-none', source: GOOD })+ expect(r.ok).toBe(true)+ expect(r.capabilities).toEqual({ secret_refs: [], dynamic_secret_refs: false })+ })++ // Receiver-tightening: non-ctx identifiers must not be treated as a+ // secret reference (over-collection would mislead the UI).+ it('does not pick up secret refs from a non-ctx receiver', async () => {+ const src = `+export default {+ actions: {+ default: async () => {+ const client = { secrets: { ref: (n: string) => 'fake' } }+ return client.secrets.ref('SHOULD_NOT_BE_COLLECTED')+ }+ }+}+ `.trim()+ const r = await compileTypedTool({ tool_id: 'caps-nonctx', source: src })+ expect(r.ok).toBe(true)+ expect(r.capabilities).toEqual({ secret_refs: [], dynamic_secret_refs: false })+ })++ // Conservative dynamic flag: any ctx.secrets access we can't fully+ // resolve to a static ctx.secrets.ref(LITERAL) call must flag+ // dynamic_secret_refs so the UI knows the static list is advisory.+ it.each([+ {+ label: 'aliased ref via local var',+ src: `+export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const r = ctx.secrets.ref+ return r('TOKEN')+ }+ }+}`,+ },+ {+ label: 'destructured ref from ctx.secrets',+ src: `+export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const { ref } = ctx.secrets+ return ref('TOKEN')+ }+ }+}`,+ },+ {+ label: 'destructured secrets from ctx',+ src: `+export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const { secrets } = ctx+ return secrets.ref('TOKEN')+ }+ }+}`,+ },+ {+ label: 'computed property access on secrets',+ src: `+export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ return ctx['secrets']['ref']('TOKEN')+ }+ }+}`,+ },+ {+ label: 'bare ctx.secrets reference (read for side effects)',+ src: `+export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ const s = ctx.secrets+ void s+ return { ok: true }+ }+ }+}`,+ },+ ])('flags dynamic_secret_refs on $label', async ({ src }) => {+ const r = await compileTypedTool({ tool_id: 'caps-alias', source: src.trim() })+ expect(r.ok).toBe(true)+ expect(r.capabilities?.dynamic_secret_refs).toBe(true)+ })+ })})diff --git a/products/agent_platform/services/agent-janitor/src/compile-custom-tools.ts b/products/agent_platform/services/agent-janitor/src/compile-custom-tools.tsindex 741e6f76f000..f56799b0fd5d 100644--- a/products/agent_platform/services/agent-janitor/src/compile-custom-tools.ts+++ b/products/agent_platform/services/agent-janitor/src/compile-custom-tools.ts@@ -1,19 +1,31 @@/**- * Custom-tool upload pipeline: parse → AST shape check → esbuild → emit- * `compiled.js`. Runs inside the `PUT /tools/:id` handler so shape failures- * surface at upload time, not at session-start.+ * Custom-tool upload pipeline: parse → AST shape check → capability walk →+ * esbuild → emit `compiled.js`. Runs inside the `PUT /tools/:id` handler so+ * failures surface at upload time, not at session-start.*- * Two distinct checks:+ * Two AST passes:*- * 1. **AST shape check** — pure source-text analysis via the TypeScript+ * 1. **Shape check** — pure source-text analysis via the TypeScript* compiler API. Walks the syntax tree without executing user code.* Confirms exactly one `export default <ObjectLiteral>` with an* `actions` property whose `default` entry is a function-shaped node.* No `vm.runInContext`, no Modal sandbox — nothing runs, nothing to* sandbox.*- * 2. **esbuild transform** — TS → CJS, the same output the runner has- * loaded since day one. Runs only if the AST check passed.+ * 2. **Capability extraction** — collects metadata the authoring UI+ * surfaces on each tool (secret names referenced via+ * `ctx.secrets.ref(...)`). Best-effort; only static string-literal+ * args are picked up.+ *+ * There is deliberately NO source-level allow/deny list of modules or+ * constructs. The sandbox is the security boundary (Docker+ * `--network=none`, Modal `blockNetwork:true`, `--cap-drop=ALL`), tools are+ * human-authored, and a compile-time ban only limits what authors can build+ * without adding protection. What a tool can *reach* is an infrastructure+ * question, not a lint question — see `docs/custom-tools.md`.+ *+ * If the shape check passes, **esbuild transform** runs (TS → CJS,+ * `node20`, the same output the runner has loaded since day one).** Failures bubble up as structured `ToolCompileError` objects. Each carries* a `kind` discriminator + a one-line `message` the caller (and the@@ -42,12 +54,29 @@ export interface ToolCompileError {column?: number}+/**+ * Capabilities the authoring UI surfaces on each tool. Best-effort: pulled+ * from a static AST walk over the source, so dynamic constructions (a+ * secret name in a variable, computed property access) won't appear. The+ * `dynamic_secret_refs` flag is true when at least one `ctx.secrets.ref()`+ * call had a non-string-literal argument — the author needs to know there+ * are references we couldn't enumerate.+ */+export interface ToolCapabilities {+ /** Distinct secret names referenced via `ctx.secrets.ref('NAME')`. Sorted. */+ secret_refs: string[]+ /** True when at least one `ctx.secrets.ref(...)` call had a non-literal arg. */+ dynamic_secret_refs: boolean+}+export interface CompileTypedToolResult {ok: boolean/** When ok: the CJS-shaped compiled.js the runner will load at session start. */compiled_js?: string/** Always present; empty when ok. */errors: ToolCompileError[]+ /** When ok: best-effort capability metadata for the authoring UI. */+ capabilities?: ToolCapabilities}/**@@ -63,18 +92,20 @@ export async function compileTypedTool(args: { tool_id: string; source: string }ts.ScriptKind.TS)- const astErrors = checkExportShape(sf)- if (astErrors.length > 0) {- return { ok: false, errors: astErrors }+ const shapeErrors = checkExportShape(sf)+ if (shapeErrors.length > 0) {+ return { ok: false, errors: shapeErrors }}+ const capabilities = extractCapabilities(sf)+try {const out = await esbuildTransform(args.source, {loader: 'ts',format: 'cjs',target: 'node20',})- return { ok: true, compiled_js: out.code, errors: [] }+ return { ok: true, compiled_js: out.code, errors: [], capabilities }} catch (err) {return {ok: false,@@ -274,3 +305,142 @@ function findProperty(obj: ts.ObjectLiteralExpression, name: string): ts.Propertfunction isCallable(node: ts.Expression): boolean {return ts.isArrowFunction(node) || ts.isFunctionExpression(node)}++// ─── Capability extraction ──────────────────────────────────────────+//+// Walks the source for `ctx.secrets.ref('NAME')` calls and collects the+// literal secret names. Pure static analysis with two precision dials:+//+// - **Receiver match is tight**: only `ctx.secrets.ref(...)` is collected,+// not `<anyIdent>.secrets.ref(...)`. The convention documented in+// `docs/custom-tools.md` and in the `CustomToolContext` JSDoc names the+// parameter `ctx`. False positives from unrelated `client.secrets.ref`+// SDK chains would mislead the UI; the trade-off is that an author+// renaming `ctx` loses the static list — that case still surfaces via+// the `dynamic_secret_refs` flag below.+//+// - **Dynamic flag is conservative**: set when we see *any* reference to+// `ctx.secrets` that the static collector can't fully resolve — alias+// (`const r = ctx.secrets.ref; r('X')`), destructure (`const {ref} =+// ctx.secrets`), computed access (`ctx['secrets']['ref'](...)`),+// optional chain (`ctx.secrets?.ref(...)`), non-literal `ref(...)` arg.+// A `true` value tells the UI "the static list is incomplete; treat as+// advisory." Silent under-reporting is the failure mode we're avoiding.+//+// Both decisions are tested.++function extractCapabilities(sf: ts.SourceFile): ToolCapabilities {+ const names = new Set<string>()+ let dynamic = false++ /** A `ctx.secrets.ref(...)` call with the exact static receiver shape. */+ function isCtxSecretsRefCall(call: ts.CallExpression): boolean {+ const fn = call.expression+ if (!ts.isPropertyAccessExpression(fn)) {+ return false+ }+ // .ref+ if (!ts.isIdentifier(fn.name) || fn.name.text !== 'ref') {+ return false+ }+ // .secrets+ const inner = fn.expression+ if (!ts.isPropertyAccessExpression(inner)) {+ return false+ }+ if (!ts.isIdentifier(inner.name) || inner.name.text !== 'secrets') {+ return false+ }+ // Receiver must be the literal identifier `ctx`. Other identifiers+ // (`client.secrets.ref` from a third-party SDK) would over-collect.+ return ts.isIdentifier(inner.expression) && inner.expression.text === 'ctx'+ }++ /** Any access to `ctx.secrets` (member, element, optional chain) — the+ * signal that the author touched the secrets surface in a way the+ * static collector may not have captured. */+ function isCtxSecretsAccess(node: ts.Node): boolean {+ // `ctx.secrets` / `ctx?.secrets`+ if (ts.isPropertyAccessExpression(node)) {+ return (+ ts.isIdentifier(node.expression) &&+ node.expression.text === 'ctx' &&+ ts.isIdentifier(node.name) &&+ node.name.text === 'secrets'+ )+ }+ // `ctx['secrets']` / `ctx?.['secrets']`+ if (ts.isElementAccessExpression(node)) {+ return (+ ts.isIdentifier(node.expression) &&+ node.expression.text === 'ctx' &&+ ts.isStringLiteral(node.argumentExpression) &&+ node.argumentExpression.text === 'secrets'+ )+ }+ return false+ }++ /** Destructure of `ctx`: `const { secrets } = ctx` — author pulled+ * `secrets` off `ctx` into a local; downstream `.ref` calls are+ * outside our static collector's receiver shape. */+ function isCtxSecretsDestructure(node: ts.Node): boolean {+ if (!ts.isVariableDeclaration(node)) {+ return false+ }+ if (!node.initializer || !ts.isIdentifier(node.initializer) || node.initializer.text !== 'ctx') {+ return false+ }+ if (!ts.isObjectBindingPattern(node.name)) {+ return false+ }+ for (const el of node.name.elements) {+ // `secrets` or `secrets: <alias>` from the `ctx` object+ const sourceName = el.propertyName ?? el.name+ if (ts.isIdentifier(sourceName) && sourceName.text === 'secrets') {+ return true+ }+ }+ return false+ }++ function visit(node: ts.Node): void {+ if (ts.isCallExpression(node) && isCtxSecretsRefCall(node)) {+ const [arg] = node.arguments+ if (arg && ts.isStringLiteral(arg)) {+ names.add(arg.text)+ } else {+ dynamic = true+ }+ } else if (isCtxSecretsAccess(node)) {+ // Allow the static-call shape to pass without flagging. The+ // `ctx.secrets` in `ctx.secrets.ref(...)` IS a PropertyAccess+ // and would be matched here too — exclude it when its parent+ // is the receiver of a matched static call. Anything else+ // (`ctx.secrets` standalone, `ctx.secrets.foo()`,+ // `ctx['secrets']`, etc.) is an alias / unexpected use → flag.+ const parent = node.parent+ const isStaticRefReceiver =+ parent &&+ ts.isPropertyAccessExpression(parent) &&+ ts.isIdentifier(parent.name) &&+ parent.name.text === 'ref' &&+ parent.parent &&+ ts.isCallExpression(parent.parent) &&+ parent.parent.expression === parent &&+ isCtxSecretsRefCall(parent.parent)+ if (!isStaticRefReceiver) {+ dynamic = true+ }+ } else if (isCtxSecretsDestructure(node)) {+ dynamic = true+ }+ ts.forEachChild(node, visit)+ }++ visit(sf)+ return {+ secret_refs: [...names].sort(),+ dynamic_secret_refs: dynamic,+ }+}diff --git a/products/agent_platform/services/agent-janitor/src/config.ts b/products/agent_platform/services/agent-janitor/src/config.tsindex 6c15ca01d121..310a6bb4f82b 100644--- a/products/agent_platform/services/agent-janitor/src/config.ts+++ b/products/agent_platform/services/agent-janitor/src/config.ts@@ -160,6 +160,72 @@ export const AgentJanitorConfigSchema = PlatformConfigSchema.extend({.string().optional().describe('Optional phs_ bearer for the model-catalog read; /models is otherwise unauthenticated.'),+ // Sandbox config — mirrors the runner's so both services pick up the+ // same SANDBOX_* env vars and end up running the same image. The janitor+ // uses this to back the single-shot dry-run endpoint+ // (`POST /revisions/:id/tools/:id/dry_run`). May split out into a+ // dedicated `agent-exec` service if execution duties grow.+ sandboxBackend: z+ .enum(['docker', 'modal'])+ .optional()+ .transform((v): 'docker' | 'modal' | undefined => v ?? (isDev() ? 'docker' : undefined))+ .describe(+ 'Sandbox pool impl for the dry-run endpoint. Mirrors the runner config (same SANDBOX_BACKEND env var).'+ ),+ sandboxHostImage: z+ .string()+ .optional()+ .transform((v): string | undefined => v ?? (isDev() ? 'posthog/agent-sandbox-host:dev' : undefined))+ .describe(+ 'Canonical agent-sandbox-host image. Defaults to the locally-built `posthog/agent-sandbox-host:dev` under isDev(); prod must set this. Mirrors the runner.'+ ),+ sandboxDockerImage: z+ .string()+ .optional()+ .describe('Backend-specific Docker image override. Takes precedence over `sandboxHostImage`.'),+ sandboxModalImage: z+ .string()+ .optional()+ .describe('Backend-specific Modal image override. Takes precedence over `sandboxHostImage`.'),+ modalAppName: z.string().optional().describe('Optional Modal app name. When unset the Modal SDK uses its default.'),+ modalRegion: z+ .string()+ .optional()+ .describe('Modal region pin (e.g. `us-east`, `eu-west`). Mirrors the runner config.'),+ sandboxOutboundCidrAllowlist: z+ .string()+ .optional()+ .transform((v): string[] =>+ v+ ? v+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ : []+ )+ .describe(+ 'Comma-separated CIDRs the Modal dry-run sandbox may reach outbound. Empty (default) → no outbound network. Mirrors the runner.'+ ),+ dryRunWallMs: z.coerce+ .number()+ .int()+ .positive()+ .default(10_000)+ .describe('Wall-clock cap for a single dry-run invocation.'),+ dryRunMemoryMb: z.coerce+ .number()+ .int()+ .positive()+ .default(256)+ .describe('Memory cap for a single dry-run sandbox.'),+ dryRunMaxConcurrent: z.coerce+ .number()+ .int()+ .positive()+ .default(2)+ .describe(+ 'Max dry-run sandboxes in flight at once, janitor-wide. Requests past the cap get a 429 — dry-run is an interactive authoring surface, not a batch one, so callers retry rather than queue.'+ ),})export type AgentJanitorConfig = z.infer<typeof AgentJanitorConfigSchema>@@ -190,6 +256,16 @@ const ENV_KEY_MAP = extendEnvKeyMap<AgentJanitorConfig>(PLATFORM_ENV_KEY_MAP, {AGENT_BUNDLE_S3_FORCE_PATH_STYLE: 'bundleS3ForcePathStyle',POSTHOG_AI_GATEWAY_URL: 'aiGatewayUrl',POSTHOG_AI_GATEWAY_KEY: 'posthogAiGatewayKey',+ SANDBOX_BACKEND: 'sandboxBackend',+ SANDBOX_HOST_IMAGE: 'sandboxHostImage',+ SANDBOX_DOCKER_IMAGE: 'sandboxDockerImage',+ SANDBOX_MODAL_IMAGE: 'sandboxModalImage',+ MODAL_APP_NAME: 'modalAppName',+ MODAL_REGION: 'modalRegion',+ SANDBOX_OUTBOUND_CIDR_ALLOWLIST: 'sandboxOutboundCidrAllowlist',+ AGENT_DRY_RUN_WALL_MS: 'dryRunWallMs',+ AGENT_DRY_RUN_MEMORY_MB: 'dryRunMemoryMb',+ AGENT_DRY_RUN_MAX_CONCURRENT: 'dryRunMaxConcurrent',})export function loadAgentJanitorConfig(env: NodeJS.ProcessEnv = process.env): AgentJanitorConfig {diff --git a/products/agent_platform/services/agent-janitor/src/index.ts b/products/agent_platform/services/agent-janitor/src/index.tsindex d1c881c69145..9d2fea9e68f7 100644--- a/products/agent_platform/services/agent-janitor/src/index.ts+++ b/products/agent_platform/services/agent-janitor/src/index.ts@@ -38,6 +38,8 @@ import {S3BundleStore,S3JsonlTabularStore,S3MemoryStore,+ SandboxPool,+ selectSandboxPool,TabularStore,} from '@posthog/agent-shared'@@ -165,6 +167,29 @@ async function main(): Promise<void> {http: new DirectHttpClient(),})+ // Single-shot sandbox pool for the dry-run endpoint. Same `selectSandboxPool`+ // impl the runner uses; the janitor just runs it with a per-call lifecycle+ // (acquire → invoke → release inside one HTTP handler) instead of the+ // runner's per-session lifecycle. If execution duties grow enough to+ // crowd out the janitor's CRUD character, the natural next step is to+ // hoist this into a dedicated `agent-exec` service — the abstraction is+ // already in agent-shared, so the split is mechanical.+ let sandboxes: SandboxPool | undefined+ if (config.sandboxBackend) {+ sandboxes = selectSandboxPool({+ backend: config.sandboxBackend,+ sandboxHostImage: config.sandboxHostImage,+ sandboxDockerImage: config.sandboxDockerImage,+ sandboxModalImage: config.sandboxModalImage,+ modalAppName: config.modalAppName,+ modalRegion: config.modalRegion,+ sandboxOutboundCidrAllowlist: config.sandboxOutboundCidrAllowlist,+ })+ log.info({ backend: config.sandboxBackend }, 'sandbox.dry_run.enabled')+ } else {+ log.warn({}, 'sandbox.dry_run.disabled — SANDBOX_BACKEND unset; dry-run endpoint will 503')+ }+const app = buildJanitorApp({queue,sweep,@@ -176,6 +201,10 @@ async function main(): Promise<void> {identityAdmin,gatewayCatalog,internalSigningKey: config.internalSigningKey,+ sandboxes,+ dryRunWallMs: config.dryRunWallMs,+ dryRunMemoryMb: config.dryRunMemoryMb,+ dryRunMaxConcurrent: config.dryRunMaxConcurrent,})app.listen(config.port, () => {log.info({ port: config.port }, 'listening')diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.tsindex 76305392d9f9..cef46553c8a4 100644--- a/products/agent_platform/services/agent-janitor/src/server.ts+++ b/products/agent_platform/services/agent-janitor/src/server.ts@@ -76,6 +76,7 @@ import {previewText,readTypedBundle,RevisionStore,+ SandboxPool,SessionQueue,skillBodyPath,SPEC_SCHEMA_SECTIONS,@@ -135,6 +136,20 @@ export interface JanitorServerOpts {/** Served-model catalog. When set, `validate` + freeze reject a models* the gateway doesn't serve; omitted → the model check is skipped. */gatewayCatalog?: GatewayCatalog+ /**+ * Single-shot sandbox pool backing the `POST /tools/:id/dry_run`+ * endpoint. Same `selectSandboxPool` impl the runner uses; lifecycle is+ * per-call (acquire → invoke → release) rather than per-session. When+ * omitted, the dry-run route 503s. May split into a dedicated+ * `agent-exec` service if execution duties grow.+ */+ sandboxes?: SandboxPool+ /** Wall-clock cap per dry-run invocation. Defaults applied at boot. */+ dryRunWallMs?: number+ /** Memory cap per dry-run sandbox. Defaults applied at boot. */+ dryRunMemoryMb?: number+ /** Max dry-run sandboxes in flight at once. Defaults applied at boot. */+ dryRunMaxConcurrent?: number}const SessionStateSchema = z.enum(['queued', 'running', 'completed', 'closed', 'failed'])@@ -920,7 +935,17 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {// (`/file?path=X`, `/bundle` with `mode`) were removed. The new// surface lives entirely under the typed router below.if (opts.revisions && opts.bundles) {- app.use('/revisions/:id', buildTypedBundleRouter({ revisions: opts.revisions, bundles: opts.bundles }))+ app.use(+ '/revisions/:id',+ buildTypedBundleRouter({+ revisions: opts.revisions,+ bundles: opts.bundles,+ sandboxes: opts.sandboxes,+ dryRunWallMs: opts.dryRunWallMs,+ dryRunMemoryMb: opts.dryRunMemoryMb,+ dryRunMaxConcurrent: opts.dryRunMaxConcurrent,+ })+ )}app.post(diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.tsindex a6274e9ef1bf..865e19072de8 100644--- a/products/agent_platform/services/agent-shared/src/index.ts+++ b/products/agent_platform/services/agent-shared/src/index.ts@@ -16,6 +16,7 @@ export * from './spec/spec-json-schema'export * from './spec/slack-manifest'export * from './spec/summarize-conversation'export * from './spec/tool'+export * from './spec/custom-tool'export * from './spec/framework-preamble'export * from './spec/system-prompt'export * from './spec/trigger-secrets'diff --git a/products/agent_platform/services/agent-shared/src/spec/custom-tool.ts b/products/agent_platform/services/agent-shared/src/spec/custom-tool.tsnew file mode 100644index 000000000000..4d550a6acfb3--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/custom-tool.ts@@ -0,0 +1,114 @@+/**+ * Author-facing contract for custom tools — user-written code an agent can+ * call, sandboxed in a Node process the platform spawns per session.+ *+ * **The sandbox is the security boundary.** The sandbox runs with no network+ * reach (`--network=none` in Docker, `blockNetwork:true` in Modal) and `ctx`+ * is deliberately minimal: a secret-nonce ref + a structured logger. There+ * is no `posthogApiBaseUrl` and no memory/table store access today. In v1 a+ * tool computes over its `args`, optionally consults secret nonces+ * (currently opaque — see note below), logs what it did, and returns+ * structured data the runner threads back to the model. What a tool can+ * reach is decided by the sandbox at runtime — the compile pipeline checks+ * shape, not reach.+ *+ * If an agent needs to call an external API today, use+ * `@posthog/http-request` (a native tool) with a secret pinned to+ * `allowed_hosts` in the spec. The direction of travel is a bridge —+ * `ctx.native(...)` / `ctx.mcp(...)` accessors that let a tool invoke+ * native tools and MCP connections from inside the sandbox — not yet+ * wired; see `docs/custom-tools.md`.+ *+ * **Secret nonces.** `ctx.secrets.ref(name)` returns an opaque per-session+ * nonce string declared in `spec.secrets[]`. The plaintext value never+ * enters the sandbox. Runner-side substitution of nonces at egress is not+ * yet wired (see `services/agent-sandbox-host/src/dispatch.js`), so a+ * returned nonce won't resolve to the real secret today — return values+ * for the runner to act on rather than attempting your own egress.+ *+ * **Authoring shape.** Custom tools are static object literals exported as+ * the file's default. The compile pipeline (see+ * `services/agent-janitor/src/compile-custom-tools.ts`) walks the AST to+ * confirm `export default { actions: { default: fn } }` before the source+ * ever runs. Use the `satisfies CustomTool` pattern below for editor+ * support — type-only imports are stripped at compile so nothing reaches+ * the sandbox runtime.+ *+ * @example+ * import type { CustomTool, CustomToolContext } from '@posthog/agent-shared'+ *+ * type Args = { name: string; count: number }+ *+ * export default {+ * actions: {+ * default: async (args: Args, ctx: CustomToolContext) => {+ * ctx.log('info', 'greeting', { name: args.name })+ * return { greeting: `hi ${args.name} × ${args.count}` }+ * },+ * },+ * } satisfies CustomTool+ */++// `Type`, `Static`, `TSchema` already flow through `@posthog/agent-shared` via+// the native-tool contract (`./tool`). Authors of custom tools import them+// from there, paired with the type-only declarations below.++/**+ * The `ctx` argument a custom-tool action receives at dispatch time.+ *+ * Mirrors the literal object built in `agent-sandbox-host/src/dispatch.js`'s+ * `buildContext` — keep this in lockstep with that file, since drift here+ * silently misleads tool authors about what's reachable in the sandbox.+ */+export interface CustomToolContext {+ /**+ * Per-session secret nonces declared in `spec.secrets[]`. Each `ref`+ * returns an opaque nonce string — the plaintext is never present in the+ * sandbox heap. Throws `secret not provisioned: <name>` if the name+ * isn't declared on the agent.+ */+ secrets: {+ ref(name: string): string+ }+ /**+ * Structured logger. Lines land in the sandbox container's stderr today;+ * ops can read them but the runner doesn't surface them in the session+ * conversation. Use for tracing your tool's internal decisions, not for+ * data the model needs to read — return data from `actions.default` for+ * that.+ */+ log(level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>): void+}++/**+ * Action signature for a custom tool. Receives validated args plus the+ * sandbox `ctx`, returns the result the runner threads back to the model.+ *+ * `args` type comes from the tool's TypeBox schema declared at PUT time+ * (`{description, args_schema, source}`); use `Static<typeof MySchema>` to+ * derive it on the author side.+ */+export type CustomToolAction<TArgs = unknown, TReturn = unknown> = (+ args: TArgs,+ ctx: CustomToolContext+) => TReturn | Promise<TReturn>++/**+ * The default-export shape every custom tool source must conform to.+ *+ * The runner always dispatches `action: "default"` today (see+ * `agent-runner/src/loop/build-agent-tools.ts`'s `makeCustomTool`), so+ * `actions.default` is the only entry the platform calls. Additional named+ * actions are allowed by the schema but unused at runtime — treat them as+ * helpers, not entry points.+ *+ * `id` is optional and informational; the binding id is set by the spec+ * entry (`spec.tools[].id`) when the tool is referenced from an agent.+ */+export interface CustomTool {+ id?: string+ actions: {+ default: CustomToolAction<unknown, unknown>+ [name: string]: CustomToolAction<unknown, unknown>+ }+}diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.tsindex 3c3254c9ce92..f1a80c7d47f7 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts@@ -63,6 +63,9 @@ export function toolCompiledPath(toolId: string): string {export function toolSchemaPath(toolId: string): string {return `tools/${toolId}/schema.json`}+export function toolCapabilitiesPath(toolId: string): string {+ return `tools/${toolId}/capabilities.json`+}// ─── Typed resource shapes ──────────────────────────────────────────@@ -81,6 +84,21 @@ export const TypedSkillSchema = z.object({body: z.string().max(200_000),})+/**+ * Capability metadata the AST walker derives at compile time. Stored on+ * the bundle as `tools/<id>/capabilities.json` so the authoring UI can+ * surface it without re-parsing the source on every read. Optional on the+ * typed shape so old bundles (compiled before capabilities existed) round-+ * trip without warnings — the read path treats a missing file as "no+ * capabilities known."+ */+export const TypedToolCapabilitiesSchema = z.object({+ secret_refs: z.array(z.string()).default([]),+ dynamic_secret_refs: z.boolean().default(false),+})++export type TypedToolCapabilities = z.infer<typeof TypedToolCapabilitiesSchema>+export const TypedToolSchema = z.object({id: ResourceIdSchema,description: z.string().min(1).max(2000),@@ -91,6 +109,12 @@ export const TypedToolSchema = z.object({*/args_schema: z.record(z.string(), z.unknown()),source: z.string().min(1).max(500_000),+ /**+ * Server-stamped at compile time; authors don't set it on the way in.+ * Optional so existing bundles (and write paths that don't have the+ * compile result handy yet) round-trip cleanly.+ */+ capabilities: TypedToolCapabilitiesSchema.optional(),})export type TypedSkill = z.infer<typeof TypedSkillSchema>@@ -231,7 +255,27 @@ export async function readTypedBundle(} catch {warnings.push(`tool ${id} schema.json is not valid JSON`)}- tools.push({ id, description, args_schema: schema, source })++ // Optional capabilities.json — present for tools compiled after the+ // capability extractor landed. Missing/malformed = no capability+ // metadata exposed (rather than failing the bundle read).+ let capabilities: TypedToolCapabilities | undefined+ const capabilitiesPath = toolCapabilitiesPath(id)+ if (paths.has(capabilitiesPath)) {+ const capsText = fileContents.get(capabilitiesPath) ?? '{}'+ try {+ const parsed = TypedToolCapabilitiesSchema.safeParse(JSON.parse(capsText))+ if (parsed.success) {+ capabilities = parsed.data+ } else {+ warnings.push(`tool ${id} capabilities.json failed schema validation`)+ }+ } catch {+ warnings.push(`tool ${id} capabilities.json is not valid JSON`)+ }+ }++ tools.push({ id, description, args_schema: schema, source, capabilities })}return {@@ -346,6 +390,7 @@ export async function syncBundleToStore(willWrite.add(toolSourcePath(tool.id))willWrite.add(toolSchemaPath(tool.id))willWrite.add(toolCompiledPath(tool.id))+ willWrite.add(toolCapabilitiesPath(tool.id))}// Delete anything in the canonical layout that's NOT in the new payload.@@ -381,7 +426,12 @@ export async function writeToolSourceAndSchema(revisionId: string, store: Bundle* Delete one tool's bundle files (source.ts, compiled.js, schema.json).*/export async function deleteToolFiles(revisionId: string, store: BundleStore, toolId: string): Promise<void> {- for (const path of [toolSourcePath(toolId), toolCompiledPath(toolId), toolSchemaPath(toolId)]) {+ for (const path of [+ toolSourcePath(toolId),+ toolCompiledPath(toolId),+ toolSchemaPath(toolId),+ toolCapabilitiesPath(toolId),+ ]) {if (await store.exists(revisionId, path)) {await store.delete(revisionId, path)}diff --git a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.tsindex f437e45aad14..68cadfd718f4 100644--- a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts@@ -450,6 +450,250 @@ describe('typed bundle authoring API: real e2e', () => {expect(res.status).toBe(400)expect(res.body.error).toBe('invalid_resource_id')})++ it('returns capabilities on a successful PUT', async () => {+ const rid = await newDraft(c)+ const res = await request(c.janitor)+ .put(`/revisions/${rid}/tools/caps`)+ .send({+ description: 'caps',+ args_schema: { type: 'object' },+ source: `export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ return { token: ctx.secrets.ref('FOO_TOKEN') }+ }+ }+ }`,+ })+ expect(res.status).toBe(200)+ expect(res.body.capabilities).toEqual({+ secret_refs: ['FOO_TOKEN'],+ dynamic_secret_refs: false,+ })+ })++ it('persists capabilities to the bundle so GET /bundle can surface them', async () => {+ const rid = await newDraft(c)+ await request(c.janitor)+ .put(`/revisions/${rid}/tools/persisted`)+ .send({+ description: 'persisted',+ args_schema: { type: 'object' },+ source: `export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => {+ return { a: ctx.secrets.ref('ALPHA'), b: ctx.secrets.ref('BETA') }+ }+ }+ }`,+ })+ .expect(200)++ // The file lands in the bundle...+ const capsRaw = await c.bundle.readText(rid, 'tools/persisted/capabilities.json')+ expect(JSON.parse(capsRaw)).toEqual({+ secret_refs: ['ALPHA', 'BETA'],+ dynamic_secret_refs: false,+ })++ // ...and round-trips through the typed read so the UI doesn't have+ // to re-run the AST walker on every load.+ const readBack = await request(c.janitor).get(`/revisions/${rid}/bundle`).expect(200)+ const tool = readBack.body.bundle.tools.find((t: { id: string }) => t.id === 'persisted')+ expect(tool.capabilities).toEqual({+ secret_refs: ['ALPHA', 'BETA'],+ dynamic_secret_refs: false,+ })+ })++ it('DELETE /tools/:id sweeps the capabilities.json file too', async () => {+ const rid = await newDraft(c)+ await request(c.janitor)+ .put(`/revisions/${rid}/tools/sweepable`)+ .send({+ description: 'sweepable',+ args_schema: { type: 'object' },+ source: `export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string }, log: Function }) => ({ x: ctx.secrets.ref('X') })+ }+ }`,+ })+ .expect(200)++ expect(await c.bundle.exists(rid, 'tools/sweepable/capabilities.json')).toBe(true)++ await request(c.janitor).delete(`/revisions/${rid}/tools/sweepable`).expect(200)++ expect(await c.bundle.exists(rid, 'tools/sweepable/capabilities.json')).toBe(false)+ expect(await c.bundle.exists(rid, 'tools/sweepable/source.ts')).toBe(false)+ expect(await c.bundle.exists(rid, 'tools/sweepable/compiled.js')).toBe(false)+ })+ })++ // ─── Dry-run: single-shot sandbox execution ─────────────────────+ //+ // Janitor proxies a compiled tool through the same sandbox pool the+ // runner uses, with a per-call lifecycle (acquire → invoke → release+ // in one handler) instead of per-session. The harness wires the same+ // InProcessSandboxPool to both worker + janitor so these cases exercise+ // the real dispatch path.++ describe('POST /tools/:id/dry_run', () => {+ async function putGoodTool(rid: string, id: string, source: string): Promise<void> {+ await request(c.janitor)+ .put(`/revisions/${rid}/tools/${id}`)+ .send({ description: id, args_schema: { type: 'object' }, source })+ .expect(200)+ }++ it('runs the persisted compiled.js with caller-supplied args and returns the result', async () => {+ const rid = await newDraft(c)+ await putGoodTool(+ rid,+ 'echo',+ `export default {+ actions: {+ default: async (args: { name: string }) => ({ greeting: 'hi ' + args.name })+ }+ }`+ )+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/echo/dry_run`)+ .send({ args: { name: 'dylan' } })+ .expect(200)+ expect(res.body.ok).toBe(true)+ expect(res.body.tool_id).toBe('echo')+ expect(res.body.result).toEqual({ greeting: 'hi dylan' })+ expect(typeof res.body.duration_ms).toBe('number')+ })++ it('surfaces a tool-thrown error as ok:false, passing the dispatcher code through', async () => {+ const rid = await newDraft(c)+ await putGoodTool(+ rid,+ 'thrower',+ `export default {+ actions: {+ default: async () => { throw new Error('boom') }+ }+ }`+ )+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/thrower/dry_run`)+ .send({ args: {} })+ .expect(200)+ expect(res.body.ok).toBe(false)+ // The dispatcher catches the throw and returns ok:false with its+ // own structured code (in-process → `exception`; docker/modal →+ // dispatcher-specific). The janitor passes that code through+ // verbatim — it does NOT overwrite with `sandbox_invoke_failed`,+ // because that code is reserved for invocations that threw+ // OUT of the sandbox (infrastructure failure, not tool code).+ expect(res.body.error.code).not.toBe('sandbox_invoke_failed')+ expect(res.body.error.code).not.toBe('sandbox_acquire_failed')+ expect(res.body.error.message).toContain('boom')+ })++ it('captures duration_ms on every path (success, tool-throw)', async () => {+ // Same `duration_ms` contract on both ok:true and ok:false paths —+ // measured after sandbox release in the finally block so the two+ // numbers are comparable.+ const rid = await newDraft(c)+ await putGoodTool(rid, 'fast', GOOD_TOOL_SOURCE)+ await putGoodTool(+ rid,+ 'fast-thrower',+ `export default { actions: { default: async () => { throw new Error('x') } } }`+ )+ const okRes = await request(c.janitor)+ .post(`/revisions/${rid}/tools/fast/dry_run`)+ .send({ args: {} })+ .expect(200)+ const throwRes = await request(c.janitor)+ .post(`/revisions/${rid}/tools/fast-thrower/dry_run`)+ .send({ args: {} })+ .expect(200)+ expect(okRes.body.ok).toBe(true)+ expect(throwRes.body.ok).toBe(false)+ expect(typeof okRes.body.duration_ms).toBe('number')+ expect(typeof throwRes.body.duration_ms).toBe('number')+ expect(okRes.body.duration_ms).toBeGreaterThanOrEqual(0)+ expect(throwRes.body.duration_ms).toBeGreaterThanOrEqual(0)+ })++ it('plumbs mock_secrets into ctx.secrets.ref(name)', async () => {+ const rid = await newDraft(c)+ await putGoodTool(+ rid,+ 'reads-secret',+ `export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string } }) => ({ token: ctx.secrets.ref('FOO_TOKEN') })+ }+ }`+ )+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/reads-secret/dry_run`)+ .send({ args: {}, mock_secrets: { FOO_TOKEN: 'nonce-abc' } })+ .expect(200)+ expect(res.body.ok).toBe(true)+ expect(res.body.result).toEqual({ token: 'nonce-abc' })+ })++ it('returns ok:false when the tool refs an undeclared secret', async () => {+ // The dispatcher (docker / modal) throws `secret not provisioned`;+ // the in-process sandbox throws `secret not bound`. Both share the+ // word `secret`, which is what we actually want to assert here —+ // that the failure surfaces back as a structured error rather than+ // a 500.+ const rid = await newDraft(c)+ await putGoodTool(+ rid,+ 'missing-secret',+ `export default {+ actions: {+ default: async (_a: unknown, ctx: { secrets: { ref(n: string): string } }) => ({ t: ctx.secrets.ref('NOPE') })+ }+ }`+ )+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/missing-secret/dry_run`)+ .send({ args: {} })+ .expect(200)+ expect(res.body.ok).toBe(false)+ expect(res.body.error.message).toMatch(/secret/)+ expect(res.body.error.message).toContain('NOPE')+ })++ it('404s when the tool has never been PUT', async () => {+ const rid = await newDraft(c)+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/never-existed/dry_run`)+ .send({ args: {} })+ .expect(404)+ expect(res.body.error).toBe('tool_not_found')+ })++ it('400s on invalid_resource_id', async () => {+ const rid = await newDraft(c)+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/BadID/dry_run`)+ .send({ args: {} })+ .expect(400)+ expect(res.body.error).toBe('invalid_resource_id')+ })++ it('400s on invalid body (mock_secrets not a string map)', async () => {+ const rid = await newDraft(c)+ await putGoodTool(rid, 'ok', GOOD_TOOL_SOURCE)+ const res = await request(c.janitor)+ .post(`/revisions/${rid}/tools/ok/dry_run`)+ .send({ args: {}, mock_secrets: { FOO: 123 } })+ .expect(400)+ expect(res.body.error).toBe('invalid_request')+ })})// ─── Spec derivation at freeze ───────────────────────────────────diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.tsindex 692112ffeef0..96aed6be444a 100644--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts@@ -485,6 +485,9 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster// (/memory/team/:t/agent/:a/...) read + write through this store and// the runner's `@posthog/memory-*` tools hit the same files.memoryStore,+ // Reuse the same in-process sandbox pool the worker uses so dry-run+ // e2e cases exercise the same dispatch path as production sessions.+ sandboxes,})return {diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yamlindex 433295fa9acc..cb2b7e0a9ead 100644--- a/services/mcp/definitions/agent_platform.yaml+++ b/services/mcp/definitions/agent_platform.yaml@@ -504,6 +504,27 @@ tools:Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist.Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch→ validate → freeze → promote workflow.+ agent-applications-revisions-tools-dry-run-create:+ operation: agent_applications_revisions_tools_dry_run_create+ enabled: true+ scopes:+ - agents:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Dry-run a custom tool+ description: >+ Execute the persisted `compiled.js` for one tool in a single-shot sandbox with caller-supplied args and a+ stubbed ctx — the authoring loop's "test this tool" button. Body `{ args, mock_secrets? }`: `args` is+ free-form JSON (NOT validated against the tool's `args_schema`); `mock_secrets` is an optional `{name →+ placeholder}` map the sandbox plumbs into `ctx.secrets.ref(name)` so the tool body can run without "secret+ not provisioned". The real secret value never enters the sandbox. Returns `{ ok, tool_id, result?, error?,+ duration_ms }`: `ok:true` + `result` when the tool returned cleanly, `ok:false` + `error` when the tool+ threw or the sandbox rejected. Requires the tool to have been PUT first (it runs the persisted bytes, not a+ fresh source). Draft-only. Per-call lifecycle — no warm pool today. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the broader branch → validate → freeze →+ promote workflow.agent-applications-revisions-tools-update:operation: agent_applications_revisions_tools_updateenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5c37ab320f2e..a54969f8ea37 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -711,6 +711,21 @@},"feature_flag": "agent-platform"},+ "agent-applications-revisions-tools-dry-run-create": {+ "description": "Execute the persisted `compiled.js` for one tool in a single-shot sandbox with caller-supplied args and a stubbed ctx — the authoring loop's \"test this tool\" button. Body `{ args, mock_secrets? }`: `args` is free-form JSON (NOT validated against the tool's `args_schema`); `mock_secrets` is an optional `{name → placeholder}` map the sandbox plumbs into `ctx.secrets.ref(name)` so the tool body can run without \"secret not provisioned\". The real secret value never enters the sandbox. Returns `{ ok, tool_id, result?, error?, duration_ms }`: `ok:true` + `result` when the tool returned cleanly, `ok:false` + `error` when the tool threw or the sandbox rejected. Requires the tool to have been PUT first (it runs the persisted bytes, not a fresh source). Draft-only. Per-call lifecycle — no warm pool today. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the broader branch → validate → freeze → promote workflow.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "Dry-run a custom tool",+ "title": "Dry-run a custom tool",+ "required_scopes": ["agents:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "agent-platform"+ },"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. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ecf7955c6322..90407797b809 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -711,6 +711,21 @@},"feature_flag": "agent-platform"},+ "agent-applications-revisions-tools-dry-run-create": {+ "description": "Execute the persisted `compiled.js` for one tool in a single-shot sandbox with caller-supplied args and a stubbed ctx — the authoring loop's \"test this tool\" button. Body `{ args, mock_secrets? }`: `args` is free-form JSON (NOT validated against the tool's `args_schema`); `mock_secrets` is an optional `{name → placeholder}` map the sandbox plumbs into `ctx.secrets.ref(name)` so the tool body can run without \"secret not provisioned\". The real secret value never enters the sandbox. Returns `{ ok, tool_id, result?, error?, duration_ms }`: `ok:true` + `result` when the tool returned cleanly, `ok:false` + `error` when the tool threw or the sandbox rejected. Requires the tool to have been PUT first (it runs the persisted bytes, not a fresh source). Draft-only. Per-call lifecycle — no warm pool today. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the broader branch → validate → freeze → promote workflow.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "Dry-run a custom tool",+ "title": "Dry-run a custom tool",+ "required_scopes": ["agents:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "agent-platform"+ },"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. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d1ca9f65f1f5..e27a67ded101 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8440,6 +8440,25 @@ export namespace Schemas {request_id: string;}+ export interface AgentRevisionDryRunToolError {+ /** Stable error code. `sandbox_acquire_failed` — the platform could not start a sandbox (infrastructure issue, not tool code). `sandbox_invoke_failed` — the sandbox started but the invoke threw uncaught (problem in the tool body, or a runtime error). Dispatcher-side codes come through on `ok:false` invoke results: `timeout`, `secret_not_provisioned`, `action_not_found`, `tool_not_found`. */+ code: string;+ /** One-line human-readable detail. */+ message: string;+ }++ export interface AgentRevisionDryRunToolResponse {+ /** True when the tool's `actions.default` returned without throwing. False when the tool threw or the sandbox rejected the invocation (the structured `error` describes which). */+ ok: boolean;+ /** Echo of the tool id from the URL. */+ tool_id: string;+ /** Present on success — the value the tool's `actions.default` returned. */+ result?: unknown;+ error?: AgentRevisionDryRunToolError;+ /** Wall-clock duration in milliseconds, measured from sandbox acquire to after release. Captured consistently across success, tool-throw, and acquire-failure paths so authors can compare timings between calls. Always present. */+ duration_ms: number;+ }+export interface AgentRevisionEnvKeyStatus {key: string;/** True if the key is present in the env block. The value itself is never returned. */@@ -18159,6 +18178,27 @@ export namespace Schemas {has_draft: boolean;}+ /**+ * Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.+ */+ export type DryRunToolRequestMockSecrets = {[key: string]: string};++ /**+ * Body shape for POST /revisions/<id>/tools/<tool_id>/dry_run/.+ *+ * Executes the persisted compiled.js once in the janitor's single-shot+ * sandbox with caller-supplied args + a stubbed ctx. No real secrets+ * leave Django — `mock_secrets` is a `{name → opaque nonce}` map the+ * sandbox plumbs into `ctx.secrets.ref(name)` so the tool body returns+ * something deterministic to the author.+ */+ export interface DryRunToolRequest {+ /** Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync. */+ args: unknown;+ /** Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox. */+ mock_secrets?: DryRunToolRequestMockSecrets;+ }+/*** * `Up` - Up* * `Down` - Downdiff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.tsindex ad0804a449e9..a143bdebcc6e 100644--- a/services/mcp/src/generated/agent_platform/api.ts+++ b/services/mcp/src/generated/agent_platform/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 36 enabled ops+ * PostHog API - MCP 37 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -755,6 +755,45 @@ export const AgentApplicationsRevisionsToolsDestroyParams = /* @__PURE__ */ zod.tool_id: zod.string().regex(agentApplicationsRevisionsToolsDestroyPathToolIdRegExp),})+/**+ * Execute one persisted custom tool in a single-shot sandbox.+ *+ * Authoring loop's "test this tool" button. The tool's source must+ * already be PUT (compiled.js is what runs); this just invokes it+ * with the caller-supplied args and a stubbed ctx. No real secrets+ * leave Django — `mock_secrets` is a `{name → placeholder}` map.+ */+export const agentApplicationsRevisionsToolsDryRunCreatePathToolIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')++export const AgentApplicationsRevisionsToolsDryRunCreateParams = /* @__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(agentApplicationsRevisionsToolsDryRunCreatePathToolIdRegExp),+})++export const AgentApplicationsRevisionsToolsDryRunCreateBody = /* @__PURE__ */ zod+ .object({+ args: zod+ .unknown()+ .describe(+ "Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync."+ ),+ mock_secrets: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.'+ ),+ })+ .describe(+ "Body shape for POST /revisions/<id>/tools/<tool_id>/dry_run/.\n\nExecutes the persisted compiled.js once in the janitor's single-shot\nsandbox with caller-supplied args + a stubbed ctx. No real secrets\nleave Django — `mock_secrets` is a `{name → opaque nonce}` map the\nsandbox plumbs into `ctx.secrets.ref(name)` so the tool body returns\nsomething deterministic to the author."+ )+/*** Pre-flight checks before freeze + promote: agent.md exists,* every native tool id is registered, every custom tool has itsdiff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.tsindex c32a50cce681..453bb231b466 100644--- a/services/mcp/src/tools/generated/agent_platform.ts+++ b/services/mcp/src/tools/generated/agent_platform.ts@@ -41,6 +41,8 @@ import {AgentApplicationsRevisionsSpecUpdateParams,AgentApplicationsRevisionsSystemPromptParams,AgentApplicationsRevisionsToolsDestroyParams,+ AgentApplicationsRevisionsToolsDryRunCreateBody,+ AgentApplicationsRevisionsToolsDryRunCreateParams,AgentApplicationsRevisionsToolsUpdateBody,AgentApplicationsRevisionsToolsUpdateParams,AgentApplicationsRevisionsValidateCreateParams,@@ -718,6 +720,34 @@ const agentApplicationsRevisionsToolsDestroy = (): ToolBase<},})+const AgentApplicationsRevisionsToolsDryRunCreateSchema = AgentApplicationsRevisionsToolsDryRunCreateParams.omit({+ project_id: true,+}).extend(AgentApplicationsRevisionsToolsDryRunCreateBody.shape)++const agentApplicationsRevisionsToolsDryRunCreate = (): ToolBase<+ typeof AgentApplicationsRevisionsToolsDryRunCreateSchema,+ Schemas.AgentRevisionDryRunToolResponse+> => ({+ name: 'agent-applications-revisions-tools-dry-run-create',+ schema: AgentApplicationsRevisionsToolsDryRunCreateSchema,+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsToolsDryRunCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.args !== undefined) {+ body['args'] = params.args+ }+ if (params.mock_secrets !== undefined) {+ body['mock_secrets'] = params.mock_secrets+ }+ const result = await context.api.request<Schemas.AgentRevisionDryRunToolResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/tools/${encodeURIComponent(String(params.tool_id))}/dry_run/`,+ body,+ })+ return result+ },+})+const AgentApplicationsRevisionsToolsUpdateSchema = AgentApplicationsRevisionsToolsUpdateParams.omit({project_id: true,}).extend(AgentApplicationsRevisionsToolsUpdateBody.shape)@@ -918,6 +948,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'agent-applications-revisions-spec-update': agentApplicationsRevisionsSpecUpdate,'agent-applications-revisions-system-prompt': agentApplicationsRevisionsSystemPrompt,'agent-applications-revisions-tools-destroy': agentApplicationsRevisionsToolsDestroy,+ 'agent-applications-revisions-tools-dry-run-create': agentApplicationsRevisionsToolsDryRunCreate,'agent-applications-revisions-tools-update': agentApplicationsRevisionsToolsUpdate,'agent-applications-revisions-validate-create': agentApplicationsRevisionsValidateCreate,'agent-applications-session-logs': agentApplicationsSessionLogs,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-dry-run-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-dry-run-create.jsonnew file mode 100644index 000000000000..347c0ce08a11--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-tools-dry-run-create.json@@ -0,0 +1,31 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "application_id": {+ "type": "string"+ },+ "args": {+ "description": "Synthetic args the tool's `actions.default` is called with. Free-form JSON; the sandbox doesn't validate against the tool's `args_schema` — that's the author's responsibility to keep in sync."+ },+ "id": {+ "description": "A UUID string identifying this agent revision.",+ "type": "string"+ },+ "mock_secrets": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Optional `{secret_name → placeholder_string}` map. The string is returned verbatim by `ctx.secrets.ref(name)` inside the tool. The real secret value never enters the sandbox.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "tool_id": {+ "pattern": "^[a-z0-9][a-z0-9_-]*$",+ "type": "string"+ }+ },+ "required": ["application_id", "id", "tool_id", "args"],+ "type": "object"+}