SDK reference
Everything `@onkeiki/agents` exports — agents, tools, alerts, entities, plugins, capability manifests, and service adapters.
@onkeiki/agents is the SDK you use to
define, configure, sync and self-host a Keiki agent. It is Effect-based and declarative: you
describe the agent once, then either push it to the cloud with kit.sync() or run the loop
yourself with kit.serve(). This page is the complete public API surface — the export list in
packages/core/src/index.ts
is canonical, and everything it exports appears here.
bun add @onkeiki/agents @onkeiki/agents-storage-postgresimport { Effect } from 'effect'
import { create } from '@onkeiki/agents'
import { PostgresStorage } from '@onkeiki/agents-storage-postgres'
const kit = create({
apiKey: process.env.KEIKI_API_KEY!,
name: 'My Agent',
resolveNumber: (ctx) => Effect.succeed(process.env.SMS_LINE!),
storage: PostgresStorage({ connectionString: process.env.DATABASE_URL! }),
agent: {
model: 'google/gemini-3.5-flash',
maxSteps: 10,
historyLimit: 40,
systemPrompt: ({ now }) => `You are a helpful assistant. Current time: ${now.toISOString()}`,
tools: [],
},
})
// Cloud-served: the platform runs the agentic loop.
await kit.sync()
// Self-hosted: run the loop yourself instead.
// await kit.serve({ port: 8789 })Cloud configuration in depth — tools, plugins, managed features, observability, storage, numbers and alerts — is covered in Cloud-served agents; this page maps the surface itself.
Agent lifecycle
| Export | Kind | Purpose |
|---|---|---|
AgentKit.create(config) | function | Create an agent instance. |
create(config) | function | Alias for AgentKit.create. |
AgentKitInstance | type | The instance: sync, serve, handleInbound, shutdown. |
ResolvedPlugins | type | Aggregated plugin state. |
-
kit.sync()pushes the full declarative config to the platform: the rendered system prompt, merged tools (bundled for cloud execution), tool policies, model and step/history limits, harness, feature flags, loop presets, user connections, capabilities, alerts and developer secrets. It is the infrastructure-as-code operation; run it on every deploy. -
kit.serve({ port?, host? })starts the HTTP server that receives turn requests from the platform and runs the loop on your machine. It syncs first. -
harnessselects the turn runner. It defaults to{ type: 'flue' }(Keiki-hosted);{ type: 'hermes' }selects Hermes (guide). For an app that runs its own async loop, such as eve, Flue or AI SDK, use the external harness:TypeScriptharness: { type: 'external', connectivity: 'push', dispatchUrl: 'https://agent.example.com/keiki/turn', timeoutMs: '5 minutes', }For relay mode, set
connectivity: 'relay'and omitdispatchUrl. For an outside agent that long-polls instead of receiving a push, setconnectivity: 'inbox'and also omitdispatchUrl; it uses a harness API key to claim turns. See the external harness contract. Unlikekit.serve(), which answers inside the same request, an external app accepts the dispatch asynchronously and replies through the turn endpoints.kit.sync()does not create the signing secret: callPOST /api/v1/developer/agents/:agentId/harness/signing-secretonce and store the returned secret. Includeharnesson every sync; omitting it sendsflueand switches an existing Hermes or external agent back to Flue. -
kit.handleInbound(msg)processes one inbound message programmatically;kit.shutdown()stops gracefully. -
channelsis a typed config surface (ChannelConfig) but is not yet forwarded bykit.sync()— identities are provisioned platform-side. Keep usingresolveNumberfor the SMS line.
The legacy SmsKit / SmsKitConfig / SmsKitInstance names are deprecated aliases of the
AgentKit names and still exported.
Tools
| Export | Kind | Purpose |
|---|---|---|
defineTool | function | Define a type-safe tool; captures its source file for cloud bundling. |
ToolDefinition | type | name, description, Effect Schema input, execute(input, ctx), optional policy. |
ToolPolicy | type | Governance enforced before execute runs (see Governed actions). |
ToolContext | type | Everything a tool can reach at runtime. |
ChannelEnvelope | type | Which channel and provider-level sender/thread metadata the turn arrived on. |
UserStateService | type | Per-user key/value state. |
SecretsService | type | Developer secrets, resolved per call. |
ToolPolicy accepts requiredScopes (matched against the speaker's scopes from the
identity webhook), approval: 'ask' | 'allow', previewTool,
freshnessFields and descriptionArg.
ToolContext exposes phone, user, optional channel, blackboard, platform,
userState, secrets, db, optional entityStore, and sandbox.
Alerts
| Export | Kind | Purpose |
|---|---|---|
defineAlert | function | Define a scheduled or triggered alert. |
AlertDefinition | type | name, description, schedule, dedupKey?, shouldSend?, generate. |
AlertSchedule | type | cron (with optional timezone), interval, or webhook schedule. |
AlertContent | type | First message plus optional ordered follow-up messages, with media. |
AlertContext | type | subscriber, now, resolved secrets, durable per-subscriber state. |
AlertMedia, AlertMessage | type | Media attachments; one message of a multi-message alert. |
AlertStateService | type | get/set KV state persisted across runs. |
Alerts support conditional delivery (shouldSend), deduplication (dedupKey), and multi-message
output. Cloud-served agents register them through kit.sync(); the alerts plugin (below)
serves the execution webhook.
Typed entities
Tenant-scoped, schema-validated persistence with generated tools.
| Export | Kind | Purpose |
|---|---|---|
defineEntity | function | Define an entity (name, schema, soft-delete, optimistic versioning). |
entityMigrations | function | Generate PostgreSQL migrations for the entity's table. |
entityTools | function | Generate <name>_query, _create, _update, _delete tools. |
createEntityDb | function | Entity database over a storage adapter. |
contextEntityStore | function | Entity store from a cloud ToolContext (prefers entityStore). |
sqlEntityStore | function | Entity store over db SQL directly. |
EntityError | error | Raised for validation, conflicts and storage failures. |
EntityStore, EntityStoreRow, EntityDefinition, EntityRow, EntityAccessor, EntityDb | types | The store and row contracts. |
Access is scoped by phone, queries are bounded, deletes are soft, and writes are audited.
Plugins
definePlugin builds a composable AgentKitPlugin. A plugin can contribute tools, alerts,
HTTP routes and middleware, before/after turn hooks, before/after tool-call hooks, Effect
layers, sync-payload transformations, and additive database migrations. Plugin order matters:
later plugins see earlier config contributions.
| Export | Kind |
|---|---|
definePlugin | function |
AgentKitPlugin, PluginContext, RouteContext, SyncPayload, PluginInitResult | types |
TurnEvent, TurnResult, ToolCallEvent, ToolCallResult | types (hook payloads) |
SmsKitPlugin, Plugin | deprecated aliases |
The built-in plugins ship separately in @onkeiki/agents-plugins:
memory, browser, sandbox, executor, steering, media, escalation,
observability, alerts, events, mcp, telegram, group-chat helpers (ObservationBuffer,
composeGroupTurn, decideGroupTurn, …) and codemode (with entityCodemodeProvider,
gmailCodemodeProvider and calendarCodemodeProvider sources).
Capability manifests
Capabilities are the packaging format behind every agent feature, official or yours — see
Capabilities for the format and Rich cards for a worked
official example. The SDK exports the types; write manifests with satisfies so mistakes fail
at compile time:
import type { CapabilityManifest } from '@onkeiki/agents'
const manifest = { /* … */ } satisfies CapabilityManifest| Export | Kind | Purpose |
|---|---|---|
CapabilityManifest | type | The full manifest, discriminated on runtime. |
CapabilityRef | type | Install a published capability by exact publisher/slug/version. |
CapabilityRuntime | type | render-template, openapi, codemode, mcp or builtin. |
CapabilityTool, CapabilityToolRun | types | A tool the capability adds and how it runs. |
CapabilityLoop, CapabilityLoopProbe, CapabilityLoopTrigger | types | Loop presets registered while installed. |
CapabilityEntity, CapabilityTemplate, CapabilitySecret, CapabilityField | types | State, card templates, and declared secrets. |
CapabilityNamespace, CapabilityInput | types | Host namespaces granted via uses, and input typing. |
A full manifest included in agent.capabilities is privately published and installed by
kit.sync(); a CapabilityRef pins an already published one.
OAuth OpenAPI helpers
Helpers for building least-privilege OAuth OpenAPI documents for MCP and user connections:
oauthOpenApiSpec, googleOpenApiSpec, microsoftOpenApiSpec, OpenApiSpecError,
GOOGLE_AUTHORIZATION_URL, GOOGLE_TOKEN_URL, MICROSOFT_AUTHORIZATION_URL,
MICROSOFT_TOKEN_URL, and the OpenApiMethod, OpenApiOperation, OpenApiParameter,
OpenApiParameterRef, OAuthOpenApiSpec, OAuthOpenApiSpecInput types. They validate
duplicate operations, path parameters, methods, scopes, and over-broad provider scopes.
Self-hosting server
| Export | Kind | Purpose |
|---|---|---|
createServer | function | Start the turn-handling HTTP server (what kit.serve() wraps). |
executeAlert | function | Run one alert delivery server-side. |
TurnRequest, TurnResponse | types | The turn request/response envelopes. |
AlertDelivery, AlertExecuteBody | types | Alert execution payloads. |
Service contracts and adapters
Effect context tags and interfaces for replacing the infrastructure under an agent. Cloud-served agents need none of these; self-hosted runtimes supply a storage adapter, and anything else can be swapped for your own implementation.
| Export | Kind | Contract |
|---|---|---|
Storage, StorageError, StorageService | service | Messages, history, profiles, subscribers and opt-outs, alert delivery claims, phone lines, usage metering. |
Transport, TransportService | service | Outbound delivery per channel. |
Platform, PlatformError, PlatformService | service | Managed platform services: memory recall/learning, browser and handoff, sandbox exec/files, background jobs, escalation, fact extraction, media transcription/description/extraction. |
Steering, SteeringService, SteeringDecision, TurnState | service | Mid-turn steering decisions. |
Blackboard, BlackboardService | service | Shared scratch state across a turn. |
Observability, ObservabilityError, TraceExporter | service | Tracing, with braintrustExporter, axiomExporter, otelExporter, customExporter factories and the TraceEvent, SpanEvent, SpanKind, SpanStatus types. |
SandboxProvider, SandboxProviderService, SandboxHandle | service | Code execution. |
PluginDb, PluginDbService, PluginMigration | service | Per-plugin SQL migrations and access. |
Storage adapters ship as separate packages:
| Package | Provides |
|---|---|
@onkeiki/agents-storage-postgres | PostgresStorage bundle, PostgresStorageLive, createPostgresPluginDb — auto-migration. |
@onkeiki/agents-storage-mongodb | MongoStorageLive — auto-indexing. |
@onkeiki/agents-storage-cloudflare | D1 tables, KV cache, R2 blobs, plugin DB support. |
@onkeiki/agents-sandbox-cloudflare | SandboxProvider backed by Cloudflare Workers containers. |
Configuration and message types
AgentKitConfig is the top-level config (apiKey, name, agent, resolveNumber or
channels, optional storage, harness, event handlers, secrets, ordered plugins). The
AgentConfig beneath it and every feature type it composes are exported:
MemoryConfig, BrowserConfig, SandboxConfig, ExecutorConfig, SteeringConfig,
MediaConfig, MediaActionConfig, EscalationConfig, EscalationRoute, EventHandlers,
ObservabilityConfig, PromptContext, TurnHooks, TurnHookState, TurnReviewState,
RetrievedContext, ResolveNumberContext, AcquireLineOpts, PhoneLine, DurationInput,
HarnessConfig, StorageBundle, and the channel types ChannelType, ChannelConfig,
SmsChannelConfig, TelegramChannelConfig. (ChannelType is open-ended; ChannelConfig
currently models only SMS and Telegram.)
Message and user types: InboundMessage, OutboundMessage, StoredMessage, MediaPayload,
SendResult, DeliveryStatus, Direction, UserProfile, Subscriber.
These are exported as types only, even where they are Effect schemas internally — build configs declaratively rather than constructing them at runtime.
Where to go next
- Cloud-served agents — the configuration guide for everything above.
- Self-hosting —
kit.serve()and full-platform hosting. - Capabilities and Publishing a capability — package new abilities for your agents or the marketplace.
- Governed actions and Identity and permissions — policy and scope enforcement around every tool call.