Skip to documentation
Documentation

AI SDK integration

Run AI SDK 7 turns in your app while Keiki manages channels, arrivals, tools and delivery.

@onkeiki/ai-sdk connects an AI SDK 7 model loop to Keiki's external harness. Keiki dispatches a signed turn request; the handler accepts it with 202, runs the model asynchronously, and reports messages and completion back to Keiki. Keiki retains channel delivery, MCP tools, cancellation, history and trace records.

When onTurn (or the model stream it returns) throws, the handler completes the turn as failed with the error's message as error (prefixed with its name unless it is a plain Error, capped at 500 characters), so the turn's trace in Keiki shows why it failed.

A provider refusal requiring a recipient reply is reported as message_delivery_failed:recipient_reply_required on completion. The rejected message was not sent; channel tools instruct the model to wait for a recipient reply rather than retry. A notice does not reset the provider's requirement.

Install

Use onOptStatusChanged to handle signed consent transitions without starting a model turn. Enable the subscription separately with a webhook destination (POST /webhooks through Keiki Code Mode); see Event webhooks for payloads, retries, and delivery inspection.

Terminal
bun add @onkeiki/ai-sdk ai @ai-sdk/mcp

Or run npx @onkeiki/cli init in your app to do this setup for you (see CLI).

With no signing secret configured (no signingSecret and no KEIKI_SIGNING_SECRET), the handler verifies Keiki's Ed25519 platform signature against https://onkeiki.com/.well-known/keiki-turn-keys.json and calls the turn API and MCP with the dispatch Keiki-Turn-Token, so the app holds no secret. Calling verifyKeikiDispatch directly, pass turnKeys: {} to accept the platform signature, and then authenticate turn calls with the returned turnToken. Otherwise, set the external harness signing secret as KEIKI_SIGNING_SECRET, or supply it through signingSecret. The handler verifies the raw dispatch body and signs every turn API and MCP request with a short-lived, agent-and-turn-bound kts1 credential. It does not keep or use the dispatch ht_ token.

Serving several agents

Resolve the signing secret by the dispatch's agent ID:

TypeScript
const : <string, string> = { : , :  }

const  = ({
  : ({  }) => [],
  : async ({  }) => ({ ,  }),
})

Returning nothing rejects the push with 401 unknown_agent. The resolver runs before the signature is verified, so use a local map or cache rather than making a network call on every request. The AI SDK calls it on every push and each signed turn API or MCP request.

Next.js

Use Vercel's waitUntil so the function can return the dispatch acknowledgement before the model run completes:

TypeScript
import {  } from '@onkeiki/ai-sdk'
import {  } from '@vercel/functions'
import {  } from 'ai'
import {  } from '@ai-sdk/openai'

export const  = ({
  ,
  : async ({ , , , ,  }) =>
    ({
      : ('gpt-4.1-mini'),
      ,
      ,
      : await (),
      ,
      ,
    }),
})

The signing secret defaults to process.env.KEIKI_SIGNING_SECRET. A provider-specific key such as OPENAI_API_KEY remains in your app environment, never in Keiki's turn payload.

Cloudflare Workers

Pass the request's execution context to the handler:

TypeScript
import {  } from '@onkeiki/ai-sdk'
import {  } from 'ai'
import {  } from '@ai-sdk/openai'

export default {
  (: , : Env, : ) {
    const  = ({ : . })
    return ({
      : () => .,
      : () => .(),
      : async ({ , , , ,  }) =>
        ({
          : ('gpt-4.1-mini'),
          ,
          ,
          : await (),
          ,
          ,
        }),
    })()
  },
}

Keep provider keys and the Keiki signing secret in Worker secrets. A Worker instance's in-memory duplicate protection cannot coordinate with another instance.

Node and Hono

Without waitUntil, the handler starts the turn in the background. Use a persistent Node server process so detached work can continue after the HTTP response:

TypeScript
import {  } from 'hono'
import {  } from '@onkeiki/ai-sdk'
import {  } from 'ai'
import {  } from '@ai-sdk/openai'

const  = new ()
const  = ({
  : async ({ , , , ,  }) =>
    ({
      : ('gpt-4.1-mini'),
      ,
      ,
      : await (),
      ,
      ,
    }),
})

.('/keiki/turn', () => (..))
export default 

Tools and mid-turn arrivals

tools() creates an AI SDK MCP client for the turn's Keiki MCP URL. Each HTTP request is signed independently. The handler closes the MCP client when that run settles.

prepareStep pulls arrivals since its last sequence and appends them to the AI SDK messages as user messages. Pass it directly to streamText or generateText. If your app has its own step preparation, compose both functions so the app sees the updated messages:

TypeScript
import { , type  } from '@onkeiki/ai-sdk'
import { , type  } from 'ai'
import {  } from '@ai-sdk/openai'


const  = async (: ) => {
  const  = (
    .,
    async ({  }) => ({
      : [..., ...(await ())],
    }),
  )

  return ({
    : ('gpt-4.1-mini'),
    : .,
    : await .(),
    ,
    : .,
  })
}

Arrival pushes are acknowledged but do not mutate the running process; durable pulls at step boundaries are the source of truth. The pull endpoint returns the same screened message batch that Keiki sent to the push adapter.

Native replies, actions and reactions

For a page that sends the user away, call await ctx.client.returnLink('Done') during the turn and save result.data.url when result.ok. The same helper is available to the model as get_return_link in await ctx.tools(). Display the URL on your page's completion screen; the user still needs to send the prepared reply. A platform notice does not count as that reply. See Bringing the user back after an external page.

messages gives the model each inbound message's content, which on threaded channels starts with the [Message; message_id=…] annotation the Keiki instructions refer to. Flagged messages start with a prompt-screening warning. The model can thread and react through the Keiki MCP tools, or your code can call ctx.client directly: message(text, { idempotencyKey, replyToMessageId }) sends a threaded reply and action(...) runs react, edit, delete or send_file. A channel that cannot do it answers unsupported without sending anything. sendFile({ data, filename, contentType?, caption? }) uploads a file from your server and sends it; inbound files are on each message's attachments, and downloadAttachment(id) fetches one. A contact's reaction arrives as onReaction and never runs a turn:

TypeScript
import {  } from '@onkeiki/ai-sdk'
import {  } from 'ai'
import {  } from '@ai-sdk/openai'

export const  = ({
  : ({  }) => {
    .(., ., .)
  },
  : async ({ , , , , ,  }) => {
    const  = ..(-1)?.
    if () await .({ : 'react', : , : 'πŸ‘€' })
    return ({ : ('gpt-4.1-mini'), : , , : await (),  })
  },
})

Streaming, generation and cancellation

Return the result from streamText or generateText. The handler sends each text-producing stream step as its own turn /stream request; non-text steps are not sent. Each generateText step with text is sent through /messages with a step-specific idempotency key. A stream request is not automatically retried when its delivery outcome is unknown. Return void if your code delivered the answer itself through ctx.client.

Turn cancellation aborts a run owned by the same process. On serverless, Keiki also rejects the next arrival pull for a closed turn; the handler aborts its model signal at that step boundary. Cancellation cannot interrupt a provider call that does not honor AbortSignal.

The handler keeps a bounded in-memory duplicate set per handler instance. It does not provide cross-instance idempotency: a serverless retry routed to a different instance may start the same turn again. Completion retries use bounded 1s/5s/15s backoff; message and stream sends are not retried. Configure Keiki's external harness in push mode and use a persistent signing secret for the agent.