Writing an AI Decision Provider

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:

  1. turns a PokerPromptModel into the provider’s request,
  2. makes one request, aborted by the given AbortSignal,
  3. 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:

ErrorWhenAudit reason
ProviderTimeoutErrorThe signal aborted, or the provider reported a timeouttimeout
ProviderRefusalErrorThe model declined to answerrefusal
ProviderHttpError(status, message)Non-2xx, network failure, oversized body, SSRF rejectionhttp-error
ProviderInvalidResponseErrorA 2xx body with no usable actioninvalid-response
ProviderConfigErrorKey or base URL missingmissing-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:

FamilyRendererOutput
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

  1. Id. Add the id to PROVIDER_IDS in src/shared/constants.ts. For a paid external API also add it to EXTERNAL_PROVIDER_IDS, give it a kill-switch key in PROVIDER_TOGGLE_KEYS and SETTING_KEYS, and, for an API key, an ENV_OVERRIDES entry. Add its display name to PROVIDER_LABELS (and model names to MODEL_LABELS) in src/shared/labels.ts.
  2. Settings. Add the key (type: "password") and toggle (type: "toggle", default true) fields to pokerEnginePlugin.configFields in package.json, and read them in readConfig (src/server/config.ts). src/__tests__/manifest.test.ts checks the setting keys against SETTING_KEYS.
  3. Adapter. Write src/server/providers/<id>.ts exporting create<Name>Provider(config, deps). Call throwIfAborted(signal) first, throw ProviderConfigError when the key is missing, parse the action with parseAction and numbers with finiteNumber / probability.
  4. Register. Add the factory to PROVIDER_FACTORIES and the key check to providerConfigured in src/server/providers/index.ts. modelCatalog then offers its models to assignment validation and the admin editor; GET /api/v1/admin/ai-bots/providers and the Overview card pick it up without further changes.
  5. Prices. Add $ / 1M token rows per model to src/catalog/price-table.json and run npm run sync-manifest, which copies the table into the priceTableJson default. A provider whose models are user-defined can use a wildcard row "<id>:*".
  6. Tests. Add cases to src/__tests__/providers.test.ts with fakeFetch / jsonResponse from fixtures.ts: the request body (model, prompt, schema), a good answer, usage mapping, every error class, and an aborted signal. Run npm run typecheck && npm test && npm run build in plugins/ai-bots, then npm run plugin:validate -- plugins/ai-bots --built from the root.
  7. 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 / renderState output 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 rationale and 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 /providers returns configured: true|false only).
  • healthCheck makes a cheap call (a model list) and never throws.
Try the live demo Pricing

Have questions about Poker Engine? We reply fast.