# Assistant

Send messages and images to the Polyester AI assistant, stream its runs, decide approvals, and manage conversations, memories, assistant keys, credits, model keys, and Telegram approval limits.

`client.assistant` wraps the Polyester AI assistant. `sendMessage` starts a run that answers the message, and `watchRun` streams the run's events. A run continues on the server when nobody watches it. An action that changes the account, such as placing an order, runs only after the user approves it with `decideApproval`.

Every method needs a session JWT. Every conversation, run, approval, and memory belongs to the signed-in user; another user's is reported as not found. Errors carry `detail: { service: "assistant", code }`. Tree-shaken builds reach the same service with `assistantService(core)` from `@polyester/sdk/services/assistant`.

## Methods

| Method                      | Summary                                                        |
| --------------------------- | -------------------------------------------------------------- |
| `sendMessage`               | Record a message and start a run that answers it.              |
| `watchRun`                  | Stream a run's events, from the start or after a `seq`.        |
| `cancelRun`                 | Ask an active run to stop.                                     |
| `decideApproval`            | Approve or reject an action a run waits for.                   |
| `listConversations`         | List conversations, most recently updated first.               |
| `listMessages`              | List one conversation's messages, newest first.                |
| `getMessageImage`           | Read one image of the caller's messages.                       |
| `listMemories`              | List what the assistant remembers, newest first.               |
| `deleteMemory`              | Make the assistant forget one memory.                          |
| `prepareKeys`               | Generate the keys the assistant acts with, to register.        |
| `completeKeys`              | Finish a key setup once its keys are registered.               |
| `listKeys`                  | List the keys the assistant holds, at most one per account.    |
| `getUsage`                  | Read today's free credits and what pays for the next messages. |
| `setModelKey`               | Save the caller's own OpenAI API key.                          |
| `getModelKey`               | Read the status of the caller's own OpenAI API key.            |
| `deleteModelKey`            | Delete the caller's own OpenAI API key.                        |
| `getTelegramApprovalLimits` | Read the limits on approvals from Telegram.                    |
| `setTelegramApprovalLimits` | Replace the limits on approvals from Telegram.                 |

### `sendMessage(input, options?)`

Records the message and starts a run that answers it, returning `{ runId, conversationId }` once the run is recorded. Omit `conversationId` to start a new conversation. A conversation runs one run at a time.

```ts
const { runId, conversationId } = await client.assistant.sendMessage({
	text: "How did BTC trade this week?",
	idempotencyKey: crypto.randomUUID(),
	page: { route: "/trade/[symbol]", title: "Trade" },
	displaySettings: ["appearance", "language"],
});
```

| Field                 | Type                               | Notes                                                                      |
| --------------------- | ---------------------------------- | -------------------------------------------------------------------------- |
| `text`                | `string`                           | Plain text or Markdown, at most 16000 characters. Required without images. |
| `images`              | `{ data, mimeType }[]`             | Images the message shows the assistant. See [Images](#images).             |
| `idempotencyKey`      | `string`                           | Client-chosen, unique per caller. Reuse it when retrying.                  |
| `conversationId`      | `string`                           | Conversation to continue. Omit to start a new one.                         |
| `subject`             | `{ strategyId }`                   | Use the one conversation about this strategy. See [Subjects](#subjects).   |
| `expectedLatestRunId` | `string`                           | Send only while this run is still the conversation's latest.               |
| `subaccountId`        | `string`                           | Trading account the run reads and acts on. Omit for the main account.      |
| `accountSelection`    | `"none"`                           | The run reads no account. `subaccountId` must then be omitted.             |
| `destinations`        | `{ id, title, description? }[]`    | Places in the client the run may suggest, at most 100, distinct `id`s.     |
| `page`                | `{ route, title, destinationId? }` | The page the user is on. Omit for a client without pages.                  |
| `displaySettings`     | `AssistantDisplaySetting[]`        | Settings the client offers now and will change when a run asks, each once. |

The request is idempotent per `idempotencyKey`, which is sent exactly as given: repeat it unchanged, every field included, to resolve an unknown outcome. The same key with a different request throws `AlreadyExistsError` (`IDEMPOTENCY_CONFLICT`), and the original run stands.

`expectedLatestRunId` needs `conversationId`. Set it to the run of the answer a follow-up sits under, such as a button below that answer, so the message never lands after a newer one. When another run is the conversation's latest, nothing is recorded and the call throws `PreconditionFailedError` (`CONVERSATION_ADVANCED`): a final answer, so do not retry it. A repeat of a request already recorded returns its run, whatever ran since.

Without `subaccountId`, the run reads the main account (balances, trading accounts, API keys, price alerts, fees, and permissions) but places, changes, and cancels nothing; asked to trade, it asks the user to pick a trading account. With `accountSelection: "none"`, it reads no account and answers about the markets and Polyester only, for example when the user has given the assistant access to no account.

`page` names the page by its template and title, never by its address: never send the URL, its query or fragment, or any ID or symbol taken from the path. `route` is the route template, such as `"/account/settings/[section]"`: it starts with `/` and has at most 200 letters, digits, `/`, `-`, `_`, `.`, `[`, and `]`. `title` is 1 to 80 characters and never the user's own data. `destinationId` is the page's `destinations` id when it is one. A destination's `id` is 1 to 64 lowercase letters, digits, and hyphens, its `title` 1 to 80 characters, and its `description` at most 200.

`displaySettings` declares the display preferences the client lets the assistant change. Omit it for a client without display settings; the run then changes none. Each setting takes these values:

| Setting         | Values                                  |
| --------------- | --------------------------------------- |
| `appearance`    | `light`, `dark`, `system`               |
| `language`      | `en`, `fr`, `zh-CN`                     |
| `currency`      | A fiat code, such as `EUR`              |
| `date_format`   | A pattern, such as `yyyy-MM-dd`         |
| `time_format`   | `12h`, `24h`                            |
| `number_format` | `US`, `EU`, `SPACE`, `CH`, `IN`, `NONE` |
| `week_start`    | `0` (Sunday) to `6` (Saturday)          |
| `sounds`        | `on`, `off`                             |

### `watchRun(input, options?)`

Returns an async iterator of the run's events in `seq` order: the recorded events after `afterSeq`, then new ones as they are recorded. `afterSeq` defaults to 0, which replays the run from its first event. The stream ends after `run_completed` or `run_failed`, and watching an ended run replays it.

The server may end the stream early, or fail it with `ServiceUnavailableError`. Call `watchRun` again with the last `seq` received as `afterSeq` to continue without gaps or repeats. Stop watching with `options.signal`; the run continues.

```ts
let afterSeq = 0;
let deltas: { seq: number; text: string }[] = [];
let ended = false;

while (!ended) {
	for await (const event of client.assistant.watchRun({ runId, afterSeq })) {
		afterSeq = event.seq;
		switch (event.type) {
			case "text_delta":
				deltas.push({ seq: event.seq, text: event.text });
				break;
			case "discard_partial":
				deltas = deltas.filter((delta) => delta.seq < event.fromSeq);
				break;
			case "approval_requested":
				showApproval(event); // summary, parameters, preview, expiresAt
				break;
			case "run_completed":
			case "run_failed":
				ended = true;
				break;
		}
	}
}

const answer = deltas.map((delta) => delta.text).join("");
```

Every event has `seq` (from 1) and `createdAt` (epoch ms), and a `type`:

| `type`                   | Fields                                                                     | Meaning                                                                                                                             |
| ------------------------ | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `text_delta`             | `text`                                                                     | Markdown to append to the answer.                                                                                                   |
| `discard_partial`        | `fromSeq`                                                                  | Drop the text of every `text_delta` received so far whose `seq` is at least `fromSeq`. Regenerated text follows. Other events stay. |
| `tool_started`           | `toolCallId`, `name`, `input`, `subagentId`                                | A tool call started. `subagentId` is set for a subagent's own calls.                                                                |
| `tool_finished`          | `toolCallId`, `name`, `ok`, `errorMessage`, `subagentId`                   | A tool call finished.                                                                                                               |
| `memories_recalled`      | `toolCallId`, `memories`                                                   | Memories a `recall_memories` call found, or the memories a `memory_updates` call reports from the user's other conversations.       |
| `destinations_suggested` | `toolCallId`, `destinationIds`                                             | Up to 3 of the message's `destinations`, most relevant first. Show each as a button; skip an id the client no longer knows.         |
| `display_setting_action` | `toolCallId`, `setting`, `value`                                           | Change a display setting, or show its choices. See below.                                                                           |
| `skill_loaded`           | `name`                                                                     | The assistant loaded a skill.                                                                                                       |
| `subagent_started`       | `subagentId`, `name`, `funding`, `creditCap`                               | A subagent started a delegated task. See [Subagents](#subagents).                                                                   |
| `subagent_finished`      | `subagentId`, `name`, `ok`, `summary`, `deployUrl`, `draftVersion`         | A subagent finished its task.                                                                                                       |
| `approval_requested`     | `approvalId`, `summary`, `expiresAt`, `parameters`, `accountId`, `preview` | The run waits for `decideApproval`. See [Approvals](#approvals).                                                                    |
| `approval_resolved`      | `approvalId`, `status`                                                     | The approval was `approved`, `rejected`, `expired`, or `cancelled` (the run ended first).                                           |
| `view`                   | `view`                                                                     | Structured content to render, tagged by `view.type`.                                                                                |
| `run_completed`          | `usage`                                                                    | The run finished its answer. Last event.                                                                                            |
| `run_failed`             | `category`, `message`, `usage`                                             | The run ended without finishing its answer. Last event. Show `message` to the user.                                                 |
| `unspecified`            |                                                                            | An event this SDK build does not know. Skip it.                                                                                     |

`usage` is `{ inputTokens, outputTokens, cachedInputTokens }`, subagents included.

`view.type` is `orders_table`, `triggers_table`, `balances_table`, `price_chart`, `markdown_table`, `price_alert`, `deposit_address`, `balance_history_chart`, `equity_history_chart`, or `transfers_table`. A view this build does not know, or cannot format (for example, one on a market missing from the catalog), arrives as `unspecified`: skip it.

`run_failed` carries one of these categories, or `"unspecified"` for one this build does not know:

| `category`            | Meaning                                                                           |
| --------------------- | --------------------------------------------------------------------------------- |
| `canceled`            | `cancelRun` stopped the run.                                                      |
| `budget_exceeded`     | The run reached its step or usage budget before it could finish.                  |
| `permission_denied`   | The run needed an action the caller is not permitted to take.                     |
| `model_unavailable`   | The language model was unavailable. Send the message again later.                 |
| `unexpected_error`    | An unexpected error stopped the run.                                              |
| `model_key_refused`   | OpenAI refused the caller's [own model key](#own-model-key) for the run.          |
| `daily_limit_reached` | The main account used up today's [free credits](#credits).                        |
| `assistant_paused`    | The assistant paused new answers until 00:00 UTC. An own model key still answers. |

#### `display_setting_action`

The run asks the client to change one of the settings the message declared in `displaySettings`. Apply `value` to `setting` once, only in a run you sent and are following, never when replaying a run, and offer an undo back to the previous value. When `value` is absent, the user did not name one: show the setting's choices and change nothing until the user picks. Ignore a setting or value the client no longer accepts.

#### Subagents

A subagent is a helper the assistant delegates a task to, with its own instructions, tools, and budget, such as `"strategy-coder"`. Its own tool calls carry its `subagentId` in their `tool_started` and `tool_finished` events, so a client can show its progress under it.

`subagent_started` says what pays for its work in `funding`: `"credits"`, `"own_key"`, or `"sponsored"` (Polyester pays), or `"unspecified"` when the server does not say, in which case show no funding. `creditCap` is the most credits it may use, measured in credits even when sponsored or on the own key, or `null` when not said. Each of its model requests is limited to what is left of the cap, and it stops when the rest cannot cover one.

`subagent_finished` carries `deployUrl`, the page on the Polyester website where the user deploys the bot the subagent proposed, after MFA and a wallet signature; it is absent when it proposed none, and a subagent never deploys a bot itself. `draftVersion` is `{ strategyId, revision, versionId }`, the last strategy revision its saves are known to have landed, valid or not, whatever its outcome: a subagent stopped at its cap or by a cancel may still have saved. It is absent when no save is known to have landed; read the strategy's revisions with [`strategies`](https://testnet.polyester.com/docs/sdk/typescript/reference/strategies) then. `revision` is a decimal string from `"1"`. It only tells the client that the strategy changed: read the strategy for what it shows.

### `cancelRun(input, options?)`

Asks an active run to stop. It then ends with `run_failed` and category `"canceled"`, and its subagents stop. A pending approval of the run resolves `cancelled`, or `expired` once its expiry has passed, before `run_failed`. Canceling an ended run succeeds and changes nothing.

```ts
await client.assistant.cancelRun({ runId });
```

## Approvals

An `approval_requested` event pauses the run until the user decides, or the approval reaches `expiresAt`. Show its `summary` and `parameters` (`{ label, value }` pairs in display order), both written from the exact action. `accountId` is the trading account the action acts on. `preview` holds the action as typed values, tagged by `preview.type`: `order`, `place_orders`, `cancel_orders`, `order_change`, `trigger_change`, `cancel_trigger`, `cancel_triggers` (every trigger one approval cancels, in `triggers`, in the order the user named them), or `swap`. When it is `unspecified`, show the summary and parameters only. Approving after a `swap` preview's own `expiresAt` executes nothing.

An `order` preview, and each of a `place_orders` preview's `orders`, has the order's market, `side`, and size. `quoteProceeds` is set on a sell sized by the quote it brings in before fees instead of by `quantity`: it sells until its proceeds reach that amount, never more. Its `order` holds the order type's own values, tagged by `order.type`: `market`, `limit`, `stop_loss`, `take_profit`, `trailing_stop`, `twap`, `ladder`, `oco`, or `pegged_limit`, or `unspecified` to show the summary only.

- `oco` has a `takeProfit` and a `stopLoss` leg, each with `triggerPrice`, `triggerPriceSource`, `direction`, and a good-till-canceled `limitPrice` (absent for a market exit). Both legs share one reserve of `reservedAsset`: the base asset for a sell, the quote asset for a buy.
- `pegged_limit` is a limit order priced once, when the exchange accepts it, from `reference` (`best_bid` or `best_ask`) plus `offsetTicks` of the pair's `tickSize`. `currentPrice` is the price the peg gave when previewed, which the order's price can differ from, and `boundPrice` is the most a buy pays or the least a sell takes, not the order's price. It also has `timeInForce`, `expireAt`, and `postOnly`.

### `decideApproval(input, options?)`

Approves or rejects a pending approval and returns its status: `"pending"`, `"approved"`, `"rejected"`, `"expired"`, `"cancelled"`, or `"unspecified"`. An approved action runs exactly as its summary says, at most once. Repeating the same decision returns the recorded status.

```ts
const status = await client.assistant.decideApproval({
	approvalId: event.approvalId,
	decision: "approve", // or "reject"
});
```

A decision the other way throws `PreconditionFailedError` with `detail.code === "APPROVAL_ALREADY_DECIDED"`, and the first decision stands. An approval that expired first throws `PreconditionFailedError` with `detail.code === "APPROVAL_EXPIRED"`, and one whose run ended before the decision, for example stopped by the user, throws `APPROVAL_RUN_ENDED`; either way nothing ran. On `ServiceUnavailableError` or `TimeoutError`, retry the same request.

## Conversations

### `listConversations(input?, options?)`

Returns `{ conversations, nextPageToken }`, most recently updated first. `limit` is 1 to 100 (default 20). Pass `subject` to list only the conversation about that subject: zero or one.

### `listMessages(input, options?)`

Returns `{ messages, nextPageToken, lastAccount, subject }` for one `conversationId`, newest first. `limit` is 1 to 200 (default 50). `subject` tells a client that opened the conversation by its ID whether it is about one of the caller's strategies, and `lastAccount` is current on every page. A message's `runId` is the run that wrote it: replay it with `watchRun` from `afterSeq: 0` to show its tool activity and views.

```ts
let pageToken = "";
do {
	const page = await client.assistant.listMessages({ conversationId, limit: 200, pageToken });
	for (const message of page.messages) console.log(message.role, message.text);
	pageToken = page.nextPageToken;
} while (pageToken !== "");
```

For both lists, pass the previous `nextPageToken` as `pageToken`; an empty `nextPageToken` means there are no more.

`lastAccount` is the account the conversation's latest message selected, from any client, in `sendMessage`'s terms: pass its `accountSelection` and `subaccountId` back to `sendMessage` unchanged to keep it. On `listConversations` it is as of that list, since a message sent later may have selected another; `listMessages` returns it as it stands when the conversation is opened. Every message still names its own account.

### Subjects

A `subject` is the one thing a conversation is about: one of the caller's strategies, `{ strategyId }`. A client that shows the assistant beside a strategy names it with each message. Without `conversationId`, `sendMessage` continues the caller's conversation about that subject, or starts it: there is at most one per subject. With `conversationId`, omit `subject` or send the conversation's own; any other subject, or one for a conversation without a subject, throws `PreconditionFailedError` (`CONVERSATION_SUBJECT_MISMATCH`) and records nothing. The subject is part of the request the `idempotencyKey` covers, and it grants nothing: every read and change is still checked against the caller's own access.

```ts
const { conversations } = await client.assistant.listConversations({ subject: { strategyId } });
const { runId } = await client.assistant.sendMessage({
	text: "Why did the backtest lose money in March?",
	subject: { strategyId },
	idempotencyKey: crypto.randomUUID(),
});
```

A conversation's subject never changes once set. A conversation without one gets one at most once: when the assistant creates a strategy in it, it becomes about that strategy, unless another conversation of the caller already is; that one then keeps the subject. A second strategy created in the same conversation leaves the subject on the first.

```ts
interface AssistantConversation {
	conversationId: string;
	title: string; // "" until a title is available
	subject: AssistantSubject | undefined; // undefined for a general conversation
	lastAccount: AssistantConversationAccount | undefined; // as of this list
	createdAt: number | undefined; // epoch ms
	updatedAt: number | undefined; // when the latest message was recorded
}

interface AssistantSubject {
	strategyId: string;
}

interface AssistantConversationAccount {
	accountSelection: "none" | undefined; // "none" when the message read no account
	subaccountId: string | undefined; // undefined for the main account, or with "none"
}

interface AssistantMessage {
	messageId: string;
	role: "user" | "assistant" | "unspecified";
	text: string; // Markdown; for an assistant message, its run's final text
	createdAt: number | undefined;
	runId: string;
	images: AssistantMessageImage[]; // a user message's images, in the order sent
}

interface AssistantMessageImage {
	imageId: string; // pass to getMessageImage
	mimeType: string; // "image/png", "image/jpeg", or "image/webp"
	width: number; // pixels
	height: number;
	sizeBytes: number;
}
```

## Images

`sendMessage` takes up to 4 `images`, such as a screenshot of an order, an error, or a chart, in the order the user attached them. With images, `text` is optional and is the question about them. Each image is `{ data, mimeType }`: a PNG, JPEG, or WebP file of at most 10 MiB, 8000 pixels on a side, and 32 megapixels in all, with `mimeType` (`"image/png"`, `"image/jpeg"`, or `"image/webp"`) matching the file. The images stay with the message, so later answers in the conversation can refer to them, and the `idempotencyKey` covers them.

```ts
const { runId } = await client.assistant.sendMessage({
	text: "Why was this order rejected?",
	images: [{ data: screenshotBytes, mimeType: "image/png" }],
	idempotencyKey: crypto.randomUUID(),
});
```

`listMessages` lists a user message's images as the assistant stored them: an image over 2000 pixels on a side is scaled down to fit, and may be stored in another of the three formats.

### `getMessageImage(input, options?)`

Returns one stored image by `imageId` as `{ data, mimeType }`. An unknown ID throws `ResourceNotFoundError` (`IMAGE_NOT_FOUND`).

```ts
const image = await client.assistant.getMessageImage({ imageId: message.images[0].imageId });
const url = URL.createObjectURL(new Blob([image.data], { type: image.mimeType }));
```

## Memories

### `listMemories(input?, options?)`

Returns `{ memories, nextPageToken }`, what the assistant remembers about the user across conversations, newest first. `limit` is 1 to 200 (default 50).

```ts
interface AssistantMemory {
	memoryId: string;
	text: string;
	createdAt: number | undefined;
	conversationId: string | undefined; // where it was learned; undefined when unknown
	kind: "fact" | "planning_figure" | "profile" | "unspecified";
}
```

A `fact` is a lasting fact or preference the user stated, and a `planning_figure` a figure they stated for their own planning, never a balance. Both are used when relevant. A `profile` memory, such as the name to use or the tone of answers, applies to every answer.

### `deleteMemory(input, options?)`

Makes the assistant forget one memory by `memoryId`; later runs no longer use it. Deleting a deleted memory succeeds.

## Assistant keys

An account without an assistant key has no account tools in a conversation. Giving the assistant keys takes three calls: `prepareKeys`, then [`apiKeys.setAssistantKeys`](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#assistant-keys) with a fresh `stepUpToken`, then `completeKeys`. The step-up token goes to `setAssistantKeys` only, never to the assistant.

```ts
const setup = await client.assistant.prepareKeys({ accounts: [{}] }); // {} is the main account

await client.apiKeys.setAssistantKeys(
	{ keys: setup.keys.map((key) => ({ ...key, preset: "read_only" })) },
	{ stepUpToken }
);

const keys = await client.assistant.completeKeys({ setupId: setup.setupId });
```

### `prepareKeys(input, options?)`

The assistant generates one Ed25519 key pair per account, keeps the private keys, and returns `{ setupId, keys, expiresAt }`. `accounts` lists 1 to 64 accounts, each once; an entry without `subaccountId` is the main account. `keys` holds one key per account in request order, each with `subaccountId` (omitted for the main account), `publicKeyEd25519`, `publicKeyHex`, `registrationProof`, and `registrationDeadline`. Register them before `expiresAt` (epoch ms). A setup replaces no key until it is registered. Too many pending setups throw `RateLimitError` with `detail.code === "USAGE_LIMIT_REACHED"`: complete one or wait until it expires.

### `completeKeys(input, options?)`

Finishes the setup `setupId` once `setAssistantKeys` registered its keys, and returns the keys the assistant now holds. The assistant drops the keys the registration replaced or left out. Completing a completed setup returns the keys again.

A setup that was never prepared, expired unregistered, or was replaced by a later one throws `ResourceNotFoundError` (`KEY_SETUP_NOT_FOUND`): prepare the keys again. Keys not registered yet, or refused, throw `PreconditionFailedError` (`KEY_SETUP_NOT_REGISTERED`), and nothing changes.

### `listKeys(input?, options?)`

Lists the keys the assistant holds, at most one per account. An account without one has no account tools. Pass `{ view: "full" }` to fill each key's `label` with its account name. Revoke the keys with [`apiKeys.deleteAssistantKeys`](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#assistant-keys).

```ts
const keys = await client.assistant.listKeys({ view: "full" });

interface AssistantKey {
	subaccountId: string | undefined; // undefined for the main account
	keyId: string;
	publicKeyEd25519: Uint8Array;
	publicKeyHex: string;
	state: "active" | "disabled" | "unspecified";
	label: string; // subaccount name, only with view "full"; "" for the main account or no name
}
```

A `disabled` key was disabled when the assistant last checked it; the assistant keeps it and uses it again once it is enabled.

## Credits

The assistant answers on free daily credits, which follow the main account's VIP tier and are shared by its subaccounts, or on the caller's [own model key](#own-model-key), which uses none. Credits reset at 00:00 UTC and do not carry over. A message sent with no credits left ends with `run_failed` and category `daily_limit_reached`.

### `getUsage(options?)`

Returns the caller's credits today.

```ts
const usage = await client.assistant.getUsage();
if (usage.fundingMode === "credits" && usage.freeCreditsLeft === 0) {
	console.log("credits reset at", usage.resetsAt);
}
```

```ts
interface AssistantUsage {
	fundingMode: "credits" | "own_key"; // what pays for the next messages
	vipTier: number | undefined; // undefined when the tier could not be read; VIP 0's credits apply
	freeCredits: number; // today's free credits
	freeCreditsUsed: number; // can exceed freeCredits: an answer started with credits left finishes
	freeCreditsLeft: number;
	resetsAt: number | undefined; // epoch ms of the next 00:00 UTC
	nextTier: { vipTier: number; dailyFreeCredits: number } | undefined; // undefined at the top tier
}
```

## Own model key

A caller can save their own OpenAI API key. Messages sent after it use that key, billed to its OpenAI account, instead of credits; the per-run limits and rate limits still apply. A run uses only the key saved when its message was sent: replacing or deleting the key never moves a started run to another key or to credits. A run whose key OpenAI refuses ends with `run_failed` and category `model_key_refused`; `getModelKey` then says why in `lastCheck`.

### `setModelKey(input, options?)`

Saves `apiKey`, an OpenAI secret API key (`sk-...`), replacing any earlier one, and returns its status. The key is checked with OpenAI first and saved only when OpenAI accepts it; it is never returned or logged. Only a signed-in session sets it.

```ts
const key = await client.assistant.setModelKey({ apiKey: openAiKey });
console.log(key.suffix, key.lastCheck); // "x7Qa", "valid"
```

A key OpenAI refuses throws `PreconditionFailedError`, and nothing is saved: `MODEL_KEY_REJECTED` (mistyped, revoked, or disabled), `MODEL_KEY_NO_QUOTA` (its OpenAI account has no quota left), or `MODEL_KEY_MODEL_UNAVAILABLE` (it cannot use the assistant's model). When OpenAI cannot be reached, it throws `ServiceUnavailableError`: retry the request.

### `getModelKey(options?)`

Returns the key's status, or `null` when the caller has none.

```ts
interface AssistantModelKey {
	suffix: string; // the key's last four characters
	addedAt: number | undefined; // epoch ms
	lastCheck: "valid" | "rejected" | "no_quota" | "model_unavailable" | "unspecified";
	checkedAt: number | undefined; // epoch ms of the last check with OpenAI
}
```

### `deleteModelKey(options?)`

Deletes the key; later messages use credits again. Runs already started on it never switch. Deleting when there is no key succeeds.

## Telegram approval limits

Users can approve assistant actions from their linked Telegram account. These optional limits cap what they may approve there, in US dollars of notional value. They apply to placing orders, swapping, modifying orders or triggers, and resuming a trigger; canceling, pausing a trigger, and rejecting are never limited. Stablecoin amounts count one US dollar per unit; other amounts are valued at the current market price, and an approval that cannot be valued is refused while a limit is set.

### `getTelegramApprovalLimits(options?)`

Returns `{ perApprovalUsd, dailyUsd, approvedLast24hUsd }`. A `null` limit is no limit. `approvedLast24hUsd` is the value approved from Telegram in the last 24 hours while a limit was set, a decimal string with 2 decimal places.

### `setTelegramApprovalLimits(input, options?)`

Replaces both limits and returns `{ perApprovalUsd, dailyUsd }` as recorded. A limit left out is turned off. Only a signed-in session sets them, and they apply to the next approval from Telegram.

```ts
await client.assistant.setTelegramApprovalLimits({ perApprovalUsd: "250.50", dailyUsd: "5000" });
```

| Field            | Type     | Notes                                                                             |
| ---------------- | -------- | --------------------------------------------------------------------------------- |
| `perApprovalUsd` | `string` | Largest value of one approval: US dollars, at most 2 decimals. `"0"` allows none. |
| `dailyUsd`       | `string` | Largest total value approved in any rolling 24 hours, in the same format.         |

## Errors

Invalid input throws `ValidationError` before the request is sent. The service's refusals:

| `detail.code`                                                                       | Error                     | Meaning                                                                                                                    |
| ----------------------------------------------------------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `CONVERSATION_NOT_FOUND`, `RUN_NOT_FOUND`, `APPROVAL_NOT_FOUND`, `MEMORY_NOT_FOUND` | `ResourceNotFoundError`   | No such resource of the caller.                                                                                            |
| `KEY_SETUP_NOT_FOUND`                                                               | `ResourceNotFoundError`   | No pending key setup with this ID. Prepare the keys again.                                                                 |
| `IMAGE_NOT_FOUND`                                                                   | `ResourceNotFoundError`   | No image of the caller's messages has this ID.                                                                             |
| `IMAGE_TOO_LARGE`, `IMAGE_TYPE_UNSUPPORTED`, `TOO_MANY_IMAGES`                      | `ValidationError`         | An attached image is too large, not a PNG, JPEG, or WebP matching `mimeType`, or one of more than 4. Nothing was recorded. |
| `RUN_ACTIVE`                                                                        | `PreconditionFailedError` | The conversation has an active run. Wait for it to end, or cancel it. Nothing was recorded.                                |
| `CONVERSATION_ADVANCED`                                                             | `PreconditionFailedError` | `expectedLatestRunId` is no longer the conversation's latest run. Nothing was recorded.                                    |
| `CONVERSATION_SUBJECT_MISMATCH`                                                     | `PreconditionFailedError` | The message names a subject other than its conversation's. Nothing was recorded.                                           |
| `MODEL_KEY_REJECTED`, `MODEL_KEY_NO_QUOTA`, `MODEL_KEY_MODEL_UNAVAILABLE`           | `PreconditionFailedError` | OpenAI refused the key `setModelKey` was given. Nothing was saved.                                                         |
| `APPROVAL_ALREADY_DECIDED`, `APPROVAL_EXPIRED`, `APPROVAL_RUN_ENDED`                | `PreconditionFailedError` | The approval was decided the other way, expired, or its run ended first. The first outcome stands.                         |
| `KEY_SETUP_NOT_REGISTERED`                                                          | `PreconditionFailedError` | The setup's keys are not registered. Nothing changed.                                                                      |
| `IDEMPOTENCY_CONFLICT`                                                              | `AlreadyExistsError`      | The `idempotencyKey` was used with a different request. The original run stands.                                           |
| `USAGE_LIMIT_REACHED`                                                               | `RateLimitError`          | Too many messages, the assistant allowance is used up, or too many key setups are pending. Retry later.                    |
| `SERVICE_UNAVAILABLE`                                                               | `ServiceUnavailableError` | Retry the same request.                                                                                                    |

While the active run waits for a decision, a `RUN_ACTIVE` error's detail carries `pendingApprovalId`, the approval it waits for. Show that approval's Approve and Reject choices instead of a generic busy message.

```ts
import { PreconditionFailedError } from "@polyester/sdk";

try {
	await client.assistant.sendMessage({ conversationId, text, idempotencyKey });
} catch (err) {
	if (
		err instanceof PreconditionFailedError &&
		err.detail?.service === "assistant" &&
		err.detail.code === "RUN_ACTIVE" &&
		err.detail.pendingApprovalId
	) {
		showApproval(err.detail.pendingApprovalId);
	} else {
		throw err;
	}
}
```

Assistant requests are rate limited under the `assistant_message`, `assistant_control`, and `assistant_read` policy classes. See [Rate-limit details](https://testnet.polyester.com/docs/sdk/typescript/reference/errors#rate-limit-details).

## Related

- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#assistant-keys) for registering and revoking assistant keys.
- [Strategies](https://testnet.polyester.com/docs/sdk/typescript/reference/strategies) for the strategies a conversation can be about and its subagents save.
- [Notifications](https://testnet.polyester.com/docs/sdk/typescript/reference/notifications) for the `telegram_approval` notices of actions approved from Telegram.
- [Price alerts](https://testnet.polyester.com/docs/sdk/typescript/reference/price-alerts) for the alerts a run can read and show.
- [Errors](https://testnet.polyester.com/docs/sdk/typescript/reference/errors) for the error type reference.
