# Quickstart (/docs/quickstart)



If you're adding a streaming chat surface to an existing app — Next.js,
Astro, SvelteKit, Remix, Vite, Hono, plain Node — this is the
shortest path. It's the same wire-level surface
[Getting started](/docs/getting-started) covers; this page goes deeper
on the env-var detection, the error contract, and what `useChat`
actually gives you.

<Callout title="Is this the right page?">
  This page is for a **new project with no runtime yet**. If you already
  have an agent loop, the [chooser on Adoption paths](/docs/adoption-paths#choose-your-path)
  routes you by where you are: keep your loop and record each call with
  [`@pleach/observe`](/docs/observe) (not on npm yet; no family lock,
  replay or checkpoints), let Pleach drive the turn over your provider and
  store with `createBrownfieldRuntime` (storage paired with a
  checkpointer), or migrate off another runtime.
</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.

## One install, one env var, three files [#one-install-one-env-var-three-files]

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

Set one provider env var:

```bash
# .env (or your platform's env config)
ANTHROPIC_API_KEY=sk-ant-...
```

```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" />;
}
```

Run `npm run dev`. You have a streaming chat against Anthropic.

`useChat` and `<ChatBox />` import from `@pleach/core/quickstart/react`;
`createPleachRoute` stays on `@pleach/core/quickstart`, which loads on a
server with no `react` installed. The old `useChat` and `ChatBox` names on
`@pleach/core/quickstart` still work on Node and in SSR but are deprecated,
and browser code must import from the `/react` subpath.

## .env setup [#env-setup]

The runtime checks env vars in priority order. The first one with a
non-empty value wins. **The default order scans Anthropic, OpenAI
and OpenRouter first**, then DeepSeek and Google, then Mistral and
Moonshot, so `ANTHROPIC_API_KEY` wins over `OPENROUTER_API_KEY` when
both are set, and `OPENAI_API_KEY` wins over `GOOGLE_API_KEY`. A
DeepSeek or Google key on its own streams from that vendor's own
OpenAI-compatible endpoint. A Mistral or Moonshot key on its own is
detected, but the route answers 503 `no_provider_key` until you pass a
`providerStream`. This behavior is
regression-tested in the package suite.

| Provider   | Env var                                                     |
| ---------- | ----------------------------------------------------------- |
| Anthropic  | `ANTHROPIC_API_KEY`                                         |
| DeepSeek   | `DEEPSEEK_API_KEY`                                          |
| Google     | `GOOGLE_GENERATIVE_AI_API_KEY` (or legacy `GOOGLE_API_KEY`) |
| Mistral    | `MISTRAL_API_KEY`                                           |
| Moonshot   | `MOONSHOT_API_KEY`                                          |
| OpenAI     | `OPENAI_API_KEY`                                            |
| OpenRouter | `OPENROUTER_API_KEY`                                        |

**Default model.** With only `OPENROUTER_API_KEY` set, the default provider
stream calls `deepseek/deepseek-v4.1-flash-1017`. Pass `model` to use another
slug.

The seven-provider surface mirrors the `ProviderFamily` set exported
from `@pleach/core/modelfamily` plus OpenRouter as a gateway
transport. The `(family × callClass)` resolution matrix itself is
host-supplied — you provide it through the
`AgentAdapter.resolveModel<C>()` seam. See
[Provider detection](/docs/quickstart/provider-detection)
for the full resolution matrix and how to override priority.

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

* **Streaming response** — `<ChatBox />` renders tokens as they arrive
  via the `useChat` hook, which speaks Pleach's `StreamEvent`
  discriminated union directly.
* **Multi-turn memory** — `useChat` owns a `sessionId` and reuses it
  across calls. Each user message appends to the same session
  history.
* **Stop is a user stop** — `useChat().stop()` aborts the in-flight
  request. The hook declares its disconnect intent on every execute
  request (`PLEACH_ON_DISCONNECT_HEADER`), so `createPleachRoute`
  classifies the abort as `"user"` and
  `runtime.wasLastTurnAbortedByUser()` is `true`. See
  [Stopping a streamed turn from the client](/docs/session-runtime#stopping-a-streamed-turn-from-the-client).
* **`bot.reset()`** equivalent — in the React surface, this is
  `clearMessages()` on the `useChat` return; on the recipes path
  (below), it's `bot.reset()` or `bot.newSession()` on the `Chatbot`.
* **`ChatStreamError` rejection** — when the underlying stream emits
  `{ type: "error" }` or the generator throws, the failure surfaces
  to the caller. The original cause is preserved on `error.cause`;
  any stream-emitted `code` is preserved on `error.code`. The
  factory contract is in `@pleach/recipes/chatbot`.

**The agent has a name.** The quickstart agent is called Hazel, and its
identity section opens with "Your name is Hazel." Pass `agentName` to
`createPleachRoute` or `createPleachAgent` to choose another name, or
`agentName: null` to leave it unnamed. A `name:` line in the
[heartwood](/docs/heartwood) wins over the option. A name over 32
characters, one with characters outside letters, digits, space and
`.-_'`, or a reserved label such as `you`, `user` or `assistant`
names nobody.

## Beyond one route: the whole family [#beyond-one-route-the-whole-family]

`createPleachRoute` mounts the single execute leg. When you want the
rest of what the runtime speaks — sessions CRUD, interrupts,
checkpoints, rollback, events-recall, sync, fork — reach for the
standalone-agent façade from the same subpath:

```typescript
// app/api/harness/[...path]/route.ts
import { createPleachAgent } from "@pleach/core/quickstart";

const agent = createPleachAgent({
  context: { provider: "anthropic", systemPrompt: "You are a helpful assistant." },
  // tools defaults to the base-tools bundle
  // db omitted → in-memory durable store (recall works, no Supabase)
});

export const { GET, POST, PUT, DELETE } = agent.nextRoutes();
```

`createPleachAgent({ context, tools, db })` takes three arms and hands
back the whole route family plus `agent.store` for direct reads. Omit
`db` and it uses an in-memory
[`DurableStore`](/docs/storage) — recall and the audit ledger work
with no external database, state resets on restart. See
[Standalone agent](/docs/server#the-standalone-agent-createpleachagent)
for the lower-level `createPleachRoutes` factory and the durable
interrupt-resolver note.

The family turns the approval authority on by default. A gated tool
call (`interrupt: { interruptBefore: [...] }`) pauses only for a user
your own `resolveUserId` names, and the resolve must present the
`approvalNonce` from that turn's `interrupt.requested` frame. With no
`resolveUserId`, gated calls are refused. A tool flagged
`requiresApproval` pauses only when you also pass an `interrupt`
config (`interrupt: {}` is enough). Without one there is no interrupt
manager to ask through, so the call is refused even when
`resolveUserId` is set. Pass
`approvalAuthority: false` to opt out. See
[Interrupts → Who can decide](/docs/interrupts#who-can-decide).

## Troubleshooting [#troubleshooting]

### `"No provider API key found in environment."` (HTTP 503) [#no-provider-api-key-found-in-environment-http-503]

The route handler fails loudly when no provider env var is set 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.

The error payload is:

```json
{
  "error": "no_provider_detected",
  "detail": "No provider API key found in environment. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, or pass `provider` to createPleachRoute()."
}
```

Fix: set one of the env vars from the table above, or pass
`provider: "anthropic"` explicitly to `createPleachRoute({ provider })`.
A custom `providerStream` does not resolve a provider by itself: with
no key in the environment, pin `provider` alongside it, or the route
still answers this 503.

There is **no keyless mode**. With no provider key the route refuses
every turn with HTTP 503 and a typed JSON body,
`{ error: "no_provider_key", provider, envVar, detail }`, where
`detail` names the env var to set. A canned answer proves no value
prop, so one is never served. Set a real key to chat.

### `localStorage is not defined` [#localstorage-is-not-defined]

If you see this from the runtime in an SSR / Node context (server
route, serverless function, test harness), it was resolved 2026-06-15 in
`fix(core): generateClientId guards window.localStorage consistently
(jsdom + SSR safe)`. `generateClientId()` now checks
`typeof window === "undefined" || !window.localStorage` before
attempting any read.

Upgrade `@pleach/core` to a version published after 2026-06-15.

### `ChatStreamError` rejection [#chatstreamerror-rejection]

`Chatbot.ask()` (on the recipes path) rejects with `ChatStreamError`
when the underlying stream fails. The original failure is preserved:

```typescript
try {
  await bot.ask("hello");
} catch (err) {
  if (err instanceof ChatStreamError) {
    console.error("stream failed", err.message);
    console.error("root cause:", err.cause);
    console.error("stream code:", err.code);
  }
}
```

Common root causes: provider API key invalid (check `.env`),
provider rate limit hit, request aborted upstream. Inspect
`err.cause` for the provider-level error.

## Alternative: `@pleach/recipes/chatbot` (no route handler) [#alternative-pleachrecipeschatbot-no-route-handler]

If you don't need an HTTP boundary — for example you're building a
CLI, a Node script, or a server-internal helper — reach for the
recipes path:

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

```typescript
import { simpleChatbot } from "@pleach/recipes/chatbot";
import { AiSdkProvider } from "@pleach/core";
import { anthropic } from "@ai-sdk/anthropic";

const bot = simpleChatbot({
  systemPrompt: "You are a helpful assistant.",
  provider: new AiSdkProvider({ model: anthropic("claude-sonnet-4-6") }),
});

console.log(await bot.ask("hello"));
console.log(await bot.ask("what did I just say?"));  // same session
await bot.reset();
console.log(await bot.ask("fresh conversation"));    // new session
```

Unlike the route handler, `simpleChatbot` does
NOT auto-detect provider env vars. You pass the provider explicitly;
the model comes from the provider. With no provider (and no
`orchestratorConfig`), `ask()` rejects with
`NoProviderConfiguredError` rather than returning canned text.

The `bot.runtime` field is the underlying `SessionRuntime`. Use it
directly when you need plugins, checkpoint inspection, custom
observers, or anything below the `ask()` surface. See
[Upgrading to @pleach/core](/docs/quickstart/upgrading-to-core).

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

<Cards>
  <Card title="Provider detection" href="/docs/quickstart/provider-detection" description="Env-var resolution matrix, priority override, custom env-var aliases." />

  <Card title="Upgrading to @pleach/core" href="/docs/quickstart/upgrading-to-core" description="When `simpleChatbot` isn't enough — plugins, custom tools, custom orchestratorConfig, direct SessionRuntime use." />

  <Card title="Which SKU do I need?" href="/docs/which-sku" description="Most projects need three or four packages." />

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