Plugin: plugins/ai-bots · Plugin API: 1.3
The ai-bots plugin chooses actions for admin-assigned bots through the game:bot:decide filter (Server Hooks). Each external model sits behind one adapter file that implements DecisionProvider. This page explains how to add one. The admin guide is AI Bots (Admin); the plugin’s architecture, settings and storage keys are in plugins/ai-bots/README.md.
What an adapter does, and what it doesn’t
The decision service (src/server/decision-service.ts) runs every gate before an adapter is called: kill switches, key check, spend caps, rate limit, circuit breaker and time budget. After the call it normalises the answer against the legal moves, records spend and writes the audit record. An adapter only:
- turns a
PokerPromptModelinto the provider’s request, - makes one request, aborted by the given
AbortSignal, - turns the response into a
ProviderDecisionResult(an action, optional amount or sizing bucket, rationale, token usage), or throws one of the provider errors.
An adapter never reads the table, the engine context or storage, never retries past its budget and never validates legality itself (an illegal answer is handled by normalizeDecision, then the fallback).
The interface
src/server/providers/provider.ts:
interface DecisionProvider {
readonly id: ProviderId;
readonly family: 'reasoning' | 'classifier';
listModels(): ProviderModelInfo[]; // id, label, pricing per 1M tokens, default
decide(req: ProviderDecisionRequest, signal: AbortSignal): Promise<ProviderDecisionResult>;
healthCheck(signal: AbortSignal): Promise<{ ok: boolean; message?: string; latencyMs?: number }>;
}
interface ProviderDecisionRequest {
prompt: PokerPromptModel; // the provider-neutral spot
legal: LegalMenu; // the engine's legal actions and bet range
sizing: SizingBucket[]; // named bet sizes (third_pot, pot, all_in, ...) with exact amounts
assignment: BotAssignment; // persona, style, effort, limits
timeBudgetMs: number;
model: string; // assignment.customModel ?? assignment.model
}
ProviderDecisionResult carries action, amount?, sizingBucket?, confidence?, rationale?, usage (input, output, cached and cache-write tokens), latencyMs and, when the provider bills a different model id than the one asked for (Jev through OpenRouter bills typesafe/jev-1.14), billedModel.
Throw these on failure, so the audit log and the breaker classify it:
| Error | When | Audit reason |
|---|---|---|
ProviderTimeoutError | The signal aborted, or the provider reported a timeout | timeout |
ProviderRefusalError | The model declined to answer | refusal |
ProviderHttpError(status, message) | Non-2xx, network failure, oversized body, SSRF rejection | http-error |
ProviderInvalidResponseError | A 2xx body with no usable action | invalid-response |
ProviderConfigError | Key or base URL missing | missing-key (no breaker count) |
Pass { usage } to the error when the provider billed tokens before failing (a refusal, say), so the spend ledger still counts them.
Choosing a renderer
Use one of the two renderers in src/server/prompt/, never your own serialisation of the engine context:
| Family | Renderer | Output |
|---|---|---|
reasoning (chat or messages models) | renderText(prompt) | { system, user }: a stable system prompt (persona, style, rules, answer format; cacheable) and a short user message with the hand. answerSchema(actions) gives the JSON schema for structured output |
classifier (decision APIs that pick from labelled options) | renderState(prompt) | A state description plus one criteria string per legal action and sizing bucket |
Both start from PokerPromptModel, which is the fairness boundary: it is built field by field from the engine’s BotDecideContext, contains only the bot’s own hole cards and the board, and describes opponents’ earlier showdowns as hand classes ("A-K suited"). If your provider needs a field the model doesn’t have, add it to buildPromptModel (prompt-model.ts) from public information only, and extend the fairness fuzz test in src/__tests__/prompt.test.ts.
HTTP
Use requestJson(url, { method, headers, body, signal, fetchImpl }) from src/server/providers/http.ts. It caps the response at 256 KB, parses JSON, and returns { status, json, text }; assertOk(result, label) throws ProviderHttpError for non-2xx. An adapter whose base URL comes from settings must call assertSafeBaseUrl(url, allowPrivateNetwork, lookup) first, which resolves the host and rejects loopback, RFC 1918 and link-local targets unless the admin allowed them. Take fetchImpl (and lookup) from the factory’s deps so tests can replace them. An SDK client is fine too (the Anthropic adapter uses @anthropic-ai/sdk, bundled into dist/server), as long as it honours the signal.
Steps
- Id. Add the id to
PROVIDER_IDSinsrc/shared/constants.ts. For a paid external API also add it toEXTERNAL_PROVIDER_IDS, give it a kill-switch key inPROVIDER_TOGGLE_KEYSandSETTING_KEYS, and, for an API key, anENV_OVERRIDESentry. Add its display name toPROVIDER_LABELS(and model names toMODEL_LABELS) insrc/shared/labels.ts. - Settings. Add the key (
type: "password") and toggle (type: "toggle", defaulttrue) fields topokerEnginePlugin.configFieldsinpackage.json, and read them inreadConfig(src/server/config.ts).src/__tests__/manifest.test.tschecks the setting keys againstSETTING_KEYS. - Adapter. Write
src/server/providers/<id>.tsexportingcreate<Name>Provider(config, deps). CallthrowIfAborted(signal)first, throwProviderConfigErrorwhen the key is missing, parse the action withparseActionand numbers withfiniteNumber/probability. - Register. Add the factory to
PROVIDER_FACTORIESand the key check toproviderConfiguredinsrc/server/providers/index.ts.modelCatalogthen offers its models to assignment validation and the admin editor;GET /api/v1/admin/ai-bots/providersand the Overview card pick it up without further changes. - Prices. Add
$ / 1M tokenrows per model tosrc/catalog/price-table.jsonand runnpm run sync-manifest, which copies the table into thepriceTableJsondefault. A provider whose models are user-defined can use a wildcard row"<id>:*". - Tests. Add cases to
src/__tests__/providers.test.tswithfakeFetch/jsonResponsefromfixtures.ts: the request body (model, prompt, schema), a good answer, usage mapping, every error class, and an aborted signal. Runnpm run typecheck && npm test && npm run buildinplugins/ai-bots, thennpm run plugin:validate -- plugins/ai-bots --builtfrom the root. - Docs. Add the provider to the keys table and the cost table in
docs/guides/admin/ai-bots.md, and to the settings table in the plugin README.
Checklist
- One request per decision, cancelled by the signal; no retries that can outlive
timeBudgetMs. - Only
renderText/renderStateoutput leaves the server; no engine context, other players’ cards or server-only state in the request. - Usage is reported in tokens, uncached input separate from cached input.
- The rationale is returned as
rationaleand nothing else is done with it (the decision service stores it in the admin audit log only). - The key never appears in a log line, an error message or an admin response (
GET /providersreturnsconfigured: true|falseonly). healthCheckmakes a cheap call (a model list) and never throws.