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

# Stream a live agent chat with the TypeScript SDK

> Follow a Reliant run's chat live from TypeScript: messages, questions and workflow status as they happen, resumed from a saved cursor after a disconnect.

By the end of this guide, a short TypeScript program follows one of your Reliant runs as it happens, printing each message and status change, then closes and picks up where it left off without fetching the chat again. That is the same live stream, resume and state the Reliant app itself is built on, from [`@reliantlabs/sdk`](https://docs.reliantlabs.io/sdk/typescript), so you can put a run's progress in your own tools: an internal dashboard, a status page for your team, a script.

## Before you begin

* The `reliant` CLI, v1.21 or later, signed in ([Sign in and tokens](https://docs.reliantlabs.io/cli/sign-in.md)), and an API token in `RELIANT_TOKEN` for this local script ([Credentials](https://docs.reliantlabs.io/sdk/overview.md#credentials)).
* Node 22.18 or newer, which runs a `.ts` file directly.
* A workflow to watch. This guide uses `release-check` from [Start and follow agent runs from a Go service](https://docs.reliantlabs.io/guides/workflows/start-runs-from-go.md), which needs no model and waits on a question.

**1. Install the SDK**

The package is not on the npm registry yet. Build `reliantlabs-sdk-0.1.0.tgz` from the Reliant repository as [the TypeScript SDK page](https://docs.reliantlabs.io/sdk/typescript.md#install) describes, then install it with its peer dependencies and a Connect transport:

```bash terminal theme={null}
npm init -y && npm pkg set type=module
npm install ./reliantlabs-sdk-0.1.0.tgz @bufbuild/protobuf @connectrpc/connect \
  @connectrpc/connect-web @opentelemetry/api @reliantlabs/forge-web-runtime
```

**2. Start a run to watch**

```bash terminal theme={null}
reliant workflow run release-check --project-id <project-id> \
  --input version=v1.5.0 --message "Check release v1.5.0"
```

Copy the `Chat/Execution ID` it prints: a run lives in a chat, and the stream is per chat.

**3. Write the watcher**

```ts watch.ts theme={null}
// watch.ts — print a Reliant run's chat as it happens, then resume it.
import { createConnectTransport } from "@connectrpc/connect-web";
import {
  createReliantClient,
  staticTokenProvider,
  type ChatSession,
  type ChatState,
} from "@reliantlabs/sdk/client";

const chatId = process.argv[2];
const reliant = createReliantClient({
  baseUrl: "https://api.reliantapi.com",
  auth: staticTokenProvider(process.env.RELIANT_TOKEN!),
  createTransport: ({ baseUrl, interceptors }) =>
    createConnectTransport({ baseUrl, interceptors }),
});

// open subscribes to the chat and prints what changes, starting from `from`
// when you have a state to resume, or from a snapshot when you do not.
function open(from?: ChatState): ChatSession {
  let seen = from?.messages.length ?? 0;
  let status = "";
  const chat = reliant.chat({
    chatId,
    initialState: from,
    hooks: {
      onCaughtUp: (i) =>
        console.log(`caught up: ${i.sync}, ${i.replayedUpdates} update(s) replayed`),
    },
  });
  chat.subscribe(() => {
    const s = chat.getState();
    for (const m of s.messages.slice(seen)) {
      console.log("message:", m.contentBlocks.map((b) => b.content ?? "").join(" "));
    }
    seen = s.messages.length;
    const wf = Object.values(s.workflowStatus).map((w) => `${w.workflow_name} ${w.status}`).join(", ");
    if (wf && wf !== status) console.log("workflow:", (status = wf));
  });
  return chat.start();
}

const first = open();
await new Promise((r) => setTimeout(r, 8000));
const saved = first.getState();
console.log(`closing at cursor ${saved.cursor}, ${saved.pendingQuestions.length} question(s) pending`);
first.close();

// Answer the question elsewhere (the app, or `reliant workflow answer`), then press Enter.
process.stdin.once("data", async () => {
  const second = open(saved);
  await new Promise((r) => setTimeout(r, 8000));
  second.close();
  process.exit(0);
});
```

`reliant.chat()` returns a `ChatSession`. It opens the chat's stream, folds every update into one state object, and calls your listener on each change. `onCaughtUp` reports how each connection synced: a `snapshot` of the whole chat, or a `replay` of what was missed since the state's `cursor`. Passing a saved state as `initialState` is what turns the second connection into a replay.

**4. Run it, answer, and watch it resume**

```bash terminal theme={null}
node watch.ts <chat-id>
```

After eight seconds the first connection closes with the question still pending. Answer it from another terminal with `reliant workflow answer <chat-id> --select Ship` (or in the app), then press Enter:

```text theme={null}
message: Check release v1.5.0
caught up: snapshot, 0 update(s) replayed
closing at cursor 7, 1 question(s) pending
message: Ship
message: Release v1.5.0 cleared to ship.
workflow: release-check completed
caught up: replay, 7 update(s) replayed
```

The second connection started from cursor 7 and received only the seven updates since then, among them the answer, the final message and the completion, not the whole chat again. The same happens on its own when a connection drops: the session reconnects with backoff and asks for everything after its cursor.

**5. Move it into a browser**

In a frontend, swap `staticTokenProvider` for an `AuthTokenProvider` over the signed-in user's own session (`getToken`, `hasSession`, `refresh`), and feed `chat.subscribe` and `chat.getState` to your framework's external-store hook, such as React's `useSyncExternalStore`. Never ship an API token to a browser ([Where the token comes from](https://docs.reliantlabs.io/sdk/typescript.md#where-the-token-comes-from)). To resume across a page reload, save the state yourself: its `cursor` is a `bigint` and some fields are `Map`s and `Set`s, so write a serializer rather than `JSON.stringify`.

## What this does not do

* **It shows a signed-in user their own chats.** Every stream acts as the Reliant user whose credential it holds, and a chat that is not theirs is refused. It is not a way to give your own customers a chat with your app.
* **It doesn't start runs or answer questions.** The TypeScript SDK streams chats and sends messages. Starting runs, answering questions and firing triggers are in the [Go SDK](https://docs.reliantlabs.io/sdk/go.md), on your server.
* **It doesn't decide approvals.** The state lists pending approvals so you can show them; deciding one takes a person in the app.

## Troubleshooting

> [accordion] The session sets an error and stops reconnecting
>
> The server refused the chat: it does not exist, or is not the signed-in user's. The two cases look the same on purpose. Check the chat ID and whose token `getToken` returns.

> [accordion] Cannot read properties of null (reading 'edgesOut')
>
> `npm install` in a copy of `sdk/ts` failed while resolving peer dependencies. Install there with `npm install --legacy-peer-deps`, or build it inside the repository's `frontends/web` workspace with `pnpm install`.

## Next steps

> [card] [Start runs from Go](https://docs.reliantlabs.io/guides/workflows/start-runs-from-go.md)
>
> Start the runs this watcher follows, from your server.

> [card] [TypeScript SDK reference](https://docs.reliantlabs.io/sdk/typescript.md)
>
> Sends with retry, tool bodies, the reducer on its own.

> [card] [Pause and steer a run](https://docs.reliantlabs.io/guides/workflows/pause-and-steer-a-run.md)
>
> Change what a running agent does from the app or the CLI.

> [card] [SDK credentials and scopes](https://docs.reliantlabs.io/sdk/overview.md#credentials)
>
> Which token goes where, and what each scope allows.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.