: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): cross-project ingress reads + server-side session search (#65480)
Ben White83fe90e50e45
diff --git a/products/agent_platform/backend/logic/janitor_client.py b/products/agent_platform/backend/logic/janitor_client.pyindex 95ab72b1c2fe..56323e6062d5 100644--- a/products/agent_platform/backend/logic/janitor_client.py+++ b/products/agent_platform/backend/logic/janitor_client.py@@ -170,6 +170,7 @@ class JanitorClient:agent_user_id: str | None = None,created_after: str | None = None,created_before: str | None = None,+ search: str | None = None,) -> dict:params: dict[str, Any] = {"application_id": application_id}if limit is not None:@@ -188,6 +189,8 @@ class JanitorClient:params["created_after"] = created_afterif created_before:params["created_before"] = created_before+ if search:+ params["search"] = searchreturn self._call("GET", "/sessions", params=params)def get_session(self, session_id: str, *, last_n: int | None = None) -> dict:diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex aa4dedcacb3b..34f219ce1908 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -1056,6 +1056,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):agent_user_id=request.query_params.get("agent_user_id") or None,created_after=request.query_params.get("created_after") or None,created_before=request.query_params.get("created_before") or None,+ search=request.query_params.get("search") or None,)except JanitorClientError as e:raise JanitorUpstreamError(e) from ediff --git a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts b/products/agent_platform/services/agent-ingress/src/routing/server.test.tsindex 910733dd3868..52671aa5a7ab 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts@@ -1,9 +1,10 @@-import { createHmac } from 'crypto'+import { createHmac, randomUUID } from 'crypto'import { Pool } from 'pg'import request from 'supertest'import {AgentSpecSchema,+ PgApprovalStore,PgCredentialBroker,PgRevisionStore,PgSessionQueue,@@ -12,8 +13,47 @@ import {import type { AgentApplication, AgentRevision } from '@posthog/agent-shared'import { reset } from '@posthog/agent-shared/testing'+import type { AuthProvider } from '../enqueue/auth'+import { buildDefaultVerifiers, type PosthogIdentityIntrospector, type TeamOrgLookup } from '../enqueue/verifiers'import { buildApp } from './server'+// Fake PostHog identity introspection for the principal-authed read routes.+// `owner-token` is a real user on the agent's team (1) / org (org-A);+// `org-peer-token` is a different user in the same org (admitted by an+// `organization`-audience agent, but NOT the session owner). No token → the+// public path yields an anonymous principal.+const OWNER_TOKEN = 'owner-token'+const ORG_PEER_TOKEN = 'org-peer-token'+const testIntrospector: PosthogIdentityIntrospector = {+ async introspect(bearer) {+ if (bearer === OWNER_TOKEN) {+ return { uuid: 'owner', email: 'owner@test', team: { id: 1 }, organization: { id: 'org-A' } }+ }+ if (bearer === ORG_PEER_TOKEN) {+ return { uuid: 'peer', email: 'peer@test', organizations: [{ id: 'org-A' }] }+ }+ return null+ },+ async canAccessTeam(bearer, teamId) {+ return bearer === OWNER_TOKEN && teamId === 1+ },+}+const testTeamOrg: TeamOrgLookup = {+ async orgForTeam(teamId) {+ return teamId === 1 ? 'org-A' : null+ },+}+const noSecret = { resolve: async (): Promise<string | null> => null }+const testAuthProvider: AuthProvider = {+ verifiers: buildDefaultVerifiers({+ introspector: testIntrospector,+ teamOrg: testTeamOrg,+ jwtSecretResolver: noSecret,+ sharedSecretResolver: noSecret,+ internalSecret: 'test-internal',+ }),+}+const TEST_SLACK_SECRET = 'test-slack-secret'const TEST_DB_URL =@@ -64,6 +104,38 @@ async function seedApp(store: PgRevisionStore, slug: string): Promise<{ app: Agereturn { app, rev }}+/**+ * Like {@link seedApp} but the chat trigger requires a PostHog+ * `organization`-audience principal — the agent-builder's auth shape, where any+ * org member may invoke (cross-project) but session ownership is still+ * per-user. Pair with `mk({}, { withAuth: true })`.+ */+async function seedPosthogApp(+ store: PgRevisionStore,+ slug: string+): Promise<{ app: AgentApplication; rev: AgentRevision }> {+ const app = await store.createApplication({ team_id: 1, slug, name: slug, description: '' })+ const rev = await store.createRevision({+ application_id: app.id,+ parent_revision_id: null,+ created_by_id: null,+ bundle_uri: 's3://x/',+ spec: AgentSpecSchema.parse({+ model: 'x',+ triggers: [+ {+ type: 'chat',+ config: {},+ auth: { modes: [{ type: 'posthog', scopes: [], audience: 'organization' }] },+ },+ ],+ }),+ })+ await store.setRevisionState(rev.id, 'live')+ await store.setLiveRevision(app.id, rev.id)+ return { app, rev }+}+describe('ingress HTTP server (path mode)', () => {let pool: Poollet bus: RedisSessionEventBus@@ -86,22 +158,31 @@ describe('ingress HTTP server (path mode)', () => {await pool.end()})- function mk(routing?: { routingMode: 'domain' | 'path'; domainSuffix?: string }): {+ function mk(+ routing?: { routingMode: 'domain' | 'path'; domainSuffix?: string },+ opts?: { withAuth?: boolean }+ ): {revisions: PgRevisionStorequeue: PgSessionQueue+ approvals: PgApprovalStorebus: RedisSessionEventBusapp: ReturnType<typeof buildApp>} {const revisions = new PgRevisionStore(pool)const queue = new PgSessionQueue(pool)+ const approvals = new PgApprovalStore(pool)const credentialBroker = new PgCredentialBroker(pool, {encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS,})const app = buildApp({revisions,queue,+ approvals,bus,credentialBroker,+ // Opt in to the PostHog identity verifiers for the principal-authed+ // read-route tests; default stays public-only like the rest.+ ...(opts?.withAuth ? { authProvider: testAuthProvider } : {}),routingMode: routing?.routingMode ?? 'path',domainSuffix: routing?.domainSuffix,pathPrefix: '/agents',@@ -115,7 +196,7 @@ describe('ingress HTTP server (path mode)', () => {},},})- return { revisions, queue, bus, app }+ return { revisions, queue, approvals, bus, app }}it('GET /healthz returns ok', async () => {@@ -692,4 +773,177 @@ describe('ingress HTTP server (path mode)', () => {expect(res.status).toBe(400)expect(res.body.error).toBe('invalid_json')})++ // Principal-authed read routes — the inline approval card + transcript reload+ // fetch straight from the ingress (cross-project), gated by principal-match.+ // The owner reads their own session; a same-org peer can't; and a public+ // (anonymous) caller is refused outright — `principalsMatch` treats all+ // anonymous principals as equal, so it can't gate a public agent.++ async function queueApproval(+ approvals: PgApprovalStore,+ opts: { sessionId: string; appId: string; revId: string; type: 'principal' | 'agent' }+ ): Promise<string> {+ const id = randomUUID()+ await approvals.upsertQueued({+ id,+ session_id: opts.sessionId,+ application_id: opts.appId,+ team_id: 1,+ revision_id: opts.revId,+ turn: 0,+ tool_call_id: 'tc-1',+ tool_name: 'danger',+ proposed_args: { x: 1 },+ assistant_message: { role: 'assistant', content: [{ type: 'text', text: '' }], timestamp: Date.now() },+ approver_scope: { type: opts.type, allow_edit: false },+ is_preview: false,+ expires_at: new Date(Date.now() + 60_000).toISOString(),+ })+ return id+ }++ it('GET /sessions/:id returns the transcript for the session principal', async () => {+ const { revisions, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'sess')+ const run = await request(app)+ .post('/agents/sess/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'hello' })+ const res = await request(app)+ .get(`/agents/sess/sessions/${run.body.session_id}`)+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(200)+ expect(res.body.id).toBe(run.body.session_id)+ expect(res.body.conversation).toHaveLength(1)+ expect(res.body.conversation_trimmed).toBe(false)+ })++ // The security property the whole feature rests on: a public-auth agent+ // hands every caller the same anonymous principal, so the read routes MUST+ // refuse it — otherwise any anonymous caller could read any session by id.+ it('GET /sessions/:id refuses an anonymous (public-auth) caller', async () => {+ const { revisions, app } = mk()+ await seedApp(revisions, 'pubsess')+ const run = await request(app).post('/agents/pubsess/run').send({ message: 'secret' })+ const res = await request(app).get(`/agents/pubsess/sessions/${run.body.session_id}`)+ expect(res.status).toBe(403)+ expect(res.body.error).toBe('forbidden')+ })++ it('GET /sessions/:id refuses a same-org peer who is not the session owner', async () => {+ const { revisions, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'sesspeer')+ const run = await request(app)+ .post('/agents/sesspeer/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'hello' })+ const res = await request(app)+ .get(`/agents/sesspeer/sessions/${run.body.session_id}`)+ .set('Authorization', `Bearer ${ORG_PEER_TOKEN}`)+ expect(res.status).toBe(403)+ expect(res.body.error).toBe('not_session_principal')+ })++ it('GET /sessions/:id 404s an unknown session', async () => {+ const { revisions, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'sess404')+ const res = await request(app)+ .get(`/agents/sess404/sessions/${randomUUID()}`)+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(404)+ })++ // Regression: `slice(-0)` is `slice(0)` (the whole array), so `last_n=0` must+ // fall through to the untrimmed branch — not return zero messages.+ it('GET /sessions/:id?last_n=0 returns the full transcript, untrimmed', async () => {+ const { revisions, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'sess0')+ const run = await request(app)+ .post('/agents/sess0/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'hello' })+ const res = await request(app)+ .get(`/agents/sess0/sessions/${run.body.session_id}?last_n=0`)+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(200)+ expect(res.body.conversation).toHaveLength(1)+ expect(res.body.conversation_trimmed).toBe(false)+ })++ it('GET /sessions/:id?last_n trims to the trailing messages', async () => {+ const { revisions, queue, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'sesstrim')+ const run = await request(app)+ .post('/agents/sesstrim/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'one' })+ const sid = run.body.session_id+ await queue.appendConversation(sid, {+ role: 'assistant',+ content: [{ type: 'text', text: 'two' }],+ timestamp: Date.now(),+ })+ const res = await request(app)+ .get(`/agents/sesstrim/sessions/${sid}?last_n=1`)+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(200)+ expect(res.body.conversation).toHaveLength(1)+ expect(res.body.conversation_trimmed).toBe(true)+ expect(res.body.conversation_total_turns).toBe(2)+ })++ it('GET /approvals/:id returns a queued principal approval for the owner', async () => {+ const { revisions, approvals, app } = mk(undefined, { withAuth: true })+ const { app: seeded, rev } = await seedPosthogApp(revisions, 'appr')+ const run = await request(app)+ .post('/agents/appr/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'do it' })+ const id = await queueApproval(approvals, {+ sessionId: run.body.session_id,+ appId: seeded.id,+ revId: rev.id,+ type: 'principal',+ })+ const res = await request(app).get(`/agents/appr/approvals/${id}`).set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(200)+ expect(res.body.id).toBe(id)+ expect(res.body.tool_name).toBe('danger')+ expect(res.body.approver_scope).toEqual({ type: 'principal', allow_edit: false })+ })++ it('GET /approvals/:id refuses an anonymous (public-auth) caller', async () => {+ const { revisions, approvals, app } = mk()+ const { app: seeded, rev } = await seedApp(revisions, 'pubappr')+ const run = await request(app).post('/agents/pubappr/run').send({ message: 'do it' })+ const id = await queueApproval(approvals, {+ sessionId: run.body.session_id,+ appId: seeded.id,+ revId: rev.id,+ type: 'principal',+ })+ const res = await request(app).get(`/agents/pubappr/approvals/${id}`)+ expect(res.status).toBe(403)+ expect(res.body.error).toBe('forbidden')+ })++ it('GET /approvals/:id 404s an agent-scope row (console-only surface)', async () => {+ const { revisions, approvals, app } = mk(undefined, { withAuth: true })+ const { app: seeded, rev } = await seedPosthogApp(revisions, 'appragent')+ const run = await request(app)+ .post('/agents/appragent/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'do it' })+ const id = await queueApproval(approvals, {+ sessionId: run.body.session_id,+ appId: seeded.id,+ revId: rev.id,+ type: 'agent',+ })+ const res = await request(app)+ .get(`/agents/appragent/approvals/${id}`)+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ expect(res.status).toBe(404)+ })})diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.tsindex 19dfa6f24d22..45b303b1e326 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts@@ -25,6 +25,7 @@ import {handleMetricsRequest,isDev,RevisionStore,+ serializeApprovalRequest,type SessionPrincipal,SessionQueue,triggerAuthConfig,@@ -188,6 +189,17 @@ async function authenticatePrincipalDecider(return null}+/**+ * A real, identifiable caller — not the shared `anonymous` principal a+ * public-auth agent hands every caller. `principalsMatch` treats all anonymous+ * principals as equal, so it's no gate on a public agent: the principal-authed+ * read surfaces (transcript, approval detail) require an identified principal,+ * else one anonymous caller could read another anonymous session's data.+ */+function isIdentifiedPrincipal(p: SessionPrincipal): boolean {+ return p.kind !== 'anonymous'+}+/** Stable id of the decider, by principal kind — stored as the approval's `decided_by`. */function principalDeciderId(p: SessionPrincipal): string {switch (p.kind) {@@ -421,6 +433,100 @@ export function buildApp(opts: BuildAppOpts): Express {}))+ // Read side of the principal-decision surface — the deep-link approval modal+ // fetches one approval straight from the ingress, authenticated as the session+ // principal, so it never touches the project-scoped Django endpoint. This is+ // what makes the approval loop work from any project (the ingress is+ // slug-routed, the row is resolved under the route's resolved application).+ // The inline chat card doesn't use this — it's fed by `approval_required` /+ // `approval_resolved` frames on `/listen` (push, no poll). Only+ // principal-decidable rows are returned — `agent`-scope stays in the console.+ const respondWithApproval = async (req: Request, res: Response): Promise<void> => {+ if (!opts.approvals) {+ res.status(500).json({ error: 'approvals_not_configured' })+ return+ }+ const resolved = await resolveAgent(resolver, req, res)+ if (!resolved) {+ return+ }+ // Tenant-scope the lookup to the resolved application so a leaked id can't+ // resolve another agent's request; `agent`-scope collapses to not-found,+ // exactly as the decide route does.+ const row = await opts.approvals.getForApplication(req.params.id, resolved.application.id)+ if (!row || effectiveApprovalType(row.approver_scope) === 'agent') {+ res.status(404).json({ error: 'not_found' })+ return+ }+ const session = await opts.queue.getForApplication(row.session_id, resolved.application.id)+ if (!session) {+ res.status(404).json({ error: 'not_found' })+ return+ }+ const caller = await authenticatePrincipalDecider(req, resolved.application, resolved.revision, authProvider)+ if (!caller) {+ res.status(401).json({ error: 'unauthenticated' })+ return+ }+ if (!isIdentifiedPrincipal(caller)) {+ res.status(403).json({ error: 'forbidden' })+ return+ }+ if (!principalsMatch(session.principal, caller)) {+ res.status(403).json({ error: 'not_session_principal' })+ return+ }+ res.json(serializeApprovalRequest(row))+ }+ app.get(`${mount}/approvals/:id`, asyncHandler(respondWithApproval))++ // Transcript reload, principal-authed: "prove you own the session" lets a+ // client rehydrate a session's conversation from any project (the dock on+ // reopen, a web chat-list opening a past session, repainting a pending+ // approval card after a reconnect). Mirrors the janitor session-detail shape+ // (`AgentApplicationSessionDetail`) so the same client mapper consumes it,+ // including the optional `?last_n=` tail. Read-only — does not attach to or+ // resume the live `/listen` stream; that stays a separate concern.+ const respondWithSession = async (req: Request, res: Response): Promise<void> => {+ const resolved = await resolveAgent(resolver, req, res)+ if (!resolved) {+ return+ }+ const session = await opts.queue.getForApplication(req.params.id, resolved.application.id)+ if (!session) {+ res.status(404).json({ error: 'not_found' })+ return+ }+ const caller = await authenticatePrincipalDecider(req, resolved.application, resolved.revision, authProvider)+ if (!caller) {+ res.status(401).json({ error: 'unauthenticated' })+ return+ }+ if (!isIdentifiedPrincipal(caller)) {+ res.status(403).json({ error: 'forbidden' })+ return+ }+ if (!principalsMatch(session.principal, caller)) {+ res.status(403).json({ error: 'not_session_principal' })+ return+ }+ const lastNRaw = typeof req.query.last_n === 'string' ? Number.parseInt(req.query.last_n, 10) : undefined+ // `> 0`, not `>= 0`: `slice(-0)` is `slice(0)` (the whole array), so a+ // `last_n=0` must fall through to the no-trim branch, not "return zero".+ const lastN = lastNRaw !== undefined && Number.isFinite(lastNRaw) && lastNRaw > 0 ? lastNRaw : undefined+ if (lastN !== undefined && lastN < session.conversation.length) {+ res.json({+ ...session,+ conversation: session.conversation.slice(-lastN),+ conversation_total_turns: session.conversation.length,+ conversation_trimmed: true,+ })+ return+ }+ res.json({ ...session, conversation_trimmed: false })+ }+ app.get(`${mount}/sessions/:id`, asyncHandler(respondWithSession))+// Self-describing schemas. The response cascades from `spec.triggers` ∩// `TRIGGER_MODULES`: only modules whose type is configured on this agent// appear, and each route is rendered with its auth concretely resolveddiff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.tsindex e02b292363b7..e5ea1a2671a2 100644--- a/products/agent_platform/services/agent-janitor/src/server.test.ts+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts@@ -194,6 +194,49 @@ describe('janitor HTTP', () => {)})+ it('GET /sessions?search matches external_key case-insensitively, not the transcript', async () => {+ const { queue, app } = mk()+ await queue.enqueue({+ ...session('s-deploy'),+ application_id: uuidFor('app-1'),+ external_key: 'slack:CWIDGET',+ conversation: [{ role: 'user', content: 'can you deploy the gadget service?', timestamp: 1 }],+ })+ await queue.enqueue({+ ...session('s-unrelated'),+ application_id: uuidFor('app-1'),+ external_key: 'slack:C999',+ conversation: [{ role: 'user', content: 'mentions WIDGET in the transcript only', timestamp: 1 }],+ })+ // external_key match, case-insensitive.+ const byKey = await request(app)+ .get('/sessions')+ .query({ application_id: uuidFor('app-1'), search: 'widget' })+ expect((byKey.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-deploy')])+ expect(byKey.body.count).toBe(1)+ // id match.+ const byId = await request(app)+ .get('/sessions')+ .query({ application_id: uuidFor('app-1'), search: uuidFor('s-unrelated') })+ expect((byId.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-unrelated')])+ // No match → empty, not an error.+ const none = await request(app)+ .get('/sessions')+ .query({ application_id: uuidFor('app-1'), search: 'zzz-nope' })+ expect(none.body.results).toHaveLength(0)+ expect(none.body.count).toBe(0)+ })++ it('GET /sessions?search treats LIKE metacharacters literally', async () => {+ const { queue, app } = mk()+ await queue.enqueue({ ...session('s-pct'), application_id: uuidFor('app-1'), external_key: 'batch-50%-run' })+ await queue.enqueue({ ...session('s-plain'), application_id: uuidFor('app-1'), external_key: 'batch-50-run' })+ const res = await request(app)+ .get('/sessions')+ .query({ application_id: uuidFor('app-1'), search: '50%' })+ expect((res.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-pct')])+ })+it('GET /sessions summaries include preview + usage_total off the persisted column', async () => {const { queue, app } = mk()await queue.enqueue({diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.tsindex 4cd422cd78a4..fe36afbf17b0 100644--- a/products/agent_platform/services/agent-janitor/src/server.ts+++ b/products/agent_platform/services/agent-janitor/src/server.ts@@ -143,6 +143,7 @@ const ListSessionsQuerySchema = z.object({agent_user_id: z.string().optional(),created_after: z.string().optional(),created_before: z.string().optional(),+ search: z.string().optional(),})const GetSessionQuerySchema = z.object({@@ -401,6 +402,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {agentUserId: q.agent_user_id,createdAfter: q.created_after,createdBefore: q.created_before,+ search: q.search,}const [sessions, count] = await Promise.all([opts.queue.listByApplication(q.application_id, { ...filter, limit: q.limit, offset: q.offset }),diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.tsindex 9b4fdb689e64..ccf8554d9ca1 100644--- a/products/agent_platform/services/agent-runner/src/index.ts+++ b/products/agent_platform/services/agent-runner/src/index.ts@@ -284,11 +284,13 @@ async function main(): Promise<void> {approvals,// Clickable deep link that opens the approval in PostHog Code (the agent// console now lives in the desktop/web app). Surfaced to the model on a- // gated tool call and whatever it posts to chat / Slack. The approval- // request id alone resolves the approval in the fleet inbox, so the link- // needs nothing more. Handled by the `approval` deep-link key in- // PostHog Code (posthog-code://approval/<id>).- buildApprovalUrl: (requestId) => `${config.approvalLinkScheme}://approval/${requestId}`,+ // gated tool call and whatever it posts to chat / Slack. Carries the+ // agent slug (`?agent=<slug>`) so the approval modal can address the+ // slug-routed ingress directly and decide under the user's own auth — no+ // project-scoped lookup. Handled by the `approval` deep-link key in+ // PostHog Code (posthog-code://approval/<id>?agent=<slug>).+ buildApprovalUrl: (requestId, slug) =>+ `${config.approvalLinkScheme}://approval/${requestId}${slug ? `?agent=${encodeURIComponent(slug)}` : ''}`,bus,logs: logSink,resolveSecrets,diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.ts b/products/agent_platform/services/agent-runner/src/loop/approval.tsindex 2db4eef38c6e..0e6a090e936c 100644--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts@@ -117,6 +117,12 @@ export async function queueApprovalResult(input: {const approval: Record<string, unknown> = {request_id: upsert.request.id,state: 'queued',+ // The inline approval card renders straight from this envelope (live+ // `tool_result` + persisted transcript on reload) — no extra fetch. It+ // needs the edit affordance and whether it's decidable inline+ // (`principal`) or console-only (`agent`); neither is on the tool_call.+ allow_edit: input.policy.allow_edit,+ approver_scope: { type: input.policy.type },}if (!suppressApprovalChannel) {approval.approver_hint = input.policy.type === 'agent' ? APPROVER_HINT_AGENT : APPROVER_HINT_PRINCIPAL@@ -128,7 +134,13 @@ export async function queueApprovalResult(input: {return {content: [{ type: 'text', text: JSON.stringify({ approval }) }],- details: { queued: true, requestId: upsert.request.id, deduped: upsert.deduped },+ details: {+ queued: true,+ requestId: upsert.request.id,+ deduped: upsert.deduped,+ allowEdit: input.policy.allow_edit,+ approverType: input.policy.type,+ },terminate: false,}}diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.tsindex c057114716b3..328ca6d6e14c 100644--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts@@ -31,6 +31,7 @@ import type { TSchema } from '@earendil-works/pi-ai'import {AgentRevision,AgentSession,+ type ApprovalType,BundleStore,CredentialBroker,getSecretAllowedHosts,@@ -71,6 +72,15 @@ export interface ToolResultDetails {requestId?: string/** True when the queue deduped onto an existing row (no new request). */deduped?: boolean+ /**+ * Approval policy on the queued row, when `queued`. Surfaced so the live+ * `tool_result` SSE event carries the same `approval` shape the persisted+ * synthetic result does — the inline card needs `allow_edit` (edit+ * affordance) and `approver_scope.type` (decidable inline vs console-only),+ * and neither is derivable from the tool_call alone.+ */+ allowEdit?: boolean+ approverType?: ApprovalType}/**diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex 34eb0e0990fd..33235a99aecc 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -656,7 +656,19 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// session conversation shows on reload. Without// this the client sees only `ok`/`error`.output: event.isError ? undefined : (details?.output ?? null),- ...(details?.queued ? { approval: { request_id: details.requestId, state: 'queued' } } : {}),+ // Mirror the persisted synthetic envelope so a live viewer+ // and a reload-from-transcript viewer build the same card+ // (request id, edit affordance, principal-vs-agent scope).+ ...(details?.queued+ ? {+ approval: {+ request_id: details.requestId,+ state: 'queued',+ allow_edit: details.allowEdit,+ approver_scope: { type: details.approverType },+ },+ }+ : {}),})// A queued gated call didn't really execute — no span for it// (the approved dispatch emits its own span on resume).diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex c6752754769a..4cb67d54d0c6 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -150,9 +150,11 @@ export interface WorkerDeps {approvals: ApprovalStore/*** Builds the deep link the synthetic queued tool_result surfaces to- * the model. Wire from config so prod hits the real domain.+ * the model. Wire from config so prod hits the real domain. Takes the+ * agent slug so the link can carry `?agent=<slug>` — the deep-link+ * approval modal needs it to address the (slug-routed) ingress directly.*/- buildApprovalUrl?: (requestId: string) => string+ buildApprovalUrl?: (requestId: string, slug: string) => string/*** S3-backed memory store for `@posthog/memory-*` tools. Wired from* AGENT_MEMORY_S3_* config; unset disables memory tools.@@ -523,6 +525,10 @@ export class Worker {const apiKey = await this.deps.resolveApiKey?.(session)const gatewayHeaders = this.deps.resolveGatewayHeaders?.(session)const gatewayUsage = await this.deps.resolveGatewayUsage?.(session)+ // Bind the agent slug into the approval-link builder so the deep link+ // carries `?agent=<slug>` — the ingress-routed approval modal needs it+ // to address the agent's ingress directly.+ const buildApprovalUrl = this.deps.buildApprovalUrlconst outcome = await runSession(rev, session, {model,apiKey,@@ -540,7 +546,9 @@ export class Worker {gatewayHeaders,gatewayUsage,approvals: this.deps.approvals,- buildApprovalUrl: this.deps.buildApprovalUrl,+ buildApprovalUrl: buildApprovalUrl+ ? (requestId) => buildApprovalUrl(requestId, application?.slug ?? '')+ : undefined,memoryStore: this.deps.memoryStore,tabularStore: this.deps.tabularStore,credentialBroker: this.deps.credentialBroker,diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.tsindex b4ec14ffe3f2..ae82383a8dac 100644--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts@@ -79,6 +79,64 @@ export function effectiveApprovalType(scope: ApprovalRequest['approver_scope']):return 'principal'}+/**+ * Wire shape for an approval row — matches the Django `approvals` serializer and+ * the frontend `AgentApprovalRequest`. Drops the internal `args_hash` (a Buffer)+ * and reports a concrete `approver_scope.type`.+ */+export interface SerializedApprovalRequest {+ id: string+ session_id: string+ application_id: string+ team_id: number+ revision_id: string+ turn: number+ tool_call_id: string+ tool_name: string+ proposed_args: Record<string, unknown>+ decided_args: Record<string, unknown> | null+ assistant_message: AssistantMessageRecord+ approver_scope: { type: ApprovalType; allow_edit: boolean }+ state: ApprovalRequestState+ decision_by: string | null+ decision_at: string | null+ decision_reason: string | null+ dispatch_outcome: { result?: unknown; error?: string } | null+ created_at: string+ expires_at: string+}++/**+ * Serialize a stored row to the wire shape clients consume. Shared by the+ * ingress read route (`GET /approvals/:id`) and the runner's `approval_required`+ * SSE frame so every surface emits an identical shape. Resolves+ * `approver_scope.type` through `effectiveApprovalType` so legacy rows report a+ * concrete type instead of `undefined`.+ */+export function serializeApprovalRequest(row: ApprovalRequest): SerializedApprovalRequest {+ return {+ id: row.id,+ session_id: row.session_id,+ application_id: row.application_id,+ team_id: row.team_id,+ revision_id: row.revision_id,+ turn: row.turn,+ tool_call_id: row.tool_call_id,+ tool_name: row.tool_name,+ proposed_args: row.proposed_args,+ decided_args: row.decided_args,+ assistant_message: row.assistant_message,+ approver_scope: { type: effectiveApprovalType(row.approver_scope), allow_edit: row.approver_scope.allow_edit },+ state: row.state,+ decision_by: row.decision_by,+ decision_at: row.decision_at,+ decision_reason: row.decision_reason,+ dispatch_outcome: row.dispatch_outcome,+ created_at: row.created_at,+ expires_at: row.expires_at,+ }+}+export interface UpsertApprovalRequestInput {id: stringsession_id: stringdiff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.tsindex cd741a0f944d..a6bef80e6df5 100644--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts@@ -610,6 +610,15 @@ function buildSessionFilter(params.push(opts.createdBefore)where.push(`created_at <= $${params.length}`)}+ if (opts.search?.trim()) {+ // id + external_key only — transcript search would scan/detoast every+ // session's JSONB; it lands on a persisted, indexed column instead.+ // LIKE wildcards escaped so the term matches literally.+ const term = `%${opts.search.trim().replace(/[\\%_]/g, '\\$&')}%`+ params.push(term)+ const idx = params.length+ where.push(`(id::text ILIKE $${idx} OR external_key ILIKE $${idx})`)+ }return { where, params }}diff --git a/products/agent_platform/services/agent-shared/src/persistence/queue.ts b/products/agent_platform/services/agent-shared/src/persistence/queue.tsindex 6acb32289989..3995c2b00776 100644--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts@@ -70,6 +70,8 @@ export interface ListSessionsOpts {createdAfter?: string/** ISO datetime — only return sessions with created_at <= this. */createdBefore?: string+ /** Case-insensitive substring over the session id and external_key. */+ search?: string}/**