# Custom clients

<p class="text-sm text-muted-foreground">Requires a Fide server.</p>

You can connect an externally hosted web app (such as a Vite, React, or Next.js app on Vercel or Cloudflare) directly to a Fide project so your UI streams reply text and tool calls straight from Fide over SSE—without building your own agent runner or proxying streams through your app's backend or database.

Custom clients use a two-tier authentication model:

1. Your backend holds a project **Server API key** (`fcli_...`) and mints a short-lived **thread token** (`fclt_...`) bound to one project and one thread.
2. Your browser uses that thread token directly against your Fide environment's `/api/client/<projectId>` endpoint.

Every thread created or resumed through the Client API is a regular Fide thread in that project, so you can open and inspect it in Fide at any time. The environment must be running and reachable at its public URL; paused cloud sandboxes do not auto-wake on incoming Client API requests.

## Enable the Client API on a project

1. Open **Settings → Client API** for the environment that holds your project.
2. Select the project, switch on **Let external custom clients run turns in this project**, and configure:
   - **Permission mode:** Required; there is no default. Choices are constrained by your managed policy and provider support. Use **Full access** only on a dedicated sandbox environment that holds nothing else.
   - **Model:** Optional project-level override. When left unset, turns use the project's default model (if neither is configured, turns fail with `MODEL_NOT_CONFIGURED`).
   - **Turn limit (seconds):** Automatically interrupts stalled unattended turns (whole number from `30` to `3600`).
   - **Allowed browser origins (CORS):** List each exact browser origin that will stream from this project—scheme, host, and optional port, with no path (for example `https://app.example.com` and `http://localhost:5173`).
3. Save the settings, copy the project's **Endpoint** URL (`https://<host>/api/client/<projectId>`), and create a named **Server API key** (`fcli_...`). The secret is shown once; store it only on your app's backend, never in browser code.

> External client turns run on this environment's signed-in provider account. For multi-user or customer-facing apps, use an API key or commercial provider account whose terms allow it.

## Connect with `@fide-work/client`

`@fide-work/client` provides three entrypoints:

- `@fide-work/client/server` — backend helper (`mintThreadToken`) to mint thread tokens with your Server API key
- `@fide-work/client/react` — React hook (`useFideThread`) for streaming, history, reconnect, and cancel
- `@fide-work/client` — framework-agnostic browser client (`FideClient`, `createFideClient`), stream reducer (`applyStreamEvent`), SSE parser (`parseSseStream`), and types

### 1. Mint a short-lived thread token on your backend

Call `mintThreadToken` only from a trusted backend (such as a server route, serverless function, or Worker). The `/tokens` endpoint rejects requests that carry a browser `Origin` header (`403 BROWSER_ORIGIN_FORBIDDEN`).

```ts
import { mintThreadToken } from "@fide-work/client/server";

const session = await mintThreadToken({
  baseUrl: process.env.FIDE_CLIENT_URL!, // https://<host>/api/client/<projectId>
  apiKey: process.env.FIDE_CLIENT_KEY!, // fcli_...
  threadId: existingThreadId, // optional; omit to create a new thread
  title: "Customer itinerary", // optional title when creating a new thread
  ttlSeconds: 900, // optional; clamped server-side to 60–3600s (default 900s)
  metadata: { record_id: "rec_123" }, // optional hint signed into the token
});
// Return { token: session.token, threadId: session.threadId, expiresAt: session.expiresAt } to the browser.
```

- Omit `threadId` to start a new thread in the project; pass an existing `threadId` from the same project to resume it. Unknown, archived, or other-project IDs fail with `404 THREAD_NOT_FOUND`.
- Metadata passed to `mintThreadToken` or `sendMessage` is prepended to the user message as a hint to the agent—never a trust boundary. Token metadata takes precedence over per-message metadata on colliding keys. Domain tools must still enforce their own server-side authorization.

### 2. Stream in React with `useFideThread`

`useFideThread` loads thread history on mount (set `autoLoadHistory: false` to control loading yourself), streams incremental text and tool-call updates into `streamingItems`, and reloads history when a turn finishes.

```tsx
import { useFideThread } from "@fide-work/client/react";

export function ProjectChat({ baseUrl, session }: {
  baseUrl: string;
  session: { token: string; threadId: string };
}) {
  const {
    turns,
    streamingItems,
    isLoadingHistory,
    isStreaming,
    error,
    sendMessage,
    subscribe,
    cancel,
    reload,
  } = useFideThread({
    baseUrl,
    token: session.token,
    threadId: session.threadId,
  });

  return (
    <div>
      {turns.map((turn) => (
        <div key={turn.runId}>
          <p>{turn.userText}</p>
          {turn.items.map((item) =>
            item.kind === "text" ? (
              <p key={item.id}>{item.text}</p>
            ) : (
              <pre key={item.id}>
                {item.toolCall.name} ({item.toolCall.state})
              </pre>
            ),
          )}
        </div>
      ))}

      {streamingItems.map((item) =>
        item.kind === "text" ? (
          <p key={item.id}>{item.text}</p>
        ) : (
          <pre key={item.id}>
            {item.toolCall.name} ({item.toolCall.state})
          </pre>
        ),
      )}

      {error && <p>{error.message}</p>}
      <button disabled={isStreaming} onClick={() => void sendMessage("Summarize recent changes")}>
        Send
      </button>
      {isStreaming && <button onClick={() => void cancel()}>Stop</button>}
    </div>
  );
}
```

### 3. Use the framework-agnostic client

For non-React frontends or custom state management, use `FideClient` (or `createFideClient`) together with `applyStreamEvent`:

```ts
import {
  FideClient,
  FideClientError,
  applyStreamEvent,
  type FideTurnItem,
} from "@fide-work/client";

const client = new FideClient({
  baseUrl: "https://<host>/api/client/<projectId>",
  token: session.token,
  threadId: session.threadId,
});

let items: ReadonlyArray<FideTurnItem> = [];
try {
  for await (const event of client.sendMessage({
    text: "Check open tasks",
    messageId: crypto.randomUUID(),
    metadata: { view: "board" },
  })) {
    items = applyStreamEvent(items, event);
    if (event.type === "run.failed") {
      console.error(event.code, event.message);
    }
  }
} catch (err) {
  if (err instanceof FideClientError && err.code === "TOKEN_EXPIRED") {
    // Request a fresh token for client.threadId from your backend, then update it:
    client.setToken(freshToken);
  }
}
```

## Disconnects, retries, and unattended turns

- **Browser disconnects and page reloads:** Closing a tab or losing network connectivity detaches the SSE listener while the run continues to completion in the background so stateful tool calls are not cut off mid-write. Call `subscribe()` (`GET /threads/<threadId>/stream`) after a reload to reattach to an in-flight run, or `getHistory()` (`GET /threads/<threadId>/history`) to load finished turns.
- **Idempotent retries:** Pass a caller-generated `messageId` to `sendMessage`. Retrying the same `messageId` after a network drop reattaches to the existing run instead of duplicating the turn or returning `409 THREAD_BUSY`.
- **One active turn per thread:** Sending a new message while a run is already active returns `409 THREAD_BUSY`. Wait for completion or call `cancel()` first.
- **Approvals and turn limits:** Unattended custom clients cannot answer interactive approval prompts. If a run pauses waiting for approval, Fide interrupts it automatically and emits `run.failed` with code `WAITING_FOR_APPROVAL`. If a run exceeds the project's configured turn limit, Fide interrupts it and emits `run.failed` with code `TURN_LIMIT_EXCEEDED`. If Fide loses a run's live updates, the stream ends with `run.failed` code `STREAM_FAILED`; the run may still be going, so call `subscribe()` or `getHistory()` to catch up.
- **Token expiry and revocation:** Thread tokens expire after their configured TTL (`401 TOKEN_EXPIRED`); mint a fresh token for the same `threadId` from your backend and pass it to `setToken` (or update the `token` prop in `useFideThread`). Revoking a server API key or disabling the Client API on a project immediately rejects tokens minted by that key (`401 KEY_REVOKED` or `PROJECT_DISABLED`) and terminates any open SSE streams.

## HTTP and SSE API

All routes live under `/api/client/<projectId>`. Browser routes validate the `Origin` header against the project's configured **Allowed browser origins (CORS)** and support `OPTIONS` preflight requests.

| Method & path | Auth | Request / response |
| --- | --- | --- |
| `POST /tokens` | `x-api-key` or `Authorization: Bearer <serverKey>` (server-only; rejects browser `Origin`) | Body: `{ threadId?, title?, ttlSeconds?, metadata? }`. Returns `{ token, projectId, threadId, expiresAt }`. |
| `POST /threads/<threadId>/messages` | `Authorization: Bearer <threadToken>` | Body: `{ text, messageId?, metadata? }`. Streams `text/event-stream` SSE events. |
| `GET /threads/<threadId>/stream` | `Authorization: Bearer <threadToken>` | Reattaches to the thread's active run over `text/event-stream`, or returns `409 NO_ACTIVE_RUN`. |
| `GET /threads/<threadId>/history` | `Authorization: Bearer <threadToken>` | Returns `{ threadId, turns }` where each turn has `{ runId, status, requestedAt, completedAt, userText, items }` (`completedAt` is `null` while the run is still going). |
| `POST /threads/<threadId>/cancel` | `Authorization: Bearer <threadToken>` | Interrupts the active run and returns `{ threadId, runId, status }`. |

### SSE events

Each SSE frame carries a JSON object in `data:`:

| `type` | Fields | Meaning |
| --- | --- | --- |
| `run.started` | `threadId`, `runId` | The turn started running. |
| `text.delta` | `threadId`, `runId`, `itemId`, `delta` | Incremental assistant text chunk for `itemId`. |
| `tool.updated` | `threadId`, `runId`, `itemId`, `toolCall` | Tool call snapshot (`{ id, name, state, input?, output?, errorText? }`, where `state` is `pending`, `running`, `completed`, or `error`). |
| `run.completed` | `threadId`, `runId` | The turn finished successfully. |
| `run.failed` | `threadId`, `runId`, `code`, `message` | The turn failed (for example `WAITING_FOR_APPROVAL`, `TURN_LIMIT_EXCEEDED`, or `STREAM_FAILED`). |
| `run.cancelled` | `threadId`, `runId` | The turn was cancelled via `/cancel` or interrupted. |

### Error responses

Non-2xx responses return JSON in the shape `{ "error": { "code": "...", "message": "..." } }`:

| Status | Codes | Meaning |
| --- | --- | --- |
| `400` | `INVALID_REQUEST` | Malformed JSON body, missing `text`, or missing route parameters. |
| `401` | `UNAUTHORIZED`, `INVALID_TOKEN`, `TOKEN_EXPIRED`, `KEY_REVOKED`, `PROJECT_DISABLED` | Missing, invalid, expired, or revoked credentials. |
| `403` | `BROWSER_ORIGIN_FORBIDDEN`, `ORIGIN_NOT_ALLOWED` | `/tokens` called with an `Origin` header, or browser `Origin` not in the project's allowed list. |
| `404` | `PROJECT_NOT_ENABLED`, `THREAD_NOT_FOUND` | Client API is disabled for the project, or the thread does not exist in that project. |
| `409` | `THREAD_BUSY`, `NO_ACTIVE_RUN` | Another run is already active on the thread, or `/stream` was called with no active run. |
| `422` | `MODEL_NOT_CONFIGURED`, `RUNTIME_MODE_UNSUPPORTED` | No model is configured for the project, or the configured permission mode is not allowed by policy/provider. |
