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(aiobs): declarative recipe-based normalizer (#60713)

Carlos Marchal7515764c003e
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 51688a2a9a29..52b6466bcbe5 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -258,6 +258,7 @@ export const commonConfig = {
'.woff2': 'file',
'.mp3': 'file',
'.sql': 'text',
+ '.yaml': 'text',
},
metafile: true,
}
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 01574f7603c4..de6e630b53a5 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -58,6 +58,8 @@ const esmModules = [
'longest-streak',
'markdown-table',
'@mathjax/src',
+ // yaml's browser entry (used under the jsdom env) is ESM and re-exports its CJS dist
+ 'yaml/browser',
]
function rootDirectories(): string[] {
return ['<rootDir>/src', '<rootDir>/../products']
@@ -141,6 +143,7 @@ const config: Config = {
moduleNameMapper: {
'^.+\\.(css|less|scss|svg|png)$': '<rootDir>/src/test/mocks/styleMock.js',
'^.+\\.sql\\?raw$': '<rootDir>/src/test/mocks/rawFileMock.js',
+ '^(.+)\\.yaml\\?raw$': '$1.yaml',
'^~/(.*)$': '<rootDir>/src/$1',
'^@posthog/hogql-parser$': '<rootDir>/node_modules/@posthog/hogql-parser/dist/index.cjs',
// @posthog/hogvm ships as ESM-only; map to the TS source so Jest (Sucrase) can handle it.
@@ -261,6 +264,7 @@ const config: Config = {
// A map from regular expressions to paths to transformers
transform: {
'\\.[jt]sx?$': '@sucrase/jest-plugin',
+ '\\.yaml$': '<rootDir>/src/test/yamlRawTransformer.js',
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
diff --git a/frontend/src/custom.d.ts b/frontend/src/custom.d.ts
index 73d34fa2e3e3..392a4bd5c38b 100644
--- a/frontend/src/custom.d.ts
+++ b/frontend/src/custom.d.ts
@@ -40,6 +40,12 @@ declare module '*.sql?raw' {
export default content
}
+// This fixes TS errors when importing a .yaml file with ?raw suffix
+declare module '*.yaml?raw' {
+ const content: string
+ export default content
+}
+
// This fixes TS2882 errors when side-effect importing .scss files
declare module '*.scss'
diff --git a/frontend/src/test/yamlRawTransformer.js b/frontend/src/test/yamlRawTransformer.js
new file mode 100644
index 000000000000..907d73110d5c
--- /dev/null
+++ b/frontend/src/test/yamlRawTransformer.js
@@ -0,0 +1,11 @@
+const crypto = require('crypto')
+
+module.exports = {
+ process(sourceText) {
+ // sourceText is just a string, this just handles wrapping it in quotes
+ return { code: `module.exports = ${JSON.stringify(sourceText)};` }
+ },
+ getCacheKey(sourceText) {
+ return crypto.createHash('md5').update(sourceText).digest('hex')
+ },
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c44314a74714..d894115e94e5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -90,6 +90,9 @@ catalogs:
use-debounce:
specifier: ^9.0.3
version: 9.0.3
+ yaml:
+ specifier: ^2.8.2
+ version: 2.9.0
overrides:
axios: ^1.15.0
@@ -2165,6 +2168,9 @@ importers:
use-debounce:
specifier: '*'
version: 9.0.3([email protected])
+ yaml:
+ specifier: 'catalog:'
+ version: 2.9.0
devDependencies:
kea-test-utils:
specifier: 'catalog:'
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 92bccfc4015f..54805be44fd9 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -63,6 +63,7 @@ catalog:
husky: ^7.0.4
lint-staged: ~15.4.3
concurrently: ^5.3.0
+ yaml: ^2.8.2
# posthog-js needs to be excluded because we only update our CDN
# once a newer posthog-js version is merged onto this repo
diff --git a/products/ai_observability/frontend/normalizer/index.ts b/products/ai_observability/frontend/normalizer/index.ts
new file mode 100644
index 000000000000..f9d4020bfd90
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/index.ts
@@ -0,0 +1,4 @@
+// Parallel to `../utils`, which stays the only production path; this is
+// exercised by the test suite, awaiting a feature flag to dual-run in prod.
+
+export { RecipeNormalizer } from './recipe/recipeNormalizer'
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.test.ts
new file mode 100644
index 000000000000..2f8ae32f608d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.test.ts
@@ -0,0 +1,16 @@
+import { Scope } from '../../scope'
+import { ArrayExpr } from './array'
+import { LiteralExpr } from './literal'
+import { PathExpr } from './path'
+
+describe('ArrayExpr', () => {
+ it('evaluates each element against the scope', () => {
+ const scope = Scope.forNode({ name: 'Ada' }, 'user')
+ const expr = new ArrayExpr([new LiteralExpr('greeting'), new PathExpr(['name'])])
+ expect(expr.eval(scope)).toEqual(['greeting', 'Ada'])
+ })
+
+ it('empty spec yields an empty array', () => {
+ expect(new ArrayExpr([]).eval(Scope.forNode({}, 'user'))).toEqual([])
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.ts
new file mode 100644
index 000000000000..37673cca59cf
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/array.ts
@@ -0,0 +1,11 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class ArrayExpr extends Expr {
+ constructor(private readonly items: Expr[]) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ return this.items.map((item) => item.eval(scope))
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/base.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/base.ts
new file mode 100644
index 000000000000..7e6a53e7dd5a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/base.ts
@@ -0,0 +1,5 @@
+import { Scope } from '../../scope'
+
+export abstract class Expr {
+ abstract eval(scope: Scope): unknown
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.test.ts
new file mode 100644
index 000000000000..4c714d86ce97
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.test.ts
@@ -0,0 +1,24 @@
+import { Scope } from '../../scope'
+import { ArrayExpr } from './array'
+import { CoalesceExpr } from './coalesce'
+import { LiteralExpr } from './literal'
+
+const coalesce = (...values: unknown[]): CoalesceExpr =>
+ new CoalesceExpr(new ArrayExpr(values.map((v) => new LiteralExpr(v))))
+
+describe('CoalesceExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+
+ it('returns the first non-nullish value', () => {
+ expect(coalesce(null, undefined, 'chosen', 'later').eval(scope)).toBe('chosen')
+ })
+
+ it('skips nullish values but keeps falsy ones like 0 and empty string', () => {
+ expect(coalesce(null, 0, 'later').eval(scope)).toBe(0)
+ expect(coalesce(undefined, '', 'later').eval(scope)).toBe('')
+ })
+
+ it('returns undefined when every candidate is nullish', () => {
+ expect(coalesce(null, undefined).eval(scope)).toBeUndefined()
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.ts
new file mode 100644
index 000000000000..fc9188d6aeeb
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/coalesce.ts
@@ -0,0 +1,15 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class CoalesceExpr extends Expr {
+ constructor(private readonly from: Expr) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const list = this.from.eval(scope)
+ if (!Array.isArray(list)) {
+ return undefined
+ }
+ return list.find((v) => v !== undefined && v !== null)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/filter.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/filter.ts
new file mode 100644
index 000000000000..9a9cf7c5ca77
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/filter.ts
@@ -0,0 +1,27 @@
+import { Scope } from '../../scope'
+import { Pattern } from '../predicate'
+import { Expr } from './base'
+
+export abstract class FilterExpr extends Expr {
+ protected constructor(
+ protected readonly from: Expr,
+ protected readonly where: Pattern | null,
+ protected readonly ifEmpty: Expr | null
+ ) {
+ super()
+ }
+
+ protected onNotArray(scope: Scope): unknown {
+ const fb = this.ifEmpty ? this.ifEmpty.eval(scope) : undefined
+ return fb ?? []
+ }
+
+ protected withIfEmpty(result: unknown[], scope: Scope): unknown {
+ if (result.length !== 0 || this.ifEmpty === null) {
+ return result
+ }
+ const fallback = this.ifEmpty.eval(scope)
+ // `if_empty: ~` (null) becomes undefined so the emit slot drops the field entirely.
+ return fallback === null ? undefined : fallback
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/index.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/index.ts
new file mode 100644
index 000000000000..34c86bcb05a2
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/index.ts
@@ -0,0 +1,14 @@
+export { Expr } from './base'
+export { LiteralExpr } from './literal'
+export { SelfExpr } from './self'
+export { PathExpr } from './path'
+export { InterpExpr } from './interp'
+export { ArrayExpr } from './array'
+export { ObjectExpr } from './object'
+export { CoalesceExpr } from './coalesce'
+export { JoinExpr } from './join'
+export { OmitExpr } from './omit'
+export { TryParseStructuredContentExpr } from './tryParseStructuredContent'
+export { StringifyExpr } from './stringify'
+export { SelectExpr } from './select'
+export { RejectExpr } from './reject'
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.test.ts
new file mode 100644
index 000000000000..dcebb50b3a89
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.test.ts
@@ -0,0 +1,17 @@
+import { Scope } from '../../scope'
+import { InterpExpr } from './interp'
+import { PathExpr } from './path'
+
+describe('InterpExpr', () => {
+ it('splices evaluated values between literal text', () => {
+ const scope = Scope.forNode({ name: 'Ada', lang: 'Hog' }, 'user')
+ const expr = new InterpExpr([new PathExpr(['name']), ' writes ', new PathExpr(['lang'])])
+ expect(expr.eval(scope)).toBe('Ada writes Hog')
+ })
+
+ it('a missing or null value renders as an empty string', () => {
+ const scope = Scope.forNode({ name: null }, 'user')
+ const expr = new InterpExpr(['name: ', new PathExpr(['name']), new PathExpr(['missing'])])
+ expect(expr.eval(scope)).toBe('name: ')
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.ts
new file mode 100644
index 000000000000..ffb27623aab6
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/interp.ts
@@ -0,0 +1,11 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class InterpExpr extends Expr {
+ constructor(private readonly parts: (string | Expr)[]) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ return this.parts.map((part) => (typeof part === 'string' ? part : String(part.eval(scope) ?? ''))).join('')
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.test.ts
new file mode 100644
index 000000000000..4a221324a1c9
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.test.ts
@@ -0,0 +1,23 @@
+import { Scope } from '../../scope'
+import { JoinExpr } from './join'
+import { LiteralExpr } from './literal'
+
+describe('JoinExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+
+ it('joins elements with the given separator', () => {
+ const expr = new JoinExpr(new LiteralExpr(['a', 'b', 'c']), new LiteralExpr(', '), null)
+ expect(expr.eval(scope)).toBe('a, b, c')
+ })
+
+ it('plucks a field from each object element when field is set', () => {
+ const items = [{ text: 'one' }, { text: 'two' }]
+ const expr = new JoinExpr(new LiteralExpr(items), new LiteralExpr(' / '), new LiteralExpr('text'))
+ expect(expr.eval(scope)).toBe('one / two')
+ })
+
+ it('returns an empty string for a non-array source', () => {
+ const expr = new JoinExpr(new LiteralExpr('not an array'), new LiteralExpr(', '), null)
+ expect(expr.eval(scope)).toBe('')
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.ts
new file mode 100644
index 000000000000..19bfa9ad94cf
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/join.ts
@@ -0,0 +1,26 @@
+import { readField } from '../../paths'
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class JoinExpr extends Expr {
+ constructor(
+ private readonly from: Expr,
+ private readonly sep: Expr | null,
+ private readonly field: Expr | null
+ ) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const arr = this.from.eval(scope)
+ if (!Array.isArray(arr)) {
+ return ''
+ }
+ const sep = this.sep ? this.sep.eval(scope) : undefined
+ const field = this.field ? this.field.eval(scope) : undefined
+ const sepStr = typeof sep === 'string' ? sep : '\n'
+ if (typeof field === 'string') {
+ return arr.map((item) => readField(item, field) ?? '').join(sepStr)
+ }
+ return arr.map((item) => String(item ?? '')).join(sepStr)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.test.ts
new file mode 100644
index 000000000000..a2b03acd7e1d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.test.ts
@@ -0,0 +1,23 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+import { LiteralExpr } from './literal'
+
+describe('LiteralExpr', () => {
+ const scope = Scope.forNode({ ignored: true }, 'user')
+
+ // Through the Expr interface: LiteralExpr narrows eval() to take no scope,
+ // but the point is that it ignores whatever scope a caller passes.
+ const evalLiteral = (value: unknown): unknown => {
+ const expr: Expr = new LiteralExpr(value)
+ return expr.eval(scope)
+ }
+
+ it('returns the wrapped value', () => {
+ expect(evalLiteral('hello')).toBe('hello')
+ expect(evalLiteral({ a: 1 })).toEqual({ a: 1 })
+ })
+
+ it.each([[0], [''], [false], [null]])('returns the falsy value %p unchanged', (value) => {
+ expect(evalLiteral(value)).toBe(value)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.ts
new file mode 100644
index 000000000000..9de7826b5af1
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/literal.ts
@@ -0,0 +1,10 @@
+import { Expr } from './base'
+
+export class LiteralExpr extends Expr {
+ constructor(readonly value: unknown) {
+ super()
+ }
+ eval(): unknown {
+ return this.value
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.test.ts
new file mode 100644
index 000000000000..24f6bb7ce6f4
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.test.ts
@@ -0,0 +1,16 @@
+import { Scope } from '../../scope'
+import { LiteralExpr } from './literal'
+import { ObjectExpr } from './object'
+import { PathExpr } from './path'
+
+describe('ObjectExpr', () => {
+ it('evaluates each field into an object', () => {
+ const scope = Scope.forNode({ name: 'Ada' }, 'user')
+ const expr = new ObjectExpr({ kind: new LiteralExpr('person'), label: new PathExpr(['name']) })
+ expect(expr.eval(scope)).toEqual({ kind: 'person', label: 'Ada' })
+ })
+
+ it('empty spec yields an empty object', () => {
+ expect(new ObjectExpr({}).eval(Scope.forNode({}, 'user'))).toEqual({})
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.ts
new file mode 100644
index 000000000000..9f0e06d6e547
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/object.ts
@@ -0,0 +1,15 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class ObjectExpr extends Expr {
+ constructor(private readonly fields: Record<string, Expr>) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const out: Record<string, unknown> = {}
+ for (const [k, v] of Object.entries(this.fields)) {
+ out[k] = v.eval(scope)
+ }
+ return out
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.test.ts
new file mode 100644
index 000000000000..b65095270172
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.test.ts
@@ -0,0 +1,23 @@
+import { Scope } from '../../scope'
+import { LiteralExpr } from './literal'
+import { OmitExpr } from './omit'
+
+describe('OmitExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+
+ it('returns a copy without the listed keys', () => {
+ const expr = new OmitExpr(new LiteralExpr({ a: 1, b: 2, c: 3 }), new LiteralExpr(['b']))
+ expect(expr.eval(scope)).toEqual({ a: 1, c: 3 })
+ })
+
+ it('does not mutate the source object', () => {
+ const source = { a: 1, b: 2 }
+ new OmitExpr(new LiteralExpr(source), new LiteralExpr(['b'])).eval(scope)
+ expect(source).toEqual({ a: 1, b: 2 })
+ })
+
+ it('returns an empty object for a non-object source', () => {
+ expect(new OmitExpr(new LiteralExpr('nope'), new LiteralExpr(['b'])).eval(scope)).toEqual({})
+ expect(new OmitExpr(new LiteralExpr([1, 2]), new LiteralExpr(['b'])).eval(scope)).toEqual({})
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.ts
new file mode 100644
index 000000000000..49b433e8e0ef
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/omit.ts
@@ -0,0 +1,24 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class OmitExpr extends Expr {
+ constructor(
+ private readonly from: Expr,
+ private readonly keys: Expr | null
+ ) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const from = this.from.eval(scope)
+ if (!from || typeof from !== 'object' || Array.isArray(from)) {
+ return {}
+ }
+ const rawKeys = this.keys ? this.keys.eval(scope) : undefined
+ const keys = Array.isArray(rawKeys) ? rawKeys.filter((k): k is string => typeof k === 'string') : []
+ const out: Record<string, unknown> = { ...(from as Record<string, unknown>) }
+ for (const k of keys) {
+ delete out[k]
+ }
+ return out
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.test.ts
new file mode 100644
index 000000000000..8a1b2b2600d8
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.test.ts
@@ -0,0 +1,15 @@
+import { Scope } from '../../scope'
+import { PathExpr } from './path'
+
+describe('PathExpr', () => {
+ it('reads a nested field by path', () => {
+ const scope = Scope.forNode({ message: { content: 'hello' } }, 'user')
+ expect(new PathExpr(['message', 'content']).eval(scope)).toBe('hello')
+ })
+
+ it('returns undefined when the path is missing', () => {
+ const scope = Scope.forNode({ message: {} }, 'user')
+ expect(new PathExpr(['message', 'content']).eval(scope)).toBeUndefined()
+ expect(new PathExpr(['missing', 'deep']).eval(scope)).toBeUndefined()
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.ts
new file mode 100644
index 000000000000..7dfa79d3600a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/path.ts
@@ -0,0 +1,12 @@
+import { readPath } from '../../paths'
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class PathExpr extends Expr {
+ constructor(private readonly segments: string[]) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ return readPath(scope.input, this.segments)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.test.ts
new file mode 100644
index 000000000000..6b9351fefca0
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.test.ts
@@ -0,0 +1,30 @@
+import { Scope } from '../../scope'
+import { EqualsPredicate, Pattern } from '../predicate'
+import { LiteralExpr } from './literal'
+import { RejectExpr } from './reject'
+
+const whereType = (type: string): Pattern => new Pattern({ type: new EqualsPredicate(type) })
+
+describe('RejectExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+ const items = [
+ { type: 'text', text: 'keep me' },
+ { type: 'image', text: 'drop me' },
+ ]
+
+ it('drops elements matching where and keeps the rest', () => {
+ const expr = new RejectExpr(new LiteralExpr(items), whereType('image'), null)
+ expect(expr.eval(scope)).toEqual([items[0]])
+ })
+
+ it('returns the if_empty fallback when everything is rejected', () => {
+ const allText = [{ type: 'text' }, { type: 'text' }]
+ const expr = new RejectExpr(new LiteralExpr(allText), whereType('text'), new LiteralExpr('fallback'))
+ expect(expr.eval(scope)).toBe('fallback')
+ })
+
+ it('a non-array source yields the empty/fallback result', () => {
+ expect(new RejectExpr(new LiteralExpr('nope'), null, null).eval(scope)).toEqual([])
+ expect(new RejectExpr(new LiteralExpr('nope'), null, new LiteralExpr('fallback')).eval(scope)).toBe('fallback')
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.ts
new file mode 100644
index 000000000000..10c74acee61d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/reject.ts
@@ -0,0 +1,18 @@
+import { Scope } from '../../scope'
+import { Pattern } from '../predicate'
+import { Expr } from './base'
+import { FilterExpr } from './filter'
+
+export class RejectExpr extends FilterExpr {
+ constructor(from: Expr, where: Pattern | null, ifEmpty: Expr | null) {
+ super(from, where, ifEmpty)
+ }
+ eval(scope: Scope): unknown {
+ const arr = this.from.eval(scope)
+ if (!Array.isArray(arr)) {
+ return this.onNotArray(scope)
+ }
+ const result = this.where ? arr.filter((item) => !this.where!.matches(item)) : arr
+ return this.withIfEmpty(result, scope)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.test.ts
new file mode 100644
index 000000000000..af88d7568579
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.test.ts
@@ -0,0 +1,38 @@
+import { Scope } from '../../scope'
+import { EqualsPredicate, Pattern } from '../predicate'
+import { LiteralExpr } from './literal'
+import { PathExpr } from './path'
+import { SelectExpr } from './select'
+
+const whereType = (type: string): Pattern => new Pattern({ type: new EqualsPredicate(type) })
+
+describe('SelectExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+ const items = [
+ { type: 'text', text: 'keep me' },
+ { type: 'image', text: 'drop me' },
+ { type: 'text', text: 'keep me too' },
+ ]
+
+ it('keeps elements matching where', () => {
+ const expr = new SelectExpr(new LiteralExpr(items), whereType('text'), null, null)
+ expect(expr.eval(scope)).toEqual([items[0], items[2]])
+ })
+
+ it('plucks a value from each kept element', () => {
+ const expr = new SelectExpr(new LiteralExpr(items), whereType('text'), new PathExpr(['text']), null)
+ expect(expr.eval(scope)).toEqual(['keep me', 'keep me too'])
+ })
+
+ it('returns the if_empty fallback when nothing matches', () => {
+ const expr = new SelectExpr(new LiteralExpr(items), whereType('audio'), null, new LiteralExpr('fallback'))
+ expect(expr.eval(scope)).toBe('fallback')
+ })
+
+ it('a non-array source yields the empty/fallback result', () => {
+ expect(new SelectExpr(new LiteralExpr('nope'), null, null, null).eval(scope)).toEqual([])
+ expect(new SelectExpr(new LiteralExpr('nope'), null, null, new LiteralExpr('fallback')).eval(scope)).toBe(
+ 'fallback'
+ )
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts
new file mode 100644
index 000000000000..04b56dddcc0e
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/select.ts
@@ -0,0 +1,24 @@
+import { Scope } from '../../scope'
+import { Pattern } from '../predicate'
+import { Expr } from './base'
+import { FilterExpr } from './filter'
+
+export class SelectExpr extends FilterExpr {
+ constructor(
+ from: Expr,
+ where: Pattern | null,
+ private readonly pluck: Expr | null,
+ ifEmpty: Expr | null
+ ) {
+ super(from, where, ifEmpty)
+ }
+ eval(scope: Scope): unknown {
+ const arr = this.from.eval(scope)
+ if (!Array.isArray(arr)) {
+ return this.onNotArray(scope)
+ }
+ const filtered = this.where ? arr.filter((item) => this.where!.matches(item)) : arr
+ const result = this.pluck ? filtered.map((item) => this.pluck!.eval(scope.withInput(item))) : filtered
+ return this.withIfEmpty(result, scope)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.test.ts
new file mode 100644
index 000000000000..5cf86758bb88
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.test.ts
@@ -0,0 +1,13 @@
+import { Scope } from '../../scope'
+import { SelfExpr } from './self'
+
+describe('SelfExpr', () => {
+ it('returns the whole input', () => {
+ const input = { role: 'user', content: 'hi' }
+ expect(new SelfExpr().eval(Scope.forNode(input, 'user'))).toBe(input)
+ })
+
+ it.each([['a string'], [42], [undefined]])('returns the primitive input %p as-is', (input) => {
+ expect(new SelfExpr().eval(Scope.forNode(input, 'user'))).toBe(input)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.ts
new file mode 100644
index 000000000000..eefe1342f91d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/self.ts
@@ -0,0 +1,8 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+export class SelfExpr extends Expr {
+ eval(scope: Scope): unknown {
+ return scope.input
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.test.ts
new file mode 100644
index 000000000000..e3c3c57758d7
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.test.ts
@@ -0,0 +1,25 @@
+import { Scope } from '../../scope'
+import { LiteralExpr } from './literal'
+import { StringifyExpr } from './stringify'
+
+describe('StringifyExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+ const stringify = (value: unknown): unknown => new StringifyExpr(new LiteralExpr(value)).eval(scope)
+
+ it('JSON-encodes an object', () => {
+ expect(stringify({ a: 1, b: 'two' })).toBe('{"a":1,"b":"two"}')
+ })
+
+ it.each([['plain'], [null], [undefined], [['a', 'b'] as unknown]])(
+ 'passes the content-slot value %p through untouched',
+ (value) => {
+ expect(stringify(value)).toEqual(value)
+ }
+ )
+
+ it('falls back to String() when the value cannot be JSON-encoded', () => {
+ const circular: Record<string, unknown> = {}
+ circular.self = circular
+ expect(stringify(circular)).toBe('[object Object]')
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.ts
new file mode 100644
index 000000000000..bdd226bb0f13
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/stringify.ts
@@ -0,0 +1,22 @@
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+// Renders a value as content text. String/array/null/undefined pass through
+// (the content slot handles those); everything else is JSON-encoded, falling
+// back to String() when JSON.stringify throws (e.g. circular refs).
+export class StringifyExpr extends Expr {
+ constructor(private readonly input: Expr) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const value = this.input.eval(scope)
+ if (typeof value === 'string' || value === null || value === undefined || Array.isArray(value)) {
+ return value
+ }
+ try {
+ return JSON.stringify(value)
+ } catch {
+ return String(value)
+ }
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts
new file mode 100644
index 000000000000..89b11352003b
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.test.ts
@@ -0,0 +1,29 @@
+import { Scope } from '../../scope'
+import { LiteralExpr } from './literal'
+import { TryParseStructuredContentExpr } from './tryParseStructuredContent'
+
+describe('TryParseStructuredContentExpr', () => {
+ const scope = Scope.forNode({}, 'user')
+ const parse = (value: unknown): unknown => new TryParseStructuredContentExpr(new LiteralExpr(value)).eval(scope)
+
+ it('parses a JSON array of structured-content blocks into objects', () => {
+ const blocks = [
+ { type: 'text', text: 'hello' },
+ { type: 'image_url', image_url: { url: 'x' } },
+ ]
+ expect(parse(JSON.stringify(blocks))).toEqual(blocks)
+ })
+
+ it('leaves a plain (non-array) string untouched', () => {
+ expect(parse('just text')).toBe('just text')
+ })
+
+ it('returns non-string input unchanged', () => {
+ const value = [{ type: 'text', text: 'hi' }]
+ expect(parse(value)).toBe(value)
+ })
+
+ it('returns the raw string when the JSON is invalid', () => {
+ expect(parse('[not valid json')).toBe('[not valid json')
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.ts b/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.ts
new file mode 100644
index 000000000000..603ee1f057d0
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/expr/tryParseStructuredContent.ts
@@ -0,0 +1,52 @@
+import { MultiModalContentItem } from '../../../../types'
+import { Scope } from '../../scope'
+import { Expr } from './base'
+
+const STRUCTURED_CONTENT_TYPES = new Set([
+ 'text',
+ 'output_text',
+ 'input_text',
+ 'function',
+ 'image',
+ 'input_image',
+ 'image_url',
+ 'file',
+ 'audio',
+ 'document',
+])
+
+export class TryParseStructuredContentExpr extends Expr {
+ constructor(private readonly input: Expr) {
+ super()
+ }
+ eval(scope: Scope): unknown {
+ const value = this.input.eval(scope)
+ return typeof value === 'string' ? parseStringifiedStructuredContent(value) : value
+ }
+}
+
+function parseStringifiedStructuredContent(content: string): string | MultiModalContentItem[] {
+ const trimmed = content.trim()
+ if (!trimmed.startsWith('[')) {
+ return content
+ }
+ try {
+ const parsed = JSON.parse(trimmed)
+ if (
+ Array.isArray(parsed) &&
+ parsed.every(
+ (item) =>
+ item &&
+ typeof item === 'object' &&
+ 'type' in item &&
+ typeof item.type === 'string' &&
+ STRUCTURED_CONTENT_TYPES.has(item.type)
+ )
+ ) {
+ return parsed as MultiModalContentItem[]
+ }
+ } catch {
+ // Not valid JSON — keep the raw string.
+ }
+ return content
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/base.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/base.ts
new file mode 100644
index 000000000000..4c023a84f1fc
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/base.ts
@@ -0,0 +1,3 @@
+export abstract class Predicate {
+ abstract test(value: unknown, present: boolean): boolean
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.test.ts
new file mode 100644
index 000000000000..4d0cd8faf1aa
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.test.ts
@@ -0,0 +1,12 @@
+import { EqualsPredicate } from './equals'
+
+describe('EqualsPredicate', () => {
+ it('true on a strict-equal value that is present', () => {
+ expect(new EqualsPredicate('tool').test('tool', true)).toBe(true)
+ expect(new EqualsPredicate('tool').test('other', true)).toBe(false)
+ })
+
+ it('false when the field is absent, even if the value would match', () => {
+ expect(new EqualsPredicate(undefined).test(undefined, false)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.ts
new file mode 100644
index 000000000000..028fba2c8588
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/equals.ts
@@ -0,0 +1,10 @@
+import { Predicate } from './base'
+
+export class EqualsPredicate extends Predicate {
+ constructor(private readonly expected: unknown) {
+ super()
+ }
+ test(value: unknown, present: boolean): boolean {
+ return present && value === this.expected
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.test.ts
new file mode 100644
index 000000000000..a9380195909a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.test.ts
@@ -0,0 +1,19 @@
+import { EveryPredicate } from './every'
+import { IsPredicate } from './is'
+
+describe('EveryPredicate', () => {
+ const allStrings = new EveryPredicate(new IsPredicate(['string']))
+
+ it('true when every element satisfies the inner predicate', () => {
+ expect(allStrings.test(['a', 'b', 'c'], true)).toBe(true)
+ })
+
+ it('false when any element fails the inner predicate', () => {
+ expect(allStrings.test(['a', 2, 'c'], true)).toBe(false)
+ })
+
+ it('false for an empty array or a non-array', () => {
+ expect(allStrings.test([], true)).toBe(false)
+ expect(allStrings.test('not an array', true)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.ts
new file mode 100644
index 000000000000..7d7f83b5c69b
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/every.ts
@@ -0,0 +1,13 @@
+import { Predicate } from './base'
+
+export class EveryPredicate extends Predicate {
+ constructor(private readonly element: Predicate) {
+ super()
+ }
+ test(value: unknown, present: boolean): boolean {
+ if (!present || !Array.isArray(value) || value.length === 0) {
+ return false
+ }
+ return value.every((item) => this.element.test(item, item !== undefined))
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.test.ts
new file mode 100644
index 000000000000..f07297b7db41
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.test.ts
@@ -0,0 +1,13 @@
+import { ExistsPredicate } from './exists'
+
+describe('ExistsPredicate', () => {
+ it('true when presence matches the expectation', () => {
+ expect(new ExistsPredicate(true).test('any', true)).toBe(true)
+ expect(new ExistsPredicate(false).test(undefined, false)).toBe(true)
+ })
+
+ it('false when presence is the opposite of what is expected', () => {
+ expect(new ExistsPredicate(true).test(undefined, false)).toBe(false)
+ expect(new ExistsPredicate(false).test('any', true)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.ts
new file mode 100644
index 000000000000..54cb74829d31
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/exists.ts
@@ -0,0 +1,10 @@
+import { Predicate } from './base'
+
+export class ExistsPredicate extends Predicate {
+ constructor(private readonly shouldExist: boolean) {
+ super()
+ }
+ test(_value: unknown, present: boolean): boolean {
+ return present === this.shouldExist
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.test.ts
new file mode 100644
index 000000000000..9e54b1a66356
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.test.ts
@@ -0,0 +1,12 @@
+import { InPredicate } from './in'
+
+describe('InPredicate', () => {
+ it('true when the value is in the set', () => {
+ expect(new InPredicate(['a', 'b', 'c']).test('b', true)).toBe(true)
+ })
+
+ it('false when the value is out of the set or absent', () => {
+ expect(new InPredicate(['a', 'b']).test('z', true)).toBe(false)
+ expect(new InPredicate(['a', 'b']).test(undefined, false)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.ts
new file mode 100644
index 000000000000..bd20d1712cfa
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/in.ts
@@ -0,0 +1,10 @@
+import { Predicate } from './base'
+
+export class InPredicate extends Predicate {
+ constructor(private readonly values: unknown[]) {
+ super()
+ }
+ test(value: unknown, present: boolean): boolean {
+ return present && this.values.includes(value)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/index.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/index.ts
new file mode 100644
index 000000000000..9ab382d11342
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/index.ts
@@ -0,0 +1,9 @@
+export { Predicate } from './base'
+export { Pattern } from './pattern'
+export type { TypeName } from './typeName'
+export { EqualsPredicate } from './equals'
+export { ExistsPredicate } from './exists'
+export { IsPredicate } from './is'
+export { InPredicate } from './in'
+export { ShapePredicate } from './shape'
+export { EveryPredicate } from './every'
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.test.ts
new file mode 100644
index 000000000000..15769988e0cb
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.test.ts
@@ -0,0 +1,13 @@
+import { IsPredicate } from './is'
+
+describe('IsPredicate', () => {
+ it('true when the value is one of the listed types', () => {
+ expect(new IsPredicate(['string', 'array']).test('hi', true)).toBe(true)
+ expect(new IsPredicate(['string', 'array']).test([1], true)).toBe(true)
+ })
+
+ it('false for a non-listed type or an absent field', () => {
+ expect(new IsPredicate(['string']).test(42, true)).toBe(false)
+ expect(new IsPredicate(['string']).test(undefined, false)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.ts
new file mode 100644
index 000000000000..1980328ba9d0
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/is.ts
@@ -0,0 +1,11 @@
+import { Predicate } from './base'
+import { matchesType, TypeName } from './typeName'
+
+export class IsPredicate extends Predicate {
+ constructor(private readonly types: TypeName[]) {
+ super()
+ }
+ test(value: unknown, present: boolean): boolean {
+ return present && this.types.some((type) => matchesType(value, type))
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.test.ts
new file mode 100644
index 000000000000..d3f9e00fcde9
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.test.ts
@@ -0,0 +1,28 @@
+import { EqualsPredicate } from './equals'
+import { ExistsPredicate } from './exists'
+import { IsPredicate } from './is'
+import { Pattern } from './pattern'
+
+describe('Pattern', () => {
+ it('true when every field predicate passes', () => {
+ const pattern = new Pattern({ role: new EqualsPredicate('user'), content: new IsPredicate(['string']) })
+ expect(pattern.matches({ role: 'user', content: 'hi' })).toBe(true)
+ })
+
+ it('false when any field predicate fails', () => {
+ const pattern = new Pattern({ role: new EqualsPredicate('user'), content: new IsPredicate(['string']) })
+ expect(pattern.matches({ role: 'user', content: 42 })).toBe(false)
+ })
+
+ it('the $ field applies its predicate to the whole input', () => {
+ const pattern = new Pattern({ $: new IsPredicate(['string']) })
+ expect(pattern.matches('a bare string')).toBe(true)
+ expect(pattern.matches({ not: 'a string' })).toBe(false)
+ })
+
+ it('an absent field is reported as not-present to its predicate', () => {
+ const pattern = new Pattern({ role: new ExistsPredicate(false) })
+ expect(pattern.matches({ content: 'hi' })).toBe(true)
+ expect(pattern.matches({ role: 'user' })).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.ts
new file mode 100644
index 000000000000..4ad1dede6d1d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/pattern.ts
@@ -0,0 +1,17 @@
+import { hasField, readField } from '../../paths'
+import { Predicate } from './base'
+
+export class Pattern {
+ constructor(private readonly fields: Record<string, Predicate>) {}
+
+ matches(input: unknown): boolean {
+ for (const [field, predicate] of Object.entries(this.fields)) {
+ const value = field === '$' ? input : readField(input, field)
+ const present = field === '$' ? input !== undefined : hasField(input, field)
+ if (!predicate.test(value, present)) {
+ return false
+ }
+ }
+ return true
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.test.ts
new file mode 100644
index 000000000000..d215880f2446
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.test.ts
@@ -0,0 +1,18 @@
+import { EqualsPredicate } from './equals'
+import { Pattern } from './pattern'
+import { ShapePredicate } from './shape'
+
+describe('ShapePredicate', () => {
+ const shape = new ShapePredicate(new Pattern({ type: new EqualsPredicate('text') }))
+
+ it('true when the nested object matches the pattern', () => {
+ expect(shape.test({ type: 'text', text: 'hi' }, true)).toBe(true)
+ })
+
+ it('false for a non-object, null, or absent value', () => {
+ expect(shape.test({ type: 'image' }, true)).toBe(false)
+ expect(shape.test('text', true)).toBe(false)
+ expect(shape.test(null, true)).toBe(false)
+ expect(shape.test(undefined, false)).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.ts
new file mode 100644
index 000000000000..6012f72b0608
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/shape.ts
@@ -0,0 +1,14 @@
+import { Predicate } from './base'
+import { Pattern } from './pattern'
+
+export class ShapePredicate extends Predicate {
+ constructor(private readonly nested: Pattern) {
+ super()
+ }
+ test(value: unknown, present: boolean): boolean {
+ if (!present || !value || typeof value !== 'object') {
+ return false
+ }
+ return this.nested.matches(value)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.test.ts
new file mode 100644
index 000000000000..467dab98eaca
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.test.ts
@@ -0,0 +1,23 @@
+import { matchesType, TypeName } from './typeName'
+
+describe('matchesType', () => {
+ it.each<[TypeName, unknown]>([
+ ['string', 'hi'],
+ ['number', 42],
+ ['boolean', true],
+ ['null', null],
+ ['array', [1, 2]],
+ ['object', { a: 1 }],
+ ])('matches %s to its value', (type, value) => {
+ expect(matchesType(value, type)).toBe(true)
+ })
+
+ it.each<[unknown]>([['hi'], [42], [null], [{ a: 1 }], [[1]]])('any matches everything (%p)', (value) => {
+ expect(matchesType(value, 'any')).toBe(true)
+ })
+
+ it('object excludes arrays and null', () => {
+ expect(matchesType([1, 2], 'object')).toBe(false)
+ expect(matchesType(null, 'object')).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.ts b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.ts
new file mode 100644
index 000000000000..d0ca7e46d7f3
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/predicate/typeName.ts
@@ -0,0 +1,20 @@
+export type TypeName = 'string' | 'array' | 'object' | 'null' | 'number' | 'boolean' | 'any'
+
+export function matchesType(value: unknown, type: TypeName): boolean {
+ switch (type) {
+ case 'any':
+ return true
+ case 'string':
+ return typeof value === 'string'
+ case 'number':
+ return typeof value === 'number'
+ case 'boolean':
+ return typeof value === 'boolean'
+ case 'null':
+ return value === null
+ case 'array':
+ return Array.isArray(value)
+ case 'object':
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts
new file mode 100644
index 000000000000..77761b55870b
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.test.ts
@@ -0,0 +1,53 @@
+import { CompatMessage } from '../../../../types'
+import { Scope } from '../../scope'
+import { FollowupSpec } from '../../spec/emitSpec'
+import { LiteralExpr } from '../expr'
+import { Pattern } from '../predicate'
+import { Rule } from './base'
+import { DispatchEngine } from './dispatch'
+
+// buildFollowups is concrete on the abstract base; a no-op subclass exposes it.
+class TestRule extends Rule {
+ produce(): CompatMessage[] {
+ return []
+ }
+}
+
+const scope = Scope.forNode({ role: 'user' }, 'user')
+
+function engineBuilding(build: DispatchEngine['coercer']['buildMessage']): DispatchEngine {
+ return { dispatch: jest.fn(), coercer: { buildMessage: build, stamp: jest.fn() } }
+}
+
+describe('Rule.buildFollowups', () => {
+ it('builds a static followup message', () => {
+ const followups: FollowupSpec[] = [{ kind: 'static', emit: {} }]
+ const message: CompatMessage = { role: 'system', content: 'note' }
+ const rule = new TestRule(new Pattern({}), followups)
+ expect(rule.buildFollowups(scope, engineBuilding(jest.fn().mockReturnValue(message)))).toEqual([message])
+ })
+
+ it('expands an array into one message per element', () => {
+ const followups: FollowupSpec[] = [{ kind: 'expand', from: new LiteralExpr(['a', 'b']), each: {} }]
+ const rule = new TestRule(new Pattern({}), followups)
+ const build = jest.fn((_emit, s: Scope): CompatMessage => ({ role: 'user', content: s.input as string }))
+ expect(rule.buildFollowups(scope, engineBuilding(build))).toEqual([
+ { role: 'user', content: 'a' },
+ { role: 'user', content: 'b' },
+ ])
+ })
+
+ it('drops followups the coercer rejects', () => {
+ const followups: FollowupSpec[] = [{ kind: 'static', emit: {} }]
+ const rule = new TestRule(new Pattern({}), followups)
+ expect(rule.buildFollowups(scope, engineBuilding(jest.fn().mockReturnValue(null)))).toEqual([])
+ })
+
+ it('an expand over a non-array yields no followups', () => {
+ const followups: FollowupSpec[] = [{ kind: 'expand', from: new LiteralExpr('not an array'), each: {} }]
+ const rule = new TestRule(new Pattern({}), followups)
+ const build = jest.fn()
+ expect(rule.buildFollowups(scope, engineBuilding(build))).toEqual([])
+ expect(build).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts
new file mode 100644
index 000000000000..f7dc51b7c9c7
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/base.ts
@@ -0,0 +1,38 @@
+import type { CompatMessage } from '../../../../types'
+import type { Scope } from '../../scope'
+import type { FollowupSpec } from '../../spec/emitSpec'
+import type { Pattern } from '../predicate'
+import type { DispatchEngine } from './dispatch'
+
+export abstract class Rule {
+ constructor(
+ readonly on: Pattern,
+ private readonly followups: FollowupSpec[]
+ ) {}
+
+ abstract produce(scope: Scope, engine: DispatchEngine, allowDrop: boolean, depth: number): CompatMessage[]
+
+ buildFollowups(scope: Scope, engine: DispatchEngine): CompatMessage[] {
+ const messages: CompatMessage[] = []
+ for (const followup of this.followups) {
+ if (followup.kind === 'static') {
+ const msg = engine.coercer.buildMessage(followup.emit, scope)
+ if (msg) {
+ messages.push(msg)
+ }
+ continue
+ }
+ const arr = followup.from.eval(scope)
+ if (!Array.isArray(arr)) {
+ continue
+ }
+ for (const item of arr) {
+ const msg = engine.coercer.buildMessage(followup.each, scope.withInput(item))
+ if (msg) {
+ messages.push(msg)
+ }
+ }
+ }
+ return messages
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts
new file mode 100644
index 000000000000..c68a280ca559
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.test.ts
@@ -0,0 +1,30 @@
+import { CompatMessage } from '../../../../types'
+import { Scope } from '../../scope'
+import { LiteralExpr } from '../expr'
+import { Pattern } from '../predicate'
+import { DelegateRule } from './delegate'
+import { DispatchEngine, NO_MATCH } from './dispatch'
+
+const scope = Scope.forNode({ role: 'assistant' }, 'user')
+
+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 rule = new DelegateRule(new Pattern({}), [], new LiteralExpr({ unwrapped: true }))
+ expect(rule.produce(scope, engine, false, 3)).toBe(inner)
+ // delegation re-dispatches the derived value at the next depth, carrying the resolved role
+ expect(dispatch).toHaveBeenCalledWith({ unwrapped: true }, 'assistant', 4)
+ })
+
+ it('returns nothing when the delegated value matches no recipe', () => {
+ const engine: DispatchEngine = {
+ dispatch: jest.fn().mockReturnValue(NO_MATCH),
+ coercer: { buildMessage: jest.fn(), stamp: jest.fn() },
+ }
+ 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/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.ts
new file mode 100644
index 000000000000..7eb7e2dbea27
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegate.ts
@@ -0,0 +1,22 @@
+import type { CompatMessage } from '../../../../types'
+import type { Scope } from '../../scope'
+import type { FollowupSpec } from '../../spec/emitSpec'
+import type { Expr } from '../expr'
+import type { Pattern } from '../predicate'
+import { Rule } from './base'
+import { DispatchEngine, NO_MATCH } from './dispatch'
+
+export class DelegateRule extends Rule {
+ constructor(
+ on: Pattern,
+ followups: FollowupSpec[],
+ private readonly source: Expr
+ ) {
+ super(on, followups)
+ }
+ produce(scope: Scope, engine: DispatchEngine, _allowDrop: boolean, depth: number): CompatMessage[] {
+ const next = this.source.eval(scope)
+ const sub = engine.dispatch(next, scope.role, depth + 1)
+ return sub === NO_MATCH ? [] : sub
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts
new file mode 100644
index 000000000000..551f5bc73783
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.test.ts
@@ -0,0 +1,57 @@
+import { CompatMessage } from '../../../../types'
+import { Scope } from '../../scope'
+import { LiteralExpr } from '../expr'
+import { Pattern } from '../predicate'
+import { DelegateEachRule } from './delegateEach'
+import { DispatchEngine, NO_MATCH } from './dispatch'
+
+const scope = Scope.forNode({ role: 'user' }, 'user')
+
+describe('DelegateEachRule', () => {
+ it('dispatches each element and concatenates the messages', () => {
+ const dispatch = jest
+ .fn()
+ .mockReturnValueOnce([{ role: 'user', content: 'a' }])
+ .mockReturnValueOnce([{ role: 'user', content: 'b' }])
+ const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+
+ const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr(['x', 'y']), null)
+ expect(rule.produce(scope, engine, false, 0)).toEqual([
+ { role: 'user', content: 'a' },
+ { role: 'user', content: 'b' },
+ ])
+ })
+
+ it('stamps the parent context onto produced messages when stamp is set', () => {
+ const stamp = jest.fn((msg: CompatMessage): CompatMessage => ({ ...msg, tool_call_id: 'parent' }))
+ const engine: DispatchEngine = {
+ dispatch: jest.fn().mockReturnValue([{ role: 'assistant (tool result)', content: 'r' }]),
+ coercer: { buildMessage: jest.fn(), stamp },
+ }
+ const rule = new DelegateEachRule(new Pattern({}), [], new LiteralExpr(['x']), {
+ toolCallId: new LiteralExpr('parent'),
+ })
+ expect(rule.produce(scope, engine, false, 0)).toEqual([
+ { role: 'assistant (tool result)', content: 'r', tool_call_id: 'parent' },
+ ])
+ expect(stamp).toHaveBeenCalledTimes(1)
+ })
+
+ it('skips elements that match no recipe', () => {
+ const dispatch = jest
+ .fn()
+ .mockReturnValueOnce(NO_MATCH)
+ .mockReturnValueOnce([{ role: 'user', content: 'kept' }])
+ const engine: DispatchEngine = { dispatch, coercer: { buildMessage: jest.fn(), stamp: jest.fn() } }
+
+ 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 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/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.ts
new file mode 100644
index 000000000000..7dca87410e47
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/delegateEach.ts
@@ -0,0 +1,35 @@
+import type { CompatMessage } from '../../../../types'
+import type { Scope } from '../../scope'
+import type { EmitSpec, FollowupSpec } from '../../spec/emitSpec'
+import type { Expr } from '../expr'
+import type { Pattern } from '../predicate'
+import { Rule } from './base'
+import { DispatchEngine, NO_MATCH } from './dispatch'
+
+export class DelegateEachRule extends Rule {
+ constructor(
+ on: Pattern,
+ followups: FollowupSpec[],
+ private readonly source: Expr,
+ private readonly stamp: EmitSpec | null
+ ) {
+ super(on, followups)
+ }
+ produce(scope: Scope, engine: DispatchEngine, _allowDrop: boolean, depth: number): CompatMessage[] {
+ const arr = this.source.eval(scope)
+ if (!Array.isArray(arr)) {
+ return []
+ }
+ const messages: CompatMessage[] = []
+ for (const item of arr) {
+ const sub = engine.dispatch(item, scope.role, depth + 1)
+ if (sub !== NO_MATCH) {
+ messages.push(...sub)
+ }
+ }
+ if (!this.stamp) {
+ return messages
+ }
+ return messages.map((msg) => engine.coercer.stamp(msg, this.stamp!, scope))
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts
new file mode 100644
index 000000000000..0546c3dafcad
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/dispatch.ts
@@ -0,0 +1,20 @@
+import type { CompatMessage } from '../../../../types'
+import type { Scope } from '../../scope'
+import type { EmitSpec } from '../../spec/emitSpec'
+
+// Distinguishes "no rule matched" (keep scanning) from "a rule matched and
+// produced zero messages" (a committed empty result).
+export const NO_MATCH = Symbol('no-match')
+export type DispatchResult = CompatMessage[] | typeof NO_MATCH
+
+// The ast layer declares this contract so it never imports from runtime/;
+// SlotCoercer is the implementation.
+export interface MessageBuilder {
+ buildMessage(emit: EmitSpec, scope: Scope, allowDrop?: boolean): CompatMessage | null
+ stamp(message: CompatMessage, emit: EmitSpec, scope: Scope): CompatMessage
+}
+
+export interface DispatchEngine {
+ dispatch(input: unknown, inheritedRole: string, depth: number): DispatchResult
+ readonly coercer: MessageBuilder
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts
new file mode 100644
index 000000000000..c8152d62e08c
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.test.ts
@@ -0,0 +1,28 @@
+import { CompatMessage } from '../../../../types'
+import { Scope } from '../../scope'
+import { Pattern } from '../predicate'
+import { Rule } from './base'
+import { DispatchEngine } from './dispatch'
+import { EmitRule } from './emit'
+
+const scope = Scope.forNode({ role: 'user' }, 'user')
+
+function engineReturning(message: CompatMessage | null): DispatchEngine {
+ return {
+ dispatch: jest.fn(),
+ coercer: { buildMessage: jest.fn().mockReturnValue(message), stamp: jest.fn() },
+ }
+}
+
+describe('EmitRule', () => {
+ it('produces a single message from the emit spec', () => {
+ const message: CompatMessage = { role: 'user', content: 'hi' }
+ const rule: Rule = new EmitRule(new Pattern({}), [], {})
+ expect(rule.produce(scope, engineReturning(message), false, 0)).toEqual([message])
+ })
+
+ it('produces nothing when the coercer drops an empty message', () => {
+ const rule: Rule = new EmitRule(new Pattern({}), [], {})
+ expect(rule.produce(scope, engineReturning(null), true, 0)).toEqual([])
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts
new file mode 100644
index 000000000000..13d715a23d6a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/emit.ts
@@ -0,0 +1,20 @@
+import type { CompatMessage } from '../../../../types'
+import type { Scope } from '../../scope'
+import type { EmitSpec, FollowupSpec } from '../../spec/emitSpec'
+import type { Pattern } from '../predicate'
+import { Rule } from './base'
+import type { DispatchEngine } from './dispatch'
+
+export class EmitRule extends Rule {
+ constructor(
+ on: Pattern,
+ followups: FollowupSpec[],
+ private readonly emit: EmitSpec
+ ) {
+ super(on, followups)
+ }
+ produce(scope: Scope, engine: DispatchEngine, allowDrop: boolean): CompatMessage[] {
+ const message = engine.coercer.buildMessage(this.emit, scope, allowDrop)
+ return message ? [message] : []
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/ast/rule/index.ts b/products/ai_observability/frontend/normalizer/recipe/ast/rule/index.ts
new file mode 100644
index 000000000000..817d720fc692
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/ast/rule/index.ts
@@ -0,0 +1,6 @@
+export { NO_MATCH } from './dispatch'
+export type { DispatchResult, DispatchEngine } from './dispatch'
+export { Rule } from './base'
+export { EmitRule } from './emit'
+export { DelegateRule } from './delegate'
+export { DelegateEachRule } from './delegateEach'
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
new file mode 100644
index 000000000000..4d66fb262f4d
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
@@ -0,0 +1,77 @@
+import { CompatMessage } from '../../../types'
+import { DispatchEngine, NO_MATCH } from '../ast/rule'
+import { SlotCoercer } from '../runtime/coercion'
+import { Scope } from '../scope'
+import { compileRecipe } from './compiler'
+
+jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
+
+const ENGINE: DispatchEngine = { dispatch: () => NO_MATCH, coercer: new SlotCoercer() }
+const INPUT = { name: 'Ada', items: ['a', 'b'] }
+
+// Compile a one-rule recipe and produce its message, so we can observe how the
+// compiler wired a value expression (trusting the AST nodes + coercer).
+function emitContent(content: unknown, input: unknown = INPUT): CompatMessage['content'] {
+ const recipe = compileRecipe({ id: 't', rules: [{ on: {}, emit: { content } }] })
+ return recipe.rules[0].produce(Scope.forNode(input, 'user'), ENGINE, false, 0)[0]?.content
+}
+
+describe('compileRecipe', () => {
+ it('compiles a full recipe into runnable rules', () => {
+ const recipe = compileRecipe({ id: 'greet', priority: 5, rules: [{ on: {}, emit: { content: 'hi' } }] })
+ expect(recipe.id).toBe('greet')
+ const produced = recipe.rules[0].produce(Scope.forNode({}, 'user'), ENGINE, false, 0)
+ expect(produced).toEqual([{ role: 'user', content: 'hi' }])
+ })
+
+ it('a $.field string compiles to a value that reads that field', () => {
+ expect(emitContent('$.name')).toBe('Ada')
+ })
+
+ it('an interpolation string compiles to a value that splices fields into text', () => {
+ expect(emitContent('hello $.name!')).toBe('hello Ada!')
+ })
+
+ it('a one-key operator object compiles to that operator', () => {
+ expect(emitContent({ join: { from: '$.items', sep: ',' } })).toBe('a,b')
+ })
+
+ it('a bare scalar field compiles to an equality predicate', () => {
+ const recipe = compileRecipe({ id: 't', rules: [{ on: { type: 'reasoning' }, emit: {} }] })
+ expect(recipe.rules[0].on.matches({ type: 'reasoning' })).toBe(true)
+ expect(recipe.rules[0].on.matches({ type: 'text' })).toBe(false)
+ })
+
+ it('priority defaults to 100 when omitted', () => {
+ expect(compileRecipe({ id: 't', rules: [{ on: {}, emit: {} }] }).priority).toBe(100)
+ })
+
+ it('literal: preserves a one-key object that collides with an operator name', () => {
+ // Bare `{ join: 'x' }` is read as the join operator, which rejects a non-mapping arg.
+ expect(() => emitContent({ join: 'x' })).toThrow(/takes a mapping/)
+ // Wrapped in `literal:`, the same object is kept as plain data (surfaced here via spread).
+ const recipe = compileRecipe({ id: 't', rules: [{ on: {}, emit: { spread: { literal: { join: 'x' } } } }] })
+ const message = recipe.rules[0].produce(Scope.forNode({}, 'user'), ENGINE, false, 0)[0]
+ expect(message.join).toBe('x')
+ })
+
+ it('throws a helpful "did you mean" error for an unknown operator', () => {
+ expect(() => emitContent({ jon: { from: '$.items' } })).toThrow(/Did you mean 'join'/)
+ })
+
+ it('throws when a rule sets none of emit, delegate, or delegateEach', () => {
+ expect(() => compileRecipe({ id: 't', rules: [{ on: {} }] })).toThrow(/emit, delegate, delegateEach/)
+ })
+
+ it.each([
+ ['missing id', { rules: [] }, /missing an 'id'/],
+ ['missing rules', { id: 't' }, /missing a 'rules:'/],
+ ])('throws when %s', (_label, raw, expected) => {
+ expect(() => compileRecipe(raw)).toThrow(expected)
+ })
+
+ it('throws when a predicate mixes multiple verbs', () => {
+ const raw = { id: 't', rules: [{ on: { field: { equals: 1, exists: true } }, emit: {} }] }
+ expect(() => compileRecipe(raw)).toThrow(/multiple verbs/)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
new file mode 100644
index 000000000000..cabffc109158
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
@@ -0,0 +1,393 @@
+import {
+ ArrayExpr,
+ CoalesceExpr,
+ Expr,
+ InterpExpr,
+ JoinExpr,
+ LiteralExpr,
+ ObjectExpr,
+ OmitExpr,
+ PathExpr,
+ RejectExpr,
+ SelectExpr,
+ SelfExpr,
+ StringifyExpr,
+ TryParseStructuredContentExpr,
+} from '../ast/expr'
+import {
+ EqualsPredicate,
+ ExistsPredicate,
+ EveryPredicate,
+ InPredicate,
+ IsPredicate,
+ Pattern,
+ Predicate,
+ ShapePredicate,
+ TypeName,
+} from '../ast/predicate'
+import { DelegateEachRule, DelegateRule, EmitRule, Rule } from '../ast/rule'
+import { EmitSpec, FollowupSpec, RoleTag } from '../spec/emitSpec'
+import { Recipe } from '../spec/recipe'
+import { nearestOperator } from './operatorSuggestion'
+
+const PREDICATE_VERBS = new Set(['equals', 'exists', 'is', 'in', 'shape', 'every'])
+const ROLE_TAGS: ReadonlySet<RoleTag> = new Set(['user', 'assistant', 'system', 'tool', 'thinking', 'tool_result'])
+const TYPE_NAMES: ReadonlySet<TypeName> = new Set(['string', 'array', 'object', 'null', 'number', 'boolean', 'any'])
+const OPERATORS = new Set([
+ 'select',
+ 'reject',
+ 'coalesce',
+ 'join',
+ 'omit',
+ 'try_parse_structured_content',
+ 'stringify',
+ 'literal',
+])
+
+const BARE_FIELD_RE = /^[A-Za-z_]\w*$/
+
+export function compileRecipe(raw: unknown): Recipe {
+ if (!isObject(raw)) {
+ throw new Error(`Recipe YAML must be a mapping at top level`)
+ }
+ const id = stringField(raw, 'id')
+ if (!id) {
+ throw new Error(`Recipe is missing an 'id' key`)
+ }
+ const rulesRaw = raw.rules
+ if (!Array.isArray(rulesRaw)) {
+ throw new Error(`Recipe '${id}' is missing a 'rules:' sequence`)
+ }
+ return {
+ id,
+ priority: numField(raw, 'priority') ?? 100,
+ capture: stringField(raw, 'capture'),
+ rules: rulesRaw.map((r, i) => {
+ try {
+ return compileRule(r)
+ } catch (err) {
+ throw new Error(`Recipe '${id}' rule[${i}]: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ }),
+ }
+}
+
+function compileRule(raw: unknown): Rule {
+ if (!isObject(raw)) {
+ throw new Error(`rule must be a mapping`)
+ }
+ if (!isObject(raw.on)) {
+ throw new Error(`rule.on must be a mapping`)
+ }
+ const on = compilePattern(raw.on)
+ const followups = compileFollowups(raw.followups)
+
+ if (raw.delegate !== undefined) {
+ return new DelegateRule(on, followups, compileValue(raw.delegate))
+ }
+ if (raw.delegateEach !== undefined) {
+ const stamp = raw.stamp !== undefined ? compileEmitSpec(raw.stamp) : null
+ return new DelegateEachRule(on, followups, compileValue(raw.delegateEach), stamp)
+ }
+ if (raw.emit !== undefined) {
+ return new EmitRule(on, followups, compileEmitSpec(raw.emit))
+ }
+ throw new Error('Rule must set one of: emit, delegate, delegateEach')
+}
+
+function compileFollowups(raw: unknown): FollowupSpec[] {
+ if (raw === undefined) {
+ return []
+ }
+ if (!Array.isArray(raw)) {
+ throw new Error(`rule.followups must be a sequence`)
+ }
+ return raw.map(compileFollowup)
+}
+
+function compileFollowup(raw: unknown): FollowupSpec {
+ if (!isObject(raw)) {
+ throw new Error(`followup entry must be a mapping`)
+ }
+ if ('from' in raw && 'each' in raw) {
+ if (!isObject(raw.each)) {
+ throw new Error(`'each:' in followup must be a mapping`)
+ }
+ return { kind: 'expand', from: compileValue(raw.from), each: compileEmitSpec(raw.each) }
+ }
+ return { kind: 'static', emit: compileEmitSpec(raw) }
+}
+
+function compilePattern(raw: Record<string, unknown>): Pattern {
+ const fields: Record<string, Predicate> = {}
+ for (const [key, value] of Object.entries(raw)) {
+ fields[key] = compilePredicate(value)
+ }
+ return new Pattern(fields)
+}
+
+function compilePredicate(raw: unknown): Predicate {
+ if (isObject(raw)) {
+ const keys = Object.keys(raw)
+ const verbs = keys.filter((k) => PREDICATE_VERBS.has(k))
+ if (verbs.length > 1) {
+ throw new Error(`predicate has multiple verbs (${verbs.join(', ')}); use one verb per field`)
+ }
+ if (verbs.length === 1) {
+ 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(', ')})`)
+ }
+ return buildPredicateFromVerb(verbs[0], raw[verbs[0]])
+ }
+ return new ShapePredicate(compilePattern(raw))
+ }
+ return new EqualsPredicate(raw)
+}
+
+function buildPredicateFromVerb(verb: string, value: unknown): Predicate {
+ switch (verb) {
+ case 'equals':
+ return new EqualsPredicate(value)
+ case 'exists':
+ return new ExistsPredicate(Boolean(value))
+ case 'is': {
+ const arr = Array.isArray(value) ? value : [value]
+ const types: TypeName[] = []
+ for (const t of arr) {
+ // YAML bare `null` parses as JS null, but inside `is: [...]` the
+ // author meant the type name 'null'. Normalize either to 'null'.
+ const name = t === null ? 'null' : t
+ if (typeof name !== 'string' || !TYPE_NAMES.has(name as TypeName)) {
+ throw new Error(`'is:' must be a type or array of types, got ${JSON.stringify(value)}`)
+ }
+ types.push(name as TypeName)
+ }
+ return new IsPredicate(types)
+ }
+ case 'in':
+ if (!Array.isArray(value)) {
+ throw new Error(`'in:' must be an array`)
+ }
+ return new InPredicate(value)
+ case 'shape':
+ if (!isObject(value)) {
+ throw new Error(`'shape:' must be a mapping`)
+ }
+ return new ShapePredicate(compilePattern(value))
+ case 'every':
+ return new EveryPredicate(compilePredicate(value))
+ default:
+ throw new Error(`Unknown predicate verb '${verb}'`)
+ }
+}
+
+function compileEmitSpec(raw: unknown): EmitSpec {
+ if (!isObject(raw)) {
+ throw new Error(`emit must be a mapping`)
+ }
+ const out: EmitSpec = {}
+ for (const [k, v] of Object.entries(raw)) {
+ switch (k) {
+ case 'role':
+ out.role = typeof v === 'string' && ROLE_TAGS.has(v as RoleTag) ? (v as RoleTag) : compileValue(v)
+ break
+ case 'content':
+ out.content = compileValue(v)
+ break
+ case 'toolCall':
+ out.toolCall = compileValue(v)
+ break
+ case 'toolCalls':
+ out.toolCalls = compileValue(v)
+ break
+ case 'toolCallId':
+ case 'tool_call_id':
+ out.toolCallId = compileValue(v)
+ break
+ case 'spread':
+ out.spread = compileValue(v)
+ break
+ default:
+ throw new Error(`Unknown emit key '${k}'`)
+ }
+ }
+ return out
+}
+
+function compileValue(raw: unknown): Expr {
+ if (raw === null || raw === undefined) {
+ return new LiteralExpr(null)
+ }
+ if (typeof raw === 'number' || typeof raw === 'boolean') {
+ return new LiteralExpr(raw)
+ }
+ if (typeof raw === 'string') {
+ return compileStringValue(raw)
+ }
+ if (Array.isArray(raw)) {
+ return new ArrayExpr(raw.map(compileValue))
+ }
+ if (isObject(raw)) {
+ const keys = Object.keys(raw)
+ if (keys.length === 1) {
+ const key = keys[0]
+ if (OPERATORS.has(key)) {
+ return compileOperator(key, raw[key])
+ }
+ const suggestion = nearestOperator(key, OPERATORS)
+ if (suggestion) {
+ throw new Error(
+ `Unknown operator '${key}'. Did you mean '${suggestion}'? ` +
+ `Wrap an intentional one-key object in 'literal:'.`
+ )
+ }
+ }
+ const fields: Record<string, Expr> = {}
+ for (const [k, v] of Object.entries(raw)) {
+ fields[k] = compileValue(v)
+ }
+ return new ObjectExpr(fields)
+ }
+ return new LiteralExpr(raw)
+}
+
+// Requires an identifier after `$.` so a stray `$` in a URL or price isn't read as a path.
+const INTERP_RE = /\$\.([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)/g
+
+function compileStringValue(s: string): Expr {
+ if (s === '$') {
+ return new SelfExpr()
+ }
+ if (/^\$\.[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/.test(s)) {
+ return new PathExpr(s.slice(2).split('.').filter(Boolean))
+ }
+ if (s.startsWith('$') && /^[$][A-Za-z_]/.test(s)) {
+ throw new Error(
+ `'${s}' is not a valid value expression. Use '$.${s.slice(1)}' for a field read, or '$' for the whole input.`
+ )
+ }
+ INTERP_RE.lastIndex = 0
+ if (INTERP_RE.test(s)) {
+ return compileInterp(s)
+ }
+ return new LiteralExpr(s)
+}
+
+function compileInterp(s: string): Expr {
+ const parts: (string | Expr)[] = []
+ INTERP_RE.lastIndex = 0
+ let cursor = 0
+ let m: RegExpExecArray | null
+ while ((m = INTERP_RE.exec(s)) !== null) {
+ if (m.index > cursor) {
+ parts.push(s.slice(cursor, m.index))
+ }
+ parts.push(new PathExpr(m[1].split('.')))
+ cursor = m.index + m[0].length
+ }
+ if (cursor < s.length) {
+ parts.push(s.slice(cursor))
+ }
+ return new InterpExpr(parts)
+}
+
+function compileOperator(op: string, payload: unknown): Expr {
+ switch (op) {
+ // Escape hatch for an intentional one-key data object whose key collides
+ // with an operator name; the payload is kept uncompiled.
+ case 'literal':
+ return new LiteralExpr(payload)
+ case 'coalesce':
+ return new CoalesceExpr(compileCoalesceFrom(payload))
+ case 'try_parse_structured_content':
+ return new TryParseStructuredContentExpr(compileValue(payload))
+ case 'stringify':
+ return new StringifyExpr(compileValue(payload))
+ case 'join': {
+ const args = asOperatorMapping(op, payload)
+ return new JoinExpr(operatorArg(args, 'from'), optionalArg(args, 'sep'), optionalArg(args, 'field'))
+ }
+ case 'omit': {
+ const args = asOperatorMapping(op, payload)
+ return new OmitExpr(operatorArg(args, 'from'), optionalArg(args, 'keys'))
+ }
+ case 'select': {
+ const args = asOperatorMapping(op, payload)
+ return new SelectExpr(
+ operatorArg(args, 'from'),
+ compileWhere(args.where),
+ compilePluck(args.pluck),
+ optionalArg(args, 'if_empty')
+ )
+ }
+ case 'reject': {
+ const args = asOperatorMapping(op, payload)
+ return new RejectExpr(operatorArg(args, 'from'), compileWhere(args.where), optionalArg(args, 'if_empty'))
+ }
+ default:
+ throw new Error(`Unknown operator: ${op}`)
+ }
+}
+
+function compileCoalesceFrom(payload: unknown): Expr {
+ if (Array.isArray(payload)) {
+ return new ArrayExpr(payload.map(compileValue))
+ }
+ if (!isObject(payload)) {
+ throw new Error(`'coalesce:' takes an array or {from: [...]}`)
+ }
+ return operatorArg(payload, 'from')
+}
+
+function compileWhere(raw: unknown): Pattern | null {
+ if (raw === undefined) {
+ return null
+ }
+ if (!isObject(raw)) {
+ throw new Error(`'where:' must be a mapping`)
+ }
+ return compilePattern(raw)
+}
+
+function compilePluck(raw: unknown): Expr | null {
+ if (raw === undefined) {
+ return null
+ }
+ if (typeof raw === 'string' && BARE_FIELD_RE.test(raw)) {
+ return new PathExpr([raw])
+ }
+ return compileValue(raw)
+}
+
+function asOperatorMapping(op: string, payload: unknown): Record<string, unknown> {
+ if (!isObject(payload)) {
+ throw new Error(`'${op}:' takes a mapping`)
+ }
+ return payload
+}
+
+function operatorArg(args: Record<string, unknown>, key: string): Expr {
+ if (!(key in args)) {
+ throw new Error(`operator requires a '${key}:' argument`)
+ }
+ return compileValue(args[key])
+}
+
+function optionalArg(args: Record<string, unknown>, key: string): Expr | null {
+ return key in args ? compileValue(args[key]) : null
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return !!v && typeof v === 'object' && !Array.isArray(v)
+}
+
+function stringField(o: Record<string, unknown>, key: string): string | undefined {
+ const value = o[key]
+ return typeof value === 'string' ? value : undefined
+}
+
+function numField(o: Record<string, unknown>, key: string): number | undefined {
+ const value = o[key]
+ return typeof value === 'number' ? value : undefined
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.test.ts b/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.test.ts
new file mode 100644
index 000000000000..f2dd0932af06
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.test.ts
@@ -0,0 +1,21 @@
+import { nearestOperator } from './operatorSuggestion'
+
+const OPERATORS = new Set(['select', 'reject', 'coalesce', 'join', 'omit', 'stringify', 'literal'])
+
+describe('nearestOperator', () => {
+ it.each([
+ ['selct', 'select', 'deletion'],
+ ['joins', 'join', 'insertion'],
+ ['omat', 'omit', 'substitution'],
+ ])('suggests %s → %s (%s)', (typo, expected) => {
+ expect(nearestOperator(typo, OPERATORS)).toBe(expected)
+ })
+
+ it('returns nothing when no operator is close', () => {
+ expect(nearestOperator('completely_different', OPERATORS)).toBeUndefined()
+ })
+
+ it('does not suggest for an exact (non-typo) match', () => {
+ expect(nearestOperator('select', OPERATORS)).toBeUndefined()
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.ts b/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.ts
new file mode 100644
index 000000000000..ff9d1af28c11
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/operatorSuggestion.ts
@@ -0,0 +1,28 @@
+export function nearestOperator(key: string, operators: Iterable<string>): string | undefined {
+ for (const op of operators) {
+ if (withinOneEdit(key, op)) {
+ return op
+ }
+ }
+ return undefined
+}
+
+function withinOneEdit(a: string, b: string): boolean {
+ if (a === b) {
+ return false
+ }
+ if (Math.abs(a.length - b.length) > 1) {
+ return false
+ }
+ let i = 0
+ while (i < a.length && i < b.length && a[i] === b[i]) {
+ i++
+ }
+ if (a.length === b.length) {
+ return a.slice(i + 1) === b.slice(i + 1) // substitution
+ }
+ if (a.length < b.length) {
+ return a.slice(i) === b.slice(i + 1) // insertion in b
+ }
+ return a.slice(i + 1) === b.slice(i) // deletion in b
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml
new file mode 100644
index 000000000000..63519a61fd18
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/anthropic.yaml
@@ -0,0 +1,99 @@
+# Example: { type: tool_use, id, name, input } · { role, content: [<block>, ...] }
+#
+# The envelope with top-level tool_calls produces N+1 messages (one per content
+# block plus a synthetic tool_calls message) via delegateEach + followups.
+
+id: anthropic
+priority: 50
+
+rules:
+ - on:
+ type: text
+ text: { exists: true }
+ emit:
+ content: $.text
+
+ - on:
+ type: thinking
+ emit:
+ role: thinking
+ content: $.thinking
+
+ - on:
+ type: tool_use
+ emit:
+ content: ''
+ toolCall:
+ id: $.id
+ name: $.name
+ args: $.input
+
+ - on:
+ type: tool_result
+ content: { is: array }
+ tool_use_id: { exists: true }
+ delegateEach: $.content
+ stamp:
+ role: tool_result
+ toolCallId: $.tool_use_id
+
+ - on:
+ type: tool_result
+ tool_use_id: { exists: true }
+ emit:
+ role: tool_result
+ content:
+ stringify: $.content
+ toolCallId: $.tool_use_id
+
+ # Anthropic ships images/documents as `source: {type: base64, data, media_type}`;
+ # reshape into the renderer's content parts.
+ - on:
+ type: image
+ source:
+ data: { is: string }
+ media_type: { is: string }
+ emit:
+ content:
+ - type: image
+ image: 'data:$.source.media_type;base64,$.source.data'
+
+ - on:
+ type: document
+ source:
+ data: { is: string }
+ media_type: { is: string }
+ emit:
+ content:
+ - type: file
+ file:
+ mime_type: $.source.media_type
+ data: $.source.data
+
+ # Top-level tool_calls duplicate the in-content tool_use blocks; the top-level
+ # version is richer, so drop the duplicates from content before delegating.
+ - on:
+ role: { is: string }
+ content: { is: array }
+ tool_calls: { is: array }
+ delegateEach:
+ reject:
+ from: $.content
+ where: { type: tool_use }
+ followups:
+ - role: $.role
+ content: ''
+ toolCalls: $.tool_calls
+
+ - on:
+ role: { is: string }
+ content: { is: array }
+ delegateEach: $.content
+
+ # The string-content fallback for envelopes openai_chat (priority 35) didn't
+ # claim — i.e. a role not on its allowlist.
+ - on:
+ role: { is: string }
+ content: { is: string }
+ emit:
+ content: $.content
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml
new file mode 100644
index 000000000000..429ead5d3d34
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml
@@ -0,0 +1,18 @@
+# Last-resort salvage for shapes no provider matched. `capture:` fires on match
+# so brand-new shapes still surface in telemetry. Highest priority so it runs last.
+
+id: cajole
+priority: 1000
+capture: llma message normalization failed
+
+rules:
+ - on:
+ content: { is: string }
+ emit:
+ content: $.content
+
+ - on:
+ $: { exists: true }
+ emit:
+ content:
+ stringify: $
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/compat_array.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/compat_array.yaml
new file mode 100644
index 000000000000..de10db63ff04
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/compat_array.yaml
@@ -0,0 +1,39 @@
+# Cross-SDK typed-block content array (`{role, content: [{type: <allowlisted>}, ...]}`).
+# Lowest priority (5) so it claims these before the envelope rules can shadow it.
+
+id: compat_array
+priority: 5
+
+rules:
+ - on:
+ role: { is: string }
+ content:
+ every:
+ shape:
+ type:
+ in:
+ - text
+ - output_text
+ - input_text
+ - function
+ - image
+ - input_image
+ - image_url
+ - file
+ - audio
+ - document
+ emit:
+ # `if_empty: ''` matches legacy's "all-function blocks → empty content".
+ content:
+ reject:
+ from: $.content
+ where: { type: function }
+ if_empty: ''
+ toolCalls:
+ select:
+ from: $.content
+ where: { type: function }
+ pluck:
+ id: $.id
+ name: $.function.name
+ args: $.function.arguments
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/dispatcher_entry.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/dispatcher_entry.yaml
new file mode 100644
index 000000000000..349d2c166c4a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/dispatcher_entry.yaml
@@ -0,0 +1,21 @@
+# Entry-level unwraps (array / {choices} envelope / bare string). Must stay at
+# the lowest priority so envelopes are peeled before any provider rule matches.
+
+id: dispatcher_entry
+priority: 1
+
+rules:
+ - on:
+ $: { is: array }
+ delegateEach: $
+
+ # The response-level `{choices: [...]}` shape, distinct from litellm.yaml's
+ # per-choice match on `finish_reason`/`index`.
+ - on:
+ choices: { is: array }
+ delegateEach: $.choices
+
+ - on:
+ $: { is: string }
+ emit:
+ content: $
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain.yaml
new file mode 100644
index 000000000000..68559c2bb0b2
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/langchain.yaml
@@ -0,0 +1,16 @@
+# LangChain / LangGraph: `type` instead of `role`. `.content` may be an arbitrary
+# object, so it goes through `stringify` (strings/arrays pass through unchanged).
+
+id: langchain
+priority: 20
+
+rules:
+ - on:
+ role: { exists: false }
+ type: { in: [human, ai, tool, system, context] }
+ content: { exists: true }
+ emit:
+ content:
+ stringify: $.content
+ toolCalls: $.tool_calls
+ toolCallId: $.tool_call_id
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/litellm.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/litellm.yaml
new file mode 100644
index 000000000000..05634b36c44f
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/litellm.yaml
@@ -0,0 +1,12 @@
+# A LiteLLM choice (`{finish_reason, index, message}`) wraps a provider message;
+# delegate `.message` so its own provider recipe handles it.
+
+id: litellm
+priority: 10
+
+rules:
+ - on:
+ finish_reason: { exists: true }
+ index: { exists: true }
+ message: { is: object }
+ delegate: $.message
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_chat.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_chat.yaml
new file mode 100644
index 000000000000..b2b0facef101
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_chat.yaml
@@ -0,0 +1,24 @@
+# Example: { role: assistant, content: "hi", tool_calls: [{ id, type: function, function: { name, arguments } }] }
+
+id: openai_chat
+priority: 35
+
+rules:
+ - on:
+ role: { exists: true }
+ content: { is: [string, null] }
+ emit:
+ # `spread: $` lets unknown kwargs (e.g. function_call) survive to the output.
+ spread: $
+ content:
+ try_parse_structured_content: $.content
+ # Lift OpenAI's `{id, type, function: {name, arguments}}` into the canonical
+ # `{id, name, args}` here, so the coercer stays provider-agnostic.
+ toolCalls:
+ select:
+ from: $.tool_calls
+ pluck:
+ id: $.id
+ name: $.function.name
+ args: $.function.arguments
+ toolCallId: $.tool_call_id
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_responses.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_responses.yaml
new file mode 100644
index 000000000000..cfafc8a2a1bc
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/openai_responses.yaml
@@ -0,0 +1,125 @@
+# Example: { type: function_call, call_id: c1, name: search, arguments: '{"q":"x"}' }
+
+id: openai_responses
+priority: 40
+
+rules:
+ - on:
+ type: function_call
+ call_id: { is: string }
+ name: { is: string }
+ arguments: { exists: true }
+ emit:
+ role: assistant
+ content: ''
+ toolCall:
+ id: $.call_id
+ name: $.name
+ args: $.arguments
+
+ - on:
+ type: function_call_output
+ call_id: { is: string }
+ output: { exists: true }
+ emit:
+ role: tool_result
+ content:
+ stringify: $.output
+ toolCallId: $.call_id
+
+ - on:
+ type: reasoning
+ summary: { is: array }
+ emit:
+ role: thinking
+ content:
+ join:
+ from: $.summary
+ field: text
+ sep: "\n"
+
+ - on:
+ type: reasoning
+ text: { is: string }
+ emit:
+ role: thinking
+ content: $.text
+
+ - on:
+ type: reasoning
+ emit:
+ role: thinking
+ content: ''
+
+ # Built-in tool calls. Three rules split on the `arguments` shape, which the
+ # SDK varies: string/object passes through; absent means the other top-level
+ # fields are the params (omit the structural keys); any other type is wrapped.
+ - on:
+ type:
+ in:
+ - web_search_call
+ - code_interpreter_call
+ - image_generation_call
+ - mcp_call
+ - file_search_call
+ - computer_call
+ id: { is: string }
+ arguments: { is: [string, object] }
+ emit:
+ role: assistant
+ content: ''
+ toolCall:
+ id: $.id
+ name:
+ coalesce:
+ - $.name
+ - $.type
+ args: $.arguments
+
+ - on:
+ type:
+ in:
+ - web_search_call
+ - code_interpreter_call
+ - image_generation_call
+ - mcp_call
+ - file_search_call
+ - computer_call
+ id: { is: string }
+ arguments: { exists: false }
+ emit:
+ role: assistant
+ content: ''
+ toolCall:
+ id: $.id
+ name:
+ coalesce:
+ - $.name
+ - $.type
+ args:
+ omit:
+ from: $
+ keys: [id, type, status, name, arguments]
+
+ - on:
+ type:
+ in:
+ - web_search_call
+ - code_interpreter_call
+ - image_generation_call
+ - mcp_call
+ - file_search_call
+ - computer_call
+ id: { is: string }
+ arguments: { exists: true }
+ emit:
+ role: assistant
+ content: ''
+ toolCall:
+ id: $.id
+ name:
+ coalesce:
+ - $.name
+ - $.type
+ args:
+ arguments: $.arguments
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/otel.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/otel.yaml
new file mode 100644
index 000000000000..5c693c4cd881
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/otel.yaml
@@ -0,0 +1,44 @@
+# OTel parts format: `{role, parts: [...]}`. text parts become content,
+# tool_call parts become tool_calls, and each tool_call_response part spawns its
+# own follow-up tool message.
+#
+# `if_empty: ~` drops the primary only when followups exist, so a message whose
+# parts produce nothing at all still emits one empty-content message (legacy parity).
+
+id: otel
+priority: 60
+
+rules:
+ - on:
+ role: { is: string }
+ parts: { is: array }
+ emit:
+ # Keep top-level metadata (e.g. `finish_reason`) by omitting only role/parts.
+ spread:
+ omit:
+ from: $
+ keys: [role, parts]
+ content:
+ select:
+ from: $.parts
+ where: { type: text }
+ pluck: content
+ if_empty: ~
+ toolCalls:
+ select:
+ from: $.parts
+ where: { type: tool_call }
+ pluck:
+ id: $.id
+ name: $.name
+ args: $.arguments
+ followups:
+ - from:
+ select:
+ from: $.parts
+ where: { type: tool_call_response }
+ each:
+ role: tool
+ toolCallId: $.id
+ content:
+ stringify: $.result
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/vercel_sdk.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/vercel_sdk.yaml
new file mode 100644
index 000000000000..f54945a29720
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/vercel_sdk.yaml
@@ -0,0 +1,60 @@
+# Example: { type: tool-call, toolCallId: t1, toolName: search, input: { q: "x" } }
+
+id: vercel_sdk
+priority: 30
+
+rules:
+ - on:
+ type: text
+ content: { is: string }
+ emit:
+ content: $.content
+
+ - on:
+ type: input_text
+ text: { is: string }
+ emit:
+ content: $.text
+
+ - on:
+ type: input_image
+ image_url: { is: string }
+ emit:
+ content:
+ - image: $.image_url
+
+ - on:
+ type: tool-call
+ id: { exists: true }
+ function:
+ name: { is: string }
+ emit:
+ content: ''
+ toolCall:
+ id: $.id
+ name: $.function.name
+ args: $.function.arguments
+
+ # `function: { exists: false }` keeps this from competing with the function variant above.
+ - on:
+ type: tool-call
+ toolName: { is: string }
+ function: { exists: false }
+ emit:
+ content: ''
+ toolCall:
+ id: $.toolCallId
+ name: $.toolName
+ args:
+ coalesce:
+ - $.input
+ - {}
+
+ - on:
+ type: tool-result
+ toolName: { is: string }
+ emit:
+ role: tool_result
+ content:
+ stringify: $.output
+ toolCallId: $.toolCallId
diff --git a/products/ai_observability/frontend/normalizer/recipe/paths.test.ts b/products/ai_observability/frontend/normalizer/recipe/paths.test.ts
new file mode 100644
index 000000000000..9f3f99db225a
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/paths.test.ts
@@ -0,0 +1,20 @@
+import { hasField, readField, readPath } from './paths'
+
+describe('paths', () => {
+ it('readField returns a present field and readPath walks nested segments', () => {
+ expect(readField({ role: 'user' }, 'role')).toBe('user')
+ expect(readPath({ a: { b: { c: 1 } } }, ['a', 'b', 'c'])).toBe(1)
+ })
+
+ it('hasField reports presence', () => {
+ expect(hasField({ role: 'user' }, 'role')).toBe(true)
+ expect(hasField({ role: undefined }, 'role')).toBe(true)
+ })
+
+ it('all return undefined/false for missing keys or non-object cursors', () => {
+ expect(readField({ a: 1 }, 'missing')).toBeUndefined()
+ expect(readField('not an object', 'length')).toBeUndefined()
+ expect(readPath({ a: {} }, ['a', 'b', 'c'])).toBeUndefined()
+ expect(hasField('not an object', 'length')).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/paths.ts b/products/ai_observability/frontend/normalizer/recipe/paths.ts
new file mode 100644
index 000000000000..a825deba52da
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/paths.ts
@@ -0,0 +1,22 @@
+export function readField(input: unknown, field: string): unknown {
+ if (input && typeof input === 'object' && field in (input as object)) {
+ return (input as Record<string, unknown>)[field]
+ }
+ return undefined
+}
+
+export function hasField(input: unknown, field: string): boolean {
+ return !!input && typeof input === 'object' && field in input
+}
+
+export function readPath(input: unknown, segments: string[]): unknown {
+ let cursor: unknown = input
+ for (const seg of segments) {
+ if (cursor && typeof cursor === 'object' && seg in (cursor as object)) {
+ cursor = (cursor as Record<string, unknown>)[seg]
+ } else {
+ return undefined
+ }
+ }
+ return cursor
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
new file mode 100644
index 000000000000..22d16b227dd9
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
@@ -0,0 +1,55 @@
+import { AVAILABLE_TOOLS_ROLE } from '../../utils'
+import { RecipeNormalizer } from './recipeNormalizer'
+import { NO_MATCH } from './runtime/pipeline'
+
+const mockRun = jest.fn()
+
+jest.mock('./registry', () => ({ loadRecipes: () => [] }))
+jest.mock('./runtime/pipeline', () => ({
+ NO_MATCH: Symbol('no-match'),
+ RecipePipeline: jest.fn().mockImplementation(() => ({ run: mockRun })),
+}))
+
+describe('RecipeNormalizer', () => {
+ let normalizer: RecipeNormalizer
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ normalizer = new RecipeNormalizer()
+ })
+
+ describe('normalizeMessage', () => {
+ it("returns the pipeline's normalized messages for a matched input", () => {
+ const messages = [{ role: 'assistant', content: 'hi' }]
+ mockRun.mockReturnValue(messages)
+ expect(normalizer.normalizeMessage({ role: 'assistant' }, 'user')).toBe(messages)
+ })
+
+ it('returns no messages for undefined input without dispatching', () => {
+ expect(normalizer.normalizeMessage(undefined, 'user')).toEqual([])
+ expect(mockRun).not.toHaveBeenCalled()
+ })
+
+ it('throws when nothing matches (catch-all coverage gap)', () => {
+ mockRun.mockReturnValue(NO_MATCH)
+ expect(() => normalizer.normalizeMessage({ weird: true }, 'user')).toThrow(/no recipe matched/)
+ })
+ })
+
+ describe('normalizeMessages', () => {
+ it('prepends an available-tools message when tools are given', () => {
+ mockRun.mockReturnValue([{ role: 'assistant', content: 'hi' }])
+ const tools = [{ name: 'search' }]
+ expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user', tools)).toEqual([
+ { role: AVAILABLE_TOOLS_ROLE, content: '', tools },
+ { role: 'assistant', content: 'hi' },
+ ])
+ })
+
+ it('without tools just returns the normalized messages', () => {
+ const messages = [{ role: 'assistant', content: 'hi' }]
+ mockRun.mockReturnValue(messages)
+ expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user')).toEqual(messages)
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
new file mode 100644
index 000000000000..edfc3ff9b529
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
@@ -0,0 +1,38 @@
+import { CompatMessage } from '../../types'
+import { AVAILABLE_TOOLS_ROLE, safeStringify } from '../../utils'
+import { loadRecipes } from './registry'
+import { NO_MATCH, RecipePipeline } from './runtime/pipeline'
+
+export class RecipeNormalizer {
+ private readonly pipeline: RecipePipeline
+
+ constructor() {
+ this.pipeline = new RecipePipeline(loadRecipes())
+ }
+
+ normalizeMessage(input: unknown, defaultRole: string): CompatMessage[] {
+ // `undefined` carries no message (a missing field, a sparse array slot). cajole
+ // intentionally doesn't match it, so handle it here rather than dispatch a miss.
+ if (input === undefined) {
+ return []
+ }
+ const result = this.pipeline.run(input, defaultRole)
+ if (result === NO_MATCH) {
+ // cajole.yaml matches anything, so NO_MATCH means a coverage gap, not a normal miss.
+ throw new Error(
+ `RecipeNormalizer: no recipe matched ${safeStringify(input, 0).slice(0, 200)} — cajole.yaml should be the final catch-all`
+ )
+ }
+ return result
+ }
+
+ normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {
+ const messages: CompatMessage[] = []
+ if (tools) {
+ // `tools` is a function parameter, not a message shape, so it has no recipe.
+ messages.push({ role: AVAILABLE_TOOLS_ROLE, content: '', tools })
+ }
+ messages.push(...this.normalizeMessage(input, defaultRole))
+ return messages
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.test.ts b/products/ai_observability/frontend/normalizer/recipe/registry.test.ts
new file mode 100644
index 000000000000..de38906f6f1f
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/registry.test.ts
@@ -0,0 +1,14 @@
+import { loadRecipes } from './registry'
+
+describe('loadRecipes', () => {
+ it('loads the bundled recipes', () => {
+ const recipes = loadRecipes()
+ expect(recipes.length).toBeGreaterThan(0)
+ expect(recipes.every((r) => typeof r.id === 'string' && r.id.length > 0)).toBe(true)
+ })
+
+ it('every loaded recipe has a unique priority', () => {
+ const priorities = loadRecipes().map((r) => r.priority)
+ expect(new Set(priorities).size).toBe(priorities.length)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.ts b/products/ai_observability/frontend/normalizer/recipe/registry.ts
new file mode 100644
index 000000000000..e4d332cbb8e6
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/registry.ts
@@ -0,0 +1,50 @@
+import { parse as parseYaml } from 'yaml'
+
+import { compileRecipe } from './compile/compiler'
+import anthropic from './default_recipes/anthropic.yaml?raw'
+import cajole from './default_recipes/cajole.yaml?raw'
+import compatArray from './default_recipes/compat_array.yaml?raw'
+import dispatcherEntry from './default_recipes/dispatcher_entry.yaml?raw'
+import langchain from './default_recipes/langchain.yaml?raw'
+import litellm from './default_recipes/litellm.yaml?raw'
+import openaiChat from './default_recipes/openai_chat.yaml?raw'
+import openaiResponses from './default_recipes/openai_responses.yaml?raw'
+import otel from './default_recipes/otel.yaml?raw'
+import vercelSdk from './default_recipes/vercel_sdk.yaml?raw'
+import { Recipe } from './spec/recipe'
+
+const RECIPE_SOURCES = {
+ anthropic,
+ cajole,
+ compatArray,
+ dispatcherEntry,
+ langchain,
+ litellm,
+ openaiChat,
+ openaiResponses,
+ otel,
+ vercelSdk,
+}
+
+const RECIPES: Recipe[] = Object.entries(RECIPE_SOURCES).map(([name, source]) => {
+ try {
+ return compileRecipe(parseYaml(source))
+ } catch (err) {
+ throw new Error(`Loading recipe ${name}: ${err instanceof Error ? err.message : String(err)}`)
+ }
+})
+
+// Dispatch is first-match-wins over priority order, so two recipes sharing a
+// priority would have an undefined relative order. Fail loudly instead.
+const seenPriorities = new Map<number, string>()
+for (const recipe of RECIPES) {
+ const clash = seenPriorities.get(recipe.priority)
+ if (clash !== undefined) {
+ throw new Error(`Recipe priority ${recipe.priority} is used by both '${clash}' and '${recipe.id}'`)
+ }
+ seenPriorities.set(recipe.priority, recipe.id)
+}
+
+export function loadRecipes(): Recipe[] {
+ return RECIPES
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts
new file mode 100644
index 000000000000..fe4e70b6c6de
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.test.ts
@@ -0,0 +1,104 @@
+import posthog from 'posthog-js'
+
+import { CompatMessage } from '../../../types'
+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 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())
+
+ it('builds a message with role and content', () => {
+ const emit: EmitSpec = { content: lit('hello') }
+ expect(coercer.buildMessage(emit, scope({}, 'assistant'))).toEqual({ role: 'assistant', content: 'hello' })
+ })
+
+ it('maps a role tag to the renderer-facing role string', () => {
+ const emit: EmitSpec = { role: 'tool_result', content: lit('done') }
+ expect(coercer.buildMessage(emit, scope())).toEqual({ role: 'assistant (tool result)', content: 'done' })
+ })
+
+ it('normalizes a function-shaped tool call into the canonical form', () => {
+ const emit: EmitSpec = {
+ toolCall: lit({
+ type: 'function',
+ id: 'c1',
+ function: { name: 'get_weather', arguments: { city: 'NYC' } },
+ }),
+ }
+ expect(coercer.buildMessage(emit, scope())?.tool_calls).toEqual([
+ { type: 'function', id: 'c1', function: { name: 'get_weather', arguments: { city: 'NYC' } } },
+ ])
+ })
+
+ it('normalizes a bare {name, args} tool call', () => {
+ const emit: EmitSpec = { toolCall: lit({ id: 'c2', name: 'search', args: { q: 'hog' } }) }
+ expect(coercer.buildMessage(emit, scope())?.tool_calls).toEqual([
+ { type: 'function', id: 'c2', function: { name: 'search', arguments: { q: 'hog' } } },
+ ])
+ })
+
+ it('parses string tool-call arguments into an object', () => {
+ const emit: EmitSpec = { toolCall: lit({ name: 'search', arguments: '{"q":"hog"}' }) }
+ expect(coercer.buildMessage(emit, scope())?.tool_calls?.[0].function.arguments).toEqual({ q: 'hog' })
+ })
+
+ it('keeps unparseable string arguments as a raw string', () => {
+ const emit: EmitSpec = { toolCall: lit({ name: 'search', arguments: '{not json' }) }
+ expect(coercer.buildMessage(emit, scope())?.tool_calls?.[0].function.arguments).toBe('{not json')
+ })
+
+ it('collapses a single-item text array to a plain string', () => {
+ const emit: EmitSpec = { content: lit(['only one']) }
+ expect(coercer.buildMessage(emit, scope())?.content).toBe('only one')
+ })
+
+ it('defaults missing content to an empty string', () => {
+ const emit: EmitSpec = { role: 'user' }
+ expect(coercer.buildMessage(emit, scope())).toEqual({ role: 'user', content: '' })
+ })
+
+ it('spread fills the base while explicit slots win', () => {
+ const emit: EmitSpec = {
+ spread: lit({ content: 'from spread', extra: 1 }),
+ role: 'system',
+ content: lit('override'),
+ }
+ expect(coercer.buildMessage(emit, scope())).toEqual({ role: 'system', content: 'override', extra: 1 })
+ })
+
+ it('drops to null when the message is empty and dropping is allowed', () => {
+ const emit: EmitSpec = { role: 'user' }
+ expect(coercer.buildMessage(emit, scope(), true)).toBeNull()
+ })
+
+ 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()
+ })
+})
+
+describe('SlotCoercer.stamp', () => {
+ it('overrides role and tool_call_id on an already-built message', () => {
+ const message: CompatMessage = { role: 'user', content: 'r' }
+ const emit: EmitSpec = { role: 'tool_result', toolCallId: lit('tc1') }
+ expect(coercer.stamp(message, emit, scope())).toEqual({
+ role: 'assistant (tool result)',
+ content: 'r',
+ tool_call_id: 'tc1',
+ })
+ })
+
+ it('leaves fields untouched when emit slots are absent', () => {
+ const message: CompatMessage = { role: 'assistant', content: 'r' }
+ expect(coercer.stamp(message, {}, scope())).toEqual({ role: 'assistant', content: 'r' })
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts
new file mode 100644
index 000000000000..ea5a753b4ef9
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/coercion.ts
@@ -0,0 +1,188 @@
+import posthog from 'posthog-js'
+
+import { CompatMessage, CompatToolCall, MultiModalContentItem } from '../../../types'
+import { normalizeRole } from '../../../utils'
+import { Expr } from '../ast/expr'
+import { Scope } from '../scope'
+import { EmitSpec, RoleTag } from '../spec/emitSpec'
+
+// Maps symbolic role tags to the legacy renderer-facing strings; a temporary
+// shim until the renderer can consume the symbolic tags directly.
+const ROLE_TAGS: Record<RoleTag, string> = {
+ user: 'user',
+ assistant: 'assistant',
+ system: 'system',
+ tool: 'tool',
+ thinking: 'assistant (thinking)',
+ tool_result: 'assistant (tool result)',
+}
+
+export class SlotCoercer {
+ buildMessage(emit: EmitSpec, scope: Scope, allowDrop: boolean = false): CompatMessage | null {
+ // Spread first, so the explicit slots below override it.
+ let base: Partial<CompatMessage> = {}
+ if (emit.spread !== undefined) {
+ const spread = emit.spread.eval(scope)
+ if (spread && typeof spread === 'object' && !Array.isArray(spread)) {
+ base = { ...(spread as Record<string, unknown>) } as Partial<CompatMessage>
+ }
+ }
+
+ const role = this.coerceRole(emit.role, scope)
+
+ if (emit.content !== undefined) {
+ base.content = this.coerceContent(emit.content.eval(scope))
+ }
+ if (emit.toolCallId !== undefined) {
+ const id = emit.toolCallId.eval(scope)
+ if (typeof id === 'string') {
+ base.tool_call_id = id
+ }
+ }
+ if (emit.toolCall !== undefined) {
+ const normalized = this.coerceSingleToolCall(emit.toolCall.eval(scope))
+ if (normalized) {
+ base.tool_calls = [normalized]
+ }
+ }
+ if (emit.toolCalls !== undefined) {
+ // Explicit override: assigning `undefined` clears any value the
+ // spread may have put there.
+ base.tool_calls = this.coerceToolCalls(emit.toolCalls.eval(scope))
+ }
+
+ const isEmpty =
+ base.content === undefined &&
+ base.tool_calls === undefined &&
+ base.tool_call_id === undefined &&
+ (base as { tools?: unknown }).tools === undefined
+
+ if (allowDrop && isEmpty) {
+ return null
+ }
+ // Renderers expect a string, so default empty content rather than leave it undefined.
+ return { ...base, role, content: base.content ?? '' }
+ }
+
+ // Attaches the parent's role/tool_call_id onto children that normalized
+ // independently via `delegateEach` (the Anthropic tool_result case).
+ stamp(message: CompatMessage, emit: EmitSpec, scope: Scope): CompatMessage {
+ const stamped: CompatMessage = { ...message }
+ if (emit.role !== undefined) {
+ stamped.role = this.coerceRole(emit.role, scope)
+ }
+ if (emit.toolCallId !== undefined) {
+ const id = emit.toolCallId.eval(scope)
+ if (typeof id === 'string') {
+ stamped.tool_call_id = id
+ }
+ }
+ return stamped
+ }
+
+ private coerceRole(roleExpr: Expr | RoleTag | undefined, scope: Scope): string {
+ const defaultRole = scope.role
+ if (roleExpr === undefined) {
+ return defaultRole
+ }
+ if (typeof roleExpr === 'string') {
+ return normalizeRole(ROLE_TAGS[roleExpr], defaultRole)
+ }
+ const evaluated = roleExpr.eval(scope)
+ if (typeof evaluated === 'string') {
+ return normalizeRole(evaluated, defaultRole)
+ }
+ return defaultRole
+ }
+
+ private coerceContent(value: unknown): CompatMessage['content'] | undefined {
+ if (value === undefined) {
+ return undefined
+ }
+ if (value === null) {
+ return ''
+ }
+ if (typeof value === 'string') {
+ return value
+ }
+ if (Array.isArray(value)) {
+ // Empties are not dropped here — recipes opt into that with `if_empty: ~`.
+ if (value.length > 0 && value.every((v) => typeof v === 'string')) {
+ if (value.length === 1) {
+ return value[0]
+ }
+ return value.map((text) => ({ type: 'text' as const, text: text as string }))
+ }
+ return value as MultiModalContentItem[]
+ }
+ // 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 })
+ return ''
+ }
+
+ private coerceToolCalls(value: unknown): CompatToolCall[] | undefined {
+ if (!Array.isArray(value) || value.length === 0) {
+ return undefined
+ }
+ const calls: CompatToolCall[] = []
+ for (const item of value) {
+ const normalized = this.coerceSingleToolCall(item)
+ if (normalized) {
+ calls.push(normalized)
+ }
+ }
+ return calls.length > 0 ? calls : undefined
+ }
+
+ private coerceSingleToolCall(value: unknown): CompatToolCall | null {
+ if (!value || typeof value !== 'object') {
+ return null
+ }
+ const obj = value as Record<string, unknown>
+ if (obj.type === 'function' && obj.function && typeof obj.function === 'object') {
+ const fn = obj.function as { name: unknown; arguments?: unknown }
+ if (typeof fn.name !== 'string') {
+ return null
+ }
+ return {
+ type: 'function',
+ id: typeof obj.id === 'string' ? obj.id : undefined,
+ function: {
+ name: fn.name,
+ arguments: parseToolArguments(fn.arguments ?? {}),
+ },
+ }
+ }
+ if (typeof obj.name === 'string') {
+ const argsRaw = obj.args ?? obj.arguments ?? {}
+ return {
+ type: 'function',
+ id: typeof obj.id === 'string' ? obj.id : undefined,
+ function: {
+ name: obj.name,
+ arguments:
+ typeof argsRaw === 'string'
+ ? parseToolArguments(argsRaw)
+ : (argsRaw as Record<string, unknown>),
+ },
+ }
+ }
+ return null
+ }
+}
+
+function parseToolArguments(args: string | Record<string, unknown> | unknown): Record<string, unknown> | string {
+ if (typeof args === 'string') {
+ try {
+ return JSON.parse(args)
+ } catch {
+ return args
+ }
+ }
+ if (args && typeof args === 'object') {
+ return args as Record<string, unknown>
+ }
+ return {}
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
new file mode 100644
index 000000000000..9c25a10d43b2
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
@@ -0,0 +1,49 @@
+import { CompatMessage } from '../../../types'
+import { ExistsPredicate, Pattern } from '../ast/predicate'
+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) })
+
+class StubRule extends Rule {
+ constructor(
+ on: Pattern,
+ private readonly messages: CompatMessage[]
+ ) {
+ super(on, [])
+ }
+ produce(): CompatMessage[] {
+ return this.messages
+ }
+}
+
+const recipe = (id: string, priority: number, rule: Rule): Recipe => ({ id, priority, rules: [rule] })
+
+describe('RecipePipeline', () => {
+ it('dispatches to the matching rule and returns its messages', () => {
+ const messages: CompatMessage[] = [{ role: 'user', content: 'hi' }]
+ const pipeline = new RecipePipeline([recipe('only', 100, new StubRule(MATCH_ALL, messages))])
+ expect(pipeline.run({ role: 'user' }, 'user')).toEqual(messages)
+ })
+
+ it('when several recipes match, the lowest priority number wins', () => {
+ const high = recipe('high', 200, new StubRule(MATCH_ALL, [{ role: 'user', content: 'low-priority' }]))
+ const low = recipe('low', 1, new StubRule(MATCH_ALL, [{ role: 'user', content: 'high-priority' }]))
+ const pipeline = new RecipePipeline([high, low])
+ expect(pipeline.run({ role: 'user' }, 'user')).toEqual([{ role: 'user', content: 'high-priority' }])
+ })
+
+ it('returns NO_MATCH when no rule matches', () => {
+ const pipeline = new RecipePipeline([recipe('none', 100, new StubRule(MATCH_NONE, []))])
+ expect(pipeline.run({ role: 'user' }, 'user')).toBe(NO_MATCH)
+ })
+
+ it('throws when recursion exceeds the max delegation depth', () => {
+ const pipeline = new RecipePipeline([recipe('only', 100, new StubRule(MATCH_ALL, []))])
+ expect(() => pipeline.dispatch({ role: 'user' }, 'user', 11)).toThrow(/max depth/)
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
new file mode 100644
index 000000000000..d1b7dbe30735
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
@@ -0,0 +1,63 @@
+import posthog from 'posthog-js'
+
+import { DispatchEngine, DispatchResult, NO_MATCH, Rule } from '../ast/rule'
+import { Scope } from '../scope'
+import { Recipe } from '../spec/recipe'
+import { SlotCoercer } from './coercion'
+
+export { NO_MATCH } from '../ast/rule'
+export type { DispatchResult } from '../ast/rule'
+
+// Insurance against a recipe that delegates to a shape matching itself.
+const MAX_DEPTH = 10
+
+export class RecipePipeline implements DispatchEngine {
+ readonly coercer = new SlotCoercer()
+ private readonly recipes: Recipe[]
+
+ constructor(recipes: Recipe[]) {
+ // Sort a copy: the input is the shared module-level registry array.
+ this.recipes = [...recipes].sort((a, b) => a.priority - b.priority)
+ }
+
+ run(input: unknown, defaultRole: string): DispatchResult {
+ return this.dispatch(input, defaultRole, 0)
+ }
+
+ dispatch(input: unknown, inheritedRole: string, depth: number): DispatchResult {
+ if (depth > MAX_DEPTH) {
+ throw new Error(
+ `RecipeNormalizer: delegation exceeded max depth (${MAX_DEPTH}) — a recipe likely delegates to itself`
+ )
+ }
+ for (const recipe of this.recipes) {
+ for (const rule of recipe.rules) {
+ const result = this.applyRule(rule, input, inheritedRole, depth)
+ if (result !== NO_MATCH) {
+ if (recipe.capture) {
+ posthog.capture(recipe.capture, {
+ message_keys: typeof input === 'object' && input !== null ? Object.keys(input) : [],
+ message_type: typeof input,
+ })
+ }
+ return result
+ }
+ }
+ }
+ return NO_MATCH
+ }
+
+ private applyRule(rule: Rule, input: unknown, inheritedRole: string, depth: number): DispatchResult {
+ if (!rule.on.matches(input)) {
+ return NO_MATCH
+ }
+ const scope = Scope.forNode(input, inheritedRole)
+
+ // Past the match, the rule owns this input and never returns NO_MATCH.
+ // Followups are built first so `produce` can drop an empty primary only
+ // when followups exist (the OTel "responses-only" case).
+ const followups = rule.buildFollowups(scope, this)
+ const primary = rule.produce(scope, this, followups.length > 0, depth)
+ return [...primary, ...followups]
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/scope.test.ts b/products/ai_observability/frontend/normalizer/recipe/scope.test.ts
new file mode 100644
index 000000000000..27ca02b8e793
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/scope.test.ts
@@ -0,0 +1,28 @@
+import { Scope } from './scope'
+
+describe('Scope', () => {
+ describe('forNode', () => {
+ it("resolves the role from the input's role field", () => {
+ expect(Scope.forNode({ role: 'assistant' }, 'user').role).toBe('assistant')
+ })
+
+ it('resolves the role from a recognized type field', () => {
+ // 'human' is a known provider alias for the user role
+ expect(Scope.forNode({ type: 'human' }, 'assistant').role).toBe('user')
+ })
+
+ it('falls back to the inherited role for input without a role', () => {
+ expect(Scope.forNode({ content: 'hi' }, 'assistant').role).toBe('assistant')
+ expect(Scope.forNode('a bare string', 'user').role).toBe('user')
+ })
+ })
+
+ describe('withInput', () => {
+ it('swaps the value but keeps the resolved role', () => {
+ const parent = Scope.forNode({ role: 'assistant', items: [1] }, 'user')
+ const child = parent.withInput({ nested: true })
+ expect(child.input).toEqual({ nested: true })
+ expect(child.role).toBe('assistant')
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/normalizer/recipe/scope.ts b/products/ai_observability/frontend/normalizer/recipe/scope.ts
new file mode 100644
index 000000000000..23b3c01297f6
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/scope.ts
@@ -0,0 +1,35 @@
+// 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'
+
+export class Scope {
+ private constructor(
+ readonly input: unknown,
+ readonly role: string
+ ) {}
+
+ static forNode(input: unknown, inheritedRole: string): Scope {
+ return new Scope(input, resolveRole(input, inheritedRole))
+ }
+
+ // Re-roots on an array element without re-resolving the role — the element is
+ // a value to read fields off, not a new message.
+ withInput(input: unknown): Scope {
+ return new Scope(input, this.role)
+ }
+}
+
+function resolveRole(input: unknown, inheritedRole: string): string {
+ if (!input || typeof input !== 'object') {
+ return inheritedRole
+ }
+ const obj = input as Record<string, unknown>
+ if (typeof obj.role === 'string') {
+ return normalizeRole(obj.role, inheritedRole)
+ }
+ if (typeof obj.type === 'string' && Object.hasOwn(roleMap, obj.type)) {
+ return normalizeRole(obj.type, inheritedRole)
+ }
+ return inheritedRole
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/spec/emitSpec.ts b/products/ai_observability/frontend/normalizer/recipe/spec/emitSpec.ts
new file mode 100644
index 000000000000..deba8f0366b6
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/spec/emitSpec.ts
@@ -0,0 +1,19 @@
+// Inert specs (not self-evaluating AST nodes): `SlotCoercer` interprets `EmitSpec`
+// and `Rule.buildFollowups` interprets `FollowupSpec`.
+
+import type { Expr } from '../ast/expr'
+
+export interface EmitSpec {
+ role?: Expr | RoleTag
+ content?: Expr
+ toolCall?: Expr
+ toolCalls?: Expr
+ toolCallId?: Expr
+ spread?: Expr
+}
+
+// Extra messages produced after the primary: a static one, or one per element
+// of a runtime array (`expand`).
+export type FollowupSpec = { kind: 'static'; emit: EmitSpec } | { kind: 'expand'; from: Expr; each: EmitSpec }
+
+export type RoleTag = 'user' | 'assistant' | 'system' | 'tool' | 'thinking' | 'tool_result'
diff --git a/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts b/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
new file mode 100644
index 000000000000..310040cd7be5
--- /dev/null
+++ b/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
@@ -0,0 +1,11 @@
+import type { Rule } from '../ast/rule'
+
+export interface Recipe {
+ id: string
+ priority: number
+ rules: Rule[]
+ // Fires a PostHog capture on every dispatch match — including recursive
+ // delegation, so only set it on a recipe that is never delegated into (a
+ // terminal catch-all like cajole), or it fires more than once per message.
+ capture?: string
+}
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 4451233a3f72..ee353f843aa1 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -1,5 +1,6 @@
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+import { RecipeNormalizer } from './normalizer'
import { AnthropicInputMessage, CompatMessage, OpenAICompletionMessage } from './types'
import {
asString,
@@ -21,15 +22,29 @@ import {
isToolResult,
isToolStepItem,
looksLikeXml,
- normalizeMessage,
- normalizeMessages,
parseOpenAIToolCalls,
parsePartialJSON,
parseToolArgumentsForDisplay,
sanitizeTraceUrlSearchParams,
} from './utils'
-
-describe('AI observability utils', () => {
+import * as legacy from './utils'
+
+// Parameterized suite: the canonical `normalizeMessage`/`normalizeMessages`
+// in `./utils` stays untouched and is the production code path; the
+// recipe-based wrapper in `./normalizer` exposes the same shape and we run
+// the entire suite against it too. Any divergence shows up as a failure on
+// only one column.
+const recipe = new RecipeNormalizer()
+const IMPLS = [
+ { name: 'legacy', normalizeMessage: legacy.normalizeMessage, normalizeMessages: legacy.normalizeMessages },
+ {
+ name: 'recipe',
+ normalizeMessage: (r: unknown, d: string) => recipe.normalizeMessage(r, d),
+ normalizeMessages: (m: unknown, d: string, t?: unknown) => recipe.normalizeMessages(m, d, t),
+ },
+] as const
+
+describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normalizeMessages }) => {
beforeEach(() => {
console.warn = jest.fn()
})
@@ -1701,6 +1716,10 @@ describe('AI observability utils', () => {
expect(result).toHaveLength(0)
})
+
+ it('returns no messages for undefined input', () => {
+ expect(normalizeMessages(undefined, 'assistant')).toEqual([])
+ })
})
describe('Role normalization', () => {
diff --git a/products/ai_observability/package.json b/products/ai_observability/package.json
index 5d9b12752d09..1c6146bf6c34 100644
--- a/products/ai_observability/package.json
+++ b/products/ai_observability/package.json
@@ -11,7 +11,8 @@
"kea-subscriptions": "catalog:",
"partial-json": "^0.1.7",
"posthog-js": "catalog:",
- "torph": "^0.0.9"
+ "torph": "^0.0.9",
+ "yaml": "catalog:"
},
"devDependencies": {
"kea-test-utils": "catalog:"
diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.py
index bc3e4430cbab..e7b643a5bf81 100644
--- a/tools/hogli-commands/hogli_commands/test_runner.py
+++ b/tools/hogli-commands/hogli_commands/test_runner.py
@@ -368,14 +368,22 @@ def _detect_go_test(file_only: str) -> TestRunConfig:
def _detect_jest_test(file_only: str, file_path: str, node_id: str | None = None) -> TestRunConfig:
- """Detect Jest test configuration by finding the nearest package.json."""
- package_json = _find_nearest(file_only, "package.json")
- if not package_json:
- raise click.UsageError(f"No package.json found for: {file_path}")
-
- pkg_name = _parse_package_json_name(package_json)
- if not pkg_name:
- raise click.UsageError(f"No name field in {package_json.relative_to(REPO_ROOT)}")
+ """Detect Jest test configuration by finding the nearest package.json.
+
+ Tests under products/ are collected by the root @posthog/frontend jest config (its
+ `roots` include ../products), which carries the path aliases and transforms they
+ rely on. The product's own package.json has no jest config, so route them to
+ @posthog/frontend; jest treats the path as a testPathPattern and matches it there.
+ """
+ if file_only.startswith("products/"):
+ pkg_name: str | None = "@posthog/frontend"
+ else:
+ package_json = _find_nearest(file_only, "package.json")
+ if not package_json:
+ raise click.UsageError(f"No package.json found for: {file_path}")
+ pkg_name = _parse_package_json_name(package_json)
+ if not pkg_name:
+ raise click.UsageError(f"No name field in {package_json.relative_to(REPO_ROOT)}")
command = ["pnpm", f"--filter={pkg_name}", "exec", "jest", file_only]
if node_id:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
index 0fa905ab0989..87ebe6d7ec53 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
@@ -75,6 +75,17 @@ class TestDetectTestType:
assert config.test_type == "jest"
assert config.command == ["pnpm", f"--filter={expected_filter}", "exec", "jest", file_path]
+ @parameterized.expand(
+ [
+ "products/ai_observability/frontend/utils.test.ts",
+ "products/llm_analytics/frontend/scenes/Trace.test.tsx",
+ ]
+ )
+ def test_product_frontend_jest_routes_to_frontend(self, file_path: str) -> None:
+ config = detect_test_type(file_path)
+ assert config.test_type == "jest"
+ assert config.command == ["pnpm", "--filter=@posthog/frontend", "exec", "jest", file_path]
+
def test_jest_node_id_adds_test_name_pattern(self) -> None:
config = detect_test_type("frontend/src/lib/utils.test.ts::some test name")
assert config.test_type == "jest"