: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(canvas): add agent request backend (#83018)
Peter Kirkhamdda285d68db4
diff --git a/products/canvas/backend/capabilities.py b/products/canvas/backend/capabilities.pyindex 405e73a49971..42bd34da9cc7 100644--- a/products/canvas/backend/capabilities.py+++ b/products/canvas/backend/capabilities.py@@ -37,6 +37,7 @@ class CapabilityWidening:insights_added: list[str]capture_events_added: list[str]inline_queries_enabled: bool+ agent_requests_enabled: boolnetwork_origins_added: list[str]state_scopes_added: list[str]actions_added: list[str]@@ -47,6 +48,7 @@ class CapabilityWidening:self.insights_addedor self.capture_events_addedor self.inline_queries_enabled+ or self.agent_requests_enabledor self.network_origins_addedor self.state_scopes_addedor self.actions_added@@ -68,6 +70,7 @@ def capability_widening(before: dict | None, after: dict | None) -> CapabilityWiset(after_ph.get("captureEvents") or []) - set(before_ph.get("captureEvents") or [])),inline_queries_enabled=bool(after_ph.get("inlineQueries")) and not bool(before_ph.get("inlineQueries")),+ agent_requests_enabled=bool(after_ph.get("agentRequests")) and not bool(before_ph.get("agentRequests")),network_origins_added=sorted(set(_network_origins(after)) - set(_network_origins(before))),state_scopes_added=sorted(set(after_ph.get("state") or []) - set(before_ph.get("state") or [])),actions_added=sorted(set(after_ph.get("actions") or []) - set(before_ph.get("actions") or [])),diff --git a/products/canvas/backend/error_reports.py b/products/canvas/backend/error_reports.pyindex 43617333c9da..595f791f7d05 100644--- a/products/canvas/backend/error_reports.py+++ b/products/canvas/backend/error_reports.py@@ -138,3 +138,15 @@ def build_fix_prompt("Stage the fix as a DRAFT with `canvas-draft-create` and wait for its build to be ready. ""Do not publish or promote anything: the user reviews the draft and promotes it.")+++def build_agent_request_prompt(canvas: Canvas, prompt: str) -> str:+ """Wrap the viewer-approved request with the canvas draft workflow."""+ return (+ f"A viewer requested a change to canvas {canvas.id}.\n\n"+ f"<canvas-change-request>\n{prompt}\n</canvas-change-request>\n\n"+ "Invoke the `building-canvases` skill and follow its workflow. Read the current source with "+ "`canvas-source-retrieve`. Stage the requested change as a DRAFT with `canvas-draft-create` and wait for "+ "its build to be ready. Do not publish or promote anything: the canvas creator reviews the draft and "+ "promotes it."+ )diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex 45b2e857f135..addf296ba12f 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -154,6 +154,7 @@ class CanvasPostHogCapabilitiesSerializer(serializers.Serializer):"'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),)+ agentRequests = serializers.BooleanField(required=False, default=False)class CanvasNetworkCapabilitiesSerializer(serializers.Serializer):@@ -201,7 +202,14 @@ class CanvasSourceProjectSerializer(serializers.Serializer):capabilities = CanvasCapabilitiesSerializer(required=False,default=lambda: {- "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "actions": []},+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "state": [],+ "actions": [],+ "agentRequests": False,+ },"network": {"origins": []},},help_text=(@@ -576,6 +584,9 @@ class CanvasCapabilityWideningSerializer(serializers.Serializer):inline_queries_enabled = serializers.BooleanField(help_text="True when the draft enables inline queries and the current head does not.")+ agent_requests_enabled = serializers.BooleanField(+ help_text="True when the draft enables requests to the canvas's authoring agent and the current head does not."+ )network_origins_added = serializers.ListField(child=serializers.CharField(),help_text="Network origins the draft newly declares it may reach.",@@ -741,3 +752,27 @@ class CanvasFixRequestResultSerializer(serializers.Serializer):),)task_id = serializers.UUIDField(help_text="The authoring task the fix was routed to.")+++class CanvasAgentRequestSerializer(serializers.Serializer):+ """A viewer-approved request for the canvas's authoring agent."""++ prompt = serializers.CharField(+ max_length=10_000,+ trim_whitespace=False,+ help_text="Exact change request the viewer reviewed and approved in the trusted host dialog.",+ )+++class CanvasAgentRequestResultSerializer(serializers.Serializer):+ """Outcome of routing a canvas change request."""++ request_outcome = serializers.ChoiceField(+ choices=["signaled", "new_run", "already_queued", "reported"],+ help_text=(+ "signaled: the live run received the request. new_run: a fresh run started. "+ "already_queued: an identical run was already starting. reported: a non-creator's request was filed "+ "in the task thread for the creator."+ ),+ )+ task_id = serializers.UUIDField(help_text="Authoring task that received the request or report.")diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 35920ec637a8..0d784b32f2bf 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -34,6 +34,8 @@ from products.canvas.backend.presentation.serializers import (CanvasActionInvokeSerializer,CanvasActionResultSerializer,CanvasActionsResponseSerializer,+ CanvasAgentRequestResultSerializer,+ CanvasAgentRequestSerializer,CanvasBuildActionSerializer,CanvasBuildSerializer,CanvasBuildsResponseSerializer,@@ -167,6 +169,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"request_fix","set_state","invoke_action",+ "request_agent",]def get_throttles(self) -> list[BaseThrottle]:@@ -631,6 +634,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):insight_capability_count=len(posthog_capabilities.get("insights") or []),capture_event_capability_count=len(posthog_capabilities.get("captureEvents") or []),inline_queries_capability=bool(posthog_capabilities.get("inlineQueries")),+ agent_requests_capability=bool(posthog_capabilities.get("agentRequests")),is_sandbox_publish=task_id is not None,)@@ -1052,6 +1056,82 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):status=status.HTTP_202_ACCEPTED,)+ @extend_schema(+ operation_id="canvases_request_agent_create",+ request=CanvasAgentRequestSerializer,+ responses={+ 202: CanvasAgentRequestResultSerializer,+ 403: OpenApiResponse(description="Agent requests are not declared or the caller is a sandbox."),+ 409: OpenApiResponse(description="The canvas has no authoring task."),+ 429: OpenApiResponse(description="The team's compute quota is exhausted; retry later."),+ },+ )+ # task:write as well: the dispatched run executes with the creator's+ # credentials, so canvas:write alone must not be able to start or steer it —+ # consistent with the task-run endpoints themselves.+ @action(methods=["POST"], detail=True, required_scopes=["canvas:write", "task:write"])+ def request_agent(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Route a viewer-approved change request to the canvas's authoring task."""+ canvas = self.get_object()+ if self._is_sandbox_authenticated(request):+ return Response(+ {"detail": "Agent requests must be approved by a viewer."},+ status=status.HTTP_403_FORBIDDEN,+ )+ capabilities = canvas.current_source_version.capabilities if canvas.current_source_version else None+ if not bool(((capabilities or {}).get("posthog") or {}).get("agentRequests")):+ return Response(+ {"detail": "This canvas has not declared agent requests."},+ status=status.HTTP_403_FORBIDDEN,+ )+ payload = CanvasAgentRequestSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ task_id = error_reports.authoring_task_id(canvas, canvas.published_build)+ if task_id is None:+ return Response(+ {"detail": "This canvas has no authoring task to receive the request."},+ status=status.HTTP_409_CONFLICT,+ )+ user = self._request_user()+ outcome = tasks_facade.request_canvas_change(+ task_id,+ self.team_id,+ prompt=error_reports.build_agent_request_prompt(canvas, payload.validated_data["prompt"]),+ viewer_prompt=payload.validated_data["prompt"],+ acting_user_id=user.id if user else None,+ )+ if outcome == "not_found":+ return Response(+ {"detail": "The authoring task for this canvas no longer exists."},+ status=status.HTTP_409_CONFLICT,+ )+ if outcome == "quota_exhausted":+ return Response(+ {"detail": "The team's compute quota is exhausted; retry later."},+ status=status.HTTP_429_TOO_MANY_REQUESTS,+ )+ self._log_canvas_activity(+ canvas,+ "agent_requested",+ Detail(+ name=canvas.name,+ trigger=Trigger(+ job_type="canvas_agent_request",+ job_id=str(task_id),+ payload={"request_outcome": outcome},+ ),+ ),+ )+ self._report_canvas_action(+ "canvas agent requested",+ canvas,+ request_outcome=outcome,+ )+ return Response(+ CanvasAgentRequestResultSerializer(instance={"request_outcome": outcome, "task_id": task_id}).data,+ status=status.HTTP_202_ACCEPTED,+ )+def _canvas_build(self, canvas: Canvas, build_id: UUID) -> CanvasBuild:"""Resolve one of this canvas's builds, or 404."""build = (diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.pyindex d8520640e929..d7ca1e663e6f 100644--- a/products/canvas/backend/source.py+++ b/products/canvas/backend/source.py@@ -85,6 +85,7 @@ _PH_STATE_RE = re.compile(r"\bph\s*\.\s*state\s*\.")_PH_STATE_CALL_RE = re.compile(r"\bph\s*\.\s*state\s*\.\s*(get|set|list)\s*\(")_STATE_SCOPE_LITERAL_RE = re.compile(r"\bscope\s*:\s*[\"']([^\"']+)[\"']")_PH_ACTIONS_RE = re.compile(r"\bph\s*\.\s*actions\s*\.\s*invoke\s*\(\s*(?:[\"']([^\"']+)[\"'])?")+_PH_AGENT_REQUEST_RE = re.compile(r"\bph\s*\.\s*agent\s*\.\s*request\s*\(")_PATH_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._@-]+$")@@ -213,6 +214,7 @@ def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -declared_insights = set(posthog_capabilities.get("insights") or [])declared_events = set(posthog_capabilities.get("captureEvents") or [])inline_queries = bool(posthog_capabilities.get("inlineQueries"))+ agent_requests = bool(posthog_capabilities.get("agentRequests"))declared_state = set(posthog_capabilities.get("state") or [])if not declared_state:@@ -352,6 +354,20 @@ def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -))+ if not agent_requests:+ request_match = _PH_AGENT_REQUEST_RE.search(code)+ if request_match is not None:+ diagnostics.append(+ diagnostic(+ "error",+ "capability_missing_agent_requests",+ "ph.agent.request() requires capabilities.posthog.agentRequests: true — "+ "the host rejects undeclared agent requests at runtime",+ path=path,+ line=_line_of(code, request_match.start()),+ )+ )+return diagnosticsdiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex fefc4f1897d2..79cd5a52fbec 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -891,11 +891,25 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):assert first.status_code == status.HTTP_200_OK, first.json()default_capabilities = {- "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "actions": []},+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "state": [],+ "actions": [],+ "agentRequests": False,+ },"network": {"origins": []},}widened_capabilities = {- "posthog": {"insights": ["abc123"], "inlineQueries": True, "captureEvents": [], "state": [], "actions": []},+ "posthog": {+ "insights": ["abc123"],+ "inlineQueries": True,+ "captureEvents": [],+ "state": [],+ "actions": [],+ "agentRequests": False,+ },"network": {"origins": []},}widened = self._project("export default function C() { return 2 }")@@ -1287,7 +1301,7 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):patcher.start()self.addCleanup(patcher.stop)- def _authored_canvas(self) -> tuple[str, str, Task]:+ def _authored_canvas(self, *, agent_requests: bool = False) -> tuple[str, str, Task]:task = Task.objects.create(team=self.team,channel=self.channel,@@ -1297,7 +1311,18 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):origin_product=Task.OriginProduct.USER_CREATED,)canvas_id = self._create_canvas()- assert self._publish(canvas_id).status_code == status.HTTP_200_OK+ project = self._project()+ if agent_requests:+ project["capabilities"] = {+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "agentRequests": True,+ },+ "network": {"origins": []},+ }+ assert self._publish(canvas_id, project).status_code == status.HTTP_200_OKbuild_id = str(CanvasBuild.objects.unscoped().get(canvas_id=canvas_id).id)Canvas.objects.unscoped().filter(id=canvas_id).update(generation_task_id=task.id)return canvas_id, build_id, task@@ -1316,6 +1341,13 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):format="json",)+ def _request_agent(self, canvas_id: str, prompt: str):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/request_agent/",+ {"prompt": prompt},+ format="json",+ )+def _reports(self, task: Task):return TaskThreadMessage.objects.for_team(self.team.id).filter(task_id=task.id, event="canvas_error_reported")@@ -1385,6 +1417,100 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):assert dispatch.call_args.kwargs["run_id"] == str(run.id)assert dispatch.call_args.kwargs["skip_user_check"] is True+ def test_request_agent_starts_creator_run_with_exact_prompt(self):+ canvas_id, _, task = self._authored_canvas(agent_requests=True)+ prompt = "Make the status card blue."++ with (+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self._request_agent(canvas_id, prompt)++ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()+ assert response.json() == {"request_outcome": "new_run", "task_id": str(task.id)}+ agent_prompt = TaskRun.objects.get(task=task).state["pending_user_message"]+ assert prompt in agent_prompt+ assert "canvas-draft-create" in agent_prompt+ update = TaskThreadMessage.objects.for_team(self.team.id).get(content="Run requested from the canvas")+ assert update.author_id == self.user.id++ def test_scoped_keys_need_task_write_to_request_the_agent(self):+ # The dispatched run executes with the creator's credentials, so a+ # canvas:write-only token must not be able to start or steer it.+ canvas_id, _, _task = self._authored_canvas(agent_requests=True)+ raw_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="canvas-agent", user=self.user, secure_value=hash_key_value(raw_key), scopes=["canvas:write"]+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/request_agent/",+ {"prompt": "Make it blue."},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {raw_key}",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()++ def test_repeat_agent_request_does_not_duplicate_the_thread_entry(self):+ # A deduplicated repeat (already_queued) produced no new run, so it must+ # not add a second "Run requested" record to the author-facing thread.+ canvas_id, _, task = self._authored_canvas(agent_requests=True)++ with (+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"),+ patch("products.tasks.backend.facade.api.signal_task_run_user_message", return_value=False),+ self.captureOnCommitCallbacks(execute=True),+ ):+ first = self._request_agent(canvas_id, "Make it blue.")+ repeat = self._request_agent(canvas_id, "Make it blue.")++ assert first.json()["request_outcome"] == "new_run", first.json()+ assert repeat.json()["request_outcome"] == "already_queued", repeat.json()+ entries = TaskThreadMessage.objects.for_team(self.team.id).filter(content="Run requested from the canvas")+ assert entries.count() == 1++ def test_request_agent_reports_non_creator_request_without_starting_run(self):+ canvas_id, _, task = self._authored_canvas(agent_requests=True)+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.force_login(teammate)++ response = self._request_agent(canvas_id, "Summarize the board.")++ assert response.status_code == status.HTTP_202_ACCEPTED, response.json()+ assert response.json()["request_outcome"] == "reported"+ assert not TaskRun.objects.filter(task=task).exists()+ update = TaskThreadMessage.objects.for_team(self.team.id).get(content__contains="Summarize the board.")+ assert update.author_id == teammate.id+ assert "Summarize the board." in update.content++ def test_request_agent_reports_miss_when_authoring_task_not_visible(self):+ # A teammate can reach the endpoint through a canvas they can see while the+ # authoring task is deleted (and so invisible to them); the request can't be+ # filed, so the endpoint must surface the miss, not report a false delivery.+ canvas_id, _, task = self._authored_canvas(agent_requests=True)+ Task.objects.filter(id=task.id).update(deleted=True)+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.force_login(teammate)++ response = self._request_agent(canvas_id, "Summarize the board.")++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ assert (+ not TaskThreadMessage.objects.for_team(self.team.id)+ .filter(content__contains="Summarize the board.")+ .exists()+ )++ def test_request_agent_requires_declared_capability(self):+ canvas_id, _, _ = self._authored_canvas()++ response = self._request_agent(canvas_id, "Change the canvas.")++ assert response.status_code == status.HTTP_403_FORBIDDEN+def test_request_fix_prompt_never_carries_unsafe_error_type(self):# The requester's error_type flows into the agent prompt; a hostile# value must be coerced, not interpolated.diff --git a/products/canvas/backend/tests/test_capabilities.py b/products/canvas/backend/tests/test_capabilities.pyindex 54962ab5c739..4a97bcd4d754 100644--- a/products/canvas/backend/tests/test_capabilities.py+++ b/products/canvas/backend/tests/test_capabilities.py@@ -5,7 +5,12 @@ from parameterized import parameterizedfrom products.canvas.backend.capabilities import capability_wideningBASE = {- "posthog": {"insights": ["abc"], "captureEvents": ["clicked"], "inlineQueries": False},+ "posthog": {+ "insights": ["abc"],+ "captureEvents": ["clicked"],+ "inlineQueries": False,+ "agentRequests": False,+ },"network": {"origins": []},}WIDER = {@@ -15,11 +20,12 @@ WIDER = {"inlineQueries": True,"state": ["user"],"actions": ["tasks.create"],+ "agentRequests": True,},"network": {"origins": ["https://api.example.com"]},}NARROWER = {- "posthog": {"insights": [], "captureEvents": [], "inlineQueries": False},+ "posthog": {"insights": [], "captureEvents": [], "inlineQueries": False, "agentRequests": False},"network": {"origins": []},}@@ -42,6 +48,7 @@ class TestCapabilityWidening(TestCase):assert widening.insights_added == ["def"]assert widening.capture_events_added == []assert widening.inline_queries_enabled is True+ assert widening.agent_requests_enabled is Trueassert widening.network_origins_added == ["https://api.example.com"]assert widening.state_scopes_added == ["user"]assert widening.actions_added == ["tasks.create"]diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.pyindex 7a21f672203b..2b96751d2964 100644--- a/products/canvas/backend/tests/test_cloud_builder.py+++ b/products/canvas/backend/tests/test_cloud_builder.py@@ -97,6 +97,7 @@ class TestCanvasCloudBuilder(SimpleTestCase):self.assertIn("event.ports[0]", runtime)self.assertIn("port.postMessage", runtime)self.assertIn("port?.postMessage", runtime)+ self.assertIn('agent:{request:(prompt)=>call("agentRequest",{prompt})}', runtime)self.assertIn('event.data?.type==="set-comment-highlights"', runtime)self.assertIn('CSS.highlights.set("posthog-canvas-comment"', runtime)self.assertNotIn("ph-canvas-comment-outline", runtime)diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.pyindex 74967b42a42a..c524a2bd5faa 100644--- a/products/canvas/backend/tests/test_source.py+++ b/products/canvas/backend/tests/test_source.py@@ -195,3 +195,21 @@ class TestCanvasSourceAdapter(SimpleTestCase):entry = next(d for d in validate_source_project(candidate) if d["code"] == "import_not_allowed")self.assertEqual(entry["path"], CANVAS_COMPONENT_PATH)self.assertEqual(entry["line"], 3)++ def test_agent_request_requires_declared_capability(self):+ candidate = project(+ files={CANVAS_COMPONENT_PATH: CODE + 'ph.agent.request("Make it blue");'},+ capabilities={+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "agentRequests": False,+ },+ "network": {"origins": []},+ },+ )++ diagnostics = validate_source_project(candidate)++ self.assertIn("capability_missing_agent_requests", [entry["code"] for entry in diagnostics])diff --git a/products/canvas/frontend/activityDescriber.tsx b/products/canvas/frontend/activityDescriber.tsxindex cc91637adce6..565b5fc12fd6 100644--- a/products/canvas/frontend/activityDescriber.tsx+++ b/products/canvas/frontend/activityDescriber.tsx@@ -11,6 +11,7 @@ interface CanvasPostHogCapabilities {insights?: string[]captureEvents?: string[]inlineQueries?: boolean+ agentRequests?: boolean}function posthogCapabilities(value: unknown): CanvasPostHogCapabilities {@@ -54,6 +55,9 @@ export function describeCapabilitiesChange(change: ActivityChange): Description[if (!!before.inlineQueries !== !!after.inlineQueries) {parts.push(after.inlineQueries ? <>enabled inline queries</> : <>disabled inline queries</>)}+ if (!!before.agentRequests !== !!after.agentRequests) {+ parts.push(after.agentRequests ? <>enabled agent requests</> : <>disabled agent requests</>)+ }return parts}diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex 55d8897942d9..30fe7e1f15b0 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -426,6 +426,7 @@ export interface CanvasPostHogCapabilitiesApi {* @items.maxLength 64*/actions?: string[]+ agentRequests?: boolean}export interface CanvasNetworkCapabilitiesApi {@@ -499,6 +500,8 @@ export interface CanvasCapabilityWideningApi {capture_events_added: string[]/** True when the draft enables inline queries and the current head does not. */inline_queries_enabled: boolean+ /** True when the draft enables requests to the canvas's authoring agent and the current head does not. */+ agent_requests_enabled: boolean/** Network origins the draft newly declares it may reach. */network_origins_added: string[]/** State scopes (user, shared) the draft newly declares for ph.state. */@@ -737,6 +740,47 @@ export interface CanvasErrorReportResultApi {report_outcome: ReportOutcomeEnumApi}+/**+ * A viewer-approved request for the canvas's authoring agent.+ */+export interface CanvasAgentRequestApi {+ /**+ * Exact change request the viewer reviewed and approved in the trusted host dialog.+ * @maxLength 10000+ */+ prompt: string+}++/**+ * * `signaled` - signaled+ * * `new_run` - new_run+ * * `already_queued` - already_queued+ * * `reported` - reported+ */+export type RequestOutcomeEnumApi = (typeof RequestOutcomeEnumApi)[keyof typeof RequestOutcomeEnumApi]++export const RequestOutcomeEnumApi = {+ Signaled: 'signaled',+ NewRun: 'new_run',+ AlreadyQueued: 'already_queued',+ Reported: 'reported',+} as const++/**+ * Outcome of routing a canvas change request.+ */+export interface CanvasAgentRequestResultApi {+ /** signaled: the live run received the request. new_run: a fresh run started. already_queued: an identical run was already starting. reported: a non-creator's request was filed in the task thread for the creator.+ *+ * * `signaled` - signaled+ * * `new_run` - new_run+ * * `already_queued` - already_queued+ * * `reported` - reported */+ request_outcome: RequestOutcomeEnumApi+ /** Authoring task that received the request or report. */+ task_id: string+}+/*** Payload for asking the canvas's authoring agent to fix a failing build or runtime error.*/diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 39f10fa30412..181bb9027fda 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -12,6 +12,8 @@ import type {CanvasActionInvokeApi,CanvasActionResultApi,CanvasActionsResponseApi,+ CanvasAgentRequestApi,+ CanvasAgentRequestResultApi,CanvasApi,CanvasBuildActionApi,CanvasBuildApi,@@ -422,6 +424,27 @@ export const canvasesReportErrorCreate = async (})}+export const getCanvasesRequestAgentCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/request_agent/`+}++/**+ * Route a viewer-approved change request to the canvas's authoring task.+ */+export const canvasesRequestAgentCreate = async (+ projectId: string,+ id: string,+ canvasAgentRequestApi: CanvasAgentRequestApi,+ options?: RequestInit+): Promise<CanvasAgentRequestResultApi> => {+ return apiMutator<CanvasAgentRequestResultApi>(getCanvasesRequestAgentCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasAgentRequestApi),+ })+}+export const getCanvasesRequestFixCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/request_fix/`}diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 39d71b181500..0f4b438ce162 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -107,6 +107,7 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMexport const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -196,6 +197,9 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),}),network: zod.object({origins: zod@@ -311,6 +315,7 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsIteexport const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -402,6 +407,9 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),}),network: zod.object({origins: zod@@ -470,6 +478,20 @@ export const CanvasesReportErrorCreateBody = /* @__PURE__ */ zod}).describe('Payload for reporting a runtime error observed while rendering a canvas build.')+/**+ * Route a viewer-approved change request to the canvas's authoring task.+ */+export const canvasesRequestAgentCreateBodyPromptMax = 10000++export const CanvasesRequestAgentCreateBody = /* @__PURE__ */ zod+ .object({+ prompt: zod+ .string()+ .max(canvasesRequestAgentCreateBodyPromptMax)+ .describe('Exact change request the viewer reviewed and approved in the trusted host dialog.'),+ })+ .describe("A viewer-approved request for the canvas's authoring agent.")+/*** Wake the canvas's authoring agent to fix a failing build or runtime error.*@@ -547,6 +569,7 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItexport const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -636,6 +659,11 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(+ canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault+ ),}),network: zod.object({origins: zoddiff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex cc1df1e8614d..27abf315f1be 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -189,6 +189,9 @@ tools:canvas-report-error-create:operation: canvases_report_error_createenabled: false+ canvas-request-agent-create:+ operation: canvases_request_agent_create+ enabled: falsecanvas-request-fix-create:operation: canvases_request_fix_createenabled: falsediff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjsindex 8a8450d6a7dc..91f432445d10 100644--- a/products/canvas/packages/canvas_builder/build.mjs+++ b/products/canvas/packages/canvas_builder/build.mjs@@ -27,7 +27,7 @@ const runtimePath = 'assets/canvas-runtime.js'// event, which fires after the app's module scripts have already run, so any// ph.* call issued during mount lands before the port exists. Those messages// queue (bounded, in case the host never connects) and flush on connect.-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal,state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal,agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`// A published canvas runs the runtime baked into its artifact by this builder,// while an unpublished one runs the desktop's sandbox document — two copies of// the same selection behavior. The pair below is ported from the desktop'sdiff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 4c6052acb244..7fa736a03949 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -82,7 +82,8 @@ matching shape above. The pattern is a hint; the user's actual request remains afetch or your own PostHog client), and**declare every `ph` call in `project.capabilities`** (insight short ids in`capabilities.posthog.insights`, captured events in `captureEvents`, `inlineQueries: true` for- ad-hoc queries) — the host enforces these at runtime and validation rejects undeclared calls.+ ad-hoc queries, and `agentRequests: true` for `ph.agent.request`) — the host enforces these at+ runtime and validation rejects undeclared calls.3. Follow `validating-and-publishing-canvases`: validate with `canvas-validate-create` as often asneeded and fix every error-severity diagnostic.4. Save the project — which tool depends on whether the canvas is already live:@@ -121,6 +122,13 @@ That field is the only valid link to a canvas — never construct one yourself;`canvases-actions-retrieve` tool and follow each verb's `usage` (payload/result shape,behavior, and the confirmation copy it warrants) before wiring it.+- **`ph.agent.request(prompt)`** — ask the canvas's authoring agent for a change, with the viewer's+ approval. Declare `agentRequests: true` in `capabilities.posthog`. Call it only from a direct+ click or form submission — the host shows the exact prompt and asks the viewer to accept before+ spending compute, and rejects calls made during render, mount, or polling. The agent stages the+ change as a draft for the canvas creator to review; a non-creator's request is filed in the+ authoring task's thread instead of starting a run.+## Source-project shape- Keep `index.html` as the entry shell returned by the source tool.diff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.mdindex 79e7b2e9ff82..79cb901ec40a 100644--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md@@ -38,6 +38,7 @@ then dies in the rendered canvas. Declare:- `capabilities.posthog.insights` — every insight short id the canvas passes to `ph.loadInsight`.- `capabilities.posthog.captureEvents` — every event name it passes to `ph.capture`.- `capabilities.posthog.inlineQueries: true` — when it calls `ph.query` at all.+- `capabilities.posthog.agentRequests: true` — when it calls `ph.agent.request`.Validation rejects undeclared literal calls (`capability_missing_*` diagnostics) so you can fixthem before publishing; dynamic ids it can only warn about, so keep the declarations complete.@@ -52,7 +53,7 @@ Diagnostics carry `severity`, a stable `code`, a `message`, and (for file-specif(bare imports are limited to react, react-dom, @posthog/quill, recharts, lucide-react, and dayjs),`forbidden_dynamic_import` / `forbidden_require` / `forbidden_inline_script`,`invalid_path`, `capability_missing_insight` / `capability_missing_capture_event` /- `capability_missing_inline_queries`,+ `capability_missing_inline_queries` / `capability_missing_agent_requests`,`dependency_not_admitted` / `dependency_version_mismatch`, and path/size violations.- `warning` diagnostics don't block, but heed them: `network_fetch` / `network_xhr` mean the codereaches for the network directly — the sandbox will block it at runtime; use the `ph` bridge.diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 8ea2c7af3145..5b415589c9d7 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -7556,6 +7556,41 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, actingreturn "new_run"+def request_canvas_change(+ task_id: str | UUID,+ team_id: int,+ *,+ prompt: str,+ viewer_prompt: str,+ acting_user_id: int | None,+) -> str:+ """Dispatch a creator's canvas request, or file a teammate's request for review."""+ with transaction.atomic():+ task = Task.objects.select_for_update().filter(id=task_id, team_id=team_id).first()+ if task is None:+ return "not_found"+ if acting_user_id is None:+ return "not_found"+ is_creator = task.created_by_id == acting_user_id+ if not is_creator:+ # A teammate can reach this through a canvas they can see while the authoring+ # task is deleted or filed in a space they can't — the thread message is then+ # dropped, so surface the miss instead of reporting a delivery that didn't happen.+ filed = create_thread_message(+ task_id,+ team_id,+ acting_user_id,+ content=f"Requested from the canvas:\n\n{viewer_prompt}",+ )+ return "reported" if filed is not None else "not_found"+ outcome = request_canvas_fix(task_id, team_id, prompt=prompt, acting_user_id=acting_user_id)+ # already_queued is a deduplicated repeat: the request that queued the run+ # already wrote this entry, so writing another would double the record.+ if outcome in {"signaled", "new_run"}:+ create_thread_message(task_id, team_id, acting_user_id, content="Run requested from the canvas")+ return outcome++def _dispatch_server_run(*, team_id: int, user_id: int | None, task_id: str, run_id: str) -> None:"""Dispatch a server-originated run's processing workflow, bypassing the per-user check.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 000276209d0d..333ecb97338d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14479,6 +14479,48 @@ export namespace Schemas {actions: CanvasActionDefinition[];}+ /**+ * A viewer-approved request for the canvas's authoring agent.+ */+ export interface CanvasAgentRequest {+ /**+ * Exact change request the viewer reviewed and approved in the trusted host dialog.+ * @maxLength 10000+ */+ prompt: string;+ }++ /**+ * * `signaled` - signaled+ * * `new_run` - new_run+ * * `already_queued` - already_queued+ * * `reported` - reported+ */+ export type RequestOutcomeEnum = typeof RequestOutcomeEnum[keyof typeof RequestOutcomeEnum];+++ export const RequestOutcomeEnum = {+ Signaled: 'signaled',+ NewRun: 'new_run',+ AlreadyQueued: 'already_queued',+ Reported: 'reported',+ } as const;++ /**+ * Outcome of routing a canvas change request.+ */+ export interface CanvasAgentRequestResult {+ /** signaled: the live run received the request. new_run: a fresh run started. already_queued: an identical run was already starting. reported: a non-creator's request was filed in the task thread for the creator.+ *+ * * `signaled` - signaled+ * * `new_run` - new_run+ * * `already_queued` - already_queued+ * * `reported` - reported */+ request_outcome: RequestOutcomeEnum;+ /** Authoring task that received the request or report. */+ task_id: string;+ }+/*** One emitted file of a built canvas artifact.*/@@ -14660,6 +14702,7 @@ export namespace Schemas {* @items.maxLength 64*/actions?: string[];+ agentRequests?: boolean;}export interface CanvasNetworkCapabilities {@@ -14688,6 +14731,8 @@ export namespace Schemas {capture_events_added: string[];/** True when the draft enables inline queries and the current head does not. */inline_queries_enabled: boolean;+ /** True when the draft enables requests to the canvas's authoring agent and the current head does not. */+ agent_requests_enabled: boolean;/** Network origins the draft newly declares it may reach. */network_origins_added: string[];/** State scopes (user, shared) the draft newly declares for ph.state. */diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex a5743e578d23..b13e821ee4a1 100644--- a/services/mcp/src/generated/canvas/api.ts+++ b/services/mcp/src/generated/canvas/api.ts@@ -117,6 +117,7 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMexport const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -206,6 +207,9 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),}),network: zod.object({origins: zod@@ -368,6 +372,7 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsIteexport const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -459,6 +464,9 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),}),network: zod.object({origins: zod@@ -568,6 +576,7 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItexport const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = falseexport const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -657,6 +666,11 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod.describe("Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."),+ agentRequests: zod+ .boolean()+ .default(+ canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault+ ),}),network: zod.object({origins: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.jsonindex 37d85f33003e..02623962f7d7 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json@@ -79,6 +79,10 @@"maxItems": 32,"type": "array"},+ "agentRequests": {+ "default": false,+ "type": "boolean"+ },"captureEvents": {"items": {"maxLength": 200,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.jsonindex 126cb9212d30..9567345d1c14 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json@@ -95,6 +95,10 @@"maxItems": 32,"type": "array"},+ "agentRequests": {+ "default": false,+ "type": "boolean"+ },"captureEvents": {"items": {"maxLength": 200,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.jsonindex 8982ca030b75..9850fc0bed15 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json@@ -79,6 +79,10 @@"maxItems": 32,"type": "array"},+ "agentRequests": {+ "default": false,+ "type": "boolean"+ },"captureEvents": {"items": {"maxLength": 200,