# @pleach/core (/docs/core)



The trellis the rest of `@pleach/*` grows on. `@pleach/core` is the
agent-runtime substrate built on three load-bearing primitives: a
**four-stage lattice**, a **family-locked model resolution matrix**,
and an **append-only audit ledger**. Every sibling `@pleach/*` package
plugs into it. Every LLM call inside an
agent is classifiable, auditable, and replayable — not one opaque
`streamText`.

Concretely: each call goes through exactly one of four seams
(`synthesizeSeam`, `reasoningSeam`, `utilitySeam`, `converseSeam`),
each seam stamps the call's row in the call ledger with the
declared `callClass`, and each row carries the `(sessionId, turnId,
stageId, seqWithinTurn)` identity tuple — joinable to the turn that
caused it, replayable in registration order. See the
[architecture deep-dive](/docs/architecture) for the walk, or
[Auditable call row](/docs/auditable-call-row) for the row shape.

**Package:** `@pleach/core` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/core](<https://www.getpleach.com/docs/core>) · **License:** FSL-1.1-Apache-2.0

## Install [#install]

<Tabs items="['npm', 'pnpm', 'yarn', 'bun']" groupId="pkg">
  <Tab value="npm">
    ```bash
    npm install @pleach/core
    ```
  </Tab>

  <Tab value="pnpm">
    ```bash
    pnpm add @pleach/core
    ```
  </Tab>

  <Tab value="yarn">
    ```bash
    yarn add @pleach/core
    ```
  </Tab>

  <Tab value="bun">
    ```bash
    bun add @pleach/core
    ```
  </Tab>
</Tabs>

For the end-to-end Next.js walkthrough — env var, route handler,
React surface — see [Getting started](/docs/getting-started). For
the cross-framework matrix (Next App / Pages, Astro, SvelteKit,
Remix, Hono, Bun), see [Install](/docs/install).

## Minimal example [#minimal-example]

```typescript
import { createPleachRuntime, AiSdkProvider } from "@pleach/core";
import { anthropic } from "@ai-sdk/anthropic";

const runtime = createPleachRuntime({
  provider: new AiSdkProvider({ model: anthropic("claude-sonnet-4-6") }),
});
// The model comes from the provider; turns run through it.
```

That's the headless-script / eval-harness shape: import,
construct with a provider, hold a reference. A provider with no
model throws `PleachRuntimeModelRequiredError` at construction. To stream messages against a real
provider, the [`@pleach/core/quickstart`](/docs/getting-started)
subpath ships `createPleachRoute()` (route handler), and
`@pleach/core/quickstart/react` ships `useChat()` + `<ChatBox />`
(React). A provider key is required — there is no
keyless mode (a canned answer proves no value prop; see the
[quickstart](/docs/quickstart)). `npx @pleach/core init` scaffolds the
route behind an `/audit` view.

## What you get [#what-you-get]

A scan of what ships. See the [architecture deep-dive](/docs/architecture)
for the walk.

* **4-stage lattice, lint-enforced.** `anchor-plan → tool-loop ⇄
  synthesize → post-turn`. Out-of-lattice edges fail CI.
* **4 call classes, declared per call.** `utility` / `reasoning` /
  `converse` / `synthesize`. The literal is lint-restricted to seam
  factories.
* **Family + transport lock per session.** Tokenizer, prompt-cache
  key, tool dialect, and refusal pattern freeze at session start. The
  cascade walks in-family rungs only.
* **Singleton synthesize seam.** Exactly one final answer per turn,
  enforced by `SynthesizeSeamHolder` + `TurnSynthesizeCounter`
  (idempotent on `messageId`).
* **`AuditableCall` ledger.** Append-only, ULID-keyed, typed payloads
  for family-lock, fallback-step, cache-breakpoint, provider-cascade,
  plan-generation, synthesis-quality, interrupt-decision,
  tool-selection, and token-cost decisions.
* **Composes under an existing Enterprise contract.** Anthropic
  Workspace or OpenAI Project stays the vendor axis; `@pleach/core`
  stamps `tenantId` on every row so per-axis rollup runs inside the
  contract you already pay for — end customers in a SaaS, or
  employees, teams, and cost centers when used internally. See
  [Migrating from Anthropic Enterprise](/docs/migrating-from-anthropic-enterprise)
  and [Migrating from OpenAI Enterprise](/docs/migrating-from-openai-enterprise).
* **Reactive channels.** `LastValue`, `BinaryOperatorAggregate`,
  `Topic`, `EphemeralValue`, `NamedBarrier`, `DataChannel` with LRU
  eviction. Deterministic reducers; concurrent-write semantics defined
  per kind.
* **BYO-DB storage + checkpointing + sync.** Memory / IndexedDB /
  Supabase adapters; per-channel `checkpoint()` / `restore()` for
  time-travel; version-vector sync detects conflicts at write time.
* **Bounded plugin contract.** Fill tier slots, register stream
  observers, contribute prompts, subscribe to events. Can't rewrite
  the lattice, bypass the synthesize seam, or reach the modelfamily
  matrix directly.

## A node graph, not a single stream [#a-node-graph-not-a-single-stream]

Call the model, run the tool it asks for, call it again: a tool-use
loop is already a little graph. Each step is a **node**, the state
you carry between steps is a **channel**, and every branch that
decides what runs next is an **edge**. Pleach makes that graph
explicit and typed. The default agent graph is dozens of these nodes
across four stages; a raw message loop is one line through it.

<NodeGraphDiagram />

Three things a graph does that a single stream can't:

* **Fan out in parallel, merge deterministically.** `Send[]` runs the
  tool batch or the subagents at once, each with its own copy of the
  state. Their writes merge through an order-independent reducer, so
  the result is identical on every replay. A `NamedBarrier` holds the
  final answer until every branch reports in. See
  [Channels](/docs/channels).
* **Branch on state, not on a hardcoded path.**
  `addConditionalEdges` picks the next node from what the turn
  actually produced — call tools, retry, or finish. The route
  function reads the latest state and returns the target; in a single
  stream that logic tangles into the loop body. See
  [Graph](/docs/graph).
* **Rewind to any past event, not just the last message.**
  Checkpointing is a channel operation: every channel snapshots
  independently, so a session forks at any past event — not just a
  node boundary — and re-runs a different path. A linear stream can
  only truncate to a prior message. See
  [Time-travel & fork](/docs/time-travel).

The graph stays auditable — the row is per model call, not per node.
Pure checks (a garble detector, a repetition guard, a cost rollup)
never touch a model and write nothing; each model call writes one
turn-keyed row tagged with its node's stage, parallel fan-out
included. [Nodes](/docs/nodes) and [Subagents](/docs/subagents) carry
the wiring.

## Advanced wiring — the `@pleach/core/runtime` subpath [#advanced-wiring--the-pleachcoreruntime-subpath]

The 30-second snippet (`import { createPleachRuntime } from "@pleach/core"`)
is the right entry point for tutorials, headless scripts, eval
harnesses, and any consumer that does not need to wire an LLM provider
through an `OrchestratorAdapter`. The runtime returns a substrate
placeholder when no provider is configured.

The moment you wire a real provider — registering an
`OrchestratorAdapter` ctor, an `AuditEmitter`, a `SupabaseFactory&#x60;,
or any of the other app-boot registries — import from the
**`@pleach/core/runtime` subpath** instead:

```typescript
import {
  createPleachRuntime,
  setOrchestratorAdapterCtor,
} from "@pleach/core/runtime";

// At app boot, before any runtime executes a message:
setOrchestratorAdapterCtor(MyOrchestratorAdapter);

const runtime = createPleachRuntime({
  // host.strategies.orchestratorConfig forwards to the adapter
  host: { strategies: { orchestratorConfig: { model: "gpt-4o-mini", /* ... */ } } },
});
```

**Why the split?** `@pleach/core` builds with shared chunks
(`splitting: true` in `tsup.config.ts`). Each `package.json:exports`
entry becomes a small file that imports the code it needs from a shared
chunk. That keeps tree-shaking honest, lets consumers pull only the
subpaths they touch, and isolates the top-level barrel from React /
Anthropic / Supabase peer-resolution surprises.

Shared chunks also mean two subpaths loaded in one process hold the
same class objects. `SessionRuntime` imported from the root and from
`@pleach/core/SessionRuntime` is one class. Earlier builds shipped each
entry as its own self-contained bundle, which duplicated the code and
gave each subpath its own copy of module state. The modules that
carry identity, such as the emit probe, also keep their state in a
process-wide slot, so sharing doesn't depend on the bundler alone.

The `@pleach/core/runtime` subpath co-locates `createPleachRuntime` with every registry setter the
runtime reads, so consumers wiring providers can do so end-to-end
through one import path.

If you only consume `createPleachRuntime`, both forms work. The
subpath is the canonical advanced-wiring path; the top-level is the
tutorial path. `@pleach/recipes` already uses the subpath; the
`npx @pleach/core init` scaffold doesn't need it, because it builds on
`createPleachRoute` from `@pleach/core/quickstart`. See [Host adapter](/docs/host-adapter)
for the full host-injection contract and [Subpath
exports](/docs/subpath-exports) for the canonical surface map.

## What lives in this package today [#what-lives-in-this-package-today]

The root barrel re-exports the most-used types and functions
(`SessionRuntime`, `createPleachRuntime`, channel primitives, the
plugin contract, prompt helpers, the event log writer, the cache
backend factory). Specialized subsystems are reachable through deep
subpath imports — see
[Subpath exports](/docs/subpath-exports) for the canonical
grouping. The substrate covers:

* **Runtime + facets.** `SessionRuntime`, `createPleachRuntime`,
  `TurnOrchestrator`, and \~18 named facet accessors
  (`runtime.sessions`, `runtime.events`, `runtime.spans`,
  `runtime.tenant`, `runtime.graph.{recovery, heuristics, config}`,
  `runtime.plugins`, …). See [Facets](/docs/facets) for the full
  inventory.
* **Persistence.** `MemoryAdapter`, `IndexedDBAdapter`,
  `SupabaseAdapter` storage adapters; matching `MemorySaver`,
  `IndexedDBSaver`, `SupabaseSaver` checkpointers;
  `SyncCoordinator` + version-vector primitives
  (`incrementVersion`, `mergeVectors`, `compareVectors`). See
  [Storage](/docs/storage), [Checkpointing](/docs/checkpointing),
  and [Sync](/docs/sync).
* **Event log.** `EventLogWriter` (fire-and-forget enqueue +
  durable flush), `EventLogClient` (read-side), 10 named
  `GraphProjection<T>` projections (interrupt, subagent, exports,
  artifact, …), and the `chainStep` hash-chain primitive that
  stamps the previous row's hash and the row hash on each row when
  an `EventLogWriter` option enables it. See
  [Event log](/docs/event-log) and
  [Event log projections](/docs/event-log-projections).
* **Audit ledger.** `MemoryProviderDecisionLedger` default
  implementation, typed `AuditableCall` payloads (family-lock,
  fallback-step, cache-breakpoint, provider-cascade,
  plan-generation, synthesis-quality, interrupt-decision,
  tool-selection, token-cost), at `auditRecordVersion = 32`. See
  [Audit ledger](/docs/audit-ledger) and
  [Typed records](/docs/typed-records).
* **Attestation.** `signAttestation` / `verifyAttestation` over
  the canonical row hash + a pluggable keystore (file-backed for
  test, AWS KMS, Vault Transit). Ships via the
  `@pleach/core/attestation` and `@pleach/core/attestation/keyStores`
  subpaths. See [Attestation](/docs/attestation).
* **Cache.** `createMemoryCacheBackend` (default-constructed in
  the `SessionRuntime` constructor) plus the
  `CacheBackend` interface for swapping in Redis / Upstash. Threads
  through the four seam factories. See [Cache](/docs/cache).
* **Safety.** `SafetyPolicyRegistry` (per-runtime, opt-in via
  `enabledSafetyPolicies`) + `composeSafetyContent` wired into the
  prompt resolver. See [Safety](/docs/safety).
* **Scrubbers.** `Scrubber` interface, `DefaultScrubberChain`,
  and the per-event-type allowlist of fields scrubbers can
  redact. See
  [Scrubbers](/docs/scrubbers).
* **Prompts + builder.** `PromptContributionRegistry` and
  `resolvePromptContributions` for the contribution contract;
  friendly-API helpers (`appendPrompt`, `prependPersona`,
  `replaceCore`, `scopedPrompt`, `gatedPrompt`, `createPlugin`), with
  `core.*` slots replaced from runtime-aware contributions only;
  44 universal core fragment templates; the
  `@pleach/core/prompt-builder` shell with `composeBudgetedPrompt`
  and the per-section authoring kit. See
  [Prompts](/docs/prompts) and [Prompt builder](/docs/prompt-builder).
* **Plugin contract.** 71 `contributeX` hooks on `HarnessPlugin`
  (prompts, runtime-aware prompts, stream observers, safety
  policies, fabrication detectors, tools, intent-tool map,
  tool-coupling hints, continuation policy, retry policy, …) plus
  the `definePleachPlugin` discoverable entry point. See
  [Plugin contract](/docs/plugin-contract).
* **OTel + lineage + fingerprint.** The observability triplet:
  `runtime.spans` for OTel-style span introspection
  (`inFlightCount`, `isShutdown`, `snapshot`); `LineageTracker` for
  cross-session parent/child/forked relationships; the
  pure-function `fingerprint` module that hashes prepared LLM
  inputs platform-uniformly (the determinism property
  `@pleach/eval` and `@pleach/replay` build on). See
  [Observability](/docs/observability), [Lineage](/docs/lineage),
  and [Fingerprint](/docs/fingerprint).
* **Quickstart.** `createPleachRoute` + the React quickstart
  surface (`useChat`, `<ChatBox/>`) at the
  `@pleach/core/quickstart` subpath for one-line bootstraps.
* **Adapters + integration.** Subpaths for query (`/query`),
  inspector (`/inspector`), MCP (`/mcp` via `createHarnessMCPServer`),
  mock executors (`/mock`), and finalization helpers (`/finalization`).

## Language-agnostic contract [#language-agnostic-contract]

The runtime contract — sessions, checkpoints, storage, tools, sync,
SSE wire — is language-agnostic by design. The TypeScript
distribution in `@pleach/core` is the reference implementation, in
production today. A Go implementation is planned; the wire
contract already works in a Go reference consumer, which reads the
SSE frames and checkpoint envelopes (see
[Language-agnostic contract](/docs/language-agnostic-contract#how-the-contract-stays-honest)
for what keeps the wire honest today and what waits on the Go
implementation).

If a claim in these docs only holds in JavaScript, that's a
documentation bug — open an issue against
[pleachhq/core](https://www.getpleach.com/docs/core).

## Related SKUs [#related-skus]

Every sibling `@pleach/*` package plugs into `@pleach/core`. The
ones consumers most often pair with it:

* [`@pleach/recipes`](/docs/recipes-pleach-recipes) — use-case-targeted
  factories (chatbot, RAG, compliant chatbot, enterprise agent,
  swarm) over the core runtime. The shortest path past the
  quickstart.
* [`@pleach/compliance`](/docs/compliance) — scrubbers + CI audit
  gates that wrap core's `EventLogWriter` at the persistence
  boundary. Adopt when audit rows are evidence.
* [`@pleach/gateway`](/docs/gateway) — multi-tenant routing client
  over core's family-locked matrix. Per-tenant scoping, BYOK
  fingerprinting, per-call cost events.
* [`@pleach/replay`](/docs/replay) — event-granular replay via the
  canonical `runtime.events.iterate/fold` surface. Deterministic
  fork-from-prefix + hash-chain verification.
* [`@pleach/eval`](/docs/eval) — `EvalSuite` + four scorers; takes a
  `ReplayClient` through constructor DI.
* [`@pleach/observe`](/docs/observability) — OpenTelemetry / Datadog
  / Honeycomb wiring over core's two write streams.
* [`@pleach/react`](/docs/react) — primitive hooks + `<ChatBox />`
  surface. Either the lower-level `@pleach/react` or the bundled
  `@pleach/core/quickstart` exports.
* [`@pleach/tools`](/docs/tools) — `defineTool` contract +
  `@pleach/base-tools` for the batteries-included starter set.

For the full SKU map see [Which SKU do I need?](/docs/which-sku).

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Getting started" href="/docs/getting-started" description="Install, wire a SessionRuntime, and stream your first message." />

  <Card title="Architecture" href="/docs/architecture" description="The six pieces of the substrate — stage lattice, call classes, seams, family-lock, audit ledger, event log." />

  <Card title="Graph" href="/docs/graph" description="Declarative topology — StateGraph, Annotation, edges, Send, the lattice gate." />

  <Card title="Nodes" href="/docs/nodes" description="Node shape, metadata, the default catalogue, authoring a custom node." />

  <Card title="Call classes" href="/docs/call-classes" description="The four-class taxonomy, per-turn allotments, the callClass lint." />

  <Card title="Seams" href="/docs/seams" description="The per-callclass entry points, the singleton synthesize seam, the observer ladder." />

  <Card title="Family-locked routing" href="/docs/family-lock" description="What locks at session start, the family-strict cascade, models no family derives from." />

  <Card title="The AuditableCall row" href="/docs/auditable-call-row" description="Per-call audit row shape — what's in it and what you can join it against." />
</Cards>
