Skip to content
pleach
Build

@pleach/observe

Destination-flexible observability SDK for AI agents. Drop it into an existing agent loop (LangChain, CrewAI, OpenAI SDK, hand-rolled) and write typed audit rows to Postgres, Supabase, your OpenTelemetry collector, or an in-memory buffer — your storage, your control plane.

@pleach/observe writes one audit row for each call you hand it, to a backend you choose: Postgres, Supabase, your OpenTelemetry collector, or an in-memory buffer. It's a small SDK (init, recordCall, subagent, and four destination factories) that sits in front of the agent loop you already run, whether that's the Vercel AI SDK, LangChain, the Anthropic or OpenAI SDK, or an in-house orchestrator. That makes it the brownfield entry point to the Pleach audit ledger.

The ObserveRow you hand it carries a subset of the runtime row's fields: @pleach/core's AuditableCall record plus the TokenCostRecord field set. Pointed at Postgres (or any ledger you pass), it writes a chained row to the same table and chain the runtime uses; OTel and in-memory destinations get telemetry. The row carries the tenant, the cost and the leaf sub-agent. Tags and the full sub-agent path are copied only with the ledgerPayload option. A ledger destination refuses sampling below 1.0, so the audit row is never sampled.

When a row becomes an AuditableCall, reasoningTokensReported is true only for a reasoning-token count that is a non-negative safe integer. Any other value is recorded as an unreported 0, which reads as unknown.

Package@pleach/observe· not on npm yetSourcegithub.com/pleachhq/observeLicenseFSL-1.1-Apache-2.0

Not on npm yet

@pleach/observe isn't on npm yet. Some names are reserved with 0.0.1 placeholders. Each package's first real release ships under FSL-1.1-Apache-2.0. The commands on this page describe the install once it lands. Packages tracks each package's status.

When @pleach/observe fits

  • Do you already have an agent loop you don't want to rewrite? observe is the brownfield hook. Call init once and recordCall after each LLM call you already make.
  • Are you starting fresh, or do you need replay from the record, family-locked routing, reactive channels, or checkpoint/restore? Use @pleach/core. Those are runtime properties, not row properties, and the SDK doesn't carry them.

Adoption paths documents the two as a pair.

Install

npm install @pleach/observe

@pleach/core is a peerDependency (>=0.1.0 <1). The Postgres destination writes through core's PostgresProviderDecisionLedger (@pleach/core/audit), and rate-based cost estimates use priceCallUsd (@pleach/core/pricing).

No @opentelemetry/* runtime dependencies. The OTel destination hands your callback a GenAI-semantic-convention envelope, and your callback ships it to the exporter you already configured.

No transport peer dependencies for Postgres or Supabase. Pass your own pg.Pool / pg.Client or SupabaseClient.

Quickstart — paste and run

The Memory destination has no external dependencies. Use it for tests, local development, and first-look demos.

import { init, recordCall } from "@pleach/observe";
import { memory } from "@pleach/observe/destinations";

const dest = memory();
init({ destination: dest });

recordCall({
  turnId: "turn_001",
  providerId: "anthropic",
  callClass: "synthesize",
  family: "anthropic",
  model: "claude-opus-4-7",
  inputTokens: 1000,
  outputTokens: 250,
  costUSD: 0.0125,
  startedAt: Date.now(),
  completedAt: Date.now() + 1200,
});

console.log(dest.rows.length); // 1
console.log(dest.rows[0].model); // "claude-opus-4-7"

That's a one-shot write: one init, one recordCall. Swap memory() for another destination below to ship the row elsewhere.

The module-level API

Call init once per process. The other three entry points use the singleton it creates.

init(config: ObserveConfig): void
recordCall(row: ObserveRow): void
getRecorder(): ObserveRecorder    // throws if called before init()
subagent(name: string): ObserveRecorder & { run: <T>(cb: () => Promise<T>) => Promise<T> }

init picks the destination. A second init call throws rather than replacing the live recorder and orphaning in-flight writes. Tests can re-initialize with the __resetForTesting hook exported from the root.

recordCall writes one ObserveRow to the destination, synchronously (memory) or asynchronously (Postgres, Supabase, OTel batching).

getRecorder returns the active recorder so you can pass it across modules. It throws before init; it never returns undefined.

subagent(name) is covered under Sub-agent attribution.

ObserveConfig

interface ObserveConfig {
  readonly destination: ObserveDestination;
  readonly sampling?: { readonly rate: number };       // 0..1, per turnId
  readonly redactor?: (row: ObserveRow) => ObserveRow; // pure, sync, pre-write
  readonly redact?: PIIRedactionConfig;                // substrate-side policy
  readonly throwOnDestinationError?: boolean;          // default false (silent-swallow)
}
  • sampling.rate is decided per turnId, so all recordCall invocations in one turn ship together or drop together. 0 drops everything; 1 (the default) keeps everything. init throws on NaN, non-finite, < 0, or > 1.
  • redactor is your PII hook, applied to every row before destination.write. It must be pure. If it throws, the SDK warns with [Observe:redactor-threw] and never writes the raw row. A telemetry destination drops the row. A ledger destination writes a withheld row instead (ids, model, tokens, cost, status and timing, tagged observe.withheld: redactor-error), so the chain has no gap.
  • redact is the built-in policy (see PII redaction), applied automatically per row.
  • throwOnDestinationError opts out of the v0.x silent-swallow default. When true, recordCall re-throws synchronous destination errors and leaves async rejections unhandled for process-level handlers.

The ObserveRow shape

Consumers of the AuditableCall schema (@pleach/eval, @pleach/compliance, dashboards) read the fields the SDK carries; the rest stay undefined. See the intro for what each destination writes.

interface ObserveRow {
  readonly turnId:        string;       // ULID
  readonly providerId:    ProviderFamily; // "anthropic" | "openai" | "google" | "deepseek" | …
  readonly callClass:     CallClass;    // "synthesize" | "reasoning" | "utility" | "converse"
  readonly family:        ProviderFamily;
  readonly model:         string;
  readonly inputTokens:   number;
  readonly outputTokens:  number;
  readonly costUSD?:      number;       // present only when the cost is known
  readonly costOmitted?:  ObserveCostOmitted; // why costUSD is absent
  readonly startedAt:     number;       // epoch millis
  readonly completedAt:   number;       // epoch millis
  readonly subagent?:     string;       // set automatically by subagent(...)
  readonly subagentPath?: readonly string[]; // path when nested
  readonly fingerprint?:  string;       // `fp_v1:`-prefixed, opt-in
  readonly tags?:         Record<string, string>;
  readonly byokFailureChain?: readonly {
    readonly provider:   ProviderFamily;
    readonly keyHint:    string;        // last 4 chars, never the full key
    readonly statusCode: number;        // -1 for transport-level failures
    readonly reason:     string;
  }[];
}

The host populates byokFailureChain when a byok-* transport call fails and the family-strict cascade moves to the next provider, one entry per BYOK provider tried. It carries a four-character keyHint, never the key.

The row leaves undefined the full RoutingDecision, the cascade walk history, attestation hashes, the priceSnapshot on a priced row, and the optional toolName. Use @pleach/core if you need them. The row's fp_v1: fingerprint covers {family, model, callClass, input}, narrower than core's, and this SDK computes it.

Unknown cost: costOmitted

An unknown cost is never reported as $0. When a row's cost isn't known, costUSD is absent and costOmitted says why. The two are never set together. ObserveCostOmitted is a closed set:

costOmittedMeaning
unpricedNo rate is known for the model, the call reported no usage, or a token class it used has no rate: a cache read, or a write whose lifetime split or rate is unknown.
served-model-mismatchThe upstream served a different model than requested, and the known rates are the requested model's.
priced-per-callA decision row whose per-call row carries the cost. Left out of sums so the call counts once.
owned-per-callA decision row whose per-call row owns the cost but is itself unpriced. Left out of the unknown count so the call counts once.
not-a-callThe row records an event, not a model call (a gateway cost alert, a plan, an interrupt, a delivery outcome).

To read the rows:

  • Total spend is SUM(costUSD) over rows that have it. Never count a row without costUSD as free.
  • Calls of unknown cost are the unpriced and served-model-mismatch rows. Report that count beside the total so a partial figure never reads as complete.
  • priced-per-call, owned-per-call and not-a-call rows belong in neither figure.

A row is never not-a-call just because it has no token usage. A call whose usage never arrived, such as a sub-agent call, is unpriced.

usage-unreported reads as unpriced. Core marks a billed call whose provider reported no usage, one token count, or 0 for both as usage-unreported. Observe projects that as unpriced (in runtimeEventToObserveRow, which observeSink uses, and in defaultAuditableCallToObserveRow, whose cost half is exported as auditableCallCostFields), so those calls land in the unknown-cost count, never in the total as $0. The main agentic turn's model.called event is always unpriced; its per-call audit row carries the price.

Cached prompt tokens. A per-call row prices cache reads at the cache-read rate when the model has one, and cache writes at the write rate for each write's lifetime. It is unpriced only when a rate is missing for a token class the call used: cached tokens with no cache-read rate, or a write whose lifetime split or rate is unknown. In that case neither the full input rate nor $0 is the real price. The CostEvent path that a gateway spend ceiling sums prices cached tokens at the full input rate instead, so an unverified discount never lets a run pass a limit it crossed. That figure is an estimate, not an upper bound: cache-write tokens, which some providers bill above the input rate, aren't added by the ceiling.

Each destination stores the omission differently; see the four destinations.

tags is the open extension hook. Beyond the cost.* namespace (see Cost attribution), the SDK passes it to the destination as-is. Conventional keys are env, release and user.tier.

The four destinations

init({ destination }) accepts a factory from the ./destinations subpath.

DestinationFactoryUse case
Memorymemory({ maxRows? })Tests, local dev, demos
Postgrespostgres({ pgClient, tenantId, sessionId }) (chained row; rowShape: "telemetry" opts out) or postgres({ ledger, tenantId, sessionId })Self-hosted production
Supabasesupabase({ ledger, tenantId, sessionId }) (chained row) or supabase({ client, rowShape: "telemetry" })Managed Postgres, quick start
OpenTelemetryotel({ exportSpan, serviceName? }) or otel({ export, serviceName? })Existing OTel collector, Honeycomb, Datadog, Grafana

Unknown cost. The Postgres and Supabase telemetry table stores 0 for an unknown cost plus a pleach.cost_omitted tag with the reason, and query() reads the pair back as an omitted cost. A SQL query that sums the cost column directly must exclude rows with that tag. The tag key is reserved: your own tag of that name is dropped. The otel destination sets pleach.observe.cost_usd only for a finite, non-negative cost, and pleach.observe.cost_omitted otherwise.

Postgres

import { Pool } from "pg";
import { init, recordCall } from "@pleach/observe";
import { postgres } from "@pleach/observe/destinations";

const pgClient = new Pool({ connectionString: process.env.DATABASE_URL });
init({
  destination: postgres({ pgClient, rowShape: "telemetry", tableName: "your_calls_table" }),
});

recordCall({
  turnId: "turn_001",
  providerId: "openai",
  callClass: "synthesize",
  family: "openai",
  model: "gpt-5",
  inputTokens: 850,
  outputTokens: 320,
  costUSD: 0.0091,
  startedAt: Date.now() - 900,
  completedAt: Date.now(),
});

Postgres reuses your own pg-shaped client; the SDK adds no pg dependency. This example writes the telemetry row, so your table needs the columns the INSERT targets (the package's docs/postgres.md has the CREATE TABLE). Without rowShape: "telemetry", postgres({ pgClient, tenantId, sessionId }) writes the runtime's call table and chain, and passing tableName throws. The ledger mode takes a ProviderDecisionLedger adapter from @pleach/core.

Ledger mode requires tenantId and sessionId. postgres({ ledger }) and supabase({ ledger }) throw at construction without them; there is no default tenant or session. A row's cost.tenant_id and sessionId tags override them per row. With core's PostgresProviderDecisionLedger, the session must be a real runtime session id.

import { PostgresProviderDecisionLedger } from "@pleach/core/audit";
import { postgres } from "@pleach/observe/destinations";

init({
  destination: postgres({
    ledger: new PostgresProviderDecisionLedger({ client: pgClient }),
    tenantId: "acme-corp",
    sessionId, // an existing runtime session id
  }),
});

Postgres is the production default. In the chained shape each row carries the destination's tenantId (or the row's cost.tenant_id tag), so cost joins to a billing schema with one group-by. The telemetry shape keeps the tenant only in tags.

Supabase

import { createClient } from "@supabase/supabase-js";
import { init, recordCall } from "@pleach/observe";
import { supabase } from "@pleach/observe/destinations";

const client = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_KEY!);
init({
  destination: supabase({ client, tableName: "your_calls_table", rowShape: "telemetry" }),
});

recordCall({
  turnId: "turn_supabase_001",
  providerId: "google",
  callClass: "reasoning",
  family: "google",
  model: "gemini-2.5-pro",
  inputTokens: 2100,
  outputTokens: 480,
  costUSD: 0.0185,
  startedAt: Date.now() - 1450,
  completedAt: Date.now(),
});

Pass your own SupabaseClient; RLS, auth and table schema stay yours. The package's docs/supabase.md has an RLS template policy. A plain supabase({ client }) writes telemetry and needs rowShape: "telemetry"; the chained row comes only through supabase({ ledger, tenantId, sessionId }).

Writes go through PostgREST. Above about 100 rows/s sustained, switch to the Postgres destination.

OpenTelemetry

import { init, recordCall } from "@pleach/observe";
import { otel } from "@pleach/observe/destinations";

init({
  destination: otel({
    serviceName: "my-agent",
    exportSpan: (envelope) => {
      // Hand `envelope` to your @opentelemetry/sdk-trace-base exporter.
      // SDK builds attributes per OTel GenAI semantic conventions.
      myExporter.export(envelope);
    },
  }),
});

recordCall({
  turnId: "turn_otel_001",
  providerId: "anthropic",
  callClass: "synthesize",
  family: "anthropic",
  model: "claude-sonnet-4-5",
  inputTokens: 1500,
  outputTokens: 600,
  costUSD: 0.0228,
  startedAt: Date.now() - 1700,
  completedAt: Date.now(),
});

No `@opentelemetry/*` runtime dependencies

The SDK builds the GenAI-semantic-convention envelope and hands it to your callback. The span is named <family>.<callClass> (for example anthropic.synthesize) with the OTel GenAI attributes gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens and gen_ai.operation.name, plus pleach.observe.turn_id, pleach.observe.provider_id, pleach.observe.cost_usd or pleach.observe.cost_omitted, and pleach.observe.tag.*. You own the OTel SDK: build a BatchSpanProcessor against your OTLP exporter and forward the envelope from exportSpan.

Two callback modes ship:

  • exportSpan(envelope) — the SDK builds the GenAI envelope for you.
  • export(row) — pass-through; you get the raw ObserveRow and map it yourself.

This is the "I already have observability" destination: rows land in your existing backend through your own OTel configuration.

Memory

import { init, recordCall } from "@pleach/observe";
import { memory } from "@pleach/observe/destinations";

const sink = memory();
init({ destination: sink });

// later, in a test:
expect(sink.rows).toHaveLength(2);
expect(sink.rows[0].costUSD).toBeCloseTo(0.0143, 4);
sink.clear(); // explicit reset between tests

An in-process buffer for unit tests and as a @pleach/eval fixture. It isn't suitable for production. init doesn't drain it; your test owns its lifecycle.

Sub-agent attribution

subagent(name) returns a scoped recorder that attributes calls to a named planner, critic, or tool-runner. Pick the mode that matches your loop.

Grab the recorder once and call .recordCall(...) directly. Use this when you already thread per-agent identity through your code.

import { init, subagent } from "@pleach/observe";
import { memory } from "@pleach/observe/destinations";

init({ destination: memory() });
const planner = subagent("planner");
const critic = subagent("critic");

planner.recordCall({
  turnId: "t1",
  providerId: "anthropic",
  callClass: "reasoning",
  family: "anthropic",
  model: "claude-opus-4-7",
  inputTokens: 1200,
  outputTokens: 320,
  costUSD: 0.014,
  startedAt: Date.now() - 900,
  completedAt: Date.now(),
});

critic.recordCall({
  turnId: "t1",
  providerId: "openai",
  callClass: "utility",
  family: "openai",
  model: "gpt-5",
  inputTokens: 450,
  outputTokens: 80,
  costUSD: 0.003,
  startedAt: Date.now() - 350,
  completedAt: Date.now(),
});

Each row is automatically tagged subagent: "planner" or subagent: "critic".

Wrap the sub-agent in .run(async () => { ... }) and any recordCall inside inherits a subagentPath. Use this for nested loops where you don't want to thread the name through every call site.

import { init, recordCall, subagent } from "@pleach/observe";
import { memory } from "@pleach/observe/destinations";

init({ destination: memory() });

await subagent("planner").run(async () => {
  await subagent("executor").run(async () => {
    // Row written here is tagged subagent: "executor",
    // subagentPath: ["planner", "executor"].
    recordCall({
      turnId: "t1",
      providerId: "anthropic",
      callClass: "synthesize",
      family: "anthropic",
      model: "claude-opus-4-7",
      inputTokens: 900,
      outputTokens: 220,
      costUSD: 0.011,
      startedAt: Date.now() - 800,
      completedAt: Date.now(),
    });
  });
});

This mode uses AsyncLocalStorage. On runtimes without it, only closure-scope works.

Reading rows back

query(filter) ships on the Memory destination, the Postgres and Supabase telemetry shapes, and the Postgres chained shape when you pass pgClient. A destination built over an injected ledger has no query, and OTel is write-only.

import { getRecorder } from "@pleach/observe"

const rows = await getRecorder().query({
  fingerprint: "fp_v1:…",          // exact match; needs persistFingerprint on Postgres/Supabase
  since: new Date(Date.now() - 7 * 86_400_000),
  until: new Date(),
  limit: 100,
})

Every field is optional. An empty filter means all rows, and a destination may cap that (Memory caps at 1,000). Bounds take epoch milliseconds or a Date.

  • The window is half-open, [since, until), so adjacent windows don't double-count a boundary row.
  • Both bounds compare against startedAt, not completedAt, as in @pleach/core's ProviderDecisionLedger.query. A long call belongs to the window it started in.

A destination without query throws QueryNotSupportedError instead of returning [], because an empty array looks like "no rows matched". Catch it to fall back to your own read path.

Persisting the fingerprint column

ObserveRow.fingerprint is a stable fp_v1:-prefixed hash of {family, model, callClass, input}, computed by computeObserveFingerprint(input) or recorder.fingerprint(input).

The Postgres and Supabase telemetry shapes write it to a column only with persistFingerprint: true; the chained shape rejects the option. It's off by default because the column needs an index to be worth querying, and adding one to an existing table is your migration.

Knowing whether the recorder is live

Before init(), recordCall drops the row and warns once, init later reports how many rows were dropped, and getRecorder() throws. isRecorderInitialized() tells you whether init has run.

Cost attribution

costAttribution fills the cost.* namespace on ObserveRow.tags for cross-tenant aggregation. isCostAttributionKey(key) and extractCostAttributionTags(tags) read it back.

import { recordCall, costAttribution } from "@pleach/observe";

recordCall({
  turnId: "t1",
  providerId: "anthropic",
  callClass: "synthesize",
  family: "anthropic",
  model: "claude-opus-4-7",
  inputTokens: 900,
  outputTokens: 220,
  costUSD: 0.011,
  startedAt: Date.now() - 800,
  completedAt: Date.now(),
  tags: costAttribution({
    workflowId: "lead-enrichment",
    tenantId: "acme-corp",
    featureId: "draft-email",
  }),
});

Three canonical keys lock at v1.0.0: cost.workflow_id, cost.tenant_id, cost.feature_id. Other cost.* keys are reserved; use tags directly for your own dimensions.

Optional PII redaction

Opt in to built-in PII scrubbing with the matcher catalog.

import { init } from "@pleach/observe";
import { memory } from "@pleach/observe/destinations";
import { BUILT_IN_MATCHERS, DEFAULT_REPLACEMENT } from "@pleach/observe";

init({
  destination: memory(),
  redact: {
    fields: ["subagent", "tags.user_email", "tags.user_phone"],
    matchers: [
      ...BUILT_IN_MATCHERS, // email + phone + SSN
      // ...your custom matchers
    ],
    replacement: DEFAULT_REPLACEMENT, // "[REDACTED]"
  },
});

Public surface for the redaction config:

ExportShapeWhen to use
PIIRedactionConfigtypeTypes the redact: arg to init.
BUILT_IN_MATCHERSreadonly Matcher[]Spread alongside custom matchers.
DEFAULT_REPLACEMENTstringReplacement token ("[REDACTED]"). Override per matcher.
APPLY_REDACTION_POLICY_IDstringPolicy id ("observe.applyRedaction.v1"). applyRedaction stamps it in the redactionPolicyId tag (APPLY_REDACTION_POLICY_TAG_KEY) on rows it scrubs; OTel shows pleach.observe.tag.redactionPolicyId.

Pair with `@pleach/compliance` for GDPR / HIPAA

For GDPR or HIPAA redaction policy management (DSAR flows, consent revocation, regional residency), pair @pleach/observe with @pleach/compliance. The @pleach/recipes compliantChatbot factory wires both. @pleach/observe doesn't auto-apply any compliance policy; redactor and redact stay yours.

The ObserveDestination interface

You can write your own destination:

interface ObserveDestination {
  write(row: ObserveRow): Promise<void> | void;
  flush?(): Promise<void>;
  query?(filter: ObserveQueryFilter): Promise<readonly ObserveRow[]>;
  readonly writesAuditLedger?: boolean;
  reportAlreadyAudited?(): void;
  reportDroppedBeforeInit?(count: number): void;
}

write takes one row and may be sync or async. Implement flush if you buffer, and drain it from a shutdown hook. query is the optional read side (see Reading rows back). writesAuditLedger marks a destination that writes the audit ledger: the SDK then refuses sampling below 1.0 and writes a withheld row when a redactor throws.

For a Kafka topic or a Cloudflare Queues binding, implement write and pass the result to init. There's no registration step.

API surface — what to import from where

Twelve entry points, the root plus eleven subpaths:

SubpathPublic exports
@pleach/observeinit, recordCall, getRecorder, subagent, costAttribution, sampling + redaction surface, fingerprint helper
@pleach/observe/destinationsmemory(), postgres(), supabase(), otel() + their option types
@pleach/observe/typesObserveRow, ObserveDestination, ObserveConfig, ObserveRecorder, CallClass, ProviderFamily
@pleach/observe/integrations/ledger-decoratorwithObserveEmit, defaultAuditableCallToObserveRow — decorate an @pleach/core audit emitter so every AuditableCall also writes an ObserveRow
@pleach/observe/integrations/cost-emitcreateCostEmitter, emitCostFromProviderResponse — derive a cost row from a raw provider response
@pleach/observe/integrations/cost-event-emitprojectGatewayCostEventToObserveRow, emitGatewayCostEvent — project @pleach/gateway cost events (breach/warn/defer) into observe rows
@pleach/observe/integrations/ai-sdkcreateObserveMiddleware — AI SDK language-model middleware, one row per model attempt
@pleach/observe/integrations/langchaincreateObserveCallbackHandler — LangChain callback handler, one row per invocation
@pleach/observe/integrations/openai-agentscreateObserveTracingProcessor — OpenAI Agents tracing processor, one row per generation or response span
@pleach/observe/integrations/mastraobserveMastraModel — wraps a Mastra model, one row per doGenerate / doStream call
@pleach/observe/resource-metermeasureResources — per-scope CPU, memory, event-loop and fetch meter
@pleach/observe/testingrunObserveDestinationConformance, assertObserveDestinationConformance + ConformanceCheck, ConformanceReport, ConformanceOptions — the conformance harness for destination authors

MemoryDestination (with .rows and .clear()), PostgresDestination and SupabaseDestination (with .mode), and OtelSpanEnvelope are exported from their destination modules, not yet from ./destinations.

Writing your own destination

@pleach/observe/testing ships the conformance harness the built-in destinations pass.

import { assertObserveDestinationConformance } from "@pleach/observe/testing"

await assertObserveDestinationConformance(() => myDestination())

assert* throws on the first failed check. runObserveDestinationConformance returns a ConformanceReport with every failure.

Run it in your own tests. The ObserveDestination type constrains shape; only the harness checks behavior.

Wiring the integration emitters

Typical wiring for the integration subpaths:

  • withObserveEmit(inner, opts?) wraps an existing ProviderDecisionLedger so each recordCall(call) also writes an ObserveRow. The observe write is fire-and-forget and skips silently until init() has run. It also skips when the installed destination already writes the audit ledger, so a call isn't mirrored into the chain twice. Pass { adapter } to override the default projection.
  • createCostEmitter({ writer, familyDeriver?, callClassResolver? }) returns an emitter whose emit(input) derives a cost row from a raw provider response and hands it to your writer. Don't await emit. It's skipped when messageId is empty or family / callClass can't be resolved.
  • projectGatewayCostEventToObserveRow(event, opts?) maps a @pleach/gateway cost event (breach, warn, defer) onto an ObserveRow without writing it. tags["gateway.cost.kind"] carries the event kind; you forward the row to a destination.
import { withObserveEmit } from "@pleach/observe/integrations/ledger-decorator";

// Fan every audit write out to an observe row too.
const ledger = withObserveEmit(existingLedger);

Sampling gate

shouldSample(turnId, rate) is the per-turn write gate, so every recordCall in a turn agrees. rate >= 1 always samples; rate <= 0 never does. The recorder calls it, and you can too. validateSamplingConfig({ rate }) is the init()-time check; it throws on NaN, non-finite, or out-of-range rate.

Where your hook sees each attempt, per runtime

Observe writes a row per call you hand it, so where you place the hook decides whether retries show up:

RuntimeIntegration exportRows
AI SDKcreateObserveMiddleware (@pleach/observe/integrations/ai-sdk)One per attempt: middleware sees every attempt.
LangChain / LangGraphcreateObserveCallbackHandler (@pleach/observe/integrations/langchain)One per invocation; retries inside it are hidden.
OpenAI Agents SDKcreateObserveTracingProcessor (@pleach/observe/integrations/openai-agents)One per model span: a retry the runner makes (modelSettings.retry) is a row per attempt, while a retry inside the OpenAI client stays invisible. With traceIncludeSensitiveData: false, a span with no model id is written as model unknown, and when one turn holds more than one model call the turn's tokens can't be split, so those rows carry none (tagged unsplit-turn).
MastraobserveMastraModel (@pleach/observe/integrations/mastra)One per doGenerate/doStream, and only for model slots you wrap (memory, titles, processors, scorers each need it).

What is hookable, what is not

Five primitives are hookable from a brownfield agent loop:

PrimitiveHookable from SDK
AuditableCall row constructionYes — recordCall(row).
turnId propagationYes — set on the row directly.
Sub-agent attributionYes — subagent(name) (closure + ALS-scope).
Fingerprint computeYes — computeObserveFingerprint re-export.
PII redactionYes — redactor callback or redact: substrate policy.

Five things are not hookable. They're properties of the runtime, not of the row:

  • Family-locked routing. When a model fails, the cascade retries within the session's family and never silently widens, including for models outside the routing matrix. The old cross-family fallback is opt-in. This lives in @pleach/core's routing decision; the SDK observes calls, it doesn't make them.
  • Reactive channels. Subscription, fan-out, and back-pressure are @pleach/core-internal.
  • Replay from the record. Replay re-serves a turn's recorded responses instead of calling the model. replayRecordedTurn (from @pleach/replay/recorded) names the first request that drifted. Steps the runtime doesn't fingerprint yet (decision, synthesize) are marked blind, so a turn on a stock runtime is never reported matched. It needs the event log; the SDK writes a subset of fields, not the full log.
  • Checkpoint / restore. @pleach/core/checkpointing is the surface; the SDK has no session state.
  • Time-travel. @pleach/replay forks from the canonical event log, which the SDK doesn't produce.

If you need the engine, adopt @pleach/core. If you need the row, use the SDK and write wherever you like.

Composing with @pleach/core

If you run both, the SDK for legacy paths and the runtime for new ones:

  • runtime.observe.record(row) forwards a row to the destination init installed, and does nothing when none is installed. The runtime's own audit rows come from its own ledger, not the SDK.
  • The SDK's fp_v1: fingerprint is narrower than core's, so the two values don't match.
  • subagent("planner").recordCall(...) rows carry the same subagent field as runtime-written rows.

Existing rows keep their ids and join to runtime-written rows. The adoption paths page walks the migration.

License + versioning

Licensed under FSL-1.1-Apache-2.0, like the rest of the @pleach/* substrate set. It's source-available and free to use in production, and each release converts to Apache 2.0 two years after it ships. See Versioning for release cadence.

The 0.x line is pre-1.0, so pin the exact 0.x.y version you adopt. The 0.0.x → 0.1.0 and 0.1.x → 1.0.0 jumps are non-caretable, and ^0.1.0 won't pick up later 0.x releases.

What's in the 0.x line

  • Sampling configuration (init({ sampling: { rate: 0.1 } })).
  • Buyer-supplied redactor hook.
  • Substrate-side PII redaction (init({ redact: { fields, matchers } })).
  • Read-side query(filter) on Memory, Postgres and Supabase (OTel stays write-only).

The pleachHosted factory on @pleach/observe/destinations is a scaffold and isn't available yet: it throws HostedBackendNotYetGA on first write. Use a Postgres, Supabase, OTel or memory destination.

Where to go next