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
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.
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"],
});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:
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.
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:
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:
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 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.
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.
ocohas atakeProfitand astopLossleg, each withtriggerPrice,triggerPriceSource,direction, and a good-till-canceledlimitPrice(absent for a market exit). Both legs share one reserve ofreservedAsset: the base asset for a sell, the quote asset for a buy.pegged_limitis a limit order priced once, when the exchange accepts it, fromreference(best_bidorbest_ask) plusoffsetTicksof the pair'stickSize.currentPriceis the price the peg gave when previewed, which the order's price can differ from, andboundPriceis the most a buy pays or the least a sell takes, not the order's price. It also hastimeInForce,expireAt, andpostOnly.
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.
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.
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.
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.
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.
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).
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).
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 with a fresh stepUpToken, then completeKeys. The step-up token goes to setAssistantKeys only, never to the
assistant.
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.
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, 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.
const usage = await client.assistant.getUsage();
if (usage.fundingMode === "credits" && usage.freeCreditsLeft === 0) {
console.log("credits reset at", usage.resetsAt);
}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.
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.
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.
await client.assistant.setTelegramApprovalLimits({ perApprovalUsd: "250.50", dailyUsd: "5000" });Errors
Invalid input throws ValidationError before the request is sent. The service's refusals:
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.
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.
Related
- API keys for registering and revoking assistant keys.
- Strategies for the strategies a conversation can be about and its subagents save.
- Notifications for the
telegram_approvalnotices of actions approved from Telegram. - Price alerts for the alerts a run can read and show.
- Errors for the error type reference.