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(agent-platform): Prometheus metrics for the agent fleet (#64851)

Ben White6d10f89d1857
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d37d4dd6eebf..e986db8afa90 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -460,7 +460,7 @@ importers:
'@storybook/react-webpack5':
specifier: ^8.6.14
'@storybook/test-runner':
specifier: ^0.19.1
@@ -514,7 +514,7 @@ importers:
version: 2.0.0([email protected])
webpack:
specifier: ^5.94.0
webpack-cli:
specifier: ^5.1.4
version: 5.1.4([email protected])
@@ -2386,6 +2386,9 @@ importers:
posthog-node:
specifier: ^5.25.0
version: 5.25.0
+ prom-client:
+ specifier: ^15.1.3
+ version: 15.1.3
typebox:
specifier: ^1.1.38
version: 1.2.8
@@ -3307,7 +3310,7 @@ importers:
version: 2.1.1
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -4092,7 +4095,7 @@ importers:
version: 1.2.1
jest:
specifier: '*'
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -19700,6 +19703,10 @@ packages:
resolution: {integrity: sha512-sF308EhTenb/pDRPakm+WgiN+VdM/T1RaHj1x+MvAuT8UiQP8JmOEbxVqtkbfR4LrvOg5n7ic01kRBDGXjYikA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==}
+ engines: {node: ^16 || ^18 || >=20}
+
resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==}
engines: {node: '>=10'}
@@ -26971,6 +26978,41 @@ snapshots:
- ts-node
- utf-8-validate
+ dependencies:
+ '@jest/console': 29.7.0
+ '@jest/reporters': 29.7.0
+ '@jest/test-result': 29.7.0
+ '@jest/transform': 29.7.0
+ '@jest/types': 29.6.3
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 29.7.0
+ jest-config: 29.7.0(@types/[email protected])
+ jest-haste-map: 29.7.0
+ jest-message-util: 29.7.0
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-resolve-dependencies: 29.7.0
+ jest-runner: 29.7.0
+ jest-runtime: 29.7.0
+ jest-snapshot: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ jest-watcher: 29.7.0
+ micromatch: 4.0.8
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-ansi: 6.0.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/console': 29.7.0
@@ -27112,6 +27154,42 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/console': 30.0.5
+ '@jest/pattern': 30.0.1
+ '@jest/reporters': 30.0.5
+ '@jest/test-result': 30.0.5
+ '@jest/transform': 30.0.5
+ '@jest/types': 30.0.5
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ exit-x: 0.2.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 30.0.5
+ jest-haste-map: 30.0.5
+ jest-message-util: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-resolve-dependencies: 30.0.5
+ jest-runner: 30.0.5
+ jest-runtime: 30.0.5
+ jest-snapshot: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ jest-watcher: 30.0.5
+ micromatch: 4.0.8
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/types': 29.6.3
@@ -31275,7 +31353,7 @@ snapshots:
ts-dedent: 2.2.0
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
'@types/semver': 7.7.1
@@ -31293,12 +31371,12 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
style-loader: 3.3.3([email protected])
ts-dedent: 2.2.0
url: 0.11.1
util: 0.12.5
util-deprecate: 1.0.2
webpack-dev-middleware: 6.1.3([email protected])
webpack-hot-middleware: 2.25.4
webpack-virtual-modules: 0.6.2
@@ -31392,7 +31470,7 @@ snapshots:
dependencies:
storybook: 8.6.18([email protected])
dependencies:
'@storybook/core-webpack': 8.6.18([email protected]([email protected]))
@@ -31407,7 +31485,7 @@ snapshots:
semver: 7.8.0
storybook: 8.6.18([email protected])
tsconfig-paths: 4.2.0
optionalDependencies:
typescript: 6.0.3
transitivePeerDependencies:
@@ -31441,7 +31519,7 @@ snapshots:
react-docgen-typescript: 2.2.2([email protected])
tslib: 2.8.1
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -31479,10 +31557,10 @@ snapshots:
- supports-color
- typescript
dependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
@@ -31576,7 +31654,7 @@ snapshots:
'@swc/core': 1.15.18
'@swc/jest': 0.2.37(@swc/[email protected])
expect-playwright: 0.8.0
+ jest: 29.7.0
jest-circus: 29.7.0
jest-environment-node: 29.7.0
jest-junit: 16.0.0
@@ -33845,17 +33923,17 @@ snapshots:
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
dependencies:
webpack-cli: 5.1.4([email protected])
'@xmldom/[email protected]': {}
@@ -34377,7 +34455,7 @@ snapshots:
loader-utils: 2.0.4
make-dir: 3.1.0
schema-utils: 2.7.1
dependencies:
@@ -35283,6 +35361,21 @@ snapshots:
safe-buffer: 5.2.1
sha.js: 2.4.12
+ dependencies:
+ '@jest/types': 29.6.3
+ chalk: 4.1.2
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-config: 29.7.0
+ jest-util: 29.7.0
+ prompts: 2.4.2
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/types': 29.6.3
@@ -35416,7 +35509,7 @@ snapshots:
postcss-value-parser: 4.2.0
schema-utils: 2.7.1
semver: 6.3.1
dependencies:
@@ -35428,7 +35521,7 @@ snapshots:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
semver: 7.8.0
dependencies:
@@ -37009,7 +37102,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
@@ -37128,7 +37221,7 @@ snapshots:
semver: 7.8.0
tapable: 2.3.3
typescript: 6.0.3
dependencies:
@@ -37790,7 +37883,7 @@ snapshots:
dependencies:
html-webpack-plugin: 5.5.3([email protected])
dependencies:
@@ -37799,7 +37892,7 @@ snapshots:
lodash: 4.18.1
pretty-error: 4.0.0
tapable: 2.2.1
dependencies:
@@ -38522,6 +38615,25 @@ snapshots:
- ts-node
- utf-8-validate
+ dependencies:
+ '@jest/core': 29.7.0
+ '@jest/test-result': 29.7.0
+ '@jest/types': 29.6.3
+ chalk: 4.1.2
+ create-jest: 29.7.0
+ exit: 0.1.2
+ import-local: 3.2.0
+ jest-config: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ yargs: 17.7.2
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
@@ -38598,6 +38710,25 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/test-result': 30.0.5
+ '@jest/types': 30.0.5
+ chalk: 4.1.2
+ exit-x: 0.2.2
+ import-local: 3.2.0
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ yargs: 17.7.2
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
dependencies:
'@babel/core': 7.29.0
@@ -38632,6 +38763,64 @@ snapshots:
- supports-color
- utf-8-validate
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -38790,6 +38979,74 @@ snapshots:
- babel-plugin-macros
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/get-type': 30.0.1
+ '@jest/pattern': 30.0.1
+ '@jest/test-sequencer': 30.0.5
+ '@jest/types': 30.0.5
+ babel-jest: 30.0.5(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ deepmerge: 4.3.1
+ glob: 10.5.0
+ graceful-fs: 4.2.11
+ jest-circus: 30.0.5
+ jest-docblock: 30.0.1
+ jest-environment-node: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-runner: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ esbuild-register: 3.6.0([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/get-type': 30.0.1
+ '@jest/pattern': 30.0.1
+ '@jest/test-sequencer': 30.0.5
+ '@jest/types': 30.0.5
+ babel-jest: 30.0.5(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 4.3.0
+ deepmerge: 4.3.1
+ glob: 10.5.0
+ graceful-fs: 4.2.11
+ jest-circus: 30.0.5
+ jest-docblock: 30.0.1
+ jest-environment-node: 30.0.5
+ jest-regex-util: 30.0.1
+ jest-resolve: 30.0.5
+ jest-runner: 30.0.5
+ jest-util: 30.0.5
+ jest-validate: 30.0.5
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 30.0.5
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 25.8.0
+ esbuild-register: 3.6.0([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
chalk: 4.1.2
@@ -39164,7 +39421,7 @@ snapshots:
dependencies:
expect-playwright: 0.8.0
+ jest: 29.7.0
jest-circus: 29.7.0
jest-environment-node: 29.7.0
jest-process-manager: 0.4.0
@@ -39599,7 +39856,7 @@ snapshots:
dependencies:
ansi-escapes: 6.0.0
chalk: 5.6.2
+ jest: 29.7.0
jest-regex-util: 29.6.3
jest-watcher: 29.7.0
slash: 5.1.0
@@ -39671,6 +39928,18 @@ snapshots:
- ts-node
- utf-8-validate
+ dependencies:
+ '@jest/core': 29.7.0
+ '@jest/types': 29.6.3
+ import-local: 3.2.0
+ jest-cli: 29.7.0
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
@@ -39720,6 +39989,19 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/types': 30.0.5
+ import-local: 3.2.0
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - esbuild-register
+ - supports-color
+ - ts-node
+
@@ -40024,7 +40306,7 @@ snapshots:
less: 4.2.2
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -42280,7 +42562,7 @@ snapshots:
postcss: 8.5.15
schema-utils: 3.3.0
semver: 7.7.0
dependencies:
@@ -42711,6 +42993,11 @@ snapshots:
dependencies:
tdigest: 0.1.2
+ dependencies:
+ '@opentelemetry/api': 1.9.0
+ tdigest: 0.1.2
+
dependencies:
err-code: 2.0.3
@@ -43044,7 +43331,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -44080,7 +44367,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
semver: 7.7.0
optionalDependencies:
sass: 1.56.0
@@ -44740,11 +45027,11 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
dependencies:
@@ -45111,30 +45398,28 @@ snapshots:
ansi-escapes: 4.3.2
supports-hyperlinks: 2.3.0
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
'@swc/core': 1.15.18
cssnano: 7.0.6([email protected])
- esbuild: 0.25.12
+ esbuild: 0.28.0
postcss: 8.5.15
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.46.0
optionalDependencies:
- '@swc/core': 1.15.18
cssnano: 7.0.6([email protected])
- esbuild: 0.28.0
postcss: 8.5.15
@@ -46286,7 +46571,7 @@ snapshots:
import-local: 3.1.0
interpret: 3.1.1
rechoir: 0.8.0
webpack-merge: 5.8.0
@@ -46297,7 +46582,7 @@ snapshots:
range-parser: 1.2.1
schema-utils: 4.3.3
optionalDependencies:
dependencies:
@@ -46316,7 +46601,7 @@ snapshots:
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.8
@@ -46340,11 +46625,9 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.0
watchpack: 2.5.1
webpack-sources: 3.3.4
- optionalDependencies:
- webpack-cli: 5.1.4([email protected])
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
@@ -46359,7 +46642,7 @@ snapshots:
- postcss
- uglify-js
dependencies:
'@types/eslint-scope': 3.7.7
'@types/estree': 1.0.8
@@ -46383,9 +46666,11 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.0
watchpack: 2.5.1
webpack-sources: 3.3.4
+ optionalDependencies:
+ webpack-cli: 5.1.4([email protected])
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
index d482dacca194..d5521bf10035 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
@@ -32,6 +32,7 @@ import {
SessionQueue,
} from '@posthog/agent-shared'
+import { enqueueTotal } from '../metrics'
import { ElevationTrigger, principalDisplay, recordElevationRequest, requireAclAccess } from './acl'
export interface EnqueueDeps {
@@ -100,6 +101,22 @@ export type EnqueueOutcome =
}
export async function enqueueOrResume(deps: EnqueueDeps, input: EnqueueInput): Promise<EnqueueOutcome> {
+ // Single intake choke point — count every enqueue by trigger + outcome.
+ // A throw (DB down, unexpected error) is counted as `error` so the demand
+ // total stays complete. The shared HTTP histogram covers latency/status;
+ // this is the only place the created-vs-resumed-vs-deduped split exists.
+ const trigger = input.trigger ?? 'chat'
+ try {
+ const outcome = await enqueueOrResumeInner(deps, input)
+ enqueueTotal.labels({ trigger, outcome: outcome.kind }).inc()
+ return outcome
+ } catch (err) {
+ enqueueTotal.labels({ trigger, outcome: 'error' }).inc()
+ throw err
+ }
+}
+
+async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Promise<EnqueueOutcome> {
// Idempotency check first — independent of externalKey. A duplicate
// request returns the original session id unchanged; the principal +
// seed of the duplicate are deliberately discarded. Stripe-shaped
diff --git a/products/agent_platform/services/agent-ingress/src/index.ts b/products/agent_platform/services/agent-ingress/src/index.ts
index f11610bc1f4e..9942fc4a709c 100644
--- a/products/agent_platform/services/agent-ingress/src/index.ts
+++ b/products/agent_platform/services/agent-ingress/src/index.ts
@@ -15,10 +15,12 @@
import {
createAgentPool,
createLogger,
+ createMetricsServer,
DirectHttpClient,
EncryptedEnvSecretResolver,
EncryptedFields,
HttpClient,
+ initMetrics,
installProcessHandlers,
PgCredentialBroker,
PgIdentityStore,
@@ -37,6 +39,12 @@ async function main(): Promise<void> {
installProcessHandlers(log)
const config = loadAgentIngressConfig()
+ // Prometheus: Node process defaults + the dedicated scrape server on a
+ // separate port from the public request listener, so /metrics is never
+ // exposed on the internet-facing ingress port.
+ initMetrics({ service: 'agent-ingress' })
+ createMetricsServer({ port: config.metricsPort, log })
+
const posthogDb = createAgentPool(config.posthogDbUrl)
const agentDb = createAgentPool(config.agentDbUrl)
diff --git a/products/agent_platform/services/agent-ingress/src/metrics.ts b/products/agent_platform/services/agent-ingress/src/metrics.ts
new file mode 100644
index 000000000000..312df9b7854e
--- /dev/null
+++ b/products/agent_platform/services/agent-ingress/src/metrics.ts
@@ -0,0 +1,40 @@
+/**
+ * Prometheus metrics for the agent-ingress (HTTP front door).
+ *
+ * Declared against the shared registry. Deliberately lean — the shared
+ * `agent_http_request_duration_seconds` histogram (recorded by the middleware
+ * in `routing/http-utils.ts`) already covers per-route latency + status, which
+ * subsumes generic request-rate, error-rate, and auth-rejection (401/403)
+ * tracking. These two add the signals HTTP status alone can't express:
+ *
+ * - intake SHAPE (a 200 doesn't say whether it created a session, resumed
+ * one, or idempotently deduped) attributed per trigger; and
+ * - open long-lived SSE streams, which never "finish" so a duration
+ * histogram can't see them — a climbing gauge means leaked subscriptions.
+ */
+
+import { Counter, Gauge } from '@posthog/agent-shared'
+
+/**
+ * Trigger intake outcomes. `outcome` ∈ created | resumed | elevation_required
+ * | error (mirrors `EnqueueOutcome.kind`). The demand signal that feeds the
+ * runner queue — break down by `trigger` to see chat vs slack vs webhook vs
+ * mcp load and the new-vs-resume mix.
+ */
+export const enqueueTotal = new Counter({
+ name: 'agent_ingress_enqueue_total',
+ help: 'Trigger intake outcomes by trigger type (created/resumed/elevation_required/error).',
+ labelNames: ['trigger', 'outcome'],
+})
+
+/**
+ * Currently-open long-lived SSE streams, by transport (chat `/listen`, mcp).
+ * These hold a Redis bus subscription + an open socket for the session's
+ * lifetime; a value that climbs without bound (vs. connected clients) is a
+ * leaked-subscription / stuck-stream signal.
+ */
+export const activeStreams = new Gauge({
+ name: 'agent_ingress_active_streams',
+ help: 'Open long-lived SSE streams by transport (chat/mcp). Climbing unbounded = leaked subscriptions.',
+ labelNames: ['transport'],
+})
diff --git a/products/agent_platform/services/agent-ingress/src/routing/http-utils.ts b/products/agent_platform/services/agent-ingress/src/routing/http-utils.ts
index 7073baf75f14..b40b183ffa82 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/http-utils.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/http-utils.ts
@@ -19,6 +19,7 @@ import type { NextFunction, Request, RequestHandler, Response } from 'express'
import { ZodError } from 'zod'
import type { Logger } from '@posthog/agent-shared'
+import { isMetricsExcludedPath, recordHttpRequest } from '@posthog/agent-shared'
import { AmbiguousRevisionError } from './resolver'
@@ -89,7 +90,9 @@ export function requestLogger(log: Logger): RequestHandler {
// first means the peer hung up mid-write.
...(res.writableFinished ? {} : { aborted: true }),
}
- if (req.path === '/healthz') {
+ if (isMetricsExcludedPath(req.path)) {
+ // Liveness probes + the scrape endpoint fire on a fixed interval —
+ // keep them out of the default `info` access stream.
log.debug(fields, 'request')
} else if (res.statusCode >= 500) {
log.error(fields, 'request')
@@ -105,6 +108,46 @@ export function requestLogger(log: Logger): RequestHandler {
}
}
+/**
+ * Records `agent_http_request_duration_seconds` for every request. Mounted
+ * right after `requestLogger` so it sees 404s and body-parse rejections too.
+ *
+ * The `route` label is the express route PATTERN (`/run`, `/listen`) — never
+ * the resolved path — so per-agent slugs / session ids can't blow up
+ * cardinality. SSE streams (`text/event-stream`) are skipped: they don't
+ * "finish" until the client disconnects, so their duration is the whole stream
+ * lifetime (tracked instead by the `agent_ingress_active_streams` gauge).
+ * Metrics + health paths are excluded entirely.
+ */
+export function httpMetricsMiddleware(): RequestHandler {
+ return (req, res, next) => {
+ if (isMetricsExcludedPath(req.path)) {
+ next()
+ return
+ }
+ const start = process.hrtime.bigint()
+ let recorded = false
+ const record = (): void => {
+ if (recorded) {
+ return
+ }
+ recorded = true
+ const contentType = res.getHeader('content-type')
+ if (typeof contentType === 'string' && contentType.includes('text/event-stream')) {
+ return
+ }
+ const route = req.route?.path ?? (res.statusCode === 404 ? 'unmatched' : 'unrouted')
+ recordHttpRequest(
+ { method: req.method, route: String(route), statusCode: res.statusCode },
+ Number(process.hrtime.bigint() - start) / 1e9
+ )
+ }
+ res.on('finish', record)
+ res.on('close', record)
+ next()
+ }
+}
+
export type AsyncRouteHandler = (req: Request, res: Response, next: NextFunction) => Promise<unknown> | unknown
export function asyncHandler(fn: AsyncRouteHandler): RequestHandler {
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.ts
index f0a6e8efc12b..8b57fd608a25 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts
@@ -23,7 +23,7 @@ import { resolveAgent } from '../triggers/resolve'
import { slackTrigger } from '../triggers/slack'
import type { RouteAuthKind, TriggerModule } from '../triggers/types'
import { webhookTrigger } from '../triggers/webhook'
-import { asyncHandler, errorHandler, requestLogger } from './http-utils'
+import { asyncHandler, errorHandler, httpMetricsMiddleware, requestLogger } from './http-utils'
import { RevisionResolver, RoutingMode } from './resolver'
/**
@@ -117,6 +117,9 @@ export function buildApp(opts: BuildAppOpts): Express {
// First in the chain so it sees — and times — every request, including
// those that never match a route (404s) or fail body parsing (400s).
app.use(requestLogger(log))
+ // Record HTTP latency/status for every request. Sits right after the
+ // logger so it shares the same view of unmatched + rejected requests.
+ app.use(httpMetricsMiddleware())
const bus = opts.bus
const resolver = new RevisionResolver({
revisions: opts.revisions,
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
index acedd994310f..d9b16531a501 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
@@ -17,6 +17,7 @@ import { buildClientToolResultMarker, CLIENT_KIND_HEADER, parseClientKind } from
import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'
import { enqueueOrResume } from '../enqueue/enqueue'
+import { activeStreams } from '../metrics'
import {
ChatCancelBodySchema,
ChatClientToolResultBodySchema,
@@ -210,6 +211,7 @@ async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQueryS
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.flushHeaders()
+ activeStreams.labels({ transport: 'chat' }).inc()
const unsubscribe = deps.bus.subscribe(sessionId, (event) => {
res.write(`data: ${JSON.stringify(event)}\n\n`)
})
@@ -223,6 +225,7 @@ async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQueryS
req.on('close', () => {
clearInterval(heartbeat)
unsubscribe()
+ activeStreams.labels({ transport: 'chat' }).dec()
})
}
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
index 0398fe7e43ae..1b401820cedb 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts
@@ -50,6 +50,7 @@ import { AgentSession, lastAssistantTextPreview, SessionPrincipal, triggerAuthCo
import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'
import { principalsMatch } from '../enqueue/auth'
import { enqueueOrResume } from '../enqueue/enqueue'
+import { activeStreams } from '../metrics'
import { McpRequestBodySchema, McpStreamQuerySchema } from './mcp.schemas'
import { getOwnedSession } from './session-access'
import {
@@ -344,10 +345,14 @@ async function mcpStreamHandler(ctx: AuthedRouteCtx<z.infer<typeof McpStreamQuer
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.flushHeaders()
+ activeStreams.labels({ transport: 'mcp' }).inc()
const unsubscribe = deps.bus.subscribe(sessionId, (event) => {
res.write(`event: ${event.kind}\ndata: ${JSON.stringify(event)}\n\n`)
})
- req.on('close', () => unsubscribe())
+ req.on('close', () => {
+ unsubscribe()
+ activeStreams.labels({ transport: 'mcp' }).dec()
+ })
}
async function mcpConnectInfoHandler(ctx: RouteCtx): Promise<void> {
diff --git a/products/agent_platform/services/agent-janitor/src/index.ts b/products/agent_platform/services/agent-janitor/src/index.ts
index 476d1cbfb66a..26fd294c37b7 100644
--- a/products/agent_platform/services/agent-janitor/src/index.ts
+++ b/products/agent_platform/services/agent-janitor/src/index.ts
@@ -21,7 +21,9 @@ import { S3Client } from '@aws-sdk/client-s3'
import {
createAgentPool,
createLogger,
+ createMetricsServer,
createModalSandboxTerminator,
+ initMetrics,
installProcessHandlers,
MemoryStore,
MultiBackendSandboxTerminator,
@@ -37,6 +39,7 @@ import {
import { loadAgentJanitorConfig } from './config'
import { cronTick, newCronTickState } from './cron-tick'
+import * as metrics from './metrics'
import { buildJanitorApp } from './server'
import { sweepOnce } from './sweep'
@@ -46,6 +49,12 @@ async function main(): Promise<void> {
installProcessHandlers(log)
const config = loadAgentJanitorConfig()
+ // Prometheus: Node process defaults + the dedicated scrape server. The
+ // sweep/cron metrics below let an alert catch a wedged singleton (rate of
+ // *_runs_total → 0); the queue-depth gauge is sampled once per tick.
+ initMetrics({ service: 'agent-janitor' })
+ createMetricsServer({ port: config.metricsPort, log })
+
// S3 bundle storage is required (enforced on `bundleS3Bucket` in config —
// dev default, fails closed at config-load in prod). Endpoint is optional:
// unset means "use the AWS SDK's regional default" (prod path); SeaweedFS
@@ -166,25 +175,59 @@ async function main(): Promise<void> {
// single throw can't take the loop down.
await Promise.all([
(async () => {
+ const end = metrics.sweepDuration.startTimer()
try {
const result = await sweepOnce(sweep)
+ end()
+ metrics.sweepRuns.inc()
+ // Each action is its own series so a rising requeued/poisoned
+ // rate (runner instability) or sandbox_reap_failures (bad
+ // terminator) stands out on the dashboard.
+ for (const [action, count] of Object.entries(result)) {
+ if (count > 0) {
+ metrics.sweptTotal.labels({ action }).inc(count)
+ }
+ }
log.debug({ ...result }, 'sweep.done')
} catch (err) {
+ end()
+ metrics.sweepFailures.inc()
log.error({ err: (err as Error).message, stack: (err as Error).stack }, 'sweep.failed')
}
})(),
(async () => {
try {
const result = await cronTick(cronTickDeps, cronTickState)
+ metrics.cronRuns.inc()
+ if (result.fired > 0) {
+ metrics.cronFired.inc(result.fired)
+ }
+ if (result.errors > 0) {
+ metrics.cronErrors.inc(result.errors)
+ }
if (result.fired > 0 || result.errors > 0) {
log.info({ ...result }, 'cron_tick.done')
} else {
log.debug({ ...result }, 'cron_tick.done')
}
} catch (err) {
+ metrics.cronFailures.inc()
log.error({ err: (err as Error).message, stack: (err as Error).stack }, 'cron_tick.failed')
}
})(),
+ // Sample fleet queue depth once per tick. Own try/catch so a depth
+ // query blip never marks the sweep failed. Zero-fill known states so
+ // a state that empties shows 0 rather than freezing at its last value.
+ (async () => {
+ try {
+ const counts = await queue.countByState()
+ for (const state of metrics.KNOWN_SESSION_STATES) {
+ metrics.queueDepth.labels({ state }).set(counts[state] ?? 0)
+ }
+ } catch (err) {
+ log.warn({ err: (err as Error).message }, 'queue_depth.sample_failed')
+ }
+ })(),
])
}, config.sweepIntervalMs)
}
diff --git a/products/agent_platform/services/agent-janitor/src/metrics.ts b/products/agent_platform/services/agent-janitor/src/metrics.ts
new file mode 100644
index 000000000000..fd03920d3d53
--- /dev/null
+++ b/products/agent_platform/services/agent-janitor/src/metrics.ts
@@ -0,0 +1,93 @@
+/**
+ * Prometheus metrics for the agent-janitor.
+ *
+ * The janitor is a SINGLETON (min=max=1 pod) running two timers: the sweep
+ * (reaps stuck/idle sessions + orphan sandboxes + expired approvals) and the
+ * cron tick (fires scheduled triggers). Because it's a singleton, a wedged
+ * timer is silent — nothing else reaps — so the `*_runs_total` counters exist
+ * precisely so an alert can fire when their rate drops to zero.
+ *
+ * It also owns the fleet's queue-depth gauge: it samples `countByState()` once
+ * per sweep so the `queued` backlog + `running` in-flight totals come from one
+ * place instead of every runner pod re-running the same aggregate.
+ *
+ * The janitor's HTTP surface (Django proxy: /revisions/*, /approvals/*) is
+ * intentionally NOT given a request-duration histogram — it's an internal,
+ * low-stakes path already latency-traced via the structured-log `instrument()`
+ * calls in server.ts, and the fleet's golden-signal HTTP surface is the
+ * ingress.
+ */
+
+import { Counter, Gauge, Histogram } from '@posthog/agent-shared'
+
+/** Sweep ticks that ran to completion. Rate → 0 means the singleton's sweep timer is wedged. */
+export const sweepRuns = new Counter({
+ name: 'agent_janitor_sweep_runs_total',
+ help: 'Sweep ticks that ran to completion (rate drops to 0 if the singleton wedges).',
+})
+
+/** Sweep ticks that threw. */
+export const sweepFailures = new Counter({
+ name: 'agent_janitor_sweep_failures_total',
+ help: 'Sweep ticks that threw.',
+})
+
+/** Sweep tick wall time. */
+export const sweepDuration = new Histogram({
+ name: 'agent_janitor_sweep_duration_seconds',
+ help: 'Wall-clock duration of one sweep tick.',
+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
+})
+
+/**
+ * Sessions / resources the sweep acted on, by action. `action` ∈ requeued |
+ * poisoned | closed | expired_approvals | cleared_idempotency_keys |
+ * reaped_sandboxes | sandbox_reap_failures. A rising `requeued` / `poisoned`
+ * rate points back at runner instability (workers crashing mid-session);
+ * `sandbox_reap_failures` points at the sandbox terminator.
+ */
+export const sweptTotal = new Counter({
+ name: 'agent_janitor_swept_total',
+ help: 'Sessions/resources acted on by the sweep, by action.',
+ labelNames: ['action'],
+})
+
+/** Cron ticks that ran to completion. Rate → 0 means scheduled triggers have stopped firing. */
+export const cronRuns = new Counter({
+ name: 'agent_janitor_cron_runs_total',
+ help: 'Cron ticks that ran to completion (rate drops to 0 if the singleton wedges).',
+})
+
+/** Cron ticks that threw. */
+export const cronFailures = new Counter({
+ name: 'agent_janitor_cron_failures_total',
+ help: 'Cron ticks that threw.',
+})
+
+/** Cron firings enqueued (scheduled sessions created). */
+export const cronFired = new Counter({
+ name: 'agent_janitor_cron_fired_total',
+ help: 'Cron firings enqueued as sessions.',
+})
+
+/** Per-revision cron evaluation errors within a tick (bad schedule, enqueue failure). */
+export const cronErrors = new Counter({
+ name: 'agent_janitor_cron_errors_total',
+ help: 'Per-revision cron evaluation errors within a tick.',
+})
+
+/**
+ * Fleet session-queue depth by state, sampled once per sweep by this
+ * singleton. `state="queued"` is the backlog the runner fleet has to burn
+ * down; `state="running"` is in-flight. Known states are zero-filled each
+ * sample so a state dropping to 0 is visible rather than frozen at its last
+ * value.
+ */
+export const queueDepth = new Gauge({
+ name: 'agent_session_queue_depth',
+ help: 'Sessions by state across the fleet, sampled by the janitor singleton.',
+ labelNames: ['state'],
+})
+
+/** Every session state — used to zero-fill `queueDepth` each sample. */
+export const KNOWN_SESSION_STATES = ['queued', 'running', 'completed', 'closed', 'cancelled', 'failed'] as const
diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.ts
index 342d17f80b80..67b9b1a637f5 100644
--- a/products/agent_platform/services/agent-runner/src/index.ts
+++ b/products/agent_platform/services/agent-runner/src/index.ts
@@ -28,8 +28,10 @@ import {
DirectHttpClient,
EncryptedEnvSecretResolver,
EncryptedFields,
+ createMetricsServer,
HttpClient,
HttpGatewayClient,
+ initMetrics,
installProcessHandlers,
isDev,
KafkaLogSink,
@@ -69,6 +71,12 @@ async function main(): Promise<void> {
installProcessHandlers(log)
const config = loadAgentRunnerConfig()
+ // Prometheus: register Node process defaults + start the dedicated scrape
+ // server before any work. Separate port from /healthz so the metrics
+ // surface is independent of the liveness server's lifecycle.
+ initMetrics({ service: 'agent-runner' })
+ const metricsServer = createMetricsServer({ port: config.metricsPort, log })
+
// Fail-fast prod guard for the dev-only bearer attached to auth-less
// external MCP refs. Prod must route auth via integrations or the
// resolver-minted `kind: agent` path, not via a global bearer.
@@ -364,6 +372,7 @@ async function main(): Promise<void> {
log.info({ sig }, 'shutdown signal received — suspending in-flight sessions')
healthy = false
healthServer.close()
+ metricsServer.close()
void worker.stop()
}
process.on('SIGTERM', () => shutdown('SIGTERM'))
diff --git a/products/agent_platform/services/agent-runner/src/metrics.ts b/products/agent_platform/services/agent-runner/src/metrics.ts
new file mode 100644
index 000000000000..e50ef07fac46
--- /dev/null
+++ b/products/agent_platform/services/agent-runner/src/metrics.ts
@@ -0,0 +1,102 @@
+/**
+ * Prometheus metrics for the agent-runner (the queue worker).
+ *
+ * Declared against the shared registry (`@posthog/agent-shared`'s
+ * `runtime/metrics.ts`). The runner is the heart of the fleet — it's the only
+ * service that actually drives sessions — so these cover its real failure
+ * modes: queue-claim faults, concurrency saturation, per-stage session
+ * failures, and the two external round-trips most likely to wedge a session
+ * (sandbox acquire + MCP open). See worker.ts for the wiring.
+ */
+
+import { Counter, Gauge, Histogram } from '@posthog/agent-shared'
+
+/**
+ * Every terminal result of a `runOne()` run, by outcome. The complete
+ * denominator for runner throughput + the failed-rate alert. `suspended`
+ * means a graceful shutdown re-queued the session — not an error.
+ */
+export const sessionOutcomes = new Counter({
+ name: 'agent_runner_session_outcomes_total',
+ help: 'Sessions that finished a run, by terminal outcome (completed/closed/suspended/failed).',
+ labelNames: ['outcome'],
+})
+
+/**
+ * Crash / pre-run failures broken down by the runner's own `categorize()`
+ * output. These are the failures that never reached the driver loop (bad
+ * revision, secret-resolver error, sandbox-acquire failure, MCP open) plus any
+ * unexpected throw — the ones a deploy is most likely to have just introduced.
+ * Graceful in-loop failures show up under `sessionOutcomes{outcome="failed"}`.
+ */
+export const sessionFailures = new Counter({
+ name: 'agent_runner_session_failures_total',
+ help: 'Pre-run / crash session failures by error category.',
+ labelNames: ['category'],
+})
+
+/** Sessions in flight on this worker right now (utilization numerator). */
+export const inflightSessions = new Gauge({
+ name: 'agent_runner_inflight_sessions',
+ help: 'Sessions currently being processed by this worker process.',
+})
+
+/** Configured per-worker concurrency ceiling (utilization denominator). */
+export const maxConcurrency = new Gauge({
+ name: 'agent_runner_max_concurrency',
+ help: 'Configured max in-flight sessions per worker (denominator for utilization).',
+})
+
+/** Queue `claim()` calls that threw — DB pool unreachable or a malformed row. */
+export const claimFailures = new Counter({
+ name: 'agent_runner_claim_failures_total',
+ help: 'Queue claim() calls that raised (DB unreachable / bad row).',
+})
+
+/**
+ * Current consecutive claim-failure streak (0 when healthy). The loop backs
+ * off exponentially on this; a non-zero plateau means the queue DB is down and
+ * the worker is parked, not processing.
+ */
+export const consecutiveClaimFailures = new Gauge({
+ name: 'agent_runner_consecutive_claim_failures',
+ help: 'Current consecutive claim() failure streak (0 = healthy).',
+})
+
+/**
+ * Wall time for one session run. Deliberately NOT labelled by outcome: that
+ * would make this histogram's `_count` an exact duplicate of
+ * `sessionOutcomes` (same label, incremented together). Counts-by-outcome live
+ * on `sessionOutcomes`; this is the overall latency distribution.
+ */
+export const sessionDuration = new Histogram({
+ name: 'agent_runner_session_duration_seconds',
+ help: 'Wall-clock duration of one runOne() session run.',
+ buckets: [0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600, 1800],
+})
+
+/** Turns executed per session run — long-tail catches runaway loops. */
+export const sessionTurns = new Histogram({
+ name: 'agent_runner_session_turns',
+ help: 'Turns executed per session run.',
+ buckets: [1, 2, 3, 5, 8, 13, 21, 34, 55, 100],
+})
+
+/**
+ * Sandbox acquire latency + outcome, by provider (modal/docker/in-process).
+ * Acquire is a network round-trip to Modal/Docker and a pool gate; a spike
+ * here strands every session that needs a custom tool.
+ */
+export const sandboxAcquire = new Histogram({
+ name: 'agent_runner_sandbox_acquire_seconds',
+ help: 'Time to acquire a sandbox for a session, by provider + outcome (ok/error).',
+ labelNames: ['provider', 'outcome'],
+ buckets: [0.1, 0.5, 1, 2.5, 5, 10, 20, 30, 60, 120],
+})
+
+/** External / integration MCP clients that failed to open at session start, by coarse category. */
+export const mcpOpenFailures = new Counter({
+ name: 'agent_runner_mcp_open_failures_total',
+ help: 'External/integration MCP clients that failed to open at session start, by category.',
+ labelNames: ['category'],
+})
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.ts
index 67bebb12427a..aac95dfa3442 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts
@@ -49,6 +49,7 @@ import {
import { runSession } from '../loop/driver'
import { IntegrationHostValidator, McpTransportFactory, openMcpClients } from '../loop/mcp-clients'
import type { IsAskerInApproverScope } from '../loop/per-asker-auth'
+import * as metrics from '../metrics'
import { resolveModelCached } from '../models/pi-client'
const log = createLogger('worker')
@@ -241,6 +242,8 @@ export class Worker {
)
}
this.maxConcurrency = Math.max(1, deps.maxConcurrency ?? 8)
+ metrics.maxConcurrency.set(this.maxConcurrency)
+ metrics.inflightSessions.set(0)
}
/** Signal a graceful shutdown. In-flight sessions suspend back to PG. */
@@ -316,6 +319,7 @@ export class Worker {
try {
session = await this.deps.queue.claim(claimMs)
consecutiveClaimFailures = 0
+ metrics.consecutiveClaimFailures.set(0)
} catch (err) {
// Transient PG error / malformed row mapping. Log and back off
// before retrying — without this guard a single bad row crashes
@@ -323,6 +327,8 @@ export class Worker {
// spins the loop hot. Equal jitter keeps the floor growing while
// de-syncing retries across pods recovering together.
consecutiveClaimFailures++
+ metrics.claimFailures.inc()
+ metrics.consecutiveClaimFailures.set(consecutiveClaimFailures)
const window = Math.min(backoffMaxMs, backoffBaseMs * 2 ** (consecutiveClaimFailures - 1))
const delayMs = Math.round(window / 2 + Math.random() * (window / 2))
log.error(
@@ -355,8 +361,10 @@ export class Worker {
})
.finally(() => {
this.inflight.delete(claimedSession.id)
+ metrics.inflightSessions.set(this.inflight.size)
})
this.inflight.set(claimedSession.id, p)
+ metrics.inflightSessions.set(this.inflight.size)
}
// Drain any still-in-flight sessions before returning so the caller
@@ -367,6 +375,7 @@ export class Worker {
async runOne(session: AgentSession): Promise<void> {
const sLog = log.child({ session_id: session.id, application_id: session.application_id })
sLog.debug({ revision_id: session.revision_id }, 'session.claim')
+ const runStartedAt = Date.now()
let sandbox = null
let sandboxInstanceId: string | null = null
// `mcpClose` is the batched closer returned by `openMcpClients`. The
@@ -418,6 +427,7 @@ export class Worker {
})
sandboxInstanceId = created.id
}
+ const sandboxStartedAt = Date.now()
try {
sandbox = await this.deps.sandboxes.acquireForSession({
sessionId: session.id,
@@ -434,6 +444,9 @@ export class Worker {
cpuCores: rev.spec.limits.max_cpu_cores,
},
})
+ metrics.sandboxAcquire
+ .labels({ provider: this.deps.sandboxes.kind, outcome: 'ok' })
+ .observe((Date.now() - sandboxStartedAt) / 1000)
if (sandboxInstanceId) {
// Real provider id (Modal sandbox id, Docker container hash,
// or sessionId fallback for in-process) so the janitor
@@ -441,6 +454,9 @@ export class Worker {
await this.deps.sandboxInstances!.markReady(sandboxInstanceId, sandbox.providerSandboxId)
}
} catch (err) {
+ metrics.sandboxAcquire
+ .labels({ provider: this.deps.sandboxes.kind, outcome: 'error' })
+ .observe((Date.now() - sandboxStartedAt) / 1000)
if (sandboxInstanceId) {
await this.deps.sandboxInstances!.markFailed(sandboxInstanceId, (err as Error).message)
}
@@ -467,6 +483,9 @@ export class Worker {
openedMcpClients = opened.clients
mcpClose = opened.close
mcpFailures = opened.failures
+ for (const f of mcpFailures) {
+ metrics.mcpOpenFailures.labels({ category: f.category }).inc()
+ }
// Persist the per-ref failure detail to log_entries so the
// agent owner can debug via the session-detail page. The
// bus + system prompt only see the coarse category — raw
@@ -562,6 +581,9 @@ export class Worker {
conversation: session.conversation,
usage_total: session.usage_total,
})
+ metrics.sessionOutcomes.labels({ outcome: outcome.state }).inc()
+ metrics.sessionDuration.observe((Date.now() - runStartedAt) / 1000)
+ metrics.sessionTurns.observe(outcome.turns)
} catch (err) {
// Pre-runSession failures (revision load, secrets, sandbox acquire,
// MCP open) skip the driver's bus / log / conversation hooks. Without
@@ -576,6 +598,9 @@ export class Worker {
const category = categorize(reason)
const userText = userFacingMessage(category)
sLog.error({ err: reason, stack: e.stack, category }, 'session.crashed')
+ metrics.sessionOutcomes.labels({ outcome: 'failed' }).inc()
+ metrics.sessionFailures.labels({ category }).inc()
+ metrics.sessionDuration.observe((Date.now() - runStartedAt) / 1000)
// 1. Synthetic assistant message — so the user sees something in the
// transcript instead of their lone user turn followed by silence.
diff --git a/products/agent_platform/services/agent-shared/package.json b/products/agent_platform/services/agent-shared/package.json
index b59d2379044b..8c12f2fe153d 100644
--- a/products/agent_platform/services/agent-shared/package.json
+++ b/products/agent_platform/services/agent-shared/package.json
@@ -28,6 +28,7 @@
"pino": "^8.11.0",
"pino-pretty": "^9.4.0",
"posthog-node": "^5.25.0",
+ "prom-client": "^15.1.3",
"typebox": "^1.1.38",
"undici": "^7.24.0",
"uuid": "^10.0.0",
diff --git a/products/agent_platform/services/agent-shared/src/config/platform.ts b/products/agent_platform/services/agent-shared/src/config/platform.ts
index 19b465c8b8e0..7b617f809f07 100644
--- a/products/agent_platform/services/agent-shared/src/config/platform.ts
+++ b/products/agent_platform/services/agent-shared/src/config/platform.ts
@@ -164,6 +164,14 @@ export const PlatformConfigSchema = z.object({
.enum(['debug', 'info', 'warn', 'error', 'fatal'])
.default('info')
.describe('pino level. Set debug to trace per-turn / per-request detail.'),
+ metricsPort: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(6738)
+ .describe(
+ 'Dedicated Prometheus scrape port. Every service binds a tiny metrics-only HTTP server here (GET /metrics + /_metrics) — separate from the request/health port so /metrics is never served on the public ingress listener. 6738 matches the rest of the PostHog Node fleet (nodejs/) and the posthog-app chart default; vmagent discovers it via the pod scrape annotations.'
+ ),
})
export type PlatformConfig = z.infer<typeof PlatformConfigSchema>
@@ -181,6 +189,7 @@ export const PLATFORM_ENV_KEY_MAP: Record<string, keyof PlatformConfig> = {
HTTPS_PROXY: 'httpsProxy',
KAFKA_HOSTS: 'kafkaHosts',
LOG_LEVEL: 'logLevel',
+ AGENT_METRICS_PORT: 'metricsPort',
}
/**
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index c965e8542288..c4d8e538d29e 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -51,6 +51,7 @@ export * from './runtime/pg-credential-broker'
export * from './runtime/log-sink'
export * from './runtime/logger'
export * from './runtime/instrument'
+export * from './runtime/metrics'
export * from './runtime/process-handlers'
export * from './runtime/encryption'
export * from './runtime/team-api-key-resolver'
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
index c5d99542e641..7b3086ee24cb 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
@@ -120,6 +120,19 @@ export class PgSessionQueue implements SessionQueue {
}
}
+ async countByState(): Promise<Partial<Record<AgentSession['state'], number>>> {
+ // Cheap GROUP BY over the queue's partial-state index. Sampled by the
+ // janitor singleton once per sweep, not on any hot path.
+ const res = await this.pool.query<{ state: AgentSession['state']; count: string }>(
+ `SELECT state, count(*)::bigint AS count FROM agent_session GROUP BY state`
+ )
+ const out: Partial<Record<AgentSession['state'], number>> = {}
+ for (const row of res.rows) {
+ out[row.state] = Number(row.count)
+ }
+ return out
+ }
+
async update(sessionId: string, patch: Partial<AgentSession>): Promise<void> {
const sets: string[] = ['updated_at = NOW()']
const params: unknown[] = [sessionId]
diff --git a/products/agent_platform/services/agent-shared/src/persistence/queue.ts b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
index dfad0e425a86..f90a110af937 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
@@ -189,4 +189,13 @@ export interface SessionQueue extends SessionInputsStore {
* may still be retained.
*/
listIdleCompleted(floorMaxAgeMs: number, limit?: number): Promise<AgentSession[]>
+ /**
+ * Count sessions grouped by state across the whole fleet. Backs the
+ * janitor's queue-depth Prometheus gauge — the singleton samples this once
+ * per sweep so we get `queued` backlog + `running` in-flight + terminal
+ * counts without every runner pod hammering the same aggregate. Returns a
+ * record keyed by state; states with no rows are simply absent (the caller
+ * zero-fills the gauge for known states).
+ */
+ countByState(): Promise<Partial<Record<AgentSession['state'], number>>>
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/bus.ts b/products/agent_platform/services/agent-shared/src/runtime/bus.ts
index 8222f31e7ddd..eeb67866b6eb 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/bus.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/bus.ts
@@ -10,6 +10,28 @@
import type { Redis as IoRedis } from 'ioredis'
import { createLogger } from './logger'
+import { Counter } from './metrics'
+
+/**
+ * Bus health metrics. The bus is critical-path for /listen: the runner
+ * publishes lifecycle events, the ingress subscribes and streams them to
+ * clients. A publish/subscribe failure means events silently never reach a
+ * connected user, so these are the signals for "the live transport is broken."
+ */
+const busPublishTotal = new Counter({
+ name: 'agent_bus_publish_total',
+ help: 'Session lifecycle events published to the Redis bus, by outcome (ok/error).',
+ labelNames: ['outcome'],
+})
+const busSubscribeFailures = new Counter({
+ name: 'agent_bus_subscribe_failures_total',
+ help: 'Failures to SUBSCRIBE a session channel on the Redis bus (the /listen stream gets no events).',
+})
+const busReceiveErrors = new Counter({
+ name: 'agent_bus_receive_errors_total',
+ help: 'Errors handling a received bus message, by kind (parse = malformed event, listener = a subscriber threw).',
+ labelNames: ['kind'],
+})
export type SessionEventKind =
| 'session_started'
@@ -171,6 +193,7 @@ export class RedisSessionEventBus implements SessionEventBus {
try {
event = JSON.parse(message) as SessionEvent
} catch (err) {
+ busReceiveErrors.labels({ kind: 'parse' }).inc()
this.log.warn({ channel, err: (err as Error).message }, 'parse_failed')
return
}
@@ -178,6 +201,7 @@ export class RedisSessionEventBus implements SessionEventBus {
try {
fn(event)
} catch (err) {
+ busReceiveErrors.labels({ kind: 'listener' }).inc()
this.log.warn({ channel, err: (err as Error).message }, 'listener_threw')
}
}
@@ -190,7 +214,13 @@ export class RedisSessionEventBus implements SessionEventBus {
if (!this.publisher) {
await this.connect()
}
- await this.publisher!.publish(this.channel(event.session_id), JSON.stringify(event))
+ try {
+ await this.publisher!.publish(this.channel(event.session_id), JSON.stringify(event))
+ busPublishTotal.labels({ outcome: 'ok' }).inc()
+ } catch (err) {
+ busPublishTotal.labels({ outcome: 'error' }).inc()
+ throw err
+ }
}
subscribe(sessionId: string, fn: (e: SessionEvent) => void): () => void {
@@ -226,6 +256,7 @@ export class RedisSessionEventBus implements SessionEventBus {
try {
await this.subscriber!.subscribe(this.channel(sessionId))
} catch (err) {
+ busSubscribeFailures.inc()
this.log.error({ session_id: sessionId, err: (err as Error).message }, 'subscribe_failed')
}
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/log-sink.ts b/products/agent_platform/services/agent-shared/src/runtime/log-sink.ts
index 2bfcddc3b3da..ca57fe6674c9 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/log-sink.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/log-sink.ts
@@ -23,6 +23,20 @@ import type { HighLevelProducer, LibrdKafkaError, Metadata, ProducerGlobalConfig
import { hostname } from 'node:os'
import { createLogger } from './logger'
+import { Counter } from './metrics'
+
+/**
+ * Log-sink throughput by outcome. The runner's only path to the `log_entries`
+ * ClickHouse table (which backs the console's session-detail timeline) is this
+ * fire-and-forget Kafka producer, so a rising `dropped` / `error` rate means
+ * per-turn logs are silently not reaching the console. `produced` = handed to
+ * rdkafka (batched on the wire), not delivery-confirmed.
+ */
+const logSinkEntries = new Counter({
+ name: 'agent_logsink_entries_total',
+ help: 'Log entries handled by the Kafka log sink, by outcome (produced/dropped/error).',
+ labelNames: ['outcome'],
+})
export type LogLevel = 'debug' | 'info' | 'warn' | 'error'
@@ -263,6 +277,7 @@ export class KafkaLogSink implements LogSink {
return
}
if (!this.connected || !this.producer) {
+ logSinkEntries.labels({ outcome: 'dropped' }).inc(entries.length)
this.log.warn('dropping entries (not connected)', { count: entries.length })
return
}
@@ -279,7 +294,9 @@ export class KafkaLogSink implements LogSink {
const value = Buffer.from(safeClickhouseString(JSON.stringify(wire)))
try {
this.producer.produce(topic, null, value, null, Date.now(), noopDeliveryCallback)
+ logSinkEntries.labels({ outcome: 'produced' }).inc()
} catch (err) {
+ logSinkEntries.labels({ outcome: 'error' }).inc()
this.log.error('produce failed', { topic, error: String(err) })
}
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/metrics.ts b/products/agent_platform/services/agent-shared/src/runtime/metrics.ts
new file mode 100644
index 000000000000..9228f6ba124c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/metrics.ts
@@ -0,0 +1,119 @@
+/**
+ * Prometheus metrics surface for the agent-platform fleet.
+ *
+ * agent-shared historically dropped prom-client to stay lean (see the note in
+ * `instrument.ts`). We add it back here — deliberately and in one place —
+ * because the three deployable services (ingress, runner, janitor) all need a
+ * uniform, scrapeable metrics surface for fleet dashboards + alerting.
+ * prom-client is pure JS and bundles cleanly into each esbuild entrypoint; the
+ * structured-log `instrument()` helper stays for ad-hoc latency tracing.
+ *
+ * Each service at boot:
+ * 1. `initMetrics({ service })` once — sets a `service` default label (so
+ * every series, including the Node process defaults, is sliceable per
+ * service in a fleet dashboard) and registers default process metrics
+ * (CPU, RSS/heap, GC pauses, event-loop lag, open FDs).
+ * 2. `createMetricsServer({ port, log })` on a DEDICATED port (default 6738,
+ * AGENT_METRICS_PORT) — never the public request port. vmagent scrapes
+ * the pod on this port; the internet-facing ingress listener never serves
+ * `/metrics`. The metrics server itself logs nothing per scrape.
+ *
+ * Express services additionally record `agent_http_request_duration_seconds`
+ * via a tiny middleware (kept in each service so agent-shared stays
+ * express-free) calling `recordHttpRequest(...)`, and keep `/healthz` +
+ * `/metrics` out of their access log via `isMetricsExcludedPath`.
+ *
+ * Per-service metric definitions live in `<service>/src/metrics.ts`, declared
+ * against the single shared `register` re-exported here.
+ */
+
+import { createServer, type Server } from 'node:http'
+import { collectDefaultMetrics, Counter, Gauge, Histogram, register } from 'prom-client'
+
+import type { Logger } from './logger'
+
+// Re-export the metric classes + registry so services declare metrics without
+// importing prom-client directly (keeps the dependency surface in one file).
+export { Counter, Gauge, Histogram, register }
+
+/**
+ * Paths an access logger or the metrics server must never log per-request:
+ * liveness probes and the scrape endpoint, which both fire on a fixed interval
+ * and would otherwise drown the `info` stream.
+ */
+export const METRICS_EXCLUDED_PATHS = ['/healthz', '/_health', '/_ready', '/metrics', '/_metrics']
+
+export function isMetricsExcludedPath(path: string): boolean {
+ return METRICS_EXCLUDED_PATHS.some((p) => path === p || path.startsWith(`${p}/`))
+}
+
+let initialized = false
+
+/**
+ * One-time metrics init. Idempotent — `collectDefaultMetrics()` throws on a
+ * second registration, so the guard makes a double-call (e.g. a test importing
+ * two entrypoints) a no-op. Sets a `service` default label so a fleet-wide
+ * query can do `{service="agent-runner"}` even before vmagent's namespace
+ * relabeling is in play.
+ */
+export function initMetrics(opts: { service: string }): void {
+ if (initialized) {
+ return
+ }
+ initialized = true
+ register.setDefaultLabels({ service: opts.service })
+ collectDefaultMetrics()
+}
+
+/**
+ * Server-side latency of inbound HTTP requests, shared by the express-based
+ * services (ingress, janitor). The `route` label is the express route PATTERN
+ * (`/:slug/chat/run`), never the resolved path, so per-agent slugs / session
+ * ids can't blow up cardinality.
+ */
+export const httpRequestDuration = new Histogram({
+ name: 'agent_http_request_duration_seconds',
+ help: 'Duration of inbound HTTP requests handled by an agent service, by route + status.',
+ labelNames: ['method', 'route', 'status_code'],
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
+})
+
+/** Record one completed HTTP request. Framework-agnostic so agent-shared keeps no express dep. */
+export function recordHttpRequest(
+ labels: { method: string; route: string; statusCode: number },
+ durationSeconds: number
+): void {
+ httpRequestDuration
+ .labels({ method: labels.method, route: labels.route, status_code: String(labels.statusCode) })
+ .observe(durationSeconds)
+}
+
+/**
+ * Start the dedicated Prometheus scrape server. Serves `GET /metrics` and
+ * `GET /_metrics` (the chart's default scrape path) from the shared registry;
+ * everything else 404s. Deliberately silent per request — scrapes fire every
+ * ~60s and would otherwise flood the log.
+ */
+export function createMetricsServer(opts: { port: number; log: Logger }): Server {
+ const server = createServer((req, res) => {
+ const url = req.url ?? '/'
+ if (req.method === 'GET' && (url === '/metrics' || url === '/_metrics')) {
+ register
+ .metrics()
+ .then((body) => {
+ res.writeHead(200, { 'content-type': register.contentType })
+ res.end(body)
+ })
+ .catch((err: unknown) => {
+ opts.log.error({ err: err instanceof Error ? err.message : String(err) }, 'metrics.collect_failed')
+ res.writeHead(500)
+ res.end()
+ })
+ return
+ }
+ res.writeHead(404)
+ res.end()
+ })
+ server.listen(opts.port, () => opts.log.info({ port: opts.port }, 'metrics server listening'))
+ return server
+}