# Sessions and the wallet (/docs/reference/core/wallet)

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.

## Session types [#session-types]

A `ProviderSession` answers chats. On a site it is the wallet answering with the visitor's account: the `session` of a `connected` state, with `providerId` set to `aiwallet` and `model` set to the account's default model, or an empty string with Auto, where the request's `onStart` names the account and model of each answer. Its `chat` sends one request to the wallet and resolves with the answer.

### ProviderSession [#providersession]

### ProviderSession

| Prop         | Type                                              | Description |
| ------------ | ------------------------------------------------- | ----------- |
| `providerId` | `string`                                          |             |
| `model`      | `string`                                          |             |
| `chat`       | `(request: ChatRequest) => Promise<ChatResponse>` |             |

### ChatRequest [#chatrequest]

### ChatRequest

| Prop       | Type                                        | Description |
| ---------- | ------------------------------------------- | ----------- |
| `messages` | `ChatMessage[]`                             |             |
| `tools?`   | `ToolDefinition[] \| undefined`             |             |
| `options?` | `GenerationOptions \| undefined`            |             |
| `signal?`  | `AbortSignal \| undefined`                  |             |
| `onStart?` | `((start: ChatStart) => void) \| undefined` |             |
| `onText?`  | `((delta: string) => void) \| undefined`    |             |

`onStart` receives who answers, once, before the first text or the result: the account's display name and the model the wallet asks it for. A site on Auto learns there which account the wallet picked. `onText` receives the answer's text as it streams. Aborting `signal` stops the chat in the wallet.

### ChatStart [#chatstart]

### ChatStart

| Prop           | Type     | Description |
| -------------- | -------- | ----------- |
| `providerName` | `string` |             |
| `model`        | `string` |             |

### ChatResponse [#chatresponse]

### ChatResponse

| Prop           | Type                 | Description |
| -------------- | -------------------- | ----------- |
| `message`      | `AssistantMessage`   |             |
| `finishReason` | `FinishReason`       |             |
| `model`        | `string`             |             |
| `usage?`       | `Usage \| undefined` |             |

`model` is the model that answered, as the provider named it. `usage` is absent when the provider reports no token counts.

### FinishReason [#finishreason]

Why the answer ended: it was complete, it reached the token limit, it calls tools, or the provider's filter stopped it.

### FinishReasons

| Prop            | Type              | Description |
| --------------- | ----------------- | ----------- |
| `contentFilter` | `"contentFilter"` |             |
| `length`        | `"length"`        |             |
| `stop`          | `"stop"`          |             |
| `toolCalls`     | `"toolCalls"`     |             |

### Usage [#usage]

The tokens the provider counted for the call. `inputTokens` includes `cachedInputTokens`.

### Usage

| Prop                | Type     | Description |
| ------------------- | -------- | ----------- |
| `inputTokens`       | `number` |             |
| `outputTokens`      | `number` |             |
| `cachedInputTokens` | `number` |             |

```ts
const { state } = client;
if (state.status === 'connected') {
  const response: ChatResponse = await state.session.chat({
    messages: [{ role: 'user', content: 'Summarise this page in two sentences.' }],
    onText: (delta) => output.append(delta),
  });
  if (response.finishReason === 'length') {
    output.append(' (cut at the token limit)');
  }
  const usage: Usage | undefined = response.usage;
  console.log(response.model, usage?.inputTokens, usage?.outputTokens);
}
```

## WalletLink [#walletlink]

What a site sees of the wallet: whether it may use the visitor's AI, and then which account answers it and on which model. `AiConnect` builds its `ConnectionState` from the links the wallet returns and announces. You meet this type directly when you implement the [wallet protocol](/docs/protocol/wallet-provider).

A site that is not connected:

### WalletUnlinked

| Prop        | Type    | Description |
| ----------- | ------- | ----------- |
| `connected` | `false` |             |

A connected site:

### WalletLinked

| Prop           | Type                  | Description |
| -------------- | --------------------- | ----------- |
| `connected`    | `true`                |             |
| `providerName` | `string`              |             |
| `model?`       | `string \| undefined` |             |

```ts
function describe(link: WalletLink): string {
  return link.connected ? `${link.providerName} answers this site` : 'Not connected';
}
```

## WalletProvider [#walletprovider]

The wallet as a page sees it: `window.aiwallet`, which the extension announces to every page. The [wallet protocol](/docs/protocol/wallet-provider) specifies its methods.

### WalletProvider

| Prop         | Type                                                   | Description |
| ------------ | ------------------------------------------------------ | ----------- |
| `isAIWallet` | `true`                                                 |             |
| `request`    | `function`                                             |             |
| `onLink`     | `(listener: (link: WalletLink) => void) => () => void` |             |

A chat streams its events to `onEvent`: one `start` naming who answers, then each piece of text. Aborting `signal` rejects the request with the signal's reason, and the wallet stops the chat it runs for it. `onLink` registers a listener for the visitor's changes, in the wallet, to the account or model the site answers with, and returns a function that removes it.

### WalletChatParams [#walletchatparams]

What a site sends with a `chat` request.

### WalletChatParams

| Prop       | Type                             | Description |
| ---------- | -------------------------------- | ----------- |
| `messages` | `ChatMessage[]`                  |             |
| `tools?`   | `ToolDefinition[] \| undefined`  |             |
| `options?` | `GenerationOptions \| undefined` |             |

A wallet of your own for a page's tests, set before the page creates its `AiConnect`:

```ts
const testWallet: WalletProvider = {
  isAIWallet: true,
  request: async (method, params, onEvent) => {
    if (method === 'status' || method === 'connect') {
      return { connected: true, providerName: 'Test' } satisfies WalletLink;
    }
    if (method === 'disconnect') {
      return { connected: false } satisfies WalletLink;
    }
    if (method === 'chat') {
      const { messages } = params as WalletChatParams;
      const content = `You said: ${textOf(messages.at(-1)?.content ?? '')}`;
      onEvent?.({ kind: 'start', providerName: 'Test', model: 'test' });
      onEvent?.({ kind: 'text', delta: content });
      return { message: { role: 'assistant', content }, finishReason: 'stop', model: 'test' } satisfies ChatResponse;
    }
    throw new WalletRequestError(`Unknown method ${method}`, 400);
  },
  onLink: () => () => undefined,
};

Object.assign(window, { aiwallet: testWallet });
```

### ChatEvent [#chatevent]

What a chat streams to the page before its result, in order: one `start`, sent before the first text or, when the answer has no text, before the result, then a `text` event per piece of text. The [wallet protocol](/docs/protocol/wallet-provider#streaming-events) describes them.

### ChatEvents

| Prop    | Type                               | Description |
| ------- | ---------------------------------- | ----------- |
| `start` | `{ kind: 'start'; } & ChatStart`   |             |
| `text`  | `{ kind: 'text'; delta: string; }` |             |
