Skip to Content
TensorPass
Reference@tensorpass/aiconnect

The client: AiConnect

AiConnect, the site's connection to the visitor's AI through AI Wallet, its connection states and options, the fetch for AI SDKs, WalletRequestError and the MCP tool source, with their types generated from the source.

Part of the @tensorpass/aiconnect reference. 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

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

Prop

Type

  • constructor. new AiConnect(options) takes the optional web account options, 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.

  • sdkOptions. The options an OpenAI or Anthropic SDK client takes to answer through the wallet. See SdkOptions.

  • webAccounts, signIn(account), cancelSignIn(), signOut(). The sign ins a visitor without the wallet is offered. See 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.

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

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

Prop

Type

StatusMeaning
checkingThe client is looking for the wallet, or the page is rendering on a server.
noWalletNo 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.
disconnectedThe 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.
connectingconnect() is waiting for the visitor in the wallet.
signingInsignIn(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.
connectedThe 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.
errorThe 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.
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

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 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)DefaultWhat it sets
siteKeyNoneThe site's public site key. Without it, webAccounts holds openrouter only.
openRouterModelopenrouter/autoThe OpenRouter model of each answer.
planLevelquickThe TensorPass level of each answer: quick, smart or expert.
planGatewayhttps://plan.tensorpass.appThe 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.
const client = new AiConnect({ siteKey: import.meta.env.VITE_TENSORPASS_SITE_KEY });

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

SdkOptions

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

Prop

Type

  • apiKey. A placeholder, since the SDKs require a key. The wallet does not read it.
  • fetch. The client's fetch.
  • dangerouslyAllowBrowser. true. The SDKs guard real keys from the browser, and no real key reaches the page.
import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';

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

WalletFetch

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

Prop

Type

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:

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 covers each SDK in full.

WalletRequestError

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

Prop

Type

StatusCause
The provider's statusThe provider refused the call.
401The visitor has not connected the site.
403The visitor declined the connection, the wallet is locked, or it holds no account.
499The 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.

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

The site's tools, read from its MCP server over Streamable HTTP. It implements ToolSource.

Prop

Type

  • 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.
const tools = new McpToolSource('/api/mcp', 'Bookshop');

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

The MCP guide covers the server side.

On this page