
# Pi agent

`agentak/pi` is Agentak's included agent runtime. It combines
[`pi-agent-core`](https://www.npmjs.com/package/@earendil-works/pi-agent-core) with browser
provider selection, model catalogs, thinking levels, tool approvals, storage, history,
usage, and user-facing errors.

The loop runs in the page. It can run an on-device model or send a request directly to a
supported provider. Agentak does not require its own backend.

This is the only Agentak entry that loads Pi. A custom `ChatSession` can use the same UI
without importing it.

## Create a session

```ts
import { createPiSession } from "agentak/pi";

const session = createPiSession();

// Pass session to ChatPanel, AgentChat, or mountChat().
// End it when the host no longer needs it.
session.dispose();
```

Create the session once, outside a render function. A fresh session starts on the first
provider in the picker, with no model. If the user sends a message first, Agentak holds it,
opens settings, and sends it after a usable model is selected.

A configured session can start with instructions, tools, persistence, and a preferred
provider:

```ts
import { browserStorage, createPiSession } from "agentak/pi";

const session = createPiSession({
  provider: "openrouter",
  apiKey: "sk-or-v1-…",
  storage: browserStorage(),
  history: true,
  page: true,
  thinkingLevel: "medium",
  systemPrompt: "You are the support agent for example.com. Keep answers short.",
  approvals: "once",
});
```

## How it reaches the widget

```text
message
  -> Pi Agent
  -> provider stream or on-device model
  -> agent events
  -> Agentak transcript, queue, approvals, usage, and errors
  -> ChatSession
  -> AgentChat / ChatPanel
```

The session rebuilds the visible transcript from Pi state after every event. Reasoning,
text, tool calls, results, images, failed turns, and compaction checkpoints become the
parts rendered by the chat.

## Options

`PiSessionOptions` includes these high-level session options and the agent options below:

| Option          | Type                               | Purpose                                                                       |
| --------------- | ---------------------------------- | ----------------------------------------------------------------------------- |
| `provider`      | `string`                           | Provider to open. The snapshot, this value, or a saved choice can supply it.  |
| `apiKey`        | `string \| Record<string, string>` | One provider key or a map of keys. Free providers need none.                  |
| `storage`       | `PiStorage`                        | Keeps keys and picker choices. Asynchronous. Shared page memory by default.   |
| `snapshot`      | `PiSnapshot`                       | Stored conversation to open, including its provider, model, level, and title. |
| `history`       | `boolean \| PiHistory`             | Adds built-in conversation history. Off by default.                           |
| `generateTitle` | `boolean`                          | Uses one extra request after the first answer to name the conversation.       |
| `page`          | `boolean \| PageTools`             | Adds WebMCP tools from this document or another page source. Off by default.  |
| `systemPrompt`  | `string`                           | Replaces the short built-in browser-assistant prompt.                         |
| `thinkingLevel` | `ThinkingLevel`                    | Starting reasoning effort before a saved model choice overrides it.           |
| `tools`         | `AgentTool[]`                      | Host tools available to the model. None are included by default.              |
| `approvals`     | `"always" \| "once" \| "never"`    | Session-wide tool confirmation policy. Default: `"once"`.                     |
| `approvalFor`   | function                           | Optional per-tool confirmation policy.                                        |
| `streamFn`      | `StreamFn`                         | Replaces provider streaming, mainly for custom runtimes and tests.            |

The thinking scale is `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`.
Agentak clamps the current choice to the levels the selected model supports. A model with
no reasoning support uses `off` and shows no thinking-level control.

## `PiSession` methods

`createPiSession()` returns a `PiSession`. It implements the complete `ChatSession`
contract and adds:

- `ready` resolves once the store has answered with the keys, the provider, the model, the
  level, and any stored conversations. Wait for it to mount without showing a chat that has
  forgotten its choices.
- `save()` returns a versioned `PiSnapshot`. It is cheap and safe while a turn streams;
  the unfinished turn is not included.
- `restore(snapshot?)` replaces the live conversation in place. With no snapshot, it
  starts a new conversation. A running turn is stopped first.
- `dispose()` removes listeners and releases session resources.

The UI never calls `dispose()`. The code that created the session must call it.

## Explore the Pi runtime

::card-group{cols="2"}
:::card{title="Providers and models" icon="i-lucide-cloud" to="/agents/pi/providers-and-models"}
All network providers, free choices, lazy catalogs, CORS rules, and model settings.
:::
:::card{title="On-device models" icon="i-lucide-cpu" to="/agents/pi/on-device-models"}
Chrome Built-in AI and local GGUF models running with wllama.
:::
:::card{title="Tools and approvals" icon="i-lucide-wrench" to="/agents/pi/tools-and-approvals"}
Typed tools, confirmation policies, denial reasons, results, and queued messages.
:::
:::card{title="WebMCP page tools" icon="system-uicons:browser" to="/agents/pi/webmcp"}
Discover and call tools published by the current page, or bridge another document.
:::
:::card{title="Storage and API keys" icon="i-lucide-key-round" to="/agents/pi/storage-and-api-keys"}
Memory defaults, localStorage, custom stores, and credential safety.
:::
:::card{title="Errors, usage, and titles" icon="i-lucide-activity" to="/agents/pi/runtime-behavior"}
Retry behavior, settings-opening failures, context limits, cost, and generated titles.
:::
:::card{title="Conversations" icon="i-lucide-archive" to="/agents/pi/conversations"}
Built-in history, snapshots, restore behavior, and storage limits.
:::
:::card{title="Advanced APIs" icon="i-lucide-braces" to="/agents/pi/advanced-api"}
Build on the lower-level agent, store, catalog, transcript, and page-tool helpers.
:::
::
