> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qredence.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Fleet Pi architecture

> Runtime topology of Fleet Pi — React 19 browser client, TanStack Start Nitro backend, repo-local agent workspace, the Pi runtime, and the configured model provider.

Fleet Pi is a TanStack Start web app with a Nitro-backed API, a React 19 UI, and a repo-local agent workspace. This page maps the runtime boundaries.

## Topology

```mermaid theme={null}
graph TD
    subgraph Client["Browser client"]
        React[React 19 + TanStack Router]
        AgentChat[AgentChat]
        InputBar[InputBar]
        MessageList[MessageList]
        RightPanels[Resources & Workspace panels]
    end

    subgraph WebApp["apps/web — TanStack Start"]
        Vite[Vite dev server]
        ChatRoute[/api/chat]
        HealthRoute[/api/health]
        ModelsRoute[/api/chat/models]
        ResourcesRoute[/api/chat/resources]
        SessionRoute[/api/chat/session]
        WorkspaceRoutes[/api/workspace/*]
        AuthRoutes[/api/auth/*]
        PiServer[Pi server module]
        PlanMode[Plan-mode extension]
        WorkspaceServer[Workspace server]
        ResourceCatalog[Workspace resource catalog]
        CircuitBreaker[Bedrock circuit breaker]
        Logger[Pino logger]
        Sanitizer[PII sanitizer]
        Provenance[Run provenance]
    end

    subgraph AgentWorkspace["agent-workspace/"]
        Memory[Project memory]
        Plans[Plans & backlog]
        Skills[Skills & evals]
        PiResources[Installed Pi resources]
        Artifacts[Artifacts & scratch]
        Manifest[manifest.json]
        Indexes[indexes/ — projections]
    end

    subgraph ProjectPi[".pi/"]
        PiConfig[settings.json]
        PiExtensions[Built-in Pi extensions]
        PiSkills[Committed Pi skills]
    end

    subgraph External["External services"]
        ModelProvider[Model provider<br/>Gemini · Bedrock · OpenAI · Anthropic · ...]
        Daytona[Daytona sandboxes<br/>optional]
    end

    React --> AgentChat
    AgentChat --> InputBar
    AgentChat --> MessageList
    AgentChat --> RightPanels
    React --> Vite
    Vite --> ChatRoute
    Vite --> HealthRoute
    Vite --> ModelsRoute
    Vite --> ResourcesRoute
    Vite --> SessionRoute
    Vite --> WorkspaceRoutes
    Vite --> AuthRoutes
    ChatRoute --> PiServer
    ChatRoute --> Sanitizer
    ChatRoute --> Logger
    ChatRoute --> Provenance
    PiServer --> CircuitBreaker
    CircuitBreaker --> ModelProvider
    PiServer --> PlanMode
    PiServer --> PiConfig
    PiServer --> PiExtensions
    PiServer --> PiSkills
    ResourcesRoute --> ResourceCatalog
    WorkspaceRoutes --> WorkspaceServer
    ResourceCatalog --> PiResources
    WorkspaceServer --> Memory
    WorkspaceServer --> Plans
    WorkspaceServer --> Skills
    WorkspaceServer --> Artifacts
    WorkspaceServer --> Manifest
    WorkspaceServer -.-> Indexes
```

## Layers

### Browser client

React 19 with TanStack Router. `AgentChat` composes `InputBar`, `MessageList`, and the right-hand resources and workspace panels. Streaming chat, structured plan cards, and tool cards are rendered with the shared `agent-elements` integration from `packages/hax-design` (`@workspace/hax-design`), the single source of truth for Fleet Pi chat surfaces, the OpenUI kit, and shared Pi protocol types.

State management:

* `usePiChat` orchestrates the NDJSON stream lifecycle, tool rendering, and queued steering / follow-up prompts.
* `useChatStorage` keeps minimal session metadata (`sessionFile`, `sessionId`) in `localStorage` so a refresh can hydrate the matching Pi session file.

### `apps/web` — TanStack Start

The Vite dev server hosts file-based API routes under `apps/web/src/routes/api/`:

| Route                    | Method   | Purpose                                                                     |
| ------------------------ | -------- | --------------------------------------------------------------------------- |
| `/api/health`            | GET      | Smoke endpoint used by the quickstart.                                      |
| `/api/chat`              | POST     | Pi-backed chat with NDJSON streaming, PII sanitization, Pino logging.       |
| `/api/chat/abort`        | POST     | Abort the active chat session.                                              |
| `/api/chat/models`       | GET      | Model catalog with default provider and thinking level.                     |
| `/api/chat/providers`    | GET/POST | Provider credential state and updates through the in-app config panel.      |
| `/api/chat/new`          | POST     | Create a new chat session.                                                  |
| `/api/chat/provenance`   | GET      | Per-run provenance records.                                                 |
| `/api/chat/question`     | POST     | Answer a `questionnaire` follow-up question.                                |
| `/api/chat/resources`    | GET      | Skills, prompts, extensions, themes, packages, AGENTS.md files.             |
| `/api/chat/resume`       | POST     | Resume an existing session file.                                            |
| `/api/chat/run`          | POST     | Run a single recorded run.                                                  |
| `/api/chat/runs`         | GET      | List recorded runs for a session.                                           |
| `/api/chat/session`      | GET      | Hydrate a session by query params.                                          |
| `/api/chat/sessions`     | GET      | List all chat sessions.                                                     |
| `/api/chat/settings`     | GET/POST | Read and patch effective `ChatPiSettings`.                                  |
| `/api/workspace/file`    | GET      | Read a canonical workspace file.                                            |
| `/api/workspace/health`  | GET      | Workspace contract health.                                                  |
| `/api/workspace/item`    | GET      | Fetch a single workspace item.                                              |
| `/api/workspace/items`   | GET      | List workspace items.                                                       |
| `/api/workspace/reindex` | POST     | Trigger a workspace reindex projection.                                     |
| `/api/workspace/search`  | GET      | Search workspace items via the projection index.                            |
| `/api/workspace/tree`    | GET      | Browse the workspace tree.                                                  |
| `/api/sandbox/preview`   | GET      | Signed preview URL into the calling user's Daytona sandbox (auth required). |
| `/api/webhooks/daytona`  | POST     | Daytona lifecycle webhook, gated by `DAYTONA_WEBHOOK_SECRET`.               |
| `/api/auth/$`            | ALL      | Mounted only when `BETTER_AUTH_SECRET` is set.                              |

Internal modules:

* `lib/pi/server.ts` — Pi runtime cache, `createPiRuntime`, `queuePromptOnActiveSession`, NDJSON encoding.
* `lib/pi/server-chat-stream.ts` — assistant turn lifecycle (`beginAssistantTurn`, `handleSessionEvent`, `finalizeAssistantTurn`).
* `lib/pi/plan-mode.ts` — mode allowlists and the plan-mode Pi extension.
* `lib/pi/circuit-breaker.ts` — `opossum` configuration around Bedrock invocations.
* `lib/pi/run-provenance.ts` — provenance recording around session and tool events.
* `lib/workspace/server.ts` and `workspace-contract.ts` — durable workspace contract, manifest, and section kinds.
* `lib/pii/sanitizer.ts` — input redaction before logging.
* `lib/logger.ts` — Pino logger with redaction and `requestId` correlation.

### `agent-workspace/`

The durable adaptive layer. The workspace server reads memory, plans, skills, and artifacts directly from files so every change shows up in Git diffs. The contract is versioned (`WORKSPACE_CONTRACT_VERSION = 1`) and the canonical section set is fixed in `workspace-contract.ts`:

`instructions/`, `system/`, `memory/`, `plans/`, `skills/`, `evals/`, `artifacts/`, `scratch/`, `pi/`, `indexes/`.

Sections have **kinds** — `canonical`, `temporary`, or `projection` — that the workspace server enforces.

### `.pi/`

Committed project Pi configuration. `settings.json` is a compatibility bridge that points Pi at workspace-native resource directories. Built-in Pi extensions and committed skills also live here.

### External

Fleet Pi calls whichever model provider is configured — Google Gemini by default (`gemini-3.5-flash`), or any other supported provider (Amazon Bedrock, OpenAI, Anthropic, Mistral, Groq, Vertex, Ollama). Provider selection lives in `.pi/settings.json`; credentials live in `.env`.

**Amazon Bedrock specifically** is wrapped by a process-wide `opossum` circuit breaker (`bedrock-api`). When you switch Fleet Pi to Bedrock, every Bedrock invocation passes through these settings:

| Option                     | Value     | Meaning                                  |
| -------------------------- | --------- | ---------------------------------------- |
| `errorThresholdPercentage` | 50%       | Open after half of sampled calls fail.   |
| `volumeThreshold`          | 5         | Minimum 5 calls before breaker can open. |
| `resetTimeout`             | 30,000 ms | Wait 30 s before trying half-open.       |
| `timeout`                  | 30,000 ms | Each call must complete within 30 s.     |

When the Bedrock breaker is open, requests fail fast with `"Bedrock API is temporarily unavailable due to repeated failures. Please try again later."`. Other providers fail through Pi's standard error path (no breaker), so reliability tuning for non-Bedrock providers happens upstream in `@earendil-works/pi-coding-agent`.

**Daytona** is an optional external service for authenticated user sandboxes — enabled by setting `DAYTONA_API_KEY`. See the [API reference](/fleet-pi/api-reference#sandbox) for the sandbox surface.

## Packages

| Package               | Purpose                                                                                                                                 |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/web`            | TanStack Start app and `/api/*` backend.                                                                                                |
| `packages/hax-design` | Shared React UI (`@workspace/hax-design`) — Fleet Pi chat and workspace surfaces, the OpenUI kit, and the `agent-elements` integration. |

Key dependencies: `@earendil-works/pi-coding-agent`, `@earendil-works/pi-ai`, `@tanstack/react-start`, `opossum`, `pino` + `pino-pretty`, `zod` + `@asteasolutions/zod-to-openapi`, `vitest`, `@playwright/test`, `husky` + `lint-staged`.

`apps/web/src/routeTree.gen.ts` is generated. Do not edit by hand.

## Request lifecycle

1. The browser sends a chat message to `/api/chat` as JSON.
2. `ChatRequestSchema` (zod) validates the body.
3. `sanitizePii` redacts the message before logging.
4. `createRequestLogger` attaches a correlation `requestId`.
5. `createPiRuntime` returns a warm Pi runtime (TTL controlled by `FLEET_PI_RUNTIME_TTL_MS`) or builds one.
6. The Pi runtime invokes the configured model provider. Bedrock calls go through the `opossum` circuit breaker; other providers go through Pi's standard provider path.
7. Events are forwarded as NDJSON via `encodeEvent`: `start`, `delta`, `thinking`, `tool`, `plan`, `state`, `queue`, `compaction`, `retry`, `done`, `error`.
8. `createRunProvenanceRecorder` records the session lifecycle and tool events.
9. On client refresh, `POST /api/chat/resume` or `GET /api/chat/session` hydrates the Pi session file.

## Related

<CardGroup cols={2}>
  <Card title="Agent workspace" icon="folder-tree" href="/fleet-pi/agent-workspace">
    What lives in `agent-workspace/` and why it is reviewable.
  </Card>

  <Card title="Adaptive workspace contract" icon="file-contract" href="/fleet-pi/adaptive-workspace">
    Canonical sections, manifest, and projection rules.
  </Card>

  <Card title="Runtime SDK seams" icon="code-branch" href="/fleet-pi/runtime-sdk-integration">
    Safe extension points around the Pi runtime.
  </Card>

  <Card title="API reference" icon="code" href="/fleet-pi/api-reference">
    Endpoint contracts and stream events.
  </Card>
</CardGroup>
