> For the complete documentation index, see [llms.txt](https://docs.uptiq.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.uptiq.ai/platform/console/agent-builder/deploy/agent-integration/typescript-sdk-client.md). Agents can also search and read this documentation through its [MCP server](https://docs.uptiq.ai/~gitbook/mcp).

# TypeScript SDK client

Drive your agent from your own code with the headless TypeScript SDK client, its instance API, a React example and best practices.

{% hint style="info" %}
**Versions are per agent.** Read the SDK version and Executor version from your own agent's **Agent Config Panel**, and use those in your app and API calls. The values shown in the samples on this page are placeholders.
{% endhint %}

{% hint style="warning" %}
**`<BASE_URL>` in every sample on this page** is a placeholder for the Uptiq Platform API host your organization uses. Confirm your production host with your Uptiq contact or your platform administrator before you ship — it differs by deployment, and a sample host will not work against your environment. (The panel's own "Download as MD" export shows a real host for your environment — copy the sample from there once you've confirmed it's the right one for where you're shipping.)
{% endhint %}

Select **TypeScript SDK** as the Client to drive the agent from your own code instead of raw HTTP. The **Headless Agent JS SDK** lets you build a custom chat interface while it handles the socket connection, real-time agent events, and file uploads automatically. Runs in the browser (React, Vue, or vanilla JS). Entry point: `createHeadlessAgentInstance(params)`, which returns an instance with `emit()`, `on()`, and `cleanup()` methods.

**Install & import**

```bash
npm install @uptiqai/widgets-sdk@1.295.0
```

```ts
import { createHeadlessAgentInstance } from '@uptiqai/widgets-sdk';
// TypeScript projects also import the types:
import type { HeadlessAgentInstance, AgentInterruptEvent } from '@uptiqai/widgets-sdk';
```

Authentication uses the **Widget Key**; your application's domain must be whitelisted (see **Shared prerequisites** in [Integrate Agent](https://docs.uptiq.ai/platform/console/agent-builder/deploy/agent-integration.md#choosing-an-integration)).

## Create an instance

```ts
const instance = createHeadlessAgentInstance({
  config: { serverUrl: '<BASE_URL>', agentId: '<agent-id>', widgetKey: '<your-widget-key>', agentExecutorVersion: '1.4' },
  user: { uid: 'user-123', firstName: 'Jane', lastName: 'User', email: 'jane@example.com' },
  instanceId: 'my-chat-instance',
});
```

| Parameter    | Type           | Required | Description                                                                                                                                                  |
| ------------ | -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `config`     | `WidgetConfig` | Yes      | `serverUrl`, `agentId`, `widgetKey`, optional `agentExecutorVersion`.                                                                                        |
| `user`       | `WidgetUser`   | Yes      | `uid`, `firstName`, `email` (required); `lastName` (optional).                                                                                               |
| `instanceId` | string         | Yes      | Unique identifier used for socket scoping.                                                                                                                   |
| `authToken`  | string         | No       | The signed-in user's identity token, for an agent with [Authentication](https://docs.uptiq.ai/platform/console/agent-builder/deploy/authentication-1.md) on. |

## Instance API

| Method         | Signature                                           | Description                                                                                        |
| -------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `emit`         | `(event: 'query', payload: QueryPayload) => void`   | Send a query to the agent, optionally with file attachments.                                       |
| `on`           | `(event: 'agent-interrupt', handler) => () => void` | Subscribe to agent events. Returns an unsubscribe function.                                        |
| `cleanup`      | `() => void`                                        | Remove listeners and disconnect the socket (call on unmount).                                      |
| `setAuthToken` | `(token?: string) => void`                          | Replace the identity token sent with every later message, for example after your app refreshes it. |

<details>

<summary>Sending messages — emit('query', payload)</summary>

| Property      | Type     | Required | Description                                                  |
| ------------- | -------- | -------- | ------------------------------------------------------------ |
| `content`     | string   | Yes      | The user's message text (use `' '` when sending only files). |
| `executionId` | string   | No       | Existing execution ID to continue a conversation.            |
| `files`       | `File[]` | No       | Browser `File` objects to upload and attach.                 |

The SDK obtains presigned upload URLs, uploads each file to cloud storage, and attaches the metadata to the message automatically. Pass the `File` objects.

```ts
// New conversation
instance.emit('query', { content: 'Hello, can you help me?' });

// With attachments
instance.emit('query', { content: 'Analyze these documents', files: [file1, file2] });

// Continue an existing conversation
instance.emit('query', { content: 'Tell me more', executionId: 'existing-execution-uuid' });

// Files only (no text)
instance.emit('query', { content: ' ', files: [selectedFile] });
```

</details>

<details>

<summary>Receiving events — on('agent-interrupt', handler)</summary>

The handler receives an `AgentInterruptEvent`; branch on its `type`:

| Event `type`    | Description                  | Key fields           |
| --------------- | ---------------------------- | -------------------- |
| `agent_message` | Agent text response          | `content`, `subtype` |
| `status_update` | Progress indicator           | `status`             |
| `done`          | Execution completed          | `content` (optional) |
| `error`         | Error occurred               | `error`              |
| `tool_call`     | Agent is calling a tool      | tool details         |
| `tool_result`   | Tool call completed          | tool result          |
| `plan_update`   | Agent created/updated a plan | plan details         |

`agent_message` events carry a `subtype`: `intermediate` (streaming), `final` (complete), `question` (needs user response), `final_stream`, `output_files`, `ask_permission`.

{% hint style="warning" %}
**Don't filter only by `subtype === 'final'`** or you'll miss agent questions and streamed replies — handle `final`, `question`, and `final_stream` at minimum.
{% endhint %}

```ts
const unsubscribe = instance.on('agent-interrupt', event => {
  switch (event.type) {
    case 'agent_message':
      if (['final', 'question', 'final_stream'].includes(event.subtype) && event.content) {
        displayMessage({ role: 'agent', content: event.content });
      }
      break;
    case 'error':
      displayMessage({ role: 'system', content: event.error ?? 'An error occurred' });
      break;
    case 'status_update':
    case 'done':
    case 'tool_call':
    case 'tool_result':
    case 'plan_update':
      // optional UI handling
      break;
    default:
      console.log('Unknown event type:', event.type);
  }
});
```

</details>

<details>

<summary>Cleanup</summary>

Always call `cleanup()` (and the unsubscribe function) when you're done — e.g. on component unmount:

```ts
unsubscribe();
instance.cleanup();
```

</details>

## React integration example

```tsx
import { createHeadlessAgentInstance } from '@uptiqai/widgets-sdk';
import type { HeadlessAgentInstance, AgentInterruptEvent } from '@uptiqai/widgets-sdk';
import { useEffect, useRef, useState } from 'react';

const config = { serverUrl: '<BASE_URL>', agentId: '<agent-id>', widgetKey: '<your-widget-key>', agentExecutorVersion: '1.4' };
const user = { uid: 'user-123', firstName: 'Jane', lastName: 'User', email: 'jane@example.com' };

export const ChatComponent = () => {
  const [messages, setMessages] = useState<Array<{ role: 'user' | 'agent'; content: string }>>([]);
  const instanceRef = useRef<HeadlessAgentInstance | null>(null);

  useEffect(() => {
    const instance = createHeadlessAgentInstance({ config, user, instanceId: 'my-chat-instance' });
    instanceRef.current = instance;

    const unsubscribe = instance.on('agent-interrupt', (event: AgentInterruptEvent) => {
      if (event.type === 'agent_message'
          && ['final', 'question', 'final_stream'].includes(event.subtype ?? '')
          && event.content) {
        setMessages(prev => [...prev, { role: 'agent', content: event.content! }]);
      }
    });

    return () => { unsubscribe(); instance.cleanup(); };
  }, []);

  const sendMessage = (text: string, files?: File[]) => {
    setMessages(prev => [...prev, { role: 'user', content: text }]);
    instanceRef.current?.emit('query', { content: text, files });
  };

  return <div>{messages.map((m, i) => <div key={i}>{m.role}: {m.content}</div>)}</div>;
};
```

<details>

<summary>TypeScript types</summary>

```ts
import type {
  HeadlessAgentInstance,
  QueryPayload,
  AgentInterruptEvent,
  CreateHeadlessAgentInstanceParams,
} from '@uptiqai/widgets-sdk';

type HeadlessAgentInstance = {
  emit: (event: 'query', payload: QueryPayload) => void;
  on: (event: 'agent-interrupt', handler: (event: AgentInterruptEvent) => void) => () => void;
  cleanup: () => void;
};

type QueryPayload = { content: string; executionId?: string; files?: File[] };
```

</details>

## Best practices

* **Single instance** — create one instance per chat context and reuse it for the whole conversation.
* **Subscribe before sending** — attach your `on('agent-interrupt', …)` handler before the first `emit` so no responses are missed.
* **Handle multiple subtypes** — capture `final`, `question`, and `final_stream`, not only `final`.
* **Always clean up** — call `cleanup()` on unmount to prevent memory leaks.
* **Persist `executionId`** — store and pass it to continue a conversation across page reloads.
* **Let the SDK handle uploads** — pass `File` objects; presigned-URL upload is automatic.

{% hint style="info" %}
The SDK manages socket connections and reconnection automatically, and shares the socket across instances that use the same `user` and `config`. For server-side or backend-only execution with no browser, use the **raw (HTTP)** client instead.
{% endhint %}

## Related

* [Integrate Agent](https://docs.uptiq.ai/platform/console/agent-builder/deploy/agent-integration.md)

***

{% columns %}
{% column width="83.33333333333334%" %}

<p align="right"><em>Maintained by</em> <mark style="color:green;">Abhishek Paul</mark><br><code>AI-assisted, human-approved</code></p>
{% endcolumn %}

{% column width="16.666666666666664%" %}

<div align="left"><img src="https://1326225582-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0qmgQjJ5aArDTj2ACFHG%2Fuploads%2Fgit-blob-d034645b4f8f8ee661985f5306b60ded3289653c%2Fmaintainer-abhishek-paul.png?alt=media" alt="" width="60"></div>
{% endcolumn %}
{% endcolumns %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.uptiq.ai/platform/console/agent-builder/deploy/agent-integration/typescript-sdk-client.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
