Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): Add standalone agent-proxy streaming service (#62067)

Charles Vien9a1ab88de4df
diff --git a/.dockerignore b/.dockerignore
index 51184b98fc1d..bb4e167ff582 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -63,6 +63,12 @@ services/agent-*/.next
services/agents/node_modules
services/agents/dist
services/agent-tests
+!services/agent-proxy
+!services/agent-proxy/package.json
+!services/agent-proxy/tsconfig.json
+!services/agent-proxy/scripts
+!services/agent-proxy/src
+!services/agent-proxy/types.d.ts
!pnpm-lock.yaml
!pnpm-workspace.yaml
!pyproject.toml
@@ -92,6 +98,9 @@ services/mcp/node_modules
services/mcp/dist
services/mcp/.wrangler
services/mcp/tests
+services/agent-proxy/node_modules
+services/agent-proxy/dist
+services/agent-proxy/tests
ee/**/node_modules
docs/**/node_modules
**/__pycache__
diff --git a/.github/workflows/cd-agent-proxy-image.yml b/.github/workflows/cd-agent-proxy-image.yml
new file mode 100644
index 000000000000..90e5280b94c0
--- /dev/null
+++ b/.github/workflows/cd-agent-proxy-image.yml
@@ -0,0 +1,112 @@
+name: Agent Proxy Container Image CD
+
+on:
+ push:
+ branches:
+ - master
+ paths:
+ - 'services/agent-proxy/**'
+ - '.github/workflows/cd-agent-proxy-image.yml'
+ workflow_dispatch:
+
+jobs:
+ build:
+ name: Build and push container image
+ if: |
+ github.repository == 'PostHog/posthog' && (
+ github.event_name == 'push' ||
+ github.event_name == 'workflow_dispatch'
+ )
+ runs-on: depot-ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ packages: write
+ id-token: write
+
+ outputs:
+ sha: ${{ steps.push.outputs.digest }}
+
+ steps:
+ - name: Check out
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 2
+
+ - name: Docker meta and registry login
+ id: docker-meta
+ uses: ./.github/actions/docker-meta
+ with:
+ image-name: posthog-agent-proxy
+ aws-role-to-assume: ${{ secrets.AWS_ECR_PUBLISH_IAM_ROLE }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ dockerhub-username: ${{ secrets.DOCKERHUB_USER }}
+ dockerhub-password: ${{ secrets.DOCKERHUB_TOKEN }}
+ push-to-dockerhub: 'false'
+
+ - name: Set up Depot CLI
+ uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+
+ - name: Build and push container image
+ id: push
+ uses: depot/build-push-action@5f3b3c2e5a00f0093de47f657aeaefcedff27d18 # v1.17.0
+ with:
+ project: ${{ vars.AGENT_PROXY_DEPOT_PROJECT_ID }}
+ file: ./services/agent-proxy/Dockerfile
+ buildx-fallback: false
+ push: ${{ github.ref == 'refs/heads/master' }}
+ tags: ${{ steps.docker-meta.outputs.tags }}
+ labels: ${{ steps.docker-meta.outputs.labels }}
+ platforms: linux/arm64,linux/amd64
+ build-args: COMMIT_HASH=${{ github.sha }}
+
+ deploy:
+ name: Trigger agent-proxy deployment
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ needs: build
+ if: github.ref == 'refs/heads/master'
+ permissions: {}
+
+ steps:
+ - name: Get deployer token
+ id: deployer
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ secrets.GH_APP_CHARTS_DEPLOYER_APP_ID }}
+ private-key: ${{ secrets.GH_APP_CHARTS_DEPLOYER_PRIVATE_KEY }}
+ owner: PostHog
+ repositories: charts
+
+ - name: Get PR labels
+ id: labels
+ uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
+ with:
+ script: |
+ const { data: pulls } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ commit_sha: context.sha,
+ });
+ const labels = pulls.flatMap(pr => pr.labels.map(l => l.name));
+ return JSON.stringify([...new Set(labels)]);
+
+ - name: Trigger agent-proxy deployment
+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
+ with:
+ token: ${{ steps.deployer.outputs.token }}
+ repository: PostHog/charts
+ event-type: commit_state_update
+ client-payload: |
+ {
+ "values": {
+ "image": {
+ "sha": "${{ needs.build.outputs.sha }}"
+ }
+ },
+ "release": "agent-proxy",
+ "commit": ${{ toJson(github.event.head_commit) }},
+ "repository": ${{ toJson(github.repository) }},
+ "labels": ${{ steps.labels.outputs.result }},
+ "timestamp": "${{ github.event.head_commit.timestamp }}"
+ }
diff --git a/.github/workflows/ci-agent-proxy.yml b/.github/workflows/ci-agent-proxy.yml
new file mode 100644
index 000000000000..38dbe482ba02
--- /dev/null
+++ b/.github/workflows/ci-agent-proxy.yml
@@ -0,0 +1,118 @@
+name: Agent Proxy CI
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ merge_group:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+ pull-requests: read
+
+jobs:
+ changes:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ name: Determine need to run agent-proxy checks
+ outputs:
+ agent_proxy: ${{ steps.filter.outputs.agent_proxy || 'true' }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ id: app-token
+ if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
+ with:
+ client-id: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}
+ - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
+ id: filter
+ if: github.event_name != 'push'
+ with:
+ token: ${{ steps.app-token.outputs.token || github.token }}
+ filters: |
+ agent_proxy:
+ - 'services/agent-proxy/**'
+ - '.github/workflows/ci-agent-proxy.yml'
+
+ agent-proxy:
+ name: Agent Proxy checks
+ needs: changes
+ if: needs.changes.outputs.agent_proxy == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+
+ - name: Set up Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ token: ${{ github.token }}
+
+ - name: Get pnpm store path
+ id: pnpm-store
+ run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT"
+
+ - name: Restore pnpm cache
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: ${{ steps.pnpm-store.outputs.path }}
+ key: pnpm-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
+ restore-keys: pnpm-${{ runner.os }}-
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile --filter @posthog/agent-proxy...
+
+ - name: Save pnpm cache
+ if: github.ref == 'refs/heads/master'
+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ with:
+ path: ${{ steps.pnpm-store.outputs.path }}
+ key: pnpm-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
+
+ - name: Typecheck
+ working-directory: services/agent-proxy
+ run: pnpm typecheck
+
+ - name: Test
+ working-directory: services/agent-proxy
+ run: pnpm exec vitest run
+
+ - name: Lint
+ working-directory: services/agent-proxy
+ run: pnpm exec oxlint
+
+ - name: Format check
+ working-directory: services/agent-proxy
+ run: pnpm exec oxfmt --check 'src/**/*.ts' 'tests/**/*.ts' 'scripts/**/*.ts'
+
+ agent_proxy_ci:
+ needs: [changes, agent-proxy]
+ name: Agent Proxy CI Pass
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ if: ${{ !cancelled() }}
+ steps:
+ - name: Check outcomes
+ run: |
+ if [[ "${{ needs.changes.result }}" == "failure" ]]; then
+ echo "Change detection job failed."
+ exit 1
+ fi
+
+ if [[ "${{ needs.agent-proxy.result }}" == "failure" ]]; then
+ echo "Agent Proxy checks failed."
+ exit 1
+ fi
+
+ echo "All agent-proxy checks passed."
diff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yaml
index 44d87b4fec2a..fd2c0421a107 100644
--- a/.github/workflows/ci-security.yaml
+++ b/.github/workflows/ci-security.yaml
@@ -161,7 +161,7 @@ jobs:
--error \
--metrics=off \
--verbose \
- frontend/ nodejs/ products/agent_platform/ services/mcp/ services/oauth-proxy/ services/stripe-app/
+ frontend/ nodejs/ products/agent_platform/ services/agent-proxy/ services/mcp/ services/oauth-proxy/ services/stripe-app/
semgrep-products-frontend:
runs-on: ubuntu-latest
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index d912a9a7391a..b4890a192d82 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -489,6 +489,14 @@ procs:
LLM_GATEWAY_POSTHOG_PROJECT_TOKEN: 'phc_localposthogprojecttoken'
LLM_GATEWAY_POSTHOG_HOST: 'http://localhost:8010'
+ agent-proxy:
+ shell: 'bin/wait-for-docker --only redis7 && pnpm --filter @posthog/agent-proxy dev'
+ capability: agent_proxy
+ ready_pattern: 'server:started'
+ groups:
+ layer: Product services
+ tech: Node
+
mcp:
sandbox: true
shell: 'bin/start-mcp-server'
diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yaml
index cef113a64ccf..cb4e56723f29 100644
--- a/devenv/intent-map.yaml
+++ b/devenv/intent-map.yaml
@@ -88,6 +88,11 @@ capabilities:
requires: [core_infra]
docker_profiles: []
+ agent_proxy:
+ description: 'Agent proxy streaming service for live task-run streaming (Tasks product)'
+ requires: [core_infra]
+ docker_profiles: []
+
ai_capture:
description: 'AI event capture service'
requires: [event_ingestion, llm_gateway]
@@ -356,6 +361,7 @@ intents:
property_definitions,
property_values,
temporal_workflows,
+ agent_proxy,
]
logs:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 1cfab40945be..479df1ae202a 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1,5 +1,10 @@
import { EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'
import { encodeParams } from 'kea-router'
+
+// Re-exported so code outside frontend/ (e.g. products/*/frontend) can type stream
+// callbacks without importing @microsoft/fetch-event-source directly — that package
+// only resolves from frontend/node_modules, not the repo root.
+export type { EventSourceMessage } from '@microsoft/fetch-event-source'
import posthog from 'posthog-js'
import { ApiError } from 'lib/api-error'
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 70b643acf4db..d9a42dfb30d8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -480,6 +480,7 @@ export const FEATURE_FLAGS = {
TASK_SUMMARIES: 'task-summaries', // owner: #team-ai-observability
TASK_TOOL: 'phai-task-tool', // owner: @kappa90 #team-posthog-ai
TASKS: 'tasks', // owner: #team-ai-observability
+ TASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observability
TAXONOMIC_FILTER_CATEGORY_DROPDOWN: 'taxonomic-filter-category-dropdown', // owner: @pauldambra #team-product-analytics multivariate=control,pill
TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)
TOGGLE_PROPERTY_ARRAYS: 'toggle-property-arrays', // owner: @arthurdedeus #team-customer-analytics
diff --git a/hogli.yaml b/hogli.yaml
index 290bb005cd9d..213cf5d7c174 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -364,6 +364,12 @@ start:
- postgresql
- redis
hidden: true
+ start:agent-proxy:
+ cmd: pnpm --filter @posthog/agent-proxy dev
+ description: Run the agent-proxy Node service for task-run live streaming with auto-reload
+ services:
+ - redis
+ hidden: true
start:celery:
bin_script: start-celery
description: Start Celery worker or beat scheduler with auto-reload
@@ -1091,3 +1097,7 @@ environment:
bin_script: migrate-agent-test-db
description: Create + migrate the agent_platform test database from the Django migrations (single source of truth)
hidden: true
+ docker:agent:proxy:
+ cmd: node dist/agent-proxy-server.mjs
+ description: 'Production entrypoint: run the agent-proxy Node service'
+ hidden: true
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a7dedd9e0c0d..841b9e842f38 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4367,6 +4367,55 @@ importers:
specifier: ^7.3.0
version: 7.3.0
+ services/agent-proxy:
+ dependencies:
+ '@hono/node-server':
+ specifier: ^2.0.2
+ version: 2.0.2([email protected])
+ esbuild:
+ specifier: ^0.25.11
+ version: 0.25.12
+ hono:
+ specifier: ^4.12.18
+ version: 4.12.24
+ ioredis:
+ specifier: ^4.28.5
+ version: 4.28.5
+ jose:
+ specifier: ^6.0.10
+ version: 6.2.3
+ pino:
+ specifier: ^8.6.0
+ version: 8.11.0
+ prom-client:
+ specifier: ^14.2.0
+ version: 14.2.0
+ devDependencies:
+ '@types/node':
+ specifier: ^22.17.2
+ version: 22.18.8
+ oxfmt:
+ specifier: 'catalog:'
+ version: 0.35.0
+ oxlint:
+ specifier: ^1.8.0
+ version: 1.9.0
+ pino-pretty:
+ specifier: ^9.1.0
+ version: 9.4.0
+ tsx:
+ specifier: ^4.20.5
+ version: 4.20.5
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
+ vite-tsconfig-paths:
+ specifier: ^5.1.4
+ vitest:
+ specifier: ^3.2.4
+
services/mcp:
dependencies:
'@hono/node-server':
@@ -12958,6 +13007,9 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-1+7q9BtaKzEmO+fmNT3kYvoNn5Y71XWAx2Q5HRim4tTVRQVRv4uJFAQ5FbK0OPUeNP/WmVCpxYxoJdvuHVjzBQ==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==}
@@ -12972,6 +13024,17 @@ packages:
vite:
optional: true
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-EZOrpDbkKotFAP7wPAQV1UIyoGOk4oX7ynWhBhLB7v+meMHbQhU16oPpIYGTTe4oFlhpryGpgpcZP/sin3hYuw==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
'@vitest/[email protected]':
resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==}
peerDependencies:
@@ -12989,18 +13052,27 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==}
'@vitest/[email protected]':
resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-HYcoSj1w5tcgUnzoF0HcyaAQjpA1gj9ftUJ7iSJSuipc02jW9gKkigwZbjFldAfYHA1fa8UZVRftdMY5msWM9Q==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==}
'@vitest/[email protected]':
resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-H+ZjNTWGpObenh0YnlBctAPnJSI20P81PL8BPzWpx54YXLLTm8hEsWawtcYLMrwvpK48hGxLLbCS+1KRXhsKhw==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==}
@@ -13010,6 +13082,9 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-oq6BbH68WzcWmwtBrU9nqLeaXTR4XwJF7FSLkKEZo4i6eoXcrxjcwSuTvWBIRUTC6VC72nXYunzqgZA+IKdtxg==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==}
@@ -13019,6 +13094,9 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==}
@@ -17379,6 +17457,9 @@ packages:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
+ resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
+
resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==}
hasBin: true
@@ -21406,6 +21487,9 @@ packages:
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
+
resolution: {integrity: sha512-axCguHItc8Sxt0HC6aSkdVRPffjYPV7EQqZRb2GkIa8FzWDycE7nHJM19C6xAIynH1Qp1/BHiopSi96jGBxT0w==}
engines: {node: '>=16'}
@@ -21828,6 +21912,10 @@ packages:
resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}
+ engines: {node: '>=14.0.0'}
+
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
engines: {node: '>=14.0.0'}
@@ -21836,6 +21924,10 @@ packages:
resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==}
+ engines: {node: '>=14.0.0'}
+
resolution: {integrity: sha512-lXnRhuQpx3zU9EONF9F7HfcRLvN1uRYUBIiKL+C/gehC/77XTU+Jye6ui86GA3rU6FjlJ0triD1Tkjt2F/2lEg==}
@@ -22519,6 +22611,11 @@ packages:
engines: {node: ^18.0.0 || >=20.0.0}
hasBin: true
+ resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
+ hasBin: true
+
resolution: {integrity: sha512-d4sOM8M/8z7vRXHHq/ebbblfaxENjogAAekcfcDCCwAyvGqnPrc7f4NZbvItS+g4WTgerW0xDwSz5qz11JT3vg==}
peerDependencies:
@@ -22719,6 +22816,34 @@ packages:
jsdom:
optional: true
+ resolution: {integrity: sha512-xejya+bT/j/+R/AGa1XOfRxLmNUlLtlwjRsFUILF+xHfzElmGcmFydy2gqqIrd62ptIEfwVMofd19uNWD9L7Nw==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@types/debug': ^4.1.12
+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
+ '@vitest/browser': 3.2.6
+ '@vitest/ui': 3.2.6
+ happy-dom: '*'
+ jsdom: '*'
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@types/debug':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==}
engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
@@ -33737,6 +33862,14 @@ snapshots:
chai: 5.3.3
tinyrainbow: 1.2.0
+ '@vitest/[email protected]':
+ dependencies:
+ '@types/chai': 5.2.2
+ '@vitest/spy': 3.2.6
+ '@vitest/utils': 3.2.6
+ chai: 5.3.3
+ tinyrainbow: 2.0.0
+
'@vitest/[email protected]':
dependencies:
'@standard-schema/spec': 1.1.0
@@ -33755,6 +33888,15 @@ snapshots:
+ dependencies:
+ '@vitest/spy': 3.2.6
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ msw: 2.14.6(@types/[email protected])([email protected])
+
dependencies:
'@vitest/spy': 4.1.8
@@ -33781,6 +33923,10 @@ snapshots:
dependencies:
tinyrainbow: 1.2.0
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 2.0.0
+
'@vitest/[email protected]':
dependencies:
tinyrainbow: 3.1.0
@@ -33790,6 +33936,12 @@ snapshots:
'@vitest/utils': 2.1.9
pathe: 1.1.2
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 3.2.6
+ pathe: 2.0.3
+ strip-literal: 3.1.0
+
'@vitest/[email protected]':
dependencies:
'@vitest/utils': 4.1.8
@@ -33801,6 +33953,12 @@ snapshots:
magic-string: 0.30.21
pathe: 1.1.2
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 3.2.6
+ magic-string: 0.30.21
+ pathe: 2.0.3
+
'@vitest/[email protected]':
dependencies:
'@vitest/pretty-format': 4.1.8
@@ -33816,6 +33974,10 @@ snapshots:
dependencies:
tinyspy: 3.0.2
+ '@vitest/[email protected]':
+ dependencies:
+ tinyspy: 4.0.4
+
'@vitest/[email protected]': {}
'@vitest/[email protected]':
@@ -33831,6 +33993,12 @@ snapshots:
loupe: 3.2.1
tinyrainbow: 1.2.0
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 3.2.6
+ loupe: 3.2.1
+ tinyrainbow: 2.0.0
+
'@vitest/[email protected]':
dependencies:
'@vitest/pretty-format': 4.1.8
@@ -39861,6 +40029,8 @@ snapshots:
+
dependencies:
argparse: 1.0.10
@@ -44850,6 +45020,10 @@ snapshots:
+ dependencies:
+ js-tokens: 9.0.1
+
optionalDependencies:
'@types/node': 25.8.0
@@ -45329,10 +45503,14 @@ snapshots:
+
+
@@ -46074,6 +46252,27 @@ snapshots:
- supports-color
- terser
+ dependencies:
+ cac: 6.7.14
+ debug: 4.4.3
+ es-module-lexer: 1.7.0
+ pathe: 2.0.3
+ transitivePeerDependencies:
+ - '@types/node'
+ - jiti
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@microsoft/api-extractor': 7.58.1(@types/[email protected])
@@ -46264,6 +46463,49 @@ snapshots:
- supports-color
- terser
+ dependencies:
+ '@types/chai': 5.2.2
+ '@vitest/expect': 3.2.6
+ '@vitest/pretty-format': 3.2.6
+ '@vitest/runner': 3.2.6
+ '@vitest/snapshot': 3.2.6
+ '@vitest/spy': 3.2.6
+ '@vitest/utils': 3.2.6
+ chai: 5.3.3
+ debug: 4.4.3
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinyglobby: 0.2.16
+ tinypool: 1.1.1
+ tinyrainbow: 2.0.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 22.18.8
+ happy-dom: 20.9.0
+ jsdom: 20.0.3
+ transitivePeerDependencies:
+ - jiti
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@vitest/expect': 4.1.8
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index f0657266c6cd..7677ca5ec71f 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -18,6 +18,7 @@ packages:
- products/agent_platform/services/*
- products/agent_platform/packages/*
- docs/onboarding
+ - services/agent-proxy
- services/oauth-proxy
- services/mcp
- services/stripe-app
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index a82cabd133b7..e08a40c590ba 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -96,9 +96,45 @@ For the safety of your instance, you must generate and set a unique key.
# RS256 private key for sandbox JWT authentication
# Used to sign tokens; public key is derived from this and injected into sandboxes for verification
SANDBOX_JWT_PRIVATE_KEY: str | None = os.getenv("SANDBOX_JWT_PRIVATE_KEY")
+# Verify-only services (e.g. the agent-proxy) set just the public key so they never hold the private
+# key. Django leaves this unset and derives the public key from the private key (it mints tokens).
+SANDBOX_JWT_PUBLIC_KEY: str | None = os.getenv("SANDBOX_JWT_PUBLIC_KEY")
# Additional RS256 private key accepted during key rotation of SANDBOX_JWT_PRIVATE_KEY
SANDBOX_JWT_PRIVATE_KEY_SECONDARY: str | None = os.getenv("SANDBOX_JWT_PRIVATE_KEY_SECONDARY")
+# Additional public key a verify-only service (the agent-proxy) trusts during key rotation, so a token
+# signed with either the primary or the secondary key verifies. The proxy holds public keys only.
+SANDBOX_JWT_PUBLIC_KEY_SECONDARY: str | None = os.getenv("SANDBOX_JWT_PUBLIC_KEY_SECONDARY")
+
+# Local dev shares one .env with the agent-proxy, which sets the verify-only public keys. Tests must
+# stay hermetic: they mint with an overridden private key and verify against the same registry, not
+# against whatever key the ambient environment carries.
+if TEST:
+ SANDBOX_JWT_PUBLIC_KEY = None
+ SANDBOX_JWT_PUBLIC_KEY_SECONDARY = None
+
+# Browser origins allowed to read the live stream from the standalone agent-proxy (cross-origin CORS).
+# Comma-separated; "*" allows any; empty disables CORS (same-origin path-routing needs none). Only the
+# agent-proxy reads this; the Django app ignores it.
+TASKS_AGENT_PROXY_CORS_ORIGINS: list[str] = [
+ origin.strip() for origin in os.getenv("TASKS_AGENT_PROXY_CORS_ORIGINS", "").split(",") if origin.strip()
+]
+
+# Base URL the sandbox agent POSTs its event-ingest stream to. When set (and sequenced ingest is on),
+# the run routes ingest to the standalone agent-proxy instead of the Django ASGI short-circuit; unset
+# falls back to the Django app URL. Reversible by clearing the env var. Locally: http://localhost:8003
+TASKS_AGENT_PROXY_INGEST_URL: str | None = os.getenv("TASKS_AGENT_PROXY_INGEST_URL") or None
+
+# Browser-facing base URL of the agent-proxy for the live-stream read leg, per environment (e.g.
+# https://agent-proxy.us.posthog.com). The stream_token endpoint returns it to clients only when this
+# is set AND the read-via-proxy flag is enabled for the user; unset means clients read from Django.
+TASKS_AGENT_PROXY_PUBLIC_URL: str | None = os.getenv("TASKS_AGENT_PROXY_PUBLIC_URL") or None
+
+# Shared service-to-service secret proving a call to the agent-proxy side-effect callback came from the
+# agent-proxy and not directly from a sandbox (which also holds the event-ingest JWT). When set, the
+# callback requires a matching X-Agent-Proxy-Secret header. Provision the same value to Django and the
+# agent-proxy in production; unset (local/CI) disables the check.
+AGENT_PROXY_CALLBACK_SECRET: str | None = os.getenv("AGENT_PROXY_CALLBACK_SECRET") or None
# These are legacy values only kept around for backwards compatibility with self hosted versions
SALT_KEY = get_list(os.getenv("SALT_KEY", "0123456789abcdefghijklmnopqrstuvwxyz"))
diff --git a/posthog/urls.py b/posthog/urls.py
index 438feb83ab00..b6dc1da920fd 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -61,6 +61,7 @@ from products.slack_app.backend.api import (
slack_workspace_claims_view,
)
from products.surveys.backend.api.survey import public_survey_page
+from products.tasks.backend.facade.agent_proxy import agent_proxy_callback
from products.user_interviews.backend.presentation.webhooks import (
start_call as user_interviews_start_call,
vapi_webhook,
@@ -367,6 +368,11 @@ urlpatterns = [
"api/public_source_configs",
PublicSourceConfigViewSet.as_view({"get": "list"}),
),
+ # Internal agent-proxy side-effect callback (auth: sandbox event ingest JWT)
+ path(
+ "internal/tasks/runs/<str:run_id>/agent-proxy-callback/",
+ csrf_exempt(agent_proxy_callback),
+ ),
# Internal service-to-service endpoints (authenticated with POSTHOG_INTERNAL_SERVICE_TOKEN)
path(
"api/projects/<str:team_id>/internal/hog_flows/user_blast_radius",
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
new file mode 100644
index 000000000000..f3dd41be37b3
--- /dev/null
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -0,0 +1,141 @@
+import hmac
+import json
+import logging
+
+from django.conf import settings
+from django.http import JsonResponse
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from jwt import PyJWTError
+
+from products.tasks.backend.models import TaskRun
+from products.tasks.backend.presentation.serializers import (
+ AgentProxyCallbackRequestSerializer,
+ AgentProxyCallbackResponseSerializer,
+ TaskRunErrorResponseSerializer,
+)
+from products.tasks.backend.push_dispatcher import notify_task_run_awaiting_input
+
+logger = logging.getLogger(__name__)
+
+
+# ---------------------------------------------------------------------------
+# Internal agent-proxy callback (not a DRF viewset action — no team scoping,
+# auth is the sandbox event ingest JWT forwarded by the Node service).
+# Registered at: internal/tasks/runs/<run_id>/agent-proxy-callback/
+# ---------------------------------------------------------------------------
+
+
+@extend_schema(
+ tags=["task-runs"],
+ request=AgentProxyCallbackRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=AgentProxyCallbackResponseSerializer,
+ description="Side effect dispatched or skipped",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request body"),
+ 401: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Missing or invalid JWT"),
+ 403: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="JWT claims do not match URL"),
+ },
+ summary="Agent-proxy side-effect callback",
+ description=(
+ "Internal endpoint called by the standalone Node agent-proxy after accepting an ingest event "
+ "that requires a Django-side side effect. Dispatches a Temporal heartbeat signal or an "
+ "awaiting-input mobile push notification depending on `kind`. "
+ "Authenticated with the forwarded sandbox event ingest JWT plus the X-Agent-Proxy-Secret "
+ "shared secret (required outside local dev/test) — no session or API key involved. "
+ "Best-effort: always returns 200 when auth passes; side-effect failures are logged, not surfaced."
+ ),
+)
+def agent_proxy_callback(request, run_id: str) -> JsonResponse:
+ """Handle side-effect callbacks from the Node agent-proxy service.
+
+ Auth: sandbox event ingest JWT forwarded from the Node service as a Bearer token.
+ The JWT already carries run_id, task_id, team_id — body fields are validated
+ against the JWT claims to prevent cross-run confusion.
+ """
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the import path
+ validate_sandbox_event_ingest_token,
+ )
+
+ if request.method != "POST":
+ return JsonResponse({"error": "Method not allowed"}, status=405)
+
+ # Extract and validate the Bearer token
+ authorization = request.headers.get("Authorization", "")
+ if not authorization.startswith("Bearer "):
+ return JsonResponse({"error": "Missing authorization bearer token"}, status=401)
+ token = authorization[len("Bearer ") :].strip()
+ if not token:
+ return JsonResponse({"error": "Missing authorization bearer token"}, status=401)
+
+ try:
+ claims = validate_sandbox_event_ingest_token(token)
+ except PyJWTError as exc:
+ return JsonResponse({"error": "Invalid event ingest token", "code": exc.__class__.__name__}, status=401)
+
+ # JWT run_id must match URL parameter
+ if claims.run_id != run_id:
+ return JsonResponse({"error": "Token does not match task run"}, status=403)
+
+ # Service-to-service guard: the event-ingest JWT is also held by the sandbox, so the JWT alone
+ # does not prove the caller is the agent-proxy. Require the shared secret so a sandbox cannot
+ # drive this callback directly (bypassing the proxy's Redis sequencing/throttle). An unset
+ # secret fails closed — the endpoint stays dead until the secret is provisioned — except in
+ # local dev/test where no proxy deployment exists to share a secret with.
+ expected_secret = settings.AGENT_PROXY_CALLBACK_SECRET
+ if expected_secret:
+ provided_secret = request.headers.get("X-Agent-Proxy-Secret", "")
+ if not hmac.compare_digest(provided_secret, expected_secret):
+ return JsonResponse({"error": "Invalid agent-proxy callback secret"}, status=403)
+ elif not (settings.DEBUG or settings.TEST):
+ return JsonResponse({"error": "Agent-proxy callback secret is not configured"}, status=403)
+
+ # Validate and parse the request body
+ try:
+ body = json.loads(request.body)
+ except (json.JSONDecodeError, ValueError):
+ return JsonResponse({"error": "Invalid JSON body"}, status=400)
+
+ serializer = AgentProxyCallbackRequestSerializer(data=body)
+ if not serializer.is_valid():
+ return JsonResponse({"error": "Invalid request body", "detail": serializer.errors}, status=400)
+
+ data = serializer.validated_data
+ kind: str = data["kind"]
+ task_id: str = data["task_id"]
+ team_id: int = data["team_id"]
+ agent_active: bool = data["agent_active"]
+
+ # Body claims must match JWT claims to prevent cross-run confusion
+ if task_id != claims.task_id or team_id != claims.team_id:
+ return JsonResponse({"error": "Token claims do not match request body"}, status=403)
+
+ dispatched = False
+
+ if kind == "heartbeat" and agent_active:
+ try:
+ task_run = TaskRun.objects.get(id=run_id, task_id=task_id, team_id=team_id)
+ task_run.heartbeat_workflow(agent_active=True)
+ dispatched = True
+ except TaskRun.DoesNotExist:
+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
+ except Exception:
+ logger.exception("agent_proxy_callback.heartbeat_failed", extra={"run_id": run_id})
+
+ elif kind == "awaiting_input":
+ try:
+ # The push dispatcher reads task.created_by; prefetch it so the dispatch stays one query.
+ task_run = TaskRun.objects.select_related("task__created_by").get(
+ id=run_id, task_id=task_id, team_id=team_id
+ )
+ if task_run.mode == "interactive":
+ notify_task_run_awaiting_input(task_run)
+ dispatched = True
+ except TaskRun.DoesNotExist:
+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
+ except Exception:
+ logger.exception("agent_proxy_callback.awaiting_input_failed", extra={"run_id": run_id})
+
+ return JsonResponse(AgentProxyCallbackResponseSerializer({"dispatched": dispatched}).data)
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index eb38d0b4ffa7..7696e53af8db 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -4,6 +4,7 @@ SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"
MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"
MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"
BURSTABLE_SANDBOX_RESOURCES_FEATURE_FLAG = "tasks-burstable-sandbox-resources"
+STREAM_VIA_PROXY_FEATURE_FLAG = "tasks-stream-via-proxy"
ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions", "auto"]
CodexPermissionMode = Literal["auto", "read-only", "full-access"]
diff --git a/products/tasks/backend/facade/agent_proxy.py b/products/tasks/backend/facade/agent_proxy.py
new file mode 100644
index 000000000000..a20b4842223b
--- /dev/null
+++ b/products/tasks/backend/facade/agent_proxy.py
@@ -0,0 +1,10 @@
+"""
+Facade re-export for the internal agent-proxy callback view.
+
+Core's URLconf routes ``internal/tasks/runs/<run_id>/agent-proxy-callback/`` directly to this
+handler, so it must be reachable from outside the product without importing internals directly.
+"""
+
+from products.tasks.backend.agent_proxy_callback import agent_proxy_callback
+
+__all__ = ["agent_proxy_callback"]
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 14654b6ffdb8..99f5e3f3f82d 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -107,6 +107,8 @@ __all__ = [
"create_task_automation",
"create_task_without_run",
"create_task_run_connection_token",
+ "create_task_run_stream_read_token",
+ "resolve_stream_base_url",
"claim_and_fail_stale_run",
"delete_sandbox_environment",
"delete_task_automation",
@@ -1702,6 +1704,52 @@ def create_task_run_connection_token(
return _create(task_run=run, user_id=user_id, distinct_id=distinct_id)
+def create_task_run_stream_read_token(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
+ """Mint a run-scoped token for reading a run's live event stream. ``None`` if the run isn't found."""
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ create_stream_read_token as _create,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return _create(task_run=run)
+
+
+def resolve_stream_base_url(*, distinct_id: str, organization_id: str | UUID) -> str | None:
+ """Agent-proxy base URL for the read leg, or ``None`` to read from Django directly.
+
+ Returns the configured agent-proxy URL only when it is set for this environment AND the
+ read-via-proxy flag is enabled for the user, so rollout stays gradual and reversible. The
+ server owns this decision; clients just connect to whatever URL comes back.
+ """
+ from django.conf import settings # noqa: PLC0415 — keep settings access local to this helper
+
+ from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAG # noqa: PLC0415
+
+ proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL
+ if not proxy_url:
+ return None
+ # Local dev disables the analytics SDK, so the rollout flag never evaluates; the URL setting
+ # is the opt-in there. Prod (DEBUG off) still gates on the flag below.
+ if settings.DEBUG:
+ return proxy_url
+ try:
+ enabled = bool(
+ posthoganalytics.feature_enabled(
+ STREAM_VIA_PROXY_FEATURE_FLAG,
+ distinct_id=distinct_id,
+ groups={"organization": str(organization_id)},
+ group_properties={"organization": {"id": str(organization_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return None
+ return proxy_url if enabled else None
+
+
# --- Task run commands (user_message signal + sandbox proxy) ---
diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.py
index 98f3fc6c63fb..b2c3046492e6 100644
--- a/products/tasks/backend/logic/services/connection_token.py
+++ b/products/tasks/backend/logic/services/connection_token.py
@@ -4,7 +4,7 @@ import hashlib
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from functools import lru_cache
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from django.conf import settings
@@ -25,6 +25,13 @@ SANDBOX_EVENT_INGEST_TOKEN_TTL = timedelta(seconds=SANDBOX_TTL_SECONDS) + SANDBO
SANDBOX_JWT_STATE_KID_KEY = "sandbox_jwt_kid"
+STREAM_READ_AUDIENCE = "posthog:stream_read"
+# Short-lived on purpose: the agent-proxy validates these tokens statelessly, so the TTL bounds
+# how long a user who lost project access can keep reconnecting to a stream. The client fetches a
+# fresh token from the stream_token endpoint (which re-checks access) on every connect, and again
+# when a reconnect is rejected with a 401 after the token expires mid-stream.
+STREAM_READ_TOKEN_TTL = timedelta(minutes=15)
+
@dataclass(frozen=True)
class SandboxEventIngestTokenPayload:
@@ -40,6 +47,13 @@ class _SandboxJwtKey:
public_key_pem: str
+@dataclass(frozen=True)
+class StreamReadTokenPayload:
+ run_id: str
+ task_id: str
+ team_id: int
+
+
def _normalize_pem_key(key: str) -> str:
"""Convert escaped newlines to actual newlines in PEM keys from env vars."""
return key.replace("\\n", "\n")
@@ -111,7 +125,15 @@ def get_primary_sandbox_jwt_kid() -> str:
def get_sandbox_jwt_public_key() -> str:
- """Public key (PEM) baked into newly provisioned sandboxes for verifying connection tokens."""
+ """Public key (PEM) used to verify sandbox tokens, baked into newly provisioned sandboxes.
+
+ Prefers an explicitly configured public key so a verify-only service (the agent-proxy)
+ never needs the private key. Falls back to the primary signing key's public half for
+ Django, which mints tokens.
+ """
+ public_key_pem = settings.SANDBOX_JWT_PUBLIC_KEY
+ if public_key_pem:
+ return _normalize_pem_key(public_key_pem)
return _primary_key().public_key_pem
@@ -128,6 +150,42 @@ def _signing_key_for_run(task_run: TaskRun) -> _SandboxJwtKey:
return _primary_key()
+def _verification_public_keys() -> list[str]:
+ """Public-key PEMs to verify sandbox tokens against.
+
+ Prefers explicitly configured public keys so a verify-only context (the agent-proxy, or a
+ public-key-only Django process) never needs the private key; the optional secondary public key
+ is additionally trusted during a rotation overlap. Falls back to the signing registry's public
+ halves when no explicit public key is configured (Django, which mints tokens).
+ """
+ explicit = settings.SANDBOX_JWT_PUBLIC_KEY
+ if explicit:
+ pems = [_normalize_pem_key(explicit)]
+ secondary = settings.SANDBOX_JWT_PUBLIC_KEY_SECONDARY
+ if secondary:
+ pems.append(_normalize_pem_key(secondary))
+ return pems
+ _, registry = _key_registry()
+ return [key.public_key_pem for key in registry.values()]
+
+
+def _decode_sandbox_token(token: str, audience: str) -> dict[str, Any]:
+ """Verify a sandbox JWT against every trusted public key, returning the first that validates.
+
+ Trusting both the primary and the rotation-secondary key is what lets the agent-proxy token
+ legs survive a primary-key rotation without downtime: a token signed under either key still
+ verifies. Only a signature mismatch advances to the next key; expiry and audience errors are
+ key-independent and propagate immediately.
+ """
+ last_error: jwt.InvalidTokenError | None = None
+ for public_key_pem in _verification_public_keys():
+ try:
+ return jwt.decode(token, public_key_pem, algorithms=["RS256"], audience=audience)
+ except jwt.InvalidSignatureError as exc:
+ last_error = exc
+ raise last_error or jwt.InvalidTokenError("No sandbox JWT keys configured")
+
+
def create_sandbox_connection_token(task_run: TaskRun, user_id: int, distinct_id: str) -> str:
"""
Create a JWT connection token for direct sandbox connections.
@@ -158,12 +216,12 @@ def create_sandbox_connection_token(task_run: TaskRun, user_id: int, distinct_id
return jwt.encode(payload, key.private_key_pem, algorithm="RS256", headers={"kid": key.kid})
-def create_sandbox_event_ingest_token(task_run: TaskRun, ttl: timedelta = SANDBOX_EVENT_INGEST_TOKEN_TTL) -> str:
- """
- Create a run-scoped JWT token for sandbox-to-Django live event ingest.
+def _encode_run_scoped_token(task_run: TaskRun, audience: str, ttl: timedelta) -> str:
+ """Encode a run-scoped JWT carrying no user identity, signed with the run's key.
- This token intentionally carries no user identity and grants one capability:
- appending ordered live events for this task run.
+ Shared by the event-ingest and stream-read tokens; they stay distinct capabilities
+ (write vs read) kept apart by ``audience`` rather than by the encoding. Signing with
+ the run's provisioned key (via ``kid``) keeps both legs working across key rotation.
"""
now = datetime.now(tz=UTC)
payload = {
@@ -172,19 +230,24 @@ def create_sandbox_event_ingest_token(task_run: TaskRun, ttl: timedelta = SANDBO
"team_id": task_run.team_id,
"iat": now,
"exp": now + ttl,
- "aud": SANDBOX_EVENT_INGEST_AUDIENCE,
+ "aud": audience,
}
+ key = _signing_key_for_run(task_run)
+ return jwt.encode(payload, key.private_key_pem, algorithm="RS256", headers={"kid": key.kid})
+
+
+def create_sandbox_event_ingest_token(task_run: TaskRun, ttl: timedelta = SANDBOX_EVENT_INGEST_TOKEN_TTL) -> str:
+ """
+ Create a run-scoped JWT token for sandbox-to-Django live event ingest.
- return jwt.encode(payload, _primary_key().private_key_pem, algorithm="RS256")
+ This token intentionally carries no user identity and grants one capability:
+ appending ordered live events for this task run.
+ """
+ return _encode_run_scoped_token(task_run, SANDBOX_EVENT_INGEST_AUDIENCE, ttl)
def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPayload:
- payload = jwt.decode(
- token,
- _primary_key().public_key_pem,
- algorithms=["RS256"],
- audience=SANDBOX_EVENT_INGEST_AUDIENCE,
- )
+ payload = _decode_sandbox_token(token, SANDBOX_EVENT_INGEST_AUDIENCE)
run_id = payload.get("run_id")
task_id = payload.get("task_id")
@@ -194,3 +257,28 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa
raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
return SandboxEventIngestTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id)
+
+
+def create_stream_read_token(task_run: TaskRun, ttl: timedelta = STREAM_READ_TOKEN_TTL) -> str:
+ """
+ Create a run-scoped JWT that authorizes reading a task run's live event stream.
+
+ Minted by Django (which authorizes the requesting user first) for the browser to
+ present to the standalone agent-proxy, which verifies it statelessly with the
+ public key. Carries no user identity and grants one capability: reading this
+ task run's stream.
+ """
+ return _encode_run_scoped_token(task_run, STREAM_READ_AUDIENCE, ttl)
+
+
+def validate_stream_read_token(token: str) -> StreamReadTokenPayload:
+ payload = _decode_sandbox_token(token, STREAM_READ_AUDIENCE)
+
+ run_id = payload.get("run_id")
+ task_id = payload.get("task_id")
+ team_id = payload.get("team_id")
+
+ if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:
+ raise jwt.InvalidTokenError("Stream read token has invalid claims")
+
+ return StreamReadTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id)
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 3c3ac590bbeb..894c64c75296 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -719,7 +719,12 @@ class DockerSandbox(SandboxBase):
mcp_servers_arg: str = "",
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> str:
+ # The host proxy URL (e.g. localhost:8003) is unreachable from inside the container;
+ # rewrite it the same way POSTHOG_API_URL is for Docker sandboxes.
+ if event_ingest_url:
+ event_ingest_url = DockerSandbox._transform_url_for_docker(event_ingest_url)
env_prefix = build_agent_runtime_env_prefix(
interaction_origin=interaction_origin,
runtime_adapter=runtime_adapter,
@@ -727,6 +732,7 @@ class DockerSandbox(SandboxBase):
model=model,
reasoning_effort=reasoning_effort,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
branch_flag = f" --baseBranch {shlex.quote(branch)}" if branch else ""
@@ -789,6 +795,7 @@ class DockerSandbox(SandboxBase):
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
@@ -835,6 +842,7 @@ class DockerSandbox(SandboxBase):
mcp_servers_arg,
allowed_domains=allowed_domains,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
@@ -868,6 +876,7 @@ class DockerSandbox(SandboxBase):
mcp_servers_arg=mcp_servers_arg,
allowed_domains=allowed_domains,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
if self._launch_and_check(command):
logger.info(f"Agent-server started on port {self._host_port} (without --baseBranch)")
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 67c4b2ff0555..56a98208a6d3 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -669,6 +669,7 @@ class ModalSandbox(SandboxBase):
mcp_servers_arg: str = "",
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> str:
env_prefix = build_agent_runtime_env_prefix(
interaction_origin=interaction_origin,
@@ -677,6 +678,7 @@ class ModalSandbox(SandboxBase):
model=model,
reasoning_effort=reasoning_effort,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
repo_flag = f" --repositoryPath {shlex.quote(repo_path)}" if repo_path else ""
@@ -773,6 +775,7 @@ class ModalSandbox(SandboxBase):
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
@@ -818,6 +821,7 @@ class ModalSandbox(SandboxBase):
mcp_servers_arg,
allowed_domains=allowed_domains,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index bced35981f43..09b62ead2436 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -137,6 +137,7 @@ def build_agent_runtime_env_prefix(
model: str | None = None,
reasoning_effort: str | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> str:
env_vars = {
"POSTHOG_CODE_INTERACTION_ORIGIN": interaction_origin,
@@ -145,6 +146,7 @@ def build_agent_runtime_env_prefix(
"POSTHOG_CODE_MODEL": model,
"POSTHOG_CODE_REASONING_EFFORT": reasoning_effort,
"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN": event_ingest_token,
+ "POSTHOG_TASK_RUN_EVENT_INGEST_URL": event_ingest_url,
}
assignments = " ".join(
f"{name}={shlex.quote(value)}" for name, value in env_vars.items() if value is not None and value != ""
@@ -254,6 +256,7 @@ class SandboxBase(ABC):
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
event_ingest_token: str | None = None,
+ event_ingest_url: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 8fc0e80dc34d..2dbe1e895767 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -538,6 +538,7 @@ class TestDockerSandboxUnit:
model="gpt-5.3-codex",
reasoning_effort="medium",
event_ingest_token="ingest-token",
+ event_ingest_url="http://localhost:8003",
)
command = _agent_server_launch_command(mock_execute)
@@ -546,6 +547,8 @@ class TestDockerSandboxUnit:
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
assert "POSTHOG_CODE_REASONING_EFFORT=medium" in command
assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=ingest-token" in command
+ # The host proxy URL is rewritten so it resolves from inside the container.
+ assert "POSTHOG_TASK_RUN_EVENT_INGEST_URL=http://host.docker.internal:8003" in command
@pytest.mark.skipif(is_ci() or not docker_available(), reason="Docker sandbox tests only run locally, not in CI")
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index 554c3ea1f001..b7ef97024fbb 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -424,6 +424,7 @@ class TestModalSandboxAgentServer:
model="gpt-5.3-codex",
reasoning_effort="high",
event_ingest_token="ingest-token",
+ event_ingest_url="https://agent-proxy.example.com",
)
command = _agent_server_launch_command(mock_sandbox.execute)
@@ -432,6 +433,8 @@ class TestModalSandboxAgentServer:
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
assert "POSTHOG_CODE_REASONING_EFFORT=high" in command
assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=ingest-token" in command
+ # Modal sandboxes reach the proxy by its real URL, no Docker-host rewrite.
+ assert "POSTHOG_TASK_RUN_EVENT_INGEST_URL=https://agent-proxy.example.com" in command
def test_start_agent_server_raises_when_not_running(self, mock_sandbox: Any):
mock_sandbox._sandbox.poll.return_value = 0
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 9dc9788e1bac..b1b31b2f8312 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -6,10 +6,14 @@ from collections.abc import AsyncGenerator, Awaitable, Callable
from dataclasses import dataclass
from typing import cast
+from django.conf import settings
+
import structlog
+import posthoganalytics
from asgiref.sync import sync_to_async
from jwt import PyJWTError
+from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAG
from products.tasks.backend.logic.services.connection_token import (
SandboxEventIngestTokenPayload,
validate_sandbox_event_ingest_token,
@@ -22,6 +26,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
get_task_run_stream_key,
)
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.push_dispatcher import notify_task_run_awaiting_input
from ee.hogai.sandbox import is_turn_complete
@@ -272,6 +277,7 @@ def _parse_ingest_line(line: str) -> EventIngestEventLine | EventIngestCompleteL
async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id: str, event: dict) -> None:
if is_turn_complete(event):
await redis_stream.set_agent_active(False)
+ await _dispatch_awaiting_input_if_interactive(run_id)
return
if _is_session_update(event):
@@ -299,6 +305,53 @@ def _heartbeat_workflow(run_id: str, agent_active: bool) -> None:
task_run.heartbeat_workflow(agent_active=agent_active)
+async def _dispatch_awaiting_input_if_interactive(run_id: str) -> None:
+ """Notify when an interactive run finishes a turn and idles for input."""
+ await sync_to_async(_dispatch_awaiting_input_if_interactive_sync, thread_sensitive=True)(run_id)
+
+
+def _dispatch_awaiting_input_if_interactive_sync(run_id: str) -> None:
+ try:
+ task_run = TaskRun.objects.select_related("task__created_by", "team").get(id=run_id)
+ except TaskRun.DoesNotExist:
+ logger.warning("task_run_event_ingest_awaiting_input_run_missing", run_id=run_id)
+ return
+
+ if task_run.mode != "interactive":
+ return
+
+ if not _awaiting_input_push_enabled(task_run):
+ return
+
+ notify_task_run_awaiting_input(task_run)
+
+
+def _awaiting_input_push_enabled(task_run: TaskRun) -> bool:
+ """Awaiting-input pushes ship with the proxy-streaming rollout: gate them on the same flag
+ so deploying this code changes nothing until the rollout starts. Local dev disables the
+ analytics SDK, so the flag never evaluates there; DEBUG is the opt-in, mirroring the
+ stream_token endpoint. Fails closed on flag-evaluation errors."""
+ if settings.DEBUG:
+ return True
+ user = task_run.task.created_by
+ if user is None:
+ return False
+ organization_id = str(task_run.team.organization_id)
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ STREAM_VIA_PROXY_FEATURE_FLAG,
+ user.distinct_id or f"user_{user.id}",
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return False
+
+
def _is_session_update(event: dict) -> bool:
if event.get("type") != "notification":
return False
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 282b0fee16ec..4ae18ce47af8 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -854,6 +854,22 @@ class ConnectionTokenResponseSerializer(serializers.Serializer):
token = serializers.CharField(help_text="JWT token for authenticating with the sandbox")
+class StreamReadTokenResponseSerializer(serializers.Serializer):
+ """Response containing a JWT token (and resolved base URL) for reading a task run's live event stream"""
+
+ token = serializers.CharField(
+ help_text="Run-scoped JWT the browser presents to the agent-proxy to read this run's live event stream"
+ )
+ stream_base_url = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Base URL of the agent-proxy to read the stream from when routing via the proxy is enabled for "
+ "this user. Null means read from the Django endpoint directly (same-origin). The client appends "
+ "the run's stream path and sends the token as a Bearer header when this is set."
+ ),
+ )
+
+
class TaskRunCreateRequestSerializer(serializers.Serializer):
"""Request body for creating a new task run"""
@@ -1746,3 +1762,45 @@ class SlackThreadContextResponseSerializer(serializers.Serializer):
many=True,
help_text="All runs on the task, oldest first. Empty when no mapping was found.",
)
+
+
+class AgentProxyCallbackRequestSerializer(serializers.Serializer):
+ """Request body for the agent-proxy side-effect callback.
+
+ Called by the standalone Node agent-proxy after it accepts an ingest event
+ that triggers a Temporal heartbeat or an awaiting-input push notification.
+ The request is authenticated with the original sandbox event ingest JWT so
+ Django can re-validate claims without an extra token round-trip.
+ """
+
+ kind = serializers.ChoiceField(
+ choices=["heartbeat", "awaiting_input"],
+ help_text=(
+ "Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its "
+ "inactivity timer. 'awaiting_input' fires a mobile push notification when an "
+ "interactive run finishes a turn and is waiting for user input."
+ ),
+ )
+ agent_active = serializers.BooleanField(
+ help_text=(
+ "Whether the agent is currently active (true) or idle (false). "
+ "For 'heartbeat' callbacks this is always true. "
+ "For 'awaiting_input' callbacks this is always false."
+ ),
+ )
+ task_id = serializers.CharField(
+ max_length=36,
+ help_text="UUID of the Task that owns this run. Must match the JWT claim.",
+ )
+ team_id = serializers.IntegerField(
+ min_value=1,
+ help_text="Numeric team (project) ID. Must match the JWT claim.",
+ )
+
+
+class AgentProxyCallbackResponseSerializer(serializers.Serializer):
+ """Response from the agent-proxy side-effect callback."""
+
+ dispatched = serializers.BooleanField(
+ help_text="True when the requested side effect was dispatched; false when skipped (e.g. run not found)."
+ )
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index ba06cc2f5b88..9d15bda6cb38 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -64,6 +64,7 @@ from products.tasks.backend.presentation.serializers import (
SandboxEnvironmentWriteSerializer,
SlackThreadContextQuerySerializer,
SlackThreadContextResponseSerializer,
+ StreamReadTokenResponseSerializer,
TaskAutomationSerializer,
TaskAutomationWriteSerializer,
TaskListQuerySerializer,
@@ -113,6 +114,9 @@ TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}
TASK_RUN_STREAM_CONNECTION_MAX_SECONDS = 15 * 60
TASK_RUN_STREAM_END_EVENT_NAME = "end"
TASK_RUN_STREAM_ROTATED_PAYLOAD = {"type": "rotated"}
+# Distinct from the rotation `end` event above: this fires once when the run itself
+# completes, so clients stop reconnecting instead of resuming from Last-Event-ID.
+TASK_RUN_STREAM_COMPLETE_EVENT_NAME = "stream-end"
TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60
@@ -680,7 +684,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
task_id = self._task_id()
is_internal_debug_read = (
_is_internal_debug_team(self.team_id)
- and self.action in ("list", "retrieve", "logs", "session_logs", "stream")
+ and self.action in ("list", "retrieve", "logs", "session_logs", "stream", "stream_token")
and self.request.query_params.get("ph_debug") == "true"
)
if not tasks_facade.task_accessible_for_run_view(
@@ -1209,6 +1213,33 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
return Response(ConnectionTokenResponseSerializer({"token": token}).data)
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(
+ response=StreamReadTokenResponseSerializer,
+ description="Run-scoped token for reading the live event stream via the agent-proxy",
+ ),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Get task run stream read token",
+ description="Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy.",
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="stream_token",
+ required_scopes=["task:read"],
+ )
+ def stream_token(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ token = tasks_facade.create_task_run_stream_read_token(pk, task_id, self.team_id)
+ if token is None:
+ raise NotFound()
+ stream_base_url = tasks_facade.resolve_stream_base_url(
+ distinct_id=request.user.distinct_id, organization_id=self.team.organization_id
+ )
+ return Response(StreamReadTokenResponseSerializer({"token": token, "stream_base_url": stream_base_url}).data)
+
@validated_request(
request_serializer=TaskRunCommandRequestSerializer,
responses={
@@ -1738,6 +1769,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
return
outcome = "completed"
+ # read_stream_entries only returns on the completion sentinel; emit an
+ # explicit terminal event so the client stops reconnecting without
+ # consulting run status (a dropped connection never reaches here).
+ yield format_sse_event({"status": "complete"}, event_name=TASK_RUN_STREAM_COMPLETE_EVENT_NAME)
except TaskRunStreamError as e:
outcome = "stream_error"
logger.error("TaskRunRedisStream error for stream %s: %s", stream_key, e, exc_info=True)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index fa5f2553603d..84dc0196c822 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -200,6 +200,12 @@ def _is_sandbox_event_ingest_enabled(
run_id: str,
state: dict | None = None,
) -> bool:
+ # Local dev disables the analytics SDK, so the captured flag below is always False there.
+ # Pointing ingest at the local agent-proxy is the opt-in and must win over the captured value;
+ # prod (DEBUG off) still gates on the flag.
+ if settings.DEBUG and settings.TASKS_AGENT_PROXY_INGEST_URL:
+ return True
+
state_override = (state or {}).get("sandbox_event_ingest_enabled")
if isinstance(state_override, bool):
log_with_activity_context(
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 57180ff67b51..6929fce8dbfa 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -1,6 +1,8 @@
import shlex
from dataclasses import dataclass
+from django.conf import settings
+
from temporalio import activity
from posthog.temporal.common.logger import get_logger
@@ -142,6 +144,10 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
event_stream_ingest_enabled = ctx.sandbox_event_ingest_enabled
event_ingest_token: str | None = None
+ # When the agent-proxy is configured, route the sandbox ingest POST to it instead of the
+ # Django ASGI short-circuit. Only meaningful once sequenced ingest is enabled. Unset means
+ # the agent falls back to POSTHOG_API_URL (Django).
+ event_ingest_url: str | None = settings.TASKS_AGENT_PROXY_INGEST_URL if event_stream_ingest_enabled else None
if event_stream_ingest_enabled:
try:
task_run = TaskRun.objects.get(id=ctx.run_id, task_id=ctx.task_id, team_id=ctx.team_id)
@@ -226,6 +232,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
mcp_configs=mcp_configs or None,
allowed_domains=agentsh_domains,
event_ingest_token=event_ingest_token,
+ event_ingest_url=event_ingest_url,
)
# Mark startup-time token issuance so follow-ups within the next
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
new file mode 100644
index 000000000000..35a625d84c5e
--- /dev/null
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -0,0 +1,169 @@
+import json
+from typing import Any
+
+from unittest.mock import patch
+
+from django.test import TransactionTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team
+
+from products.tasks.backend.logic.services.connection_token import (
+ create_sandbox_event_ingest_token,
+ reset_sandbox_jwt_key_cache,
+)
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
+
+
+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+class TestAgentProxyCallback(TransactionTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ reset_sandbox_jwt_key_cache()
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.task = Task.objects.create(
+ team=self.team,
+ title="Test Task",
+ description="Test Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ self.task_run: TaskRun = self.task.create_run()
+
+ def tearDown(self) -> None:
+ reset_sandbox_jwt_key_cache()
+ super().tearDown()
+
+ def _url(self, run_id: str | None = None) -> str:
+ return f"/internal/tasks/runs/{run_id or self.task_run.id}/agent-proxy-callback/"
+
+ def _token(self, run: TaskRun | None = None) -> str:
+ return create_sandbox_event_ingest_token(run or self.task_run)
+
+ def _body(self, **overrides: Any) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "kind": "heartbeat",
+ "agent_active": True,
+ "task_id": str(self.task.id),
+ "team_id": self.team.id,
+ }
+ body.update(overrides)
+ return body
+
+ def _post(self, body: dict[str, Any], token: str | None, run_id: str | None = None, secret: str | None = None):
+ kwargs: dict[str, Any] = {"content_type": "application/json"}
+ if token is not None:
+ kwargs["HTTP_AUTHORIZATION"] = f"Bearer {token}"
+ if secret is not None:
+ kwargs["HTTP_X_AGENT_PROXY_SECRET"] = secret
+ return self.client.post(self._url(run_id), data=json.dumps(body), **kwargs)
+
+ def test_get_method_returns_405(self) -> None:
+ response = self.client.get(self._url(), HTTP_AUTHORIZATION=f"Bearer {self._token()}")
+ self.assertEqual(response.status_code, 405)
+
+ @override_settings(AGENT_PROXY_CALLBACK_SECRET="proxy-only-secret")
+ def test_callback_secret_required_when_configured(self) -> None:
+ # A valid ingest JWT without the shared secret is rejected: the JWT is also held by the
+ # sandbox, so the secret is what proves the call came from the agent-proxy.
+ self.assertEqual(self._post(self._body(), token=self._token()).status_code, 403)
+ self.assertEqual(self._post(self._body(), token=self._token(), secret="wrong").status_code, 403)
+ # Correct secret passes the gate and reaches body handling (empty body is a 400, not a 403).
+ self.assertEqual(self._post({}, token=self._token(), secret="proxy-only-secret").status_code, 400)
+
+ @override_settings(AGENT_PROXY_CALLBACK_SECRET=None, DEBUG=False, TEST=False)
+ def test_callback_fails_closed_when_secret_unset_outside_dev(self) -> None:
+ # Production with no secret provisioned: the endpoint refuses even a valid ingest JWT
+ # rather than letting sandboxes drive side effects directly.
+ response = self._post(self._body(), token=self._token())
+ self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.json()["error"], "Agent-proxy callback secret is not configured")
+
+ @override_settings(AGENT_PROXY_CALLBACK_SECRET=None)
+ def test_callback_allows_unset_secret_in_test_mode(self) -> None:
+ # Local dev/test has no proxy deployment to share a secret with; the gate stays open so
+ # the callback remains exercisable (empty body reaches handling: 400, not 403).
+ self.assertEqual(self._post({}, token=self._token()).status_code, 400)
+
+ def test_missing_authorization_returns_401(self) -> None:
+ response = self.client.post(self._url(), data=json.dumps(self._body()), content_type="application/json")
+ self.assertEqual(response.status_code, 401)
+
+ @parameterized.expand(
+ [
+ ("no_bearer_prefix", "Token abc"),
+ ("empty_bearer", "Bearer "),
+ ("garbage_token", "Bearer not-a-jwt"),
+ ]
+ )
+ def test_invalid_authorization_returns_401(self, _name: str, header: str) -> None:
+ response = self.client.post(
+ self._url(),
+ data=json.dumps(self._body()),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=header,
+ )
+ self.assertEqual(response.status_code, 401)
+
+ def test_token_run_mismatch_returns_403(self) -> None:
+ other_run = self.task.create_run()
+ response = self._post(self._body(), token=self._token(other_run))
+ self.assertEqual(response.status_code, 403)
+
+ def test_body_task_id_mismatch_returns_403(self) -> None:
+ response = self._post(self._body(task_id="00000000-0000-0000-0000-000000000000"), token=self._token())
+ self.assertEqual(response.status_code, 403)
+
+ def test_body_team_id_mismatch_returns_403(self) -> None:
+ response = self._post(self._body(team_id=self.team.id + 999), token=self._token())
+ self.assertEqual(response.status_code, 403)
+
+ def test_invalid_body_returns_400(self) -> None:
+ response = self._post({"kind": "heartbeat"}, token=self._token())
+ self.assertEqual(response.status_code, 400)
+
+ def test_heartbeat_dispatches_when_active(self) -> None:
+ with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:
+ response = self._post(self._body(kind="heartbeat", agent_active=True), token=self._token())
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["dispatched"])
+ heartbeat.assert_called_once_with(agent_active=True)
+
+ def test_heartbeat_not_dispatched_when_inactive(self) -> None:
+ with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:
+ response = self._post(self._body(kind="heartbeat", agent_active=False), token=self._token())
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(response.json()["dispatched"])
+ heartbeat.assert_not_called()
+
+ def test_awaiting_input_dispatches_for_interactive_run(self) -> None:
+ run = self.task.create_run(mode="interactive")
+ with patch("products.tasks.backend.agent_proxy_callback.notify_task_run_awaiting_input") as notify:
+ response = self._post(
+ self._body(kind="awaiting_input", agent_active=False),
+ token=self._token(run),
+ run_id=str(run.id),
+ )
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["dispatched"])
+ notify.assert_called_once()
+
+ def test_awaiting_input_skipped_for_background_run(self) -> None:
+ with patch("products.tasks.backend.agent_proxy_callback.notify_task_run_awaiting_input") as notify:
+ response = self._post(self._body(kind="awaiting_input", agent_active=False), token=self._token())
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(response.json()["dispatched"])
+ notify.assert_not_called()
+
+ def test_unknown_run_returns_200_not_dispatched(self) -> None:
+ run = self.task.create_run()
+ run_id = str(run.id)
+ token = self._token(run)
+ TaskRun.objects.filter(id=run_id).delete()
+ with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:
+ response = self._post(self._body(kind="heartbeat", agent_active=True), token=token, run_id=run_id)
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(response.json()["dispatched"])
+ heartbeat.assert_not_called()
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 8572a1920ddc..6deba054e3b6 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -4970,6 +4970,103 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertIn("distinct_id", decoded)
self.assertEqual(decoded["distinct_id"], self.user.distinct_id)
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @override_settings(SANDBOX_JWT_PUBLIC_KEY=None)
+ def test_stream_token_returns_run_scoped_jwt(self):
+ reset_sandbox_jwt_key_cache()
+
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ data = response.json()
+ self.assertIn("token", data)
+ # No proxy URL configured for this environment, so clients read from Django directly.
+ self.assertIsNone(data["stream_base_url"])
+
+ public_key = get_sandbox_jwt_public_key()
+ decoded = jwt.decode(
+ data["token"],
+ public_key,
+ audience="posthog:stream_read",
+ algorithms=["RS256"],
+ )
+
+ self.assertEqual(decoded["run_id"], str(run.id))
+ self.assertEqual(decoded["task_id"], str(task.id))
+ self.assertEqual(decoded["team_id"], self.team.id)
+ self.assertNotIn("user_id", decoded)
+ self.assertIn("exp", decoded)
+
+ def test_stream_token_returns_proxy_url_when_configured_and_flag_enabled(self):
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ with (
+ self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
+ patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True),
+ ):
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")
+
+ def test_stream_token_omits_proxy_url_when_flag_disabled(self):
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ # Disable only the stream-via-proxy flag; leave other flags at their real values so the
+ # request's own access checks still pass.
+ def flag_enabled(key, *args, **kwargs):
+ return key != "tasks-stream-via-proxy"
+
+ with (
+ self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
+ patch(
+ "products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
+ side_effect=flag_enabled,
+ ),
+ ):
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(response.json()["stream_base_url"])
+
+ def test_stream_token_returns_proxy_url_in_debug_without_flag(self):
+ # Local dev (DEBUG) disables the analytics SDK, so the URL setting alone opts in.
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ with self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="http://localhost:8003", DEBUG=True):
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["stream_base_url"], "http://localhost:8003")
+
+ def test_stream_token_omits_proxy_url_when_flag_evaluation_fails(self):
+ # A flag-service outage must fall back to reading from Django, not break token issuance.
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ def flag_enabled(key, *args, **kwargs):
+ if key == "tasks-stream-via-proxy":
+ raise RuntimeError("flag service unavailable")
+ return True
+
+ with (
+ self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
+ patch(
+ "products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
+ side_effect=flag_enabled,
+ ),
+ ):
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(response.json()["stream_base_url"])
+
def test_connection_token_cannot_access_other_team_run(self):
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Team")
@@ -4986,6 +5083,20 @@ class TestTaskRunAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ def test_stream_token_cannot_access_other_team_run(self):
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ other_task = Task.objects.create(
+ team=other_team,
+ title="Other Task",
+ description="Description",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ other_run = TaskRun.objects.create(task=other_task, team=other_team, status=TaskRun.Status.IN_PROGRESS)
+
+ response = self.client.get(f"/api/projects/@current/tasks/{other_task.id}/runs/{other_run.id}/stream_token/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
class TestTaskRunSessionLogsAPI(BaseTaskAPITest):
"""Tests for the GET .../session_logs/ endpoint that returns filtered log entries."""
@@ -5307,8 +5418,10 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
events = self._collect_sse_events(response)
- self.assertEqual(len(events), 1)
- self.assertEqual(events[0]["data"]["notification"]["method"], "_posthog/sandbox_output")
+ data_events = [event for event in events if event["event"] != "stream-end"]
+ self.assertEqual(len(data_events), 1)
+ self.assertEqual(data_events[0]["data"]["notification"]["method"], "_posthog/sandbox_output")
+ self.assertEqual(events[-1]["event"], "stream-end")
def test_stream_start_latest_only_yields_new_events(self):
task = self.create_task()
@@ -5340,9 +5453,13 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):
events = self._collect_sse_events(response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertGreaterEqual(len(events), 1)
- self.assertTrue(all(event["data"]["notification"]["method"] == "_posthog/console" for event in events), events)
- self.assertEqual(events[-1]["data"]["notification"]["params"]["message"], "late hello")
+ data_events = [event for event in events if event["event"] not in ("stream-end", "keepalive")]
+ self.assertGreaterEqual(len(data_events), 1)
+ self.assertTrue(
+ all(event["data"]["notification"]["method"] == "_posthog/console" for event in data_events), data_events
+ )
+ self.assertEqual(data_events[-1]["data"]["notification"]["params"]["message"], "late hello")
+ self.assertEqual(events[-1]["event"], "stream-end")
class TestTaskRunRedisStreamKeepalive(TestCase):
@@ -5593,12 +5710,16 @@ class TestTaskRunStreamConnectionCapAPI(BaseTaskAPITest):
self.assertEqual(second_response.status_code, status.HTTP_200_OK)
second_events = self._collect_sse_events(second_response)
+ # The run was marked complete, so the resumed connection ends with the in-band
+ # completion sentinel (id-less, so it can't poison the resume cursor) rather than
+ # a bare EOF or a rotation marker.
+ self.assertEqual(second_events[-1]["event"], "stream-end")
+ second_data_events = [event for event in second_events if event["event"] != "stream-end"]
# Resuming from the rotated connection's last id delivers the remaining
- # events exactly once — no gap, no duplicate — then completes without a
- # rotation marker.
- self.assertEqual([event["id"] for event in second_events], stream_ids[1:])
+ # events exactly once — no gap, no duplicate.
+ self.assertEqual([event["id"] for event in second_data_events], stream_ids[1:])
self.assertEqual(
- [event["data"]["notification"]["params"]["message"] for event in second_events],
+ [event["data"]["notification"]["params"]["message"] for event in second_data_events],
["first message", "second message"],
)
diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.py
index 70039d302008..b6aae52e60b6 100644
--- a/products/tasks/backend/tests/test_connection_token.py
+++ b/products/tasks/backend/tests/test_connection_token.py
@@ -1,10 +1,14 @@
import uuid
+from datetime import timedelta
from types import SimpleNamespace
from typing import cast
+import pytest
+
from django.test import SimpleTestCase, override_settings
import jwt
+from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
@@ -15,12 +19,15 @@ from products.tasks.backend.logic.services.connection_token import (
_derive_public_key_pem,
create_sandbox_connection_token,
create_sandbox_event_ingest_token,
+ create_stream_read_token,
get_primary_sandbox_jwt_kid,
get_sandbox_jwt_public_key,
reset_sandbox_jwt_key_cache,
validate_sandbox_event_ingest_token,
+ validate_stream_read_token,
)
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
def _generate_private_key_pem() -> str:
@@ -93,28 +100,61 @@ class TestSandboxJwtRotation(SimpleTestCase):
token = create_sandbox_connection_token(_fake_run({}), user_id=1, distinct_id="d")
self.assertEqual(jwt.get_unverified_header(token)["kid"], KID_A)
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A)
- def test_ingest_token_always_uses_primary_ignoring_run_kid(self) -> None:
+ @override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A, SANDBOX_JWT_PUBLIC_KEY=None
+ )
+ def test_ingest_token_signed_with_run_stored_kid(self) -> None:
reset_sandbox_jwt_key_cache()
- # The ingest path is single-key: it signs/validates with the primary key only and
- # ignores the run's stored kid (unlike the connection token).
+ # Like the connection token, the ingest token now carries a kid and is signed with the key
+ # the run was provisioned under, so the agent-proxy legs survive a primary-key rotation.
token = create_sandbox_event_ingest_token(_fake_run({SANDBOX_JWT_STATE_KID_KEY: KID_A}))
- self.assertNotIn("kid", jwt.get_unverified_header(token))
+ self.assertEqual(jwt.get_unverified_header(token)["kid"], KID_A)
payload = validate_sandbox_event_ingest_token(token)
self.assertEqual(payload.team_id, 1)
- def test_ingest_token_rejected_after_primary_rotation(self) -> None:
- # Ingest is intentionally NOT rotation-safe: a token signed under the old primary
- # stops validating once the primary is rotated, even if the old key is kept as secondary.
+ def test_ingest_token_validates_after_primary_rotation(self) -> None:
+ # Ingest is rotation-safe: a token signed under the old primary keeps validating after the
+ # primary rotates, as long as the old key is retained as the secondary.
with override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None):
reset_sandbox_jwt_key_cache()
token = create_sandbox_event_ingest_token(_fake_run())
- with override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A):
+ with override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A, SANDBOX_JWT_PUBLIC_KEY=None
+ ):
+ reset_sandbox_jwt_key_cache()
+ payload = validate_sandbox_event_ingest_token(token)
+ self.assertEqual(payload.team_id, 1)
+
+ # Once the old key is dropped entirely the token no longer validates.
+ with override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None, SANDBOX_JWT_PUBLIC_KEY=None
+ ):
reset_sandbox_jwt_key_cache()
with self.assertRaises(jwt.InvalidTokenError):
validate_sandbox_event_ingest_token(token)
+ def test_stream_read_token_validates_after_primary_rotation(self) -> None:
+ # The stream-read leg must survive rotation the same way ingest does: a token signed under
+ # the old primary keeps validating while the old key is retained as the secondary.
+ with override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None):
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_run())
+
+ with override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A, SANDBOX_JWT_PUBLIC_KEY=None
+ ):
+ reset_sandbox_jwt_key_cache()
+ payload = validate_stream_read_token(token)
+ self.assertEqual(payload.team_id, 1)
+
+ with override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_B, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None, SANDBOX_JWT_PUBLIC_KEY=None
+ ):
+ reset_sandbox_jwt_key_cache()
+ with self.assertRaises(jwt.InvalidTokenError):
+ validate_stream_read_token(token)
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)
def test_connection_token_rejected_as_ingest_token(self) -> None:
reset_sandbox_jwt_key_cache()
@@ -123,7 +163,9 @@ class TestSandboxJwtRotation(SimpleTestCase):
with self.assertRaises(jwt.InvalidTokenError):
validate_sandbox_event_ingest_token(token)
- @override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A)
+ @override_settings(
+ SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=KEY_A, SANDBOX_JWT_PUBLIC_KEY=None
+ )
def test_duplicate_primary_and_secondary_collapse_to_one_key(self) -> None:
reset_sandbox_jwt_key_cache()
token = create_sandbox_event_ingest_token(_fake_run({SANDBOX_JWT_STATE_KID_KEY: KID_A}))
@@ -131,3 +173,75 @@ class TestSandboxJwtRotation(SimpleTestCase):
self.assertEqual(payload.team_id, 1)
self.assertEqual(get_primary_sandbox_jwt_kid(), KID_A)
self.assertEqual(get_sandbox_jwt_public_key(), _derive_public_key_pem(KEY_A))
+
+
+_RUN_ID = "11111111-1111-1111-1111-111111111111"
+_TASK_ID = "22222222-2222-2222-2222-222222222222"
+
+
+def _fake_task_run() -> TaskRun:
+ return cast(TaskRun, SimpleNamespace(id=_RUN_ID, task_id=_TASK_ID, team_id=7, state={}))
+
+
+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY, SANDBOX_JWT_PUBLIC_KEY=None)
+def test_stream_read_token_roundtrip():
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_task_run())
+
+ claims = validate_stream_read_token(token)
+
+ assert claims.run_id == _RUN_ID
+ assert claims.task_id == _TASK_ID
+ assert claims.team_id == 7
+
+
+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY, SANDBOX_JWT_PUBLIC_KEY=None)
+def test_stream_read_token_rejects_expired():
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_task_run(), ttl=timedelta(seconds=-1))
+
+ with pytest.raises(jwt.ExpiredSignatureError):
+ validate_stream_read_token(token)
+
+
+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY, SANDBOX_JWT_PUBLIC_KEY=None)
+def test_stream_read_token_is_not_accepted_for_event_ingest():
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_task_run())
+
+ with pytest.raises(jwt.InvalidAudienceError):
+ validate_sandbox_event_ingest_token(token)
+
+
+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY, SANDBOX_JWT_PUBLIC_KEY=None)
+def test_event_ingest_token_is_not_accepted_for_stream_read():
+ reset_sandbox_jwt_key_cache()
+ token = create_sandbox_event_ingest_token(_fake_task_run())
+
+ with pytest.raises(jwt.InvalidAudienceError):
+ validate_stream_read_token(token)
+
+
+def _public_key_for(private_key_pem: str) -> str:
+ private_key = serialization.load_pem_private_key(private_key_pem.encode(), password=None, backend=default_backend())
+ return (
+ private_key.public_key()
+ .public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)
+ .decode()
+ )
+
+
+def test_stream_read_token_validates_with_public_key_only():
+ # Django mints with the private key; a verify-only service (agent-proxy) validates with ONLY
+ # the public key configured and no private key present.
+ with override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY, SANDBOX_JWT_PUBLIC_KEY=None):
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_task_run())
+
+ with override_settings(SANDBOX_JWT_PRIVATE_KEY=None, SANDBOX_JWT_PUBLIC_KEY=_public_key_for(TEST_RSA_PRIVATE_KEY)):
+ reset_sandbox_jwt_key_cache()
+ claims = validate_stream_read_token(token)
+
+ assert claims.run_id == _RUN_ID
+ assert claims.team_id == 7
+ reset_sandbox_jwt_key_cache()
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index 7f66c1203013..5f68a9988167 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -10,7 +10,7 @@ from django.test import TestCase, override_settings
from asgiref.sync import async_to_sync
from parameterized import parameterized
-from posthog.models import Organization, Team
+from posthog.models import Organization, Team, User
from posthog.redis import TEST_clear_clients
from products.tasks.backend.logic.services.connection_token import (
@@ -201,6 +201,47 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(body["accepted"], 1)
self.assertEqual(self._read_notification_methods(), ["session/update"])
+ @parameterized.expand([(True,), (False,)])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_turn_complete_ingest_notifies_interactive_run_awaiting_input_only_with_flag(
+ self, flag_enabled: bool
+ ) -> None:
+ self.task.created_by = User.objects.create_user("[email protected]", None, "Ingest")
+ self.task.save(update_fields=["created_by"])
+ self.task_run.state = {"mode": "interactive"}
+ self.task_run.save(update_fields=["state"])
+ token = self._create_token()
+
+ with (
+ patch(
+ "products.tasks.backend.logic.stream.event_ingest.notify_task_run_awaiting_input"
+ ) as notify_awaiting_input,
+ patch(
+ "products.tasks.backend.logic.stream.event_ingest.posthoganalytics.feature_enabled",
+ return_value=flag_enabled,
+ ),
+ ):
+ status, body = self._call_ingest(
+ token,
+ [
+ {
+ "seq": 1,
+ "event": {
+ "type": "notification",
+ "notification": {"method": "_posthog/turn_complete"},
+ },
+ }
+ ],
+ )
+
+ self.assertEqual(status, 200)
+ self.assertEqual(body["accepted"], 1)
+ if flag_enabled:
+ notify_awaiting_input.assert_called_once()
+ self.assertEqual(notify_awaiting_input.call_args.args[0].id, self.task_run.id)
+ else:
+ notify_awaiting_input.assert_not_called()
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_workflow_heartbeat_does_not_block_event_loop(self) -> None:
token = self._create_token()
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 8138cf9d6164..8a8514a6a068 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1535,6 +1535,19 @@ export interface TaskRunStartRequestApi {
pending_user_artifact_ids?: string[]
}
+/**
+ * Response containing a JWT token (and resolved base URL) for reading a task run's live event stream
+ */
+export interface StreamReadTokenResponseApi {
+ /** Run-scoped JWT the browser presents to the agent-proxy to read this run's live event stream */
+ token: string
+ /**
+ * Base URL of the agent-proxy to read the stream from when routing via the proxy is enabled for this user. Null means read from the Django endpoint directly (same-origin). The client appends the run's stream path and sends the token as a Bearer header when this is set.
+ * @nullable
+ */
+ stream_base_url: string | null
+}
+
export interface TaskRepositoriesResponseApi {
/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */
repositories: string[]
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index fbfa4d402f72..698b8de5f147 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -26,6 +26,7 @@ import type {
SandboxEnvironmentWriteApi,
SandboxListParams,
SlackThreadContextResponseApi,
+ StreamReadTokenResponseApi,
TaskAutomationDTOApi,
TaskAutomationWriteApi,
TaskAutomationsListParams,
@@ -1012,6 +1013,26 @@ export const tasksRunsStreamRetrieve = async (
})
}
+export const getTasksRunsStreamTokenRetrieveUrl = (projectId: string, taskId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream_token/`
+}
+
+/**
+ * Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy.
+ * @summary Get task run stream read token
+ */
+export const tasksRunsStreamTokenRetrieve = async (
+ projectId: string,
+ taskId: string,
+ id: string,
+ options?: RequestInit
+): Promise<StreamReadTokenResponseApi> => {
+ return apiMutator<StreamReadTokenResponseApi>(getTasksRunsStreamTokenRetrieveUrl(projectId, taskId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTasksRepositoriesRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tasks/repositories/`
}
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
index 11fa68c7a019..c32b0d8f1ab3 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts
@@ -1,6 +1,9 @@
import { expectLogic } from 'kea-test-utils'
import { ReadableStream as NodeReadableStream } from 'stream/web'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { initKeaTests } from '~/test/init'
import { OriginProduct, Task, TaskRun, TaskRunEnvironment, TaskRunStatus } from '../types'
@@ -41,7 +44,7 @@ const createMockRun = (id: string, status: TaskRunStatus): TaskRun => ({
completed_at: null,
})
-function buildReadableStream(chunks: string[], keepOpen = false, onClose?: () => void): ReadableStream<Uint8Array> {
+function buildReadableStream(chunks: string[], keepOpen = false): ReadableStream<Uint8Array> {
const encoder = new TextEncoder()
let index = 0
const StreamConstructor = globalThis.ReadableStream ?? NodeReadableStream
@@ -52,17 +55,16 @@ function buildReadableStream(chunks: string[], keepOpen = false, onClose?: () =>
controller.enqueue(encoder.encode(chunks[index]))
index += 1
} else if (!keepOpen) {
- onClose?.()
controller.close()
}
},
})
}
-function createSseResponse(chunks: string[], keepOpen = false, onClose?: () => void): Response {
+function createSseResponse(chunks: string[], keepOpen = false): Response {
return {
ok: true,
- body: buildReadableStream(chunks, keepOpen, onClose),
+ body: buildReadableStream(chunks, keepOpen),
} as Response
}
@@ -108,18 +110,29 @@ function createJsonResponse(payload: unknown): Response {
function createFetchMock({
runs = {},
streamResponses = [],
+ streamBaseUrl = null,
}: {
runs?: Record<string, TaskRun>
streamResponses?: Response[]
+ streamBaseUrl?: string | null
} = {}): typeof fetch {
return jest.fn((input: RequestInfo | URL) => {
const url = String(input)
+ const streamTokenMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/stream_token\/$/)
const taskRunMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/$/)
- const streamMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/stream\/$/)
+ // Matches both the Django read path (.../runs/:run/stream/) and the proxy path (/v1/runs/:run/stream).
+ const streamMatch = url.match(/\/runs\/([^/]+)\/stream\/?(\?|$)/)
const logsMatch = url.match(/\/tasks\/([^/]+)\/runs\/([^/]+)\/logs\/$/)
const runsListMatch = url.match(/\/tasks\/([^/]+)\/runs\/$/)
const taskMatch = url.match(/\/tasks\/([^/]+)\/$/)
+ if (url.includes('/_preflight')) {
+ // Keep is_debug unset so streamViaProxyEnabled is driven purely by the feature flag.
+ return Promise.resolve(createJsonResponse({}))
+ }
+ if (streamTokenMatch) {
+ return Promise.resolve(createJsonResponse({ token: 'proxy-test-token', stream_base_url: streamBaseUrl }))
+ }
if (streamMatch) {
const nextResponse = streamResponses.shift()
if (!nextResponse) {
@@ -146,14 +159,26 @@ function createFetchMock({
}
async function flushStreaming(): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, 0))
- await new Promise((resolve) => setTimeout(resolve, 0))
+ // fetch-event-source has a deeper internal async chain (fetch -> onopen -> getBytes
+ // -> getLines -> getMessages -> onmessage), so flush several macro+micro cycles.
+ for (let i = 0; i < 6; i++) {
+ await Promise.resolve()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ }
}
describe('taskDetailSceneLogic', () => {
const originalFetch = global.fetch
beforeEach(() => {
+ // featureFlagLogic persists flags to localStorage and hydrates as soon as initKeaTests
+ // mounts the common logics, so clear before init or flags enabled in one test leak into
+ // the next.
+ window.localStorage.clear()
+ // preflightLogic prefers the app context over fetching, and the default test fixture has
+ // is_debug: true, which would force streamViaProxyEnabled on. Pin it to false so the
+ // feature flag alone drives the rollout-gated behavior in these tests.
+ window.POSTHOG_APP_CONTEXT = { preflight: { is_debug: false } } as unknown as typeof window.POSTHOG_APP_CONTEXT
initKeaTests()
global.fetch = createFetchMock()
})
@@ -266,13 +291,53 @@ describe('taskDetailSceneLogic', () => {
})
describe('streaming', () => {
- it('restarts streaming after a clean EOF when the run is still in progress', async () => {
+ const getHeader = (init: RequestInit | undefined, name: string): string | undefined => {
+ const headers = (init?.headers ?? {}) as Record<string, string>
+ const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name.toLowerCase())
+ return key !== undefined ? headers[key] : undefined
+ }
+
+ const streamFetchCalls = (): [RequestInfo | URL, RequestInit | undefined][] =>
+ (global.fetch as jest.Mock).mock.calls.filter(([url]) => /\/runs\/[^/]+\/stream\/?(\?|$)/.test(String(url)))
+
+ const streamTokenFetchCalls = (): [RequestInfo | URL, RequestInit | undefined][] =>
+ (global.fetch as jest.Mock).mock.calls.filter(([url]) => String(url).includes('/stream_token/'))
+
+ // The durable-streaming rollout flag gates stream_token resolution and status-unaware
+ // streams; tests covering the new behavior opt in explicitly, the rest run with it off.
+ const enableProxyStreaming = (): void =>
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY], {
+ [FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY]: true,
+ })
+
+ beforeEach(() => {
+ window.sessionStorage.clear()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('streams events, dedupes by id, and resumes from the last event id on restart', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
- createSseResponse([createConsoleSseEvent('1-0', 'first message')]),
- createSseResponse([createConsoleSseEvent('2-0', 'second message')], true),
+ createSseResponse(
+ [
+ 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
+ 'id: 2-0\nevent: message\ndata: {"type":"assistant","content":"world"}\n\n',
+ ],
+ true
+ ),
+ createSseResponse(
+ [
+ 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
+ 'event: keepalive\ndata: {"status":"ok"}\n\n',
+ 'id: 3-0\nevent: message\ndata: {"type":"assistant","content":"again"}\n\n',
+ ],
+ true
+ ),
],
})
@@ -283,30 +348,34 @@ describe('taskDetailSceneLogic', () => {
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
+
+ expect(logic.values.lastStreamEventId).toBe('2-0')
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'world'])
+
+ logic.actions.stopStreaming()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.startStreaming()
+ await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(2)
- expect(logic.values.isStreaming).toBe(true)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([
- 'first message',
- 'second message',
- ])
- expect(logic.values.streamEntries.map((entry) => entry.id)).toEqual(['stream-1-0', 'stream-2-0'])
+ const calls = streamFetchCalls()
+ expect(calls).toHaveLength(2)
+ expect(getHeader(calls[1][1], 'Last-Event-ID')).toBe('2-0')
+ expect(logic.values.lastStreamEventId).toBe('3-0')
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'worldagain'])
logic.unmount()
})
- it('resumes the automatic restart with Last-Event-ID and ignores replayed events', async () => {
+ it('resumes from the sessionStorage event id after a page refresh', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
+ window.sessionStorage.setItem('tasks:stream-resume:run-1', '5-0')
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
- createSseResponse([createConsoleSseEvent('1-0', 'first message')]),
createSseResponse(
- [createConsoleSseEvent('1-0', 'first message'), createConsoleSseEvent('2-0', 'second message')],
+ ['id: 6-0\nevent: message\ndata: {"type":"assistant","content":"resumed"}\n\n'],
true
),
],
@@ -319,76 +388,71 @@ describe('taskDetailSceneLogic', () => {
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- await flushStreaming()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(2)
- expect((streamCalls[1][1] as RequestInit)?.headers).toMatchObject({
- Accept: 'text/event-stream',
- 'Last-Event-ID': '1-0',
- })
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([
- 'first message',
- 'second message',
- ])
+ const calls = streamFetchCalls()
+ expect(calls).toHaveLength(1)
+ expect(getHeader(calls[0][1], 'Last-Event-ID')).toBe('5-0')
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['resumed'])
logic.unmount()
})
- it('ignores the rotation end marker and skips the log refetch on rotation resume', async () => {
- const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
+ it('stops on a stream-end event for a terminal run without reconnecting or downgrading to polling', async () => {
+ const run = createMockRun('run-1', TaskRunStatus.COMPLETED)
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
createSseResponse([
- createConsoleSseEvent('1-0', 'first message'),
- 'event: end\ndata: {"type": "rotated"}\n\n',
+ createConsoleSseEvent('1-0', 'hello'),
+ 'event: stream-end\ndata: {"status":"complete"}\n\n',
]),
- createSseResponse([createConsoleSseEvent('2-0', 'second message')], true),
],
})
const logic = taskDetailSceneLogic({ taskId: 'task-123' })
logic.mount()
+ enableProxyStreaming()
await expectLogic(logic).toFinishAllListeners()
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
+
+ expect(logic.values.streamComplete).toBe(true)
+ expect(logic.values.streamingFailed).toBe(false)
+ expect(logic.values.isStreaming).toBe(false)
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
+ expect(streamFetchCalls()).toHaveLength(1)
+ expect(window.sessionStorage.getItem('tasks:stream-resume:run-1')).toBeNull()
+
+ logic.unmount()
+ })
+
+ it('keeps the pre-proxy behavior with the flag off: terminal runs never stream or fetch a stream token', async () => {
+ const run = createMockRun('run-1', TaskRunStatus.COMPLETED)
+ global.fetch = createFetchMock({ runs: { [run.id]: run } })
+
+ const logic = taskDetailSceneLogic({ taskId: 'task-123' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setSelectedRunId(run.id, 'task-123')
+ await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- const fetchCalls = (global.fetch as jest.Mock).mock.calls.map(([url]) => String(url))
- expect(fetchCalls.filter((url) => url.includes('/stream/'))).toHaveLength(2)
- // The rotation marker is not rendered as a log entry
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([
- 'first message',
- 'second message',
- ])
- // The rotation resume skips the redundant log-file refetch — only the
- // initial run selection fetches it while entries are streaming
- expect(fetchCalls.filter((url) => url.includes('/logs/'))).toHaveLength(1)
+ expect(logic.values.isStreaming).toBe(false)
+ expect(streamFetchCalls()).toHaveLength(0)
+ expect(streamTokenFetchCalls()).toHaveLength(0)
logic.unmount()
})
- it('drains the missed tail when a rotation EOF races run completion', async () => {
+ it('streams live runs with the flag off via the Django path without fetching a stream token', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
- createSseResponse(
- [createConsoleSseEvent('1-0', 'first message'), 'event: end\ndata: {"type": "rotated"}\n\n'],
- false,
- // The run completes while the rotated connection is reconnecting,
- // so the post-EOF refetch sees a terminal run
- () => {
- run.status = TaskRunStatus.COMPLETED
- }
- ),
- // The drain connection delivers the tail then EOFs naturally
- createSseResponse([createConsoleSseEvent('2-0', 'tail message')]),
+ createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n'], true),
],
})
@@ -399,40 +463,25 @@ describe('taskDetailSceneLogic', () => {
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- await flushStreaming()
- await expectLogic(logic).toFinishAllListeners()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(2)
- expect((streamCalls[1][1] as RequestInit)?.headers).toMatchObject({
- Accept: 'text/event-stream',
- 'Last-Event-ID': '1-0',
- })
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['first message', 'tail message'])
+ const calls = streamFetchCalls()
+ expect(calls).toHaveLength(1)
+ expect(String(calls[0][0])).toContain('/api/projects/@current/tasks/task-123/runs/run-1/stream/')
+ expect(streamTokenFetchCalls()).toHaveLength(0)
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
logic.unmount()
})
- it('does not re-drain when the drain connection itself ends with a rotation marker', async () => {
+ it('polls after a stream-end event when the refreshed run is still in progress', async () => {
+ const setIntervalSpy = jest.spyOn(window, 'setInterval')
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
- createSseResponse(
- [createConsoleSseEvent('1-0', 'first message'), 'event: end\ndata: {"type": "rotated"}\n\n'],
- false,
- // The run completes while the rotated connection is reconnecting
- () => {
- run.status = TaskRunStatus.COMPLETED
- }
- ),
- // The completion sentinel was never written, so the drain connection
- // also rotates instead of EOFing naturally
createSseResponse([
- createConsoleSseEvent('2-0', 'tail message'),
- 'event: end\ndata: {"type": "rotated"}\n\n',
+ createConsoleSseEvent('1-0', 'hello'),
+ 'event: stream-end\ndata: {"status":"complete"}\n\n',
]),
],
})
@@ -444,155 +493,148 @@ describe('taskDetailSceneLogic', () => {
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- await flushStreaming()
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
- await expectLogic(logic).toFinishAllListeners()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(2)
+ expect(logic.values.streamComplete).toBe(true)
+ expect(logic.values.streamingFailed).toBe(false)
expect(logic.values.isStreaming).toBe(false)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['first message', 'tail message'])
+ expect(streamFetchCalls()).toHaveLength(1)
+ expect(setIntervalSpy).toHaveBeenCalledWith(expect.any(Function), 1000)
logic.unmount()
})
- it('falls back to polling after repeated immediate EOFs instead of reconnecting in a tight loop', async () => {
+ it('routes the stream through the proxy when the server resolves a stream base url', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
- streamResponses: [createSseResponse([]), createSseResponse([]), createSseResponse([])],
+ streamBaseUrl: 'https://proxy.example/',
+ streamResponses: [
+ createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hi"}\n\n'], true),
+ ],
})
const logic = taskDetailSceneLogic({ taskId: 'task-123' })
logic.mount()
+ enableProxyStreaming()
await expectLogic(logic).toFinishAllListeners()
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
- for (let i = 0; i < 6; i++) {
- await flushStreaming()
- }
- await expectLogic(logic).toFinishAllListeners()
+ await flushStreaming()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(3)
- expect(logic.values.streamingFailed).toBe(true)
- expect(logic.values.isStreaming).toBe(false)
+ const calls = streamFetchCalls()
+ expect(calls).toHaveLength(1)
+ expect(String(calls[0][0])).toBe('https://proxy.example/v1/runs/run-1/stream')
+ expect(getHeader(calls[0][1], 'Authorization')).toBe('Bearer proxy-test-token')
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hi'])
logic.unmount()
})
- it('starts polling when the post-EOF run refresh fails for an active run', async () => {
+ it('refreshes the stream token and reconnects when the proxy rejects an expired token', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
- streamResponses: [createSseResponse([], true)],
+ streamBaseUrl: 'https://proxy.example/',
+ streamResponses: [
+ new Response(JSON.stringify({ error: 'Invalid stream read token' }), { status: 401 }),
+ createSseResponse(['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hi"}\n\n'], true),
+ ],
})
const logic = taskDetailSceneLogic({ taskId: 'task-123' })
logic.mount()
+ enableProxyStreaming()
await expectLogic(logic).toFinishAllListeners()
logic.actions.setSelectedRunId(run.id, 'task-123')
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
+ await flushStreaming()
- // Mirror the real sequence: the stream EOFs (stopStreaming), then the
- // post-EOF run refresh fails
- logic.actions.stopStreaming()
- await expectLogic(logic, () => {
- logic.actions.loadSelectedRunFailure('network error')
- }).toDispatchActions(['startPolling'])
+ expect(streamTokenFetchCalls()).toHaveLength(2)
+ expect(streamFetchCalls()).toHaveLength(2)
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hi'])
+ expect(logic.values.streamingFailed).toBe(false)
logic.unmount()
})
- it.each<[string, TaskRunStatus | null]>([
- ['no run has loaded', null],
- ['the loaded run is terminal', TaskRunStatus.COMPLETED],
- ])('does not start polling when the run refresh fails and %s', async (_desc, status) => {
- if (status) {
- const run = createMockRun('run-1', status)
- global.fetch = createFetchMock({ runs: { [run.id]: run } })
- }
+ it('reconnects after a dropped connection without latching to polling', async () => {
+ jest.useFakeTimers()
+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
+ global.fetch = createFetchMock({
+ runs: { [run.id]: run },
+ streamResponses: [
+ // First connection emits one event then the body ends (a drop)
+ createSseResponse([createConsoleSseEvent('1-0', 'first message')]),
+ // Reconnect picks up the next event and stays open
+ createSseResponse([createConsoleSseEvent('2-0', 'second message')], true),
+ ],
+ })
const logic = taskDetailSceneLogic({ taskId: 'task-123' })
logic.mount()
- await expectLogic(logic).toFinishAllListeners()
+ await jest.advanceTimersByTimeAsync(0)
- if (status) {
- logic.actions.setSelectedRunId('run-1', 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- }
+ logic.actions.setSelectedRunId(run.id, 'task-123')
+ await jest.advanceTimersByTimeAsync(0)
+
+ // A drop must not immediately downgrade to polling
+ expect(logic.values.streamingFailed).toBe(false)
- await expectLogic(logic, () => {
- logic.actions.loadSelectedRunFailure('network error')
- }).toNotHaveDispatchedActions(['startPolling'])
+ // Advance past the first reconnect backoff (1000ms base)
+ await jest.advanceTimersByTimeAsync(1000)
+ await jest.advanceTimersByTimeAsync(0)
+
+ const calls = streamFetchCalls()
+ expect(calls).toHaveLength(2)
+ expect(logic.values.streamingFailed).toBe(false)
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([
+ 'first message',
+ 'second message',
+ ])
logic.unmount()
})
- it('does not restart an active stream when selected run reloads', async () => {
+ it('exhausts the reconnect budget when connections die immediately instead of looping forever', async () => {
+ jest.useFakeTimers()
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
- streamResponses: [
- createSseResponse(
- ['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hello"}\n\n'],
- true
- ),
- ],
+ // Initial connection plus MAX_STREAM_RECONNECTS retries, all dying instantly.
+ // None lives past STREAM_MIN_HEALTHY_CONNECTION_MS, so the budget never resets.
+ streamResponses: Array.from({ length: 7 }, () => createSseResponse([])),
})
const logic = taskDetailSceneLogic({ taskId: 'task-123' })
logic.mount()
- await expectLogic(logic).toFinishAllListeners()
+ await jest.advanceTimersByTimeAsync(0)
logic.actions.setSelectedRunId(run.id, 'task-123')
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
+ await jest.advanceTimersByTimeAsync(0)
- const streamCallsAfterFirstLoad = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCallsAfterFirstLoad).toHaveLength(1)
-
- logic.actions.loadSelectedRunSuccess(run)
- await expectLogic(logic).toFinishAllListeners()
- await flushStreaming()
+ // Walk through every reconnect backoff: 1s, 2s, 4s, 8s, then capped at 15s.
+ for (const backoffMs of [1000, 2000, 4000, 8000, 15000, 15000]) {
+ await jest.advanceTimersByTimeAsync(backoffMs)
+ await jest.advanceTimersByTimeAsync(0)
+ }
- const streamCallsAfterReload = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCallsAfterReload).toHaveLength(1)
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
+ expect(streamFetchCalls()).toHaveLength(7)
+ expect(logic.values.streamingFailed).toBe(true)
+ expect(logic.values.isStreaming).toBe(false)
logic.unmount()
})
- it('resumes with Last-Event-ID and ignores replayed events', async () => {
+ it('does not restart an active stream when selected run reloads', async () => {
const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)
global.fetch = createFetchMock({
runs: { [run.id]: run },
streamResponses: [
createSseResponse(
- [
- 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
- 'id: 2-0\nevent: message\ndata: {"type":"assistant","content":"world"}\n\n',
- ],
- true
- ),
- createSseResponse(
- [
- 'id: 1-0\nevent: message\ndata: {"type":"user","content":"hello"}\n\n',
- 'event: keepalive\ndata: {"status":"ok"}\n\n',
- 'id: 3-0\nevent: message\ndata: {"type":"assistant","content":"again"}\n\n',
- ],
+ ['id: 1-0\nevent: message\ndata: {"type":"assistant","content":"hello"}\n\n'],
true
),
],
@@ -606,26 +648,14 @@ describe('taskDetailSceneLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- expect(logic.values.lastStreamEventId).toBe('2-0')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'world'])
-
- logic.actions.stopStreaming()
- await expectLogic(logic).toFinishAllListeners()
+ expect(streamFetchCalls()).toHaveLength(1)
- logic.actions.startStreaming()
+ logic.actions.loadSelectedRunSuccess(run)
await expectLogic(logic).toFinishAllListeners()
await flushStreaming()
- const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
- String(url).includes('/stream/')
- )
- expect(streamCalls).toHaveLength(2)
- expect((streamCalls[1][1] as RequestInit)?.headers).toMatchObject({
- Accept: 'text/event-stream',
- 'Last-Event-ID': '2-0',
- })
- expect(logic.values.lastStreamEventId).toBe('3-0')
- expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello', 'worldagain'])
+ expect(streamFetchCalls()).toHaveLength(1)
+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['hello'])
logic.unmount()
})
diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
index 2ea87f071591..0496be4eb945 100644
--- a/products/tasks/frontend/logics/taskDetailSceneLogic.ts
+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.ts
@@ -15,11 +15,15 @@ import {
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
-import api from 'lib/api'
+import api, { type EventSourceMessage } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isUUIDLike } from 'lib/utils/guards'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { tasksRunsStreamTokenRetrieve } from '../generated/api'
import { LogEntry, parseLogEvent } from '../lib/parse-logs'
import { phDebugQueryParams, phDebugQuerySuffix } from '../lib/ph-debug'
import { TaskRun, TaskRunStatus } from '../types'
@@ -28,19 +32,47 @@ import { TaskLogicProps, taskLogic } from './taskLogic'
import { tasksLogic } from './tasksLogic'
const LOG_POLL_INTERVAL_MS = 1000
-// The server rotates stream connections on a fixed cap (clean EOF + Last-Event-ID
-// resume), so reconnect-after-EOF is a routine loop. If connections start dying
-// this quickly, something is wrong server-side — stop hammering it and fall back
-// to polling instead of reconnecting in a tight loop.
+// Reconnect the live stream a bounded number of times with exponential backoff
+// before giving up. End-of-run is signalled in-band (the `stream-end` event), so
+// a dropped connection always means "reconnect", never "the run is done".
+const MAX_STREAM_RECONNECTS = 6
+const STREAM_RECONNECT_BASE_MS = 1000
+const STREAM_RECONNECT_MAX_MS = 15000
+// A connection must stay open this long before a later drop earns a fresh reconnect
+// budget. Resetting on every open would let a rapid open-and-die loop reconnect forever.
const STREAM_MIN_HEALTHY_CONNECTION_MS = 5000
-const STREAM_MAX_CONSECUTIVE_SHORT_CONNECTIONS = 3
+// "Run is complete" terminal event. Named COMPLETE (not END) because connection-rotation
+// work introduces a separate `end` event that means "reconnect", the opposite semantics.
+const STREAM_COMPLETE_EVENT = 'stream-end'
export type TaskDetailSceneLogicProps = TaskLogicProps
-interface ParsedSseEvent {
- data: string
- eventType: string | null
- id: string | null
+function streamResumeStorageKey(runId: string): string {
+ return `tasks:stream-resume:${runId}`
+}
+
+function readStreamResumeId(runId: string): string | null {
+ try {
+ return window.sessionStorage.getItem(streamResumeStorageKey(runId))
+ } catch {
+ return null
+ }
+}
+
+function writeStreamResumeId(runId: string, eventId: string): void {
+ try {
+ window.sessionStorage.setItem(streamResumeStorageKey(runId), eventId)
+ } catch {
+ // sessionStorage may be unavailable (private mode / quota) — resume from in-memory state only
+ }
+}
+
+function clearStreamResumeId(runId: string): void {
+ try {
+ window.sessionStorage.removeItem(streamResumeStorageKey(runId))
+ } catch {
+ // ignore
+ }
}
function buildToolMap(entries: LogEntry[]): Map<string, LogEntry> {
@@ -53,36 +85,34 @@ function buildToolMap(entries: LogEntry[]): Map<string, LogEntry> {
return toolMap
}
-function parseSseEventBlock(block: string): ParsedSseEvent | null {
- let data = ''
- let eventType: string | null = null
- let id: string | null = null
+interface StreamTarget {
+ url: string
+ headers: Record<string, string>
+}
- for (const line of block.split('\n')) {
- if (!line) {
- continue
- }
- if (line.startsWith(':')) {
- continue
- }
- if (line.startsWith('event:')) {
- eventType = line.slice(6).trim() || null
- continue
- }
- if (line.startsWith('id:')) {
- id = line.slice(3).trim() || null
- continue
+// Route the live stream through the standalone agent-proxy when the rollout flag is on AND the
+// server resolves a base URL for it; otherwise hit the Django endpoint directly. The proxy is
+// purely additive: if the token call fails (or the server returns no base URL), we fall back to
+// the Django path, so streaming never breaks. With the flag off the token call is skipped
+// entirely, keeping the pre-proxy request pattern unchanged.
+async function resolveStreamTarget(taskId: string, runId: string, viaProxy: boolean): Promise<StreamTarget> {
+ const djangoPath = `/api/projects/@current/tasks/${taskId}/runs/${runId}/stream/`
+ if (!viaProxy) {
+ return { url: djangoPath, headers: {} }
+ }
+ try {
+ const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve('@current', taskId, runId)
+ if (!stream_base_url) {
+ return { url: djangoPath, headers: {} }
}
- if (line.startsWith('data:')) {
- data = data ? `${data}\n${line.slice(5).trimStart()}` : line.slice(5).trimStart()
+ // The proxy exposes a clean run-scoped path; the run-scoped token carries team and task.
+ return {
+ url: `${stream_base_url.replace(/\/+$/, '')}/v1/runs/${runId}/stream`,
+ headers: { Authorization: `Bearer ${token}` },
}
+ } catch {
+ return { url: djangoPath, headers: {} }
}
-
- if (!data && !eventType && !id) {
- return null
- }
-
- return { data, eventType, id }
}
export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
@@ -91,7 +121,16 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
key((props) => props.taskId),
connect((props: TaskDetailSceneLogicProps) => ({
- values: [taskLogic(props), ['task', 'taskLoading'], teamLogic, ['currentProjectId']],
+ values: [
+ taskLogic(props),
+ ['task', 'taskLoading'],
+ teamLogic,
+ ['currentProjectId'],
+ featureFlagLogic,
+ ['featureFlags'],
+ preflightLogic,
+ ['preflight'],
+ ],
actions: [
taskLogic(props),
['loadTask', 'loadTaskSuccess', 'runTask', 'runTaskSuccess', 'deleteTask', 'updateTask'],
@@ -107,9 +146,10 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
startStreaming: true,
stopStreaming: true,
markStreamingFailed: true,
+ markStreamComplete: true,
appendStreamEntries: (entries: LogEntry[]) => ({ entries }),
updateStreamEntries: (entries: LogEntry[]) => ({ entries }),
- recordStreamProgress: (lastEventId: string) => ({ lastEventId }),
+ recordStreamProgress: (lastEventId: string | null, seenEventIds: string[]) => ({ lastEventId, seenEventIds }),
setLogs: (logs: string) => ({ logs }),
updateRun: (run: TaskRun) => ({ run }),
}),
@@ -191,7 +231,22 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
null as string | null,
{
setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? null : state),
- recordStreamProgress: (_, { lastEventId }) => lastEventId,
+ recordStreamProgress: (state, { lastEventId }) => lastEventId ?? state,
+ },
+ ],
+ seenStreamEventIds: [
+ {} as Record<string, true>,
+ {
+ setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? {} : state),
+ recordStreamProgress: (state, { seenEventIds }) => {
+ if (seenEventIds.length === 0) {
+ return state
+ }
+ return {
+ ...state,
+ ...Object.fromEntries(seenEventIds.map((eventId) => [eventId, true])),
+ }
+ },
},
],
isStreaming: [
@@ -208,6 +263,14 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
markStreamingFailed: () => true,
},
],
+ streamComplete: [
+ false,
+ {
+ setSelectedRunId: () => false,
+ startStreaming: () => false,
+ markStreamComplete: () => true,
+ },
+ ],
})),
loaders(({ props, values, actions }) => ({
@@ -228,19 +291,10 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
return null
}
const run = await api.tasks.runs.get(props.taskId, values.selectedRunId, phDebugQueryParams())
- const runActive = run?.status === TaskRunStatus.QUEUED || run?.status === TaskRunStatus.IN_PROGRESS
- // While live stream entries are rendered the log file isn't shown, so
- // skip refetching it on every stream rotation. Once the run is terminal
- // (or streaming has fallen back to polling) the fetch always happens —
- // it backs the non-streaming fallback view; any tail a rotation cut off
- // is recovered by the final drain connection in loadSelectedRunSuccess.
- const streamRendersEntries = !values.streamingFailed && values.streamEntries.length > 0
- if (!(runActive && streamRendersEntries)) {
- // Use proxy endpoint to avoid CORS issues with direct S3 access
- actions.loadLogs({
- url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,
- })
- }
+ // Use proxy endpoint to avoid CORS issues with direct S3 access
+ actions.loadLogs({
+ url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,
+ })
return run
},
},
@@ -300,6 +354,14 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
return selectedRun.status === TaskRunStatus.QUEUED || selectedRun.status === TaskRunStatus.IN_PROGRESS
},
],
+ streamViaProxyEnabled: [
+ (s) => [s.featureFlags, s.preflight],
+ (featureFlags, preflight): boolean =>
+ // Gates the durable-streaming rollout (stream_token + status-unaware streams). Local
+ // dev disables the analytics SDK, so DEBUG instances opt in unconditionally — the
+ // server still owns the final proxy-vs-Django decision via stream_token.
+ !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY] || !!preflight?.is_debug,
+ ],
title: [
(s) => [s.task],
(task): string => {
@@ -317,10 +379,6 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
if (taskId !== props.taskId) {
return
}
- cache.seenStreamEventIds = new Set<string>()
- cache.consecutiveShortStreamConnections = 0
- cache.streamEndedWithRotation = false
- cache.finalDrainAttempted = false
actions.stopPolling()
actions.stopStreaming()
actions.loadSelectedRun()
@@ -345,50 +403,46 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
actions.loadSelectedRun()
}
},
- loadSelectedRunFailure: () => {
- // Stream rotation routes through loadSelectedRun (EOF → refresh → restart),
- // so a transient failure here must not strand the run view with neither
- // stream nor polling. Polling self-heals: the next successful load restarts
- // streaming or stops everything once the run is terminal. Gate on the last
- // loaded run still being active (shouldPoll) — a run that never loaded or
- // already finished must not arm a forever-retrying poll loop against a
- // permanently failing endpoint.
- if (values.shouldPoll && !values.isStreaming) {
- actions.startPolling()
- }
- },
loadSelectedRunSuccess: ({ selectedRunData }) => {
if (selectedRunData) {
actions.updateRun(selectedRunData)
}
actions.loadTask()
- if (values.shouldPoll) {
- if (values.streamingFailed) {
- actions.startPolling()
- } else if (!values.isStreaming) {
- actions.startStreaming()
- }
- } else {
- actions.stopPolling()
+ if (values.streamComplete) {
+ // The stream signalled end-of-run in-band; stop reopening it, but keep polling
+ // until the refreshed run record catches up to a terminal status.
+ actions.stopStreaming()
+ const refreshedRun = selectedRunData ?? values.selectedRun
if (
- cache.streamEndedWithRotation &&
- !cache.finalDrainAttempted &&
- !values.isStreaming &&
- !values.streamingFailed &&
- values.streamEntries.length > 0
+ refreshedRun?.status === TaskRunStatus.QUEUED ||
+ refreshedRun?.status === TaskRunStatus.IN_PROGRESS
) {
- // The rotation EOF raced run completion: events published after the
- // resume cursor would otherwise never render (streamEntries shadow the
- // log file). One final drain connection delivers them, then normally
- // EOFs via the completion sentinel — no rotation marker. But the
- // sentinel is best-effort and can be missing, in which case the drain
- // itself rotates and re-sets the flag; finalDrainAttempted makes the
- // drain one-shot so a finished run can't re-drain in 15-minute cycles
- // until the stream key expires.
- cache.streamEndedWithRotation = false
- cache.finalDrainAttempted = true
+ actions.startPolling()
+ } else {
+ actions.stopPolling()
+ }
+ return
+ }
+ if (values.streamingFailed) {
+ // Reconnects were exhausted earlier; fall back to polling while the run is live,
+ // and stop once it reaches a terminal status so the page doesn't poll forever.
+ if (values.shouldPoll) {
+ actions.startPolling()
+ } else {
+ actions.stopPolling()
+ }
+ } else if (!values.isStreaming) {
+ if (values.streamViaProxyEnabled) {
+ // The durable stream is status-unaware: open it regardless of the run's current
+ // status and rely on the in-band stream-end sentinel to finish. Terminal runs
+ // replay their buffered events plus the sentinel; live runs stream as they go.
+ actions.startStreaming()
+ } else if (values.shouldPoll) {
actions.startStreaming()
} else {
+ // Rollout flag off: keep the pre-proxy behavior — terminal runs never open a
+ // stream connection.
+ actions.stopPolling()
actions.stopStreaming()
}
}
@@ -405,150 +459,158 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([
}
},
startStreaming: () => {
- // Stop any existing polling — streaming replaces it
+ // Streaming replaces polling
actions.stopPolling()
+ const runId = values.selectedRunId
+ if (!runId) {
+ return
+ }
+
cache.disposables.add(() => {
const abortController = new AbortController()
- const runId = values.selectedRunId
- if (!runId) {
- return () => {}
- }
-
- // TODO(no-at-current-in-api-urls): migrate to `currentProjectIdStrict`. Rule misses this site because the URL is bound to a const and passed to fetch via the variable.
- const streamUrl = `/api/projects/@current/tasks/${props.taskId}/runs/${runId}/stream/`
const toolMap = buildToolMap(values.streamEntries)
let eventIndex = values.streamEntries.length
- // Dedupes events replayed across rotated connections. Lives in cache
- // (reset per selected run) so it survives reconnects without an O(n)
- // reducer copy per chunk batch on long runs.
- const seenStreamEventIds: Set<string> = (cache.seenStreamEventIds ??= new Set<string>())
+ let reconnectCount = 0
+ let tokenRefreshes = 0
+ let openedAt = 0
+ let terminated = false
+ let disposed = false
+
+ const handleDataEvent = (message: EventSourceMessage): void => {
+ if (message.id && values.seenStreamEventIds[message.id]) {
+ return
+ }
+ let event: Record<string, unknown>
+ try {
+ event = JSON.parse(message.data) as Record<string, unknown>
+ } catch {
+ return
+ }
+ const entryId = message.id ? `stream-${message.id}` : `stream-${eventIndex++}`
+ const entry = parseLogEvent(event, entryId, toolMap, (updatedEntry) => {
+ actions.updateStreamEntries([updatedEntry])
+ })
+ if (entry) {
+ // appendStreamEntries merges consecutive agent/thinking messages at the reducer level
+ actions.appendStreamEntries([entry])
+ }
+ if (message.id) {
+ actions.recordStreamProgress(message.id, [message.id])
+ writeStreamResumeId(runId, message.id)
+ }
+ }
const consume = async (): Promise<void> => {
- const connectionStartedAt = performance.now()
- cache.streamEndedWithRotation = false
+ // Resolve the stream target (agent-proxy when enabled, else Django) and seed the
+ // first connection from the persisted resume point; fetch-event-source manages
+ // Last-Event-ID across its own reconnects after that.
+ const target = await resolveStreamTarget(props.taskId, runId, values.streamViaProxyEnabled)
+ const resumeId = values.lastStreamEventId ?? readStreamResumeId(runId)
try {
- const response = await fetch(streamUrl, {
+ await api.stream(target.url, {
+ method: 'GET',
signal: abortController.signal,
- headers: {
- Accept: 'text/event-stream',
- ...(values.lastStreamEventId ? { 'Last-Event-ID': values.lastStreamEventId } : {}),
+ headers: { ...target.headers, ...(resumeId ? { 'Last-Event-ID': resumeId } : {}) },
+ onOpen: () => {
+ openedAt = Date.now()
},
- })
-
- if (!response.ok || !response.body) {
- // Stream not available — fall back to polling
- actions.stopStreaming()
- actions.markStreamingFailed()
- actions.startPolling()
- return
- }
-
- const reader = response.body.getReader()
- const decoder = new TextDecoder()
- let buffer = ''
-
- while (true) {
- const { done, value } = await reader.read()
- if (done) {
- break
- }
-
- buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n')
- const blocks = buffer.split('\n\n')
- buffer = blocks.pop() || ''
-
- const batch: LogEntry[] = []
- const updatedEntriesById = new Map<string, LogEntry>()
- let lastProcessedEventId: string | null = null
-
- for (const block of blocks) {
- const parsedEvent = parseSseEventBlock(block)
- if (parsedEvent?.eventType === 'end') {
- // `event: end` marks a connection-cap rotation, not run
- // completion — the EOF that follows triggers the restart.
- cache.streamEndedWithRotation = true
- continue
+ onMessage: (message) => {
+ if (terminated) {
+ return
}
- if (!parsedEvent || parsedEvent.eventType === 'keepalive' || !parsedEvent.data) {
- continue
+ if (message.event === STREAM_COMPLETE_EVENT) {
+ terminated = true
+ clearStreamResumeId(runId)
+ actions.markStreamComplete()
+ abortController.abort()
+ return
}
-
- if (parsedEvent.id) {
- if (seenStreamEventIds.has(parsedEvent.id)) {
- continue
- }
- seenStreamEventIds.add(parsedEvent.id)
- lastProcessedEventId = parsedEvent.id
+ if (message.event === 'error') {
+ terminated = true
+ abortController.abort()
+ return
}
-
- try {
- const event = JSON.parse(parsedEvent.data) as Record<string, unknown>
- const entryId = parsedEvent.id
- ? `stream-${parsedEvent.id}`
- : `stream-${eventIndex++}`
- const entry = parseLogEvent(event, entryId, toolMap, (updatedEntry) => {
- updatedEntriesById.set(updatedEntry.id, updatedEntry)
- })
- if (entry) {
- // Merge consecutive agent/thinking messages
- const last = batch[batch.length - 1]
- if (
- last?.type === entry.type &&
- (entry.type === 'agent' || entry.type === 'thinking')
- ) {
- last.message = (last.message || '') + (entry.message || '')
- } else {
- batch.push(entry)
- }
- }
- } catch {
- // Skip invalid JSON
+ if (message.event === 'keepalive' || !message.data) {
+ return
}
- }
-
- if (lastProcessedEventId) {
- actions.recordStreamProgress(lastProcessedEventId)
- }
- if (updatedEntriesById.size > 0) {
- actions.updateStreamEntries(Array.from(updatedEntriesById.values()))
- }
- if (batch.length > 0) {
- actions.appendStreamEntries(batch)
- }
+ handleDataEvent(message)
+ },
+ onError: (error) => {
+ // fetch-event-source: returning a number reconnects after that
+ // many ms; throwing stops. A 4xx (run gone / forbidden) is fatal.
+ if (terminated || disposed) {
+ throw error
+ }
+ // Only a connection that stayed healthy earns fresh budgets; this
+ // runs before the 4xx check so a mid-stream token expiry on a
+ // long-lived connection refreshes with a clean slate.
+ if (openedAt > 0 && Date.now() - openedAt >= STREAM_MIN_HEALTHY_CONNECTION_MS) {
+ reconnectCount = 0
+ tokenRefreshes = 0
+ }
+ openedAt = 0
+ const status = (error as { status?: number } | undefined)?.status
+ if (typeof status === 'number' && status >= 400 && status < 500) {
+ throw error
+ }
+ reconnectCount += 1
+ if (reconnectCount > MAX_STREAM_RECONNECTS) {
+ throw error
+ }
+ return Math.min(
+ STREAM_RECONNECT_BASE_MS * 2 ** (reconnectCount - 1),
+ STREAM_RECONNECT_MAX_MS
+ )
+ },
+ onClose: () => {
+ // Server closed the body without an end-of-run sentinel (e.g. a
+ // backend restart). Route through onError to reconnect; a genuine
+ // completion already set `terminated`.
+ if (terminated || disposed) {
+ return
+ }
+ throw new Error('stream closed before completion')
+ },
+ })
+ } catch (error) {
+ // Stream read tokens are short-lived (the proxy validates them statelessly),
+ // so a reconnect on a long stream can outlive its token. On a 401 from the
+ // proxy leg, re-resolve the target — minting a fresh token re-checks access
+ // server-side — instead of giving up. Revoked users fail the re-resolve and
+ // land on the Django path, whose 4xx stays fatal.
+ const status = (error as { status?: number } | undefined)?.status
+ if (
+ !disposed &&
+ !terminated &&
+ status === 401 &&
+ target.headers.Authorization &&
+ tokenRefreshes < MAX_STREAM_RECONNECTS
+ ) {
+ tokenRefreshes += 1
+ return consume()
}
+ // Aborted, fatal, or reconnects exhausted — reconciled below
+ }
- if (performance.now() - connectionStartedAt < STREAM_MIN_HEALTHY_CONNECTION_MS) {
- cache.consecutiveShortStreamConnections = (cache.consecutiveShortStreamConnections ?? 0) + 1
- } else {
- cache.consecutiveShortStreamConnections = 0
- }
- // Clear streaming state before refreshing the run so in-progress
- // runs can reconnect cleanly after an EOF.
- actions.stopStreaming()
- if (cache.consecutiveShortStreamConnections >= STREAM_MAX_CONSECUTIVE_SHORT_CONNECTIONS) {
- console.warn('SSE stream ended immediately several times in a row, falling back to polling')
- actions.markStreamingFailed()
- actions.startPolling()
- return
- }
- // Stream ended normally — do a final poll to get the latest run status
- actions.loadSelectedRun()
- } catch (e) {
- if ((e as Error).name === 'AbortError') {
- return
- }
- // Stream failed — fall back to polling
- console.warn('SSE stream error, falling back to polling:', e)
- actions.stopStreaming()
+ if (disposed) {
+ return
+ }
+ actions.stopStreaming()
+ if (!values.streamComplete) {
+ // Gave up only after real reconnect attempts (not the old one-error
+ // latch); fall back to polling. Resets when the run changes.
actions.markStreamingFailed()
- actions.startPolling()
}
+ actions.loadSelectedRun()
}
- consume()
+ void consume()
- return () => abortController.abort()
+ return () => {
+ disposed = true
+ abortController.abort()
+ }
}, 'sseStream')
},
stopStreaming: () => {
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index f461e7d3416d..edbe24323e9e 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -234,6 +234,9 @@ tools:
tasks-runs-stream-retrieve:
operation: tasks_runs_stream_retrieve
enabled: false
+ tasks-runs-stream-token-retrieve:
+ operation: tasks_runs_stream_token_retrieve
+ enabled: false
tasks-slack-thread-context-retrieve:
operation: tasks_slack_thread_context_retrieve
enabled: false
diff --git a/services/agent-proxy/.dev.vars.example b/services/agent-proxy/.dev.vars.example
new file mode 100644
index 000000000000..f05d7daaf5e8
--- /dev/null
+++ b/services/agent-proxy/.dev.vars.example
@@ -0,0 +1,100 @@
+# agent-proxy local development environment variables.
+#
+# Copy to .dev.vars and fill in real values. The .dev.vars file is git-ignored;
+# this example file is checked in as documentation.
+#
+# In production all values come from Kubernetes Secrets or environment injection.
+# Required vars are marked; optional vars show their default when absent.
+
+# ---------------------------------------------------------------------------
+# Redis
+# ---------------------------------------------------------------------------
+
+# Redis connection URL. Required in production (NODE_ENV=production).
+# In non-production NODE_ENV the service falls back to a local Redis instance
+# when this is unset.
+# nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
+REDIS_URL=redis://localhost:6379
+
+# ---------------------------------------------------------------------------
+# JWT / Auth
+# ---------------------------------------------------------------------------
+
+# RS256 public key PEM used to verify both token types:
+# - posthog:stream_read (GET /v1/runs/:run/stream leg)
+# - posthog:sandbox_event_ingest (POST /v1/runs/:run/ingest leg)
+#
+# Required. Store the PEM with literal \n sequences (backslash + n) — the
+# service normalizes them to real newlines before calling importSPKI.
+#
+# To generate a test key pair:
+# openssl genrsa -out test-private.pem 2048
+# openssl rsa -in test-private.pem -pubout -out test-public.pem
+# awk 'NR>1{printf "%s", prev} {prev=$0} END{print prev}' test-public.pem \
+# | sed 's/-----BEGIN PUBLIC KEY-----/-----BEGIN PUBLIC KEY-----\\n/' \
+# | sed 's/-----END PUBLIC KEY-----/\\n-----END PUBLIC KEY-----/'
+SANDBOX_JWT_PUBLIC_KEY=
+
+# ---------------------------------------------------------------------------
+# Callbacks
+# ---------------------------------------------------------------------------
+
+# Base URL of the internal Django service (no trailing slash). Required in
+# production. When unset in dev the callback fires are silently skipped, so
+# local ingest testing works without a running Django process.
+AGENT_PROXY_DJANGO_CALLBACK_URL=http://localhost:8000
+
+# ---------------------------------------------------------------------------
+# HTTP server
+# ---------------------------------------------------------------------------
+
+# TCP port the Hono server listens on. Optional; default 8003.
+PORT=8003
+
+# Per-pod cap on concurrent SSE stream connections. Each open stream holds a
+# dedicated Redis connection, so this protects the Redis maxclients budget.
+# Optional; default 1000.
+AGENT_PROXY_MAX_CONCURRENT_STREAMS=1000
+
+# Cap on concurrent SSE stream connections per task run, so a single
+# stream-read token cannot exhaust the pod-wide budget. Optional; default 25.
+AGENT_PROXY_MAX_STREAMS_PER_RUN=25
+
+# Bearer token gating GET /_metrics when set (scrape with: Authorization:
+# Bearer <token>). Deployments scrape in-cluster via annotation-based Prometheus
+# (no auth header) and block external /_metrics at the ingress, so this is left
+# empty there; set it only for a scrape path that can send the header.
+AGENT_PROXY_METRICS_TOKEN=
+
+# TCP bind address. Optional; default 0.0.0.0 (all interfaces).
+HOST=0.0.0.0
+
+# ---------------------------------------------------------------------------
+# CORS
+# ---------------------------------------------------------------------------
+
+# Comma-separated list of allowed origins for CORS responses.
+# Use * to allow all origins (dev only). Leave empty to disable CORS.
+# Example: http://localhost:3000,https://app.example.com
+TASKS_AGENT_PROXY_CORS_ORIGINS=*
+
+# ---------------------------------------------------------------------------
+# Logging
+# ---------------------------------------------------------------------------
+
+# Log level threshold: debug | info | warn | error.
+# Defaults: debug (local dev), info (production), warn (test).
+AGENT_PROXY_LOG_LEVEL=debug
+
+# ---------------------------------------------------------------------------
+# Lifecycle / shutdown
+# ---------------------------------------------------------------------------
+
+# Maximum time in milliseconds to wait for in-flight SSE connections to drain
+# before the process exits on SIGTERM/SIGINT. Optional; default 300000 (5 min).
+SHUTDOWN_GRACE_MS=300000
+
+# Additional sleep in milliseconds before closing the HTTP server on shutdown.
+# Useful when a load balancer needs time to drain traffic before the pod stops.
+# Optional; default 0 (no pre-stop delay).
+SHUTDOWN_PRESTOP_DELAY_MS=0
diff --git a/services/agent-proxy/.gitignore b/services/agent-proxy/.gitignore
new file mode 100644
index 000000000000..3e886c924bca
--- /dev/null
+++ b/services/agent-proxy/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+dist/
+*.mjs.map
+.env
+.env.local
+.dev.vars
+!.dev.vars.example
diff --git a/services/agent-proxy/Dockerfile b/services/agent-proxy/Dockerfile
new file mode 100644
index 000000000000..71bff75dffda
--- /dev/null
+++ b/services/agent-proxy/Dockerfile
@@ -0,0 +1,67 @@
+# PostHog agent-proxy server (Hono / Node.js).
+#
+# Standalone SSE streaming and NDJSON ingest service — a pure streaming plane
+# backed by Redis, with no Postgres, Temporal, or Celery dependencies.
+#
+# Build from repo root (build context must be the workspace root so pnpm can
+# resolve cross-package deps):
+#
+# docker build -f services/agent-proxy/Dockerfile -t posthog-agent-proxy .
+
+# Pin the same Node version as the rest of the monorepo (.nvmrc).
+# The digest wins over the tag — update both together when bumping NODE_VERSION.
+ARG NODE_VERSION=24.13.0
+ARG NODE_IMAGE=node:${NODE_VERSION}-bookworm-slim@sha256:4660b1ca8b28d6d1906fd644abe34b2ed81d15434d26d845ef0aced307cf4b6f
+
+#
+# Build stage — install workspace deps, bundle the Hono entry into a single .mjs.
+# Everything (including ioredis) is bundled so the runtime stage ships with no
+# node_modules at all.
+#
+FROM ${NODE_IMAGE} AS build
+WORKDIR /code
+
+# `corepack enable` reads the `packageManager` field in package.json to pick the
+# pnpm version — no `corepack prepare pnpm@latest` (non-deterministic).
+RUN corepack enable
+
+# Copy lockfile + workspace manifests first so the install layer caches across
+# unrelated source changes. `patches/` is needed because pnpm-lock.yaml may
+# reference workspace-level patch files.
+COPY pnpm-lock.yaml pnpm-workspace.yaml package.json tsconfig.json ./
+COPY patches/ patches/
+
+# pnpm needs every referenced workspace package's `package.json` BEFORE install
+# so it can build the dependency graph. Copy manifests only (cache-friendly),
+# then source after.
+COPY services/agent-proxy/package.json services/agent-proxy/package.json
+
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm install --frozen-lockfile --filter @posthog/agent-proxy...
+
+COPY services/agent-proxy/ services/agent-proxy/
+WORKDIR /code/services/agent-proxy
+RUN pnpm exec tsx scripts/build-agent-proxy.ts
+
+#
+# Runtime stage — minimal slim image with just the self-contained bundle.
+#
+FROM ${NODE_IMAGE}
+WORKDIR /code
+
+# Commit hash burned in for incident triage.
+ARG COMMIT_HASH
+RUN echo "${COMMIT_HASH:-unknown}" > /code/commit.txt
+
+# Bundle is fully self-contained — ioredis and every other dep is inlined.
+COPY --from=build --chown=node:node /code/services/agent-proxy/dist/agent-proxy-server.mjs ./agent-proxy-server.mjs
+COPY --from=build --chown=node:node /code/services/agent-proxy/dist/agent-proxy-server.mjs.map ./agent-proxy-server.mjs.map
+
+ENV NODE_ENV=production \
+ PORT=8003
+
+EXPOSE 8003
+
+USER node
+
+CMD ["node", "agent-proxy-server.mjs"]
diff --git a/services/agent-proxy/README.md b/services/agent-proxy/README.md
new file mode 100644
index 000000000000..79c34c12a03d
--- /dev/null
+++ b/services/agent-proxy/README.md
@@ -0,0 +1,181 @@
+# agent-proxy
+
+Standalone Hono / Node.js service that replaces the Python ASGI agent-proxy
+(`products/tasks/backend/proxy.py`). Serves the task-run live event plane:
+SSE stream reads for browsers and NDJSON event ingest from sandboxes, both
+backed by the same Redis streams that Django writes.
+
+No Postgres, no Temporal client, no Celery — the service is a pure streaming
+plane. Side effects (Temporal heartbeats, awaiting-input push notifications)
+are delegated to a single internal Django callback endpoint.
+
+## Routes
+
+| Method | Path | Description |
+| --------- | ---------------------- | -------------------------------------------------- |
+| `GET` | `/v1/runs/:run/stream` | SSE read — streams task-run events to browsers |
+| `POST` | `/v1/runs/:run/ingest` | NDJSON ingest — accepts events from sandbox agents |
+| `GET` | `/_health` | Liveness probe |
+| `GET` | `/_readyz` | Readiness probe (returns 503 while shutting down) |
+| `GET` | `/health` | Liveness probe (alias) |
+| `GET` | `/_metrics` | Prometheus metrics |
+| `OPTIONS` | `*` | CORS preflight (204) |
+
+Tokens are accepted via `Authorization: Bearer <token>` on both legs. There is
+no `?token=` query fallback: query strings leak into upstream infrastructure
+access logs, which would expose the run-scoped JWT. The browser uses
+fetch-event-source (which sets headers), not native `EventSource`.
+
+Resume is via the `Last-Event-ID` header; `?start=latest` tails from the
+newest available entry.
+
+## Environment variables
+
+| Variable | Required | Default | Description |
+| --------------------------------- | ---------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `REDIS_URL` | yes (prod) | `localhost:6379` | Redis connection URL (unencrypted local Redis by default; use a TLS URL in production) |
+| `SANDBOX_JWT_PUBLIC_KEY` | yes | — | RS256 public key PEM (`\n` literals in env vars are normalized to real newlines before use) |
+| `AGENT_PROXY_DJANGO_CALLBACK_URL` | yes (prod) | — | Base URL of the Django service for side-effect callbacks (Temporal heartbeat, awaiting-input push), e.g. `http://web:8000` |
+| `AGENT_PROXY_CALLBACK_SECRET` | no | `''` | Shared secret sent as `X-Agent-Proxy-Secret` on the Django callback; Django enforces it when the same value is set on both sides, so a sandbox cannot call the callback directly |
+| `TASKS_AGENT_PROXY_CORS_ORIGINS` | no | `''` | Comma-separated allowed CORS origins; `*` allows all |
+| `PORT` | no | `8003` | HTTP listen port |
+| `HOST` | no | `0.0.0.0` | HTTP listen address |
+| `SHUTDOWN_GRACE_MS` | no | `300000` | Maximum drain budget on SIGTERM before force-exit (ms) |
+| `SHUTDOWN_PRESTOP_DELAY_MS` | no | `0` | Sleep before closing on SIGTERM (useful for Kubernetes preStop hooks) |
+| `NODE_ENV` | no | — | `production` enables strict startup checks |
+| `AGENT_PROXY_LOG_LEVEL` | no | `debug` dev / `info` prod | One of `debug`, `info`, `warn`, `error`. `debug` logs every connect / read / write |
+
+## Running locally (end to end)
+
+Both stream legs (browser read + sandbox ingest) route to this service when
+Django has the proxy URLs set and runs with `DEBUG=True`. Local dev disables the
+analytics SDK, so the URL settings are the opt-in (no feature flag needed
+locally).
+
+All config is read from the repo-root `.env`, which flox loads into every process
+(`DOTENV_FILE = ".env"` in the flox manifest) — the same place Django, the
+Temporal worker, and the other services read from. There is no per-service `.env`
+to manage. (The dev script will also load an optional `services/agent-proxy/.env`
+override if one exists, mirroring `services/mcp`, but it is not needed.) flox
+caches the dotenv, so re-activate your shell or restart `hogli` after editing
+`.env`.
+
+### 1. Point Django at the proxy
+
+In the repo-root `.env` (read by Django web and the Temporal worker):
+
+```bash
+DEBUG=1
+TASKS_AGENT_PROXY_PUBLIC_URL=http://localhost:8003 # browser read leg
+TASKS_AGENT_PROXY_INGEST_URL=http://localhost:8003 # sandbox ingest leg (auto-rewritten for the Docker sandbox)
+```
+
+### 2. Give this service its verify key + CORS
+
+Same repo-root `.env`. This service is verify-only, so it needs the public half
+of Django's `SANDBOX_JWT_PRIVATE_KEY`. Derive it (double-quote the value, like
+the private key, so the PEM newlines survive flox's dotenv parser):
+
+```sh
+# from repo root, inside flox — prints the line to add to .env
+python3 - <<'PY'
+import re, pathlib
+from cryptography.hazmat.primitives import serialization
+priv = re.search(r'^SANDBOX_JWT_PRIVATE_KEY=(.*)$', pathlib.Path(".env").read_text(), re.M).group(1).strip().strip('"').strip("'")
+key = serialization.load_pem_private_key(priv.replace("\\n", "\n").encode(), password=None)
+pub = key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
+print('SANDBOX_JWT_PUBLIC_KEY="' + pub.replace(chr(10), "\\n") + '"')
+PY
+```
+
+Add that line plus these to the root `.env`:
+
+```bash
+SANDBOX_JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n"
+TASKS_AGENT_PROXY_CORS_ORIGINS=http://localhost:8010
+AGENT_PROXY_DJANGO_CALLBACK_URL=http://localhost:8000 # heartbeat + awaiting-input callbacks; omit to skip them
+```
+
+`REDIS_URL` is optional locally — it defaults to `localhost:6379`, the
+same instance Django uses (the `redis7` host maps to localhost).
+
+### 3. Start
+
+`hogli start` runs this service automatically when the `ai_features` intent is
+enabled, listed as `agent-proxy` on :8003 (watch mode). Enable the intent with
+`hogli dev:setup` if it is not already on.
+
+```sh
+hogli start # Redis, Django (:8000), frontend (:8010), Temporal worker, agent-proxy (:8003)
+```
+
+To run only this service standalone (for example when `ai_features` is off):
+
+```sh
+hogli start:agent-proxy # this service on :8003 (watch mode); or: pnpm --filter @posthog/agent-proxy dev
+```
+
+The proxy must be running before you start a task run. With the URL settings
+above there is no automatic failover: if the proxy is down the client fails to
+connect, it does not fall back to Django.
+
+### 4. Verify both legs
+
+Create a run at `http://localhost:8010/project/1/tasks`, then:
+
+- Read leg: in browser DevTools > Network the `/v1/runs/:run/stream` EventStream request
+ host is `localhost:8003` (not `:8000`). The `/stream_token/` response carries
+ `stream_base_url: http://localhost:8003`.
+- Write leg: the proxy console logs ingest activity as the sandbox POSTs, and
+ events render live in the task UI.
+- Health: `curl localhost:8003/_health` and `curl localhost:8003/_metrics`.
+
+### Rolling back to Django
+
+Unset `TASKS_AGENT_PROXY_PUBLIC_URL` and `TASKS_AGENT_PROXY_INGEST_URL` in the
+root `.env` and restart. No data migration is needed: the Redis stream format is
+identical, so the Django in-process path picks up seamlessly.
+
+## Building
+
+```sh
+# From repo root
+docker build -f services/agent-proxy/Dockerfile -t posthog-agent-proxy .
+
+# Or build the JS bundle only (no Docker)
+pnpm --filter @posthog/agent-proxy build
+# Output: services/agent-proxy/dist/agent-proxy-server.mjs
+```
+
+## Testing
+
+```sh
+pnpm --filter @posthog/agent-proxy test
+```
+
+## Type checking
+
+```sh
+pnpm --filter @posthog/agent-proxy typecheck
+```
+
+## Cutover note
+
+Browsers discover the proxy URL from the `stream_base_url` field returned by
+the Django `stream_token` endpoint. When `TASKS_AGENT_PROXY_PUBLIC_URL` is set
+on Django (read leg) it points to this service; the write leg routes here when
+`TASKS_AGENT_PROXY_INGEST_URL` is set. When unset, browsers and sandboxes use
+the Django in-process path instead — no client code changes are needed for the
+cutover.
+
+The Redis stream key format (`task-run-stream:{run_id}`) and all companion
+keys are byte-identical between this Node service and the Python implementation.
+During the cutover window both services read and write the same streams safely.
+
+To roll back: unset `TASKS_AGENT_PROXY_PUBLIC_URL` and `TASKS_AGENT_PROXY_INGEST_URL`
+on Django. No data migration is needed because the stream format is identical.
+
+S3 hydration on resume gap is explicitly out of scope for this version — when a
+client's `Last-Event-ID` has been trimmed from Redis, the service emits a metric
+and continues reading from the oldest available entry, matching the current
+Python behavior exactly.
diff --git a/services/agent-proxy/docs/DURABLE_STREAMING.md b/services/agent-proxy/docs/DURABLE_STREAMING.md
new file mode 100644
index 000000000000..a46b6367a816
--- /dev/null
+++ b/services/agent-proxy/docs/DURABLE_STREAMING.md
@@ -0,0 +1,105 @@
+# Durable streaming: what we have and what is missing
+
+This is a concept-level assessment of the agent-proxy live event plane against the
+high-level ideas of durable streaming: resumability, ordering, idempotent append,
+durable closure and gap awareness. It is **not** a wire-conformance check against the
+durable-streams.com protocol. agent-proxy stays byte-identical to the Python proxy
+during the cutover, so it cannot share that protocol's wire format, and that is by
+design. What follows is purely about the guarantees the streaming layer provides and
+where it falls short, regardless of how they are framed on the wire.
+
+Reference concepts:
+
+- <https://durablestreams.com/building-a-server>
+- <https://durablestreams.com/building-a-client>
+- <https://github.com/durable-streams/durable-streams/blob/main/PROTOCOL.md>
+
+## What we have
+
+- **Resumability.** A client reconnects from its last position (`Last-Event-ID`) and the
+ server replays forward from there. This is the core durable-streaming property and it
+ is solid. See the read leg in `src/hono/app.ts` and `streamTaskRunEvents` in
+ `src/hono/sse-handler.ts`.
+- **Stable, ordered positions.** Every event has a monotonic id (the Redis stream id);
+ events are delivered in a strict, stable order. See `src/lib/redis-stream.ts`.
+- **Catch-up then live.** A reader gets history from the start, or `?start=latest` to skip
+ to the tail, then seamlessly tails live from the same connection. The two modes are
+ fused rather than separate endpoints.
+- **No-skip and no-duplicate delivery within the retention window.** Resume is exclusive
+ of the last id, so inside the live window a client neither re-receives nor skips events.
+- **Idempotent, ordered append.** The ingest `seq` enforces contiguous ordering (a gap is
+ rejected) and a replayed `seq` is deduplicated rather than re-appended, so the producer
+ can retry safely. This is effectively exactly-once on the write side for a single
+ producer. See `writeEventWithSequence` in `src/lib/redis-stream.ts`.
+- **Completion consistency.** Closing the stream verifies the final sequence matches what
+ was accepted, so the stream cannot be marked complete past a hole. See
+ `markCompleteAfterSequence`.
+- **Durable, observable EOF.** The `stream-end` sentinel plus the persisted `completed`
+ marker mean a late reader still learns the stream ended, and the client honors it to
+ stop reconnecting.
+- **Liveness and reconnect robustness.** Keepalives, reconnect backoff, a cumulative
+ retry budget and a "keepalive proves recovery" reset. The client distinguishes
+ transport cuts from backend errors (in the `cloud-task` watcher on the client side).
+- **Backpressure to slow readers.** The SSE writer awaits each chunk
+ (`responseStream.write`), so a slow consumer naturally throttles the read loop.
+- **Multi-reader fan-out.** Several clients can independently tail the same run, each with
+ its own cursor and its own dedicated Redis connection.
+
+## What is missing or partial
+
+Ranked by how much it matters for the current use case (watching a live agent run).
+
+1. **Gap awareness (the real hole).** The server **detects** when a reader's resume point
+ has been trimmed out of the window (`resumePointTrimmed` / `detectResumeGap` in
+ `src/lib/redis-stream.ts`, surfaced as the `stream:resume_gap` metric) but it does
+ **not tell the reader**. It silently continues from the oldest surviving event. So a
+ client that reconnects after a long gap, or watches a long run, can silently miss a
+ span of events and never know. Durable streaming's whole point is that the reader
+ either receives every event or is explicitly told it lost some. This is already a known
+ deferral: S3 hydration on resume gap is out of scope for now (see the `ResumeGap`
+ comment in `src/lib/types.ts` and `DESIGN.md`). Closing it means either a
+ client-visible "you missed events from A to B" signal, a backfill from durable storage,
+ or both.
+2. **Bounded retention.** "Durable" here means roughly a 6h TTL plus a ~20k event
+ `MAXLEN` (`STREAM_TTL_SECONDS`, `STREAM_MAX_LENGTH` in `src/lib/constants.ts`), after
+ which data is gone. That bound is the cause of gap awareness above. It is fine for
+ watching a run live, but not for replaying a run's stream much later. If long replay
+ becomes a goal, this is the lever.
+3. **No "caught up to the tail" signal.** A reader cannot tell when it transitions from
+ replaying history to being live at the tail. This is minor for a live UI, which just
+ keeps tailing, but it is a real durable-streaming concept that is not exposed.
+4. **No producer fencing.** The `seq` protocol gives ordering and deduplication for one
+ writer, but nothing fences out a second or zombie writer to the same run (for example a
+ retried or duplicated sandbox). We rely on "one sandbox per run" by construction. If
+ that assumption can break, two producers could interleave and we would only catch it as
+ sequence gaps, not as "you are not the active writer."
+5. **Not needed for this use case, noted for completeness.** Stream forking, durable
+ multi-consumer subscriptions (webhooks or pull-wake) and consumer-group coordination.
+ These are durable-streaming features we do not have and almost certainly do not want
+ here.
+
+## Summary
+
+| Concept | Status |
+| -------------------------------------------- | ----------------------------------------- |
+| Resume from last position | Have |
+| Stable ordered positions | Have |
+| Catch-up then live tail | Have |
+| No-skip / no-duplicate within window | Have |
+| Idempotent, ordered append (single producer) | Have |
+| Completion consistency | Have |
+| Durable, observable EOF | Have |
+| Keepalive, reconnect robustness | Have |
+| Backpressure to slow readers | Have |
+| Multi-reader fan-out | Have |
+| Gap awareness on trimmed resume | **Missing** (detected, not signalled) |
+| Retention beyond ~6h / ~20k | **Partial** (bounded, then dropped) |
+| Caught-up-to-tail signal | Missing |
+| Producer fencing across writers | Partial (single-producer by construction) |
+| Forking / subscriptions / consumer groups | Missing (not needed) |
+
+We have resumability, ordering, idempotent append and durable closure, which is the meat
+of durable streaming. The two gaps that actually matter are **gap awareness** (the silent
+skip on trimmed resume) and the **bounded retention** behind it. Everything else missing
+is either cosmetic (the caught-up signal) or out of scope (forking, subscriptions). The
+important one is already on the roadmap as deferred S3 hydration.
diff --git a/services/agent-proxy/docs/REDIS.md b/services/agent-proxy/docs/REDIS.md
new file mode 100644
index 000000000000..009068aaf3ce
--- /dev/null
+++ b/services/agent-proxy/docs/REDIS.md
@@ -0,0 +1,95 @@
+# Redis connection model
+
+**Status:** Accepted (2026-06-06)
+**Scope:** the SSE read path in `src/hono/sse-handler.ts` and `src/lib/redis-stream.ts`
+
+## Decision
+
+Each SSE stream opens its own dedicated Redis connection (`redis.duplicate()`) for its blocking `XREAD` read loop, and closes it when the stream ends.
+The single shared client is kept for everything else: ingest writes (`XADD`, `WATCH`/`MULTI`) and non-blocking control reads.
+
+We chose this over two alternatives:
+
+1. one shared connection for everything (what the first cut did): correct-looking but broken under load, see below
+2. a bounded pool of multiplexed blocking-read connections: the right answer at large scale, but premature complexity for our current workload
+
+We are accepting one extra Redis connection per active SSE stream as the cost, with monitoring and a documented migration path instead of building the pool now.
+
+## What the connection actually does
+
+agent-proxy talks to Redis on two very different access patterns:
+
+| Path | Commands | Holds the connection? |
+| --------------------------------- | --------------------------------- | ---------------------------------- |
+| SSE read (tail a task-run stream) | `XREAD ... BLOCK 100` in a loop | **Yes**, up to `BLOCK_MS` per call |
+| Ingest write (sandbox to Node) | `XADD`, `WATCH`/`MULTI`, `EXPIRE` | No (returns immediately) |
+| Control / lifecycle | `GET`, `SET`, `EXISTS`, `EXPIRE` | No |
+
+The read path is the only one that blocks the connection. Everything else is a short request/response.
+
+## Why not one shared connection
+
+ioredis sends every command for a client over a single TCP socket in FIFO order.
+A blocking `XREAD ... BLOCK 100` occupies that socket for up to 100 ms waiting for data.
+With N concurrent SSE streams sharing one client, the blocking reads serialize:
+
+- worst-case event-delivery latency for any one stream is about N x `BLOCK_MS`
+- ingest `XADD` writes queue behind the blocking reads, so reads starve writes
+
+This degrades at trivial concurrency (tens of streams already give multi-second delays plus ingest backpressure). It is not an optimization to skip. The fix is mandatory. The only open question is which fix.
+
+## Why per-stream over a pool, for our workload
+
+Our streams are task-run watchers: relatively few at a time, long-lived (minutes up to the 6h sandbox TTL), low churn. For that shape a connection per stream is simple and obviously correct:
+
+- the connection's lifetime is the stream's lifetime (created right before the read loop, closed in the generator's `finally` on completion, error or client disconnect)
+- no shared state, no head-of-line blocking between streams, nothing to rebalance
+
+A bounded pool would block-read many streams per connection using multi-key `XREAD`. It bounds connection count, but it is a real subsystem:
+
+- you cannot add or remove a stream from an in-flight blocking `XREAD`; every connect/disconnect makes you let the current block return then reissue with a new key set
+- you own per-stream cursors (each stream advances independently), demultiplexing returned entries to the right consumer, per-consumer backpressure (one slow client must not stall the shared reader for others on that connection) and shard rebalancing
+
+That is worth building when connection count is the binding constraint. It is not worth building speculatively.
+
+## The cost we are accepting (read this part)
+
+agent-proxy connects to `REDIS_URL`, which in production is **the main shared Redis**. That instance also backs the Celery broker and result backend, general caching, rate limiting and today the Python proxy's stream plane (`products/tasks/backend/stream/redis_stream.py`, which uses `settings.REDIS_URL` and shares the exact same stream with us during the cutover).
+
+So every active SSE stream consumes one connection on a resource that almost every PostHog service hits. Two failure modes follow, and neither is local to agent-proxy:
+
+- **Connection count.** Active dedicated connections grow linearly with concurrent streams, summed across every agent-proxy pod. If that fleet-wide total competes for the shared instance's `maxclients` budget (Redis default 10,000, but the real ceiling is whatever the managed instance is set to), exhaustion surfaces as errors in _other_ services, not just here.
+- **Idle-poll load (bandwidth and ops).** With `BLOCK_MS = 100`, an idle stream issues about 10 `XREAD` round-trips per second. N idle streams is roughly 10N ops/sec of command traffic on the shared instance even when nothing is happening. The event payload itself would transfer under any design, but the idle-poll round-trip rate is pure overhead that scales with stream count.
+
+The Python proxy already runs this same blocking-read pattern against the same Redis, so the load shape is not new. The Node rewrite makes the connection count explicit, which is precisely why we are writing it down and governing it rather than leaving it implicit.
+
+This is the open risk. We are accepting it at current scale. We are not claiming it is free.
+
+## What makes it safe enough today
+
+- **It is observable.** `agent_proxy_sse_open_streams` (gauge) tracks active streams, which is an upper bound on dedicated read connections. `posthog_tasks_task_run_stream_connections_opened_total` / `_closed_total` give the same view from counters.
+- **It fails soft.** If a dedicated connection cannot be established (for example the instance is at `maxclients`), the read path emits an SSE `error` event and ends that one stream instead of crashing the process (`stream:redis_dup_connect_failed`). Ingest uses the separate shared client, so a read-side connection ceiling does not directly kill writes.
+- **It is conservative per connection.** Duplicated connections inherit the shared client's options: `commandTimeout`, bounded `maxRetriesPerRequest`, `enableOfflineQueue: false`. A stuck or unreachable Redis surfaces fast rather than piling up queued work.
+
+## Cheap levers, available without re-architecting
+
+These reduce shared-Redis load while keeping the simple per-stream model. None change the wire protocol (same keys, same `XREAD` args, same SSE bytes):
+
+- **Raise `BLOCK_MS`.** `XREAD ... BLOCK` returns _immediately_ when data arrives, so a larger block timeout cuts the idle-poll rate with no added latency on real events. Going from 100 ms to 1000 ms drops idle traffic roughly 10x. The only thing a longer block delays is the loop's periodic wake to check the 20s keepalive timer, which is fine. Client disconnect is still immediate because `disconnect()` aborts the in-flight call.
+- **Add a per-pod cap.** A max-concurrent-streams limit that returns `503` on new SSE connections past the cap turns a silent `maxclients` cliff into predictable load shedding. Roughly 15 lines, can be added at any time.
+
+## Migration path, in order of preference
+
+1. **Dedicated Redis for the task-run stream plane.** This removes the blast-radius concern entirely by isolating both the connection count and the idle-poll load off the shared instance, and it lets the simple per-stream model stay. PostHog already isolates hot workloads this way: `FLAGS_REDIS_URL`, `AI_GATEWAY_REDIS_URL`, `SESSION_RECORDING_REDIS_URL`, `QUERY_CACHE_REDIS_CLUSTER_URL`. Add an equivalent (for example `TASKS_STREAM_REDIS_URL`) and point it at its own cluster.
+ - **Constraint:** the stream is shared with the Python proxy during the cutover. Both sides (the Python stream plane and agent-proxy) must move to the same dedicated instance together, or this waits until the Python proxy is retired. Moving one side alone splits the stream and breaks live runs.
+2. **Bounded connection pool (multiplexed `XREAD`).** If even a dedicated instance's connection count or idle-poll rate is the binding constraint, replace per-stream `duplicate()` with a small fixed pool (for example 10 to 20 connections), each block-reading a shard of streams via multi-key `XREAD`. This is the subsystem described above. The wire protocol is unaffected.
+
+The order is deliberate. A dedicated Redis is operationally cheap and solves the actual concern (shared blast radius). The pool only becomes worthwhile once the workload is already isolated and still too large for one connection per stream.
+
+## When to revisit
+
+Pull the migration path when any of these fire:
+
+- fleet-wide `agent_proxy_sse_open_streams` (pods x streams per pod) approaches the connection headroom you are willing to allocate this workload out of the shared `maxclients` budget (suggest alerting around 50 to 60%)
+- `stream:redis_dup_connect_failed` starts logging, which means streams are already hitting the connection ceiling
+- connection-establishment latency, or shared-Redis CPU and network, climbs in step with stream count
diff --git a/services/agent-proxy/docs/SECURITY.md b/services/agent-proxy/docs/SECURITY.md
new file mode 100644
index 000000000000..182afa1fc5f4
--- /dev/null
+++ b/services/agent-proxy/docs/SECURITY.md
@@ -0,0 +1,110 @@
+# Security: authentication and key rotation
+
+How the live event plane authenticates callers, how it separates read from write
+and how signing keys rotate without downtime.
+
+## Token model
+
+agent-proxy is **verify-only**. It never signs. Django holds the RS256 private key
+(`SANDBOX_JWT_PRIVATE_KEY`) and is the only minter. agent-proxy holds only the public half
+(`SANDBOX_JWT_PUBLIC_KEY`) and verifies statelessly, with no Django or database round-trip on
+the hot path. A compromise of agent-proxy cannot forge a token for any run.
+
+Every request to either leg must carry a valid, unexpired, Django-signed RS256 bearer token.
+agent-proxy checks signature, expiry, audience and claim types. Invalid or missing means `401`.
+
+## Read vs write is enforced by audience
+
+Two token types, each a single capability for a single run. Neither carries user identity.
+
+| | Client (browser) | Sandbox |
+| --------- | ------------------------------------------------------------- | ------------------------------------------------------------- |
+| `aud` | `posthog:stream_read` | `posthog:sandbox_event_ingest` |
+| Leg | `GET /v1/runs/:run/stream` | `POST /v1/runs/:run/ingest` |
+| Minted by | `create_stream_read_token` (after Django authorizes the user) | `create_sandbox_event_ingest_token` (at sandbox provisioning) |
+| Grants | read this run's stream | append events to this run's stream |
+| TTL | `SANDBOX_TTL + 1h` (~7h) | `SANDBOX_TTL + 1h` (~7h) |
+
+Each leg validates only its own audience (`jwt.ts` `validateStreamReadToken` /
+`validateSandboxEventIngestToken`). jose enforces `aud` as part of verification, so a read token
+POSTed to the ingest leg fails (`401`) and an ingest token on the read leg fails. The split is
+cryptographic, not a matter of which token each party happens to hold.
+
+Beyond audience, both handlers bind the token to the URL: the `run_id`, `task_id` and `team_id`
+claims must match the path, else `403`. A token for run A cannot touch run B.
+
+Credential delivery:
+
+- The browser gets its read token from Django's `stream_token` endpoint, which is
+ session-authenticated and permission-checked first. It presents the token as
+ `Authorization: Bearer` only — no `?token=` query fallback, since query strings
+ leak into upstream infrastructure access logs.
+- The sandbox gets its ingest token injected at provisioning, baked into its env for the run
+ lifetime. Bearer only, no query fallback.
+
+A third token type, `posthog:sandbox_connection`, carries identity for direct sandbox connections
+and is not used by agent-proxy.
+
+## Key rotation without downtime
+
+### How it works
+
+Both tokens agent-proxy verifies are signed with the key the run was provisioned under and carry a
+`kid` header (`connection_token.py` `_encode_run_scoped_token`), reusing the same key registry the
+`sandbox_connection` token already uses. agent-proxy trusts a **set** of public keys —
+`SANDBOX_JWT_PUBLIC_KEY` plus the optional `SANDBOX_JWT_PUBLIC_KEY_SECONDARY` — and accepts a token
+that verifies under **any** of them (`verifyWithKeys`); only a signature mismatch advances to the
+next key. Django verifies the same way against its registry (`_decode_sandbox_token`). So rotating
+the primary key is zero-downtime across all three token legs, not just `sandbox_connection`.
+
+### The principle
+
+JWTs are distributed, long-lived bearer credentials. A token lives ~7h, and a sandbox provisioned
+just before a rotation holds an old-key token for its whole run. You cannot flip atomically.
+
+> The verifier must trust the old key and the new key at the same time, for an overlap window at
+> least as long as the longest token TTL in circulation (~7h).
+
+### The choreography
+
+1. **Expand trust.** Teach agent-proxy to accept both the current and the new public key. Deploy.
+ Signing is unchanged, so nothing functionally changes yet.
+2. **Switch signing.** Make the new key Django's primary. Now in-flight old-key tokens and fresh
+ new-key tokens both verify. This is the zero-downtime moment.
+3. **Wait** at least the max TTL (~7h) so every old-key token has expired.
+4. **Contract trust.** Drop the old key from agent-proxy and Django. Deploy.
+
+Step 1 must ship and bake before step 2. Step 4 must wait until the TTL drains, not just until
+signing flips.
+
+### Implementation options
+
+**A. Static dual key.** Add `SANDBOX_JWT_PUBLIC_KEY_SECONDARY`, load both, try the second key on a
+verify miss. Mirrors Django's existing `SANDBOX_JWT_PRIVATE_KEY` / `_SECONDARY` idiom. Smallest
+change. Without a kid, agent-proxy verifies per key on the miss path (one extra RSA verify, so keep
+the expected key first to keep the common path single-verify).
+
+**B. Static dual key + `kid` (recommended).** Add a `kid` header to the two token minters (Django
+already computes kids) and give jose a resolver `(header) => keymap[header.kid]`. O(1) selection, no
+network dependency, clean support for N keys. The smallest change that is correct rather than
+brute-forced.
+
+**C. JWKS + `kid`.** Django serves a JWKS of trusted keys by kid. agent-proxy uses jose
+`createRemoteJWKSet`, which caches and auto-refreshes on an unseen kid. Rotation becomes
+near-automatic with no agent-proxy redeploy or coordinated config flip. Cost: a network dependency
+(mitigated by caching plus a cached fallback) and a Django endpoint to maintain. The OIDC-standard
+approach, worth it once rotations are frequent or automated.
+
+### Operational notes
+
+- The overlap window is set by `SANDBOX_EVENT_INGEST_TOKEN_TTL` and `STREAM_READ_TOKEN_TTL`
+ (`SANDBOX_TTL_SECONDS + 1h`). Shorter token TTLs make rotation cheaper.
+- Keep the old key trusted until every sandbox provisioned under it has aged out, which the ~7h
+ TTL covers.
+- Until one of the options above lands, a primary-key rotation has a brief failure window on the
+ agent-proxy legs. Plan rotations accordingly, or build Option B first.
+- Rolling deploys interact with rotation the same way: every verifier must trust the full key set
+ before any minter signs with a non-primary key. A Django pod that only verifies against the
+ primary key rejects (401) tokens that a newer pod minted under a run's stored secondary `kid`,
+ so do not enable `SANDBOX_JWT_PRIVATE_KEY_SECONDARY` while pods without multi-key verification
+ are still draining — and conversely, finish or roll back a rotation before such a deploy.
diff --git a/services/agent-proxy/package.json b/services/agent-proxy/package.json
new file mode 100644
index 000000000000..737bec469d68
--- /dev/null
+++ b/services/agent-proxy/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@posthog/agent-proxy",
+ "version": "1.0.0",
+ "description": "PostHog agent-proxy SSE streaming service",
+ "license": "MIT",
+ "author": "PostHog Inc.",
+ "type": "module",
+ "scripts": {
+ "build": "tsx scripts/build-agent-proxy.ts",
+ "dev": "tsx scripts/dev-agent-proxy.ts | pino-pretty --colorize --ignore pid,hostname --messageKey event --translateTime SYS:HH:MM:ss.l",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit",
+ "format": "oxlint --fix --fix-suggestions --fix-dangerously --quiet && oxfmt \"./**/*.{js,mjs,ts,tsx,json,yaml,yml,css,scss}\""
+ },
+ "dependencies": {
+ "@hono/node-server": "^2.0.2",
+ "esbuild": "^0.25.11",
+ "hono": "^4.12.18",
+ "ioredis": "^4.28.5",
+ "jose": "^6.0.10",
+ "pino": "^8.6.0",
+ "prom-client": "^14.2.0"
+ },
+ "devDependencies": {
+ "@types/node": "^22.17.2",
+ "oxfmt": "catalog:",
+ "oxlint": "^1.8.0",
+ "pino-pretty": "^9.1.0",
+ "tsx": "^4.20.5",
+ "typescript": "catalog:",
+ "vite-tsconfig-paths": "^5.1.4",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/services/agent-proxy/scripts/agent-proxy-esbuild-config.ts b/services/agent-proxy/scripts/agent-proxy-esbuild-config.ts
new file mode 100644
index 000000000000..4711f9f45e7c
--- /dev/null
+++ b/services/agent-proxy/scripts/agent-proxy-esbuild-config.ts
@@ -0,0 +1,30 @@
+import type { BuildOptions, Plugin } from 'esbuild'
+// Shared esbuild config for the agent-proxy Hono runtime. `build-agent-proxy.ts`
+// runs it once for production; `dev-agent-proxy.ts` wraps it in `context().watch()`
+// for the dev loop.
+//
+// No externals: ioredis and every other prod dep is pure-JS (or has a Node-target
+// shim esbuild handles). Bundling everything lets the runtime image ship a single
+// .mjs with no node_modules at all.
+import { resolve } from 'path'
+
+export const agentProxyOutfile = resolve(process.cwd(), 'dist/agent-proxy-server.mjs')
+
+export function agentProxyEsbuildOptions(opts: { dev?: boolean; extraPlugins?: Plugin[] } = {}): BuildOptions {
+ return {
+ entryPoints: [resolve(process.cwd(), 'src/hono/index.ts')],
+ bundle: true,
+ platform: 'node',
+ target: 'node22',
+ format: 'esm',
+ outfile: agentProxyOutfile,
+ sourcemap: true,
+ external: [],
+ loader: { '.json': 'json' },
+ define: { 'process.env.NODE_ENV': opts.dev ? '"development"' : '"production"' },
+ plugins: opts.extraPlugins ?? [],
+ // Bundled CJS modules (e.g. ioredis using `require('util')`) call through
+ // to a global `require`. ESM has no `require`; banner injects one.
+ banner: { js: `import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);` },
+ }
+}
diff --git a/services/agent-proxy/scripts/build-agent-proxy.ts b/services/agent-proxy/scripts/build-agent-proxy.ts
new file mode 100644
index 000000000000..861763c0b683
--- /dev/null
+++ b/services/agent-proxy/scripts/build-agent-proxy.ts
@@ -0,0 +1,12 @@
+import { build } from 'esbuild'
+
+import { agentProxyEsbuildOptions, agentProxyOutfile } from './agent-proxy-esbuild-config'
+
+build(agentProxyEsbuildOptions())
+ .then(() => {
+ console.info(`Built agent-proxy server → ${agentProxyOutfile}`)
+ })
+ .catch((err: unknown) => {
+ console.error('Build failed:', err)
+ process.exit(1)
+ })
diff --git a/services/agent-proxy/scripts/dev-agent-proxy.ts b/services/agent-proxy/scripts/dev-agent-proxy.ts
new file mode 100644
index 000000000000..c5af5da9ead6
--- /dev/null
+++ b/services/agent-proxy/scripts/dev-agent-proxy.ts
@@ -0,0 +1,93 @@
+import { spawn, type ChildProcess } from 'child_process'
+import { context, type Plugin } from 'esbuild'
+// esbuild watch + node respawn — same bundling pipeline as build-agent-proxy.ts so
+// dev and prod behave identically.
+import { existsSync } from 'fs'
+import { resolve } from 'path'
+
+import { agentProxyEsbuildOptions, agentProxyOutfile } from './agent-proxy-esbuild-config'
+
+// Load the repo-root .env directly (the single source of truth that flox also
+// loads). Reading it here means dev does not depend on flox's dotenv cache being
+// fresh after you edit .env. A per-service services/agent-proxy/.env, if present,
+// is loaded last as a local override.
+for (const envPath of [resolve(process.cwd(), '../../.env'), resolve(process.cwd(), '.env')]) {
+ if (existsSync(envPath)) {
+ process.loadEnvFile(envPath)
+ }
+}
+
+// flox sets SSL_CERT_FILE; Node's TLS layer only reads NODE_EXTRA_CA_CERTS.
+if (!process.env.NODE_EXTRA_CA_CERTS && process.env.SSL_CERT_FILE) {
+ process.env.NODE_EXTRA_CA_CERTS = process.env.SSL_CERT_FILE
+}
+
+let child: ChildProcess | undefined
+
+const killChild = (): Promise<void> => {
+ return new Promise((resolve) => {
+ if (!child) {
+ resolve()
+ return
+ }
+ const proc = child
+ child = undefined
+ proc.removeAllListeners()
+ proc.on('exit', () => resolve())
+ proc.kill('SIGTERM')
+ })
+}
+
+const launch = async (): Promise<void> => {
+ await killChild()
+ child = spawn(process.execPath, [agentProxyOutfile], {
+ stdio: 'inherit',
+ env: { ...process.env, SHUTDOWN_PRESTOP_DELAY_MS: '0' },
+ })
+ child.on('exit', (code, signal) => {
+ if (signal === 'SIGTERM') {
+ return
+ }
+ if (code !== 0) {
+ console.warn(`[dev-agent-proxy] node exited with code=${code}; waiting for next rebuild...`)
+ }
+ })
+}
+
+const restartPlugin: Plugin = {
+ name: 'dev-agent-proxy-restart',
+ setup(build): void {
+ build.onEnd((result) => {
+ if (result.errors.length > 0) {
+ console.error(`[dev-agent-proxy] build failed with ${result.errors.length} error(s); not restarting`)
+ return
+ }
+ void launch()
+ })
+ },
+}
+
+async function main(): Promise<void> {
+ const ctx = await context({
+ ...agentProxyEsbuildOptions({ dev: true, extraPlugins: [restartPlugin] }),
+ logLevel: 'info',
+ })
+
+ const shutdown = async (): Promise<void> => {
+ if (child) {
+ child.kill('SIGTERM')
+ }
+ await ctx.dispose()
+ process.exit(0)
+ }
+ process.on('SIGINT', shutdown)
+ process.on('SIGTERM', shutdown)
+
+ await ctx.watch()
+ console.info('[dev-agent-proxy] watching src/hono/** for changes')
+}
+
+main().catch((err: unknown) => {
+ console.error('[dev-agent-proxy] fatal:', err)
+ process.exit(1)
+})
diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.ts
new file mode 100644
index 000000000000..1dbac1e73e47
--- /dev/null
+++ b/services/agent-proxy/src/hono/app.ts
@@ -0,0 +1,187 @@
+// Hono application factory for the agent-proxy service.
+//
+// Exposes:
+// GET /v1/runs/:run/stream SSE read
+// POST /v1/runs/:run/ingest NDJSON ingest
+// GET /_health, /_readyz, /health liveness / readiness
+// GET /_metrics Prometheus scrape
+// OPTIONS * CORS preflight (204)
+//
+// The run path segment is for readable logs and metrics; the run-scoped JWT is
+// the authority, so the handlers only check that it agrees with the token's run
+// claim. team/task come from the verified token, not the URL.
+//
+// Wire protocol is byte-identical to the Python proxy (proxy.py) — Django and
+// this Node service share the same Redis stream during the cutover window.
+
+import { Hono } from 'hono'
+import { stream } from 'hono/streaming'
+import type { Redis } from 'ioredis'
+
+import type { Config } from '../lib/config.js'
+import { validateStreamReadToken } from '../lib/jwt.js'
+import { logger } from '../lib/logging.js'
+import { getStreamKey } from '../lib/redis-stream.js'
+import { StreamCapacity } from '../lib/stream-capacity.js'
+import type { StreamReadTokenPayload } from '../lib/types.js'
+import { handleIngest } from './ingest-handler.js'
+import { observeStreamConnectionRejected } from './metrics.js'
+import { corsHeaders, corsPreflightHandler, httpMetrics, requestLog, securityHeaders } from './middleware.js'
+import { registerPublicRoutes } from './public-routes.js'
+import { streamTaskRunEvents } from './sse-handler.js'
+import type { Lifecycle } from './types.js'
+
+// ---------------------------------------------------------------------------
+// Exported types
+// ---------------------------------------------------------------------------
+
+export interface App {
+ app: Hono
+ lifecycle: Lifecycle
+}
+
+// ---------------------------------------------------------------------------
+// Factory
+// ---------------------------------------------------------------------------
+
+export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[]): App {
+ const app = new Hono()
+ const lifecycle: Lifecycle = { shuttingDown: false }
+ const streamCapacity = new StreamCapacity(config.maxConcurrentStreams, config.maxStreamsPerRun)
+
+ app.use('*', securityHeaders)
+ app.use('*', corsHeaders(config))
+ app.use('*', httpMetrics)
+ app.use('*', requestLog)
+
+ // -- CORS preflight --
+ app.options('*', corsPreflightHandler(config))
+
+ // -- Health, readiness, metrics --
+ registerPublicRoutes(app, lifecycle, config.metricsToken)
+
+ // -- SSE stream read --
+ app.get('/v1/runs/:run/stream', async (c) => {
+ // Token via Authorization: Bearer <token> only (no ?token= query param).
+ const token = extractStreamReadToken(c)
+ if (token === null) {
+ return c.json({ error: 'Missing stream read token' }, 401)
+ }
+
+ let claims: StreamReadTokenPayload
+ try {
+ claims = await validateStreamReadToken(token, publicKeys)
+ } catch (err: unknown) {
+ const code = err instanceof Error ? err.constructor.name : 'UnknownError'
+ return c.json({ error: 'Invalid stream read token', code }, 401)
+ }
+
+ const { run } = c.req.param() as { run: string }
+ if (claims.runId !== run) {
+ return c.json({ error: 'Token does not match run' }, 403)
+ }
+
+ const lastEventId = c.req.header('Last-Event-ID') ?? c.req.header('last-event-id') ?? null
+ const startLatest = c.req.query('start') === 'latest'
+ const streamKey = getStreamKey(claims.runId)
+
+ // Reserve a concurrency slot before any Redis work; each accepted stream holds a
+ // dedicated Redis connection until it closes. 503 (not 4xx) so clients reconnect
+ // through their normal backoff instead of treating it as fatal.
+ const rejection = streamCapacity.tryAcquire(claims.runId)
+ if (rejection !== null) {
+ observeStreamConnectionRejected(rejection)
+ logger.warn('stream:rejected_capacity', { run, reason: rejection, open: streamCapacity.openTotal })
+ c.header('Retry-After', '5')
+ return c.json({ error: 'Too many concurrent stream connections' }, 503)
+ }
+
+ logger.info('stream:open', { run, lastEventId: lastEventId ?? undefined, startLatest })
+
+ // The abort signal from the raw Request fires when the client disconnects.
+ const signal = c.req.raw.signal
+
+ return stream(c, async (responseStream) => {
+ let chunks = 0
+ const openedAt = Date.now()
+ // Wire disconnect: when the client drops, abort the SSE generator.
+ const generator = streamTaskRunEvents(streamKey, redis, {
+ originProduct: 'unknown',
+ lastEventId,
+ startLatest,
+ })
+
+ // Race each generator chunk against the client-disconnect abort signal.
+ // When abort fires we close the generator (its finally block records
+ // the 'client_disconnect' metric outcome and cleans up Redis).
+ const onAbort = (): void => {
+ // Closing the response stream also causes the outer streaming()
+ // wrapper to return, ending the handler.
+ void generator.return(undefined)
+ }
+
+ signal.addEventListener('abort', onAbort, { once: true })
+
+ try {
+ // Set SSE-specific headers on the response.
+ // Hono's stream() helper sets the response up before we write —
+ // we mutate headers before writing the first byte.
+ c.header('Content-Type', 'text/event-stream')
+ c.header('Cache-Control', 'no-cache')
+ c.header('X-Accel-Buffering', 'no')
+
+ for await (const chunk of generator) {
+ if (signal.aborted) {
+ break
+ }
+ await responseStream.write(chunk)
+ chunks++
+ if (chunks === 1) {
+ logger.debug('stream:first-event', { run })
+ }
+ }
+ } finally {
+ streamCapacity.release(claims.runId)
+ signal.removeEventListener('abort', onAbort)
+ // Ensure the generator's cleanup runs even if we broke early.
+ await generator.return(undefined).catch(() => undefined)
+ logger.info('stream:close', { run, chunks, ms: Date.now() - openedAt, aborted: signal.aborted })
+ }
+ })
+ })
+
+ // -- NDJSON event ingest --
+ app.post('/v1/runs/:run/ingest', async (c) => {
+ return handleIngest(c, redis, config, publicKeys)
+ })
+
+ // -- Catch-all 404 --
+ app.all('*', (c) => c.json({ error: 'Not found' }, 404))
+
+ return { app, lifecycle }
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+// Extract the bearer token for the stream-read leg from the Authorization
+// header only. There is deliberately no ?token= query fallback: query strings
+// are recorded by upstream infrastructure (load balancers, reverse proxies,
+// CDNs, WAFs) even though the app logger strips them, which would leak the
+// run-scoped JWT into access logs. Every client sends Authorization: Bearer
+// (the browser uses fetch-event-source, not native EventSource), so the header
+// is sufficient. If a native-EventSource client is ever needed, add a
+// single-use ticket-exchange endpoint rather than putting the JWT in the URL.
+function extractStreamReadToken(c: { req: { header: (name: string) => string | undefined } }): string | null {
+ const authorization = c.req.header('Authorization') ?? c.req.header('authorization')
+ if (!authorization) {
+ return null
+ }
+ const prefix = 'Bearer '
+ if (!authorization.startsWith(prefix)) {
+ return null
+ }
+ const token = authorization.slice(prefix.length).trim()
+ return token || null
+}
diff --git a/services/agent-proxy/src/hono/index.ts b/services/agent-proxy/src/hono/index.ts
new file mode 100644
index 000000000000..8bcb6d649a55
--- /dev/null
+++ b/services/agent-proxy/src/hono/index.ts
@@ -0,0 +1,83 @@
+// Entry point for the agent-proxy Hono server.
+//
+// Startup sequence:
+// 1. Load and validate configuration from environment variables.
+// 2. Connect to Redis (eager connect with retry).
+// 3. Import and cache the RS256 public key.
+// 4. Create the Hono app.
+// 5. Start the HTTP server on PORT (default 8003).
+// 6. Register SIGTERM/SIGINT shutdown handlers (drain in-flight SSE, quit Redis).
+
+import { serve } from '@hono/node-server'
+import Redis from 'ioredis'
+
+import { loadConfig } from '../lib/config.js'
+import { loadPublicKeys } from '../lib/jwt.js'
+import { logger } from '../lib/logging.js'
+import { createApp } from './app.js'
+import { registerShutdownHandlers } from './shutdown.js'
+
+async function main(): Promise<void> {
+ const config = loadConfig()
+
+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
+ const redis = new Redis(config.redisUrl, {
+ lazyConnect: true,
+ maxRetriesPerRequest: 3,
+ enableOfflineQueue: false,
+ connectTimeout: 5000,
+ commandTimeout: 2000,
+ keepAlive: 30000,
+ retryStrategy: (times: number) => Math.min(times * 200, 2000),
+ })
+
+ redis.on('error', (err: Error) => {
+ logger.error('redis:error', { error: err.message })
+ })
+
+ redis.on('connect', () => {
+ logger.info('redis:connected', {})
+ })
+
+ try {
+ await redis.connect()
+ } catch (err) {
+ logger.error('redis:connect_failed', { error: err instanceof Error ? err.message : String(err) })
+ process.exit(1)
+ }
+
+ let publicKeys: globalThis.CryptoKey[]
+ try {
+ publicKeys = await loadPublicKeys(config.sandboxJwtPublicKeysPem)
+ } catch (err) {
+ logger.error('jwt:public_key_load_failed', { error: err instanceof Error ? err.message : String(err) })
+ process.exit(1)
+ }
+
+ const { app, lifecycle } = createApp(redis, config, publicKeys)
+
+ const server = serve(
+ {
+ fetch: app.fetch,
+ port: config.port,
+ hostname: config.host,
+ serverOptions: { requestTimeout: 0 },
+ },
+ (info) => {
+ logger.info('server:started', { host: config.host, port: info.port })
+ }
+ )
+
+ registerShutdownHandlers({
+ server,
+ lifecycle,
+ redis,
+ shutdownGraceMs: config.shutdownGraceMs,
+ shutdownPrestopDelayMs: config.shutdownPrestopDelayMs,
+ })
+}
+
+main().catch((err) => {
+ logger.error('fatal', { error: err instanceof Error ? err.message : String(err) })
+ process.exit(1)
+})
diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.ts
new file mode 100644
index 000000000000..7dddb18bdacc
--- /dev/null
+++ b/services/agent-proxy/src/hono/ingest-handler.ts
@@ -0,0 +1,377 @@
+// NDJSON event ingest handler for POST /v1/runs/:run/ingest
+//
+// Wire protocol stays byte-identical to event_ingest.py — both the Python and
+// Node services read/write the same Redis stream during the cutover window.
+//
+// HTTP status codes:
+// 200 success: {accepted, duplicate, last_accepted_seq}
+// 400 bad NDJSON: invalid JSON, non-object, wrong field types, ordering
+// 401 missing / invalid JWT
+// 403 JWT claims don't match URL params
+// 405 wrong HTTP method
+// 409 SequenceGap / AlreadyCompleted / CompletionSequenceMismatch: {error, last_accepted_seq}
+// 413 payload too large: {error, last_accepted_seq}
+
+import type { CryptoKey } from 'crypto'
+import type { Context } from 'hono'
+import type { Redis } from 'ioredis'
+
+import type { Config } from '../lib/config.js'
+import {
+ MAX_EVENT_LINE_BYTES,
+ MAX_REQUEST_BYTES,
+ MAX_EVENTS_PER_REQUEST,
+ STREAM_COMPLETE_CONTROL_TYPE,
+} from '../lib/constants.js'
+import { validateSandboxEventIngestToken } from '../lib/jwt.js'
+import { logger } from '../lib/logging.js'
+import { TaskRunRedisStream, getStreamKey } from '../lib/redis-stream.js'
+import { heartbeatWorkflowIfNeeded } from '../lib/side-effects.js'
+import {
+ EventIngestBadRequest,
+ EventIngestPayloadTooLarge,
+ TaskRunStreamSequenceGap,
+ TaskRunStreamAlreadyCompleted,
+ TaskRunStreamCompletionSequenceMismatch,
+ type IngestEventLine,
+ type IngestCompleteLine,
+ type IngestLine,
+ type EventIngestResult,
+ type SandboxEventIngestTokenPayload,
+} from '../lib/types.js'
+import { observeStreamIngestEvents } from './metrics.js'
+
+// ---------------------------------------------------------------------------
+// Route handler (exported; wired in app.ts)
+// ---------------------------------------------------------------------------
+
+export async function handleIngest(
+ c: Context,
+ redis: Redis,
+ config: Config,
+ publicKeys: CryptoKey[]
+): Promise<Response> {
+ // Method guard (Hono enforces the route method, but keep an explicit check
+ // so the handler is safe when registered on a catch-all route too).
+ if (c.req.method !== 'POST') {
+ return c.json({ error: 'Method not allowed' }, 405)
+ }
+
+ // Authorization: Bearer <token> only (no ?token= fallback on ingest).
+ const token = extractBearerToken(c)
+ if (token === null) {
+ return c.json({ error: 'Missing authorization bearer token' }, 401)
+ }
+
+ // JWT validation.
+ let claims: SandboxEventIngestTokenPayload
+ try {
+ claims = await validateSandboxEventIngestToken(token, publicKeys)
+ } catch (err: unknown) {
+ const code = err instanceof Error ? err.constructor.name : 'UnknownError'
+ return c.json({ error: 'Invalid event ingest token', code }, 401)
+ }
+
+ // The run-scoped JWT is the authority (Django minted it for this run/task/team);
+ // the run path segment only has to agree with the token's run claim. team/task
+ // come from the verified token, not the URL.
+ const { run } = c.req.param() as { run: string }
+ if (claims.runId !== run) {
+ return c.json({ error: 'Token does not match run' }, 403)
+ }
+
+ // No run-existence check. The run-scoped sandbox_event_ingest JWT is the
+ // authorization — Django minted it for this exact run/task/team. Keeping the
+ // ingest plane free of a per-request Django round-trip is the whole point of
+ // the standalone proxy; events for a run deleted mid-stream land in the TTL-
+ // and MAXLEN-bounded Redis stream and are never read.
+
+ // NDJSON body parsing + Redis writes.
+ const streamKey = getStreamKey(claims.runId)
+ const redisStream = new TaskRunRedisStream(streamKey, redis)
+
+ let result: EventIngestResult
+ try {
+ result = await ingestEventLines(redisStream, claims, token, config, c.req.raw)
+ } catch (err: unknown) {
+ if (err instanceof EventIngestBadRequest) {
+ return c.json({ error: err.message }, 400)
+ }
+ if (err instanceof EventIngestPayloadTooLarge) {
+ return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 413)
+ }
+ if (err instanceof TaskRunStreamSequenceGap) {
+ return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 409)
+ }
+ if (err instanceof TaskRunStreamAlreadyCompleted) {
+ return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 409)
+ }
+ if (err instanceof TaskRunStreamCompletionSequenceMismatch) {
+ return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 409)
+ }
+ throw err
+ }
+
+ observeStreamIngestEvents({ accepted: result.accepted, duplicate: result.duplicate })
+
+ logger.info('ingest', {
+ run: claims.runId,
+ accepted: result.accepted,
+ duplicate: result.duplicate,
+ lastSeq: result.last_accepted_seq,
+ })
+
+ return c.json(
+ {
+ accepted: result.accepted,
+ duplicate: result.duplicate,
+ last_accepted_seq: result.last_accepted_seq,
+ },
+ 200
+ )
+}
+
+// ---------------------------------------------------------------------------
+// NDJSON body parsing + Redis write loop
+// ---------------------------------------------------------------------------
+
+async function ingestEventLines(
+ redisStream: TaskRunRedisStream,
+ claims: SandboxEventIngestTokenPayload,
+ originalToken: string,
+ config: Config,
+ rawRequest: Request
+): Promise<EventIngestResult> {
+ const result: EventIngestResult = {
+ accepted: 0,
+ duplicate: 0,
+ last_accepted_seq: await redisStream.getLastSequence(),
+ }
+
+ let eventCount = 0
+ let completionLineFinalSeq: number | null = null
+
+ try {
+ for await (const line of iterRequestLines(rawRequest)) {
+ const parsed = parseIngestLine(line)
+
+ if (parsed.kind === 'complete') {
+ if (completionLineFinalSeq !== null) {
+ throw new EventIngestBadRequest('Completion line must be the final event stream line')
+ }
+ completionLineFinalSeq = (parsed as IngestCompleteLine).finalSeq
+ continue
+ }
+
+ if (completionLineFinalSeq !== null) {
+ throw new EventIngestBadRequest('Completion line must be the final event stream line')
+ }
+
+ const eventLine = parsed as IngestEventLine
+ eventCount++
+ if (eventCount > MAX_EVENTS_PER_REQUEST) {
+ throw new EventIngestPayloadTooLarge('Too many events in request', result.last_accepted_seq)
+ }
+
+ const { seq, event } = eventLine
+ const streamId = await redisStream.writeEventWithSequence(event, seq)
+
+ if (streamId === null) {
+ // Duplicate: advance last_accepted_seq to whatever Redis has.
+ result.duplicate++
+ result.last_accepted_seq = Math.max(result.last_accepted_seq, await redisStream.getLastSequence())
+ continue
+ }
+
+ result.accepted++
+ result.last_accepted_seq = seq
+
+ await heartbeatWorkflowIfNeeded(
+ redisStream,
+ claims.runId,
+ event,
+ claims.taskId,
+ claims.teamId,
+ originalToken,
+ config
+ )
+ }
+ } catch (err: unknown) {
+ // Re-throw EventIngestPayloadTooLarge with the current last_accepted_seq
+ // if the error didn't carry one (mirrors Python's except re-raise).
+ if (err instanceof EventIngestPayloadTooLarge && result.last_accepted_seq > 0 && err.lastAcceptedSeq === 0) {
+ err.lastAcceptedSeq = result.last_accepted_seq
+ }
+ throw err
+ }
+
+ if (completionLineFinalSeq !== null) {
+ await redisStream.markCompleteAfterSequence(completionLineFinalSeq)
+ }
+
+ return result
+}
+
+// ---------------------------------------------------------------------------
+// NDJSON line parser (mirrors _parse_ingest_line)
+// ---------------------------------------------------------------------------
+
+function parseIngestLine(line: string): IngestLine {
+ let payload: unknown
+ try {
+ payload = JSON.parse(line)
+ } catch {
+ throw new EventIngestBadRequest('Invalid JSON line')
+ }
+
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
+ throw new EventIngestBadRequest('Each event line must be a JSON object')
+ }
+
+ const obj = payload as Record<string, unknown>
+
+ // Completion line detection (must come before event line parsing).
+ if (obj['type'] === STREAM_COMPLETE_CONTROL_TYPE) {
+ const finalSeq = obj['final_seq']
+ // type(final_sequence) is not int or final_sequence < 0 (Python exact check).
+ // typeof guards booleans (typeof true === 'boolean', not 'number').
+ if (typeof finalSeq !== 'number' || !Number.isInteger(finalSeq) || finalSeq < 0) {
+ throw new EventIngestBadRequest('Completion final sequence must be a non-negative integer')
+ }
+ return { kind: 'complete', finalSeq }
+ }
+
+ // Event line.
+ const seq = obj['seq']
+ const event = obj['event']
+
+ // typeof guards booleans (typeof true === 'boolean', not 'number').
+ if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 1) {
+ throw new EventIngestBadRequest('Event sequence must be a positive integer')
+ }
+ if (typeof event !== 'object' || event === null || Array.isArray(event)) {
+ throw new EventIngestBadRequest('Event payload must be an object')
+ }
+
+ return { kind: 'event', seq, event: event as Record<string, unknown> }
+}
+
+// ---------------------------------------------------------------------------
+// Streaming NDJSON body reader (mirrors _iter_request_lines)
+// ---------------------------------------------------------------------------
+
+async function* iterRequestLines(request: Request): AsyncGenerator<string> {
+ const body = request.body
+ if (body === null) {
+ return
+ }
+
+ const reader = body.getReader()
+ let buffer = new Uint8Array(0)
+ let requestSize = 0
+ const newline = 0x0a // '\n'
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+
+ if (value !== undefined && value.length > 0) {
+ requestSize += value.length
+ if (requestSize > MAX_REQUEST_BYTES) {
+ throw new EventIngestPayloadTooLarge('Event ingest request is too large')
+ }
+
+ // Append chunk to buffer.
+ const combined = new Uint8Array(buffer.length + value.length)
+ combined.set(buffer)
+ combined.set(value, buffer.length)
+ buffer = combined
+
+ // Guard: if the buffer is larger than one max line with no newline,
+ // the line itself is already too large.
+ if (buffer.length > MAX_EVENT_LINE_BYTES && !buffer.includes(newline)) {
+ throw new EventIngestPayloadTooLarge('Event line is too large')
+ }
+
+ // Yield all complete lines (terminated by '\n').
+ let start = 0
+ for (let i = 0; i < buffer.length; i++) {
+ if (buffer[i] === newline) {
+ const lineBytes = buffer.subarray(start, i)
+ start = i + 1
+
+ if (lineBytes.length > MAX_EVENT_LINE_BYTES) {
+ throw new EventIngestPayloadTooLarge('Event line is too large')
+ }
+
+ // Trim whitespace (strip).
+ const trimmed = trimBytes(lineBytes)
+ if (trimmed.length === 0) {
+ continue
+ }
+
+ yield decodeUtf8(trimmed)
+ }
+ }
+
+ // Keep the partial trailing line in buffer.
+ buffer = buffer.subarray(start)
+ }
+
+ if (done) {
+ // Flush trailing partial line.
+ const trimmed = trimBytes(buffer)
+ if (trimmed.length > 0) {
+ if (trimmed.length > MAX_EVENT_LINE_BYTES) {
+ throw new EventIngestPayloadTooLarge('Event line is too large')
+ }
+ yield decodeUtf8(trimmed)
+ }
+ return
+ }
+ }
+ } finally {
+ reader.releaseLock()
+ }
+}
+
+// Decode bytes as UTF-8, mapping decode errors to EventIngestBadRequest.
+function decodeUtf8(bytes: Uint8Array): string {
+ try {
+ // TextDecoder with fatal:true throws on invalid byte sequences.
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes)
+ } catch {
+ throw new EventIngestBadRequest('Invalid UTF-8 in event stream')
+ }
+}
+
+// Trim leading and trailing ASCII whitespace bytes (space, tab, CR, LF).
+function trimBytes(bytes: Uint8Array): Uint8Array {
+ const isWs = (b: number): boolean => b === 0x20 || b === 0x09 || b === 0x0d || b === 0x0a
+ let start = 0
+ let end = bytes.length
+ while (start < end && isWs(bytes[start] ?? 0)) {
+ start++
+ }
+ while (end > start && isWs(bytes[end - 1] ?? 0)) {
+ end--
+ }
+ return bytes.subarray(start, end)
+}
+
+// ---------------------------------------------------------------------------
+// Token extraction
+// ---------------------------------------------------------------------------
+
+function extractBearerToken(c: Context): string | null {
+ const authorization = c.req.header('Authorization') ?? c.req.header('authorization')
+ if (!authorization) {
+ return null
+ }
+ const prefix = 'Bearer '
+ if (!authorization.startsWith(prefix)) {
+ return null
+ }
+ const token = authorization.slice(prefix.length).trim()
+ return token || null
+}
diff --git a/services/agent-proxy/src/hono/metrics.ts b/services/agent-proxy/src/hono/metrics.ts
new file mode 100644
index 000000000000..fc14c5bae94e
--- /dev/null
+++ b/services/agent-proxy/src/hono/metrics.ts
@@ -0,0 +1,181 @@
+// Prometheus metrics for the agent-proxy service.
+//
+// Metric names are byte-identical to their Python counterparts in
+// products/tasks/backend/metrics.py so dashboards and alerts work across both
+// the Python ASGI proxy and this Node service without changes.
+//
+// Cardinality is intentionally kept low: only origin_product and outcome are
+// used as labels on the hot-path stream metrics. Never add per-run or per-team
+// labels here.
+
+import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from 'prom-client'
+
+import type { StreamConnectionOutcome } from '../lib/types.js'
+
+export const register = new Registry()
+
+// Collect default Node.js metrics (event loop lag, GC, memory, etc.) with a
+// consistent prefix so they don't collide with application metric names.
+collectDefaultMetrics({ register, prefix: 'agent_proxy_' })
+
+// ---------------------------------------------------------------------------
+// SSE stream connection metrics (names match Python counterparts exactly)
+// ---------------------------------------------------------------------------
+
+export const taskRunStreamConnectionsOpenedTotal = new Counter({
+ name: 'posthog_tasks_task_run_stream_connections_opened_total',
+ help: 'SSE task-run stream connections opened',
+ labelNames: ['origin_product'],
+ registers: [register],
+})
+
+export const taskRunStreamConnectionsClosedTotal = new Counter({
+ name: 'posthog_tasks_task_run_stream_connections_closed_total',
+ help: 'SSE task-run stream connections closed, labeled by how they ended',
+ labelNames: ['origin_product', 'outcome'],
+ registers: [register],
+})
+
+// Connection lifetimes span a few seconds (cold reconnect) to the 6h sandbox
+// TTL. The 120s bucket is deliberate: it isolates connections cut at the
+// Envoy/Contour response_timeout boundary from genuinely long-lived ones.
+export const taskRunStreamConnectionDurationSeconds = new Histogram({
+ name: 'posthog_tasks_task_run_stream_connection_duration_seconds',
+ help: 'Lifetime of an SSE task-run stream connection',
+ labelNames: ['origin_product', 'outcome'],
+ buckets: [1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200, 21600],
+ registers: [register],
+})
+
+// Stream length is capped at TASK_RUN_STREAM_MAX_LENGTH (~20k); the top
+// buckets show how close real runs get to the trim threshold.
+export const taskRunStreamLengthOnConnect = new Histogram({
+ name: 'posthog_tasks_task_run_stream_length_on_connect',
+ help: 'Redis stream length observed when an SSE connection reconnects with a cursor',
+ buckets: [10, 50, 100, 500, 1000, 2500, 5000, 10000, 15000, 20000],
+ registers: [register],
+})
+
+export const taskRunStreamResumeGapTotal = new Counter({
+ name: 'posthog_tasks_task_run_stream_resume_gap_total',
+ help: 'SSE reconnects whose Last-Event-ID was already trimmed from Redis (events lost for that client)',
+ labelNames: ['origin_product'],
+ registers: [register],
+})
+
+// Connections turned away by the concurrency caps before any Redis work; reason is
+// 'pod_capacity' (pod-wide total reached) or 'run_capacity' (per-run fanout reached).
+export const taskRunStreamConnectionsRejectedTotal = new Counter({
+ name: 'posthog_tasks_task_run_stream_connections_rejected_total',
+ help: 'SSE task-run stream connections rejected by concurrency caps',
+ labelNames: ['reason'],
+ registers: [register],
+})
+
+// ---------------------------------------------------------------------------
+// Ingest plane metrics
+// ---------------------------------------------------------------------------
+
+export const streamIngestEventsTotal = new Counter({
+ name: 'posthog_tasks_stream_ingest_events_total',
+ help: 'Sandbox-to-Node ingested events by acceptance result',
+ labelNames: ['result'],
+ registers: [register],
+})
+
+// ---------------------------------------------------------------------------
+// HTTP infrastructure metrics
+// ---------------------------------------------------------------------------
+
+// Map parameterised route paths to stable label values so cardinality stays
+// bounded. Dynamic segments (UUIDs, IDs) must never appear in label values.
+export function routeLabel(pathname: string): string {
+ // Probe and scrape paths are already stable.
+ if (pathname === '/_health' || pathname === '/_readyz' || pathname === '/_metrics' || pathname === '/health') {
+ return pathname
+ }
+ // SSE read leg: /v1/runs/<run>/stream
+ if (/^\/v1\/runs\/[^/]+\/stream$/.test(pathname)) {
+ return '/v1/runs/stream'
+ }
+ // NDJSON ingest leg: /v1/runs/<run>/ingest
+ if (/^\/v1\/runs\/[^/]+\/ingest$/.test(pathname)) {
+ return '/v1/runs/ingest'
+ }
+ return 'other'
+}
+
+export const httpRequestsTotal = new Counter({
+ name: 'agent_proxy_http_requests_total',
+ help: 'Total HTTP requests received',
+ labelNames: ['method', 'route', 'status'],
+ registers: [register],
+})
+
+export const httpRequestDurationSeconds = new Histogram({
+ name: 'agent_proxy_http_request_duration_seconds',
+ help: 'HTTP request duration in seconds',
+ labelNames: ['method', 'route', 'status'],
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
+ registers: [register],
+})
+
+export const inflightRequests = new Gauge({
+ name: 'agent_proxy_http_requests_inflight',
+ help: 'Number of HTTP requests currently being processed',
+ labelNames: ['route'] as const,
+ registers: [register],
+})
+
+export const shuttingDown = new Gauge({
+ name: 'agent_proxy_shutting_down',
+ help: '1 if the service is in the process of shutting down, 0 otherwise',
+ registers: [register],
+})
+
+// Tracks the number of currently open SSE stream connections.
+export const openSseStreams = new Gauge({
+ name: 'agent_proxy_sse_open_streams',
+ help: 'Number of SSE task-run stream connections currently open',
+ registers: [register],
+})
+
+// ---------------------------------------------------------------------------
+// Convenience wrappers (mirror the Python observe_* helpers)
+// ---------------------------------------------------------------------------
+
+export function observeStreamConnectionOpened(originProduct: string): void {
+ taskRunStreamConnectionsOpenedTotal.labels({ origin_product: originProduct }).inc()
+ openSseStreams.inc()
+}
+
+export function observeStreamConnectionClosed(
+ originProduct: string,
+ outcome: StreamConnectionOutcome,
+ durationSeconds: number
+): void {
+ taskRunStreamConnectionsClosedTotal.labels({ origin_product: originProduct, outcome }).inc()
+ taskRunStreamConnectionDurationSeconds.labels({ origin_product: originProduct, outcome }).observe(durationSeconds)
+ openSseStreams.dec()
+}
+
+export function observeStreamLengthOnConnect(length: number): void {
+ taskRunStreamLengthOnConnect.observe(length)
+}
+
+export function observeStreamResumeGap(originProduct: string): void {
+ taskRunStreamResumeGapTotal.labels({ origin_product: originProduct }).inc()
+}
+
+export function observeStreamConnectionRejected(reason: string): void {
+ taskRunStreamConnectionsRejectedTotal.labels({ reason }).inc()
+}
+
+export function observeStreamIngestEvents(opts: { accepted: number; duplicate: number }): void {
+ if (opts.accepted > 0) {
+ streamIngestEventsTotal.labels({ result: 'accepted' }).inc(opts.accepted)
+ }
+ if (opts.duplicate > 0) {
+ streamIngestEventsTotal.labels({ result: 'duplicate' }).inc(opts.duplicate)
+ }
+}
diff --git a/services/agent-proxy/src/hono/middleware.ts b/services/agent-proxy/src/hono/middleware.ts
new file mode 100644
index 000000000000..fc38445b15ce
--- /dev/null
+++ b/services/agent-proxy/src/hono/middleware.ts
@@ -0,0 +1,104 @@
+// Named Hono middleware exports for the agent-proxy.
+//
+// securityHeaders — X-Content-Type-Options, X-Frame-Options on every response.
+// corsHeaders — Access-Control-Allow-Origin / Vary on matching origin responses.
+// httpMetrics — prom-client counter + histogram + inflight gauge per request.
+// requestLog — wide-event RequestLogger summary line at INFO level.
+
+import type { MiddlewareHandler } from 'hono'
+
+import type { Config } from '../lib/config.js'
+import { CORS_ALLOW_HEADERS, CORS_ALLOW_METHODS, CORS_MAX_AGE } from '../lib/constants.js'
+import { RequestLogger, logger, redactHeaders } from '../lib/logging.js'
+import { httpRequestDurationSeconds, httpRequestsTotal, inflightRequests, routeLabel } from './metrics.js'
+import { PROBE_PATHS } from './public-routes.js'
+import type { HonoVariables } from './types.js'
+
+export const securityHeaders: MiddlewareHandler = async (c, next) => {
+ await next()
+ c.header('X-Content-Type-Options', 'nosniff')
+ c.header('X-Frame-Options', 'DENY')
+}
+
+export function corsHeaders(config: Config): MiddlewareHandler {
+ return async (c, next) => {
+ const origin = c.req.header('Origin')
+ await next()
+ if (!origin) {
+ return
+ }
+ const allowed = config.corsOrigins.has('*') || config.corsOrigins.has(origin)
+ if (allowed) {
+ c.header('Access-Control-Allow-Origin', origin)
+ c.header('Vary', 'Origin')
+ }
+ }
+}
+
+// Skip /_metrics itself to avoid self-scrape noise inflating the histograms.
+// Uses prom-client's startTimer so the observation fires even if next() throws.
+export const httpMetrics: MiddlewareHandler = async (c, next) => {
+ const pathname = new URL(c.req.url).pathname
+ if (pathname === '/_metrics') {
+ return next()
+ }
+
+ const route = routeLabel(pathname)
+ inflightRequests.labels({ route }).inc()
+ const endTimer = httpRequestDurationSeconds.startTimer({ method: c.req.method, route })
+
+ try {
+ await next()
+ } finally {
+ const status = String(c.res.status)
+ inflightRequests.labels({ route }).dec()
+ httpRequestsTotal.labels({ method: c.req.method, route, status }).inc()
+ endTimer({ status })
+ }
+}
+
+// Emit one structured summary line per non-probe request at INFO level.
+// Route handlers may call c.get('requestLogger').extend({ ... }) to merge
+// domain-specific fields (run ID, accepted count, etc.) into the summary.
+export const requestLog: MiddlewareHandler<{ Variables: HonoVariables }> = async (c, next) => {
+ const pathname = new URL(c.req.url).pathname
+ if (PROBE_PATHS.has(pathname)) {
+ return next()
+ }
+
+ const log = new RequestLogger()
+ c.set('requestLogger', log)
+
+ // Capture a curated subset of request headers (redact sensitive values).
+ const rawHeaders: Record<string, string> = {}
+ c.req.raw.headers.forEach((value, key) => {
+ rawHeaders[key] = value
+ })
+ log.extend({
+ method: c.req.method,
+ path: pathname,
+ headers: redactHeaders(rawHeaders),
+ })
+
+ try {
+ await next()
+ } finally {
+ logger.info('http.request', log.finish(c.res.status))
+ }
+}
+
+// CORS preflight handler — registered on app.options('*') in app.ts.
+// Returns 204 with CORS headers when origin is in the allowlist.
+export function corsPreflightHandler(config: Config): MiddlewareHandler {
+ return async (c) => {
+ const origin = c.req.header('Origin')
+ if (origin && (config.corsOrigins.has('*') || config.corsOrigins.has(origin))) {
+ c.header('Access-Control-Allow-Origin', origin)
+ c.header('Vary', 'Origin')
+ c.header('Access-Control-Allow-Methods', CORS_ALLOW_METHODS)
+ c.header('Access-Control-Allow-Headers', CORS_ALLOW_HEADERS)
+ c.header('Access-Control-Max-Age', CORS_MAX_AGE)
+ }
+ return c.body(null, 204)
+ }
+}
diff --git a/services/agent-proxy/src/hono/public-routes.ts b/services/agent-proxy/src/hono/public-routes.ts
new file mode 100644
index 000000000000..1c22ebd77190
--- /dev/null
+++ b/services/agent-proxy/src/hono/public-routes.ts
@@ -0,0 +1,56 @@
+// Probe, health and metrics routes for the agent-proxy.
+//
+// These paths are excluded from the request log so Kubernetes health checks
+// don't drown out real traffic.
+//
+// /_metrics optionally requires a bearer token (AGENT_PROXY_METRICS_TOKEN):
+// this host is publicly reachable for the SSE/ingest routes, so operational
+// metrics should not be open to the internet once the scrape token is
+// provisioned. Unset keeps the route open for in-cluster scrapes that have
+// no token configured.
+
+import type { Hono } from 'hono'
+import { createHash, timingSafeEqual } from 'node:crypto'
+
+import { register, shuttingDown as shuttingDownGauge } from './metrics.js'
+import type { Lifecycle } from './types.js'
+
+// Paths excluded from the request log middleware.
+export const PROBE_PATHS = new Set(['/_health', '/_readyz', '/_metrics', '/health'])
+
+// Hash both sides so timingSafeEqual gets equal-length buffers without leaking
+// the configured token's length through an early mismatch return.
+function tokensMatch(provided: string, expected: string): boolean {
+ const providedDigest = createHash('sha256').update(provided).digest()
+ const expectedDigest = createHash('sha256').update(expected).digest()
+ return timingSafeEqual(providedDigest, expectedDigest)
+}
+
+export function registerPublicRoutes(app: Hono, lifecycle: Lifecycle, metricsToken: string): void {
+ app.get('/_health', (c) => c.json({ status: 'ok' }))
+
+ app.get('/_readyz', (c) => {
+ if (lifecycle.shuttingDown) {
+ return c.json({ status: 'shutting_down' }, 503)
+ }
+ return c.json({ status: 'ok' })
+ })
+
+ app.get('/health', (c) => c.json({ status: 'ok' }))
+
+ app.get('/_metrics', async (c) => {
+ if (metricsToken) {
+ const authorization = c.req.header('Authorization') ?? ''
+ const provided = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length).trim() : ''
+ if (!provided || !tokensMatch(provided, metricsToken)) {
+ return c.json({ error: 'Unauthorized' }, 401)
+ }
+ }
+
+ // Update shutting-down gauge inline so it reflects the current state
+ // when the scrape runs (no event-loop delays on the gauge itself).
+ shuttingDownGauge.set(lifecycle.shuttingDown ? 1 : 0)
+ const metrics = await register.metrics()
+ return c.text(metrics, 200, { 'Content-Type': register.contentType })
+ })
+}
diff --git a/services/agent-proxy/src/hono/shutdown.ts b/services/agent-proxy/src/hono/shutdown.ts
new file mode 100644
index 000000000000..ee6c6a8e634e
--- /dev/null
+++ b/services/agent-proxy/src/hono/shutdown.ts
@@ -0,0 +1,62 @@
+// Graceful shutdown handler for the agent-proxy Hono server.
+//
+// Registers SIGTERM and SIGINT handlers that:
+// 1. Optionally wait for a prestop delay (Kubernetes lifecycle hook window).
+// 2. Drain in-flight SSE connections up to the grace budget.
+// 3. Quit the shared Redis client.
+// 4. Exit with code 0.
+
+import type { ServerType } from '@hono/node-server'
+import type { Redis } from 'ioredis'
+
+import { logger } from '../lib/logging.js'
+import { shuttingDown as shuttingDownGauge } from './metrics.js'
+import type { Lifecycle } from './types.js'
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+export function registerShutdownHandlers(opts: {
+ server: ServerType
+ lifecycle: Lifecycle
+ redis: InstanceType<typeof Redis>
+ shutdownGraceMs: number
+ shutdownPrestopDelayMs: number
+}): void {
+ const { server, lifecycle, redis, shutdownGraceMs, shutdownPrestopDelayMs } = opts
+ let alreadyShuttingDown = false
+
+ const shutdown = async (signal: string): Promise<void> => {
+ if (alreadyShuttingDown) {
+ return
+ }
+ alreadyShuttingDown = true
+ logger.info('shutdown:start', { signal })
+
+ lifecycle.shuttingDown = true
+ shuttingDownGauge.set(1)
+
+ const shutdownStart = Date.now()
+ if (shutdownPrestopDelayMs > 0) {
+ await sleep(shutdownPrestopDelayMs)
+ }
+
+ // Drain in-flight requests (SSE connections) up to the grace budget.
+ const drainBudget = Math.max(shutdownGraceMs - (Date.now() - shutdownStart), 1000)
+ const closed = new Promise<void>((resolve) => server.close(() => resolve()))
+ await Promise.race([closed, sleep(drainBudget)])
+
+ try {
+ await redis.quit()
+ } catch (err) {
+ logger.error('shutdown:redis_quit_failed', { error: err instanceof Error ? err.message : String(err) })
+ }
+
+ logger.info('shutdown:complete', {})
+ process.exit(0)
+ }
+
+ process.on('SIGTERM', () => void shutdown('SIGTERM'))
+ process.on('SIGINT', () => void shutdown('SIGINT'))
+}
diff --git a/services/agent-proxy/src/hono/sse-handler.ts b/services/agent-proxy/src/hono/sse-handler.ts
new file mode 100644
index 000000000000..114ee79451c7
--- /dev/null
+++ b/services/agent-proxy/src/hono/sse-handler.ts
@@ -0,0 +1,263 @@
+// SSE stream handler for task-run event streams.
+//
+// Ports products/tasks/backend/stream/sse.py (stream_task_run_events) to an
+// async generator yielding SSE byte chunks. Wire protocol is byte-identical to
+// the Python implementation: during cutover Django and this Node service read
+// the SAME Redis stream and serve the SAME clients. Any drift corrupts live runs.
+//
+// SSE framing (format_sse_event — byte-identical to Python):
+// [event: <name>\n] — only when eventName is truthy
+// [id: <eventId>\n] — only when eventId is truthy
+// data: <JSON>\n
+// \n
+//
+// Event types:
+// Normal stream event — no eventName, id = Redis stream ID
+// Keepalive — eventName='keepalive', data={"type":"keepalive"}
+// Terminal — eventName='stream-end', data={"status":"complete"}
+// Stream error — eventName='error', data={"error":"<msg>"}
+// Stream unavailable — eventName='error', data={"error":"Stream not available"}
+
+import type { Redis } from 'ioredis'
+
+import {
+ KEEPALIVE_INTERVAL_MS,
+ SSE_EVENT_ERROR,
+ SSE_EVENT_KEEPALIVE,
+ SSE_EVENT_STREAM_END,
+ SSE_PAYLOAD_KEEPALIVE,
+ SSE_PAYLOAD_STREAM_END,
+ WAIT_DELAY_INCREMENT_MS,
+ WAIT_INITIAL_DELAY_MS,
+ WAIT_MAX_DELAY_MS,
+ WAIT_TIMEOUT_MS,
+ makeSseErrorPayload,
+} from '../lib/constants.js'
+import { logger } from '../lib/logging.js'
+import { TaskRunRedisStream } from '../lib/redis-stream.js'
+import type { StreamConnectionOutcome } from '../lib/types.js'
+import { TaskRunStreamError } from '../lib/types.js'
+import {
+ observeStreamConnectionClosed,
+ observeStreamConnectionOpened,
+ observeStreamLengthOnConnect,
+ observeStreamResumeGap,
+} from './metrics.js'
+
+// ---------------------------------------------------------------------------
+// SSE framing
+// ---------------------------------------------------------------------------
+
+/**
+ * Format one SSE event frame, byte-identical to the Python format_sse_event.
+ *
+ * Order: [event: <name>\n] [id: <id>\n] data: <json>\n\n
+ *
+ * The result is encoded as UTF-8 and returned as a Buffer so callers can pipe
+ * it directly into an HTTP response body without additional conversion.
+ */
+export function formatSseEvent(data: Record<string, unknown>, opts?: { eventId?: string; eventName?: string }): Buffer {
+ const parts: string[] = []
+ if (opts?.eventName) {
+ parts.push(`event: ${opts.eventName}`)
+ }
+ if (opts?.eventId) {
+ parts.push(`id: ${opts.eventId}`)
+ }
+ parts.push(`data: ${JSON.stringify(data)}`)
+ return Buffer.from(parts.join('\n') + '\n\n', 'utf8')
+}
+
+// ---------------------------------------------------------------------------
+// SSE stream generator
+// ---------------------------------------------------------------------------
+
+/**
+ * Async generator that yields SSE-formatted byte chunks for one task-run
+ * stream connection.
+ *
+ * Mirrors Python stream_task_run_events exactly:
+ * 1. Records opened metric; sets default outcome = 'client_disconnect'.
+ * 2. Wait-for-stream loop: polls exists() with linear backoff until the
+ * stream appears or the 120s timeout fires (yields unavailable error event
+ * and returns on timeout; yields keepalive every 20s while waiting).
+ * 3. Resolves startId from lastEventId / startLatest / '0'.
+ * 4. On reconnect (lastEventId set): observes stream length and checks for
+ * resume gap (best-effort — catches all exceptions, never breaks stream).
+ * 5. Iterates readStreamEntries:
+ * - null → yield keepalive
+ * - entry → yield formatSseEvent(event, {eventId})
+ * 6. After generator returns (completion sentinel consumed): yield stream-end
+ * terminal event; set outcome = 'completed'.
+ * 7. On TaskRunStreamError: yield error event; set outcome = 'stream_error'.
+ * 8. Finally: record closed metric with outcome and duration.
+ *
+ * @yields {Buffer} SSE-formatted byte chunk (UTF-8 encoded).
+ */
+export async function* streamTaskRunEvents(
+ streamKey: string,
+ redis: Redis,
+ opts: {
+ originProduct?: string
+ lastEventId?: string | null
+ startLatest?: boolean
+ }
+): AsyncGenerator<Buffer, void, unknown> {
+ const originProduct = opts.originProduct ?? 'unknown'
+ const lastEventId = opts.lastEventId ?? null
+ const startLatest = opts.startLatest ?? false
+
+ const redisStream = new TaskRunRedisStream(streamKey, redis)
+ const connectionStartedAt = Date.now()
+
+ let outcome: StreamConnectionOutcome = 'client_disconnect'
+ let opened = false
+ // Dedicated blocking-read connection created just before the main read loop.
+ // Declared here so the finally block can close it regardless of how the
+ // generator exits (completion, error, or client disconnect).
+ let dedupRedis: Redis | undefined
+
+ try {
+ observeStreamConnectionOpened(originProduct)
+ opened = true
+
+ // -- Wait-for-stream loop --
+ let delay = WAIT_INITIAL_DELAY_MS
+ const waitStartedAt = Date.now()
+ let lastKeepaliveAt = waitStartedAt
+ let waited = false
+
+ while (!(await redisStream.exists())) {
+ const now = Date.now()
+
+ if (!waited) {
+ waited = true
+ logger.debug('stream:waiting', { streamKey })
+ }
+
+ if (now - waitStartedAt >= WAIT_TIMEOUT_MS) {
+ outcome = 'unavailable'
+ logger.warn('stream:unavailable', { streamKey, waitedMs: now - waitStartedAt })
+ yield formatSseEvent(makeSseErrorPayload('Stream not available'), {
+ eventName: SSE_EVENT_ERROR,
+ })
+ return
+ }
+
+ if (now - lastKeepaliveAt >= KEEPALIVE_INTERVAL_MS) {
+ lastKeepaliveAt = now
+ yield formatSseEvent(SSE_PAYLOAD_KEEPALIVE, { eventName: SSE_EVENT_KEEPALIVE })
+ }
+
+ await sleep(delay)
+ delay = Math.min(delay + WAIT_DELAY_INCREMENT_MS, WAIT_MAX_DELAY_MS)
+ }
+
+ if (waited) {
+ logger.debug('stream:available', { streamKey, waitedMs: Date.now() - waitStartedAt })
+ }
+
+ // -- Resolve start ID --
+ let startId: string
+ if (lastEventId) {
+ startId = lastEventId
+ } else if (startLatest) {
+ startId = (await redisStream.getLatestStreamId()) ?? '0'
+ } else {
+ startId = '0'
+ }
+
+ // -- Resume gap detection (only on reconnects; best-effort) --
+ if (lastEventId) {
+ try {
+ observeStreamLengthOnConnect(await redisStream.getLength())
+ if (await redisStream.resumePointTrimmed(lastEventId)) {
+ observeStreamResumeGap(originProduct)
+ logger.warn('stream:resume_gap', { streamKey, lastEventId })
+ }
+ } catch {
+ logger.warn('stream:attach_observe_failed', { streamKey })
+ }
+ }
+
+ // Dedicated connection for the blocking XREAD loop so it cannot delay the
+ // shared client's ingest writes (XADD, WATCH/MULTI) or non-blocking reads.
+ // Connection count is bounded upstream by StreamCapacity (app.ts), which caps
+ // concurrent streams per pod and per run before this duplicate is created.
+ // FOLLOWUP: if pod-level connection count becomes a concern within those caps,
+ // replace the per-stream duplicate with a small bounded pool of blocking-read
+ // connections shared across streams. Not worth the complexity until profiling
+ // shows a connection-count problem.
+ // enableOfflineQueue:false + lazyConnect means we must call connect() explicitly
+ // before the first command and register an error listener.
+ dedupRedis = redis.duplicate()
+ dedupRedis.on('error', (err: Error) => logger.warn('stream:redis_dup_error', { streamKey, error: err.message }))
+ try {
+ await dedupRedis.connect()
+ } catch (err) {
+ // The dedicated connection could not be established (e.g. Redis at its
+ // connection limit). Degrade like a mid-stream connection loss: surface
+ // an SSE error event rather than throwing a raw error out of the handler.
+ outcome = 'stream_error'
+ logger.error('stream:redis_dup_connect_failed', {
+ streamKey,
+ error: err instanceof Error ? err.message : String(err),
+ })
+ yield formatSseEvent(makeSseErrorPayload('Connection lost to task run stream'), {
+ eventName: SSE_EVENT_ERROR,
+ })
+ return
+ }
+
+ // -- Main read loop --
+ try {
+ for await (const streamItem of redisStream.readStreamEntries({
+ startId,
+ keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS,
+ blockingRedis: dedupRedis,
+ })) {
+ if (streamItem === null) {
+ // Idle keepalive signal from readStreamEntries
+ yield formatSseEvent(SSE_PAYLOAD_KEEPALIVE, { eventName: SSE_EVENT_KEEPALIVE })
+ continue
+ }
+
+ const [eventId, event] = streamItem
+ yield formatSseEvent(event, { eventId })
+ }
+
+ // Generator returned normally — completion sentinel was consumed.
+ outcome = 'completed'
+ yield formatSseEvent(SSE_PAYLOAD_STREAM_END, { eventName: SSE_EVENT_STREAM_END })
+ } catch (err) {
+ if (err instanceof TaskRunStreamError) {
+ outcome = 'stream_error'
+ logger.error('stream:error', { streamKey, error: err.message })
+ yield formatSseEvent(makeSseErrorPayload(err.message), { eventName: SSE_EVENT_ERROR })
+ } else {
+ throw err
+ }
+ }
+ } finally {
+ if (opened) {
+ const durationSeconds = (Date.now() - connectionStartedAt) / 1000
+ observeStreamConnectionClosed(originProduct, outcome, durationSeconds)
+ }
+ // Close the dedicated blocking-read connection. ioredis v4 disconnect() is
+ // synchronous (returns void) and also aborts any in-flight XREAD BLOCK on
+ // client disconnect, which is what we want.
+ try {
+ dedupRedis?.disconnect()
+ } catch {
+ // best-effort cleanup — never let teardown throw out of the finally
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
diff --git a/services/agent-proxy/src/hono/types.ts b/services/agent-proxy/src/hono/types.ts
new file mode 100644
index 000000000000..900062b65267
--- /dev/null
+++ b/services/agent-proxy/src/hono/types.ts
@@ -0,0 +1,17 @@
+// Hono application-level types for the agent-proxy.
+//
+// HonoVariables is the context variables map wired into the Hono app. Route
+// handlers use HonoCtx to get typed access to c.get('requestLogger') without
+// casts.
+
+import type { Context } from 'hono'
+
+import type { RequestLogger } from '../lib/logging.js'
+
+export type HonoVariables = { requestLogger: RequestLogger }
+export type HonoCtx = Context<{ Variables: HonoVariables }>
+
+// Lifecycle flag shared between app factory, public-routes, and shutdown handler.
+export interface Lifecycle {
+ shuttingDown: boolean
+}
diff --git a/services/agent-proxy/src/lib/config.ts b/services/agent-proxy/src/lib/config.ts
new file mode 100644
index 000000000000..56479075a9a2
--- /dev/null
+++ b/services/agent-proxy/src/lib/config.ts
@@ -0,0 +1,142 @@
+// Environment variable loading and validation for the agent-proxy service.
+//
+// Required vars (must be present in production / NODE_ENV=production):
+// REDIS_URL
+// SANDBOX_JWT_PUBLIC_KEY
+// AGENT_PROXY_DJANGO_CALLBACK_URL
+//
+// Optional with defaults:
+// SANDBOX_JWT_PUBLIC_KEY_SECONDARY — extra public key trusted during key rotation
+// TASKS_AGENT_PROXY_CORS_ORIGINS — comma-separated origins; '' disables CORS
+// AGENT_PROXY_MAX_CONCURRENT_STREAMS — default 1000; per-pod cap on open SSE streams
+// AGENT_PROXY_MAX_STREAMS_PER_RUN — default 25; per-run cap on open SSE streams
+// AGENT_PROXY_METRICS_TOKEN — default ''; bearer token gating /_metrics when set
+// PORT — default 8003
+// HOST — default '0.0.0.0'
+// SHUTDOWN_GRACE_MS — default 300000 (5 min)
+// SHUTDOWN_PRESTOP_DELAY_MS — default 0
+
+import { getEnv, type KnownEnvKey } from './env.js'
+import { logger } from './logging.js'
+
+export interface Config {
+ redisUrl: string
+ // PEM strings with real newlines (backslash-n sequences normalized before storage). The
+ // primary key first, then an optional rotation-secondary key; a token verifies against any.
+ sandboxJwtPublicKeysPem: string[]
+ // Parsed from comma-separated TASKS_AGENT_PROXY_CORS_ORIGINS; '*' = all origins
+ corsOrigins: Set<string>
+ // Base URL of the internal Django service (no trailing slash)
+ djangoCallbackBaseUrl: string
+ // Shared secret sent as X-Agent-Proxy-Secret on the Django callback so Django can prove the call
+ // came from this proxy and not directly from a sandbox. Empty disables it (local/dev).
+ agentProxyCallbackSecret: string
+ // Each open SSE stream holds a dedicated Redis connection, so these caps protect the Redis
+ // maxclients budget: a pod-wide total and a per-run fanout limit (one stream-read token must
+ // not be able to exhaust the pod).
+ maxConcurrentStreams: number
+ maxStreamsPerRun: number
+ // Bearer token gating /_metrics when set. Deployments scrape metrics in-cluster via
+ // annotation-based Prometheus, which sends no auth header, so this stays optional and the
+ // route stays open for that scrape; external exposure is blocked at the ingress instead.
+ metricsToken: string
+ port: number
+ host: string
+ shutdownGraceMs: number
+ shutdownPrestopDelayMs: number
+}
+
+// Replace every literal two-character sequence `\n` (backslash + n, as stored
+// in environment variables) with a real newline (0x0A), so the PEM can be
+// parsed by importSPKI. Must run before any call to importSPKI.
+export function normalizePemKey(raw: string): string {
+ return raw.replace(/\\n/g, '\n')
+}
+
+function parseCorsOrigins(raw: string): Set<string> {
+ if (!raw.trim()) {
+ return new Set()
+ }
+ return new Set(
+ raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ )
+}
+
+function requireEnv(name: KnownEnvKey, isProd: boolean): string {
+ const value = getEnv(name)
+ if (!value) {
+ if (isProd) {
+ logger.error('config:missing_required_env', { name })
+ process.exit(1)
+ }
+ return ''
+ }
+ return value
+}
+
+export function loadConfig(): Config {
+ const isProd = getEnv('NODE_ENV') === 'production'
+
+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport
+ const redisUrl = getEnv('REDIS_URL') ?? (isProd ? requireEnv('REDIS_URL', true) : 'redis://localhost:6379')
+
+ // Primary key (required) plus an optional secondary trusted during a key rotation overlap.
+ const sandboxJwtPublicKeysPem = [
+ normalizePemKey(requireEnv('SANDBOX_JWT_PUBLIC_KEY', isProd)),
+ normalizePemKey(getEnv('SANDBOX_JWT_PUBLIC_KEY_SECONDARY') ?? ''),
+ ].filter((pem) => pem.length > 0)
+
+ const djangoCallbackBaseUrl = requireEnv('AGENT_PROXY_DJANGO_CALLBACK_URL', isProd)
+
+ const agentProxyCallbackSecret = getEnv('AGENT_PROXY_CALLBACK_SECRET') ?? ''
+
+ const maxConcurrentStreamsRaw = getEnv('AGENT_PROXY_MAX_CONCURRENT_STREAMS')
+ const maxConcurrentStreams = maxConcurrentStreamsRaw !== undefined ? parseInt(maxConcurrentStreamsRaw, 10) : 1000
+ if (Number.isNaN(maxConcurrentStreams) || maxConcurrentStreams <= 0) {
+ logger.error('config:invalid_max_concurrent_streams', { raw: maxConcurrentStreamsRaw })
+ process.exit(1)
+ }
+
+ const maxStreamsPerRunRaw = getEnv('AGENT_PROXY_MAX_STREAMS_PER_RUN')
+ const maxStreamsPerRun = maxStreamsPerRunRaw !== undefined ? parseInt(maxStreamsPerRunRaw, 10) : 25
+ if (Number.isNaN(maxStreamsPerRun) || maxStreamsPerRun <= 0) {
+ logger.error('config:invalid_max_streams_per_run', { raw: maxStreamsPerRunRaw })
+ process.exit(1)
+ }
+
+ const metricsToken = getEnv('AGENT_PROXY_METRICS_TOKEN') ?? ''
+
+ const corsOrigins = parseCorsOrigins(getEnv('TASKS_AGENT_PROXY_CORS_ORIGINS') ?? '')
+
+ const portRaw = getEnv('PORT')
+ const port = portRaw !== undefined ? parseInt(portRaw, 10) : 8003
+ if (Number.isNaN(port)) {
+ logger.error('config:invalid_port', { raw: portRaw })
+ process.exit(1)
+ }
+
+ const host = getEnv('HOST') ?? '0.0.0.0'
+
+ const graceRaw = getEnv('SHUTDOWN_GRACE_MS')
+ const shutdownGraceMs = graceRaw !== undefined ? parseInt(graceRaw, 10) : 300_000
+ const prestopRaw = getEnv('SHUTDOWN_PRESTOP_DELAY_MS')
+ const shutdownPrestopDelayMs = prestopRaw !== undefined ? parseInt(prestopRaw, 10) : 0
+
+ return {
+ redisUrl,
+ sandboxJwtPublicKeysPem,
+ corsOrigins,
+ djangoCallbackBaseUrl,
+ agentProxyCallbackSecret,
+ maxConcurrentStreams,
+ maxStreamsPerRun,
+ metricsToken,
+ port,
+ host,
+ shutdownGraceMs,
+ shutdownPrestopDelayMs,
+ }
+}
diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.ts
new file mode 100644
index 000000000000..11a86ef62adf
--- /dev/null
+++ b/services/agent-proxy/src/lib/constants.ts
@@ -0,0 +1,100 @@
+// Wire-protocol constants for the agent-proxy Redis stream plane.
+//
+// Every value here must stay byte-identical to the Python implementation in
+// products/tasks/backend/stream/redis_stream.py and
+// products/tasks/backend/services/sandbox_config.py — Django and this Node
+// service share the SAME Redis stream during the cutover window.
+
+// SANDBOX_TTL_SECONDS from sandbox_config.py (production value only; the TEST
+// branch short-circuits to 15 min but Node never runs in Django TEST mode).
+export const STREAM_TTL_SECONDS = 6 * 60 * 60 // 21600
+
+// TTL for last-seq and completed keys = SANDBOX_TTL_SECONDS + 1 hour buffer
+// (mirrors SANDBOX_EVENT_INGEST_TOKEN_TTL in connection_token.py).
+export const SEQUENCE_TTL_SECONDS = STREAM_TTL_SECONDS + 3600 // 25200
+
+// Redis XADD MAXLEN ~ (approximate trim, not exact).
+export const STREAM_MAX_LENGTH = 20_000
+
+// XREAD tuning
+export const READ_COUNT = 16
+export const BLOCK_MS = 100
+
+// wait_for_stream linear backoff (mirrors Python constants, converted to ms)
+export const WAIT_INITIAL_DELAY_MS = 50
+export const WAIT_DELAY_INCREMENT_MS = 150
+export const WAIT_MAX_DELAY_MS = 2_000
+export const WAIT_TIMEOUT_MS = 300_000
+
+// Idle threshold before emitting a keepalive SSE event
+export const KEEPALIVE_INTERVAL_MS = 20_000
+
+// Redis SET NX EX throttle window for the Temporal heartbeat callback (seconds)
+export const HEARTBEAT_THROTTLE_SECONDS = 30
+
+// Redis key prefix (byte-identical to TASK_RUN_STREAM_PREFIX in Python)
+export const STREAM_PREFIX = 'task-run-stream:'
+
+// Redis key builder functions (byte-identical to Python get_task_run_stream_*_key)
+
+export function getStreamKey(runId: string): string {
+ return `${STREAM_PREFIX}${runId}`
+}
+
+export function getSequenceKey(streamKey: string): string {
+ return `${streamKey}:last-seq`
+}
+
+export function getCompletedKey(streamKey: string): string {
+ return `${streamKey}:completed`
+}
+
+export function getAgentActiveKey(streamKey: string): string {
+ return `${streamKey}:ingest-agent-active`
+}
+
+export function getHeartbeatKey(streamKey: string): string {
+ return `${streamKey}:ingest-heartbeat`
+}
+
+// Sentinel factory helpers (values must match Python's json.dumps output)
+
+export function makeCompleteSentinel(): Record<string, string> {
+ return { type: 'STREAM_STATUS', status: 'complete' }
+}
+
+export function makeErrorSentinel(error: string): Record<string, string> {
+ return { type: 'STREAM_STATUS', status: 'error', error: error.slice(0, 500) }
+}
+
+// Control type used in the NDJSON completion line from the sandbox ingest client
+export const STREAM_COMPLETE_CONTROL_TYPE = '_posthog/stream_complete'
+
+// NDJSON ingest byte limits (byte-identical to Python event_ingest.py)
+export const MAX_EVENT_LINE_BYTES = 1_000_000
+export const MAX_REQUEST_BYTES = 5_000_000
+export const MAX_EVENTS_PER_REQUEST = 1_000
+
+// CORS headers (must match the Python ASGI middleware values exactly)
+export const CORS_ALLOW_METHODS = 'GET, POST, OPTIONS'
+export const CORS_ALLOW_HEADERS =
+ 'authorization, last-event-id, content-type, accept, x-csrftoken, x-posthog-session-id'
+export const CORS_MAX_AGE = '600'
+
+// JWT audience strings (must match Python validate_* helpers)
+export const STREAM_READ_AUDIENCE = 'posthog:stream_read'
+export const SANDBOX_EVENT_INGEST_AUDIENCE = 'posthog:sandbox_event_ingest'
+
+// SSE event names (keepalive and terminal events carry a named "event:" line;
+// normal stream events do not — they carry only "id:" and "data:").
+export const SSE_EVENT_KEEPALIVE = 'keepalive'
+export const SSE_EVENT_STREAM_END = 'stream-end'
+export const SSE_EVENT_ERROR = 'error'
+
+// SSE payload shapes (byte-identical to Python format_sse_event call sites)
+export const SSE_PAYLOAD_KEEPALIVE: Record<string, string> = { type: 'keepalive' }
+export const SSE_PAYLOAD_STREAM_END: Record<string, string> = { status: 'complete' }
+
+export function makeSseErrorPayload(error: string): Record<string, string> {
+ return { error }
+}
diff --git a/services/agent-proxy/src/lib/env.ts b/services/agent-proxy/src/lib/env.ts
new file mode 100644
index 000000000000..6287761f8a3e
--- /dev/null
+++ b/services/agent-proxy/src/lib/env.ts
@@ -0,0 +1,27 @@
+// Typed accessor for process.env in the agent-proxy service.
+//
+// KnownEnvKey is an exhaustive union of every environment variable the service
+// reads. Callers use getEnv() instead of process.env[] directly so typos in
+// key names are caught at compile time rather than silently returning undefined
+// at runtime.
+
+export type KnownEnvKey =
+ | 'REDIS_URL'
+ | 'SANDBOX_JWT_PUBLIC_KEY'
+ | 'SANDBOX_JWT_PUBLIC_KEY_SECONDARY'
+ | 'TASKS_AGENT_PROXY_CORS_ORIGINS'
+ | 'AGENT_PROXY_DJANGO_CALLBACK_URL'
+ | 'AGENT_PROXY_CALLBACK_SECRET'
+ | 'AGENT_PROXY_MAX_CONCURRENT_STREAMS'
+ | 'AGENT_PROXY_MAX_STREAMS_PER_RUN'
+ | 'AGENT_PROXY_METRICS_TOKEN'
+ | 'PORT'
+ | 'HOST'
+ | 'SHUTDOWN_GRACE_MS'
+ | 'SHUTDOWN_PRESTOP_DELAY_MS'
+ | 'NODE_ENV'
+ | 'AGENT_PROXY_LOG_LEVEL'
+
+export function getEnv(key: KnownEnvKey): string | undefined {
+ return process.env[key]
+}
diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.ts
new file mode 100644
index 000000000000..499dce1c1534
--- /dev/null
+++ b/services/agent-proxy/src/lib/jwt.ts
@@ -0,0 +1,115 @@
+// JWT verification for the agent-proxy service.
+//
+// Verify-only: this service never signs tokens. The private key is never loaded.
+// Both legs (stream-read and sandbox event ingest) verify RS256 tokens against the
+// public keys from SANDBOX_JWT_PUBLIC_KEY plus the optional SANDBOX_JWT_PUBLIC_KEY_SECONDARY
+// (normalized in config.ts before reaching here).
+//
+// Zero-downtime key rotation: a token is verified against every configured public key in
+// turn and accepted if any one validates the signature. This mirrors Django's
+// SANDBOX_JWT_PRIVATE_KEY / _SECONDARY signing registry — during a rotation overlap the proxy
+// trusts both the old and the new key, so flipping Django's primary signing key never rejects
+// an in-flight token. jose ignores the token's kid for a concrete CryptoKey, so the keys are
+// simply tried in order; only a signature mismatch advances to the next key (expiry, wrong
+// audience and malformed claims are key-independent and fail fast).
+
+import { errors, importSPKI, jwtVerify, type JWTPayload } from 'jose'
+
+import { SANDBOX_EVENT_INGEST_AUDIENCE, STREAM_READ_AUDIENCE } from './constants.js'
+import type { SandboxEventIngestTokenPayload, StreamReadTokenPayload } from './types.js'
+
+// ---------------------------------------------------------------------------
+// Public key loading
+// ---------------------------------------------------------------------------
+
+// Call once at startup with config.sandboxJwtPublicKeysPem (already normalized): the primary
+// key first, then any rotation-secondary key. The returned CryptoKeys are cached by the caller
+// for the process lifetime.
+export async function loadPublicKeys(pemsRaw: string[]): Promise<CryptoKey[]> {
+ return Promise.all(pemsRaw.map((pem) => importSPKI(pem, 'RS256')))
+}
+
+// ---------------------------------------------------------------------------
+// Shared claim extraction
+// ---------------------------------------------------------------------------
+
+// Extract and validate the three required claims shared by both token types.
+// Throws a plain Error (mapped to 401 by the server) on any claim type violation.
+//
+// Validation mirrors the Python validate_* helpers exactly:
+// - run_id: must be a string
+// - task_id: must be a string
+// - team_id: must be an integer (Number.isInteger rejects floats, booleans,
+// strings, null — booleans fail because typeof true === 'boolean', not
+// 'number', so Number.isInteger(true) is false)
+function assertStreamClaims(payload: Record<string, unknown>): { runId: string; taskId: string; teamId: number } {
+ const runId = payload['run_id']
+ const taskId = payload['task_id']
+ const teamId = payload['team_id']
+
+ if (typeof runId !== 'string') {
+ throw new Error('Token has invalid claim: run_id must be a string')
+ }
+ if (typeof taskId !== 'string') {
+ throw new Error('Token has invalid claim: task_id must be a string')
+ }
+ if (!Number.isInteger(teamId)) {
+ throw new Error('Token has invalid claim: team_id must be an integer')
+ }
+
+ return { runId, taskId, teamId: teamId as number }
+}
+
+// Verify a token against every configured public key, returning the payload from the first key
+// whose signature validates. Only a signature mismatch advances to the next key; expiry, wrong
+// audience and malformed claims are key-independent and fail fast. This is what makes a
+// primary-key rotation zero-downtime.
+async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience: string): Promise<JWTPayload> {
+ let lastSignatureError: unknown
+ for (const key of publicKeys) {
+ try {
+ const { payload } = await jwtVerify(token, key, { algorithms: ['RS256'], audience })
+ return payload
+ } catch (err) {
+ if (err instanceof errors.JWSSignatureVerificationFailed) {
+ lastSignatureError = err
+ continue
+ }
+ throw err
+ }
+ }
+ throw lastSignatureError ?? new Error('Token signature verification failed: no public keys configured')
+}
+
+// ---------------------------------------------------------------------------
+// Stream-read token (GET /v1/runs/:run/stream leg)
+// ---------------------------------------------------------------------------
+
+// Audience: posthog:stream_read
+// Required claims: run_id (string), task_id (string), team_id (integer)
+// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)
+//
+// Throws jose error subtypes (JWTExpired, JWTInvalid, JWSSignatureVerificationFailed,
+// JWTClaimValidationFailed, etc.) on bad signature, wrong audience or expiry; throws
+// a plain Error on malformed claim types. The server maps all of these to 401.
+export async function validateStreamReadToken(token: string, publicKeys: CryptoKey[]): Promise<StreamReadTokenPayload> {
+ const payload = await verifyWithKeys(token, publicKeys, STREAM_READ_AUDIENCE)
+ return assertStreamClaims(payload as Record<string, unknown>)
+}
+
+// ---------------------------------------------------------------------------
+// Sandbox event ingest token (POST /v1/runs/:run/ingest leg)
+// ---------------------------------------------------------------------------
+
+// Audience: posthog:sandbox_event_ingest
+// Required claims: run_id (string), task_id (string), team_id (integer)
+// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)
+//
+// Same error semantics as validateStreamReadToken.
+export async function validateSandboxEventIngestToken(
+ token: string,
+ publicKeys: CryptoKey[]
+): Promise<SandboxEventIngestTokenPayload> {
+ const payload = await verifyWithKeys(token, publicKeys, SANDBOX_EVENT_INGEST_AUDIENCE)
+ return assertStreamClaims(payload as Record<string, unknown>)
+}
diff --git a/services/agent-proxy/src/lib/logging.ts b/services/agent-proxy/src/lib/logging.ts
new file mode 100644
index 000000000000..60544ce9992b
--- /dev/null
+++ b/services/agent-proxy/src/lib/logging.ts
@@ -0,0 +1,129 @@
+// Leveled logger + wide-event RequestLogger for the agent-proxy.
+//
+// Backed by pino, the PostHog Node house logger (see nodejs/src/utils/logger.ts).
+// The logger never constructs a pino transport: dev and prod both run the esbuild
+// bundle, and a transport would spawn a worker needing lib/worker.js + __dirname,
+// neither of which exists in a single-file ESM bundle. Instead:
+// - production: pino writes JSON with level NAMES (for log ingestion)
+// - dev: pino writes JSON with numeric levels; the `dev` npm script pipes it
+// through the pino-pretty CLI for readable, colorized output
+// - test: plain JSON (vitest does not pipe), no worker threads to leak
+//
+// Two complementary patterns:
+// 1. Leveled logger (logger.debug/info/warn/error), imported by every module;
+// emits one line per discrete event, keyed by `event`.
+// 2. RequestLogger, created once per HTTP request by the requestLog middleware;
+// accumulates fields via extend(); emitted as a single wide line at request
+// completion via logger.info('http.request', log.finish(status)).
+//
+// Level comes from AGENT_PROXY_LOG_LEVEL (debug|info|warn|error). When unset it
+// defaults by NODE_ENV: debug in local dev, info in production, warn under tests.
+
+import pino from 'pino'
+
+import { getEnv } from './env.js'
+
+type LogLevel = 'debug' | 'info' | 'warn' | 'error'
+
+function resolveLevel(): LogLevel {
+ const explicit = getEnv('AGENT_PROXY_LOG_LEVEL')?.toLowerCase()
+ if (explicit === 'debug' || explicit === 'info' || explicit === 'warn' || explicit === 'error') {
+ return explicit
+ }
+ switch (getEnv('NODE_ENV')) {
+ case 'production':
+ return 'info'
+ case 'test':
+ return 'warn'
+ default:
+ return 'debug'
+ }
+}
+
+const level = resolveLevel()
+
+// Plain pino with no transport, so the esbuild bundle stays worker-free. A
+// pino-pretty transport spawns a thread-stream worker that resolves
+// join(__dirname, 'lib', 'worker.js'), and __dirname does not exist in the
+// single-file ESM bundle that dev and prod both run. Pretty output in dev comes
+// from piping this JSON through the pino-pretty CLI in the `dev` script instead.
+//
+// Production emits the level NAME (for log ingestion, matching nodejs); dev and
+// test keep pino's numeric levels, which the pino-pretty CLI renders natively.
+const pinoOptions: pino.LoggerOptions = { level }
+if (getEnv('NODE_ENV') === 'production') {
+ pinoOptions.formatters = { level: (label) => ({ level: label }) }
+}
+const pinoLogger = pino(pinoOptions)
+
+export const logger = {
+ debug: (event: string, fields?: Record<string, unknown>): void => pinoLogger.debug({ event, ...fields }),
+ info: (event: string, fields?: Record<string, unknown>): void => pinoLogger.info({ event, ...fields }),
+ warn: (event: string, fields?: Record<string, unknown>): void => pinoLogger.warn({ event, ...fields }),
+ error: (event: string, fields?: Record<string, unknown>): void => pinoLogger.error({ event, ...fields }),
+}
+
+// ---------------------------------------------------------------------------
+// Wide-event request logger
+// ---------------------------------------------------------------------------
+
+// Header names that must never appear in logs — values replaced with '[REDACTED]'.
+// x-csrftoken and x-posthog-session-id carry per-user browser tokens that api.stream
+// sends on every request, so they are redacted alongside the standard auth headers.
+export const SENSITIVE_HEADERS = new Set([
+ 'authorization',
+ 'cookie',
+ 'x-api-key',
+ 'x-csrftoken',
+ 'x-posthog-session-id',
+])
+
+// Return a copy of `headers` with sensitive values replaced by '[REDACTED]'.
+// Comparison is case-insensitive to handle both canonical and lowercased names.
+export function redactHeaders(headers: Record<string, string>): Record<string, string> {
+ const result: Record<string, string> = {}
+ for (const [key, value] of Object.entries(headers)) {
+ result[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? '[REDACTED]' : value
+ }
+ return result
+}
+
+// Accumulates per-request fields from all handler layers and emits a single
+// wide JSON log line at request completion.
+//
+// Usage in middleware:
+// const log = new RequestLogger()
+// c.set('requestLogger', log)
+// log.extend({ method, pathname, headers: redactHeaders(...) })
+// // in route handler:
+// log.extend({ run: claims.runId, project })
+// // in finally:
+// logger.info('http.request', log.finish(c.res.status))
+export class RequestLogger {
+ private readonly requestId: string
+ private readonly startTime: number
+ private data: Record<string, unknown> = {}
+
+ constructor() {
+ this.requestId = crypto.randomUUID().slice(0, 8)
+ this.startTime = Date.now()
+ this.data['requestId'] = this.requestId
+ }
+
+ // Merge additional fields into the accumulated record. Later calls win on
+ // key conflicts — route handlers overwrite middleware-set placeholders.
+ extend(data: Record<string, unknown>): void {
+ Object.assign(this.data, data)
+ }
+
+ // Return the accumulated record with status and durationMs appended.
+ // Pass directly to logger.info as the fields argument:
+ // logger.info('http.request', log.finish(c.res.status))
+ finish(status: number): Record<string, unknown> {
+ return {
+ ...this.data,
+ status,
+ durationMs: Date.now() - this.startTime,
+ }
+ }
+}
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
new file mode 100644
index 000000000000..8a74da5eac76
--- /dev/null
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -0,0 +1,534 @@
+// Redis stream read/write plane for task-run event streaming.
+//
+// Wire protocol is byte-identical to the Python implementation in
+// products/tasks/backend/stream/redis_stream.py — Django and this Node
+// service share the SAME Redis stream during the cutover window.
+// Any change to key names, TTLs, field names, or sentinel shapes will
+// corrupt live runs.
+
+import type { Redis } from 'ioredis'
+
+import {
+ BLOCK_MS,
+ READ_COUNT,
+ SEQUENCE_TTL_SECONDS,
+ STREAM_MAX_LENGTH,
+ STREAM_PREFIX,
+ STREAM_TTL_SECONDS,
+ WAIT_DELAY_INCREMENT_MS,
+ WAIT_INITIAL_DELAY_MS,
+ WAIT_MAX_DELAY_MS,
+ WAIT_TIMEOUT_MS,
+} from './constants.js'
+import type { ReadStreamEntriesOptions, ResumeGap, StreamEntryOrKeepalive } from './types.js'
+import {
+ TaskRunStreamAlreadyCompleted,
+ TaskRunStreamCompletionSequenceMismatch,
+ TaskRunStreamError,
+ TaskRunStreamSequenceGap,
+} from './types.js'
+
+// ---------------------------------------------------------------------------
+// Key helpers — byte-identical to Python get_task_run_stream_*_key
+// ---------------------------------------------------------------------------
+
+export function getStreamKey(runId: string): string {
+ return `${STREAM_PREFIX}${runId}`
+}
+
+export function getSequenceKey(streamKey: string): string {
+ return `${streamKey}:last-seq`
+}
+
+export function getCompletedKey(streamKey: string): string {
+ return `${streamKey}:completed`
+}
+
+export function getAgentActiveKey(streamKey: string): string {
+ return `${streamKey}:ingest-agent-active`
+}
+
+export function getHeartbeatKey(streamKey: string): string {
+ return `${streamKey}:ingest-heartbeat`
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+function normalizeStreamId(id: unknown): string {
+ if (typeof id === 'string') {
+ return id
+ }
+ if (Buffer.isBuffer(id)) {
+ return id.toString('utf8')
+ }
+ return String(id)
+}
+
+function normalizeRedisInt(value: string | Buffer | null | undefined): number {
+ if (value == null) {
+ return 0
+ }
+ const str = Buffer.isBuffer(value) ? value.toString('utf8') : String(value)
+ const n = parseInt(str, 10)
+ return Number.isNaN(n) ? 0 : n
+}
+
+// Parse a Redis stream ID "<ms>-<seq>" into a comparable [ms, seq] tuple.
+// On any parse failure returns [0, 0] (matches Python _stream_id_sort_key).
+function streamIdSortKey(id: string): [number, number] {
+ const dashIndex = id.indexOf('-')
+ if (dashIndex === -1) {
+ const ms = parseInt(id, 10)
+ return Number.isNaN(ms) ? [0, 0] : [ms, 0]
+ }
+ const msPart = id.slice(0, dashIndex)
+ const seqPart = id.slice(dashIndex + 1)
+ const ms = parseInt(msPart, 10)
+ const seq = seqPart === '' ? 0 : parseInt(seqPart, 10)
+ if (Number.isNaN(ms) || Number.isNaN(seq)) {
+ return [0, 0]
+ }
+ return [ms, seq]
+}
+
+function streamIdLessThan(a: string, b: string): boolean {
+ const [aMs, aSeq] = streamIdSortKey(a)
+ const [bMs, bSeq] = streamIdSortKey(b)
+ return aMs < bMs || (aMs === bMs && aSeq < bSeq)
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+// ---------------------------------------------------------------------------
+// TaskRunRedisStream
+// ---------------------------------------------------------------------------
+
+// Maximum number of WATCH/MULTI retry iterations before giving up.
+// Python's while True retries indefinitely, but unbounded loops are
+// unsafe in Node. 100 iterations is far beyond what real contention
+// requires — if a slot is genuinely that contested something is wrong.
+const MAX_WATCH_RETRIES = 100
+
+export class TaskRunRedisStream {
+ private readonly streamKey: string
+ private readonly redis: Redis
+ private readonly timeout: number
+ private readonly sequenceTimeout: number
+ private readonly maxLength: number
+
+ constructor(
+ streamKey: string,
+ redis: Redis,
+ opts?: {
+ timeout?: number
+ maxLength?: number
+ }
+ ) {
+ this.streamKey = streamKey
+ this.redis = redis
+ this.timeout = opts?.timeout ?? STREAM_TTL_SECONDS
+ // sequence key TTL must be at least timeout + SEQUENCE_TTL_SECONDS
+ this.sequenceTimeout = Math.max(this.timeout, SEQUENCE_TTL_SECONDS)
+ this.maxLength = opts?.maxLength ?? STREAM_MAX_LENGTH
+ }
+
+ // SET EXPIRE on the stream key; does not create it.
+ async initialize(): Promise<void> {
+ await this.redis.expire(this.streamKey, this.timeout)
+ }
+
+ // EXISTS stream_key -> bool
+ async exists(): Promise<boolean> {
+ const count = await this.redis.exists(this.streamKey)
+ return count > 0
+ }
+
+ // Linear backoff poll: initial 50ms, +150ms/step, cap 2000ms, timeout 120s.
+ // Returns true if stream exists, false on timeout.
+ async waitForStream(): Promise<boolean> {
+ let delay = WAIT_INITIAL_DELAY_MS
+ const start = Date.now()
+
+ while (true) {
+ const elapsed = Date.now() - start
+ if (elapsed >= WAIT_TIMEOUT_MS) {
+ return false
+ }
+
+ if (await this.exists()) {
+ return true
+ }
+
+ await sleep(delay)
+ delay = Math.min(delay + WAIT_DELAY_INCREMENT_MS, WAIT_MAX_DELAY_MS)
+ }
+ }
+
+ // XREVRANGE stream_key + - COUNT 1 -> string | null
+ async getLatestStreamId(): Promise<string | null> {
+ const messages = await this.redis.xrevrange(this.streamKey, '+', '-', 'COUNT', 1)
+ if (!messages || messages.length === 0) {
+ return null
+ }
+ const [streamId] = messages[0]
+ return normalizeStreamId(streamId)
+ }
+
+ // XRANGE stream_key - + COUNT 1 -> string | null
+ async getFirstStreamId(): Promise<string | null> {
+ const messages = await this.redis.xrange(this.streamKey, '-', '+', 'COUNT', 1)
+ if (!messages || messages.length === 0) {
+ return null
+ }
+ const [streamId] = messages[0]
+ return normalizeStreamId(streamId)
+ }
+
+ // XLEN -> number
+ async getLength(): Promise<number> {
+ return this.redis.xlen(this.streamKey)
+ }
+
+ // False if lastEventId in ('', '0'). False if stream empty.
+ // True if streamIdSortKey(lastEventId) < streamIdSortKey(firstId).
+ async resumePointTrimmed(lastEventId: string): Promise<boolean> {
+ if (lastEventId === '' || lastEventId === '0') {
+ return false
+ }
+ const firstId = await this.getFirstStreamId()
+ if (firstId === null) {
+ return false
+ }
+ return streamIdLessThan(lastEventId, firstId)
+ }
+
+ // None for startId in ('0','0-0','$',''). None if stream empty.
+ // ResumeGap if startId < firstId.
+ async detectResumeGap(startId: string): Promise<ResumeGap | null> {
+ if (startId === '0' || startId === '0-0' || startId === '$' || startId === '') {
+ return null
+ }
+ const firstId = await this.getFirstStreamId()
+ if (firstId === null) {
+ return null
+ }
+ if (streamIdLessThan(startId, firstId)) {
+ return { requestedId: startId, oldestAvailableId: firstId }
+ }
+ return null
+ }
+
+ // Async generator: yields [streamId, data] tuples or null (keepalive signal).
+ //
+ // Advances currentId per entry. XREAD block=100ms count=16.
+ // On STREAM_STATUS complete: return (generator ends, sentinel not yielded).
+ // On STREAM_STATUS error: throw TaskRunStreamError.
+ // On idle >= keepaliveIntervalMs: yield null and reset idle timer.
+ // On elapsed > timeout: throw TaskRunStreamError('Stream timeout...').
+ // Redis errors mapped to TaskRunStreamError substrings matching Python.
+ async *readStreamEntries(opts: ReadStreamEntriesOptions = {}): AsyncGenerator<StreamEntryOrKeepalive> {
+ const startId = opts.startId ?? '0'
+ const blockMs = opts.blockMs ?? BLOCK_MS
+ const count = opts.count ?? READ_COUNT
+ const keepaliveIntervalMs = opts.keepaliveIntervalMs ?? null
+ // Use a dedicated connection for blocking reads when the caller provides
+ // one, so that XREAD BLOCK calls don't queue behind ingest XADD writes
+ // on the shared client.
+ const xreadClient = opts.blockingRedis ?? this.redis
+
+ let currentId = startId
+ const startTime = Date.now()
+ let lastYieldTime = startTime
+
+ while (true) {
+ const now = Date.now()
+ if (now - startTime > this.timeout * 1000) {
+ throw new TaskRunStreamError('Stream timeout — task run took too long')
+ }
+
+ let messages: Array<[string, Array<[string, string[]]>]> | null = null
+ try {
+ // ioredis XREAD returns: Array<[streamName, Array<[id, fields]>]>
+ // fields is a flat array: [key1, val1, key2, val2, ...]
+ const raw = await xreadClient.xread(
+ 'COUNT',
+ count,
+ 'BLOCK',
+ blockMs,
+ 'STREAMS',
+ this.streamKey,
+ currentId
+ )
+ messages = raw as typeof messages
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err)
+ if (
+ msg.includes('ECONNREFUSED') ||
+ msg.includes('ECONNRESET') ||
+ msg.includes('Connection is closed')
+ ) {
+ throw new TaskRunStreamError('Connection lost to task run stream')
+ }
+ if (msg.includes('ETIMEDOUT') || msg.includes('timed out')) {
+ throw new TaskRunStreamError('Stream read timeout')
+ }
+ throw new TaskRunStreamError('Stream read error')
+ }
+
+ // TypeScript 6 incorrectly narrows `messages` to `never` inside an
+ // async generator when the catch block always throws — false positive.
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error TS6 async-generator narrowing false positive
+ if (!messages || messages.length === 0) {
+ const idleMs = Date.now() - lastYieldTime
+ if (keepaliveIntervalMs !== null && idleMs >= keepaliveIntervalMs) {
+ lastYieldTime = Date.now()
+ yield null
+ }
+ continue
+ }
+
+ // @ts-expect-error TS6 async-generator narrowing false positive
+ for (const [, streamMessages] of messages) {
+ for (const [streamId, fields] of streamMessages) {
+ const normalizedId = normalizeStreamId(streamId)
+ currentId = normalizedId
+
+ // fields is a flat array [key1, val1, key2, val2, ...]
+ // Find the 'data' field value.
+ let rawData = ''
+ for (let i = 0; i < fields.length - 1; i += 2) {
+ if (fields[i] === 'data') {
+ rawData = fields[i + 1] ?? ''
+ break
+ }
+ }
+
+ let data: Record<string, unknown>
+ try {
+ data = JSON.parse(rawData) as Record<string, unknown>
+ } catch {
+ // Skip unparseable entries rather than crashing the stream.
+ continue
+ }
+
+ if (data['type'] === 'STREAM_STATUS') {
+ const status = data['status']
+ if (status === 'complete') {
+ return
+ } else if (status === 'error') {
+ throw new TaskRunStreamError(
+ typeof data['error'] === 'string' ? data['error'] : 'Unknown stream error'
+ )
+ }
+ } else {
+ lastYieldTime = Date.now()
+ yield [normalizedId, data]
+ }
+ }
+ }
+ }
+ }
+
+ // XADD + EXPIRE; no sequence check. Returns Redis stream ID string.
+ // Refreshes TTL on every write (sliding window).
+ async writeEvent(event: Record<string, unknown>): Promise<string> {
+ const raw = JSON.stringify(event)
+ const streamId = await this.redis.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
+ await this.redis.expire(this.streamKey, this.timeout)
+ return normalizeStreamId(streamId)
+ }
+
+ // GET last-seq; if result is not null EXPIRE it (sliding TTL). Returns int (0 if absent).
+ async getLastSequence(): Promise<number> {
+ const sequenceKey = getSequenceKey(this.streamKey)
+ const raw = await this.redis.get(sequenceKey)
+ if (raw !== null) {
+ await this.redis.expire(sequenceKey, this.sequenceTimeout)
+ }
+ return normalizeRedisInt(raw)
+ }
+
+ // SET agent-active-key ('1'|'0') EX STREAM_TTL_SECONDS
+ async setAgentActive(active: boolean): Promise<void> {
+ await this.redis.set(getAgentActiveKey(this.streamKey), active ? '1' : '0', 'EX', this.timeout)
+ }
+
+ // GET agent-active-key; true iff value === '1'
+ async getAgentActive(): Promise<boolean> {
+ const raw = await this.redis.get(getAgentActiveKey(this.streamKey))
+ return raw === '1'
+ }
+
+ // SET heartbeat-key '1' EX throttleSeconds NX. True if claimed.
+ async claimAgentActiveHeartbeat(throttleSeconds: number): Promise<boolean> {
+ const result = await this.redis.set(getHeartbeatKey(this.streamKey), '1', 'EX', throttleSeconds, 'NX')
+ return result === 'OK'
+ }
+
+ // WATCH/MULTI optimistic retry loop (never the TEST shortcut).
+ // Returns stream ID string on accept, null on duplicate.
+ // Throws TaskRunStreamSequenceGap, TaskRunStreamAlreadyCompleted.
+ //
+ // Sequences start at 1; sequence 0 is the initial sentinel treated as accepted.
+ // seq == last+1 -> accept (XADD, set last-seq, refresh TTLs, return stream ID)
+ // seq <= last -> duplicate (return null)
+ // seq > last+1 -> TaskRunStreamSequenceGap
+ // completed key present -> TaskRunStreamAlreadyCompleted
+ async writeEventWithSequence(event: Record<string, unknown>, sequence: number): Promise<string | null> {
+ const sequenceKey = getSequenceKey(this.streamKey)
+ const completedKey = getCompletedKey(this.streamKey)
+ const raw = JSON.stringify(event)
+
+ for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
+ await this.redis.watch(sequenceKey, completedKey)
+
+ const lastSeqRaw = await this.redis.get(sequenceKey)
+ const lastSequence = normalizeRedisInt(lastSeqRaw)
+ const completedExists = (await this.redis.exists(completedKey)) > 0
+
+ if (completedExists) {
+ await this.redis.unwatch()
+ throw new TaskRunStreamAlreadyCompleted(lastSequence)
+ }
+
+ if (sequence <= lastSequence) {
+ await this.redis.unwatch()
+ return null
+ }
+
+ if (sequence !== lastSequence + 1) {
+ await this.redis.unwatch()
+ throw new TaskRunStreamSequenceGap(lastSequence + 1, sequence, lastSequence)
+ }
+
+ const pipeline = this.redis.multi()
+ pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
+ pipeline.expire(this.streamKey, this.timeout)
+ pipeline.set(sequenceKey, String(sequence), 'EX', this.sequenceTimeout)
+
+ const results = await pipeline.exec()
+ if (results === null) {
+ // WATCH conflict — retry
+ continue
+ }
+
+ // results[0] is [error, streamId]
+ const [xaddErr, streamId] = results[0] ?? [null, null]
+ if (xaddErr) {
+ throw new TaskRunStreamError(`XADD failed: ${String(xaddErr)}`)
+ }
+ return normalizeStreamId(streamId)
+ }
+
+ throw new TaskRunStreamError('writeEventWithSequence: too many WATCH conflicts')
+ }
+
+ // WATCH/MULTI on completed_key. Idempotent: returns if already completed.
+ async markComplete(): Promise<void> {
+ const completedKey = getCompletedKey(this.streamKey)
+ const raw = JSON.stringify({ type: 'STREAM_STATUS', status: 'complete' })
+
+ for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
+ await this.redis.watch(completedKey)
+
+ const completedExists = (await this.redis.exists(completedKey)) > 0
+ if (completedExists) {
+ await this.redis.unwatch()
+ return
+ }
+
+ const pipeline = this.redis.multi()
+ pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
+ pipeline.expire(this.streamKey, this.timeout)
+ pipeline.set(completedKey, '1', 'EX', this.sequenceTimeout)
+
+ const results = await pipeline.exec()
+ if (results === null) {
+ // WATCH conflict — retry
+ continue
+ }
+ return
+ }
+
+ throw new TaskRunStreamError('markComplete: too many WATCH conflicts')
+ }
+
+ // WATCH/MULTI on sequence_key + completed_key.
+ // Throws TaskRunStreamCompletionSequenceMismatch if last_seq != finalSequence.
+ // EXPIRE sequence_key only if it existed before (lastSeqRaw !== null).
+ async markCompleteAfterSequence(finalSequence: number): Promise<void> {
+ const sequenceKey = getSequenceKey(this.streamKey)
+ const completedKey = getCompletedKey(this.streamKey)
+ const raw = JSON.stringify({ type: 'STREAM_STATUS', status: 'complete' })
+
+ for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
+ await this.redis.watch(sequenceKey, completedKey)
+
+ const lastSeqRaw = await this.redis.get(sequenceKey)
+ const lastSequence = normalizeRedisInt(lastSeqRaw)
+ const completedExists = (await this.redis.exists(completedKey)) > 0
+
+ if (completedExists) {
+ await this.redis.unwatch()
+ return
+ }
+
+ if (lastSequence !== finalSequence) {
+ await this.redis.unwatch()
+ throw new TaskRunStreamCompletionSequenceMismatch(finalSequence, lastSequence)
+ }
+
+ const seqKeyExisted = lastSeqRaw !== null
+
+ const pipeline = this.redis.multi()
+ pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
+ pipeline.expire(this.streamKey, this.timeout)
+ // Only EXPIRE the sequence key if it existed before the transaction;
+ // matches Python: `if last_sequence_raw is not None: pipe.expire(sequence_key, ...)`
+ if (seqKeyExisted) {
+ pipeline.expire(sequenceKey, this.sequenceTimeout)
+ }
+ pipeline.set(completedKey, '1', 'EX', this.sequenceTimeout)
+
+ const results = await pipeline.exec()
+ if (results === null) {
+ // WATCH conflict — retry
+ continue
+ }
+ return
+ }
+
+ throw new TaskRunStreamError('markCompleteAfterSequence: too many WATCH conflicts')
+ }
+
+ // No WATCH/MULTI. XADD error sentinel, truncated to 500 chars.
+ async markError(error: string): Promise<void> {
+ await this.writeEvent({ type: 'STREAM_STATUS', status: 'error', error: error.slice(0, 500) })
+ }
+
+ // DEL all five keys atomically. Returns true if at least one key was deleted.
+ // Catches all exceptions; returns false on failure.
+ async deleteStream(): Promise<boolean> {
+ try {
+ const sequenceKey = getSequenceKey(this.streamKey)
+ const completedKey = getCompletedKey(this.streamKey)
+ const agentActiveKey = getAgentActiveKey(this.streamKey)
+ const heartbeatKey = getHeartbeatKey(this.streamKey)
+ const deleted = await this.redis.del(
+ this.streamKey,
+ sequenceKey,
+ completedKey,
+ agentActiveKey,
+ heartbeatKey
+ )
+ return deleted > 0
+ } catch {
+ return false
+ }
+ }
+}
diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.ts
new file mode 100644
index 000000000000..52e702b44b25
--- /dev/null
+++ b/services/agent-proxy/src/lib/side-effects.ts
@@ -0,0 +1,165 @@
+// Side-effect dispatch for the ingest handler.
+//
+// After each accepted ingest event the handler calls heartbeatWorkflowIfNeeded.
+// Redis state mutations (setAgentActive, claimAgentActiveHeartbeat) are awaited
+// because they gate the callback decision. The Django HTTP callback is
+// fire-and-forget: the fetch result is consumed in a detached promise with
+// error logging so failures never propagate into the ingest response.
+//
+// The Node service stays a pure streaming plane — Temporal signals and Celery
+// push notifications go through a single internal Django endpoint. Django
+// decides whether a run is interactive; Node always calls the callback and lets
+// Django branch on mode.
+
+import type { Config } from './config.js'
+import { HEARTBEAT_THROTTLE_SECONDS } from './constants.js'
+import { logger } from './logging.js'
+import type { TaskRunRedisStream } from './redis-stream.js'
+import type { SideEffectKind } from './types.js'
+
+// ACP event field values (byte-identical to ee/hogai/sandbox/types.py)
+const ACP_NOTIFICATION_TYPE = 'notification'
+const TURN_COMPLETE_METHOD = '_posthog/turn_complete'
+const STOP_REASON_END_TURN = 'end_turn'
+const ACP_METHOD_SESSION_UPDATE = 'session/update'
+
+// isTurnComplete mirrors ee/hogai/sandbox/types.py:is_turn_complete exactly.
+// Matches both the raw ACP prompt response (result.stopReason == "end_turn")
+// and the synthetic _posthog/turn_complete notification.
+export function isTurnComplete(event: Record<string, unknown>): boolean {
+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {
+ return false
+ }
+ const notification = event['notification']
+ if (typeof notification !== 'object' || notification === null) {
+ return false
+ }
+ const notif = notification as Record<string, unknown>
+ if (notif['method'] === TURN_COMPLETE_METHOD) {
+ return true
+ }
+ const result = notif['result']
+ return (
+ typeof result === 'object' &&
+ result !== null &&
+ (result as Record<string, unknown>)['stopReason'] === STOP_REASON_END_TURN
+ )
+}
+
+// isSessionUpdate mirrors event_ingest.py:_is_session_update exactly.
+export function isSessionUpdate(event: Record<string, unknown>): boolean {
+ if (event['type'] !== ACP_NOTIFICATION_TYPE) {
+ return false
+ }
+ const notification = event['notification']
+ if (typeof notification !== 'object' || notification === null) {
+ return false
+ }
+ return (notification as Record<string, unknown>)['method'] === ACP_METHOD_SESSION_UPDATE
+}
+
+// fireCallback issues a best-effort POST to the Django agent-proxy callback.
+// The call is fire-and-forget: the promise is not returned to the caller.
+// Any failure is logged but never thrown into the ingest path.
+//
+// The original sandbox_event_ingest JWT is forwarded as the Authorization
+// header so Django can re-validate it with validate_sandbox_event_ingest_token
+// (same RS256 public key, same audience).
+function fireCallback(
+ runId: string,
+ kind: SideEffectKind,
+ agentActive: boolean,
+ taskId: string,
+ teamId: number,
+ originalToken: string,
+ config: Config
+): void {
+ if (!config.djangoCallbackBaseUrl) {
+ // Dev environment without AGENT_PROXY_DJANGO_CALLBACK_URL — skip silently.
+ return
+ }
+
+ const url = `${config.djangoCallbackBaseUrl}/internal/tasks/runs/${runId}/agent-proxy-callback/`
+ const body = JSON.stringify({ kind, agent_active: agentActive, task_id: taskId, team_id: teamId })
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${originalToken}`,
+ }
+ // Service-to-service secret proving this call came from the proxy, not directly from a sandbox
+ // (which also holds the ingest JWT). Django enforces it only when it has the same secret configured.
+ if (config.agentProxyCallbackSecret) {
+ headers['X-Agent-Proxy-Secret'] = config.agentProxyCallbackSecret
+ }
+
+ logger.debug('side_effect:fire', { run: runId, kind, agentActive })
+
+ // Detached promise — errors are swallowed and logged.
+ fetch(url, {
+ method: 'POST',
+ headers,
+ body,
+ // Node 18+ fetch doesn't expose a timeout option in the standard API;
+ // we rely on the OS TCP timeout (typically 2 min). The callback is
+ // best-effort so a slow/hanging response is acceptable.
+ })
+ .then((res) => {
+ if (!res.ok) {
+ logger.warn('side_effect:non_2xx', { run: runId, kind, status: res.status })
+ }
+ })
+ .catch((err: unknown) => {
+ const message = err instanceof Error ? err.message : String(err)
+ logger.error('side_effect:failed', { run: runId, kind, error: message })
+ })
+}
+
+// heartbeatWorkflowIfNeeded implements the side-effect decision from docs/DESIGN.md §2
+// and mirrors event_ingest.py:_heartbeat_workflow_if_needed exactly.
+//
+// Decision tree:
+// 1. isTurnComplete -> setAgentActive(false), fire awaiting_input callback, return.
+// 2. isSessionUpdate -> setAgentActive(true), set agentActive=true.
+// 3. else -> agentActive = getAgentActive().
+// 4. if !agentActive -> return.
+// 5. claimAgentActiveHeartbeat(30s) -> if throttled, return.
+// 6. fire heartbeat callback.
+//
+// Redis operations are awaited synchronously (they gate the callback decision).
+// The Django HTTP callback is fire-and-forget in both branches.
+export async function heartbeatWorkflowIfNeeded(
+ redisStream: TaskRunRedisStream,
+ runId: string,
+ event: Record<string, unknown>,
+ taskId: string,
+ teamId: number,
+ originalToken: string,
+ config: Config
+): Promise<void> {
+ if (isTurnComplete(event)) {
+ await redisStream.setAgentActive(false)
+ // Let Django decide whether the run is interactive; it will only
+ // dispatch the push notification for interactive mode runs.
+ fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config)
+ return
+ }
+
+ let agentActive: boolean
+ if (isSessionUpdate(event)) {
+ await redisStream.setAgentActive(true)
+ agentActive = true
+ } else {
+ agentActive = await redisStream.getAgentActive()
+ }
+
+ if (!agentActive) {
+ return
+ }
+
+ const claimed = await redisStream.claimAgentActiveHeartbeat(HEARTBEAT_THROTTLE_SECONDS)
+ if (!claimed) {
+ return
+ }
+
+ fireCallback(runId, 'heartbeat', true, taskId, teamId, originalToken, config)
+}
diff --git a/services/agent-proxy/src/lib/stream-capacity.ts b/services/agent-proxy/src/lib/stream-capacity.ts
new file mode 100644
index 000000000000..a16742d3e65c
--- /dev/null
+++ b/services/agent-proxy/src/lib/stream-capacity.ts
@@ -0,0 +1,50 @@
+// Per-pod concurrency guard for SSE stream connections.
+//
+// Every stream holds a dedicated blocking-read Redis connection for its whole
+// lifetime, so unbounded concurrent streams translate directly into Redis
+// connection exhaustion (maxclients) — and a single valid stream-read token is
+// enough to open arbitrarily many connections. Two caps bound the blast
+// radius: a pod-wide total, and a per-run fanout so one token cannot consume
+// the pod's whole budget. Rejected connections receive a 503 and come back
+// through the client's normal reconnect backoff.
+
+export type StreamRejectionReason = 'pod_capacity' | 'run_capacity'
+
+export class StreamCapacity {
+ private total = 0
+ private readonly byRun = new Map<string, number>()
+
+ constructor(
+ private readonly maxTotal: number,
+ private readonly maxPerRun: number
+ ) {}
+
+ /** Reserve a slot for runId. Returns the rejection reason, or null when acquired. */
+ tryAcquire(runId: string): StreamRejectionReason | null {
+ if (this.total >= this.maxTotal) {
+ return 'pod_capacity'
+ }
+ const runCount = this.byRun.get(runId) ?? 0
+ if (runCount >= this.maxPerRun) {
+ return 'run_capacity'
+ }
+ this.total += 1
+ this.byRun.set(runId, runCount + 1)
+ return null
+ }
+
+ /** Release a previously acquired slot. Must be called exactly once per successful tryAcquire. */
+ release(runId: string): void {
+ this.total = Math.max(0, this.total - 1)
+ const runCount = this.byRun.get(runId) ?? 0
+ if (runCount <= 1) {
+ this.byRun.delete(runId)
+ } else {
+ this.byRun.set(runId, runCount - 1)
+ }
+ }
+
+ get openTotal(): number {
+ return this.total
+ }
+}
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
new file mode 100644
index 000000000000..93c18513b809
--- /dev/null
+++ b/services/agent-proxy/src/lib/types.ts
@@ -0,0 +1,149 @@
+// Domain types, error classes and discriminated unions for the agent-proxy.
+// Shapes defined here must stay compatible with the Python counterparts in
+// products/tasks/backend/stream/redis_stream.py and
+// products/tasks/backend/proxy/event_ingest.py — both sides share the same
+// Redis stream and HTTP contracts.
+
+import type { Redis } from 'ioredis'
+
+// ---------------------------------------------------------------------------
+// Error classes
+// ---------------------------------------------------------------------------
+
+export class TaskRunStreamError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'TaskRunStreamError'
+ }
+}
+
+export class TaskRunStreamSequenceGap extends Error {
+ constructor(
+ public readonly expectedSequence: number,
+ public readonly receivedSequence: number,
+ public readonly lastAcceptedSeq: number
+ ) {
+ super(`Expected sequence ${expectedSequence}, got ${receivedSequence}`)
+ this.name = 'TaskRunStreamSequenceGap'
+ }
+}
+
+export class TaskRunStreamCompletionSequenceMismatch extends Error {
+ constructor(
+ public readonly finalSequence: number,
+ public readonly lastAcceptedSeq: number
+ ) {
+ super(`Cannot complete stream at sequence ${finalSequence}; last accepted sequence is ${lastAcceptedSeq}`)
+ this.name = 'TaskRunStreamCompletionSequenceMismatch'
+ }
+}
+
+export class TaskRunStreamAlreadyCompleted extends Error {
+ constructor(public readonly lastAcceptedSeq: number) {
+ super('Task run stream is already complete')
+ this.name = 'TaskRunStreamAlreadyCompleted'
+ }
+}
+
+export class EventIngestBadRequest extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'EventIngestBadRequest'
+ }
+}
+
+export class EventIngestPayloadTooLarge extends Error {
+ constructor(
+ message: string,
+ public lastAcceptedSeq: number = 0
+ ) {
+ super(message)
+ this.name = 'EventIngestPayloadTooLarge'
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Redis stream types
+// ---------------------------------------------------------------------------
+
+// Returned by detectResumeGap when the client's Last-Event-ID has been trimmed.
+// S3 hydration is out of scope; callers log and continue from oldestAvailableId.
+export interface ResumeGap {
+ requestedId: string
+ oldestAvailableId: string
+}
+
+// ---------------------------------------------------------------------------
+// JWT claim types
+// ---------------------------------------------------------------------------
+
+// Claims extracted from a posthog:stream_read JWT (GET /v1/runs/:run/stream leg)
+export interface StreamReadTokenPayload {
+ runId: string
+ taskId: string
+ teamId: number
+}
+
+// Claims extracted from a posthog:sandbox_event_ingest JWT (POST /v1/runs/:run/ingest leg)
+export interface SandboxEventIngestTokenPayload {
+ runId: string
+ taskId: string
+ teamId: number
+}
+
+// ---------------------------------------------------------------------------
+// SSE stream connection outcome (matches Python StreamConnectionOutcome values)
+// ---------------------------------------------------------------------------
+
+export type StreamConnectionOutcome = 'completed' | 'stream_error' | 'unavailable' | 'client_disconnect'
+
+// ---------------------------------------------------------------------------
+// Ingest HTTP response shape (200 OK body)
+// ---------------------------------------------------------------------------
+
+export interface EventIngestResult {
+ accepted: number
+ duplicate: number
+ last_accepted_seq: number
+}
+
+// ---------------------------------------------------------------------------
+// Parsed NDJSON line discriminated union
+// ---------------------------------------------------------------------------
+
+export interface IngestEventLine {
+ kind: 'event'
+ seq: number
+ event: Record<string, unknown>
+}
+
+export interface IngestCompleteLine {
+ kind: 'complete'
+ finalSeq: number
+}
+
+export type IngestLine = IngestEventLine | IngestCompleteLine
+
+// ---------------------------------------------------------------------------
+// Side-effect callback kind (matches Python callback contract in docs/DESIGN.md)
+// ---------------------------------------------------------------------------
+
+export type SideEffectKind = 'heartbeat' | 'awaiting_input'
+
+// ---------------------------------------------------------------------------
+// TaskRunRedisStream method interface
+// ---------------------------------------------------------------------------
+
+// Async generator element: either a [streamId, event] tuple or null (keepalive signal).
+export type StreamEntry = [string, Record<string, unknown>]
+export type StreamEntryOrKeepalive = StreamEntry | null
+
+export interface ReadStreamEntriesOptions {
+ startId?: string
+ blockMs?: number
+ count?: number
+ keepaliveIntervalMs?: number | null
+ // When provided, this connection is used for the blocking XREAD call instead
+ // of the class-level shared client — isolates blocking reads from ingest writes.
+ blockingRedis?: Redis
+}
diff --git a/services/agent-proxy/tests/README.md b/services/agent-proxy/tests/README.md
new file mode 100644
index 000000000000..68d9cb27be31
--- /dev/null
+++ b/services/agent-proxy/tests/README.md
@@ -0,0 +1,24 @@
+# Tests
+
+Unit tests for the agent-proxy service. The tree mirrors `src/` so a test sits at
+the same relative path as the module it covers:
+
+- `tests/hono/` — HTTP layer: app routes, middleware, SSE and ingest handlers, metrics
+- `tests/lib/` — domain utilities: Redis stream, JWT validation, constants
+
+Production code imports use the `@/` path alias (e.g. `@/lib/redis-stream.js`), so test
+files never reach back into `src/` with relative paths.
+
+## Setup
+
+`tests/setup.ts` is the global setup (wired via `vitest.config.mts`). It mocks
+`@/hono/metrics.js` so prom-client never registers duplicate metrics across suites.
+A test that needs the real implementation (see `tests/hono/metrics.test.ts`) pulls it
+in with `vi.importActual`.
+
+## Running
+
+```bash
+pnpm --filter @posthog/agent-proxy test # watch mode
+pnpm --filter @posthog/agent-proxy exec vitest run # single run
+```
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
new file mode 100644
index 000000000000..43cc91a8b8af
--- /dev/null
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -0,0 +1,1148 @@
+// Tests for ingest-handler.ts
+//
+// Coverage goals (mirrors products/tasks/backend/stream/tests/):
+// - NDJSON parsing across chunk boundaries
+// - Byte/line/count limits → 413 with last_accepted_seq
+// - Sequence gap + already-completed → 409
+// - Accepted/duplicate counting + last_accepted_seq tracking
+// - Completion line handling (happy path, mismatch, ordering errors)
+// - Side-effect triggering: turn-complete vs session/update vs throttled heartbeat
+// - Best-effort side effects: callback failure does not fail ingest
+//
+// Wire-protocol invariants tested:
+// - Stream key: "task-run-stream:{run_id}"
+// - Sequence numbers start at 1 (0 is the initial sentinel)
+// - Completion sentinel: {"type":"STREAM_STATUS","status":"complete"}
+// - Redis field name is "data"
+
+import type { Redis } from 'ioredis'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+import type { Config } from '@/lib/config.js'
+import {
+ MAX_EVENT_LINE_BYTES,
+ MAX_REQUEST_BYTES,
+ MAX_EVENTS_PER_REQUEST,
+ HEARTBEAT_THROTTLE_SECONDS,
+} from '@/lib/constants.js'
+import { TaskRunRedisStream, getStreamKey } from '@/lib/redis-stream.js'
+import { heartbeatWorkflowIfNeeded } from '@/lib/side-effects.js'
+import type { SandboxEventIngestTokenPayload } from '@/lib/types.js'
+
+// ---------------------------------------------------------------------------
+// Minimal in-memory Redis fake
+//
+// Implements: get, set, exists, del, expire, xadd, watch, unwatch, multi
+// Enough surface for TaskRunRedisStream.writeEventWithSequence,
+// getLastSequence, setAgentActive, getAgentActive, claimAgentActiveHeartbeat,
+// markCompleteAfterSequence, and deleteStream.
+// ---------------------------------------------------------------------------
+
+interface StreamEntry {
+ id: string
+ data: Record<string, string>
+}
+
+class FakeRedis {
+ private strings = new Map<string, { value: string; expireAt: number | null }>()
+ private streams = new Map<string, StreamEntry[]>()
+ private watchedKeys = new Set<string>()
+ private watchConflict = false
+ private seq = 0
+
+ // Allow tests to simulate a WATCH conflict once.
+ simulateWatchConflict(): void {
+ this.watchConflict = true
+ }
+
+ private nextStreamId(): string {
+ this.seq++
+ return `${Date.now()}-${this.seq}`
+ }
+
+ async get(key: string): Promise<string | null> {
+ const entry = this.strings.get(key)
+ if (!entry) {
+ return null
+ }
+ if (entry.expireAt !== null && Date.now() > entry.expireAt) {
+ this.strings.delete(key)
+ return null
+ }
+ return entry.value
+ }
+
+ async set(key: string, value: string, ...args: (string | number)[]): Promise<'OK'> {
+ let ttl: number | null = null
+ let nx = false
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]
+ if (typeof arg === 'string' && arg.toUpperCase() === 'EX') {
+ const raw = args[i + 1]
+ ttl = typeof raw === 'number' ? raw : parseInt(String(raw), 10)
+ i++
+ }
+ if (typeof arg === 'string' && arg.toUpperCase() === 'NX') {
+ nx = true
+ }
+ }
+ if (nx && this.strings.has(key)) {
+ const existing = this.strings.get(key)!
+ if (existing.expireAt === null || Date.now() <= existing.expireAt) {
+ return 'OK' as const // NX: don't overwrite — return 'OK' but value unchanged
+ // NOTE: real ioredis returns null on NX fail. We handle this below.
+ }
+ }
+ this.strings.set(key, {
+ value,
+ expireAt: ttl !== null ? Date.now() + ttl * 1000 : null,
+ })
+ return 'OK'
+ }
+
+ // Real ioredis returns null when SET NX fails. Override for that contract.
+ async setNX(key: string, value: string, ttl: number): Promise<string | null> {
+ const existing = this.strings.get(key)
+ if (existing && (existing.expireAt === null || Date.now() <= existing.expireAt)) {
+ return null
+ }
+ this.strings.set(key, { value, expireAt: Date.now() + ttl * 1000 })
+ return 'OK'
+ }
+
+ async exists(...keys: string[]): Promise<number> {
+ let count = 0
+ for (const key of keys) {
+ const entry = this.strings.get(key)
+ if (entry && (entry.expireAt === null || Date.now() <= entry.expireAt)) {
+ count++
+ }
+ }
+ return count
+ }
+
+ async expire(key: string, seconds: number): Promise<number> {
+ const entry = this.strings.get(key)
+ if (entry) {
+ entry.expireAt = Date.now() + seconds * 1000
+ }
+ return entry ? 1 : 0
+ }
+
+ async del(...keys: string[]): Promise<number> {
+ let deleted = 0
+ for (const key of keys) {
+ if (this.strings.delete(key)) {
+ deleted++
+ }
+ if (this.streams.delete(key)) {
+ deleted++
+ }
+ }
+ return deleted
+ }
+
+ async xadd(
+ key: string,
+ _maxlenToken: 'MAXLEN',
+ _approxToken: '~',
+ _maxLen: number,
+ _idSpec: '*',
+ ...fieldValues: string[]
+ ): Promise<string> {
+ const id = this.nextStreamId()
+ const data: Record<string, string> = {}
+ for (let i = 0; i + 1 < fieldValues.length; i += 2) {
+ data[fieldValues[i]!] = fieldValues[i + 1]!
+ }
+ const entries = this.streams.get(key) ?? []
+ entries.push({ id, data })
+ this.streams.set(key, entries)
+ return id
+ }
+
+ async xrange(key: string, _start = '-', _end = '+'): Promise<[string, Record<string, string>][]> {
+ const entries = this.streams.get(key) ?? []
+ return entries.map((e) => [e.id, e.data])
+ }
+
+ async watch(...keys: string[]): Promise<'OK'> {
+ for (const k of keys) {
+ this.watchedKeys.add(k)
+ }
+ return 'OK'
+ }
+
+ async unwatch(): Promise<'OK'> {
+ this.watchedKeys.clear()
+ return 'OK'
+ }
+
+ // Returns a fake pipeline (MULTI).
+ multi(): FakePipeline {
+ const conflict = this.watchConflict
+ this.watchConflict = false
+ return new FakePipeline(this, conflict)
+ }
+}
+
+// Rewrite `set` so NX behaviour is correct (returns null not 'OK' on failure).
+// We patch FakeRedis.set to correctly handle NX per ioredis contract.
+const _origSet = FakeRedis.prototype.set
+FakeRedis.prototype.set = async function (
+ this: FakeRedis,
+ key: string,
+ value: string,
+ ...args: (string | number)[]
+): Promise<'OK' | null> {
+ let nx = false
+ for (const arg of args) {
+ if (typeof arg === 'string' && arg.toUpperCase() === 'NX') {
+ nx = true
+ }
+ }
+ if (nx) {
+ const existing = await this.get(key)
+ if (existing !== null) {
+ // NX fail — don't overwrite, return null (ioredis contract)
+ return null as unknown as 'OK'
+ }
+ }
+ return _origSet.call(this, key, value, ...args)
+} as typeof FakeRedis.prototype.set
+
+class FakePipeline {
+ private ops: Array<() => Promise<[null, unknown]>> = []
+ private conflictOnExec: boolean
+
+ constructor(
+ private redis: FakeRedis,
+ conflict: boolean
+ ) {
+ this.conflictOnExec = conflict
+ }
+
+ xadd(
+ key: string,
+ maxlenToken: 'MAXLEN',
+ approxToken: '~',
+ maxLen: number,
+ idSpec: '*',
+ ...fieldValues: string[]
+ ): this {
+ this.ops.push(async () => {
+ const id = await this.redis.xadd(key, maxlenToken, approxToken, maxLen, idSpec, ...fieldValues)
+ return [null, id]
+ })
+ return this
+ }
+
+ set(key: string, value: string, ...args: (string | number)[]): this {
+ this.ops.push(async () => {
+ const result = await this.redis.set(key, value, ...args)
+ return [null, result]
+ })
+ return this
+ }
+
+ expire(key: string, seconds: number): this {
+ this.ops.push(async () => {
+ const result = await this.redis.expire(key, seconds)
+ return [null, result]
+ })
+ return this
+ }
+
+ async exec(): Promise<Array<[null, unknown]> | null> {
+ if (this.conflictOnExec) {
+ return null
+ }
+ const results: Array<[null, unknown]> = []
+ for (const op of this.ops) {
+ results.push(await op())
+ }
+ return results
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Test helpers
+// ---------------------------------------------------------------------------
+
+function makeFakeRedis(): FakeRedis {
+ return new FakeRedis()
+}
+
+function makeRedisStream(fakeRedis: FakeRedis, runId: string): TaskRunRedisStream {
+ return new TaskRunRedisStream(getStreamKey(runId), fakeRedis as unknown as Redis, { timeout: 60, maxLength: 20000 })
+}
+
+// Build a minimal Config with no Django callback URL so side-effect HTTP calls are skipped.
+function makeConfig(overrides?: Partial<Config>): Config {
+ return {
+ redisUrl: 'redis://localhost:6379',
+ sandboxJwtPublicKeysPem: [],
+ corsOrigins: new Set(),
+ djangoCallbackBaseUrl: '',
+ agentProxyCallbackSecret: '',
+ maxConcurrentStreams: 1000,
+ maxStreamsPerRun: 25,
+ metricsToken: '',
+ port: 8003,
+ host: '0.0.0.0',
+ shutdownGraceMs: 300_000,
+ shutdownPrestopDelayMs: 0,
+ ...overrides,
+ }
+}
+
+// Build claims for the given runId/taskId/teamId.
+function makeClaims(overrides?: Partial<SandboxEventIngestTokenPayload>): SandboxEventIngestTokenPayload {
+ return {
+ runId: 'run-123',
+ taskId: 'task-abc',
+ teamId: 42,
+ ...overrides,
+ }
+}
+
+// Build a ReadableStream body from an array of Uint8Array chunks.
+function makeChunkedBody(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
+ let idx = 0
+ return new ReadableStream({
+ pull(controller) {
+ const chunk = chunks[idx++]
+ if (chunk === undefined) {
+ controller.close()
+ return
+ }
+ controller.enqueue(chunk)
+ },
+ })
+}
+
+// Build a ReadableStream body from a plain string.
+function makeStringBody(text: string): ReadableStream<Uint8Array> {
+ const encoded = new TextEncoder().encode(text)
+ return makeChunkedBody([encoded])
+}
+
+// Import the private helpers by re-exporting a thin shim that calls them.
+// Because ingest-handler.ts doesn't export the inner loop helpers, we drive
+// the behavior through the exported handleIngest() function with a mocked Hono
+// Context, a mocked JWT validator, and a mocked run-exists check.
+//
+// We avoid unit-testing the private functions directly; instead we observe
+// their behavior via the public surface (handleIngest or the sub-module
+// heartbeatWorkflowIfNeeded exported from side-effects.ts).
+
+// Inline the re-exported NDJSON + Redis write helpers under test via the
+// ingestEventLines path driven through the public handler.
+// We wire handleIngest with a fake Hono context and a pre-validated claims object
+// (by vi.mocking the JWT module).
+
+vi.mock('@/lib/jwt.js', () => ({
+ validateSandboxEventIngestToken: vi.fn(),
+ validateStreamReadToken: vi.fn(),
+ loadPublicKey: vi.fn(),
+}))
+
+import { handleIngest } from '@/hono/ingest-handler.js'
+import { validateSandboxEventIngestToken } from '@/lib/jwt.js'
+
+const mockValidate = vi.mocked(validateSandboxEventIngestToken)
+
+// Build a minimal Hono Context-like object sufficient for handleIngest.
+function makeContext(opts: {
+ runId?: string
+ method?: string
+ token?: string
+ body?: ReadableStream<Uint8Array> | null
+}): Parameters<typeof handleIngest>[0] {
+ const { runId = 'run-123', method = 'POST', token = 'test-token', body = null } = opts
+
+ return {
+ req: {
+ method,
+ param: () => ({ run: runId }),
+ header: (name: string) => {
+ const lc = name.toLowerCase()
+ if (lc === 'authorization') {
+ return token ? `Bearer ${token}` : undefined
+ }
+ return undefined
+ },
+ raw: new Request('http://localhost/', {
+ method: 'POST',
+ body,
+ // Required for streaming body in Node
+ // @ts-expect-error duplex is Node-only
+ duplex: 'half',
+ }),
+ },
+ json: (data: unknown, status: number) => {
+ return new Response(JSON.stringify(data), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ },
+ } as unknown as Parameters<typeof handleIngest>[0]
+}
+
+// Decode a JSON response body.
+async function decodeJson(res: Response): Promise<unknown> {
+ return res.json()
+}
+
+// ---------------------------------------------------------------------------
+// Describe block
+// ---------------------------------------------------------------------------
+
+describe('ingest-handler', () => {
+ let fakeRedis: FakeRedis
+ let redisStream: TaskRunRedisStream
+ const RUN_ID = 'run-123'
+ const TASK_ID = 'task-abc'
+ const TEAM_ID = 42
+
+ beforeEach(() => {
+ fakeRedis = makeFakeRedis()
+ redisStream = makeRedisStream(fakeRedis, RUN_ID)
+ vi.clearAllMocks()
+ // Default: token is valid, claims match the route params
+ mockValidate.mockResolvedValue(makeClaims())
+ })
+
+ // -----------------------------------------------------------------------
+ // Auth / routing guards
+ // -----------------------------------------------------------------------
+
+ it('returns 405 on non-POST', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ method: 'GET' })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(405)
+ })
+
+ it('returns 401 when Authorization header is missing', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ token: '' })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(401)
+ })
+
+ it('returns 401 when JWT validation fails', async () => {
+ mockValidate.mockRejectedValue(new Error('invalid signature'))
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody('') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(401)
+ })
+
+ it('returns 403 when run id in claims does not match route', async () => {
+ mockValidate.mockResolvedValue(makeClaims({ runId: 'different-run' }))
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody('') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(403)
+ })
+
+ // -----------------------------------------------------------------------
+ // Happy-path: single event accepted
+ // -----------------------------------------------------------------------
+
+ it('returns 200 with accepted=1 duplicate=0 last_accepted_seq=1 for a single valid event', async () => {
+ const config = makeConfig()
+ const ndjson = JSON.stringify({ seq: 1, event: { type: 'message' } }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const body = await decodeJson(res)
+ expect(body).toMatchObject({ accepted: 1, duplicate: 0, last_accepted_seq: 1 })
+ })
+
+ it('accepts multiple sequential events', async () => {
+ const config = makeConfig()
+ const lines =
+ [
+ JSON.stringify({ seq: 1, event: { type: 'a' } }),
+ JSON.stringify({ seq: 2, event: { type: 'b' } }),
+ JSON.stringify({ seq: 3, event: { type: 'c' } }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(lines) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const body = (await decodeJson(res)) as { accepted: number; duplicate: number; last_accepted_seq: number }
+ expect(body.accepted).toBe(3)
+ expect(body.duplicate).toBe(0)
+ expect(body.last_accepted_seq).toBe(3)
+ })
+
+ // -----------------------------------------------------------------------
+ // Duplicate handling
+ // -----------------------------------------------------------------------
+
+ it('counts duplicate when same seq sent twice', async () => {
+ const config = makeConfig()
+ // First request: accept seq 1
+ const ndjson1 = JSON.stringify({ seq: 1, event: { type: 'first' } }) + '\n'
+ const ctx1 = makeContext({ body: makeStringBody(ndjson1) })
+ await handleIngest(ctx1, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+
+ // Second request: resend seq 1 → duplicate
+ const ndjson2 = JSON.stringify({ seq: 1, event: { type: 'first-again' } }) + '\n'
+ const ctx2 = makeContext({ body: makeStringBody(ndjson2) })
+ const res2 = await handleIngest(ctx2, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res2.status).toBe(200)
+ const body = (await decodeJson(res2)) as { accepted: number; duplicate: number; last_accepted_seq: number }
+ expect(body.accepted).toBe(0)
+ expect(body.duplicate).toBe(1)
+ expect(body.last_accepted_seq).toBe(1)
+ })
+
+ it('mixes accepted and duplicate when some events are re-sent', async () => {
+ const config = makeConfig()
+ // Seed seq 1 via a prior request
+ const seed = JSON.stringify({ seq: 1, event: { type: 'seed' } }) + '\n'
+ await handleIngest(
+ makeContext({ body: makeStringBody(seed) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+
+ // Resend seq 1 + new seq 2
+ const mixed =
+ [
+ JSON.stringify({ seq: 1, event: { type: 'duplicate' } }),
+ JSON.stringify({ seq: 2, event: { type: 'new' } }),
+ ].join('\n') + '\n'
+ const res = await handleIngest(
+ makeContext({ body: makeStringBody(mixed) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+ expect(res.status).toBe(200)
+ const body = (await decodeJson(res)) as { accepted: number; duplicate: number; last_accepted_seq: number }
+ expect(body.accepted).toBe(1)
+ expect(body.duplicate).toBe(1)
+ expect(body.last_accepted_seq).toBe(2)
+ })
+
+ // -----------------------------------------------------------------------
+ // Sequence gap → 409
+ // -----------------------------------------------------------------------
+
+ it('returns 409 for a sequence gap with last_accepted_seq', async () => {
+ const config = makeConfig()
+ // seq 2 without first accepting seq 1
+ const ndjson = JSON.stringify({ seq: 2, event: { type: 'jump' } }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(409)
+ const body = (await decodeJson(res)) as { last_accepted_seq: number }
+ expect(body.last_accepted_seq).toBe(0)
+ })
+
+ it('reports correct last_accepted_seq in sequence gap response after prior accepts', async () => {
+ const config = makeConfig()
+ // Accept 1 and 2 first
+ const setup =
+ [JSON.stringify({ seq: 1, event: { type: 'a' } }), JSON.stringify({ seq: 2, event: { type: 'b' } })].join(
+ '\n'
+ ) + '\n'
+ await handleIngest(
+ makeContext({ body: makeStringBody(setup) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+
+ // Now send seq 4 (gap at 3)
+ const gap = JSON.stringify({ seq: 4, event: { type: 'skip' } }) + '\n'
+ const res = await handleIngest(
+ makeContext({ body: makeStringBody(gap) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+ expect(res.status).toBe(409)
+ const body = (await decodeJson(res)) as { last_accepted_seq: number }
+ expect(body.last_accepted_seq).toBe(2)
+ })
+
+ // -----------------------------------------------------------------------
+ // Already-completed → 409
+ // -----------------------------------------------------------------------
+
+ it('returns 409 when writing to an already-completed stream', async () => {
+ const config = makeConfig()
+ // Accept 1 and mark complete
+ const ndjson1 =
+ JSON.stringify({ seq: 1, event: { type: 'msg' } }) +
+ '\n' +
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 1 }) +
+ '\n'
+ await handleIngest(
+ makeContext({ body: makeStringBody(ndjson1) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+
+ // Second request: try to write seq 2
+ const ndjson2 = JSON.stringify({ seq: 2, event: { type: 'late' } }) + '\n'
+ const res = await handleIngest(
+ makeContext({ body: makeStringBody(ndjson2) }),
+ fakeRedis as unknown as Redis,
+ config,
+ [] as CryptoKey[]
+ )
+ expect(res.status).toBe(409)
+ const body = (await decodeJson(res)) as { last_accepted_seq: number }
+ expect(body.last_accepted_seq).toBe(1)
+ })
+
+ // -----------------------------------------------------------------------
+ // Completion line: happy path
+ // -----------------------------------------------------------------------
+
+ it('accepts completion line with final_seq matching last accepted', async () => {
+ const config = makeConfig()
+ const ndjson =
+ [
+ JSON.stringify({ seq: 1, event: { type: 'msg' } }),
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 1 }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const body = (await decodeJson(res)) as { accepted: number; last_accepted_seq: number }
+ expect(body.accepted).toBe(1)
+ expect(body.last_accepted_seq).toBe(1)
+
+ // Verify the completion sentinel was written to the Redis stream.
+ const entries = await fakeRedis.xrange(getStreamKey(RUN_ID))
+ const sentinelEntry = entries.find(([, fields]) => {
+ const raw = fields['data']
+ if (!raw) {
+ return false
+ }
+ const parsed = JSON.parse(raw)
+ return parsed.type === 'STREAM_STATUS' && parsed.status === 'complete'
+ })
+ expect(sentinelEntry).toBeTruthy()
+ })
+
+ it('returns 409 when completion final_seq does not match last accepted', async () => {
+ const config = makeConfig()
+ const ndjson =
+ [
+ JSON.stringify({ seq: 1, event: { type: 'msg' } }),
+ // final_seq=2 but only seq 1 was accepted
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 2 }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(409)
+ const body = (await decodeJson(res)) as { last_accepted_seq: number }
+ expect(body.last_accepted_seq).toBe(1)
+ })
+
+ it('accepts completion line with final_seq=0 when no events were sent', async () => {
+ const config = makeConfig()
+ const ndjson = JSON.stringify({ type: '_posthog/stream_complete', final_seq: 0 }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ })
+
+ it('returns 400 when an event line follows the completion line', async () => {
+ const config = makeConfig()
+ const ndjson =
+ [
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 0 }),
+ JSON.stringify({ seq: 1, event: { type: 'after' } }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 when completion line appears more than once', async () => {
+ const config = makeConfig()
+ const ndjson =
+ [
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 0 }),
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 0 }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ // -----------------------------------------------------------------------
+ // NDJSON parsing: chunk-boundary splitting
+ // -----------------------------------------------------------------------
+
+ it('parses NDJSON correctly when JSON object is split across two chunks', async () => {
+ const config = makeConfig()
+ const line = JSON.stringify({ seq: 1, event: { type: 'chunked' } })
+ const full = line + '\n'
+ const mid = Math.floor(full.length / 2)
+ const enc = new TextEncoder()
+ const chunk1 = enc.encode(full.slice(0, mid))
+ const chunk2 = enc.encode(full.slice(mid))
+ const body = makeChunkedBody([chunk1, chunk2])
+ const ctx = makeContext({ body })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const rb = (await decodeJson(res)) as { accepted: number }
+ expect(rb.accepted).toBe(1)
+ })
+
+ it('parses multiple events when newlines land at chunk boundaries', async () => {
+ const config = makeConfig()
+ const enc = new TextEncoder()
+ // Build two lines, split so the newline after line 1 is in its own chunk
+ const line1 = JSON.stringify({ seq: 1, event: { type: 'a' } })
+ const line2 = JSON.stringify({ seq: 2, event: { type: 'b' } })
+ const chunks = [enc.encode(line1), enc.encode('\n'), enc.encode(line2), enc.encode('\n')]
+ const body = makeChunkedBody(chunks)
+ const ctx = makeContext({ body })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const rb = (await decodeJson(res)) as { accepted: number }
+ expect(rb.accepted).toBe(2)
+ })
+
+ it('handles a trailing partial line with no trailing newline', async () => {
+ const config = makeConfig()
+ const line = JSON.stringify({ seq: 1, event: { type: 'no-newline' } })
+ // No trailing newline — the flush-on-done path handles it
+ const ctx = makeContext({ body: makeStringBody(line) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const rb = (await decodeJson(res)) as { accepted: number }
+ expect(rb.accepted).toBe(1)
+ })
+
+ it('skips blank lines between events', async () => {
+ const config = makeConfig()
+ const ndjson =
+ '\n' +
+ JSON.stringify({ seq: 1, event: { type: 'a' } }) +
+ '\n\n' +
+ JSON.stringify({ seq: 2, event: { type: 'b' } }) +
+ '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const rb = (await decodeJson(res)) as { accepted: number }
+ expect(rb.accepted).toBe(2)
+ })
+
+ // -----------------------------------------------------------------------
+ // Byte / line / count limits → 413
+ // -----------------------------------------------------------------------
+
+ it('returns 413 when request body exceeds MAX_REQUEST_BYTES', async () => {
+ const config = makeConfig()
+ const enc = new TextEncoder()
+
+ // Chunk 1: a valid event line that fits within MAX_REQUEST_BYTES.
+ // This chunk is processed first; seq 1 is yielded and accepted.
+ const line1 = JSON.stringify({ seq: 1, event: { type: 'ok' } }) + '\n'
+
+ // Chunk 2: another event line whose addition pushes the cumulative total
+ // over MAX_REQUEST_BYTES, triggering the 413 before seq 2 is accepted.
+ // The check is requestSize > MAX_REQUEST_BYTES after adding the chunk,
+ // so we need chunk2.length > MAX_REQUEST_BYTES - chunk1.length.
+ const padding = 'x'.repeat(MAX_REQUEST_BYTES)
+ const line2 = JSON.stringify({ seq: 2, event: { type: 'big', data: padding } }) + '\n'
+
+ const body = makeChunkedBody([enc.encode(line1), enc.encode(line2)])
+ const ctx = makeContext({ body })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(413)
+ const rb = (await decodeJson(res)) as { last_accepted_seq: number }
+ // seq 1 was accepted (chunk 1 was processed) before chunk 2 exceeded the limit
+ expect(rb.last_accepted_seq).toBe(1)
+ })
+
+ it('returns 413 when a single line exceeds MAX_EVENT_LINE_BYTES', async () => {
+ const config = makeConfig()
+ // A single event line larger than 1_000_000 bytes.
+ const hugePayload = 'y'.repeat(MAX_EVENT_LINE_BYTES + 1)
+ const ndjson = JSON.stringify({ seq: 1, event: { data: hugePayload } }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(413)
+ })
+
+ it('returns 413 when event count exceeds MAX_EVENTS_PER_REQUEST', async () => {
+ const config = makeConfig()
+ const lines: string[] = []
+ for (let i = 1; i <= MAX_EVENTS_PER_REQUEST + 1; i++) {
+ lines.push(JSON.stringify({ seq: i, event: { type: 'e' } }))
+ }
+ const ndjson = lines.join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(413)
+ const body = (await decodeJson(res)) as { last_accepted_seq: number }
+ // last_accepted_seq should be MAX_EVENTS_PER_REQUEST (the last accepted before the limit)
+ expect(body.last_accepted_seq).toBe(MAX_EVENTS_PER_REQUEST)
+ })
+
+ // -----------------------------------------------------------------------
+ // NDJSON parse errors → 400
+ // -----------------------------------------------------------------------
+
+ it('returns 400 for invalid JSON', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody('not json\n') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 for a JSON array (not an object)', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody('[1,2]\n') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 for seq=0 (must be >= 1)', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody(JSON.stringify({ seq: 0, event: {} }) + '\n') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 when seq is not an integer', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody(JSON.stringify({ seq: 1.5, event: {} }) + '\n') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 when event field is not an object', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody(JSON.stringify({ seq: 1, event: 'string' }) + '\n') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 when completion final_seq is negative', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({
+ body: makeStringBody(JSON.stringify({ type: '_posthog/stream_complete', final_seq: -1 }) + '\n'),
+ })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ it('returns 400 when completion final_seq is not an integer', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({
+ body: makeStringBody(JSON.stringify({ type: '_posthog/stream_complete', final_seq: 1.5 }) + '\n'),
+ })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(400)
+ })
+
+ // -----------------------------------------------------------------------
+ // Empty body
+ // -----------------------------------------------------------------------
+
+ it('returns 200 with accepted=0 for an empty body', async () => {
+ const config = makeConfig()
+ const ctx = makeContext({ body: makeStringBody('') })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+ const body = (await decodeJson(res)) as { accepted: number; duplicate: number; last_accepted_seq: number }
+ expect(body.accepted).toBe(0)
+ expect(body.duplicate).toBe(0)
+ expect(body.last_accepted_seq).toBe(0)
+ })
+
+ // -----------------------------------------------------------------------
+ // Side effects: turn-complete
+ // -----------------------------------------------------------------------
+
+ it('sets agent inactive and fires awaiting_input callback on turn-complete event', async () => {
+ const fetchCalls: { url: string; body: unknown }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (url, init) => {
+ fetchCalls.push({ url: String(url), body: JSON.parse(String((init as RequestInit).body)) })
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ mockValidate.mockResolvedValue(makeClaims())
+
+ const turnCompleteEvent = {
+ type: 'notification',
+ notification: { method: '_posthog/turn_complete' },
+ }
+ const ndjson = JSON.stringify({ seq: 1, event: turnCompleteEvent }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+
+ // Agent must have been set inactive.
+ const agentActive = await redisStream.getAgentActive()
+ expect(agentActive).toBe(false)
+
+ // Flush any queued microtasks so the detached fire-and-forget promise runs.
+ await new Promise((r) => setTimeout(r, 0))
+
+ const callbackCall = fetchCalls.find((c) => c.url.includes('agent-proxy-callback'))
+ expect(callbackCall).toBeTruthy()
+ expect(callbackCall?.body).toMatchObject({ kind: 'awaiting_input', agent_active: false })
+
+ global.fetch = originalFetch
+ })
+
+ // -----------------------------------------------------------------------
+ // Side effects: session/update → agent active
+ // -----------------------------------------------------------------------
+
+ it('sets agent active on session/update event and fires heartbeat after claim', async () => {
+ const fetchCalls: { url: string; body: unknown }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (url, init) => {
+ fetchCalls.push({ url: String(url), body: JSON.parse(String((init as RequestInit).body)) })
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ mockValidate.mockResolvedValue(makeClaims())
+
+ const sessionUpdateEvent = {
+ type: 'notification',
+ notification: { method: 'session/update' },
+ }
+ const ndjson = JSON.stringify({ seq: 1, event: sessionUpdateEvent }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+
+ const agentActive = await redisStream.getAgentActive()
+ expect(agentActive).toBe(true)
+
+ await new Promise((r) => setTimeout(r, 0))
+
+ const callbackCall = fetchCalls.find((c) => c.url.includes('agent-proxy-callback'))
+ expect(callbackCall).toBeTruthy()
+ expect(callbackCall?.body).toMatchObject({ kind: 'heartbeat', agent_active: true })
+
+ global.fetch = originalFetch
+ })
+
+ // -----------------------------------------------------------------------
+ // Side effects: heartbeat throttle
+ // -----------------------------------------------------------------------
+
+ it('does not fire second heartbeat callback when heartbeat key is already claimed', async () => {
+ const fetchCalls: { url: string }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (url) => {
+ fetchCalls.push({ url: String(url) })
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+
+ // Pre-seed: set agent active so heartbeat path runs
+ await redisStream.setAgentActive(true)
+ // Claim the heartbeat key so the throttle fires (first heartbeat claimed)
+ await redisStream.claimAgentActiveHeartbeat(HEARTBEAT_THROTTLE_SECONDS)
+
+ const sessionUpdateEvent = {
+ type: 'notification',
+ notification: { method: 'session/update' },
+ }
+ const ndjson =
+ [
+ JSON.stringify({ seq: 1, event: sessionUpdateEvent }),
+ JSON.stringify({ seq: 2, event: { type: 'other' } }),
+ ].join('\n') + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+
+ await new Promise((r) => setTimeout(r, 0))
+
+ // The heartbeat key was already claimed; no callback should fire.
+ const callbackCalls = fetchCalls.filter((c) => c.url.includes('agent-proxy-callback'))
+ // session/update on seq 1 tries to claim → already claimed → no callback
+ // seq 2 is a non-session-update event; agentActive is true; tries to claim → already claimed → no callback
+ expect(callbackCalls.length).toBe(0)
+
+ global.fetch = originalFetch
+ })
+
+ // -----------------------------------------------------------------------
+ // Side effects: best-effort (callback failure does not fail ingest)
+ // -----------------------------------------------------------------------
+
+ it('still returns 200 when the Django callback throws', async () => {
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async () => {
+ throw new Error('network failure')
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+
+ const turnCompleteEvent = {
+ type: 'notification',
+ notification: { method: '_posthog/turn_complete' },
+ }
+ const ndjson = JSON.stringify({ seq: 1, event: turnCompleteEvent }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ // Callback failure must NOT affect ingest response
+ expect(res.status).toBe(200)
+
+ // Let the detached promise settle without crashing the test
+ await new Promise((r) => setTimeout(r, 10))
+
+ global.fetch = originalFetch
+ })
+
+ it('still returns 200 when the Django callback returns a non-2xx status', async () => {
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async () => new Response('', { status: 500 })) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+
+ const turnCompleteEvent = {
+ type: 'notification',
+ notification: { method: '_posthog/turn_complete' },
+ }
+ const ndjson = JSON.stringify({ seq: 1, event: turnCompleteEvent }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+
+ await new Promise((r) => setTimeout(r, 10))
+
+ global.fetch = originalFetch
+ })
+
+ // -----------------------------------------------------------------------
+ // heartbeatWorkflowIfNeeded (side-effects.ts) unit tests
+ // -----------------------------------------------------------------------
+
+ describe('heartbeatWorkflowIfNeeded', () => {
+ it('sets agent inactive and fires awaiting_input for a turn-complete event', async () => {
+ const fired: { kind: string }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const event = { type: 'notification', notification: { method: '_posthog/turn_complete' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ expect(await redisStream.getAgentActive()).toBe(false)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired.some((f) => f.kind === 'awaiting_input')).toBe(true)
+
+ global.fetch = originalFetch
+ })
+
+ it('sets agent active and fires heartbeat for a session/update event', async () => {
+ const fired: { kind: string }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const event = { type: 'notification', notification: { method: 'session/update' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ expect(await redisStream.getAgentActive()).toBe(true)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired.some((f) => f.kind === 'heartbeat')).toBe(true)
+
+ global.fetch = originalFetch
+ })
+
+ it('does not fire heartbeat for a plain event when agent is not active', async () => {
+ const fired: unknown[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const event = { type: 'notification', notification: { method: 'other' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired).toHaveLength(0)
+
+ global.fetch = originalFetch
+ })
+
+ it('fires heartbeat for a plain event when agent is already active', async () => {
+ const fired: { kind: string }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ await redisStream.setAgentActive(true)
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const event = { type: 'notification', notification: { method: 'other' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired.some((f) => f.kind === 'heartbeat')).toBe(true)
+
+ global.fetch = originalFetch
+ })
+
+ it('skips the heartbeat callback when the throttle key is already claimed', async () => {
+ const fired: unknown[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ await redisStream.setAgentActive(true)
+ // Pre-claim the heartbeat slot
+ await redisStream.claimAgentActiveHeartbeat(HEARTBEAT_THROTTLE_SECONDS)
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ const event = { type: 'notification', notification: { method: 'other' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired).toHaveLength(0)
+
+ global.fetch = originalFetch
+ })
+
+ it('does not fire any callback when djangoCallbackBaseUrl is empty', async () => {
+ const fetchSpy = vi.spyOn(global, 'fetch')
+ const config = makeConfig({ djangoCallbackBaseUrl: '' })
+ const event = { type: 'notification', notification: { method: '_posthog/turn_complete' } }
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fetchSpy).not.toHaveBeenCalled()
+ fetchSpy.mockRestore()
+ })
+ })
+})
diff --git a/services/agent-proxy/tests/hono/metrics.test.ts b/services/agent-proxy/tests/hono/metrics.test.ts
new file mode 100644
index 000000000000..552e0d7f94d2
--- /dev/null
+++ b/services/agent-proxy/tests/hono/metrics.test.ts
@@ -0,0 +1,32 @@
+import { describe, it, expect, vi } from 'vitest'
+
+// test-setup.ts globally mocks ./hono/metrics.js (so prom-client does not register
+// duplicate metrics across suites), replacing routeLabel with an identity stub.
+// Pull the REAL implementation so this suite exercises the actual label logic —
+// that global stub is exactly why a routeLabel mismatch could otherwise go unseen.
+const { routeLabel } = await vi.importActual<typeof import('@/hono/metrics.js')>('@/hono/metrics.js')
+
+describe('metrics', () => {
+ // The http metric `route` label must stay LOW cardinality: parameterised routes
+ // collapse to a single stable label, never leaking project/task/run ids. The two
+ // primary legs each get their own readable label so stream reads and ingests are
+ // distinguishable on dashboards.
+ it.each([
+ ['/v1/runs/run-xyz/stream', '/v1/runs/stream'],
+ ['/v1/runs/run-xyz/ingest', '/v1/runs/ingest'],
+ ['/_health', '/_health'],
+ ['/_readyz', '/_readyz'],
+ ['/_metrics', '/_metrics'],
+ ['/health', '/health'],
+ ['/', 'other'],
+ ['/v1/runs/run-xyz/', 'other'],
+ ['/v1/runs/run-xyz/stream/', 'other'],
+ ['/api/projects/123/tasks/abc/runs/run-xyz/stream/', 'other'],
+ ])('routeLabel(%s) -> %s', (pathname, expected) => {
+ expect(routeLabel(pathname)).toBe(expected)
+ })
+
+ it('does not leak run ids into the route label', () => {
+ expect(routeLabel('/v1/runs/secret-run-id/stream')).not.toContain('secret-run-id')
+ })
+})
diff --git a/services/agent-proxy/tests/hono/public-routes.test.ts b/services/agent-proxy/tests/hono/public-routes.test.ts
new file mode 100644
index 000000000000..3063c125471e
--- /dev/null
+++ b/services/agent-proxy/tests/hono/public-routes.test.ts
@@ -0,0 +1,51 @@
+import { Hono } from 'hono'
+import { describe, expect, it } from 'vitest'
+
+import { registerPublicRoutes } from '@/hono/public-routes.js'
+
+function makeApp(metricsToken: string): Hono {
+ const app = new Hono()
+ registerPublicRoutes(app, { shuttingDown: false }, metricsToken)
+ return app
+}
+
+describe('public routes', () => {
+ describe('/_metrics token guard', () => {
+ it('serves metrics openly when no token is configured', async () => {
+ const res = await makeApp('').request('/_metrics')
+
+ expect(res.status).toBe(200)
+ expect(res.headers.get('Content-Type')).toContain('text/plain')
+ })
+
+ it('rejects a scrape without a bearer token when a token is configured', async () => {
+ const res = await makeApp('scrape-secret').request('/_metrics')
+
+ expect(res.status).toBe(401)
+ })
+
+ it('rejects a scrape with the wrong bearer token', async () => {
+ const res = await makeApp('scrape-secret').request('/_metrics', {
+ headers: { Authorization: 'Bearer not-the-secret' },
+ })
+
+ expect(res.status).toBe(401)
+ })
+
+ it('serves metrics with the correct bearer token', async () => {
+ const res = await makeApp('scrape-secret').request('/_metrics', {
+ headers: { Authorization: 'Bearer scrape-secret' },
+ })
+
+ expect(res.status).toBe(200)
+ })
+ })
+
+ it('health and readiness routes stay open regardless of the metrics token', async () => {
+ const app = makeApp('scrape-secret')
+
+ expect((await app.request('/_health')).status).toBe(200)
+ expect((await app.request('/_readyz')).status).toBe(200)
+ expect((await app.request('/health')).status).toBe(200)
+ })
+})
diff --git a/services/agent-proxy/tests/hono/sse-handler.test.ts b/services/agent-proxy/tests/hono/sse-handler.test.ts
new file mode 100644
index 000000000000..41576b38726f
--- /dev/null
+++ b/services/agent-proxy/tests/hono/sse-handler.test.ts
@@ -0,0 +1,773 @@
+// Tests for SSE framing and streamTaskRunEvents generator.
+//
+// Wire-protocol invariant: SSE output must be byte-identical to the Python
+// format_sse_event in products/tasks/backend/stream/sse.py. Django and this
+// Node service read/write the SAME Redis stream during the cutover window.
+//
+// Coverage mirrors products/tasks/backend/stream/tests/test_sse.py plus the
+// timing paths (keepalive cadence, wait-for-stream timeout) that are hard to
+// exercise in Python without mocking.
+
+import type { Redis } from 'ioredis'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { formatSseEvent, streamTaskRunEvents } from '@/hono/sse-handler.js'
+import {
+ KEEPALIVE_INTERVAL_MS,
+ SSE_EVENT_ERROR,
+ SSE_EVENT_KEEPALIVE,
+ SSE_EVENT_STREAM_END,
+ WAIT_TIMEOUT_MS,
+} from '@/lib/constants.js'
+
+// ---------------------------------------------------------------------------
+// Minimal in-memory fake Redis
+//
+// Implements exactly the subset of the ioredis API that TaskRunRedisStream
+// uses. The goal is correctness of the SSE framing and generator flow, not
+// exhaustive Redis semantics.
+// ---------------------------------------------------------------------------
+
+interface StreamMessage {
+ id: string
+ fields: Record<string, string>
+}
+
+let _autoSeq = 0
+function nextStreamId(): string {
+ _autoSeq++
+ return `${Date.now()}-${_autoSeq}`
+}
+
+class FakeRedisPipeline {
+ private readonly ops: Array<() => [null, unknown]> = []
+ private readonly store: FakeRedis
+
+ constructor(store: FakeRedis) {
+ this.store = store
+ }
+
+ xadd(key: string, ...args: string[]): this {
+ this.ops.push(() => {
+ const id = this.store._xadd(key, args)
+ return [null, id]
+ })
+ return this
+ }
+
+ expire(_key: string, _seconds: number): this {
+ this.ops.push(() => [null, 1])
+ return this
+ }
+
+ set(key: string, value: string, ..._rest: string[]): this {
+ this.ops.push(() => {
+ this.store._set(key, value)
+ return [null, 'OK']
+ })
+ return this
+ }
+
+ async exec(): Promise<Array<[null, unknown]> | null> {
+ if (this.store._watchConflict) {
+ this.store._watchConflict = false
+ return null
+ }
+ const results: Array<[null, unknown]> = []
+ for (const op of this.ops) {
+ results.push(op())
+ }
+ return results
+ }
+}
+
+// Shape that ioredis XREAD returns:
+// Array<[streamName, Array<[id, fields_flat_array]>]>
+type XreadResult = Array<[string, Array<[string, string[]]>]>
+
+class FakeRedis {
+ private readonly strings = new Map<string, string>()
+ private readonly streams = new Map<string, StreamMessage[]>()
+
+ // Set this true before the next pipeline exec() to simulate a WATCH conflict.
+ _watchConflict = false
+
+ // Blocked XREAD calls waiting for new messages.
+ private pendingReads: Array<{
+ streamKey: string
+ currentId: string
+ resolve: (result: XreadResult | null) => void
+ }> = []
+
+ // ---------------------------------------------------------------------------
+ // Helpers used by FakeRedisPipeline
+ // ---------------------------------------------------------------------------
+
+ _xadd(key: string, args: string[]): string {
+ // args: ['MAXLEN', '~', maxlen, '*', 'data', value] or bare ['*', 'data', value]
+ const idIdx = args.indexOf('*')
+ const id = nextStreamId()
+ const fieldsFlat = args.slice(idIdx + 1)
+ const fields: Record<string, string> = {}
+ for (let i = 0; i < fieldsFlat.length - 1; i += 2) {
+ fields[fieldsFlat[i] as string] = fieldsFlat[i + 1] as string
+ }
+ const msg: StreamMessage = { id, fields }
+ const bucket = this.streams.get(key) ?? []
+ bucket.push(msg)
+ this.streams.set(key, bucket)
+
+ // Notify any blocked XREAD waiting on this key.
+ const pending = this.pendingReads.filter((r) => r.streamKey === key)
+ for (const waiter of pending) {
+ this.pendingReads = this.pendingReads.filter((r) => r !== waiter)
+ const matching = bucket.filter((m) => this._streamIdGt(m.id, waiter.currentId))
+ if (matching.length > 0) {
+ waiter.resolve([[key, matching.map((m) => [m.id, this._flatFields(m.fields)])]])
+ } else {
+ waiter.resolve(null)
+ }
+ }
+
+ return id
+ }
+
+ _set(key: string, value: string): void {
+ this.strings.set(key, value)
+ }
+
+ // ---------------------------------------------------------------------------
+ // ioredis-compatible API surface
+ // ---------------------------------------------------------------------------
+
+ async exists(key: string): Promise<number> {
+ const hasStr = this.strings.has(key)
+ const hasStream = (this.streams.get(key)?.length ?? 0) > 0
+ return hasStr || hasStream ? 1 : 0
+ }
+
+ async get(key: string): Promise<string | null> {
+ return this.strings.get(key) ?? null
+ }
+
+ async set(key: string, value: string, ..._rest: unknown[]): Promise<string> {
+ this.strings.set(key, value)
+ return 'OK'
+ }
+
+ async expire(_key: string, _seconds: number): Promise<number> {
+ return 1
+ }
+
+ async del(...keys: string[]): Promise<number> {
+ let n = 0
+ for (const k of keys) {
+ if (this.strings.delete(k) || this.streams.delete(k)) {
+ n++
+ }
+ }
+ return n
+ }
+
+ async xadd(key: string, ...args: string[]): Promise<string> {
+ return this._xadd(key, args)
+ }
+
+ async xlen(key: string): Promise<number> {
+ return this.streams.get(key)?.length ?? 0
+ }
+
+ async xrange(key: string, start: string, end: string, ..._rest: unknown[]): Promise<Array<[string, string[]]>> {
+ const msgs = this.streams.get(key) ?? []
+ return msgs.filter((m) => this._inRange(m.id, start, end)).map((m) => [m.id, this._flatFields(m.fields)])
+ }
+
+ async xrevrange(key: string, end: string, start: string, ..._rest: unknown[]): Promise<Array<[string, string[]]>> {
+ const msgs = (this.streams.get(key) ?? []).slice()
+ return msgs
+ .reverse()
+ .filter((m) => this._inRange(m.id, start, end))
+ .map((m) => [m.id, this._flatFields(m.fields)])
+ }
+
+ // XREAD COUNT count BLOCK blockMs STREAMS key currentId
+ async xread(...args: unknown[]): Promise<XreadResult | null> {
+ const argsStr = args.map(String)
+ const streamsIdx = argsStr.indexOf('STREAMS')
+ const streamKey = argsStr[streamsIdx + 1] as string
+ const currentId = argsStr[streamsIdx + 2] as string
+ const blockIdx = argsStr.indexOf('BLOCK')
+ const blockMs = blockIdx === -1 ? 0 : parseInt(argsStr[blockIdx + 1] as string, 10)
+ const countIdx = argsStr.indexOf('COUNT')
+ const count = countIdx === -1 ? 16 : parseInt(argsStr[countIdx + 1] as string, 10)
+
+ const bucket = this.streams.get(streamKey) ?? []
+ const matching = bucket.filter((m) => this._streamIdGt(m.id, currentId)).slice(0, count)
+
+ if (matching.length > 0) {
+ return [[streamKey, matching.map((m) => [m.id, this._flatFields(m.fields)])]]
+ }
+
+ if (blockMs === 0) {
+ return null
+ }
+
+ // Blocking read: return a promise that resolves when new data arrives
+ // or the block timeout fires.
+ return new Promise<XreadResult | null>((resolve) => {
+ const entry = { streamKey, currentId, resolve }
+ this.pendingReads.push(entry)
+
+ // Resolve with null after blockMs (simulates XREAD block timeout).
+ // We use the real setTimeout here; in fake-timer tests the test
+ // controls when time advances, so the timeout fires on demand.
+ setTimeout(() => {
+ this.pendingReads = this.pendingReads.filter((r) => r !== entry)
+ resolve(null)
+ }, blockMs)
+ })
+ }
+
+ async watch(..._keys: string[]): Promise<string> {
+ return 'OK'
+ }
+
+ async unwatch(): Promise<string> {
+ return 'OK'
+ }
+
+ multi(): FakeRedisPipeline {
+ return new FakeRedisPipeline(this)
+ }
+
+ // Stubs for the per-stream redis.duplicate() connection lifecycle.
+ // duplicate() returns `this` so the shared in-memory store is visible to
+ // both the "shared" and "blocking" sides — correct for single-threaded tests.
+ duplicate(): this {
+ return this
+ }
+
+ async connect(): Promise<void> {}
+
+ async disconnect(): Promise<void> {}
+
+ on(_event: string, _handler: (...args: unknown[]) => void): this {
+ return this
+ }
+
+ // ---------------------------------------------------------------------------
+ // Internal helpers
+ // ---------------------------------------------------------------------------
+
+ private _flatFields(fields: Record<string, string>): string[] {
+ const flat: string[] = []
+ for (const [k, v] of Object.entries(fields)) {
+ flat.push(k, v)
+ }
+ return flat
+ }
+
+ private _parseId(id: string): [number, number] {
+ if (id === '-') {
+ return [0, 0]
+ }
+ if (id === '+') {
+ return [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]
+ }
+ if (id === '0' || id === '0-0') {
+ return [0, 0]
+ }
+ const dash = id.indexOf('-')
+ if (dash === -1) {
+ return [parseInt(id, 10) || 0, 0]
+ }
+ return [parseInt(id.slice(0, dash), 10) || 0, parseInt(id.slice(dash + 1), 10) || 0]
+ }
+
+ private _streamIdGt(id: string, cursor: string): boolean {
+ const [aMs, aSeq] = this._parseId(id)
+ const [bMs, bSeq] = this._parseId(cursor)
+ return aMs > bMs || (aMs === bMs && aSeq > bSeq)
+ }
+
+ private _inRange(id: string, start: string, end: string): boolean {
+ const [ms, seq] = this._parseId(id)
+ const [startMs, startSeq] = this._parseId(start)
+ const [endMs, endSeq] = this._parseId(end)
+ const afterStart = ms > startMs || (ms === startMs && seq >= startSeq)
+ const beforeEnd = ms < endMs || (ms === endMs && seq <= endSeq)
+ return afterStart && beforeEnd
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+async function collect(gen: AsyncGenerator<Buffer, void, unknown>): Promise<string> {
+ const chunks: string[] = []
+ for await (const chunk of gen) {
+ chunks.push(chunk.toString('utf8'))
+ }
+ return chunks.join('')
+}
+
+function makeStreamKey(runId: string): string {
+ return `task-run-stream:${runId}`
+}
+
+function uniqueRunId(): string {
+ return `test-run-${crypto.randomUUID()}`
+}
+
+// Write a data entry directly to the fake stream (bypasses sequence checks).
+function xaddData(redis: FakeRedis, streamKey: string, event: Record<string, unknown>): void {
+ void redis.xadd(streamKey, 'MAXLEN', '~', '20000', '*', 'data', JSON.stringify(event))
+}
+
+// Write the completion sentinel.
+function xaddComplete(redis: FakeRedis, streamKey: string): void {
+ xaddData(redis, streamKey, { type: 'STREAM_STATUS', status: 'complete' })
+}
+
+// Write the error sentinel.
+function xaddError(redis: FakeRedis, streamKey: string, error: string): void {
+ xaddData(redis, streamKey, { type: 'STREAM_STATUS', status: 'error', error })
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('sse-handler', () => {
+ let redis: FakeRedis
+
+ beforeEach(() => {
+ redis = new FakeRedis()
+ _autoSeq = 0
+ vi.restoreAllMocks()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ // -------------------------------------------------------------------------
+ // formatSseEvent — wire-protocol byte framing
+ // -------------------------------------------------------------------------
+
+ describe('formatSseEvent', () => {
+ it('emits data line terminated by a double newline for a plain event', () => {
+ const buf = formatSseEvent({ hello: 'world' })
+ const text = buf.toString('utf8')
+ expect(text).toBe('data: {"hello":"world"}\n\n')
+ })
+
+ it('emits event line before id and data when eventName is given', () => {
+ const buf = formatSseEvent({ type: 'keepalive' }, { eventName: 'keepalive' })
+ const text = buf.toString('utf8')
+ expect(text).toBe('event: keepalive\ndata: {"type":"keepalive"}\n\n')
+ })
+
+ it('emits id line between event and data when eventId is given', () => {
+ const buf = formatSseEvent({ msg: 'hi' }, { eventId: '123-1', eventName: 'message' })
+ const text = buf.toString('utf8')
+ expect(text).toBe('event: message\nid: 123-1\ndata: {"msg":"hi"}\n\n')
+ })
+
+ it('emits only id and data when eventName is omitted', () => {
+ const buf = formatSseEvent({ seq: 1 }, { eventId: '456-0' })
+ const text = buf.toString('utf8')
+ expect(text).toBe('id: 456-0\ndata: {"seq":1}\n\n')
+ })
+
+ it('returns a Buffer', () => {
+ const buf = formatSseEvent({ x: 1 })
+ expect(Buffer.isBuffer(buf)).toBe(true)
+ })
+
+ it('always ends with exactly two newlines (blank line delimiter)', () => {
+ // 4 opts × 2 expects each; oxlint's static analyser does not descend into for-loops
+ expect.assertions(8)
+ for (const opts of [{}, { eventName: 'ping' }, { eventId: '1-0' }, { eventName: 'ping', eventId: '1-0' }]) {
+ const text = formatSseEvent({ n: 1 }, opts).toString('utf8')
+ expect(text.endsWith('\n\n')).toBe(true)
+ // No triple newline — only one blank line.
+ expect(text.includes('\n\n\n')).toBe(false)
+ }
+ })
+
+ it('does not emit event line when eventName is empty string', () => {
+ const text = formatSseEvent({ x: 1 }, { eventName: '' }).toString('utf8')
+ expect(text.startsWith('event:')).toBe(false)
+ })
+
+ it('does not emit id line when eventId is empty string', () => {
+ const text = formatSseEvent({ x: 1 }, { eventId: '' }).toString('utf8')
+ expect(text.includes('id:')).toBe(false)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — normal stream events then stream-end terminal
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — happy path', () => {
+ it('emits events then stream-end terminal on clean completion', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'hello' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ expect(body).toContain('"msg":"hello"')
+ expect(body).toContain(`event: ${SSE_EVENT_STREAM_END}`)
+ expect(body).toContain('"status":"complete"')
+ })
+
+ it('emits normal events without an event: line (only id: and data:)', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'test' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // Split into individual SSE frames (blank-line delimited).
+ const frames = body.split('\n\n').filter((f) => f.trim() !== '')
+
+ // First frame is the data event — must not have an event: line.
+ const dataFrame = frames.find((f) => f.includes('"msg":"test"'))
+ expect(dataFrame).toBeTruthy()
+ expect(dataFrame!.startsWith('event:')).toBe(false)
+
+ // It must carry an id: line (the Redis stream ID).
+ expect(dataFrame!).toContain('id:')
+ })
+
+ it('does not yield the completion sentinel as a data event', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // The STREAM_STATUS sentinel must never appear as a data payload.
+ expect(body).not.toContain('"STREAM_STATUS"')
+ expect(body).not.toContain('"status":"complete"' + '\n\n')
+ // The terminal stream-end event carries status:complete in a named event frame.
+ expect(body).toContain(`event: ${SSE_EVENT_STREAM_END}`)
+ })
+
+ it('emits multiple events in order before stream-end', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first' })
+ xaddData(redis, streamKey, { type: 'notification', msg: 'second' })
+ xaddData(redis, streamKey, { type: 'notification', msg: 'third' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ const firstPos = body.indexOf('"first"')
+ const secondPos = body.indexOf('"second"')
+ const thirdPos = body.indexOf('"third"')
+ const endPos = body.indexOf(SSE_EVENT_STREAM_END)
+
+ expect(firstPos).toBeLessThan(secondPos)
+ expect(secondPos).toBeLessThan(thirdPos)
+ expect(thirdPos).toBeLessThan(endPos)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — terminal stream-end event framing
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — terminal stream-end event', () => {
+ it('terminal event is named stream-end and carries {status:complete}', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // Find the stream-end frame.
+ const frames = body.split('\n\n').filter((f) => f.trim() !== '')
+ const terminalFrame = frames.find((f) => f.includes(SSE_EVENT_STREAM_END))
+ expect(terminalFrame).toBeTruthy()
+ expect(terminalFrame!).toBe(`event: ${SSE_EVENT_STREAM_END}\ndata: {"status":"complete"}`)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — error sentinel
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — stream error event', () => {
+ it('emits error event and stops on error sentinel', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'before error' })
+ xaddError(redis, streamKey, 'boom')
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ expect(body).toContain('"before error"')
+ expect(body).toContain(`event: ${SSE_EVENT_ERROR}`)
+ expect(body).toContain('"boom"')
+ })
+
+ it('does not emit stream-end after an error', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddError(redis, streamKey, 'catastrophic failure')
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ expect(body).not.toContain(SSE_EVENT_STREAM_END)
+ })
+
+ it('error event is named error and carries {error:"..."} payload', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddError(redis, streamKey, 'disk full')
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ const frames = body.split('\n\n').filter((f) => f.trim() !== '')
+ const errorFrame = frames.find((f) => f.includes(`event: ${SSE_EVENT_ERROR}`))
+ expect(errorFrame).toBeTruthy()
+ expect(errorFrame!).toContain('"disk full"')
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — resume from Last-Event-ID
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — resume from Last-Event-ID', () => {
+ it('resumes from last-event-id, skipping events already seen', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first' })
+ // Capture the id of the first event to use as Last-Event-ID.
+ const msgs = await redis.xrange(streamKey, '-', '+', 'COUNT', 1)
+ const firstId = msgs[0]![0]
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'second' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: firstId })
+ )
+
+ expect(body).toContain('"second"')
+ expect(body).not.toContain('"first"')
+ expect(body).toContain(SSE_EVENT_STREAM_END)
+ })
+
+ it('id field in each SSE frame matches the Redis stream ID used for resuming', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'ping' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // The data frame must contain an "id:" line.
+ const frames = body.split('\n\n').filter((f) => f.trim() !== '')
+ const dataFrame = frames.find((f) => f.includes('"ping"'))
+ expect(dataFrame).toBeTruthy()
+ const idLine = dataFrame!.split('\n').find((l) => l.startsWith('id:'))
+ expect(idLine).toBeTruthy()
+
+ // The id value must look like a Redis stream ID ("<ms>-<seq>").
+ const idValue = idLine!.slice('id: '.length)
+ expect(idValue).toMatch(/^\d+-\d+$/)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — startLatest
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — startLatest', () => {
+ it('with startLatest=true skips already-written events and reads only new ones', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'old' })
+
+ // Stream the generator; because startLatest=true it reads from the
+ // latest ID. We must add the completion sentinel after the generator
+ // starts waiting so that it sees it. Use a short async delay.
+ const genPromise = (async () => {
+ const chunks: string[] = []
+ const gen = streamTaskRunEvents(streamKey, redis as unknown as Redis, { startLatest: true })
+ for await (const chunk of gen) {
+ chunks.push(chunk.toString('utf8'))
+ }
+ return chunks.join('')
+ })()
+
+ // Let the generator start its XREAD wait, then push new data and complete.
+ await new Promise((r) => setTimeout(r, 50))
+ xaddData(redis, streamKey, { type: 'notification', msg: 'new' })
+ xaddComplete(redis, streamKey)
+
+ const body = await genPromise
+
+ expect(body).not.toContain('"old"')
+ expect(body).toContain('"new"')
+ expect(body).toContain(SSE_EVENT_STREAM_END)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — keepalive emission
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — keepalive emission', () => {
+ it('emits a keepalive SSE event named keepalive with {type:keepalive} payload', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ // Stream is available immediately but has no events yet.
+ xaddData(redis, streamKey, { type: 'PLACEHOLDER' })
+
+ let resolveKeepalive!: (buf: Buffer) => void
+ const keepaliveSeen = new Promise<Buffer>((r) => {
+ resolveKeepalive = r
+ })
+
+ const gen = streamTaskRunEvents(streamKey, redis as unknown as Redis, {})
+
+ // Collect chunks in the background, resolving on the first keepalive frame.
+ const collecting = (async () => {
+ for await (const chunk of gen) {
+ if (chunk.toString('utf8').includes(`event: ${SSE_EVENT_KEEPALIVE}`)) {
+ resolveKeepalive(chunk)
+ break
+ }
+ }
+ })()
+
+ // Advance time past the keepalive threshold to trigger it.
+ await vi.advanceTimersByTimeAsync(KEEPALIVE_INTERVAL_MS + 500)
+ xaddComplete(redis, streamKey)
+
+ const kaBuf = await keepaliveSeen
+ const kaText = kaBuf.toString('utf8')
+ expect(kaText).toContain(`event: ${SSE_EVENT_KEEPALIVE}`)
+ expect(kaText).toContain('"type":"keepalive"')
+
+ await collecting
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — wait-for-stream timeout
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — wait-for-stream timeout', () => {
+ it('emits error event with "Stream not available" when stream never appears', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+ // Do NOT add any entries — stream does not exist.
+
+ const bodyPromise = collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // Advance past the 120 s wait timeout.
+ await vi.advanceTimersByTimeAsync(WAIT_TIMEOUT_MS + 1_000)
+
+ const body = await bodyPromise
+
+ expect(body).toContain(`event: ${SSE_EVENT_ERROR}`)
+ expect(body).toContain('Stream not available')
+ })
+
+ it('emits keepalive events while waiting for the stream to appear', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const chunks: string[] = []
+ const gen = streamTaskRunEvents(streamKey, redis as unknown as Redis, {})
+
+ const collecting = (async () => {
+ for await (const chunk of gen) {
+ chunks.push(chunk.toString('utf8'))
+ }
+ })()
+
+ // Advance time by enough to trigger one keepalive during the wait.
+ await vi.advanceTimersByTimeAsync(KEEPALIVE_INTERVAL_MS + 500)
+
+ // Now make the stream appear and complete it so the generator can finish.
+ xaddComplete(redis, streamKey)
+ await vi.advanceTimersByTimeAsync(2_000)
+
+ await collecting
+
+ const body = chunks.join('')
+ expect(body).toContain(`event: ${SSE_EVENT_KEEPALIVE}`)
+ })
+ })
+
+ // -------------------------------------------------------------------------
+ // streamTaskRunEvents — SSE framing invariants over full output
+ // -------------------------------------------------------------------------
+
+ describe('streamTaskRunEvents — framing invariants', () => {
+ it('every SSE frame ends with exactly one blank line', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'a' })
+ xaddData(redis, streamKey, { type: 'notification', msg: 'b' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ // No triple newline (i.e. no empty frame or double blank line).
+ expect(body).not.toContain('\n\n\n')
+ // Body ends with exactly \n\n.
+ expect(body.endsWith('\n\n')).toBe(true)
+ })
+
+ it('each data event frame has exactly one data: line', async () => {
+ // Assertions are inside a for-loop; oxlint's static analyser does not descend into them
+ expect.hasAssertions()
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'single' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ const frames = body.split('\n\n').filter((f) => f.trim() !== '')
+ for (const frame of frames) {
+ const dataLines = frame.split('\n').filter((l) => l.startsWith('data:'))
+ expect(dataLines.length).toBe(1)
+ }
+ })
+ })
+})
diff --git a/services/agent-proxy/tests/lib/jwt.test.ts b/services/agent-proxy/tests/lib/jwt.test.ts
new file mode 100644
index 000000000000..53c60002565e
--- /dev/null
+++ b/services/agent-proxy/tests/lib/jwt.test.ts
@@ -0,0 +1,319 @@
+// Tests for jwt.ts: RS256 key pair generated inline, tokens signed and verified.
+//
+// Coverage mirrors the Python validate_* tests in
+// products/tasks/backend/stream/tests/ adapted for the Node JWT helpers.
+
+import { SignJWT, exportSPKI, generateKeyPair } from 'jose'
+import { describe, it, expect, beforeAll } from 'vitest'
+
+import { SANDBOX_EVENT_INGEST_AUDIENCE, STREAM_READ_AUDIENCE } from '@/lib/constants.js'
+import { loadPublicKeys, validateSandboxEventIngestToken, validateStreamReadToken } from '@/lib/jwt.js'
+
+// ---------------------------------------------------------------------------
+// Shared key-pair fixture
+// ---------------------------------------------------------------------------
+
+interface KeyPairFixture {
+ privateKey: CryptoKey
+ alternatePrivateKey: CryptoKey
+ // Default trusted set the validators receive: the primary key only.
+ publicKeys: CryptoKey[]
+ primaryPublicKey: CryptoKey
+ alternatePublicKey: CryptoKey
+}
+
+let keys: KeyPairFixture
+
+beforeAll(async () => {
+ const primary = await generateKeyPair('RS256', { extractable: true })
+ const alternate = await generateKeyPair('RS256', { extractable: true })
+
+ const [primaryPublicKey, alternatePublicKey] = await loadPublicKeys([
+ await exportSPKI(primary.publicKey),
+ await exportSPKI(alternate.publicKey),
+ ])
+ if (!primaryPublicKey || !alternatePublicKey) {
+ throw new Error('failed to load test public keys')
+ }
+
+ keys = {
+ privateKey: primary.privateKey,
+ alternatePrivateKey: alternate.privateKey,
+ publicKeys: [primaryPublicKey],
+ primaryPublicKey,
+ alternatePublicKey,
+ }
+})
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+interface TokenOptions {
+ audience?: string
+ runId?: string
+ taskId?: string
+ teamId?: unknown
+ expiresIn?: string
+ omitExp?: boolean
+ signingKey?: CryptoKey
+}
+
+async function signToken(opts: TokenOptions = {}): Promise<string> {
+ const {
+ audience = STREAM_READ_AUDIENCE,
+ runId = 'run-abc-123',
+ taskId = 'task-abc-123',
+ teamId = 42,
+ expiresIn = '1h',
+ omitExp = false,
+ signingKey,
+ } = opts
+
+ const builder = new SignJWT({ run_id: runId, task_id: taskId, team_id: teamId }).setProtectedHeader({
+ alg: 'RS256',
+ })
+
+ if (audience) {
+ builder.setAudience(audience)
+ }
+ if (!omitExp) {
+ builder.setExpirationTime(expiresIn)
+ }
+
+ return builder.sign(signingKey ?? keys.privateKey)
+}
+
+// ---------------------------------------------------------------------------
+// stream_read tokens
+// ---------------------------------------------------------------------------
+
+describe('jwt', () => {
+ describe('validateStreamReadToken', () => {
+ it('verifies a valid stream_read token', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE })
+ const payload = await validateStreamReadToken(token, keys.publicKeys)
+
+ expect(payload.runId).toBe('run-abc-123')
+ expect(payload.taskId).toBe('task-abc-123')
+ expect(payload.teamId).toBe(42)
+ })
+
+ it('rejects a token with the wrong audience (sandbox_event_ingest)', async () => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects an expired token', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, expiresIn: '-1s' })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects a token signed with a different private key (bad signature)', async () => {
+ const token = await signToken({
+ audience: STREAM_READ_AUDIENCE,
+ signingKey: keys.alternatePrivateKey,
+ })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects a plainly malformed token string', async () => {
+ await expect(validateStreamReadToken('not.a.jwt', keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects when run_id claim is not a string', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, runId: 999 as unknown as string })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('run_id must be a string')
+ })
+
+ it('rejects when task_id claim is not a string', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, taskId: true as unknown as string })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('task_id must be a string')
+ })
+
+ it('rejects when team_id claim is a float', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, teamId: 1.5 })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('team_id must be an integer')
+ })
+
+ it('rejects when team_id claim is a string', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, teamId: '42' })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('team_id must be an integer')
+ })
+
+ it('rejects when team_id claim is null', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, teamId: null })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('team_id must be an integer')
+ })
+
+ it('rejects when team_id claim is a boolean', async () => {
+ // Number.isInteger(true) is false because typeof true === 'boolean'
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, teamId: true })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow('team_id must be an integer')
+ })
+ })
+
+ // ---------------------------------------------------------------------------
+ // sandbox_event_ingest tokens
+ // ---------------------------------------------------------------------------
+
+ describe('validateSandboxEventIngestToken', () => {
+ it('verifies a valid sandbox_event_ingest token', async () => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE })
+ const payload = await validateSandboxEventIngestToken(token, keys.publicKeys)
+
+ expect(payload.runId).toBe('run-abc-123')
+ expect(payload.taskId).toBe('task-abc-123')
+ expect(payload.teamId).toBe(42)
+ })
+
+ it('rejects a token with the wrong audience (stream_read)', async () => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects an expired token', async () => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, expiresIn: '-1s' })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects a token signed with a different private key (bad signature)', async () => {
+ const token = await signToken({
+ audience: SANDBOX_EVENT_INGEST_AUDIENCE,
+ signingKey: keys.alternatePrivateKey,
+ })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects a plainly malformed token string', async () => {
+ await expect(validateSandboxEventIngestToken('header.payload', keys.publicKeys)).rejects.toThrow(Error)
+ })
+
+ it('rejects when run_id claim is not a string', async () => {
+ const token = await signToken({
+ audience: SANDBOX_EVENT_INGEST_AUDIENCE,
+ runId: 0 as unknown as string,
+ })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(
+ 'run_id must be a string'
+ )
+ })
+
+ it('rejects when task_id claim is not a string', async () => {
+ const token = await signToken({
+ audience: SANDBOX_EVENT_INGEST_AUDIENCE,
+ taskId: null as unknown as string,
+ })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(
+ 'task_id must be a string'
+ )
+ })
+
+ it('rejects when team_id claim is a float', async () => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, teamId: 42.7 })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(
+ 'team_id must be an integer'
+ )
+ })
+
+ it('rejects when team_id claim is missing', async () => {
+ // Build a token without team_id using a raw builder
+ const token = await new SignJWT({ run_id: 'r', task_id: 't' })
+ .setProtectedHeader({ alg: 'RS256' })
+ .setAudience(SANDBOX_EVENT_INGEST_AUDIENCE)
+ .setExpirationTime('1h')
+ .sign(keys.privateKey)
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(
+ 'team_id must be an integer'
+ )
+ })
+ })
+
+ // ---------------------------------------------------------------------------
+ // Key rotation: a token signed under the secondary key still verifies
+ // ---------------------------------------------------------------------------
+
+ describe('key rotation', () => {
+ it('accepts a token signed with the secondary key when both keys are trusted', async () => {
+ const token = await signToken({
+ audience: STREAM_READ_AUDIENCE,
+ signingKey: keys.alternatePrivateKey,
+ })
+
+ // Verifying against the primary alone fails (the bad-signature case above)...
+ await expect(validateStreamReadToken(token, [keys.primaryPublicKey])).rejects.toThrow(Error)
+ // ...but verifying against [primary, secondary] succeeds — zero-downtime rotation.
+ const payload = await validateStreamReadToken(token, [keys.primaryPublicKey, keys.alternatePublicKey])
+ expect(payload.runId).toBe('run-abc-123')
+ })
+
+ it('still rejects an expired token even when multiple keys are trusted', async () => {
+ const token = await signToken({
+ audience: STREAM_READ_AUDIENCE,
+ signingKey: keys.alternatePrivateKey,
+ expiresIn: '-1s',
+ })
+
+ await expect(
+ validateStreamReadToken(token, [keys.primaryPublicKey, keys.alternatePublicKey])
+ ).rejects.toThrow(Error)
+ })
+ })
+
+ // ---------------------------------------------------------------------------
+ // loadPublicKeys / normalization
+ // ---------------------------------------------------------------------------
+
+ describe('loadPublicKeys', () => {
+ it('loads valid SPKI PEMs and returns CryptoKeys', async () => {
+ const { publicKey: rawPub } = await generateKeyPair('RS256', { extractable: true })
+ const spki = await exportSPKI(rawPub)
+ const [key] = await loadPublicKeys([spki])
+
+ expect(key).toBeTruthy()
+ expect(key?.type).toBe('public')
+ })
+
+ it('keys loaded from PEM verify tokens signed by the matching private key', async () => {
+ const { privateKey: pk, publicKey: rawPub } = await generateKeyPair('RS256', { extractable: true })
+ const spki = await exportSPKI(rawPub)
+ const loadedKeys = await loadPublicKeys([spki])
+
+ const token = await new SignJWT({ run_id: 'r', task_id: 't', team_id: 1 })
+ .setProtectedHeader({ alg: 'RS256' })
+ .setAudience(STREAM_READ_AUDIENCE)
+ .setExpirationTime('1h')
+ .sign(pk)
+
+ const payload = await validateStreamReadToken(token, loadedKeys)
+ expect(payload.runId).toBe('r')
+ })
+
+ it('rejects a PEM with literal backslash-n sequences (not normalized)', async () => {
+ // A PEM with \\n instead of real newlines is invalid unless normalized first.
+ // loadPublicKeys expects pre-normalized PEMs (normalizePemKey is called in config.ts
+ // before the keys reach loadPublicKeys).
+ const { publicKey: rawPub } = await generateKeyPair('RS256', { extractable: true })
+ const spki = await exportSPKI(rawPub)
+ const broken = spki.replace(/\n/g, '\\n')
+
+ await expect(loadPublicKeys([broken])).rejects.toThrow(Error)
+ })
+ })
+})
diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.ts
new file mode 100644
index 000000000000..fe312697e11b
--- /dev/null
+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts
@@ -0,0 +1,1255 @@
+// Tests for TaskRunRedisStream.
+//
+// Wire protocol must stay byte-identical to the Python implementation in
+// products/tasks/backend/stream/redis_stream.py. Both sides share the same
+// Redis stream during the cutover window; any drift corrupts live runs.
+//
+// Uses a small in-memory fake instead of ioredis-mock to avoid an extra
+// dependency. The fake implements the subset of the Redis API that
+// TaskRunRedisStream calls (XADD, XRANGE, XREVRANGE, XREAD, XLEN, GET, SET,
+// EXISTS, EXPIRE, DEL, WATCH, UNWATCH, MULTI/EXEC).
+
+import { describe, it, expect } from 'vitest'
+
+import {
+ TaskRunRedisStream,
+ getStreamKey,
+ getSequenceKey,
+ getCompletedKey,
+ getAgentActiveKey,
+ getHeartbeatKey,
+} from '@/lib/redis-stream.js'
+import {
+ TaskRunStreamError,
+ TaskRunStreamSequenceGap,
+ TaskRunStreamAlreadyCompleted,
+ TaskRunStreamCompletionSequenceMismatch,
+} from '@/lib/types.js'
+
+// ---------------------------------------------------------------------------
+// In-memory Redis fake
+// ---------------------------------------------------------------------------
+
+interface StreamEntry {
+ id: string
+ fields: Record<string, string>
+}
+
+type ExpiryMs = number
+
+class FakeRedis {
+ private _strings: Map<string, string> = new Map()
+ private _expiry: Map<string, ExpiryMs> = new Map()
+ private _streams: Map<string, StreamEntry[]> = new Map()
+ private _streamExpiry: Map<string, ExpiryMs> = new Map()
+ private _watchedKeys: Set<string> = new Set()
+ private _watchDirty = false
+ private _nextSeq = 0
+ private _xaddCallCount = 0
+ private _expireCallCount = 0
+
+ // Counters exposed for TTL/MAXLEN assertions
+ get xaddCallCount(): number {
+ return this._xaddCallCount
+ }
+ get expireCallCount(): number {
+ return this._expireCallCount
+ }
+
+ private _isExpired(key: string): boolean {
+ const exp = this._expiry.get(key)
+ if (exp === undefined) {
+ return false
+ }
+ return Date.now() > exp
+ }
+
+ private _generateId(): string {
+ return `${Date.now()}-${this._nextSeq++}`
+ }
+
+ // Simulate a concurrent write that makes the WATCHed keys dirty.
+ simulateWatchConflict(): void {
+ this._watchDirty = true
+ }
+
+ async get(key: string): Promise<string | null> {
+ if (this._isExpired(key)) {
+ this._strings.delete(key)
+ this._expiry.delete(key)
+ return null
+ }
+ return this._strings.get(key) ?? null
+ }
+
+ async set(key: string, value: string | number, ...args: unknown[]): Promise<string> {
+ const strValue = String(value)
+ // Parse optional EX/NX flags
+ let ex: number | null = null
+ let nx = false
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]
+ if (arg === 'EX') {
+ ex = Number(args[i + 1])
+ i++
+ } else if (arg === 'NX') {
+ nx = true
+ }
+ }
+
+ if (nx && this._strings.has(key) && !this._isExpired(key)) {
+ return 'null' // not set
+ }
+
+ // Dirty any watching on this key
+ if (this._watchedKeys.has(key)) {
+ // Only dirty if this set happens during a WATCH window (handled externally)
+ }
+
+ this._strings.set(key, strValue)
+ if (ex !== null) {
+ this._expiry.set(key, Date.now() + ex * 1000)
+ } else {
+ this._expiry.delete(key)
+ }
+
+ // Return 'OK' for normal set, 'null' for NX miss (already handled above)
+ return 'OK'
+ }
+
+ async exists(...keys: string[]): Promise<number> {
+ let count = 0
+ for (const key of keys) {
+ if (this._strings.has(key) && !this._isExpired(key)) {
+ count++
+ }
+ if (this._streams.has(key)) {
+ count++
+ }
+ }
+ return count
+ }
+
+ async expire(key: string, seconds: number): Promise<number> {
+ this._expireCallCount++
+ const hasString = this._strings.has(key) && !this._isExpired(key)
+ const hasStream = this._streams.has(key)
+ if (!hasString && !hasStream) {
+ return 0
+ }
+ const expMs = Date.now() + seconds * 1000
+ if (hasString) {
+ this._expiry.set(key, expMs)
+ }
+ if (hasStream) {
+ this._streamExpiry.set(key, expMs)
+ }
+ return 1
+ }
+
+ async del(...keys: string[]): Promise<number> {
+ let count = 0
+ for (const key of keys) {
+ if (this._strings.delete(key)) {
+ count++
+ }
+ this._expiry.delete(key)
+ if (this._streams.delete(key)) {
+ count++
+ }
+ this._streamExpiry.delete(key)
+ }
+ return count
+ }
+
+ async xadd(key: string, ...args: unknown[]): Promise<string | null> {
+ this._xaddCallCount++
+ // Parse: MAXLEN ~ N * 'data' value
+ let i = 0
+ while (i < args.length && args[i] !== '*') {
+ i++
+ }
+ i++ // skip '*'
+
+ const fields: Record<string, string> = {}
+ while (i < args.length - 1) {
+ const fieldKey = String(args[i])
+ const fieldVal = String(args[i + 1])
+ fields[fieldKey] = fieldVal
+ i += 2
+ }
+
+ const id = this._generateId()
+ if (!this._streams.has(key)) {
+ this._streams.set(key, [])
+ }
+ this._streams.get(key)!.push({ id, fields })
+ return id
+ }
+
+ async xlen(key: string): Promise<number> {
+ return this._streams.get(key)?.length ?? 0
+ }
+
+ async xrange(key: string, start: string, end: string, ...args: unknown[]): Promise<Array<[string, string[]]>> {
+ const entries = this._streams.get(key) ?? []
+ let count: number | null = null
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === 'COUNT') {
+ count = Number(args[i + 1])
+ break
+ }
+ }
+ const result = entries
+ .filter((e) => {
+ if (start === '-') {
+ return true
+ }
+ return this._streamIdGte(e.id, start)
+ })
+ .filter((e) => {
+ if (end === '+') {
+ return true
+ }
+ return this._streamIdLte(e.id, end)
+ })
+ .slice(0, count ?? undefined)
+ return result.map((e) => [e.id, this._flattenFields(e.fields)])
+ }
+
+ async xrevrange(key: string, end: string, start: string, ...args: unknown[]): Promise<Array<[string, string[]]>> {
+ const entries = this._streams.get(key) ?? []
+ let count: number | null = null
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === 'COUNT') {
+ count = Number(args[i + 1])
+ break
+ }
+ }
+ const filtered = entries
+ .filter((e) => {
+ if (start === '-') {
+ return true
+ }
+ return this._streamIdGte(e.id, start)
+ })
+ .filter((e) => {
+ if (end === '+') {
+ return true
+ }
+ return this._streamIdLte(e.id, end)
+ })
+ const reversed = [...filtered].reverse().slice(0, count ?? undefined)
+ return reversed.map((e) => [e.id, this._flattenFields(e.fields)])
+ }
+
+ // Controlled XREAD for test scenarios: reads synchronously, no blocking.
+ // Returns messages newer than lastId.
+ async xread(...args: unknown[]): Promise<Array<[string, Array<[string, string[]]>]> | null> {
+ let streamKey = ''
+ let lastId = '0'
+ let count = 16
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === 'COUNT') {
+ count = Number(args[i + 1])
+ i++
+ } else if (args[i] === 'BLOCK') {
+ i++ // skip the ms value
+ } else if (args[i] === 'STREAMS') {
+ streamKey = String(args[i + 1])
+ lastId = String(args[i + 2])
+ break
+ }
+ }
+
+ const entries = this._streams.get(streamKey) ?? []
+ const newer = entries
+ .filter((e) => {
+ if (lastId === '0' || lastId === '0-0') {
+ return true
+ }
+ return this._streamIdGt(e.id, lastId)
+ })
+ .slice(0, count)
+
+ if (newer.length === 0) {
+ return null
+ }
+
+ return [[streamKey, newer.map((e) => [e.id, this._flattenFields(e.fields)])]]
+ }
+
+ async watch(...keys: string[]): Promise<'OK'> {
+ for (const k of keys) {
+ this._watchedKeys.add(k)
+ }
+ this._watchDirty = false
+ return 'OK'
+ }
+
+ async unwatch(): Promise<'OK'> {
+ this._watchedKeys.clear()
+ this._watchDirty = false
+ return 'OK'
+ }
+
+ multi(): FakePipeline {
+ const dirty = this._watchDirty
+ this._watchedKeys.clear()
+ this._watchDirty = false
+ return new FakePipeline(this, dirty)
+ }
+
+ // Helper to mark keys dirty (used internally by the pipeline on commit)
+ _markKeyDirty(key: string): void {
+ if (this._watchedKeys.has(key)) {
+ this._watchDirty = true
+ }
+ }
+
+ // Expose streams for direct inspection in tests
+ getStreamEntries(key: string): StreamEntry[] {
+ return this._streams.get(key) ?? []
+ }
+
+ getStringValue(key: string): string | null {
+ if (this._isExpired(key)) {
+ return null
+ }
+ return this._strings.get(key) ?? null
+ }
+
+ getExpiryMs(key: string): number | null {
+ // Check both string expiry and stream expiry maps
+ const strExp = this._expiry.get(key)
+ const streamExp = this._streamExpiry.get(key)
+ if (strExp !== undefined && streamExp !== undefined) {
+ return Math.max(strExp, streamExp)
+ }
+ if (strExp !== undefined) {
+ return strExp
+ }
+ if (streamExp !== undefined) {
+ return streamExp
+ }
+ return null
+ }
+
+ // Read all 'data' field values from the stream as parsed JSON
+ readStreamData(key: string): Array<Record<string, unknown>> {
+ return this.getStreamEntries(key).map((e) => JSON.parse(e.fields['data'] ?? '{}') as Record<string, unknown>)
+ }
+
+ private _parseId(id: string): [number, number] {
+ const dash = id.indexOf('-')
+ if (dash === -1) {
+ const ms = parseInt(id, 10)
+ return Number.isNaN(ms) ? [0, 0] : [ms, 0]
+ }
+ const ms = parseInt(id.slice(0, dash), 10)
+ const seq = parseInt(id.slice(dash + 1), 10)
+ if (Number.isNaN(ms) || Number.isNaN(seq)) {
+ return [0, 0]
+ }
+ return [ms, seq]
+ }
+
+ private _cmp(a: string, b: string): number {
+ const [ams, aseq] = this._parseId(a)
+ const [bms, bseq] = this._parseId(b)
+ if (ams !== bms) {
+ return ams - bms
+ }
+ return aseq - bseq
+ }
+
+ private _streamIdGte(a: string, b: string): boolean {
+ return this._cmp(a, b) >= 0
+ }
+ private _streamIdLte(a: string, b: string): boolean {
+ return this._cmp(a, b) <= 0
+ }
+ private _streamIdGt(a: string, b: string): boolean {
+ return this._cmp(a, b) > 0
+ }
+
+ private _flattenFields(fields: Record<string, string>): string[] {
+ const flat: string[] = []
+ for (const [k, v] of Object.entries(fields)) {
+ flat.push(k, v)
+ }
+ return flat
+ }
+}
+
+class FakePipeline {
+ private _ops: Array<() => Promise<[Error | null, unknown]>> = []
+
+ constructor(
+ private readonly _redis: FakeRedis,
+ private readonly _dirty: boolean
+ ) {}
+
+ xadd(key: string, ...args: unknown[]): this {
+ this._ops.push(() => this._redis.xadd(key, ...args).then((v) => [null, v]))
+ return this
+ }
+
+ expire(key: string, seconds: number): this {
+ this._ops.push(() => this._redis.expire(key, seconds).then((v) => [null, v]))
+ return this
+ }
+
+ set(key: string, value: string | number, ...args: unknown[]): this {
+ this._ops.push(() => this._redis.set(key, value, ...args).then((v) => [null, v]))
+ return this
+ }
+
+ async exec(): Promise<Array<[Error | null, unknown]> | null> {
+ if (this._dirty) {
+ return null // WATCH conflict
+ }
+ const results: Array<[Error | null, unknown]> = []
+ for (const op of this._ops) {
+ results.push(await op())
+ }
+ return results
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Test helpers
+// ---------------------------------------------------------------------------
+
+let _runCounter = 0
+
+function newStream(redis?: FakeRedis): { stream: TaskRunRedisStream; redis: FakeRedis; streamKey: string } {
+ const r = redis ?? new FakeRedis()
+ _runCounter++
+ const runId = `test-run-${_runCounter}`
+ const streamKey = getStreamKey(runId)
+ const stream = new TaskRunRedisStream(streamKey, r as unknown as import('ioredis').Redis, { timeout: 60 })
+ return { stream, redis: r, streamKey }
+}
+
+// Drain the async generator into an array. Stops at the first null (keepalive)
+// if stopOnKeepalive=true; otherwise collects everything.
+async function drainEntries(
+ gen: AsyncGenerator<import('@/lib/types.js').StreamEntryOrKeepalive>,
+ opts?: { maxItems?: number }
+): Promise<Array<[string, Record<string, unknown>] | null>> {
+ const result: Array<[string, Record<string, unknown>] | null> = []
+ const max = opts?.maxItems ?? 1000
+ for await (const item of gen) {
+ result.push(item)
+ if (result.length >= max) {
+ break
+ }
+ }
+ return result
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('redis-stream', () => {
+ // -----------------------------------------------------------------------
+ // Key helpers
+ // -----------------------------------------------------------------------
+
+ describe('key helpers', () => {
+ it('produces byte-identical keys to the Python implementation', () => {
+ const runId = 'abc-123'
+ const streamKey = getStreamKey(runId)
+ expect(streamKey).toBe('task-run-stream:abc-123')
+ expect(getSequenceKey(streamKey)).toBe('task-run-stream:abc-123:last-seq')
+ expect(getCompletedKey(streamKey)).toBe('task-run-stream:abc-123:completed')
+ expect(getAgentActiveKey(streamKey)).toBe('task-run-stream:abc-123:ingest-agent-active')
+ expect(getHeartbeatKey(streamKey)).toBe('task-run-stream:abc-123:ingest-heartbeat')
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // writeEventWithSequence — sequencing state machine
+ // -----------------------------------------------------------------------
+
+ describe('writeEventWithSequence', () => {
+ it('accepts seq=1 as the first event (seq=0 is the initial sentinel)', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ const id = await stream.writeEventWithSequence({ type: 'msg' }, 1)
+
+ expect(id).not.toBeNull()
+ expect(typeof id).toBe('string')
+ expect(id!.length).toBeGreaterThan(0)
+ // last-seq key updated
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('1')
+ // event written to stream
+ const data = redis.readStreamData(streamKey)
+ expect(data).toHaveLength(1)
+ expect(data[0]).toEqual({ type: 'msg' })
+ })
+
+ it('accepts consecutive sequences and advances last-seq', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ const id1 = await stream.writeEventWithSequence({ type: 'a' }, 1)
+ const id2 = await stream.writeEventWithSequence({ type: 'b' }, 2)
+ const id3 = await stream.writeEventWithSequence({ type: 'c' }, 3)
+
+ expect(id1).not.toBeNull()
+ expect(id2).not.toBeNull()
+ expect(id3).not.toBeNull()
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('3')
+ expect(redis.readStreamData(streamKey)).toHaveLength(3)
+ })
+
+ it('returns null for a duplicate sequence (already accepted)', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ const first = await stream.writeEventWithSequence({ type: 'first' }, 1)
+ const dup = await stream.writeEventWithSequence({ type: 'duplicate' }, 1)
+
+ expect(first).not.toBeNull()
+ expect(dup).toBeNull()
+ // Only the original event in stream
+ const data = redis.readStreamData(streamKey)
+ expect(data).toHaveLength(1)
+ expect(data[0]).toEqual({ type: 'first' })
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('1')
+ })
+
+ it('returns null for seq=0 (treated as already accepted / initial sentinel)', async () => {
+ const { stream } = newStream()
+
+ const result = await stream.writeEventWithSequence({ type: 'zero' }, 0)
+
+ expect(result).toBeNull()
+ })
+
+ it('throws TaskRunStreamSequenceGap when seq skips ahead', async () => {
+ const { stream } = newStream()
+
+ await expect(stream.writeEventWithSequence({ type: 'msg' }, 2)).rejects.toThrow(TaskRunStreamSequenceGap)
+ })
+
+ it('carries correct gap metadata: expectedSequence, receivedSequence, lastAcceptedSeq', async () => {
+ const { stream } = newStream()
+
+ let err: TaskRunStreamSequenceGap | undefined
+ try {
+ await stream.writeEventWithSequence({ type: 'msg' }, 3)
+ } catch (e) {
+ err = e as TaskRunStreamSequenceGap
+ }
+
+ expect(err).toBeInstanceOf(TaskRunStreamSequenceGap)
+ expect(err!.expectedSequence).toBe(1)
+ expect(err!.receivedSequence).toBe(3)
+ expect(err!.lastAcceptedSeq).toBe(0)
+ })
+
+ it('throws TaskRunStreamSequenceGap with correct last-seq after some events are written', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ await stream.writeEventWithSequence({ type: 'b' }, 2)
+
+ let err: TaskRunStreamSequenceGap | undefined
+ try {
+ await stream.writeEventWithSequence({ type: 'x' }, 5)
+ } catch (e) {
+ err = e as TaskRunStreamSequenceGap
+ }
+
+ expect(err).toBeInstanceOf(TaskRunStreamSequenceGap)
+ expect(err!.expectedSequence).toBe(3)
+ expect(err!.receivedSequence).toBe(5)
+ expect(err!.lastAcceptedSeq).toBe(2)
+ })
+
+ it('throws TaskRunStreamAlreadyCompleted when stream is complete', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'msg' }, 1)
+ await stream.markCompleteAfterSequence(1)
+
+ await expect(stream.writeEventWithSequence({ type: 'late' }, 2)).rejects.toThrow(
+ TaskRunStreamAlreadyCompleted
+ )
+ })
+
+ it('carries lastAcceptedSeq on TaskRunStreamAlreadyCompleted', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ await stream.writeEventWithSequence({ type: 'b' }, 2)
+ await stream.markCompleteAfterSequence(2)
+
+ let err: TaskRunStreamAlreadyCompleted | undefined
+ try {
+ await stream.writeEventWithSequence({ type: 'late' }, 3)
+ } catch (e) {
+ err = e as TaskRunStreamAlreadyCompleted
+ }
+
+ expect(err).toBeInstanceOf(TaskRunStreamAlreadyCompleted)
+ expect(err!.lastAcceptedSeq).toBe(2)
+ })
+
+ it('applies MAXLEN on every XADD', async () => {
+ const { stream, redis } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ // The xaddCallCount tracks that XADD is called
+ // (MAXLEN ~ flag is included in the pipeline args)
+ expect(redis.xaddCallCount).toBeGreaterThanOrEqual(1)
+ })
+
+ it('refreshes stream TTL on every accepted write', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ // EXPIRE should have been called on the stream key
+ const exp = redis.getExpiryMs(streamKey)
+ expect(exp).not.toBeNull()
+ // Should expire roughly 60 seconds from now (stream timeout)
+ expect(exp!).toBeGreaterThan(Date.now() + 50_000)
+ })
+
+ it('sets last-seq key with TTL = sequenceTimeout on accept', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ const seqExp = redis.getExpiryMs(getSequenceKey(streamKey))
+ expect(seqExp).not.toBeNull()
+ // sequenceTimeout >= timeout (60s), so expiry must be in the future
+ expect(seqExp!).toBeGreaterThan(Date.now())
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // markComplete
+ // -----------------------------------------------------------------------
+
+ describe('markComplete', () => {
+ it('writes the completion sentinel to the stream', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markComplete()
+
+ const data = redis.readStreamData(streamKey)
+ expect(data).toHaveLength(1)
+ expect(data[0]).toEqual({ type: 'STREAM_STATUS', status: 'complete' })
+ })
+
+ it('sets the completed key to "1"', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markComplete()
+
+ expect(redis.getStringValue(getCompletedKey(streamKey))).toBe('1')
+ })
+
+ it('is idempotent: second call is a no-op', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markComplete()
+ await stream.markComplete()
+
+ // Sentinel written only once
+ const data = redis.readStreamData(streamKey)
+ expect(data).toHaveLength(1)
+ })
+
+ it('refreshes stream TTL on completion', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markComplete()
+
+ const exp = redis.getExpiryMs(streamKey)
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeGreaterThan(Date.now())
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // markCompleteAfterSequence
+ // -----------------------------------------------------------------------
+
+ describe('markCompleteAfterSequence', () => {
+ it('succeeds when finalSequence matches last-seq', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'msg' }, 1)
+ await stream.markCompleteAfterSequence(1)
+
+ const data = redis.readStreamData(streamKey)
+ const sentinel = data.find((d) => d['type'] === 'STREAM_STATUS')
+ expect(sentinel).toEqual({ type: 'STREAM_STATUS', status: 'complete' })
+ expect(redis.getStringValue(getCompletedKey(streamKey))).toBe('1')
+ })
+
+ it('throws TaskRunStreamCompletionSequenceMismatch when finalSequence != last-seq', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'msg' }, 1)
+
+ await expect(stream.markCompleteAfterSequence(2)).rejects.toThrow(TaskRunStreamCompletionSequenceMismatch)
+ })
+
+ it('carries correct metadata on mismatch: finalSequence and lastAcceptedSeq', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+
+ let err: TaskRunStreamCompletionSequenceMismatch | undefined
+ try {
+ await stream.markCompleteAfterSequence(5)
+ } catch (e) {
+ err = e as TaskRunStreamCompletionSequenceMismatch
+ }
+
+ expect(err).toBeInstanceOf(TaskRunStreamCompletionSequenceMismatch)
+ expect(err!.finalSequence).toBe(5)
+ expect(err!.lastAcceptedSeq).toBe(1)
+ })
+
+ it('is idempotent: second call returns without writing another sentinel', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'msg' }, 1)
+ await stream.markCompleteAfterSequence(1)
+ await stream.markCompleteAfterSequence(1)
+
+ // Only the original event + one sentinel
+ const data = redis.readStreamData(streamKey)
+ const sentinels = data.filter((d) => d['type'] === 'STREAM_STATUS')
+ expect(sentinels).toHaveLength(1)
+ })
+
+ it('only EXPIREs last-seq when the key existed before the transaction', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ // finalSequence=0 with no prior events: last-seq key does not exist
+ await stream.markCompleteAfterSequence(0)
+
+ // The completed key was set regardless
+ expect(redis.getStringValue(getCompletedKey(streamKey))).toBe('1')
+ // last-seq key should not have been created by the EXPIRE call
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBeNull()
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // markError
+ // -----------------------------------------------------------------------
+
+ describe('markError', () => {
+ it('writes an error sentinel to the stream', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markError('something went wrong')
+
+ const data = redis.readStreamData(streamKey)
+ expect(data).toHaveLength(1)
+ expect(data[0]).toEqual({ type: 'STREAM_STATUS', status: 'error', error: 'something went wrong' })
+ })
+
+ it('truncates error messages longer than 500 chars', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ const longError = 'x'.repeat(600)
+ await stream.markError(longError)
+
+ const data = redis.readStreamData(streamKey)
+ const error = data[0]?.['error']
+ expect(typeof error).toBe('string')
+ expect((error as string).length).toBe(500)
+ })
+
+ it('refreshes stream TTL when writing the error sentinel', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markError('oops')
+
+ const exp = redis.getExpiryMs(streamKey)
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeGreaterThan(Date.now())
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // setAgentActive / getAgentActive
+ // -----------------------------------------------------------------------
+
+ describe('agent-active flag', () => {
+ it('setAgentActive(true) stores "1" in Redis', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.setAgentActive(true)
+
+ expect(redis.getStringValue(getAgentActiveKey(streamKey))).toBe('1')
+ })
+
+ it('setAgentActive(false) stores "0" in Redis', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.setAgentActive(false)
+
+ expect(redis.getStringValue(getAgentActiveKey(streamKey))).toBe('0')
+ })
+
+ it('getAgentActive returns true when value is "1"', async () => {
+ const { stream } = newStream()
+
+ await stream.setAgentActive(true)
+
+ expect(await stream.getAgentActive()).toBe(true)
+ })
+
+ it('getAgentActive returns false when value is "0"', async () => {
+ const { stream } = newStream()
+
+ await stream.setAgentActive(false)
+
+ expect(await stream.getAgentActive()).toBe(false)
+ })
+
+ it('getAgentActive returns false when key is absent', async () => {
+ const { stream } = newStream()
+
+ expect(await stream.getAgentActive()).toBe(false)
+ })
+
+ it('setAgentActive applies a TTL equal to the stream timeout', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.setAgentActive(true)
+
+ const exp = redis.getExpiryMs(getAgentActiveKey(streamKey))
+ expect(exp).not.toBeNull()
+ // 60s timeout -> expiry ~60s from now
+ expect(exp!).toBeGreaterThan(Date.now() + 50_000)
+ expect(exp!).toBeLessThan(Date.now() + 70_000)
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // claimAgentActiveHeartbeat
+ // -----------------------------------------------------------------------
+
+ describe('claimAgentActiveHeartbeat', () => {
+ it('returns true on first claim (key absent)', async () => {
+ const { stream } = newStream()
+
+ const claimed = await stream.claimAgentActiveHeartbeat(30)
+
+ expect(claimed).toBe(true)
+ })
+
+ it('returns false when the heartbeat key already exists', async () => {
+ const { stream } = newStream()
+
+ // First claim succeeds, second must fail (NX)
+ const first = await stream.claimAgentActiveHeartbeat(30)
+ const second = await stream.claimAgentActiveHeartbeat(30)
+
+ expect(first).toBe(true)
+ expect(second).toBe(false)
+ })
+
+ it('sets the heartbeat key with the given throttle EX', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.claimAgentActiveHeartbeat(30)
+
+ const exp = redis.getExpiryMs(getHeartbeatKey(streamKey))
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeGreaterThan(Date.now() + 25_000)
+ expect(exp!).toBeLessThan(Date.now() + 35_000)
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // resumePointTrimmed + detectResumeGap
+ // -----------------------------------------------------------------------
+
+ describe('resumePointTrimmed', () => {
+ it('returns false for empty string cursor', async () => {
+ const { stream, redis, streamKey } = newStream()
+ await redis.xadd(streamKey, 'MAXLEN', '~', 20000, '*', 'data', '{}')
+
+ expect(await stream.resumePointTrimmed('')).toBe(false)
+ })
+
+ it('returns false for "0" cursor', async () => {
+ const { stream, redis, streamKey } = newStream()
+ await redis.xadd(streamKey, 'MAXLEN', '~', 20000, '*', 'data', '{}')
+
+ expect(await stream.resumePointTrimmed('0')).toBe(false)
+ })
+
+ it('returns false when stream is empty', async () => {
+ const { stream } = newStream()
+
+ expect(await stream.resumePointTrimmed('100-0')).toBe(false)
+ })
+
+ it('returns false when cursor is still inside the window', async () => {
+ const { stream } = newStream()
+
+ const firstId = await stream.writeEvent({ type: 'a' })
+ await stream.writeEvent({ type: 'b' })
+
+ expect(await stream.resumePointTrimmed(firstId)).toBe(false)
+ })
+
+ it('returns true when cursor predates the oldest surviving entry', async () => {
+ const { stream } = newStream()
+
+ // Add an event that gets a real timestamp-based ID
+ await stream.writeEvent({ type: 'a' })
+
+ // Cursor "1-0" is older than any real Redis ID (timestamp 1ms)
+ expect(await stream.resumePointTrimmed('1-0')).toBe(true)
+ })
+ })
+
+ describe('detectResumeGap', () => {
+ it.each(['0', '0-0', '$', ''])('returns null for fresh/tail start_id=%s', async (startId) => {
+ const { stream } = newStream()
+ await stream.writeEvent({ type: 'msg' })
+
+ expect(await stream.detectResumeGap(startId)).toBeNull()
+ })
+
+ it('returns null when stream is empty', async () => {
+ const { stream } = newStream()
+
+ expect(await stream.detectResumeGap('100-0')).toBeNull()
+ })
+
+ it('returns null when resume point is inside the live window', async () => {
+ const { stream } = newStream()
+
+ const firstId = await stream.writeEvent({ type: 'a' })
+ await stream.writeEvent({ type: 'b' })
+
+ expect(await stream.detectResumeGap(firstId)).toBeNull()
+ })
+
+ it('returns a ResumeGap when cursor predates oldest surviving entry', async () => {
+ const { stream } = newStream()
+
+ const oldestId = await stream.writeEvent({ type: 'msg' })
+
+ const gap = await stream.detectResumeGap('1-0')
+
+ expect(gap).not.toBeNull()
+ expect(gap!.requestedId).toBe('1-0')
+ expect(gap!.oldestAvailableId).toBe(oldestId)
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // readStreamEntries — read loop
+ // -----------------------------------------------------------------------
+
+ describe('readStreamEntries', () => {
+ it('yields normal events and ends (returns) on the complete sentinel', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEvent({ type: 'notification', msg: 'hello' })
+ await stream.markComplete()
+
+ const entries = await drainEntries(stream.readStreamEntries())
+
+ // One real event (no sentinel yielded)
+ expect(entries).toHaveLength(1)
+ const [id, data] = entries[0] as [string, Record<string, unknown>]
+ expect(typeof id).toBe('string')
+ expect(data).toEqual({ type: 'notification', msg: 'hello' })
+ })
+
+ it('never yields the complete sentinel to callers', async () => {
+ const { stream } = newStream()
+
+ await stream.markComplete()
+
+ const entries = await drainEntries(stream.readStreamEntries())
+
+ expect(entries).toHaveLength(0)
+ })
+
+ it('throws TaskRunStreamError on the error sentinel', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEvent({ type: 'first' })
+ await stream.markError('boom')
+
+ await expect(drainEntries(stream.readStreamEntries())).rejects.toThrow(TaskRunStreamError)
+ })
+
+ it('includes the error message from the error sentinel', async () => {
+ const { stream } = newStream()
+
+ await stream.markError('task crashed')
+
+ let err: TaskRunStreamError | undefined
+ try {
+ await drainEntries(stream.readStreamEntries())
+ } catch (e) {
+ err = e as TaskRunStreamError
+ }
+
+ expect(err).toBeInstanceOf(TaskRunStreamError)
+ expect(err!.message).toBe('task crashed')
+ })
+
+ it('yields events written before the error sentinel, then throws', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEvent({ type: 'a' })
+ await stream.writeEvent({ type: 'b' })
+ await stream.markError('oops')
+
+ const collected: Array<[string, Record<string, unknown>] | null> = []
+ let threw = false
+ try {
+ for await (const item of stream.readStreamEntries()) {
+ collected.push(item)
+ }
+ } catch {
+ threw = true
+ }
+
+ expect(threw).toBe(true)
+ // The two real events were yielded before the error
+ expect(collected).toHaveLength(2)
+ })
+
+ it('resumes from a given startId, skipping earlier entries', async () => {
+ const { stream } = newStream()
+
+ const firstId = await stream.writeEvent({ type: 'first' })
+ await stream.writeEvent({ type: 'second' })
+ await stream.markComplete()
+
+ // Resume after the first event
+ const entries = await drainEntries(stream.readStreamEntries({ startId: firstId }))
+
+ expect(entries).toHaveLength(1)
+ const [, data] = entries[0] as [string, Record<string, unknown>]
+ expect(data).toEqual({ type: 'second' })
+ })
+
+ it('yields null (keepalive signal) when idle beyond keepaliveIntervalMs', async () => {
+ const { stream } = newStream()
+
+ // Write the complete sentinel immediately so the loop exits quickly
+ await stream.markComplete()
+
+ // Set a very short keepalive interval; the FakeRedis xread returns null
+ // on empty results so the loop should detect idle and yield null before
+ // seeing the complete sentinel. However since FakeRedis reads all at once,
+ // we validate this via a manual stream with no events first.
+ //
+ // Build a separate stream that only has a complete sentinel but we
+ // interpose an "already idle" situation by checking that the readStreamEntries
+ // signature accepts keepaliveIntervalMs.
+ const { stream: s2 } = newStream()
+ await s2.markComplete()
+
+ // Just confirm null can appear in the output type
+ const gen = s2.readStreamEntries({ keepaliveIntervalMs: 1 })
+ const result = await drainEntries(gen)
+
+ // With FakeRedis synchronous reads, the complete sentinel is found
+ // immediately so no keepalive fires. The test validates the parameter
+ // is accepted and the loop terminates correctly.
+ expect(Array.isArray(result)).toBe(true)
+ })
+
+ it('uses "0" as default startId (reads from beginning)', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEvent({ type: 'first' })
+ await stream.markComplete()
+
+ const entries = await drainEntries(stream.readStreamEntries())
+
+ expect(entries).toHaveLength(1)
+ const [, data] = entries[0] as [string, Record<string, unknown>]
+ expect(data).toEqual({ type: 'first' })
+ })
+
+ it('provides the Redis stream ID as the first element of each entry tuple', async () => {
+ const { stream } = newStream()
+
+ const writtenId = await stream.writeEvent({ type: 'evt' })
+ await stream.markComplete()
+
+ const entries = await drainEntries(stream.readStreamEntries())
+
+ expect(entries).toHaveLength(1)
+ const [readId] = entries[0] as [string, Record<string, unknown>]
+ expect(readId).toBe(writtenId)
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // writeEvent (TTL + MAXLEN)
+ // -----------------------------------------------------------------------
+
+ describe('writeEvent', () => {
+ it('returns a non-empty Redis stream ID string', async () => {
+ const { stream } = newStream()
+
+ const id = await stream.writeEvent({ type: 'test' })
+
+ expect(typeof id).toBe('string')
+ expect(id.length).toBeGreaterThan(0)
+ })
+
+ it('refreshes the stream TTL on every write', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEvent({ type: 'a' })
+ const expAfterFirst = redis.getExpiryMs(streamKey)
+ await stream.writeEvent({ type: 'b' })
+ const expAfterSecond = redis.getExpiryMs(streamKey)
+
+ expect(expAfterFirst).not.toBeNull()
+ expect(expAfterSecond).not.toBeNull()
+ // Both should be ~60s in the future (within a 10s tolerance for test speed)
+ expect(expAfterFirst!).toBeGreaterThan(Date.now() + 50_000)
+ expect(expAfterSecond!).toBeGreaterThan(Date.now() + 50_000)
+ })
+
+ it('uses the "data" field name in the stream entry', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEvent({ type: 'wire-check' })
+
+ const entry = redis.getStreamEntries(streamKey)[0]
+ expect(entry).toBeTruthy()
+ expect(Object.keys(entry!.fields)).toContain('data')
+ const parsed = JSON.parse(entry!.fields['data']!) as Record<string, unknown>
+ expect(parsed).toEqual({ type: 'wire-check' })
+ })
+
+ it('calls XADD with MAXLEN ~ flag for stream trimming', async () => {
+ const { stream, redis } = newStream()
+
+ const before = redis.xaddCallCount
+ await stream.writeEvent({ type: 'x' })
+ const after = redis.xaddCallCount
+
+ expect(after).toBe(before + 1)
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // getLastSequence
+ // -----------------------------------------------------------------------
+
+ describe('getLastSequence', () => {
+ it('returns 0 when no sequence has been set', async () => {
+ const { stream } = newStream()
+
+ expect(await stream.getLastSequence()).toBe(0)
+ })
+
+ it('returns the current last-seq value after writes', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ await stream.writeEventWithSequence({ type: 'b' }, 2)
+
+ expect(await stream.getLastSequence()).toBe(2)
+ })
+
+ it('refreshes the last-seq key TTL on read (sliding window)', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ const seqKey = getSequenceKey(streamKey)
+ const expBefore = redis.getExpiryMs(seqKey)
+
+ await stream.getLastSequence()
+ const expAfter = redis.getExpiryMs(seqKey)
+
+ expect(expBefore).not.toBeNull()
+ expect(expAfter).not.toBeNull()
+ // TTL was refreshed (expAfter >= expBefore)
+ expect(expAfter!).toBeGreaterThanOrEqual(expBefore! - 100) // allow 100ms clock drift
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // exists / initialize
+ // -----------------------------------------------------------------------
+
+ describe('exists and initialize', () => {
+ it('exists() returns false before any writes', async () => {
+ const { stream } = newStream()
+
+ expect(await stream.exists()).toBe(false)
+ })
+
+ it('exists() returns true after a write', async () => {
+ const { stream } = newStream()
+
+ await stream.writeEvent({ type: 'test' })
+
+ expect(await stream.exists()).toBe(true)
+ })
+
+ it('initialize() sets an EXPIRE on the stream key', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEvent({ type: 'x' })
+ await stream.initialize()
+
+ const exp = redis.getExpiryMs(streamKey)
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeGreaterThan(Date.now())
+ })
+ })
+
+ // -----------------------------------------------------------------------
+ // deleteStream
+ // -----------------------------------------------------------------------
+
+ describe('deleteStream', () => {
+ it('returns true and removes all five keys', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEventWithSequence({ type: 'a' }, 1)
+ await stream.setAgentActive(true)
+ await stream.claimAgentActiveHeartbeat(30)
+
+ const deleted = await stream.deleteStream()
+
+ expect(deleted).toBe(true)
+ expect(redis.getStreamEntries(streamKey)).toHaveLength(0)
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBeNull()
+ expect(redis.getStringValue(getCompletedKey(streamKey))).toBeNull()
+ expect(redis.getStringValue(getAgentActiveKey(streamKey))).toBeNull()
+ expect(redis.getStringValue(getHeartbeatKey(streamKey))).toBeNull()
+ })
+
+ it('returns false (no error thrown) when stream does not exist', async () => {
+ const { stream } = newStream()
+
+ // No writes — all keys absent
+ const deleted = await stream.deleteStream()
+
+ // deleted=0 keys, so returns false
+ expect(deleted).toBe(false)
+ })
+ })
+})
diff --git a/services/agent-proxy/tests/lib/stream-capacity.test.ts b/services/agent-proxy/tests/lib/stream-capacity.test.ts
new file mode 100644
index 000000000000..d0087ab2aee7
--- /dev/null
+++ b/services/agent-proxy/tests/lib/stream-capacity.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+
+import { StreamCapacity } from '@/lib/stream-capacity.js'
+
+describe('StreamCapacity', () => {
+ it('acquires until the pod-wide cap and rejects with pod_capacity beyond it', () => {
+ const capacity = new StreamCapacity(2, 10)
+
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-b')).toBeNull()
+ expect(capacity.tryAcquire('run-c')).toBe('pod_capacity')
+ expect(capacity.openTotal).toBe(2)
+ })
+
+ it('rejects with run_capacity when one run reaches its fanout cap', () => {
+ const capacity = new StreamCapacity(10, 2)
+
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-a')).toBe('run_capacity')
+ // Other runs are unaffected by run-a hitting its cap.
+ expect(capacity.tryAcquire('run-b')).toBeNull()
+ })
+
+ it('release frees both the pod-wide and per-run slot', () => {
+ const capacity = new StreamCapacity(1, 1)
+
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-a')).toBe('pod_capacity')
+
+ capacity.release('run-a')
+
+ expect(capacity.openTotal).toBe(0)
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ })
+
+ it('interleaved acquire and release across runs keeps counts consistent', () => {
+ const capacity = new StreamCapacity(3, 2)
+
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ expect(capacity.tryAcquire('run-b')).toBeNull()
+ expect(capacity.tryAcquire('run-b')).toBe('pod_capacity')
+
+ capacity.release('run-a')
+ expect(capacity.tryAcquire('run-b')).toBeNull()
+ expect(capacity.tryAcquire('run-a')).toBe('pod_capacity')
+
+ capacity.release('run-a')
+ capacity.release('run-b')
+ capacity.release('run-b')
+ expect(capacity.openTotal).toBe(0)
+ })
+
+ it('release on an untracked run never goes negative', () => {
+ const capacity = new StreamCapacity(1, 1)
+
+ capacity.release('run-never-acquired')
+
+ expect(capacity.openTotal).toBe(0)
+ expect(capacity.tryAcquire('run-a')).toBeNull()
+ })
+})
diff --git a/services/agent-proxy/tests/setup.ts b/services/agent-proxy/tests/setup.ts
new file mode 100644
index 000000000000..a907f838c947
--- /dev/null
+++ b/services/agent-proxy/tests/setup.ts
@@ -0,0 +1,57 @@
+// Global vitest setup file — loaded via vitest.config.mts setupFiles.
+//
+// Mocks the metrics module so prom-client never tries to register duplicate
+// Counters/Gauges/Histograms across test files that import handler modules.
+// Each handler imports from hono/metrics.js at module load time; without this
+// mock the second test suite that imports a handler would fail with
+// "A metric with that name has already been registered" from prom-client.
+
+import { vi } from 'vitest'
+
+const mockInc = vi.fn()
+const mockDec = vi.fn()
+const mockSet = vi.fn()
+const mockObserve = vi.fn()
+const mockLabels = vi.fn()
+
+// Counters
+const mockCounter = { labels: mockLabels.mockReturnValue({ inc: mockInc }), inc: mockInc }
+// Gauges
+const mockGauge = {
+ labels: mockLabels.mockReturnValue({ inc: mockInc, dec: mockDec, set: mockSet }),
+ inc: mockInc,
+ dec: mockDec,
+ set: mockSet,
+}
+// Histograms
+const mockHistogram = {
+ labels: mockLabels.mockReturnValue({ observe: mockObserve }),
+ observe: mockObserve,
+ startTimer: vi.fn().mockReturnValue(vi.fn()),
+}
+
+vi.mock('@/hono/metrics.js', () => ({
+ register: {
+ metrics: vi.fn().mockResolvedValue(''),
+ contentType: 'text/plain; version=0.0.4; charset=utf-8',
+ },
+ routeLabel: vi.fn((p: string) => p),
+ taskRunStreamConnectionsOpenedTotal: mockCounter,
+ taskRunStreamConnectionsClosedTotal: mockCounter,
+ taskRunStreamConnectionDurationSeconds: mockHistogram,
+ taskRunStreamLengthOnConnect: mockHistogram,
+ taskRunStreamResumeGapTotal: mockCounter,
+ taskRunStreamConnectionsRejectedTotal: mockCounter,
+ streamIngestEventsTotal: mockCounter,
+ httpRequestsTotal: mockCounter,
+ httpRequestDurationSeconds: mockHistogram,
+ inflightRequests: mockGauge,
+ shuttingDown: mockGauge,
+ openSseStreams: mockGauge,
+ observeStreamConnectionOpened: vi.fn(),
+ observeStreamConnectionClosed: vi.fn(),
+ observeStreamLengthOnConnect: vi.fn(),
+ observeStreamResumeGap: vi.fn(),
+ observeStreamConnectionRejected: vi.fn(),
+ observeStreamIngestEvents: vi.fn(),
+}))
diff --git a/services/agent-proxy/tsconfig.json b/services/agent-proxy/tsconfig.json
new file mode 100644
index 000000000000..b9efb5326103
--- /dev/null
+++ b/services/agent-proxy/tsconfig.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "target": "es2021",
+ "lib": ["es2021", "dom", "dom.iterable"],
+ "module": "es2022",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "allowJs": false,
+ "noEmit": true,
+ "isolatedModules": true,
+ "allowSyntheticDefaultImports": true,
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedIndexedAccess": true,
+ "exactOptionalPropertyTypes": true,
+ "skipLibCheck": true,
+ "types": ["node"],
+ "paths": {
+ "@/*": ["./src/*", "./tests/*"]
+ }
+ },
+ "include": ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "types.d.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/services/agent-proxy/types.d.ts b/services/agent-proxy/types.d.ts
new file mode 100644
index 000000000000..65c5e3000a9c
--- /dev/null
+++ b/services/agent-proxy/types.d.ts
@@ -0,0 +1,54 @@
+// ioredis v4 ships without bundled type declarations. We expose a minimal
+// structural type so `import type { Redis } from 'ioredis'` resolves across
+// all modules. Return types on Redis commands are typed as `any` — this lets
+// the pre-existing call sites in redis-stream.ts use their own local type
+// assertions (e.g. `raw as Array<[string, ...]>`) without conflicting with a
+// stricter shim return type. Mirrors the pattern in services/mcp/types.d.ts.
+declare module 'ioredis' {
+ interface Pipeline {
+ xadd(...args: any[]): this
+ expire(...args: any[]): this
+ set(...args: any[]): this
+ exec(): Promise<Array<[Error | null, any]> | null>
+ }
+
+ interface Redis {
+ connect(): Promise<void>
+ quit(): Promise<string>
+ // ioredis v4 disconnect() is synchronous and returns void (not a Promise).
+ disconnect(): void
+ duplicate(): Redis
+ on(event: string, listener: (...args: any[]) => void): this
+ get(key: string): Promise<string | null>
+ set(key: string, value: string | number, ...args: any[]): Promise<any>
+ exists(...keys: string[]): Promise<number>
+ expire(key: string, seconds: number): Promise<number>
+ del(...keys: string[]): Promise<number>
+ xadd(key: string, ...args: any[]): Promise<string | null>
+ xread(...args: any[]): Promise<any>
+ xlen(key: string): Promise<number>
+ xrange(key: string, start: string, end: string, ...args: any[]): Promise<any>
+ xrevrange(key: string, end: string, start: string, ...args: any[]): Promise<any>
+ watch(...keys: string[]): Promise<'OK'>
+ unwatch(): Promise<'OK'>
+ multi(): Pipeline
+ status: string
+ }
+
+ const Redis: {
+ new (url: string, opts?: any): Redis
+ new (opts?: any): Redis
+ }
+
+ export { Redis }
+ export default Redis
+}
+
+// CryptoKey is a WebCrypto global (lib.dom.d.ts). Node's `node:crypto` module
+// also surfaces it at runtime but the @types/node declaration omits the re-export.
+// Augment the ambient `crypto` module so `import type { CryptoKey } from 'crypto'`
+// in ingest-handler.ts resolves to the same global type.
+declare module 'crypto' {
+ type CryptoKey = globalThis.CryptoKey
+ export { CryptoKey }
+}
diff --git a/services/agent-proxy/vitest.config.mts b/services/agent-proxy/vitest.config.mts
new file mode 100644
index 000000000000..b7cc77438cf0
--- /dev/null
+++ b/services/agent-proxy/vitest.config.mts
@@ -0,0 +1,14 @@
+import tsconfigPaths from 'vite-tsconfig-paths'
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ plugins: [tsconfigPaths({ root: '.' })],
+ test: {
+ globals: true,
+ environment: 'node',
+ testTimeout: 15000,
+ setupFiles: ['tests/setup.ts'],
+ include: ['tests/**/*.test.ts'],
+ exclude: ['node_modules/**', 'dist/**'],
+ },
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 227fbacf7803..5608300cb32f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -47974,6 +47974,19 @@ export namespace Schemas {
Service: 'service',
} as const;
+ /**
+ * Response containing a JWT token (and resolved base URL) for reading a task run's live event stream
+ */
+ export interface StreamReadTokenResponse {
+ /** Run-scoped JWT the browser presents to the agent-proxy to read this run's live event stream */
+ token: string;
+ /**
+ * Base URL of the agent-proxy to read the stream from when routing via the proxy is enabled for this user. Null means read from the Django endpoint directly (same-origin). The client appends the run's stream path and sends the token as a Bearer header when this is set.
+ * @nullable
+ */
+ stream_base_url: string | null;
+ }
+
export interface SummaryBullet {
text: string;
line_refs: string;