Skip to documentation
Documentation

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.

Shell
bun add @onkeiki/agents @onkeiki/agents-storage-postgres
TypeScript
import { 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

ExportKindPurpose
AgentKit.create(config)functionCreate an agent instance.
create(config)functionAlias for AgentKit.create.
AgentKitInstancetypeThe instance: sync, serve, handleInbound, shutdown.
ResolvedPluginstypeAggregated 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.

  • harness selects 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:

    TypeScript
    harness: {
      type: 'external',
      connectivity: 'push',
      dispatchUrl: 'https://agent.example.com/keiki/turn',
      timeoutMs: '5 minutes',
    }

    For relay mode, set connectivity: 'relay' and omit dispatchUrl. For an outside agent that long-polls instead of receiving a push, set connectivity: 'inbox' and also omit dispatchUrl; it uses a harness API key to claim turns. See the external harness contract. Unlike kit.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: call POST /api/v1/developer/agents/:agentId/harness/signing-secret once and store the returned secret. Include harness on every sync; omitting it sends flue and switches an existing Hermes or external agent back to Flue.

  • kit.handleInbound(msg) processes one inbound message programmatically; kit.shutdown() stops gracefully.

  • channels is a typed config surface (ChannelConfig) but is not yet forwarded by kit.sync() — identities are provisioned platform-side. Keep using resolveNumber for the SMS line.

The legacy SmsKit / SmsKitConfig / SmsKitInstance names are deprecated aliases of the AgentKit names and still exported.

Tools

ExportKindPurpose
defineToolfunctionDefine a type-safe tool; captures its source file for cloud bundling.
ToolDefinitiontypename, description, Effect Schema input, execute(input, ctx), optional policy.
ToolPolicytypeGovernance enforced before execute runs (see Governed actions).
ToolContexttypeEverything a tool can reach at runtime.
ChannelEnvelopetypeWhich channel and provider-level sender/thread metadata the turn arrived on.
UserStateServicetypePer-user key/value state.
SecretsServicetypeDeveloper 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

ExportKindPurpose
defineAlertfunctionDefine a scheduled or triggered alert.
AlertDefinitiontypename, description, schedule, dedupKey?, shouldSend?, generate.
AlertScheduletypecron (with optional timezone), interval, or webhook schedule.
AlertContenttypeFirst message plus optional ordered follow-up messages, with media.
AlertContexttypesubscriber, now, resolved secrets, durable per-subscriber state.
AlertMedia, AlertMessagetypeMedia attachments; one message of a multi-message alert.
AlertStateServicetypeget/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.

ExportKindPurpose
defineEntityfunctionDefine an entity (name, schema, soft-delete, optimistic versioning).
entityMigrationsfunctionGenerate PostgreSQL migrations for the entity's table.
entityToolsfunctionGenerate <name>_query, _create, _update, _delete tools.
createEntityDbfunctionEntity database over a storage adapter.
contextEntityStorefunctionEntity store from a cloud ToolContext (prefers entityStore).
sqlEntityStorefunctionEntity store over db SQL directly.
EntityErrorerrorRaised for validation, conflicts and storage failures.
EntityStore, EntityStoreRow, EntityDefinition, EntityRow, EntityAccessor, EntityDbtypesThe 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.

ExportKind
definePluginfunction
AgentKitPlugin, PluginContext, RouteContext, SyncPayload, PluginInitResulttypes
TurnEvent, TurnResult, ToolCallEvent, ToolCallResulttypes (hook payloads)
SmsKitPlugin, Plugindeprecated 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:

TypeScript
import type { CapabilityManifest } from '@onkeiki/agents'

const manifest = { /* … */ } satisfies CapabilityManifest
ExportKindPurpose
CapabilityManifesttypeThe full manifest, discriminated on runtime.
CapabilityReftypeInstall a published capability by exact publisher/slug/version.
CapabilityRuntimetyperender-template, openapi, codemode, mcp or builtin.
CapabilityTool, CapabilityToolRuntypesA tool the capability adds and how it runs.
CapabilityLoop, CapabilityLoopProbe, CapabilityLoopTriggertypesLoop presets registered while installed.
CapabilityEntity, CapabilityTemplate, CapabilitySecret, CapabilityFieldtypesState, card templates, and declared secrets.
CapabilityNamespace, CapabilityInputtypesHost 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

ExportKindPurpose
createServerfunctionStart the turn-handling HTTP server (what kit.serve() wraps).
executeAlertfunctionRun one alert delivery server-side.
TurnRequest, TurnResponsetypesThe turn request/response envelopes.
AlertDelivery, AlertExecuteBodytypesAlert 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.

ExportKindContract
Storage, StorageError, StorageServiceserviceMessages, history, profiles, subscribers and opt-outs, alert delivery claims, phone lines, usage metering.
Transport, TransportServiceserviceOutbound delivery per channel.
Platform, PlatformError, PlatformServiceserviceManaged platform services: memory recall/learning, browser and handoff, sandbox exec/files, background jobs, escalation, fact extraction, media transcription/description/extraction.
Steering, SteeringService, SteeringDecision, TurnStateserviceMid-turn steering decisions.
Blackboard, BlackboardServiceserviceShared scratch state across a turn.
Observability, ObservabilityError, TraceExporterserviceTracing, with braintrustExporter, axiomExporter, otelExporter, customExporter factories and the TraceEvent, SpanEvent, SpanKind, SpanStatus types.
SandboxProvider, SandboxProviderService, SandboxHandleserviceCode execution.
PluginDb, PluginDbService, PluginMigrationservicePer-plugin SQL migrations and access.

Storage adapters ship as separate packages:

PackageProvides
@onkeiki/agents-storage-postgresPostgresStorage bundle, PostgresStorageLive, createPostgresPluginDb — auto-migration.
@onkeiki/agents-storage-mongodbMongoStorageLive — auto-indexing.
@onkeiki/agents-storage-cloudflareD1 tables, KV cache, R2 blobs, plugin DB support.
@onkeiki/agents-sandbox-cloudflareSandboxProvider 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