# Getting started (/docs/getting-started)



Pleach is a free, fair-source agent runtime: every LLM call your
agent makes writes one typed row to a database you own, giving you
per-customer cost, SQL-queryable compliance, and deterministic
replay. `@pleach/core` is the TypeScript runtime, running in
production today.

Two paths from zero to a working chat surface. The wizard is the
faster one; the snippets are if you'd rather see what gets
generated. Pick whichever fits your taste.

<Callout title="Which page is yours?">
  This page is for a **new project with no runtime yet**: it builds a
  fresh chat surface on `@pleach/core`. If you already run an agent, pick
  by what you have:

  * **A new project, and you know another runtime:** mount
    `createPleachRoute()` as your chat route ([Quickstart](/docs/quickstart)).
  * **A loop you want to keep, with a record of each call:**
    [`@pleach/observe`](/docs/observe) (not on npm yet). It records rows;
    it gives no family lock, replay or checkpoints.
  * **Your provider and store, with Pleach driving the turn:**
    `createBrownfieldRuntime` with storage and a paired checkpointer.
  * **Moving off another runtime:** migrate one feature at a time, or
    replace it and bring your history.

  The [six-row chooser](/docs/adoption-paths#choose-your-path) compares all of them.
</Callout>

> **Not on npm yet.** The `@pleach/*` packages aren'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](/docs/packages) tracks each package's status.

## Path A — `npx @pleach/core init` (recommended for a fresh build) [#path-a--npx-pleachcore-init-recommended-for-a-fresh-build]

```bash
npx @pleach/core init
```

The wizard detects your framework (Next.js App / Pages, Astro,
SvelteKit, Remix, Vite, plain Node), asks a few questions
(template, provider, plugin stub, schema scaffold, subagents), and
writes a starter project. On Next.js App Router that's a route
handler, a `<ChatBox />` page, and an `/audit` view — plus,
optionally, a plugin stub and the base tier of the Postgres schema.
`npx @pleach/core create` runs the same wizard. See
[CLI → `pleach init`](/docs/cli#pleach-init--the-wizard) for the
per-framework template matrix.

Run `npm run dev`. Set `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` /
`OPENROUTER_API_KEY`) first — there is no keyless mode: with no key
the route refuses every turn with HTTP 503
`{ error: "no_provider_key", provider, envVar, detail }`, and
`detail` names the env var to set. Once a key is set, `/audit` shows
real rows — model family, row count, tokens, est. cost — from your
first message.
\~60 seconds wall-clock.

## Path B — wire it by hand [#path-b--wire-it-by-hand]

Two snippets. The `@pleach/core/quickstart` subpath is the
canonical wire-level surface and ships in `@pleach/core@0.1.0`. Its
React half, `useChat` and `<ChatBox />`, is on
`@pleach/core/quickstart/react`, so the server entry loads on a
server where the optional `react` peer is not installed.

```bash
npm install @pleach/core
```

Set one provider env var — pick whichever you already have a key for:

<ProviderTabs shape="env" />

The runtime auto-detects whichever key is set. Detection scans the three providers with a built-in stream first
(Anthropic, then OpenAI, then OpenRouter), then DeepSeek, Google,
Mistral and Moonshot. A DeepSeek, Google, Mistral or Moonshot key on
its own is detected but has no built-in stream, so the route answers
503 `no_provider_key` until you pass a `providerStream`.

```typescript
// app/api/chat/route.ts
import { createPleachRoute } from "@pleach/core/quickstart";

export const POST = createPleachRoute();
```

```tsx
// app/page.tsx
"use client";
import { ChatBox } from "@pleach/core/quickstart/react";

export default function Home() {
  return <ChatBox apiUrl="/api/chat" />;
}
```

That's it. Run `npm run dev` and you have a streaming chat. The
handler accepts `{ sessionId?, message }` JSON and streams
`StreamEvent`s back as SSE. `<ChatBox />` is an unstyled, semantic,
ARIA-correct chat surface composed of plain HTML with
`data-pleach-*` selectors.

## What you just got [#what-you-just-got]

The five exports below, three from `@pleach/core/quickstart` and
the React pair from `@pleach/core/quickstart/react`, together form
the canonical wire-level surface:

| Export                                            | Shape                                             | Job                                                                                                                          |
| ------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `createPleachRoute(opts?)`                        | `(req: Request) => Response \| Promise<Response>` | Fetch-handler around `SessionRuntime`. Works in App Router, Bun, Hono — any Node.js server that speaks `Request → Response`. |
| `useChat(opts)` (`@pleach/core/quickstart/react`) | React hook                                        | Owns the in-flight stream, `messages`, `sessionId`, status (`idle \| submitting \| streaming \| error`).                     |
| `<ChatBox />` (`@pleach/core/quickstart/react`)   | React component                                   | Unstyled, semantic, accessible. Composes `useChat`.                                                                          |
| `defaultPlugin`                                   | `HarnessPlugin`                                   | Empty baseline meeting the structural contract — drop into `plugins` as the "no domain customization" floor.                 |
| `providerDetection`                               | helpers + constants                               | `detectProvider`, `detectAvailableProviders`, `DEFAULT_PROVIDER_ENV_VARS`, `DEFAULT_PROVIDER_PRIORITY`.                      |

## Two things to know before you ship [#two-things-to-know-before-you-ship]

* **No provider env var set → HTTP 503.** The handler fails
  loudly at install time rather than silently falling back to a
  stub. Surface the 503 in your client; it's the signal that
  `ANTHROPIC_API_KEY` (or your equivalent) didn't reach the
  runtime. There is no keyless fallback — a missing key always
  fails loudly rather than serving canned text.
* **`useChat` is Pleach-native, not Vercel-AI-SDK shape.** The
  hook speaks Pleach's `StreamEvent` discriminated union
  directly. If you're already on the AI SDK event taxonomy, see
  [Migrating from the AI SDK](/docs/migrating-from-ai-sdk) for the
  compat layer.

## Custom storage, plugins, or provider pinning [#custom-storage-plugins-or-provider-pinning]

The zero-config defaults work for tutorials, evals, and local
dev. Production hosts pass options through:

```typescript
// app/api/chat/route.ts
import { createPleachRoute } from "@pleach/core/quickstart";
import { SupabaseAdapter } from "@pleach/core/sessions";
import { myPlugin } from "./pleach.plugin";

export const POST = createPleachRoute({
  storage: new SupabaseAdapter({ client: supabase }),
  plugins: [myPlugin],
  provider: "anthropic",                      // pin one; skip detection
  systemPrompt: (req) => promptFor(req),      // per-request override
});
```

`SupabaseAdapter` writes to the sessions table that core's base schema creates, so apply
core's base schema first (`npx @pleach/core migrate` runs it; `npx @pleach/core
schema --apply` only copies the SQL files into your project). Pass a
durable `checkpointer` alongside custom `storage`; see
[Adopt storage and checkpointer as a pair](/docs/adoption-paths#pick-core-brownfield-when).

<Callout type="warn" title="Adding a database? Pair storage with a checkpointer">
  Durable state is split across two adapters — `storage` holds the session row
  (messages, metadata) and the `Checkpointer` holds turn/graph state. Swap in a
  custom durable `storage` but leave the checkpointer defaulted (the in-memory
  `MemorySaver`) and `resumeSession` can silently overwrite session data. Pass a
  matching durable checkpointer (`SupabaseSaver` alongside `SupabaseAdapter`) —
  both are shown together on [Runtime construction](/docs/runtime-construction).
  `createBrownfieldRuntime` (from `@pleach/core/runtime`) enforces this pairing
  for you by throwing `SplitPersistenceError`; the raw `SessionRuntime` /
  `createPleachRuntime` path warns.
</Callout>

When you need to drop below the route handler — multi-tenant
SaaS, regulated deployment, custom transport — reach for the
[runtime construction](/docs/runtime-construction) page.

## A progressive path through the docs [#a-progressive-path-through-the-docs]

You can stop reading at any of these tiers and have a working
deployment. Tier 2 adds production concerns; tier 3 adds the
audit, compliance, and replay differentiation.

### Tier 1 — \~5 minutes — streaming chat [#tier-1--5-minutes--streaming-chat]

You're here. Path A or Path B above. &#x2A;*Need a custom system
prompt?** On the route handler, pass `systemPrompt` (the option
shown in [Custom storage, plugins, or provider pinning](#custom-storage-plugins-or-provider-pinning)
above). On a raw `SessionRuntime`, there is no `systemPrompt`
string — prompts are composed from typed, replay-deterministic
contributions — but the one-liner produces one for you:

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

const runtime = createPleachRuntime({
  plugins: [systemPromptPlugin("You are a careful research assistant. Cite sources.")],
});
```

`systemPromptPlugin` builds a real contribution (composed into the
actual prompt, replay-deterministic), defaulting to `prepend` so the
persona anchors first. Need scoped or per-turn prompts? Drop to
`definePleachPlugin({ prompts: [...] })` — see
[Prompts](/docs/prompts). Then you're shipping.

**Read next:** [Providers](/docs/providers) for provider
switching · [`<ChatBox />` styling](/docs/react) for matching
your design system.

### Tier 2 — \~30 minutes — production-ready chat [#tier-2--30-minutes--production-ready-chat]

Persistent storage, custom plugins, multi-tenant cost rollup,
OTel observability.

**Read next:** [Which SKU do I need?](/docs/which-sku) ·
[Runtime construction](/docs/runtime-construction) ·
[Multi-tenant](/docs/multi-tenant) ·
[`@pleach/observe`](/docs/observe).

### Tier 3 — \~2 hours — audit + compliance + replay [#tier-3--2-hours--audit--compliance--replay]

The `AuditableCall` ledger, the four-stage lattice, scrubbers
for HIPAA / GDPR / PCI-DSS, hash-chain attestation,
replay-deterministic regression testing.

**Read next:** [Audit ledger](/docs/audit-ledger) ·
[Compliance](/docs/compliance) ·
[`@pleach/replay`](/docs/replay) · [`@pleach/eval`](/docs/eval) ·
[Decisions](/docs/decisions).

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

<Cards>
  <Card title="Which SKU do I need?" href="/docs/which-sku" description="Most projects need three or four packages. The shortest install list for what you're building." />

  <Card title="Recipes" href="/docs/recipes" description="End-to-end runnable patterns — Next.js chat, OTel, multi-tenant, compliance, RAG, subagent swarms." />

  <Card title="Playground & devtools" href="/docs/playground-and-devtools" description="What ships today for inspecting sessions, walking checkpoints, and tailing the event log — and what doesn't." />

  <Card title="Runtime construction" href="/docs/runtime-construction" description="When you need to drop below the route handler — SessionRuntime constructor + createPleachRuntime factory." />

  <Card title="Decisions" href="/docs/decisions" description="Session vs Turn vs Subagent · Ledger vs Observability · Scrubber vs ComplianceRuntime · Recipe vs Direct." />
</Cards>

## License [#license]

`@pleach/core` is licensed under **FSL-1.1-Apache-2.0**
(Functional Source License with Apache 2.0 as the future license,
auto-transitions to Apache 2.0 two years after each
release). See [versioning](/docs/versioning) for the policy.
