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(phai): restore llma-parser-recipe-create on a shared normalizer package (#73224)

Georgiy Tarasov6ea7ccd6041b
diff --git a/.dockerignore b/.dockerignore
index 012c0b973c8d..ed5b8017545e 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -13,6 +13,7 @@
!common/plugin_transpiler/src
!common/tailwind
!packages/quill
+!packages/llm-normalizer
!dags
!docs/onboarding
!ee
@@ -84,6 +85,8 @@ common/*/*/dist
common/*/dist
packages/quill/**/node_modules
packages/quill/**/dist
+packages/llm-normalizer/**/node_modules
+packages/llm-normalizer/**/dist
products/**/node_modules
# Nested standalone workspace, not imported by any server image; `!products` above
# would otherwise pull ~56 MiB of desktop assets into every image build context.
diff --git a/.github/workflows/cd-mcp-image.yml b/.github/workflows/cd-mcp-image.yml
index 1da81f9a14d0..996de5af9409 100644
--- a/.github/workflows/cd-mcp-image.yml
+++ b/.github/workflows/cd-mcp-image.yml
@@ -13,6 +13,11 @@ on:
paths:
- 'services/mcp/**'
- '.github/workflows/cd-mcp-image.yml'
+ # Bundled into the MCP image at build time (copy-instructions.ts `shared/` copy +
+ # shared parser sources) — without these paths an edit there never rebuilds the
+ # image and the bundle goes stale.
+ - 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml'
+ - 'packages/llm-normalizer/**'
# paths mirror the push trigger; the build-mcp-image label only forces a
# build on PRs touching these paths, use workflow_dispatch otherwise.
pull_request:
@@ -20,6 +25,8 @@ on:
paths:
- 'services/mcp/**'
- '.github/workflows/cd-mcp-image.yml'
+ - 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml'
+ - 'packages/llm-normalizer/**'
workflow_dispatch:
jobs:
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index f27cdb73e36d..88dfe2eca6f2 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -61,6 +61,8 @@ jobs:
# MCP service and per-product tool/UI-app configs
- 'services/mcp/**'
- 'products/*/mcp/**'
+ # Bundled into the MCP server (parser recipe tools)
+ - 'packages/llm-normalizer/**'
# MCP integration tests exercise the full PostHog backend
- 'posthog/**/*.py'
- 'ee/**/*.py'
diff --git a/Dockerfile b/Dockerfile
index f935d7805c01..348dd32e79db 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -38,6 +38,7 @@ COPY common/esbuilder/ common/esbuilder/
COPY common/replay-shared/ common/replay-shared/
COPY common/tailwind/ common/tailwind/
COPY packages/quill/ packages/quill/
+COPY packages/llm-normalizer/ packages/llm-normalizer/
COPY products/ products/
COPY docs/onboarding/ docs/onboarding/
RUN --mount=type=cache,id=pnpm,target=/tmp/pnpm-store-v24 \
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index cca37ae16f8c..cf86ba1d2236 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -89,6 +89,7 @@ function rootDirectories(): string[] {
'<rootDir>/../products',
'<rootDir>/../packages/quill/packages/charts/src',
'<rootDir>/../packages/quill/packages/components/src',
+ '<rootDir>/../packages/llm-normalizer/src',
]
}
@@ -216,6 +217,8 @@ const config: Config = {
'^common/(.*)$': '<rootDir>/../common/$1',
'^@posthog/replay-shared$': '<rootDir>/../common/replay-shared/src/index.ts',
'^@posthog/replay-shared/(.*)$': '<rootDir>/../common/replay-shared/src/$1',
+ '^@posthog/llm-normalizer$': '<rootDir>/../packages/llm-normalizer/src/index.ts',
+ '^@posthog/llm-normalizer/(.*)$': '<rootDir>/../packages/llm-normalizer/src/$1',
'^@posthog/quill$': '<rootDir>/../packages/quill/packages/quill/src/index.ts',
'^@posthog/quill-blocks$': '<rootDir>/../packages/quill/packages/blocks/src/index.ts',
'^@posthog/quill-charts$': '<rootDir>/../packages/quill/packages/charts/src/index.ts',
diff --git a/frontend/package.json b/frontend/package.json
index 75987429ca5f..0264955328f9 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -35,7 +35,7 @@
"typegen:write": "cd .. && NODE_OPTIONS=--max-old-space-size=8192 kea-typegen write --delete --show-ts-errors --use-cache",
"typegen:write:no-cache": "cd .. && NODE_OPTIONS=--max-old-space-size=8192 kea-typegen write --delete --show-ts-errors",
"schema:build:json": "ts-node ./bin/build-schema-json.mjs && oxfmt ./src/queries/schema.json && ts-node ./bin/build-validators.mjs && oxfmt ./src/queries/validators.js",
- "test": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo $SHARD_IDX/$SHARD_TOTAL; pnpm build:products && jest --testPathPattern='(frontend/|products/|common/|packages/quill/)' --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL",
+ "test": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo $SHARD_IDX/$SHARD_TOTAL; pnpm build:products && jest --testPathPattern='(frontend/|products/|common/|packages/quill/|packages/llm-normalizer/)' --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL",
"jest": "pnpm build:products && jest",
"typescript:check": "tsgo --noEmit && echo \"No errors reported by tsgo.\"",
"typescript:version": "tsgo --version",
@@ -79,6 +79,7 @@
"@posthog/hogql-parser": "1.3.75",
"@posthog/hogvm": "workspace:*",
"@posthog/icons": "catalog:",
+ "@posthog/llm-normalizer": "workspace:*",
"@posthog/products-access-control": "workspace:*",
"@posthog/products-actions": "workspace:*",
"@posthog/products-ai-gateway": "workspace:*",
diff --git a/packages/llm-normalizer/package.json b/packages/llm-normalizer/package.json
new file mode 100644
index 000000000000..82255d1ef7c1
--- /dev/null
+++ b/packages/llm-normalizer/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@posthog/llm-normalizer",
+ "version": "0.0.1",
+ "private": true,
+ "main": "src/index.ts",
+ "exports": {
+ ".": "./src/index.ts",
+ "./types": "./src/types.ts"
+ },
+ "dependencies": {
+ "yaml": "catalog:"
+ }
+}
diff --git a/packages/llm-normalizer/src/index.ts b/packages/llm-normalizer/src/index.ts
new file mode 100644
index 000000000000..b1884258561d
--- /dev/null
+++ b/packages/llm-normalizer/src/index.ts
@@ -0,0 +1,14 @@
+// Portable LLM analytics message normalizer + recipe DSL. Shared by the PostHog frontend
+// (products/ai_observability) and headless runtimes (services/mcp) — keep it free of
+// browser- and app-coupled imports.
+
+export { RecipeNormalizer } from './normalizer/recipe/recipeNormalizer'
+export type { RunOutcome } from './normalizer/recipe/runtime/pipeline'
+export { mergeRecipes } from './normalizer/recipe/merge'
+export type { StoredRecipe } from './normalizer/recipe/merge'
+export { compileRecipe } from './normalizer/recipe/compile/compiler'
+export { setNormalizerTelemetry } from './normalizer/telemetry'
+export { roleMap, normalizeRole, AVAILABLE_TOOLS_ROLE } from './normalizer/roles'
+export { validateRecipeAgainstSample, handleCreateParserRecipeCall } from './validateRecipe'
+export type { RecipeValidationSample, RecipeVerdict, CreateParserRecipeHandlerDeps } from './validateRecipe'
+export { sampleForContext } from './sampleForContext'
diff --git a/products/ai_observability/frontend/normalizer/index.ts b/packages/llm-normalizer/src/normalizer/index.ts
similarity index 88%
rename from products/ai_observability/frontend/normalizer/index.ts
rename to packages/llm-normalizer/src/normalizer/index.ts
index 212d1347797f..a8e62e01dca6 100644
--- a/products/ai_observability/frontend/normalizer/index.ts
+++ b/packages/llm-normalizer/src/normalizer/index.ts
@@ -6,3 +6,4 @@ export type { RunOutcome } from './recipe/runtime/pipeline'
export { mergeRecipes } from './recipe/merge'
export type { StoredRecipe } from './recipe/merge'
export { compileRecipe } from './recipe/compile/compiler'
+export { setNormalizerTelemetry } from './telemetry'
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/array.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/array.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/array.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/array.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/array.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/array.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/base.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/base.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/base.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/base.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/coalesce.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/coalesce.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/coalesce.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/coalesce.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/filter.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/filter.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/filter.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/filter.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/index.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/index.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/index.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/index.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/interp.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/interp.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/interp.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/interp.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/join.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/join.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/join.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/join.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/join.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/join.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/literal.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/literal.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/literal.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/literal.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/object.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/object.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/object.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/object.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/object.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/object.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/omit.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/omit.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/omit.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/omit.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/path.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/path.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/path.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/path.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/path.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/path.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/reject.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/reject.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/reject.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/reject.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/select.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/select.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/select.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/select.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/select.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/self.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/self.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/self.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/self.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/self.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/self.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/stringify.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/stringify.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/stringify.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/stringify.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/expr/tryParseStructuredContent.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/expr/tryParseStructuredContent.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/base.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/base.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/base.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/base.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/equals.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/equals.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/equals.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/equals.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/every.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/every.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/every.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/every.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/exists.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/exists.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/exists.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/exists.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/in.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/in.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/in.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/in.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/index.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/index.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/index.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/index.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/is.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/is.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/is.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/is.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/pattern.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/pattern.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/pattern.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/pattern.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/shape.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/shape.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/shape.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/shape.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/typeName.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/typeName.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/predicate/typeName.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/predicate/typeName.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.test.ts
similarity index 95%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.test.ts
index 77761b55870b..b93757620c9d 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.test.ts
@@ -1,4 +1,5 @@
import { CompatMessage } from '../../../../types'
+import { ExecutionBudget } from '../../runtime/budget'
import { Scope } from '../../scope'
import { FollowupSpec } from '../../spec/emitSpec'
import { LiteralExpr } from '../expr'
@@ -16,7 +17,7 @@ class TestRule extends Rule {
const scope = Scope.forNode({ role: 'user' }, 'user')
function engineBuilding(build: DispatchEngine['coercer']['buildMessage']): DispatchEngine {
- return { dispatch: jest.fn(), coercer: { buildMessage: build, stamp: jest.fn() } }
+ return { dispatch: jest.fn(), coercer: { buildMessage: build, stamp: jest.fn() }, budget: new ExecutionBudget() }
}
describe('Rule.buildFollowups', () => {
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.ts
similarity index 84%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.ts
index f82905bdf1e3..605ce243e7b2 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/base.ts
@@ -18,6 +18,7 @@ export abstract class Rule {
if (followup.kind === 'static') {
const msg = engine.coercer.buildMessage(followup.emit, scope, /* allowDrop */ true)
if (msg) {
+ engine.budget.chargeMessages(1)
messages.push(msg)
}
continue
@@ -26,9 +27,12 @@ export abstract class Rule {
if (!Array.isArray(arr)) {
continue
}
+ // Charged up front so an expansion over a huge array trips before it is walked.
+ engine.budget.chargeOperations(arr.length)
for (const item of arr) {
const msg = engine.coercer.buildMessage(followup.each, scope.withInput(item))
if (msg) {
+ engine.budget.chargeMessages(1)
messages.push(msg)
}
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegate.test.ts
similarity index 89%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegate.test.ts
index c68a280ca559..015229fd4562 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegate.test.ts
@@ -1,4 +1,5 @@
import { CompatMessage } from '../../../../types'
+import { ExecutionBudget } from '../../runtime/budget'
import { Scope } from '../../scope'
import { LiteralExpr } from '../expr'
import { Pattern } from '../predicate'
@@ -6,12 +7,13 @@ import { DelegateRule } from './delegate'
import { DispatchEngine, NO_MATCH } from './dispatch'
const scope = Scope.forNode({ role: 'assistant' }, 'user')
+const budget = new ExecutionBudget()
describe('DelegateRule', () => {
it('re-dispatches the derived value and returns its messages', () => {
const inner: CompatMessage[] = [{ role: 'assistant', content: 'delegated' }]
const dispatch = jest.fn().mockReturnValue(inner)
- const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+ const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() }, budget }
const rule = new DelegateRule(new Pattern({}), [], new LiteralExpr({ unwrapped: true }))
expect(rule.produce(scope, engine, false, 3)).toBe(inner)
@@ -23,6 +25,7 @@ describe('DelegateRule', () => {
const engine: DispatchEngine = {
dispatch: jest.fn().mockReturnValue(NO_MATCH),
coercer: { buildMessage: jest.fn(), stamp: jest.fn() },
+ budget,
}
const rule = new DelegateRule(new Pattern({}), [], new LiteralExpr('anything'))
expect(rule.produce(scope, engine, false, 0)).toEqual([])
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegate.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegate.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegateEach.test.ts
similarity index 86%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegateEach.test.ts
index 551f5bc73783..805462346f8d 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegateEach.test.ts
@@ -1,4 +1,5 @@
import { CompatMessage } from '../../../../types'
+import { ExecutionBudget } from '../../runtime/budget'
import { Scope } from '../../scope'
import { LiteralExpr } from '../expr'
import { Pattern } from '../predicate'
@@ -6,6 +7,7 @@ import { DelegateEachRule } from './delegateEach'
import { DispatchEngine, NO_MATCH } from './dispatch'
const scope = Scope.forNode({ role: 'user' }, 'user')
+const budget = new ExecutionBudget()
describe('DelegateEachRule', () => {
it('dispatches each element and concatenates the messages', () => {
@@ -13,7 +15,7 @@ describe('DelegateEachRule', () => {
.fn()
.mockReturnValueOnce([{ role: 'user', content: 'a' }])
.mockReturnValueOnce([{ role: 'user', content: 'b' }])
- const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+ const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() }, budget }
const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr(['x', 'y']), null)
expect(rule.produce(scope, engine, false, 0)).toEqual([
@@ -27,6 +29,7 @@ describe('DelegateEachRule', () => {
const engine: DispatchEngine = {
dispatch: jest.fn().mockReturnValue([{ role: 'assistant (tool result)', content: 'r' }]),
coercer: { buildMessage: jest.fn(), stamp },
+ budget,
}
const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr(['x']), {
toolCallId: new LiteralExpr('parent'),
@@ -42,14 +45,18 @@ describe('DelegateEachRule', () => {
.fn()
.mockReturnValueOnce(NO_MATCH)
.mockReturnValueOnce([{ role: 'user', content: 'kept' }])
- const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+ const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() }, budget }
const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr(['skip', 'keep']), null)
expect(rule.produce(scope, engine, false, 0)).toEqual([{ role: 'user', content: 'kept' }])
})
it('returns nothing for a non-array source', () => {
- const engine: DispatchEngine = { dispatch: jest.fn(), coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+ const engine: DispatchEngine = {
+ dispatch: jest.fn(),
+ coercer: { buildMessage: jest.fn(), stamp: jest.fn() },
+ budget,
+ }
const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr('not an array'), null)
expect(rule.produce(scope, engine, false, 0)).toEqual([])
expect(engine.dispatch).not.toHaveBeenCalled()
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegateEach.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/delegateEach.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/dispatch.ts
similarity index 75%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/dispatch.ts
index 0546c3dafcad..856dc6cb3381 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/dispatch.ts
@@ -14,7 +14,15 @@ export interface MessageBuilder {
stamp(message: CompatMessage, emit: EmitSpec, scope: Scope): CompatMessage
}
+// Charged as work happens so a runaway recipe trips a ceiling instead of the process;
+// ExecutionBudget is the implementation.
+export interface WorkBudget {
+ chargeOperations(count: number): void
+ chargeMessages(count: number): void
+}
+
export interface DispatchEngine {
dispatch(input: unknown, inheritedRole: string, depth: number): DispatchResult
readonly coercer: MessageBuilder
+ readonly budget: WorkBudget
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.test.ts
similarity index 91%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.test.ts
index c8152d62e08c..b948cf689801 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.test.ts
@@ -1,4 +1,5 @@
import { CompatMessage } from '../../../../types'
+import { ExecutionBudget } from '../../runtime/budget'
import { Scope } from '../../scope'
import { Pattern } from '../predicate'
import { Rule } from './base'
@@ -11,6 +12,7 @@ function engineReturning(message: CompatMessage | null): DispatchEngine {
return {
dispatch: jest.fn(),
coercer: { buildMessage: jest.fn().mockReturnValue(message), stamp: jest.fn() },
+ budget: new ExecutionBudget(),
}
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.ts
similarity index 84%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.ts
index 13d715a23d6a..159391f72f82 100644
--- a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/emit.ts
@@ -15,6 +15,10 @@ export class EmitRule extends Rule {
}
produce(scope: Scope, engine: DispatchEngine, allowDrop: boolean): CompatMessage[] {
const message = engine.coercer.buildMessage(this.emit, scope, allowDrop)
- return message ? [message] : []
+ if (!message) {
+ return []
+ }
+ engine.budget.chargeMessages(1)
+ return [message]
}
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/index.ts b/packages/llm-normalizer/src/normalizer/recipe/ast/rule/index.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/ast/rule/index.ts
rename to packages/llm-normalizer/src/normalizer/recipe/ast/rule/index.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts b/packages/llm-normalizer/src/normalizer/recipe/compile/compiler.test.ts
similarity index 97%
rename from products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/compile/compiler.test.ts
index 9ce502a8b229..d9230ff13a4c 100644
--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/compile/compiler.test.ts
@@ -1,10 +1,11 @@
import { CompatMessage } from '../../../types'
import { DispatchEngine, NO_MATCH } from '../ast/rule'
+import { ExecutionBudget } from '../runtime/budget'
import { SlotCoercer } from '../runtime/coercion'
import { Scope } from '../scope'
import { compileRecipe } from './compiler'
-const ENGINE: DispatchEngine = { dispatch: () => NO_MATCH, coercer: new SlotCoercer() }
+const ENGINE: DispatchEngine = { dispatch: () => NO_MATCH, coercer: new SlotCoercer(), budget: new ExecutionBudget() }
const INPUT = { name: 'Ada', items: ['a', 'b'] }
// Compile a one-rule recipe and produce its message, so we can observe how the
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts b/packages/llm-normalizer/src/normalizer/recipe/compile/compiler.ts
similarity index 97%
rename from products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
rename to packages/llm-normalizer/src/normalizer/recipe/compile/compiler.ts
index 50ad88ac8207..38022524879a 100644
--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/compile/compiler.ts
@@ -135,11 +135,12 @@ function compilePredicate(raw: unknown): Predicate {
throw new Error(`predicate has multiple verbs (${verbs.join(', ')}); use one verb per field`)
}
if (verbs.length === 1) {
+ const verb = verbs[0]!
if (keys.length > 1) {
const fields = keys.filter((k) => !PREDICATE_VERBS.has(k))
- throw new Error(`predicate verb '${verbs[0]}' cannot be mixed with field keys (${fields.join(', ')})`)
+ throw new Error(`predicate verb '${verb}' cannot be mixed with field keys (${fields.join(', ')})`)
}
- return buildPredicateFromVerb(verbs[0], raw[verbs[0]])
+ return buildPredicateFromVerb(verb, raw[verb])
}
return new ShapePredicate(compilePattern(raw))
}
@@ -232,7 +233,7 @@ function compileValue(raw: unknown): Expr {
if (isObject(raw)) {
const keys = Object.keys(raw)
if (keys.length === 1) {
- const key = keys[0]
+ const key = keys[0]!
if (OPERATORS.has(key)) {
return compileOperator(key, raw[key])
}
@@ -284,7 +285,7 @@ function compileInterp(s: string): Expr {
if (m.index > cursor) {
parts.push(s.slice(cursor, m.index))
}
- parts.push(new PathExpr(m[1].split('.')))
+ parts.push(new PathExpr(m[1]!.split('.')))
cursor = m.index + m[0].length
}
if (cursor < s.length) {
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.test.ts b/packages/llm-normalizer/src/normalizer/recipe/compile/operatorSuggestion.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/compile/operatorSuggestion.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.ts b/packages/llm-normalizer/src/normalizer/recipe/compile/operatorSuggestion.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.ts
rename to packages/llm-normalizer/src/normalizer/recipe/compile/operatorSuggestion.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/anthropic.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/anthropic.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/compat_array.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/compat_array.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/compat_array.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/compat_array.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/dispatcher_entry.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/dispatcher_entry.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/dispatcher_entry.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/dispatcher_entry.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/langchain.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/langchain.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain_envelope.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/langchain_envelope.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain_envelope.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/langchain_envelope.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/litellm.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/litellm.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/litellm.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/litellm.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_chat.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/openai_chat.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_chat.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/openai_chat.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_responses.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/openai_responses.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_responses.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/openai_responses.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/otel.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/otel.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/otel.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/typed_agent_items.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/typed_agent_items.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/vercel_sdk.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/vercel_sdk.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/vercel_sdk.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/vercel_sdk.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/wrappers.yaml b/packages/llm-normalizer/src/normalizer/recipe/default_recipes/wrappers.yaml
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/default_recipes/wrappers.yaml
rename to packages/llm-normalizer/src/normalizer/recipe/default_recipes/wrappers.yaml
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.test.ts b/packages/llm-normalizer/src/normalizer/recipe/merge.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/merge.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/merge.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.ts b/packages/llm-normalizer/src/normalizer/recipe/merge.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/merge.ts
rename to packages/llm-normalizer/src/normalizer/recipe/merge.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/paths.test.ts b/packages/llm-normalizer/src/normalizer/recipe/paths.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/paths.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/paths.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/paths.ts b/packages/llm-normalizer/src/normalizer/recipe/paths.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/paths.ts
rename to packages/llm-normalizer/src/normalizer/recipe/paths.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts b/packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.test.ts
similarity index 98%
rename from products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.test.ts
index 36ce37402286..ef0e4336bd1e 100644
--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.test.ts
@@ -1,4 +1,4 @@
-import { AVAILABLE_TOOLS_ROLE } from '../../utils'
+import { AVAILABLE_TOOLS_ROLE } from '../roles'
import { RecipeNormalizer } from './recipeNormalizer'
const mockRun = jest.fn()
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.ts
similarity index 96%
rename from products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
rename to packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.ts
index 4afc4fbc7b71..df8332cfe9e9 100644
--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/recipeNormalizer.ts
@@ -1,5 +1,5 @@
import { CompatMessage } from '../../types'
-import { AVAILABLE_TOOLS_ROLE } from '../../utils'
+import { AVAILABLE_TOOLS_ROLE } from '../roles'
import { loadRecipes } from './registry'
import { RecipePipeline, RunOutcome } from './runtime/pipeline'
import { Recipe } from './spec/recipe'
diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.test.ts b/packages/llm-normalizer/src/normalizer/recipe/registry.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/registry.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/registry.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.ts b/packages/llm-normalizer/src/normalizer/recipe/registry.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/registry.ts
rename to packages/llm-normalizer/src/normalizer/recipe/registry.ts
diff --git a/packages/llm-normalizer/src/normalizer/recipe/runtime/budget.ts b/packages/llm-normalizer/src/normalizer/recipe/runtime/budget.ts
new file mode 100644
index 000000000000..4fb57cf4c423
--- /dev/null
+++ b/packages/llm-normalizer/src/normalizer/recipe/runtime/budget.ts
@@ -0,0 +1,37 @@
+// Insurance against a recipe that expands a large event into unbounded work. Recipes are
+// team-authored and now also run headless (the MCP tool compiles a candidate and runs it
+// against the real event), so a pathological one has to fail fast instead of pinning the
+// process. Both ceilings sit far above what any renderable trace produces.
+const MAX_OPERATIONS = 250_000
+const MAX_MESSAGES = 25_000
+
+export class ExecutionBudget {
+ // Input nodes dispatched, plus array items a followup expands over.
+ private operations = 0
+ // Messages materialized across the whole run.
+ private messages = 0
+
+ // Charged per run, not per pipeline: the browser keeps one normalizer for the session.
+ reset(): void {
+ this.operations = 0
+ this.messages = 0
+ }
+
+ chargeOperations(count: number): void {
+ this.operations += count
+ if (this.operations > MAX_OPERATIONS) {
+ throw new Error(
+ `RecipeNormalizer: exceeded the operation budget (${MAX_OPERATIONS}) — a recipe expands this event into too much work`
+ )
+ }
+ }
+
+ chargeMessages(count: number): void {
+ this.messages += count
+ if (this.messages > MAX_MESSAGES) {
+ throw new Error(
+ `RecipeNormalizer: exceeded the message budget (${MAX_MESSAGES}) — a recipe expands this event into too many messages`
+ )
+ }
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts b/packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.test.ts
similarity index 95%
rename from products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.test.ts
index fe4e70b6c6de..4a92a08f80d7 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.test.ts
@@ -1,19 +1,19 @@
-import posthog from 'posthog-js'
-
import { CompatMessage } from '../../../types'
+import { setNormalizerTelemetry } from '../../telemetry'
import { LiteralExpr } from '../ast/expr'
import { Scope } from '../scope'
import { EmitSpec } from '../spec/emitSpec'
import { SlotCoercer } from './coercion'
-jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
+const telemetrySpy = jest.fn()
+setNormalizerTelemetry(telemetrySpy)
const coercer = new SlotCoercer()
const scope = (input: unknown = {}, role = 'user'): Scope => Scope.forNode(input, role)
const lit = (value: unknown): LiteralExpr => new LiteralExpr(value)
describe('SlotCoercer.buildMessage', () => {
- beforeEach(() => jest.clearAllMocks())
+ beforeEach(() => telemetrySpy.mockClear())
it('builds a message with role and content', () => {
const emit: EmitSpec = { content: lit('hello') }
@@ -82,7 +82,7 @@ describe('SlotCoercer.buildMessage', () => {
it('non-text content yields an empty string instead of leaking JSON', () => {
const emit: EmitSpec = { content: lit({ unexpected: 'object' }) }
expect(coercer.buildMessage(emit, scope())?.content).toBe('')
- expect(posthog.capture).toHaveBeenCalled()
+ expect(telemetrySpy).toHaveBeenCalled()
})
})
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts b/packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.ts
similarity index 97%
rename from products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts
rename to packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.ts
index ea5a753b4ef9..333d5719b63c 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/runtime/coercion.ts
@@ -1,7 +1,6 @@
-import posthog from 'posthog-js'
-
import { CompatMessage, CompatToolCall, MultiModalContentItem } from '../../../types'
-import { normalizeRole } from '../../../utils'
+import { normalizeRole } from '../../roles'
+import { emitNormalizerTelemetry } from '../../telemetry'
import { Expr } from '../ast/expr'
import { Scope } from '../scope'
import { EmitSpec, RoleTag } from '../spec/emitSpec'
@@ -118,7 +117,7 @@ export class SlotCoercer {
// Reaching here is a recipe bug or coverage gap (recipes opt into rendering
// arbitrary values with `stringify`); surface '' rather than plausible-looking
// JSON, and log type only since the value may be sensitive.
- posthog.capture('llma recipe produced non-text content', { content_type: typeof value })
+ emitNormalizerTelemetry('llma recipe produced non-text content', { content_type: typeof value })
return ''
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts b/packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.test.ts
similarity index 97%
rename from products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.test.ts
index 571cd22d7382..8f2aaee21a43 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.test.ts
@@ -4,8 +4,6 @@ import { Rule } from '../ast/rule'
import { Recipe } from '../spec/recipe'
import { NO_MATCH, RecipePipeline } from './pipeline'
-jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
-
const MATCH_ALL = new Pattern({})
const MATCH_NONE = new Pattern({ __absent: new ExistsPredicate(true) })
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts b/packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.ts
similarity index 94%
rename from products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
rename to packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.ts
index 9b65eeb74f5d..ea7b9d1c8cbf 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/runtime/pipeline.ts
@@ -2,6 +2,7 @@ import { CompatMessage } from '../../../types'
import { DispatchEngine, DispatchResult, NO_MATCH, Rule } from '../ast/rule'
import { Scope } from '../scope'
import { Recipe } from '../spec/recipe'
+import { ExecutionBudget } from './budget'
import { SlotCoercer } from './coercion'
export { NO_MATCH } from '../ast/rule'
@@ -17,6 +18,7 @@ const MAX_DEPTH = 10
export class RecipePipeline implements DispatchEngine {
readonly coercer = new SlotCoercer()
+ readonly budget = new ExecutionBudget()
private readonly recipes: Recipe[]
constructor(recipes: Iterable<Recipe>) {
@@ -24,6 +26,7 @@ export class RecipePipeline implements DispatchEngine {
}
run(input: unknown, defaultRole: string): RunOutcome {
+ this.budget.reset()
const matched = this.matchRecipes(input, defaultRole, 0)
if (matched !== NO_MATCH) {
return { messages: matched, recognized: true }
@@ -45,6 +48,7 @@ export class RecipePipeline implements DispatchEngine {
`RecipeNormalizer: delegation exceeded max depth (${MAX_DEPTH}) — a recipe likely delegates to itself`
)
}
+ this.budget.chargeOperations(1)
for (const recipe of this.recipes) {
for (const rule of recipe.rules) {
const result = this.applyRule(rule, input, inheritedRole, depth)
@@ -63,6 +67,7 @@ export class RecipePipeline implements DispatchEngine {
const role = Scope.forNode(input, inheritedRole).role
const content =
isPlainObject(input) && typeof input.content === 'string' ? input.content : stringifyContent(input)
+ this.budget.chargeMessages(1)
return [{ role, content }]
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/scope.test.ts b/packages/llm-normalizer/src/normalizer/recipe/scope.test.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/scope.test.ts
rename to packages/llm-normalizer/src/normalizer/recipe/scope.test.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/scope.ts b/packages/llm-normalizer/src/normalizer/recipe/scope.ts
similarity index 87%
rename from products/ai_observability/frontend/normalizer/recipe/scope.ts
rename to packages/llm-normalizer/src/normalizer/recipe/scope.ts
index 23b3c01297f6..214aee9aedc3 100644
--- a/products/ai_observability/frontend/normalizer/recipe/scope.ts
+++ b/packages/llm-normalizer/src/normalizer/recipe/scope.ts
@@ -1,7 +1,7 @@
// Per-dispatch context. The role is the only thing that flows parent → child;
// everything else a rule needs comes from `input`.
-import { normalizeRole, roleMap } from '../../utils'
+import { normalizeRole, roleMap } from '../roles'
export class Scope {
private constructor(
@@ -28,7 +28,7 @@ function resolveRole(input: unknown, inheritedRole: string): string {
if (typeof obj.role === 'string') {
return normalizeRole(obj.role, inheritedRole)
}
- if (typeof obj.type === 'string' && Object.hasOwn(roleMap, obj.type)) {
+ if (typeof obj.type === 'string' && Object.prototype.hasOwnProperty.call(roleMap, obj.type)) {
return normalizeRole(obj.type, inheritedRole)
}
return inheritedRole
diff --git a/products/ai_observability/frontend/normalizer/recipe/spec/emitSpec.ts b/packages/llm-normalizer/src/normalizer/recipe/spec/emitSpec.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/spec/emitSpec.ts
rename to packages/llm-normalizer/src/normalizer/recipe/spec/emitSpec.ts
diff --git a/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts b/packages/llm-normalizer/src/normalizer/recipe/spec/recipe.ts
similarity index 100%
rename from products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
rename to packages/llm-normalizer/src/normalizer/recipe/spec/recipe.ts
diff --git a/packages/llm-normalizer/src/normalizer/roles.ts b/packages/llm-normalizer/src/normalizer/roles.ts
new file mode 100644
index 000000000000..ee444a991269
--- /dev/null
+++ b/packages/llm-normalizer/src/normalizer/roles.ts
@@ -0,0 +1,24 @@
+export const roleMap: Record<string, string> = {
+ user: 'user',
+ human: 'user',
+
+ assistant: 'assistant',
+ model: 'assistant',
+ ai: 'assistant',
+ bot: 'assistant',
+
+ system: 'system',
+ instructions: 'system',
+ context: 'system',
+}
+
+export function normalizeRole(rawRole: unknown, fallback: string): string {
+ if (typeof rawRole !== 'string') {
+ return fallback
+ }
+ const lowercased = rawRole.toLowerCase()
+ return roleMap[lowercased] || lowercased
+}
+
+// Synthetic role used to surface the `$ai_tools` payload as a pseudo-message
+export const AVAILABLE_TOOLS_ROLE = 'available tools'
diff --git a/packages/llm-normalizer/src/normalizer/telemetry.ts b/packages/llm-normalizer/src/normalizer/telemetry.ts
new file mode 100644
index 000000000000..2b1872626f42
--- /dev/null
+++ b/packages/llm-normalizer/src/normalizer/telemetry.ts
@@ -0,0 +1,15 @@
+// Telemetry sink for the recipe normalizer. Kept injectable so the normalizer
+// stays portable to Node (MCP server, tasks sandbox) — the browser wires a
+// `posthog.capture` callback via `setNormalizerTelemetry`; elsewhere it's a noop.
+
+type NormalizerTelemetryCallback = (event: string, properties: Record<string, unknown>) => void
+
+let telemetryCallback: NormalizerTelemetryCallback = () => {}
+
+export function setNormalizerTelemetry(callback: NormalizerTelemetryCallback): void {
+ telemetryCallback = callback
+}
+
+export function emitNormalizerTelemetry(event: string, properties: Record<string, unknown>): void {
+ telemetryCallback(event, properties)
+}
diff --git a/products/ai_observability/frontend/customParser/sampleForContext.test.ts b/packages/llm-normalizer/src/sampleForContext.test.ts
similarity index 100%
rename from products/ai_observability/frontend/customParser/sampleForContext.test.ts
rename to packages/llm-normalizer/src/sampleForContext.test.ts
diff --git a/products/ai_observability/frontend/customParser/sampleForContext.ts b/packages/llm-normalizer/src/sampleForContext.ts
similarity index 100%
rename from products/ai_observability/frontend/customParser/sampleForContext.ts
rename to packages/llm-normalizer/src/sampleForContext.ts
diff --git a/packages/llm-normalizer/src/types.ts b/packages/llm-normalizer/src/types.ts
new file mode 100644
index 000000000000..b27f009a2159
--- /dev/null
+++ b/packages/llm-normalizer/src/types.ts
@@ -0,0 +1,299 @@
+export interface DateRangeFilter {
+ dateFrom: string | null
+ dateTo: string | null
+}
+
+export interface RoleBasedMessage {
+ role: string
+ content: string | { type: string; content: string } | MultiModalContentItem[]
+}
+
+export interface StringContentObject {
+ content: string
+}
+
+export interface OpenAIToolCall {
+ type: string
+ id?: string
+ function: {
+ name: string
+ arguments: string
+ }
+}
+
+export interface OpenAICompletionMessage extends RoleBasedMessage {
+ tool_calls?: Record<string, any>[]
+ [additionalKey: string]: any
+}
+
+export interface AnthropicTextMessage {
+ type: 'text'
+ text: string
+}
+
+export interface VercelSDKTextMessage {
+ type: 'text'
+ content: string
+}
+
+export interface VercelSDKImageMessage {
+ type: 'image'
+ image: string
+}
+
+export interface VercelSDKInputImageMessage {
+ type: 'input_image'
+ image_url: string
+}
+
+export interface OpenAIImageURLMessage {
+ type: 'image_url'
+ image_url: {
+ url: string
+ }
+}
+
+export interface OpenAIFileMessage {
+ type: 'file'
+ file: {
+ file_data: string
+ filename: string
+ }
+}
+
+export interface OpenAIAudioMessage {
+ type: 'audio'
+ data: string
+ transcript: string
+ id: string
+ expires_at: number
+}
+
+export interface AnthropicImageMessage {
+ type: 'image'
+ source: {
+ type: 'base64'
+ media_type: string
+ data: string
+ }
+}
+
+export interface AnthropicDocumentMessage {
+ type: 'document'
+ source: {
+ type: 'base64'
+ media_type: string
+ data: string
+ }
+}
+
+export interface GeminiAudioMessage {
+ type: 'audio'
+ data: string
+ mime_type: string
+}
+
+export interface GeminiImageMessage {
+ type: 'image'
+ // snake_case (Python SDK)
+ inline_data?: {
+ data: string
+ mime_type: string
+ }
+ // camelCase (Node SDK)
+ inlineData?: {
+ data: string
+ mimeType: string
+ }
+}
+
+export interface GeminiDocumentMessage {
+ type: 'document' | 'image' // 'image' when SDK misdetects PDF by MIME type
+ // snake_case (Python SDK)
+ inline_data?: {
+ data: string
+ mime_type: string
+ }
+ // camelCase (Node SDK)
+ inlineData?: {
+ data: string
+ mimeType: string
+ }
+}
+
+export interface VercelSDKInputTextMessage {
+ type: 'input_text'
+ text: string
+}
+
+export interface VercelSDKToolCallFunctionMessage {
+ type: 'tool-call'
+ id?: string
+ function: {
+ name: string
+ arguments: string | Record<string, unknown>
+ }
+ toolCallId?: string
+ toolName?: string
+ [key: string]: unknown
+}
+
+export interface VercelSDKToolCallToolNameMessage {
+ type: 'tool-call'
+ id?: string
+ function?: undefined
+ toolCallId?: string
+ toolName: string
+ input?: Record<string, unknown> | string
+ [key: string]: unknown
+}
+
+export type VercelSDKToolCallMessage = VercelSDKToolCallFunctionMessage | VercelSDKToolCallToolNameMessage
+
+export interface VercelSDKToolResultMessage {
+ type: 'tool-result'
+ toolCallId?: string
+ toolName: string
+ output?: unknown
+ [key: string]: unknown
+}
+
+export interface AnthropicToolCallMessage {
+ type: 'tool_use'
+ id: string
+ name: string
+ input: Record<string, any>
+}
+
+export interface AnthropicThinkingMessage {
+ type: 'thinking'
+ thinking: string
+ signature: string
+}
+
+export interface AnthropicToolResultMessage {
+ type: 'tool_result'
+ tool_use_id: string
+ content: string | AnthropicTextMessage[]
+}
+
+export type AnthropicCompletionMessage = AnthropicTextMessage | AnthropicToolCallMessage | AnthropicToolResultMessage
+
+export interface AnthropicInputMessage {
+ role: string
+ content: string | AnthropicCompletionMessage[]
+}
+
+// OpenAI Responses API types (role-less, use `type` instead)
+export interface OpenAIResponsesFunctionCall {
+ type: 'function_call'
+ call_id: string
+ name: string
+ arguments: string
+ id?: string
+ status?: string
+}
+
+export interface OpenAIResponsesFunctionCallOutput {
+ type: 'function_call_output'
+ call_id: string
+ output: string
+}
+
+/** Responses API built-in tool calls (web_search_call, reasoning, etc.) */
+export interface OpenAIResponsesBuiltinToolCall {
+ type:
+ | 'web_search_call'
+ | 'code_interpreter_call'
+ | 'image_generation_call'
+ | 'mcp_call'
+ | 'file_search_call'
+ | 'computer_call'
+ id?: string
+ status?: string
+ [key: string]: unknown
+}
+
+export interface OpenAIResponsesReasoning {
+ type: 'reasoning'
+ id?: string
+ summary?: { type: string; text: string }[]
+ [key: string]: unknown
+}
+
+export type InputMessage = OpenAICompletionMessage | AnthropicInputMessage
+export type CompletionMessage = OpenAICompletionMessage | AnthropicCompletionMessage
+
+export interface CompatToolCall {
+ type: string
+ id?: string
+ function: {
+ name: string
+ arguments: Record<string, any> | string // Allow string for unparsed/malformed JSON
+ }
+}
+
+export interface CompatMessage extends RoleBasedMessage {
+ tool_calls?: CompatToolCall[]
+ [additionalKey: string]: any
+ tool_call_id?: string
+}
+
+export interface LiteLLMChoice {
+ finish_reason: string
+ index: number
+ message: {
+ annotations?: any[]
+ content: string | null
+ function_call?: any
+ role: string
+ tool_calls?: any[] | null
+ }
+ provider_specific_fields?: Record<string, any>
+}
+
+export interface LiteLLMResponse {
+ choices?: LiteLLMChoice[]
+ [additionalKey: string]: any
+}
+
+export interface TextContentItem {
+ type: 'text'
+ text: string
+}
+
+export interface OutputTextContentItem {
+ type: 'output_text'
+ text: string
+}
+
+export interface ImageContentItem {
+ type: 'image'
+ image: string
+}
+
+export interface FunctionContentItem {
+ type: 'function'
+ id?: string
+ function: {
+ name: string
+ arguments: string | Record<string, unknown> | null
+ }
+}
+
+export type MultiModalContentItem =
+ | string
+ | TextContentItem
+ | OutputTextContentItem
+ | ImageContentItem
+ | FunctionContentItem
+ | VercelSDKInputTextMessage
+ | VercelSDKInputImageMessage
+ | OpenAIImageURLMessage
+ | OpenAIFileMessage
+ | OpenAIAudioMessage
+ | AnthropicImageMessage
+ | AnthropicDocumentMessage
+ | GeminiImageMessage
+ | GeminiDocumentMessage
+ | GeminiAudioMessage
diff --git a/products/ai_observability/frontend/customParser/validateRecipe.test.ts b/packages/llm-normalizer/src/validateRecipe.test.ts
similarity index 89%
rename from products/ai_observability/frontend/customParser/validateRecipe.test.ts
rename to packages/llm-normalizer/src/validateRecipe.test.ts
index f16d0f219c48..579c10a47aeb 100644
--- a/products/ai_observability/frontend/customParser/validateRecipe.test.ts
+++ b/packages/llm-normalizer/src/validateRecipe.test.ts
@@ -67,6 +67,28 @@ describe('custom parser validation', () => {
expect(verdict.error).toContain('failed while running against the sample')
})
+ it('rejects a recipe that expands the sample past the runtime work budget', () => {
+ const expanding = `
+rules:
+ - on:
+ acme_kind: q
+ emit:
+ content: ''
+ followups:
+ - from: $.acme_items
+ each:
+ role: user
+ content: $.text
+`
+ const verdict = validateRecipeAgainstSample(expanding, [], {
+ ...sample,
+ input: { acme_kind: 'q', acme_items: Array.from({ length: 30_000 }, () => ({ text: 'x' })) },
+ })
+
+ expect(verdict.valid).toBe(false)
+ expect(verdict.error).toContain('budget')
+ })
+
it('accepts a recipe whose rules match the elements of an array input', () => {
// Top-level arrays are unwrapped by a built-in rule; elements re-match all recipes.
const verdict = validateRecipeAgainstSample(MATCHING_RECIPE, [], {
diff --git a/products/ai_observability/frontend/customParser/validateRecipe.ts b/packages/llm-normalizer/src/validateRecipe.ts
similarity index 99%
rename from products/ai_observability/frontend/customParser/validateRecipe.ts
rename to packages/llm-normalizer/src/validateRecipe.ts
index b520f7500f08..56e63845398a 100644
--- a/products/ai_observability/frontend/customParser/validateRecipe.ts
+++ b/packages/llm-normalizer/src/validateRecipe.ts
@@ -1,6 +1,6 @@
import { parse as parseYaml } from 'yaml'
-import { compileRecipe, mergeRecipes, RecipeNormalizer, RunOutcome, StoredRecipe } from '../normalizer'
+import { compileRecipe, mergeRecipes, RecipeNormalizer, RunOutcome, StoredRecipe } from './normalizer'
export interface RecipeValidationSample {
input: unknown
diff --git a/packages/llm-normalizer/src/yaml.d.ts b/packages/llm-normalizer/src/yaml.d.ts
new file mode 100644
index 000000000000..0c8153a82f23
--- /dev/null
+++ b/packages/llm-normalizer/src/yaml.d.ts
@@ -0,0 +1,4 @@
+declare module '*.yaml?raw' {
+ const content: string
+ export default content
+}
diff --git a/packages/llm-normalizer/tsconfig.json b/packages/llm-normalizer/tsconfig.json
new file mode 100644
index 000000000000..c3dbb01e7578
--- /dev/null
+++ b/packages/llm-normalizer/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "esModuleInterop": true,
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true
+ },
+ "include": ["src"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ad53899e32a6..04252e50b1a7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -632,6 +632,9 @@ importers:
'@posthog/icons':
specifier: 'catalog:'
+ '@posthog/llm-normalizer':
+ specifier: workspace:*
+ version: link:../packages/llm-normalizer
'@posthog/products-access-control':
specifier: workspace:*
version: link:../products/access_control
@@ -1893,6 +1896,12 @@ importers:
specifier: ^4.7.0
version: 4.20.5
+ packages/llm-normalizer:
+ dependencies:
+ yaml:
+ specifier: 'catalog:'
+ version: 2.9.0
+
packages/quill:
devDependencies:
tailwindcss-scroll-mask:
@@ -4780,6 +4789,9 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.29.0
version: 1.29.0(@cfworker/[email protected])([email protected])
+ '@posthog/llm-normalizer':
+ specifier: workspace:*
+ version: link:../../packages/llm-normalizer
'@posthog/mcp-analytics':
specifier: npm:@posthog/[email protected]
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 4274d4a42200..04a379f9df46 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -7,6 +7,7 @@ packages:
- common/replay-shared
- common/replay-headless
- common/tailwind
+ - packages/llm-normalizer
- packages/quill
- packages/quill/apps/*
- packages/quill/packages/*
diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
index 7eea5a096600..6dd959cfb660 100644
--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
@@ -105,6 +105,7 @@ export function EventContentConversation({
const openCustomParserMax = useCustomParserMaxTool({
eventId,
+ traceId,
input,
output,
tools: loadedTools,
diff --git a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts
index 9f4d649e0dff..57439b200636 100644
--- a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts
+++ b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts
@@ -2,21 +2,36 @@ import { useActions, useValues } from 'kea'
import { useCallback, useMemo } from 'react'
import { lemonToast } from '@posthog/lemon-ui'
+import { handleCreateParserRecipeCall, sampleForContext } from '@posthog/llm-normalizer'
import { useMaxTool } from 'scenes/max/useMaxTool'
import { teamLogic } from 'scenes/teamLogic'
-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { llmAnalyticsParserRecipesCreate } from '../generated/api'
import { parserRecipesLogic } from '../settings/parserRecipesLogic'
-import { sampleForContext } from './sampleForContext'
-import { handleCreateParserRecipeCall } from './validateRecipe'
const MAX_EXISTING_RECIPES_CONTEXT_LENGTH = 4000
+// Static, trusted instruction — never interpolate user or ingested trace data into it.
+// Points the headless agent at the reference + create tools and the trace_id/event_uuid it
+// finds in the untrusted trace-event sample block.
+const AI_TRACE_PARSER_TOOL_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ 'The user has an LLM trace event open that fell back to raw JSON because no parser recognized it. ' +
+ 'To fix it, first call llma-parser-recipe-reference for the recipe DSL syntax and examples, then call ' +
+ 'llma-parser-recipe-create with the trace_id and event_uuid from the attached trace event sample. The ' +
+ 'samples in context are truncated, but the server compiles and validates your recipe against the full ' +
+ 'event and only saves it when it works. The open trace re-renders once the recipe is saved.',
+}
+
export interface CustomParserMaxToolOptions {
eventId: string
+ traceId?: string | null
input: unknown
output: unknown
tools?: unknown
@@ -33,6 +48,7 @@ export interface CustomParserMaxToolOptions {
*/
export function useCustomParserMaxTool({
eventId,
+ traceId,
input,
output,
tools,
@@ -105,10 +121,13 @@ export function useCustomParserMaxTool({
useAttachedContext(
active
? [
+ AI_TRACE_PARSER_TOOL_CONTEXT_ITEM,
{ type: 'llm_trace_event', key: eventId },
{
type: 'ai_trace_parser_context',
value: JSON.stringify({
+ trace_id: traceId ?? null,
+ event_uuid: eventId,
event_type: isGeneration ? 'generation' : 'span',
unrecognized,
sample_input: sampleForContext(input),
@@ -120,6 +139,32 @@ export function useCustomParserMaxTool({
: null
)
+ // Headless mirror: when the agent's llma-parser-recipe-create tool completes, reload the team's
+ // recipes so the live normalizer re-renders the open trace. loadRecipes is idempotent, so we run
+ // it on every completion regardless of whether the tool actually saved.
+ useMcpToolApplyBack({
+ tools: ['llma-parser-recipe-create'],
+ targetKey: 'ai-trace-parser',
+ active,
+ onApply: (event, { innerInput }) => {
+ loadRecipes()
+ // A create for a different event must not claim this one was fixed; when the
+ // args are unparseable we keep the toast, matching the pre-innerInput behavior.
+ if (innerInput && typeof innerInput.event_uuid === 'string' && innerInput.event_uuid !== eventId) {
+ return
+ }
+ try {
+ const output = event.invocation.output
+ const serialized = typeof output === 'string' ? output : JSON.stringify(output)
+ if (serialized && serialized.includes('recipe_id')) {
+ lemonToast.success('Custom parser saved')
+ }
+ } catch {
+ // Output shape is client-profile-dependent — the agent narrates failures in chat.
+ }
+ },
+ })
+
const { openMax } = useMaxTool({
identifier: 'create_ai_trace_parser',
active,
diff --git a/products/ai_observability/frontend/normalizer/recipe/dslExamples.test.ts b/products/ai_observability/frontend/dslExamples.test.ts
similarity index 84%
rename from products/ai_observability/frontend/normalizer/recipe/dslExamples.test.ts
rename to products/ai_observability/frontend/dslExamples.test.ts
index 25e30523254f..37fbcf2500bb 100644
--- a/products/ai_observability/frontend/normalizer/recipe/dslExamples.test.ts
+++ b/products/ai_observability/frontend/dslExamples.test.ts
@@ -2,12 +2,13 @@ import * as fs from 'fs'
import * as path from 'path'
import { parse as parseYaml } from 'yaml'
-import { compileRecipe } from './compile/compiler'
-import { RecipeNormalizer } from './recipeNormalizer'
+import { compileRecipe, RecipeNormalizer } from '@posthog/llm-normalizer'
// The examples file is the DSL reference embedded in the create_ai_trace_parser tool prompt;
// running every documented example against the real compiler keeps the prompt from drifting.
-const EXAMPLES_PATH = path.resolve(__dirname, '../../../backend/prompts/parser_recipe_examples.yaml')
+// The test lives next to the yaml (not in the normalizer package) because the prompt is
+// owned by this product's backend.
+const EXAMPLES_PATH = path.resolve(__dirname, '../backend/prompts/parser_recipe_examples.yaml')
interface ExampleCase {
input: unknown
diff --git a/products/ai_observability/frontend/messageNormalization.ts b/products/ai_observability/frontend/messageNormalization.ts
index 0a76d235a38f..df4752788d76 100644
--- a/products/ai_observability/frontend/messageNormalization.ts
+++ b/products/ai_observability/frontend/messageNormalization.ts
@@ -1,10 +1,21 @@
import posthog from 'posthog-js'
-import { mergeRecipes, RecipeNormalizer, RunOutcome, StoredRecipe } from './normalizer'
+import {
+ mergeRecipes,
+ RecipeNormalizer,
+ RunOutcome,
+ setNormalizerTelemetry,
+ StoredRecipe,
+} from '@posthog/llm-normalizer'
+
import { CompatMessage } from './types'
export type NormalizationResult = RunOutcome
+// Route the portable normalizer's telemetry back through posthog-js in the browser.
+// Headless callers (MCP server, tasks sandbox) leave the noop default in place.
+setNormalizerTelemetry((event, properties) => posthog.capture(event, properties))
+
// Constructed once: the constructor compiles and sorts every recipe, so per-call
// construction would be wasteful.
const recipeNormalizer = new RecipeNormalizer()
diff --git a/products/ai_observability/frontend/settings/parserRecipesLogic.ts b/products/ai_observability/frontend/settings/parserRecipesLogic.ts
index e19bf05f1d94..d1cfc7820bde 100644
--- a/products/ai_observability/frontend/settings/parserRecipesLogic.ts
+++ b/products/ai_observability/frontend/settings/parserRecipesLogic.ts
@@ -4,6 +4,7 @@ import { subscriptions } from 'kea-subscriptions'
import { parse as parseYaml } from 'yaml'
import { lemonToast } from '@posthog/lemon-ui'
+import { compileRecipe, StoredRecipe } from '@posthog/llm-normalizer'
import { teamLogic } from 'scenes/teamLogic'
@@ -15,7 +16,6 @@ import {
} from '../generated/api'
import { ParserRecipeApi } from '../generated/api.schemas'
import { applyTeamParserRecipes } from '../messageNormalization'
-import { compileRecipe, StoredRecipe } from '../normalizer'
export interface CustomRecipeItem {
id: string
diff --git a/products/ai_observability/frontend/types.ts b/products/ai_observability/frontend/types.ts
index b27f009a2159..9862545034c1 100644
--- a/products/ai_observability/frontend/types.ts
+++ b/products/ai_observability/frontend/types.ts
@@ -1,299 +1,4 @@
-export interface DateRangeFilter {
- dateFrom: string | null
- dateTo: string | null
-}
-
-export interface RoleBasedMessage {
- role: string
- content: string | { type: string; content: string } | MultiModalContentItem[]
-}
-
-export interface StringContentObject {
- content: string
-}
-
-export interface OpenAIToolCall {
- type: string
- id?: string
- function: {
- name: string
- arguments: string
- }
-}
-
-export interface OpenAICompletionMessage extends RoleBasedMessage {
- tool_calls?: Record<string, any>[]
- [additionalKey: string]: any
-}
-
-export interface AnthropicTextMessage {
- type: 'text'
- text: string
-}
-
-export interface VercelSDKTextMessage {
- type: 'text'
- content: string
-}
-
-export interface VercelSDKImageMessage {
- type: 'image'
- image: string
-}
-
-export interface VercelSDKInputImageMessage {
- type: 'input_image'
- image_url: string
-}
-
-export interface OpenAIImageURLMessage {
- type: 'image_url'
- image_url: {
- url: string
- }
-}
-
-export interface OpenAIFileMessage {
- type: 'file'
- file: {
- file_data: string
- filename: string
- }
-}
-
-export interface OpenAIAudioMessage {
- type: 'audio'
- data: string
- transcript: string
- id: string
- expires_at: number
-}
-
-export interface AnthropicImageMessage {
- type: 'image'
- source: {
- type: 'base64'
- media_type: string
- data: string
- }
-}
-
-export interface AnthropicDocumentMessage {
- type: 'document'
- source: {
- type: 'base64'
- media_type: string
- data: string
- }
-}
-
-export interface GeminiAudioMessage {
- type: 'audio'
- data: string
- mime_type: string
-}
-
-export interface GeminiImageMessage {
- type: 'image'
- // snake_case (Python SDK)
- inline_data?: {
- data: string
- mime_type: string
- }
- // camelCase (Node SDK)
- inlineData?: {
- data: string
- mimeType: string
- }
-}
-
-export interface GeminiDocumentMessage {
- type: 'document' | 'image' // 'image' when SDK misdetects PDF by MIME type
- // snake_case (Python SDK)
- inline_data?: {
- data: string
- mime_type: string
- }
- // camelCase (Node SDK)
- inlineData?: {
- data: string
- mimeType: string
- }
-}
-
-export interface VercelSDKInputTextMessage {
- type: 'input_text'
- text: string
-}
-
-export interface VercelSDKToolCallFunctionMessage {
- type: 'tool-call'
- id?: string
- function: {
- name: string
- arguments: string | Record<string, unknown>
- }
- toolCallId?: string
- toolName?: string
- [key: string]: unknown
-}
-
-export interface VercelSDKToolCallToolNameMessage {
- type: 'tool-call'
- id?: string
- function?: undefined
- toolCallId?: string
- toolName: string
- input?: Record<string, unknown> | string
- [key: string]: unknown
-}
-
-export type VercelSDKToolCallMessage = VercelSDKToolCallFunctionMessage | VercelSDKToolCallToolNameMessage
-
-export interface VercelSDKToolResultMessage {
- type: 'tool-result'
- toolCallId?: string
- toolName: string
- output?: unknown
- [key: string]: unknown
-}
-
-export interface AnthropicToolCallMessage {
- type: 'tool_use'
- id: string
- name: string
- input: Record<string, any>
-}
-
-export interface AnthropicThinkingMessage {
- type: 'thinking'
- thinking: string
- signature: string
-}
-
-export interface AnthropicToolResultMessage {
- type: 'tool_result'
- tool_use_id: string
- content: string | AnthropicTextMessage[]
-}
-
-export type AnthropicCompletionMessage = AnthropicTextMessage | AnthropicToolCallMessage | AnthropicToolResultMessage
-
-export interface AnthropicInputMessage {
- role: string
- content: string | AnthropicCompletionMessage[]
-}
-
-// OpenAI Responses API types (role-less, use `type` instead)
-export interface OpenAIResponsesFunctionCall {
- type: 'function_call'
- call_id: string
- name: string
- arguments: string
- id?: string
- status?: string
-}
-
-export interface OpenAIResponsesFunctionCallOutput {
- type: 'function_call_output'
- call_id: string
- output: string
-}
-
-/** Responses API built-in tool calls (web_search_call, reasoning, etc.) */
-export interface OpenAIResponsesBuiltinToolCall {
- type:
- | 'web_search_call'
- | 'code_interpreter_call'
- | 'image_generation_call'
- | 'mcp_call'
- | 'file_search_call'
- | 'computer_call'
- id?: string
- status?: string
- [key: string]: unknown
-}
-
-export interface OpenAIResponsesReasoning {
- type: 'reasoning'
- id?: string
- summary?: { type: string; text: string }[]
- [key: string]: unknown
-}
-
-export type InputMessage = OpenAICompletionMessage | AnthropicInputMessage
-export type CompletionMessage = OpenAICompletionMessage | AnthropicCompletionMessage
-
-export interface CompatToolCall {
- type: string
- id?: string
- function: {
- name: string
- arguments: Record<string, any> | string // Allow string for unparsed/malformed JSON
- }
-}
-
-export interface CompatMessage extends RoleBasedMessage {
- tool_calls?: CompatToolCall[]
- [additionalKey: string]: any
- tool_call_id?: string
-}
-
-export interface LiteLLMChoice {
- finish_reason: string
- index: number
- message: {
- annotations?: any[]
- content: string | null
- function_call?: any
- role: string
- tool_calls?: any[] | null
- }
- provider_specific_fields?: Record<string, any>
-}
-
-export interface LiteLLMResponse {
- choices?: LiteLLMChoice[]
- [additionalKey: string]: any
-}
-
-export interface TextContentItem {
- type: 'text'
- text: string
-}
-
-export interface OutputTextContentItem {
- type: 'output_text'
- text: string
-}
-
-export interface ImageContentItem {
- type: 'image'
- image: string
-}
-
-export interface FunctionContentItem {
- type: 'function'
- id?: string
- function: {
- name: string
- arguments: string | Record<string, unknown> | null
- }
-}
-
-export type MultiModalContentItem =
- | string
- | TextContentItem
- | OutputTextContentItem
- | ImageContentItem
- | FunctionContentItem
- | VercelSDKInputTextMessage
- | VercelSDKInputImageMessage
- | OpenAIImageURLMessage
- | OpenAIFileMessage
- | OpenAIAudioMessage
- | AnthropicImageMessage
- | AnthropicDocumentMessage
- | GeminiImageMessage
- | GeminiDocumentMessage
- | GeminiAudioMessage
+// The compat message/trace types moved to the shared @posthog/llm-normalizer package so
+// services/mcp can use them without importing products/. Re-exported here so the many
+// in-product consumers keep their import path.
+export * from '@posthog/llm-normalizer/types'
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 45928bd8aced..c0784d8883e0 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -1,6 +1,7 @@
+import { RecipeNormalizer } from '@posthog/llm-normalizer'
+
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
-import { RecipeNormalizer } from './normalizer'
import { AnthropicInputMessage, CompatMessage, OpenAICompletionMessage } from './types'
import {
asString,
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index f36f39beb600..a2684f0b6f1d 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -828,30 +828,9 @@ export function isOTelPartsMessage(input: unknown): input is OTelPartsMessage {
)
}
-export const roleMap: Record<string, string> = {
- user: 'user',
- human: 'user',
-
- assistant: 'assistant',
- model: 'assistant',
- ai: 'assistant',
- bot: 'assistant',
-
- system: 'system',
- instructions: 'system',
- context: 'system',
-}
-
-export function normalizeRole(rawRole: unknown, fallback: string): string {
- if (typeof rawRole !== 'string') {
- return fallback
- }
- const lowercased = rawRole.toLowerCase()
- return roleMap[lowercased] || lowercased
-}
-
-// Synthetic role used to surface the `$ai_tools` payload as a pseudo-message
-export const AVAILABLE_TOOLS_ROLE = 'available tools'
+// Role helpers live in the portable normalizer module (leaf, no browser deps);
+// re-exported here so the many frontend consumers keep their import paths.
+export { roleMap, normalizeRole, AVAILABLE_TOOLS_ROLE } from '@posthog/llm-normalizer'
export const INTERNAL_THINKING_ROLE = 'assistant (thinking)'
export const INTERNAL_TOOL_RESULT_ROLE = 'assistant (tool result)'
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index 57e2a4904f94..d43895dd4c77 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -162,6 +162,7 @@ const PERSIST_PROMPT_SUB_TOOLS = new Set([
'cdp-functions-create',
'workflows-create',
'workflows-create-email-template',
+ 'llma-parser-recipe-create',
])
/**
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 4fe6f0e6716b..cdf6d4d406d9 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -243,6 +243,7 @@ POSTHOG_EXEC_PERSIST_SUB_TOOLS: tuple[str, ...] = (
"cdp-functions-create",
"workflows-create",
"workflows-create-email-template",
+ "llma-parser-recipe-create",
)
POSTHOG_EXEC_PERMISSION_REGEX = (
diff --git a/services/mcp/Dockerfile b/services/mcp/Dockerfile
index ace4106d4f16..4f6c4775a4a1 100644
--- a/services/mcp/Dockerfile
+++ b/services/mcp/Dockerfile
@@ -38,12 +38,9 @@ COPY patches/ patches/
# source after, so source edits don't bust the install cache.
COPY services/mcp/package.json services/mcp/package.json
COPY tools/openapi-codegen/package.json tools/openapi-codegen/package.json
-# @posthog/mcp depends on @posthog/products-ai-observability (workspace:*) —
-# pnpm needs its manifest to resolve the dependency graph and install its
-# transitive deps (e.g. yaml).
-COPY products/ai_observability/package.json products/ai_observability/package.json
-# UI apps depend on @posthog/quill — copy all its workspace manifests so pnpm
-# can resolve the full dependency graph during install.
+# UI apps depend on @posthog/quill, and the parser tools on @posthog/llm-normalizer —
+# copy all workspace package manifests so pnpm can resolve the full dependency
+# graph during install.
COPY packages/ packages/
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
diff --git a/services/mcp/package.json b/services/mcp/package.json
index e51d2caa84d4..7a7318a0e817 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -51,6 +51,7 @@
"@hono/node-server": "^2.0.2",
"@modelcontextprotocol/ext-apps": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.29.0",
+ "@posthog/llm-normalizer": "workspace:*",
"@posthog/mcp-analytics": "npm:@posthog/[email protected]",
"@posthog/quill": "workspace:*",
"@posthog/quill-charts": "workspace:*",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4a40436653d4..71020d995410 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5925,6 +5925,34 @@
"readOnlyHint": false
}
},
+ "llma-parser-recipe-create": {
+ "description": "Writes and saves a custom LLM analytics parser recipe so an unparsed trace event renders as a readable conversation. Call `llma-parser-recipe-reference` first to get the recipe DSL syntax and worked examples. The server loads the exact event (by trace_id + event_uuid), compiles your YAML, and validates it against that event, saving the recipe only when a previously-unrecognized input or output side becomes recognized. If the result is not valid, read the error, fix the YAML, and call again in the same turn; stop after about three failed attempts and explain what is blocking you. Do not force non-conversational data into a fake conversation shape — if the event genuinely is not a conversation, say so instead of inventing rules. Samples in your context are truncated, but the server always validates against the full event.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Compiles, validates, and saves a custom parser recipe for an LLM analytics trace event.",
+ "title": "Create parser recipe",
+ "required_scopes": ["llm_analytics:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-parser-recipe-reference": {
+ "description": "Returns the LLM analytics parser recipe DSL reference: the syntax and a set of worked examples for writing parser recipes. Call this before `llma-parser-recipe-create` so you know the recipe grammar.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Returns the parser recipe DSL syntax and worked examples.",
+ "title": "Parser recipe reference",
+ "required_scopes": ["llm_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"llma-personal-spend": {
"description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model and UTC day. The `product` query param is required and scopes the tool / model / day breakdowns to a single product; currently only `posthog_code` is supported. `by_product` always returns the cross-product view, and `by_day` is a day-ascending series for spend-over-time questions. Pass `refresh=true` to bypass the 5-minute cache.",
"category": "AI observability",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 9344cc866d74..071b136e0cca 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -360,6 +360,34 @@
"readOnlyHint": true
}
},
+ "llma-parser-recipe-create": {
+ "description": "Writes and saves a custom LLM analytics parser recipe so an unparsed trace event renders as a readable conversation. Call `llma-parser-recipe-reference` first to get the recipe DSL syntax and worked examples. The server loads the exact event (by trace_id + event_uuid), compiles your YAML, and validates it against that event, saving the recipe only when a previously-unrecognized input or output side becomes recognized. If the result is not valid, read the error, fix the YAML, and call again in the same turn; stop after about three failed attempts and explain what is blocking you. Do not force non-conversational data into a fake conversation shape — if the event genuinely is not a conversation, say so instead of inventing rules. Samples in your context are truncated, but the server always validates against the full event.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Compiles, validates, and saves a custom parser recipe for an LLM analytics trace event.",
+ "title": "Create parser recipe",
+ "required_scopes": ["llm_analytics:write", "query:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-parser-recipe-reference": {
+ "description": "Returns the LLM analytics parser recipe DSL reference: the syntax and a set of worked examples for writing parser recipes. Call this before `llma-parser-recipe-create` so you know the recipe grammar.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Returns the parser recipe DSL syntax and worked examples.",
+ "title": "Parser recipe reference",
+ "required_scopes": ["llm_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"organizations-get": {
"description": "Fetches the organizations that the user has access to, with their id, name, and membership level. Use this to discover organizations — including ones other than the active organization — and to resolve an organization name to the id you pass to `switch-organization`.",
"category": "Organization & project management",
diff --git a/services/mcp/scripts/copy-instructions.ts b/services/mcp/scripts/copy-instructions.ts
index 8bae179c2d26..212ab4ff286c 100644
--- a/services/mcp/scripts/copy-instructions.ts
+++ b/services/mcp/scripts/copy-instructions.ts
@@ -15,6 +15,12 @@ const PROMPTS = [
src: 'products/posthog_ai/skills/querying-posthog-data/references/guidelines.md',
dest: 'shared/guidelines.md',
},
+ {
+ // Parser recipe DSL reference served by `llma-parser-recipe-reference`;
+ // the Python MaxTool reads the same file, keeping one source of truth.
+ src: 'products/ai_observability/backend/prompts/parser_recipe_examples.yaml',
+ dest: 'shared/parser_recipe_examples.yaml',
+ },
]
export function copyInstructions(): void {
diff --git a/services/mcp/scripts/hono-esbuild-config.ts b/services/mcp/scripts/hono-esbuild-config.ts
index 2e7942660694..9905da89bf71 100644
--- a/services/mcp/scripts/hono-esbuild-config.ts
+++ b/services/mcp/scripts/hono-esbuild-config.ts
@@ -42,7 +42,7 @@ export function honoEsbuildOptions(opts: HonoEsbuildOptions = {}): BuildOptions
sourcemap: opts.sourcemap ?? true,
external: [],
plugins: [cfWorkersStub, ...(opts.extraPlugins ?? [])],
- loader: { '.html': 'text', '.md': 'text', '.json': 'json' },
+ loader: { '.html': 'text', '.md': 'text', '.yaml': 'text', '.json': 'json' },
define: { 'process.env.NODE_ENV': opts.dev ? '"development"' : '"production"' },
// Bundled CJS modules (e.g. ioredis using `require('util')`) call through
// to a global `require`. ESM has no `require`; banner injects one. The
diff --git a/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts b/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts
new file mode 100644
index 000000000000..0888a0d350a4
--- /dev/null
+++ b/services/mcp/src/tools/aiObservability/parserRecipeCreate.ts
@@ -0,0 +1,191 @@
+import { z } from 'zod'
+
+import { mergeRecipes, RecipeNormalizer, type StoredRecipe, validateRecipeAgainstSample } from '@posthog/llm-normalizer'
+
+import { getPostHogClient } from '@/lib/posthog'
+import type { Context, ToolBase } from '@/tools/types'
+
+// Mirrors MAX_SOURCE_LENGTH on the ParserRecipe model.
+const MAX_SOURCE_LENGTH = 100_000
+
+// The team's custom recipes are fetched with a fixed cap. A team with more custom
+// recipes than this gets a slightly stale merge — acceptable, since the server still
+// validates against the full event and the built-ins always run first.
+const RECIPE_LIST_LIMIT = 300
+
+const schema = z.object({
+ name: z.string().min(1).max(255).describe('Short human-readable name for the recipe, shown in the parser editor.'),
+ yaml_source: z
+ .string()
+ .min(1)
+ .max(MAX_SOURCE_LENGTH)
+ .describe(
+ 'The recipe as raw YAML. Call `llma-parser-recipe-reference` first for the DSL syntax and worked examples. The server compiles and validates this against the exact event before saving.'
+ ),
+ trace_id: z.string().min(1).describe('The `$ai_trace_id` of the trace containing the event to parse.'),
+ event_uuid: z.string().min(1).describe('The UUID (`id`) of the specific event within the trace to parse.'),
+})
+
+type Params = z.infer<typeof schema>
+
+interface ParserRecipeCreateResult {
+ valid: boolean
+ error?: string
+ recipe_id?: string
+ saved?: boolean
+ already_recognized?: boolean
+}
+
+interface TraceEvent {
+ id: string
+ event: string
+ properties?: Record<string, unknown>
+}
+
+interface Trace {
+ events?: TraceEvent[]
+}
+
+interface EventSample {
+ input: unknown
+ output: unknown
+ // Embeddings have no message-shaped output; treat that side as recognized so the
+ // recipe only has to explain the input.
+ outputRecognizedByDefault: boolean
+}
+
+// Extract the input/output sides by event type, mirroring `ConversationDisplay`.
+function extractSample(eventName: string, properties: Record<string, unknown>): EventSample {
+ if (eventName === '$ai_generation') {
+ return {
+ input: properties.$ai_input,
+ output: properties.$ai_output_choices ?? properties.$ai_output,
+ outputRecognizedByDefault: false,
+ }
+ }
+ if (eventName === '$ai_embedding') {
+ return { input: properties.$ai_input, output: undefined, outputRecognizedByDefault: true }
+ }
+ // Spans and everything else carry their payload in the `_state` fields.
+ return {
+ input: properties.$ai_input_state,
+ output: properties.$ai_output_state,
+ outputRecognizedByDefault: false,
+ }
+}
+
+export const parserRecipeCreateHandler: ToolBase<typeof schema, ParserRecipeCreateResult>['handler'] = async (
+ context: Context,
+ params: Params
+) => {
+ const projectId = await context.stateManager.getProjectId()
+
+ // The 1-year window mirrors the frontend trace fetch (`aiObservabilityTraceDataLogic`);
+ // without it, older traces silently return no rows.
+ const dateFrom = new Date(Date.now() - 365 * 24 * 3600 * 1000).toISOString()
+ const traceResult = await context.api
+ .query({ projectId: String(projectId) })
+ .execute({ queryBody: { kind: 'TraceQuery', traceId: params.trace_id, dateRange: { date_from: dateFrom } } })
+ if (!traceResult.success) {
+ // Infra failures are exceptions; validation failures are results.
+ throw new Error(`Failed to load trace ${params.trace_id}: ${traceResult.error.message}`)
+ }
+
+ const traces = (traceResult.data.results ?? []) as Trace[]
+ const event = traces.flatMap((trace) => trace.events ?? []).find((candidate) => candidate.id === params.event_uuid)
+ if (!event) {
+ return { valid: false, error: 'event not found in trace — re-check trace_id and event_uuid' }
+ }
+
+ const properties = event.properties ?? {}
+ const { input, output, outputRecognizedByDefault } = extractSample(event.event, properties)
+ if (input === undefined && output === undefined) {
+ // TraceQuery falls back to the shared events table where the heavy AI columns are
+ // stripped, and `ai_events` has a retention TTL — a payload-less event can't prove
+ // anything about a recipe, and normalizeMessages(undefined) would count as recognized.
+ return {
+ valid: false,
+ error: 'the event payload is not available server-side (it likely aged out of retention) — the recipe cannot be validated against it',
+ }
+ }
+ const tools = properties.$ai_tools
+
+ const listResponse = await context.api.request<{ results?: Array<{ id: string; source: string }> }>({
+ method: 'GET',
+ path: `/api/projects/${projectId}/llm_analytics/parser_recipes/`,
+ query: { limit: RECIPE_LIST_LIMIT },
+ })
+ const teamRecipes: StoredRecipe[] = (listResponse.results ?? []).map((row) => ({ id: row.id, source: row.source }))
+
+ // Recompute recognition the way the browser does, so validation only demands the
+ // sides that are currently unrecognized. The whole (possibly multi-MB) trace is
+ // deserialized once here and discarded — the same order of work the browser does.
+ let inputRecognized: boolean
+ let outputRecognized: boolean
+ try {
+ const normalizer = new RecipeNormalizer(mergeRecipes(teamRecipes))
+ inputRecognized = normalizer.normalizeMessages(input, 'user', tools).recognized
+ outputRecognized = outputRecognizedByDefault || normalizer.normalizeMessages(output, 'assistant').recognized
+ } catch (error) {
+ // An already-saved team recipe blew the runtime's depth or work budget on this event.
+ // That is a defect in that recipe, not in the candidate — say so instead of 500ing.
+ return {
+ valid: false,
+ error: `the team's existing recipes failed on this event: ${error instanceof Error ? error.message : String(error)}`,
+ }
+ }
+
+ const verdict = validateRecipeAgainstSample(params.yaml_source, teamRecipes, {
+ input,
+ output,
+ tools,
+ inputRecognized,
+ outputRecognized,
+ })
+ if (!verdict.valid) {
+ return { valid: false, error: verdict.error }
+ }
+
+ // An event both sides of which are already recognized doesn't need a recipe; the
+ // candidate then only has to compile. Flag it so the caller knows.
+ const alreadyRecognized = inputRecognized && outputRecognized
+
+ // A byte-identical recipe already exists — return it instead of saving a duplicate.
+ const existing = teamRecipes.find((recipe) => recipe.source === params.yaml_source)
+ if (existing) {
+ return { valid: true, recipe_id: existing.id, ...(alreadyRecognized ? { already_recognized: true } : {}) }
+ }
+
+ // With both sides pre-recognized, validation was vacuous — the candidate proved
+ // nothing, so persisting it team-wide would save an unproven recipe.
+ if (alreadyRecognized) {
+ return { valid: true, already_recognized: true }
+ }
+
+ try {
+ const created = await context.api.request<{ id: string }>({
+ method: 'POST',
+ path: `/api/projects/${projectId}/llm_analytics/parser_recipes/`,
+ body: { name: params.name, source: params.yaml_source },
+ })
+ return { valid: true, recipe_id: created.id }
+ } catch (error) {
+ // Capture before the soft return: the graceful result bypasses `handleToolError`,
+ // the path that normally surfaces 5xx-class failures to observability.
+ try {
+ getPostHogClient().captureException(error, undefined, { tag: 'mcp', tool: 'llma-parser-recipe-create' })
+ } catch {
+ // Observability must never break the request.
+ }
+ // Only persistence failed — never make the agent rewrite a correct recipe.
+ return { valid: true, saved: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+const tool = (): ToolBase<typeof schema, ParserRecipeCreateResult> => ({
+ name: 'llma-parser-recipe-create',
+ schema,
+ handler: parserRecipeCreateHandler,
+})
+
+export default tool
diff --git a/services/mcp/src/tools/aiObservability/parserRecipeReference.ts b/services/mcp/src/tools/aiObservability/parserRecipeReference.ts
new file mode 100644
index 000000000000..4f23bc743f95
--- /dev/null
+++ b/services/mcp/src/tools/aiObservability/parserRecipeReference.ts
@@ -0,0 +1,26 @@
+// Copied into `shared/` by scripts/copy-instructions.ts before bundling so this stays
+// the single source of truth with the Python MaxTool, which reads the same file.
+// Too big (~14KB) to embed in a tool description.
+import parserRecipeExamples from '@shared/parser_recipe_examples.yaml'
+import { z } from 'zod'
+
+import type { ToolBase } from '@/tools/types'
+
+const schema = z.object({})
+
+interface ParserRecipeReferenceResult {
+ reference: string
+}
+
+export const parserRecipeReferenceHandler: ToolBase<
+ typeof schema,
+ ParserRecipeReferenceResult
+>['handler'] = async () => ({ reference: parserRecipeExamples })
+
+const tool = (): ToolBase<typeof schema, ParserRecipeReferenceResult> => ({
+ name: 'llma-parser-recipe-reference',
+ schema,
+ handler: parserRecipeReferenceHandler,
+})
+
+export default tool
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index e5b40c5f8805..c26281694335 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -3,6 +3,8 @@ import { filterStaffOnlyTools } from '@/lib/staff-only-tools'
// AI observability
import getLLMCosts from './aiObservability/getLLMCosts'
+import parserRecipeCreate from './aiObservability/parserRecipeCreate'
+import parserRecipeReference from './aiObservability/parserRecipeReference'
// Debug
import debugMcpUiApps from './debug/debugMcpUiApps'
// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)
@@ -99,6 +101,8 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// AI observability
'get-llm-total-costs-for-project': getLLMCosts,
+ 'llma-parser-recipe-create': parserRecipeCreate,
+ 'llma-parser-recipe-reference': parserRecipeReference,
// Notebooks
'notebook-edit': notebookEdit,
diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.ts
index 1e27e7a4b90c..1b8124e8e053 100644
--- a/services/mcp/tests/hono/setup.ts
+++ b/services/mcp/tests/hono/setup.ts
@@ -13,10 +13,13 @@ vi.mock('cloudflare:workers', () => ({
},
}))
-// Mock shared guidelines (generated by scripts/copy-instructions.ts, not checked in)
+// Mock shared prompt files (generated by scripts/copy-instructions.ts, not checked in)
vi.mock('@shared/guidelines.md', () => ({
default: '# Guidelines\nTest guidelines content.',
}))
+vi.mock('@shared/parser_recipe_examples.yaml', () => ({
+ default: 'rules: []\n',
+}))
vi.mock('@/resources/ui-apps', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/resources/ui-apps')>()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.json
new file mode 100644
index 000000000000..a4b15c88486f
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-create.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "event_uuid": {
+ "description": "The UUID (`id`) of the specific event within the trace to parse.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "name": {
+ "description": "Short human-readable name for the recipe, shown in the parser editor.",
+ "maxLength": 255,
+ "minLength": 1,
+ "type": "string"
+ },
+ "trace_id": {
+ "description": "The `$ai_trace_id` of the trace containing the event to parse.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "yaml_source": {
+ "description": "The recipe as raw YAML. Call `llma-parser-recipe-reference` first for the DSL syntax and worked examples. The server compiles and validates this against the exact event before saving.",
+ "maxLength": 100000,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["name", "yaml_source", "trace_id", "event_uuid"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.json
new file mode 100644
index 000000000000..7b7ea9186078
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-parser-recipe-reference.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {},
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/parser-recipe-create.test.ts b/services/mcp/tests/unit/parser-recipe-create.test.ts
new file mode 100644
index 000000000000..fa1f5e32776b
--- /dev/null
+++ b/services/mcp/tests/unit/parser-recipe-create.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import parserRecipeCreate from '@/tools/aiObservability/parserRecipeCreate'
+import type { Context } from '@/tools/types'
+
+// A recipe whose rule matches the `acme_*` sample shape below. The built-in recipes
+// do not recognize that shape, so this recipe is what makes the sample recognized.
+const MATCHING_RECIPE = `
+rules:
+ - on:
+ acme_kind: q
+ emit:
+ role: user
+ content: $.acme_text
+`
+
+// Compiles, but matches nothing in the sample — the event stays unrecognized.
+const NON_MATCHING_RECIPE = `
+rules:
+ - on:
+ some_other_key: { exists: true }
+ emit:
+ role: user
+ content: $.acme_text
+`
+
+const TRACE_ID = 'trace-1'
+const EVENT_UUID = 'event-1'
+
+interface EventShape {
+ id: string
+ event: string
+ properties: Record<string, unknown>
+}
+
+function generationEvent(overrides: Partial<EventShape> = {}): EventShape {
+ return {
+ id: EVENT_UUID,
+ event: '$ai_generation',
+ properties: {
+ $ai_input: { acme_kind: 'q', acme_text: 'hi' },
+ $ai_output: { acme_kind: 'q', acme_text: 'bye' },
+ },
+ ...overrides,
+ }
+}
+
+function createContext(options: { events: EventShape[]; queryError?: string; request?: ReturnType<typeof vi.fn> }): {
+ context: Context
+ execute: ReturnType<typeof vi.fn>
+ request: ReturnType<typeof vi.fn>
+} {
+ const execute = vi
+ .fn()
+ .mockResolvedValue(
+ options.queryError
+ ? { success: false, error: { message: options.queryError } }
+ : { success: true, data: { results: [{ events: options.events }] } }
+ )
+ const request = options.request ?? vi.fn().mockResolvedValue({ results: [] })
+ const context = {
+ api: { request, query: vi.fn().mockReturnValue({ execute }) } as any,
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,
+ env: {} as any,
+ sessionManager: {} as any,
+ cache: {} as any,
+ getDistinctId: async () => 'distinct-id',
+ trackEvent: async () => {},
+ } as Context
+ return { context, execute, request }
+}
+
+describe('llma-parser-recipe-create handler', () => {
+ const baseParams = {
+ name: 'Acme SDK',
+ yaml_source: MATCHING_RECIPE,
+ trace_id: TRACE_ID,
+ event_uuid: EVENT_UUID,
+ }
+
+ it('validates against the event and persists the recipe, returning its id', async () => {
+ const request = vi
+ .fn()
+ .mockResolvedValueOnce({ results: [] }) // GET recipes list
+ .mockResolvedValueOnce({ id: 'recipe-123' }) // POST create
+ const { context } = createContext({ events: [generationEvent()], request })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result).toEqual({ valid: true, recipe_id: 'recipe-123' })
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(request.mock.calls[1]![0]).toMatchObject({
+ method: 'POST',
+ path: '/api/projects/42/llm_analytics/parser_recipes/',
+ body: { name: 'Acme SDK', source: MATCHING_RECIPE },
+ })
+ })
+
+ it('returns a validation error and does not persist when the source is not valid YAML', async () => {
+ const { context, request } = createContext({ events: [generationEvent()] })
+
+ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: 'rules: [unclosed' })
+
+ expect(result.valid).toBe(false)
+ // Only the recipe list GET ran — nothing was POSTed.
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('rejects a recipe that compiles but leaves the event unrecognized', async () => {
+ const { context, request } = createContext({ events: [generationEvent()] })
+
+ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: NON_MATCHING_RECIPE })
+
+ expect(result.valid).toBe(false)
+ expect(result.error).toContain('no rule matched')
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('reuses an identical existing recipe instead of POSTing a duplicate', async () => {
+ const request = vi.fn().mockResolvedValueOnce({ results: [{ id: 'recipe-0', source: MATCHING_RECIPE }] })
+ const { context } = createContext({ events: [generationEvent()], request })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ // The identical recipe is already installed, so the event is already recognized
+ // by the time we recompute — hence the flag alongside the deduped id.
+ expect(result).toEqual({ valid: true, recipe_id: 'recipe-0', already_recognized: true })
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not persist an unproven recipe when both sides are already recognized', async () => {
+ // MATCHING_RECIPE is already installed, so validation of the candidate is vacuous —
+ // a non-matching candidate must be flagged, not saved team-wide.
+ const request = vi.fn().mockResolvedValueOnce({ results: [{ id: 'recipe-0', source: MATCHING_RECIPE }] })
+ const { context } = createContext({ events: [generationEvent()], request })
+
+ const result = await parserRecipeCreate().handler(context, { ...baseParams, yaml_source: NON_MATCHING_RECIPE })
+
+ expect(result).toEqual({ valid: true, already_recognized: true })
+ // Only the recipe list GET ran — nothing was POSTed.
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('rejects an event whose payload is unavailable server-side instead of saving blind', async () => {
+ // Retention TTL / events-table fallback strips the heavy AI columns; with both sides
+ // undefined the normalizer reports recognized and any compiling YAML would save.
+ const strippedEvent = generationEvent({ properties: {} })
+ const { context, request } = createContext({ events: [strippedEvent] })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result.valid).toBe(false)
+ expect(result.error).toContain('not available')
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ it('returns a not-found error when the event is absent from the trace', async () => {
+ const { context, request } = createContext({ events: [generationEvent({ id: 'someone-else' })] })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result).toEqual({ valid: false, error: 'event not found in trace — re-check trace_id and event_uuid' })
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ it('reads $ai_input_state / $ai_output_state for span events', async () => {
+ // Only the `_state` fields carry the sample; if the handler read `$ai_input`
+ // instead, the input would be undefined and the recipe would fail to match.
+ const spanEvent = generationEvent({
+ event: '$ai_span',
+ properties: {
+ $ai_input_state: { acme_kind: 'q', acme_text: 'in' },
+ $ai_output_state: { acme_kind: 'q', acme_text: 'out' },
+ },
+ })
+ const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockResolvedValueOnce({ id: 'recipe-span' })
+ const { context } = createContext({ events: [spanEvent], request })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result).toEqual({ valid: true, recipe_id: 'recipe-span' })
+ })
+
+ it('reports a saved team recipe that blows up on the event as a verdict, not an exception', async () => {
+ // A self-delegating recipe compiles but trips the runtime's depth guard. It is already
+ // installed, so it throws during the pre-recognition pass, before the candidate is judged.
+ const selfDelegating = 'rules:\n - on:\n acme_kind: q\n delegate: $\n'
+ const request = vi.fn().mockResolvedValueOnce({ results: [{ id: 'recipe-bad', source: selfDelegating }] })
+ const { context } = createContext({ events: [generationEvent()], request })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result.valid).toBe(false)
+ expect(result.error).toContain("team's existing recipes failed")
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('reports a persistence failure as valid-but-unsaved so the agent does not rewrite', async () => {
+ const request = vi.fn().mockResolvedValueOnce({ results: [] }).mockRejectedValueOnce(new Error('500 from API'))
+ const { context } = createContext({ events: [generationEvent()], request })
+
+ const result = await parserRecipeCreate().handler(context, baseParams)
+
+ expect(result).toEqual({ valid: true, saved: false, error: '500 from API' })
+ })
+})
diff --git a/services/mcp/tests/vitest-text-loader.ts b/services/mcp/tests/vitest-text-loader.ts
new file mode 100644
index 000000000000..81ac6423bd87
--- /dev/null
+++ b/services/mcp/tests/vitest-text-loader.ts
@@ -0,0 +1,17 @@
+// The Hono and worker entry points import `*.md`, `*.html`, and `*.yaml` files as raw
+// text (esbuild inlines them via its `text` loader at build time; wrangler via a `Text`
+// rule). Vitest's default loader rejects those as JS, so every Node-pool vitest config
+// registers this transform that stringifies their contents. The workers-pool project
+// has its own transform stack and doesn't need it.
+export const textLoader = {
+ name: 'text-loader',
+ transform(code: string, id: string): { code: string; map: null } | undefined {
+ if (id.endsWith('.md') || id.endsWith('.html') || id.endsWith('.yaml')) {
+ return {
+ code: `export default ${JSON.stringify(code)}`,
+ map: null,
+ }
+ }
+ return undefined
+ },
+}
diff --git a/services/mcp/tsconfig.json b/services/mcp/tsconfig.json
index 9cb1fd569dff..93d00494d3d3 100644
--- a/services/mcp/tsconfig.json
+++ b/services/mcp/tsconfig.json
@@ -26,6 +26,8 @@
"@posthog/mcp-ui/*": ["./src/ui-apps/lib/*"],
"@posthog/quill": ["../../packages/quill/packages/quill/dist/index.d.ts"],
"@posthog/quill-charts": ["../../packages/quill/packages/charts/dist/index.d.ts"],
+ "@posthog/llm-normalizer": ["../../packages/llm-normalizer/src/index.ts"],
+ "@posthog/llm-normalizer/*": ["../../packages/llm-normalizer/src/*"],
"lucide-react": ["./node_modules/lucide-react"],
"@common/*": ["../../common/*"]
}
diff --git a/services/mcp/types.d.ts b/services/mcp/types.d.ts
index 2b06e4467367..a52af9ab01dc 100644
--- a/services/mcp/types.d.ts
+++ b/services/mcp/types.d.ts
@@ -14,3 +14,17 @@ declare namespace Cloudflare {
MCP_HONO_URL: string | undefined
}
}
+
+// YAML imports resolve to the file's raw text (esbuild `.yaml` text loader,
+// wrangler `Text` rule, vitest raw-text transform).
+declare module '*.yaml' {
+ const content: string
+ export default content
+}
+
+// Vite-style raw suffix used by @posthog/llm-normalizer's recipe registry; esbuild
+// retries resolution without the query and applies the same text loader.
+declare module '*.yaml?raw' {
+ const content: string
+ export default content
+}
diff --git a/services/mcp/vitest.config.mts b/services/mcp/vitest.config.mts
index f63025b0994f..091e27ea2664 100644
--- a/services/mcp/vitest.config.mts
+++ b/services/mcp/vitest.config.mts
@@ -1,19 +1,7 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
-// Shared markdown loader so *.md imports resolve as string exports in the
-// Node-pool project. The workers-pool project has its own transform stack.
-const markdownLoader = {
- name: 'markdown-loader',
- transform(code: string, id: string) {
- if (id.endsWith('.md')) {
- return {
- code: `export default ${JSON.stringify(code)}`,
- map: null,
- }
- }
- },
-}
+import { textLoader } from './tests/vitest-text-loader'
// Two projects run under a single `pnpm test` invocation:
// - `unit` → fast Node-pool suite (default pool, ~2s)
@@ -29,7 +17,7 @@ export default defineConfig({
globalSetup: ['tests/global-setup.ts'],
projects: [
{
- plugins: [tsconfigPaths({ root: '.' }), markdownLoader],
+ plugins: [tsconfigPaths({ root: '.' }), textLoader],
test: {
name: 'unit',
globals: true,
diff --git a/services/mcp/vitest.hono.config.mts b/services/mcp/vitest.hono.config.mts
index e2416dc74454..b4f04a5f27c4 100644
--- a/services/mcp/vitest.hono.config.mts
+++ b/services/mcp/vitest.hono.config.mts
@@ -1,21 +1,10 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
+import { textLoader } from './tests/vitest-text-loader'
+
export default defineConfig({
- plugins: [
- tsconfigPaths({ root: '.' }),
- {
- name: 'text-loader',
- transform(code, id) {
- if (id.endsWith('.md') || id.endsWith('.html')) {
- return {
- code: `export default ${JSON.stringify(code)}`,
- map: null,
- }
- }
- },
- },
- ],
+ plugins: [tsconfigPaths({ root: '.' }), textLoader],
test: {
globals: true,
environment: 'node',
diff --git a/services/mcp/vitest.integration.config.mts b/services/mcp/vitest.integration.config.mts
index c307e636fe75..adf4e9928f72 100644
--- a/services/mcp/vitest.integration.config.mts
+++ b/services/mcp/vitest.integration.config.mts
@@ -1,21 +1,7 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
-// The Hono and worker entry points import `*.md` and `*.html` template files
-// directly. Vitest's default loader rejects those as JS, so we register a tiny
-// transform that stringifies their contents. Mirrors the loader in the other
-// vitest configs.
-const textLoader = {
- name: 'text-loader',
- transform(code: string, id: string) {
- if (id.endsWith('.md') || id.endsWith('.html')) {
- return {
- code: `export default ${JSON.stringify(code)}`,
- map: null,
- }
- }
- },
-}
+import { textLoader } from './tests/vitest-text-loader'
export default defineConfig({
plugins: [tsconfigPaths({ root: '.' }), textLoader],
diff --git a/services/mcp/vitest.perf.config.mts b/services/mcp/vitest.perf.config.mts
index 3e6aeabbddd4..1f5794e25765 100644
--- a/services/mcp/vitest.perf.config.mts
+++ b/services/mcp/vitest.perf.config.mts
@@ -1,21 +1,10 @@
import tsconfigPaths from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
+import { textLoader } from './tests/vitest-text-loader'
+
export default defineConfig({
- plugins: [
- tsconfigPaths({ root: '.' }),
- {
- name: 'text-loader',
- transform(code, id) {
- if (id.endsWith('.md') || id.endsWith('.html')) {
- return {
- code: `export default ${JSON.stringify(code)}`,
- map: null,
- }
- }
- },
- },
- ],
+ plugins: [tsconfigPaths({ root: '.' }), textLoader],
test: {
globals: true,
environment: 'node',
diff --git a/services/mcp/wrangler.jsonc b/services/mcp/wrangler.jsonc
index 2bf90f83948e..f53a3cfa6576 100644
--- a/services/mcp/wrangler.jsonc
+++ b/services/mcp/wrangler.jsonc
@@ -55,7 +55,7 @@
"rules": [
{
"type": "Text",
- "globs": ["**/*.md"],
+ "globs": ["**/*.md", "**/*.yaml"],
"fallthrough": true,
},
],
diff --git a/tsconfig.json b/tsconfig.json
index 9e8e329c6049..a12db5452f8d 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -20,6 +20,8 @@
"@posthog/mcp-ui/*": ["./services/mcp/src/ui-apps/lib/*"],
"@posthog/replay-shared": ["./common/replay-shared/src/index.ts"],
"@posthog/replay-shared/*": ["./common/replay-shared/src/*"],
+ "@posthog/llm-normalizer": ["./packages/llm-normalizer/src/index.ts"],
+ "@posthog/llm-normalizer/*": ["./packages/llm-normalizer/src/*"],
"@posthog/quill-charts": ["./packages/quill/packages/charts/src/index.ts"],
"@posthog/quill-charts/*": ["./packages/quill/packages/charts/src/*"],
// @tiptap/* is installed under frontend/node_modules only, which product files
@@ -68,7 +70,8 @@
"common/replay-shared/src/**/*",
"common/storybook/*",
"docs/onboarding/**/*",
- "packages/quill/packages/charts/src/**/*"
+ "packages/quill/packages/charts/src/**/*",
+ "packages/llm-normalizer/src/**/*"
],
"exclude": ["frontend/dist/**/*", "**/*.mdx"],
"ts-node": {