: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(tasks): relay agent permission requests to django (#118576)
Chris Volzerc21c733de47b
diff --git a/services/agent-proxy/README.md b/services/agent-proxy/README.mdindex 1576e89fc32a..2523ac5a1428 100644--- a/services/agent-proxy/README.md+++ b/services/agent-proxy/README.md@@ -13,6 +13,8 @@ Budget steer callbacks preserve the original event timestamp and queue analyticsDjango returns 503 if dispatch fails, and the proxy retries the callback once.The capture worker retries analytics upload failures independently of event streaming.+Permission requests and agent questions also trigger a Django callback so interactive runs can notify their creator before the turn completes. Deploy the Django callback support before this proxy change. Older Django versions reject the new `permission_requested` callback, and the proxy drops that notification after logging the rejection.+## Routes| Method | Path | Description |diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex 9b3fadb4914e..54dd5dd69e05 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -32,6 +32,7 @@ import {captureBudgetSteerIfNeeded,captureProcessKilledIfNeeded,heartbeatWorkflowIfNeeded,+ notifyPermissionRequestIfNeeded,} from '../lib/side-effects.js'import {ClientDisconnected,@@ -274,6 +275,15 @@ async function ingestEventLines(result.accepted++result.last_accepted_seq = seqcaptureProcessKilledIfNeeded(claims.runId, seq, event, claims.taskId, claims.teamId, originalToken, config)+ notifyPermissionRequestIfNeeded(+ claims.runId,+ seq,+ event,+ claims.taskId,+ claims.teamId,+ originalToken,+ config+ )await heartbeatWorkflowIfNeeded(redisStream,diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.tsindex 2dab320ce6d9..e0eb81d04b9c 100644--- a/services/agent-proxy/src/lib/side-effects.ts+++ b/services/agent-proxy/src/lib/side-effects.ts@@ -186,11 +186,14 @@ const CALLBACK_TIMEOUT_MS = 10_000const RETRY_DELAY_MS = 1000const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input',+ 'permission_requested','turn_failed','budget_steer','process_killed',])const PROCESS_KILLED_METHOD = '_posthog/process_killed'+const PERMISSION_REQUEST_TYPE = 'permission_request'+const PERMISSION_REQUEST_METHOD = '_posthog/permission_request'interface ProcessKilledPayload {comm: string@@ -251,9 +254,18 @@ function fireCallback(activityStarted?: booleanbudgetSteer?: { sequence: number; timestamp?: string; params: Record<string, unknown> }processKilled?: { sequence: number; payload: ProcessKilledPayload }+ permissionRequest?: { sequence: number; requestId: string }} = {}): void {- const { releaseClaim, turnCompleted, turnSucceeded, activityStarted, budgetSteer, processKilled } = options+ const {+ releaseClaim,+ turnCompleted,+ turnSucceeded,+ activityStarted,+ budgetSteer,+ processKilled,+ permissionRequest,+ } = optionsif (!config.djangoCallbackBaseUrl) {// Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.void releaseMilestoneClaim(releaseClaim, runId, kind)@@ -277,6 +289,7 @@ function fireCallback(}: {}),...(processKilled ? { sequence: processKilled.sequence, process_killed: processKilled.payload } : {}),+ ...(permissionRequest ? { sequence: permissionRequest.sequence, request_id: permissionRequest.requestId } : {}),kind,agent_active: agentActive,task_id: taskId,@@ -412,6 +425,63 @@ export function captureProcessKilledIfNeeded(})}+function asObject(value: unknown): Record<string, unknown> | null {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null+}++function permissionRequestPayload(event: Record<string, unknown>): Record<string, unknown> | null {+ if (event['type'] === PERMISSION_REQUEST_TYPE) {+ return event+ }+ const notification = asObject(event['notification'])+ if (notification === null || notification['method'] !== PERMISSION_REQUEST_METHOD) {+ return null+ }+ return asObject(notification['params'])+}++// permissionRequestId mirrors permission_broker.py:parse_permission_request exactly, so the proxy+// pushes for the same events as the Django ingest. Unlike isTurnComplete and the other ACP+// predicates, the notification shape does not need type 'notification'.+export function permissionRequestId(event: Record<string, unknown>): string | null {+ const payload = permissionRequestPayload(event)+ if (payload === null) {+ return null+ }+ const requestId = payload['requestId']+ const options = payload['options']+ const hasOption =+ Array.isArray(options) &&+ options.some((option) => {+ const optionId = asObject(option)?.['optionId']+ return typeof optionId === 'string' && optionId !== ''+ })+ if (typeof requestId !== 'string' || requestId === '' || asObject(payload['toolCall']) === null || !hasOption) {+ return null+ }+ return requestId+}++export function notifyPermissionRequestIfNeeded(+ runId: string,+ sequence: number,+ event: Record<string, unknown>,+ taskId: string,+ teamId: number,+ originalToken: string,+ config: Config+): void {+ const requestId = permissionRequestId(event)+ if (requestId === null) {+ return+ }+ fireCallback(runId, 'permission_requested', false, taskId, teamId, originalToken, config, {+ permissionRequest: { sequence, requestId },+ })+}+async function releaseMilestoneClaim(release: (() => Promise<void>) | undefined,runId: string,diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex 4da8409af7cb..971fdebb5963 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -177,6 +177,7 @@ export type IngestLine = IngestEventLine | IngestCompleteLineexport type SideEffectKind =| 'heartbeat'| 'awaiting_input'+ | 'permission_requested'| 'turn_failed'| 'command_dispatched'| 'agent_activity'diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 2b2825426b64..0dc609be8280 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -28,7 +28,7 @@ import {} from '@/lib/constants.js'import { logger } from '@/lib/logging.js'import { TaskRunRedisStream, getCompletedKey, getStreamKey, getWatchedKey } from '@/lib/redis-stream.js'-import { heartbeatWorkflowIfNeeded } from '@/lib/side-effects.js'+import { heartbeatWorkflowIfNeeded, notifyPermissionRequestIfNeeded } from '@/lib/side-effects.js'import type { SandboxEventIngestTokenPayload } from '@/lib/types.js'// ---------------------------------------------------------------------------@@ -733,6 +733,46 @@ describe('ingest-handler', () => {}})+ it('reports an accepted permission request once, and skips replays and malformed requests', async () => {+ const callback = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(new Response(JSON.stringify({ dispatched: true }), { status: 200 }))+ try {+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django.example.com' })+ const params = { requestId: 'perm-1', toolCall: { title: 'Run tests' }, options: [{ optionId: 'allow' }] }+ const request = { type: 'notification', notification: { method: '_posthog/permission_request', params } }+ const malformed = {+ type: 'notification',+ notification: { method: '_posthog/permission_request', params: { ...params, options: [] } },+ }+ const lines = [+ { seq: 1, event: request },+ { seq: 1, event: request },+ { seq: 2, event: malformed },+ ]+ for (const line of lines) {+ const response = await handleIngest(+ makeContext({ body: makeStringBody(JSON.stringify(line) + '\n') }),+ fakeRedis as unknown as Redis,+ config,+ [] as CryptoKey[]+ )+ expect(response.status).toBe(200)+ }+ expect(callback).toHaveBeenCalledTimes(1)+ expect(JSON.parse(String(callback.mock.calls[0]![1]?.body))).toMatchObject({+ kind: 'permission_requested',+ agent_active: false,+ task_id: TASK_ID,+ team_id: TEAM_ID,+ sequence: 1,+ request_id: 'perm-1',+ })+ } finally {+ callback.mockRestore()+ }+ })+it('retries a budget steer callback after a temporary capture failure', async () => {const callback = vi.spyOn(globalThis, 'fetch')@@ -1600,6 +1640,13 @@ describe('ingest-handler', () => {type: 'notification',notification: { method: 'session/update', params: { update: { sessionUpdate: 'agent_message_chunk' } } },}+ const permissionRequest = {+ type: 'notification',+ notification: {+ method: '_posthog/permission_request',+ params: { requestId: 'perm-1', toolCall: {}, options: [{ optionId: 'allow' }] },+ },+ }const networkFailure = Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } })it.each([@@ -1608,6 +1655,7 @@ describe('ingest-handler', () => {['awaiting_input', turnComplete, '400', new Response('', { status: 400 }), 1],['turn_failed', piTurnError, 'network failure', networkFailure, 2],['turn_failed', piTurnError, '503', new Response('', { status: 503 }), 2],+ ['permission_requested', permissionRequest, '503', new Response('', { status: 503 }), 2],['heartbeat', sessionUpdate, 'network failure', networkFailure, 1],['heartbeat', sessionUpdate, '503', new Response('', { status: 503 }), 1],])(@@ -1626,6 +1674,7 @@ describe('ingest-handler', () => {await redisStream.claimFirstAgentActivity()const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)+ notifyPermissionRequestIfNeeded(RUN_ID, 1, event, TASK_ID, TEAM_ID, 'tok', config)await vi.advanceTimersByTimeAsync(2000)expect(fetchMock).toHaveBeenCalledTimes(expectedCalls)diff --git a/services/agent-proxy/tests/lib/side-effects.test.ts b/services/agent-proxy/tests/lib/side-effects.test.tsindex 7dbb82a07f8c..15c48119d141 100644--- a/services/agent-proxy/tests/lib/side-effects.test.ts+++ b/services/agent-proxy/tests/lib/side-effects.test.ts@@ -6,6 +6,7 @@ import {isPiTurnError,isSessionUpdate,isTurnComplete,+ permissionRequestId,turnCompletedSuccessfully,} from '../../src/lib/side-effects.js'@@ -17,17 +18,65 @@ const cases = JSON.parse(expect: Record<string, boolean>}[]-// The fixture also carries expectations for predicates only one side has, so-// each side compares the keys it implements.-describe('turn event contract', () => {- it.each(cases)('$name', ({ event, expect: expected }) => {- const actual = {- turn_complete: isTurnComplete(event),- idle_resume: isIdleResumeTurnComplete(event),- pi_error: isPiTurnError(event),- session_update: isSessionUpdate(event),- successful: turnCompletedSuccessfully(event),- }- expect(actual).toEqual(Object.fromEntries(Object.keys(actual).map((key) => [key, expected[key]])))+const PERMISSION_PARAMS = { requestId: 'perm-1', toolCall: { title: 'Run tests' }, options: [{ optionId: 'allow' }] }++function permissionNotification(params: unknown): Record<string, unknown> {+ return { type: 'notification', notification: { method: '_posthog/permission_request', params } }+}++describe('side-effect predicates', () => {+ // The fixture also carries expectations for predicates only one side has, so+ // each side compares the keys it implements.+ describe('turn event contract', () => {+ it.each(cases)('$name', ({ event, expect: expected }) => {+ const actual = {+ turn_complete: isTurnComplete(event),+ idle_resume: isIdleResumeTurnComplete(event),+ pi_error: isPiTurnError(event),+ session_update: isSessionUpdate(event),+ successful: turnCompletedSuccessfully(event),+ }+ expect(actual).toEqual(Object.fromEntries(Object.keys(actual).map((key) => [key, expected[key]])))+ })+ })++ it.each<[string, Record<string, unknown>, string | null]>([+ ['a bare request', { type: 'permission_request', ...PERMISSION_PARAMS }, 'perm-1'],+ ['a notification request', permissionNotification(PERMISSION_PARAMS), 'perm-1'],+ [+ 'a notification request without the notification type',+ { notification: { method: '_posthog/permission_request', params: PERMISSION_PARAMS } },+ 'perm-1',+ ],+ [+ 'a request with one usable option among malformed ones',+ permissionNotification({+ ...PERMISSION_PARAMS,+ options: ['allow', { optionId: '' }, { optionId: 'allow' }],+ }),+ 'perm-1',+ ],+ [+ 'another method',+ { type: 'notification', notification: { method: 'session/update', params: PERMISSION_PARAMS } },+ null,+ ],+ ['an empty request id', permissionNotification({ ...PERMISSION_PARAMS, requestId: '' }), null],+ ['a numeric request id', permissionNotification({ ...PERMISSION_PARAMS, requestId: 7 }), null],+ ['a missing tool call', permissionNotification({ ...PERMISSION_PARAMS, toolCall: undefined }), null],+ ['an array tool call', permissionNotification({ ...PERMISSION_PARAMS, toolCall: [] }), null],+ [+ 'options without a non-empty string optionId',+ permissionNotification({ ...PERMISSION_PARAMS, options: [{ optionId: '' }, { optionId: 1 }, 'allow'] }),+ null,+ ],+ ['array params', permissionNotification([PERMISSION_PARAMS]), null],+ [+ 'a bare type that wraps a notification request',+ { ...permissionNotification(PERMISSION_PARAMS), type: 'permission_request' },+ null,+ ],+ ])('permissionRequestId reads %s as %s', (_label, event, expected) => {+ expect(permissionRequestId(event)).toBe(expected)})})