AgentsKit Chat

Server handler

Mount createChatHandler for Web-standard streaming turns with session CAS and auth.

View canonical Markdown

Web-standard server handler

createChatHandler mounts one shared ChatDefinition behind platform Request, Response, ReadableStream, and AbortSignal.

For grounded Q&A after deterministic misses, use createAskServiceHandler.

Turn flow

Loading diagram...

Minimal handler

code
import { createChatHandler } from '@agentskit/chat/server'

const handleChat = createChatHandler({
  authenticate: async request => {
    const identity = await verifyBearer(request)
    return identity
      ? { ok: true, context: identity }
      : { ok: false, response: new Response('Unauthorized', { status: 401 }) }
  },
  resolveDefinition: context => chats.forTenant(context?.tenantId),
  sessionStorage: context => sessions.forTenant(context?.tenantId),
  timeoutMs: 30_000,
})

export const POST = (request: Request) => handleChat(request)

Request / response

DirectionFormat
Request bodyapplication/json encoded client.turn.submit or client.action.decide
Success bodyapplication/x-ndjson — one encoded turn event per line
DecodedecodeTurnEvent from @agentskit/chat/protocol

Auth completes before parsing untrusted JSON. Trusted context lives only in the host closure — never from the submit payload.

Sessions and memory

sessionStorage is required: cursor, active-turn lease, and recent terminal turns prevent rollback, concurrent execution, and replay of tool effects.

Confirmed actions across requests

Pass decisions to accept client.action.decide. It returns the upstream ToolDecisionStore for the authorized tenant and session; @agentskit/chat/drizzle-pg ships a PostgreSQL one.

code
import { chatDecisionDDL, createDrizzleDecisionStore, createDrizzleSessionStorage } from '@agentskit/chat/drizzle-pg'

// Apply chatDecisionDDL once in a migration.
const handleChat = createChatHandler({
  authenticate,
  resolveDefinition: context => chats.forTenant(context?.tenantId),
  sessionStorage: context => createDrizzleSessionStorage(db, context!.tenantId),
  decisions: (context, sessionId) => createDrizzleDecisionStore(db, context!.tenantId, sessionId),
})

A tool with requiresConfirmation then stops its turn as pending. The decision can arrive in another request or on another instance: the store's atomic claim lets one request execute the tool, and the model continues in that request's stream. Repeating a settled decision replays the stored result.

StatusCodeMeaning
404ACTION_NOT_FOUNDNo pending action has this token
409ACTION_ALREADY_DECIDEDAnother decision won, or is being applied
409SESSION_BUSY / SESSION_CONFLICTAnother turn holds the session; retry
501ACTION_DECIDE_UNAVAILABLEThe host did not configure decisions

Keep definition.chat.memory configured: the decision resumes from the stored messages. The claim is not a transaction with your domain write, so keep unique(tool_call_id) on tables written by tools.

Spend limits

Pass cost to meter turns against a durable CostStore from @agentskit/observability.

code
import { postgresCostStore } from '@agentskit/observability/postgres'

const handleChat = createChatHandler({
  // ...
  cost: async context => ({
    store: postgresCostStore({ db }),
    tenant: context!.tenantId,
    capUsd: await plans.capFor(context!.tenantId), // your entitlements
    reserveUsd: 0.002,
    priceUsd: usage => (usage.promptTokens * 0.1 + usage.completionTokens * 0.4) / 1_000_000,
    model: 'google/gemini-2.5-flash-lite',
  }),
})

The handler reserves reserveUsd before the model runs, commits the real cost with a ledger entry after model dispatch, including failed, timed-out, or cancelled turns. When usage is unknown it charges the reservation; it releases the reservation only if no model call started. A turn the client cancels (request abort or response cancel) charges only its real cost, at least cancelMinimumUsd (default 0), so a turn cancelled before any token usage never costs the whole reservation; a server timeout still charges the reservation. A turn that does not fit the cap gets 402 QUOTA_EXCEEDED and never reaches the model. A custom createId must generate unique IDs on every call; a constant value can reuse a reservation and bypass the quota. The first snapshot carries quota.utilization and quota.warning (true from 80% by default, warnAt to change) for a usage bar.

Erasing a tenant's data

eraseTenantChatData erases all chat data of one tenant in a single call (LGPD data-subject erasure): sessions, decisions, memory, and cost records. Each category runs through an eraser you provide, scoped to the tenant:

code
import { eraseTenantChatData } from '@agentskit/chat/server'

const receipt = await eraseTenantChatData({
  tenant: 'tenant-123',
  sessions: tenant => db.deleteWhere('agentskit_chat_sessions', { tenant_id: tenant }),
  decisions: tenant => db.deleteWhere('agentskit_chat_decisions', { tenant_id: tenant }),
  memory: tenant => db.deleteWhere('chat_messages', { tenant_id: tenant }),
  cost: tenant => db.deleteWhere('agentskit_cost_window', { tenant_id: tenant }), // and its reservation and ledger tables
})
// receipt.erased → { sessions, decisions, memory, cost } counts

All four erasers are required, so pass () => 0 for a category you do not store. Each eraser must be idempotent and must delete only that tenant's records. A failure in one category does not stop the others; the call then throws TenantErasureError with the failed categories, and you can retry it safely. Stop accepting turns for the tenant before you erase (for example, refuse the tenant in authenticate). Otherwise a turn already running can write again. See ADR-0041.

Limits and failures

DefaultValue
Body limit64 KiB
Deadline30 s

Method, media type, body, event, timeout, cancellation, and internal failures emit safe versioned diagnostics. Request abort / response cancel / timeout stop the upstream AgentsKit controller.

Where to mount

HostPattern
Next / Remix / SvelteKit / edgeExport the handler where Web handlers are supported
Node HTTPTranslate to Request, pipe Response.body
Express / HonoThin bridge; forward disconnect cancellation

Full recipes: Deployment.