# The client: AiConnect (/docs/reference/core/client)

Part of the [`@tensorpass/aiconnect` reference](/docs/reference/core). The tables are generated from the package's TypeScript source each time the docs are built. Open a row to see its full type.

## AiConnect [#aiconnect]

The site's connection to the visitor's AI, through AI Wallet. Its public members:

### AiConnectMembers

| Prop           | Type                                       | Description |
| -------------- | ------------------------------------------ | ----------- |
| `browser`      | `VisitorBrowser`                           |             |
| `installUrl`   | `string`                                   |             |
| `fetch`        | `WalletFetch`                              |             |
| `sdkOptions`   | `SdkOptions`                               |             |
| `webAccounts`  | `WebAccountId[]`                           |             |
| `signIn`       | `(account: WebAccountId) => Promise<void>` |             |
| `cancelSignIn` | `() => void`                               |             |
| `planAccess`   | `() => PlanAccess \| null`                 |             |
| `signOut`      | `() => Promise<void>`                      |             |
| `state`        | `ConnectionState`                          |             |
| `subscribe`    | `(listener: Listener) => () => void`       |             |
| `connect`      | `() => Promise<void>`                      |             |
| `disconnect`   | `() => Promise<void>`                      |             |

- **constructor.** `new AiConnect(options)` takes the optional [web account options](#web-accounts), and `new AiConnect()` works without them. In a browser, the client looks for the wallet at once and asks for the site's status. A site the visitor already approved becomes `connected` without a prompt. Built where `window` does not exist, during a server render, the client does nothing and stays `checking`.
- **installUrl.** The AI Wallet page, https://tensorpass.app/wallet, where a visitor without the wallet gets it. The connect window of `@tensorpass/aiconnect-react` links to it in the `noWallet` state.
- **state.** The current connection state.
- **subscribe(listener).** Calls `listener` with each new state and returns a function that removes it. The listener is not called with the current state when you subscribe, so read `state` first.
- **connect().** Asks the wallet to let this site use the visitor's AI. Without a wallet the state becomes `noWallet`. Otherwise it moves to `connecting`, then to the state the wallet's answer gives, usually `connected`, or to `error` with the wallet's message and, when the visitor's step says why, its `reason` (`declined`, `closed` or `interrupted`). The promise resolves in each of these cases. The first time a site connects, one wallet window takes the visitor through what the connection needs: the wallet's setup or unlock, a first account, then the approval.
- **disconnect().** Asks the wallet to remove this site from the visitor's approved sites, then sets the state to `disconnected`, or to `noWallet` without a wallet. The next `connect()` asks the visitor again. The promise rejects when the wallet refuses, for example "The wallet is locked".
- **fetch.** A `fetch` for the AI SDKs, which answers their requests through the wallet in their own protocol. See [WalletFetch](#walletfetch).
- **sdkOptions.** The options an OpenAI or Anthropic SDK client takes to answer through the wallet. See [SdkOptions](#sdkoptions).

- **webAccounts, signIn(account), cancelSignIn(), signOut().** The sign ins a visitor without the wallet is offered. See [Web accounts](#web-accounts).

The state also changes on its own when the visitor acts in the wallet: picking another account for the site, removing the site, or unlocking the wallet.

```ts
const client = new AiConnect();

client.subscribe((state) => {
  if (state.status === 'connected') {
    console.log(`Answered by ${state.providerName}`);
  }
});

document.querySelector('#connect')?.addEventListener('click', () => client.connect());
```

## ConnectionState [#connectionstate]

A union of seven states, one per `status`. Each row holds the shape of the state with that status.

### ConnectionStates

| Prop           | Type                                                            | Description |
| -------------- | --------------------------------------------------------------- | ----------- |
| `checking`     | `{ status: 'checking'; }`                                       |             |
| `connected`    | `object`                                                        |             |
| `connecting`   | `{ status: 'connecting'; }`                                     |             |
| `disconnected` | `{ status: 'disconnected'; }`                                   |             |
| `error`        | `{ status: 'error'; message: string; reason?: WalletRefusal; }` |             |
| `noWallet`     | `{ status: 'noWallet'; signInFailure?: WebSignInFailure; }`     |             |
| `signingIn`    | `{ status: 'signingIn'; account: WebAccountId; }`               |             |

| Status | Meaning |
| --- | --- |
| `checking` | The client is looking for the wallet, or the page is rendering on a server. |
| `noWallet` | No wallet answered within 300 milliseconds of the page asking for one. After a web sign in that did not go through, `signInFailure` holds the `account`, a `reason` (`declined` when the visitor cancelled on the provider's page, `failed`, or `expired` after 10 minutes) and the provider's `message`. |
| `disconnected` | The wallet answered, and this site is not connected. A wallet that is locked when the page loads reports the site this way until the visitor unlocks it. |
| `connecting` | `connect()` is waiting for the visitor in the wallet. |
| `signingIn` | `signIn(account)` is waiting for the visitor in the sign in popup, or in the tab when the browser blocked the popup. `account` is `tensorpass` or `openrouter`. |
| `connected` | The site may chat. `providerName` is the display name of the account that answers it, or `Auto`. `model` is that account's default model, absent with Auto. `session` sends chats to the wallet, or to the provider on a web account. `account` is `tensorpass` or `openrouter` on a web account, and absent on the wallet path. |
| `error` | The last `connect()` failed. `message` holds the wallet's words, and `reason` is `declined`, `closed` or `interrupted` when the visitor's step in the wallet says why. |

```ts
function label(state: ConnectionState): string {
  switch (state.status) {
    case 'connected':
      return state.model ? `${state.providerName} (${state.model})` : state.providerName;
    case 'error':
      return state.message;
    default:
      return state.status;
  }
}
```

## Web accounts [#web-accounts]

A visitor without AI Wallet signs in with OpenRouter on any site, or with the TensorPass plan on a site that passes a site key. The [web accounts page](/docs/providers/web-accounts) describes both paths and where their credentials live. The client uses a web account only when it finds no wallet.

| Option of `new AiConnect(options)` | Default | What it sets |
| --- | --- | --- |
| `siteKey` | None | The site's public [site key](/docs/quickstart/site-key). Without it, `webAccounts` holds `openrouter` only. |
| `openRouterModel` | `openrouter/auto` | The OpenRouter model of each answer. |
| `planLevel` | `quick` | The TensorPass level of each answer: `quick`, `smart` or `expert`. |
| `planGateway` | `https://plan.tensorpass.app` | The plan's gateway, for a test against another one. |

- **webAccounts.** The sign ins the connect window offers, as `WebAccountId` values: `tensorpass` when the client has a site key, then `openrouter`.
- **signIn(account).** Opens the provider's sign in in a popup, with a PKCE challenge and a state, and moves the state to `signingIn`. Call it from the visitor's click: browsers block a popup opened after an `await`. When the browser blocks it anyway, the sign in runs in the tab itself and comes back to the page that started it, through the `signInCallback` page when the client has one, and the client finishes it as the page loads. The promise resolves once the sign in page is open. Follow the outcome through `subscribe`: the state becomes `connected` once the code is traded, or `noWallet` with `signInFailure` when the visitor cancels on the provider's page or the code cannot be traded.
- **cancelSignIn().** Ends a sign in in progress and returns the state to `noWallet`. The popup closes itself on its return, so the client cannot tell when a visitor closes it; the connect window offers this as its Cancel button.
- **signOut().** Removes the credential from the site's `localStorage`, revokes a TensorPass refresh token at the plan's gateway, and sets the state to `noWallet`.

```ts
const client = new AiConnect({ siteKey: import.meta.env.VITE_TENSORPASS_SITE_KEY });

document.querySelector('#openrouter')?.addEventListener('click', () => client.signIn('openrouter'));
```

## SdkOptions [#sdkoptions]

The type of `client.sdkOptions`: the options an OpenAI or Anthropic SDK client takes to answer through the wallet.

### SdkOptions

| Prop                      | Type          | Description |
| ------------------------- | ------------- | ----------- |
| `apiKey`                  | `string`      |             |
| `fetch`                   | `WalletFetch` |             |
| `dangerouslyAllowBrowser` | `true`        |             |

- **apiKey.** A placeholder, since the SDKs require a key. The wallet does not read it.
- **fetch.** The client's [`fetch`](#walletfetch).
- **dangerouslyAllowBrowser.** `true`. The SDKs guard real keys from the browser, and no real key reaches the page.

```ts
import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';

const openai = new OpenAI(client.sdkOptions);
const anthropic = new Anthropic(client.sdkOptions);
```

## WalletFetch [#walletfetch]

The type of `client.fetch`, a function with the signature of the global `fetch`:

### WalletFetchSignature

| Prop         | Type                                                           | Description |
| ------------ | -------------------------------------------------------------- | ----------- |
| `parameters` | `[input: URL \| RequestInfo, init?: RequestInit \| undefined]` |             |
| `returns`    | `Promise<Response>`                                            |             |

It lets the AI SDK a site already uses answer through the visitor's AI. The request stays in the page: `fetch` reads neither the host the SDK targets nor its API key.

- It answers `POST` requests whose path ends with `/chat/completions` (OpenAI Chat Completions), `/responses` (OpenAI Responses), `/messages` (Anthropic Messages), or `:generateContent` and `:streamGenerateContent` (Gemini). Any other request gets a 404 with a JSON error in the shape the OpenAI, Anthropic and Google SDKs read.
- It reads the request into the wallet's chat format, asks the wallet, and answers in the same protocol, streamed or whole. The wallet answers with the account the visitor picked for the site, and the response names the model that answered. The model the request names is not used.
- It waits for the status check or the visitor's approval to end. A site that is not connected gets a 401 in the protocol's error shape, with "AI Wallet is not connected on this site" or "AI Wallet is not installed in this browser". Called outside a browser, it answers 401 with "AI Wallet answers in the browser only".
- An answer that fails before any text comes back as an HTTP error with the wallet's status, so each SDK raises its own typed error. Aborting the SDK's signal stops the chat in the wallet.

The SDKs that take a `fetch` of their own receive it directly:

```ts
import { createOpenAI } from '@ai-sdk/openai';
import { GoogleGenAI } from '@google/genai';

const openai = createOpenAI({ apiKey: client.sdkOptions.apiKey, fetch: client.fetch });
const google = new GoogleGenAI({ apiKey: client.sdkOptions.apiKey, httpOptions: { fetch: client.fetch } });
```

The [existing SDKs guide](/docs/guides/existing-sdks) covers each SDK in full.

## WalletRequestError [#walletrequesterror]

A request the wallet refused or could not answer. It extends `Error` with the request's HTTP `status`.

### WalletRequestError

| Prop      | Type                         | Description |
| --------- | ---------------------------- | ----------- |
| `status`  | `number`                     |             |
| `reason?` | `WalletRefusal \| undefined` |             |
| `code?`   | `string \| undefined`        |             |
| `name`    | `string`                     |             |
| `message` | `string`                     |             |
| `stack?`  | `string \| undefined`        |             |
| `cause?`  | `unknown`                    |             |

| Status | Cause |
| --- | --- |
| The provider's status | The provider refused the call. |
| `401` | The visitor has not connected the site. |
| `403` | The visitor declined the connection, the wallet is locked, or it holds no account. |
| `499` | The visitor stopped the answer in AI Wallet. |

AI Wallet builds its errors with its own copy of the class, so a site reads `name` and `status` and leaves `instanceof` aside. A chat aborted by the site's own signal rejects with the signal's reason instead.

```ts
try {
  transcript.push(...await runConversation({ session: state.session, tools, messages: transcript }));
} catch (error) {
  const { name, status } = error as { name?: string; status?: number };
  if (name === 'WalletRequestError' && status === 499) {
    showNotice('You stopped the answer in AI Wallet.');
  }
}
```

## McpToolSource [#mcptoolsource]

The site's tools, read from its MCP server over Streamable HTTP. It implements [`ToolSource`](/docs/reference/core/messages#tool-types).

### McpToolSourceMembers

| Prop        | Type                                                               | Description |
| ----------- | ------------------------------------------------------------------ | ----------- |
| `listTools` | `() => Promise<ToolDefinition[]>`                                  |             |
| `callTool`  | `(name: string, args: Record<string, unknown>) => Promise<string>` |             |

- **constructor.** `new McpToolSource(url, clientName)` takes the server's address, as a string or a `URL`. A relative URL resolves against the page's address, so outside a page pass an absolute one. `clientName` is the client name your MCP server sees when the client initializes, `aiconnect` by default.
- **listTools().** Connects on first use, reads the tool list once and keeps it for the life of the instance. A failed attempt is forgotten, so the next call asks the server again.
- **callTool(name, args).** Returns the result's text parts joined with line breaks. A result marked `isError` comes back as `Tool error: ` followed by its text.

```ts
const tools = new McpToolSource('/api/mcp', 'Bookshop');

const definitions = await tools.listTools();
const result = await tools.callTool('search_books', { mood: 'calm' });
```

The [MCP guide](/docs/guides/mcp-tools) covers the server side.
