Skip to documentation
Documentation

External harness

Run an agent's turn loop in your own application while Keiki keeps channel ingress and delivery.

The external harness runs the model loop in an application you control. Keiki continues to receive channel messages, apply steering and turn-slot limits, provide tools, deliver messages, and record the turn trace. For each turn it sends a signed request to your app, then waits for your app to report the result.

Open-source starters you can fork: imessage-hono-workers-starter (Cloudflare Workers), imessage-mcp-agent (your MCP server's tools) and imessage-whatsapp-telegram-slack-agent (one handler on four channels).

Configure an agent

For timestamped opt-out notifications and a delivery/retry log, configure a consent event subscription for your push dispatch URL. Consent changes are signed, non-turn events; they are not automatically sent to every external harness.

Set the agent's harness to external and configure its connection with the developer API (a partner deployment takes the same harness and harness_config in its agent spec):

JSON
{
  "harness": "external",
  "harness_config": {
    "mode": "push",
    "dispatchUrl": "https://agent.example.com/keiki/turn",
    "timeoutMs": 600000
  }
}

mode is push, relay, or inbox. Push mode posts directly to dispatchUrl; relay mode queues the signed request for a connected relay to forward. Inbox mode queues work for an outside agent to claim when it polls, and needs neither a dispatch URL nor a signing secret. timeoutMs overrides the turn deadline, up to ten minutes. The default is ten minutes. Push and relay apps verify Keiki's Ed25519 platform signature (see Turn request) and need no secret, or use the signing secret returned by POST /api/v1/developer/agents/:agentId/harness/signing-secret; the returned whsec_... value is shown once and should be stored in your app's secret manager. Inbox pollers authenticate with a harness API key instead. A multi-agent handler can resolve the secret by agentId; a missing match should reject the push with 401 unknown_agent.

Owners/admins can configure a customer-owned card extension entirely through MCP: call post_sso_domains, publish the returned keiki-sso-verify= TXT record, call it again until verified, then call put_agents_card_app with the agent ID and { card_app }. No SSO plan is required for domain claims. Code Mode uses keiki.sso.post_domains and keiki.agents.put_card_app; see the setup example. This changes only the card identity, not the agent's other features; Dynamic UI must still be enabled.

Push through a tunnel

Run your HTTP server first, then start the shared tunnel supervisor with the agent's API key and the port your server listens on:

Terminal
curl -fsSL https://<your-keiki-host>/api/v1/harness/tunnel.sh \
  | KEIKI_API_KEY=sk_live_… PORT=8789 sh

TUNNEL defaults to cloudflared; set TUNNEL=ngrok to use ngrok instead, and optionally provide NGROK_AUTHTOKEN. TURN_PATH appends a path such as /keiki/turn to the public URL. HARNESS defaults to external; Hermes installs use HARNESS=hermes. KEIKI_HOME defaults to ~/.keiki.

The script verifies the key and agent harness, then warns if nothing is listening on PORT yet; it does not require the local server to be ready before starting a detached supervisor that manages only the tunnel, not your app. Its PID, log, state and persisted supervisor script are isolated under ~/.keiki/tunnels/<agent id>/. It registers the public URL in Push mode while preserving the other harness settings. If the tunnel exits, it restarts with exponential backoff from 2 to 60 seconds and updates the URL only when it changes. A failed registration is retried with backoff. Re-running the command validates the setup and downloads the supervisor before stopping the previous one.

Stop it explicitly with the same agent API key:

Terminal
curl -fsSL https://<your-keiki-host>/api/v1/harness/tunnel.sh \
  | KEIKI_API_KEY=sk_live_… KEIKI_TUNNEL_STOP=1 sh

Logs are at ~/.keiki/tunnels/<agent id>/tunnel.log. Configure your app to verify Keiki-Signature-Ed25519 against Keiki's JWKS, or generate a signing secret in the dashboard and verify Keiki-Signature, before handling turns.

Push turns are synchronous: if the endpoint is down, the turn fails rather than being queued. The agent page probes the endpoint and shows the latest delivery outcome.

Turn request

Keiki sends a JSON keiki.turn payload with version: 1. It includes the turn and agent IDs, conversation ID, channel envelope, inbound messages, bounded history, structured context, prompt instructions, held-back/silent/quiet-loop flags, and a deadline. The keiki object provides the platform API base, the turn-scoped URL, and the MCP URL. Provider credentials and platform API keys are not included. The messages array includes every current inbound message; an entry excluded from prompt guarding and inbound recording is marked with silent: true. Each message carries the contact's raw text and content, the same text as a Keiki model reads it: on channels with native reply threads it starts with a [Message; message_id=…] annotation (platform notices carry no id), which is what the reply guidance in instructions tells the model to look for. Show your model content (and history, which is annotated the same way); forward text when you pass the message on verbatim. sentAt is when the person sent the message, per the channel provider (ISO 8601). It is absent when the provider gives no time, and on notices. A notice still has a messageId, which identifies its entry in the payload. It is not a channel message, so do not pass it to replyToMessageId or /actions.

Reading attachments with your own model

Messages with stored files carry an attachments array. Keiki's built-in agent reads photo descriptions and extracted PDF text, not the original image or PDF content blocks. The description and extraction step uses a separate media model. An external harness can fetch the originals and pass them to its own vision or document-capable model instead.

For example, an entry in the turn's messages array can include:

JSON
{
  "content": "[Attachment: receipt.jpg; attachment_id=att_D6kl04dQnJ7pvFI49OCHmw; mime=image/jpeg; size=4830: A receipt showing a total of $6.75.]",
  "attachments": [{
    "id": "att_D6kl04dQnJ7pvFI49OCHmw",
    "filename": "receipt.jpg",
    "mimeType": "image/jpeg",
    "size": 4830,
    "url": "https://keiki.example/api/v1/attachments/att_D6kl04dQnJ7pvFI49OCHmw/content?exp=…&sig=…",
    "expiresAt": "2026-10-31T03:15:00.000Z"
  }]
}

url downloads the bytes without credentials for 15 minutes. After that, use GET {turnUrl}/attachments/{id} with a valid turn credential. filename can be null; url and expiresAt are omitted if the platform cannot generate a signed link. Treat signed URLs as temporary access credentials, not permanent file addresses.

In a group chat, each message also carries who wrote it and whether it addressed the agent (named it or replied to one of its messages). Keiki strips the agent's name from text, so mentionsAgent is the only record of it:

JSON
{
  "text": "[Dana]: what time is the table?",
  "sender": { "id": "+15555550100", "name": "Dana" },
  "mentionsAgent": true
}

sender.id is the person's phone number or email. sender.name is the name Keiki knows them by, and is absent when it knows none or when screening withheld the message. Both fields are set on iMessage groups and are absent in one-to-one chats.

After verifying the turn request, fetch a stored image from its message:

TypeScript
const  = .
  .( => . ?? [])
  .( => ..('image/') && .)

if (?.) {
  const  = await (.)
  if (!.) throw new (`Attachment download failed: ${.}`)
  const  = new (await .())
  // Pass bytes and image.mimeType to your model SDK's image input.
}

Fetching alone does not give your model vision. Your harness must construct an image content block in the format its model SDK accepts. Keep the text description as a fallback for models without image input. For PDFs, use a document-capable model's file input or parse the downloaded bytes yourself.

Request screening and authentication

When prompt guarding is enabled, deterministic Shield rule matches are refused before the app receives the turn. Other flagged messages are delivered with their original text and screening: { "flagged": true }, so the app can warn its model while still answering ordinary replies normally. The @onkeiki/flue, @onkeiki/eve and @onkeiki/ai-sdk adapters add that warning and give the model each message's content; for your own runtime, keikiMessagePrompt in @onkeiki/channels does the same.

Requests include Keiki-Turn-Id, Keiki-Turn-Token, and Keiki-Signature headers. The signature is HMAC-SHA256 over the exact raw request body, prefixed by the Unix timestamp and a period:

text
Keiki-Signature: t=<unix-seconds>,v1=<hex HMAC-SHA256(secret, "<unix-seconds>.<raw-body>")>

Verify the signature against the raw bytes before parsing or acting on the body. The Keiki-Turn-Token is a short-lived bearer token for that turn's routes and should not be logged or reused for another turn. Return any 2xx response once the request is accepted; the model loop may continue asynchronously.

When Keiki's platform key is configured, every push, arrival and cancellation also carries an Ed25519 signature that needs no per-agent secret:

text
Keiki-Signature-Ed25519: t=<unix-seconds>,kid=<key id>,v1=<base64url Ed25519 signature over "<unix-seconds>.<turn-token>.<raw-body>">

Verify it with the public key whose kid matches in https://onkeiki.com/.well-known/keiki-turn-keys.json (a JWKS of OKP/Ed25519 keys; cache it and refetch on an unknown kid). An agent with no signing secret is then pushed with only this header. <turn-token> is the request's Keiki-Turn-Token (empty on a cancellation), so the token can't be swapped onto a signed body. Use that token for the turn's routes.

Runtimes that cannot carry the dispatch token between processes can instead sign a short-lived turn credential with the agent signing secret and use it as the bearer for the turn API and MCP endpoint. The ht_ token remains available to runtimes that can forward the dispatch header. The credential is bound to the agent and trace ID and expires after five minutes:

text
Authorization: Bearer kts1.<payloadB64>.<sigHex>
payloadB64 = base64url(JSON.stringify({ a: agentId, t: turnId, ts: unixSeconds }))
sigHex = hex(HMAC-SHA256(signingSecret, `keiki-turn-auth.v1.${payloadB64}`))

Use signTurnAuth from @onkeiki/channels to create it. Do not log either bearer or the signing secret.

Mid-turn arrivals

In push mode, the external harness can deliver messages that arrive during an eligible append turn to the running app. It polls for arrivals about once a second and sends a signed keiki.turn.arrival request with the same raw-body signature headers as a normal dispatch, plus a 1-based sequence number for that turn. The payload includes the turn and conversation IDs, the inbound messages, and non-secret binding context:

JSON
{
  "type": "keiki.turn.arrival",
  "version": 1,
  "turnId": "turn-123",
  "agentId": "agent-456",
  "conversationId": "+15555550123",
  "heldBack": false,
  "channel": "sms",
  "keiki": {
    "apiBase": "https://keiki.example/api/v1",
    "turnUrl": "https://keiki.example/api/v1/turns/turn-123",
    "mcpUrl": "https://keiki.example/api/v1/harness/mcp/codemode"
  },
  "sequence": 1,
  "messages": [{ "text": "one more detail", "messageId": "message-789" }]
}

The signed request includes the same Keiki-Turn-Token header as the turn's original dispatch, alongside Keiki-Signature and Keiki-Turn-Id. The token is never included in the arrival body; adapters that steer an active turn must preserve its turn authentication. Do not log or persist the token.

Push delivery is also persisted for pull-based runtimes. The push and pull APIs carry the same screened wire messages for each accepted batch. An app may acknowledge the push without processing it and pull between its own model steps:

HTTP
GET {turnUrl}/arrivals?after=0
Authorization: Bearer kts1.…

after is a non-negative sequence cursor and defaults to 0. The response contains up to 50 batches ordered by sequence:

JSON
{
  "arrivals": [{
    "sequence": 1,
    "messages": [{ "text": "one more detail", "messageId": "message-789" }]
  }]
}

Use the highest returned sequence as the next cursor. Only batches accepted by push dispatch are pullable; rejected batches return to steering. The endpoint requires an open turn credential.

Turn API routes other than /complete, and /api/v1/harness/mcp, return 409 {"error":"turn_closed"} when a verified turn credential belongs to a completed or expired turn. /complete continues accepting unexpired completed-turn credentials so duplicate completions remain idempotent; expired credentials or signed credentials outside the timestamp window remain 401 there. Unknown tokens and invalid signatures remain 401 Unauthorized. Outside /complete, a signed credential outside the five-minute timestamp window is rejected with 401 unless its signature verifies and its turn is already closed. Do not replay closed-turn requests or authentication rejections. Channels marks 401/403/404/409 responses non-retryable; Eve logs and drops terminal delivery failures while continuing to throw on network and server failures.

Report arrivals the app processed in its /complete request; on a failed turn, report only those already answered. A sequence is answered when a /messages send returns ok or turn_closed after that arrival was processed. Completed turns should report every processed arrival:

JSON
{ "status": "completed", "consumedArrivals": [1, 2] }

The field is optional; omitting it means no arrivals were consumed. An app that consumes an arrival but omits its sequence will cause Keiki to put those messages back at the front of the pending queue, where a later turn answers them. Unconsumed batches and batches rejected by the app after retries are also returned to the queue. Returned messages are not written to turn history until a later turn takes them. Relay-mode turns do not take arrivals.

If an arrival reaches the app after the turn's completion boundary but before Keiki receives /complete, the framework may start a new run against the closing Keiki turn. The app must not report that arrival as consumed; its turn API calls can return 409 turn_closed, and Keiki requeues it for the next turn. Flue adapters keep the turn binding until the instance's queued and running submissions settle, so an arrival already queued for that instance is handled before this completion boundary.

For the Eve extension, see the Eve integration guide. For Flue 2.x applications, see the Flue integration guide. For AI SDK 7 apps, see the AI SDK integration guide.

Turn-scoped API

Use the turnUrl from the payload. Every route accepts either Authorization: Bearer ht_... with the token from Keiki-Turn-Token, or the signed kts1.… credential above. The URL's turn ID must match the credential.

RequestPurpose
GET {turnUrl}/return-link?text=DoneDerive { url: string | null, channel } for the contact to return from an external page. Authenticated like the other turn routes.
POST {turnUrl}/messagesDeliver { "text": "...", "idempotencyKey": "..." }; the key is optional. Add replyToMessageId to reply to one message, or effect for an iMessage screen/bubble effect (not both). The response carries the sent messageId.
POST {turnUrl}/actionsRun a native channel action: { "action": "react", "messageId", "emoji", "remove"? }, { "action": "react", "messageId", "sticker": { "url" | "attachmentId" | "path", "x"?, "y"?, "scale"?, "rotation"? } }, { "action": "edit", "messageId", "text" }, { "action": "delete", "messageId" }, { "action": "send_file", "attachmentId" | "path", "caption"? }, or { "action": "send_file", "url" | "attachmentId" | "path", "sticker": true } (stickers). Takes an optional idempotencyKey.
POST {turnUrl}/attachments?filename=…Upload a file to send: the raw bytes as the body, with its Content-Type. Returns 201 with { "id": "att_…", "filename", "mimeType", "size" }; pass id as send_file's attachmentId. Up to 100 MB; the channel's own limit still applies when it is sent.

For a URL app card, post { "action": "send_widget", "url": "https://app.swoop.ae/approvals?id=1234", "caption": "Approval", "subcaption": "Details", "idempotencyKey": "approval-1234" } to {turnUrl}/actions. The URL must be HTTPS (up to 2048 characters); caption and subcaption are optional, with limits of 60 and 80 characters. The key is required (up to 128 characters). Notice turns use the same action. The response is { "ok": true, "result": { "state": "accepted", "messageId": "…" } }, unavailable with a reason (unsupported_channel, line_not_eligible, url_host_not_allowed, addon_disabled, or delivery_failed), or unknown. Never resend an unknown result: the card may have arrived. Duplicate keys use the same duplicate acknowledgement as other actions. Closed turns return 409; held-back and steered turns cannot send. Turns outside direct dedicated iMessage chats return unsupported_channel. Keiki never substitutes text: on unavailable, your harness can send its own plain link through /messages. See iMessage Apps for features.card_app, required organization domain verification, normalized links, custom identity and verbatim URL delivery.

| GET {turnUrl}/attachments/{id} | Download a file from the turn's conversation, such as an inbound message's attachment. | | POST {turnUrl}/stream | Send newline-delimited JSON events: text-delta with text, and message-break. | | POST {turnUrl}/typing | Ask Keiki to show typing where the channel supports it. | | POST {turnUrl}/lease | Refresh a live claim for a long-running turn. | | GET {turnUrl}/arrivals?after=0 | Pull up to 50 durable arrival batches after a sequence cursor. | | POST {turnUrl}/complete | Settle the turn with status: "completed" or "failed", optional error, and optional usage. |

Messages on normal channel turns are delivered by Keiki and recorded in the trace. The stream endpoint appends live to an active Slack stream when available; otherwise it buffers text and delivers paragraphs at message breaks or blank-line boundaries. Keiki never sends twice under one message idempotency key. Reusing a key whose send succeeded returns the first response again (its messageId or action result) with duplicate: true, without sending. A retry that arrives while the first request with the key is still sending returns 409 with attempt_in_progress and retryable: true: retry the same key shortly. After any delivery error, /messages returns 502 with retryable: false; the delivery outcome is unknown. A retry with that key returns 409 with previous_attempt_failed, as does a key whose first request stopped before it settled (Keiki treats a send it has not heard from for 2 minutes as stopped; a slow send that is still running stays attempt_in_progress). To try again anyway, send a new key and accept that the contact might receive the message twice.

Native channel actions

Each message and action is recorded on the turn's trace as the same tool call the platform's own model would make (reply, react_to_message, update_message, delete_message, send_file, send_widget), so it counts in Logs, Insights and /api/v1/developer/usage alongside your other tool calls. Duplicate idempotency keys are not recorded again, and a request that sent nothing (refused, failed, or a widget answered unavailable) is recorded as a failed call that usage does not count. Typing indicators, uploads, lease refreshes and MCP tool listings are recorded on the trace as external_typing, external_upload, external_lease and external_tool_list events, which are not tool calls. The trace also keeps the model your completion reports, the number of tool calls the turn made, and firstMessageMs, the time from the turn's start to its first delivered message.

/messages and /actions run the same channel tools the platform's own model uses, so a threaded reply, effect, reaction, edit, unsend or file goes out natively on whatever channel the conversation is on (iMessage, WhatsApp, Telegram, Slack, Teams, email, X). Message ids are the messageId values from the turn's messages and replyTo, and the ids /messages returns. A request the conversation's channel cannot carry out returns 400 with error: "unsupported" before anything is sent, including when the action's tool is not enabled for the agent (for example, sandbox path file sends with the sandbox feature off). Stored conversation attachments can be sent with attachmentId regardless of the sandbox setting. Without the sandbox, the model/MCP send_file schema offers only attachment_id, not path. A locally rejected message target returns 400 with error: "invalid_message" when the message is not in this conversation, or an edit/delete target is not a message this agent sent. These responses include retryable: false; their idempotency keys may be reused after correcting the request. Provider failures remain delivery errors, not invalid_message rejections. Held-back turns cannot run actions (400, error: "held_back"). The same actions are MCP tools at turn.keiki.mcpUrl (reply with reply_to_message_id, react_to_message, update_message, delete_message, send_file), listed only where the channel supports them.

On iMessage, react_to_message and the react action take an emoji or a case-insensitive tapback name: love, like, dislike, laugh, emphasize, or question. Aliases include heart, thumbs_up / thumbsup, thumbs_down / thumbsdown, haha / lol, exclamation, and question_mark. Unknown word names are rejected; custom emoji are passed through to the provider.

External agents receive direct tools at turn.keiki.mcpUrl by default. Set harness_config.toolMode: "codemode" to opt into external harness Code Mode: search and execute this agent's tools as JavaScript while keeping delivery tools direct. Unset the option or use "direct" to switch back. Hermes remains on direct tools.

The MCP catalog also includes tools from the agent's enabled, installed capabilities, including render_cards from Cards when a renderer is configured. Capability-granted features enable the corresponding built-in tools, just as on the hosted loop. Authored tools take precedence over built-ins and installed tools of the same name. The installed tool catalog is snapshotted per turn; changes apply on the next turn. Calls execute on Keiki with the bound agent and conversation's delivery context, on both external and Hermes harnesses.

Hosted and harness turns share catalog assembly, including declared personal-secret tools. Installing an official built-in capability does not bypass connection or sandbox provider availability checks.

Reaction events

When a contact adds or removes a reaction, Keiki records it and tells the app without starting a turn:

JSON
{
  "type": "keiki.reaction",
  "version": 1,
  "eventId": "8c1f…",
  "agentId": "agent-123",
  "conversationId": "+15551234567",
  "occurredAt": "2026-10-24T21:40:00.000Z",
  "reaction": { "emoji": "❤️", "removed": false, "messageId": "msg-456", "on": "outbound" }
}

reaction.on is outbound for a reaction on the agent's message and inbound for one on the contact's own. Push mode POSTs the event to dispatchUrl once, signed like a cancellation: Keiki-Signature and Keiki-Signature-Ed25519 (over an empty turn token), with no Keiki-Turn-Token or Keiki-Turn-Id. verifyKeikiRequest and verifyKeikiDispatch return it as { kind: "reaction", reaction }. The Flue and Eve adapters accept it with 202 and run nothing; the AI SDK handler passes it to onReaction. Inbox mode returns it from /harness/inbox/next as { "turn": null, "event": { ... } }, at most once, for up to a day. Relay mode does not receive reaction events.

Recipient reply required

If a channel provider requires the recipient to message first or reply again, message, action/file-send, and stream requests return HTTP 429:

JSON
{
  "error": "recipient_reply_required",
  "message": "The message was not sent. The recipient must message you first or reply again before you can send. Do not retry until then; a platform notice does not count.",
  "retryable": false
}

Do not retry the rejected send until the recipient replies. A notice starts a turn, but it is not a recipient reply and does not reset this provider requirement. This is not a local reciprocity cap. Explicit provider refusals requiring a reply map to this channel-neutral code, including WhatsApp's immediate-send error 131047 (re-engagement window closed), and iMessage refusals 403 inbound_only_no_prior_inbound, 429 conversation_streak_limit, 429 conversation_awaiting_reply, and 429 conversation_inactive_paused. Up to 3 messages may be sent before the recipient responds. Other rate limits remain ordinary delivery failures. If a connection resets or is unavailable while opening a one-to-one iMessage chat, Keiki retries opening it once before sending. This retry does not apply to group chat lookups, and a connection error during the send itself does not cause Keiki to replay the message. If Keiki can't refresh the connection before retrying, or the second attempt fails with a connection error, the reply returns a non-retryable 502 and appears as not delivered in the conversation dashboard. Asynchronous failed delivery receipts retain their provider error strings; they do not retroactively turn an accepted send into this response.

@onkeiki/channels returns code: 'recipient_reply_required' with retryable: false and an explanatory message. The AI SDK, Flue, and Eve adapters complete a turn whose delivery failed with message_delivery_failed:recipient_reply_required. Channel tools return the same code and explain that nothing was sent. A stream may have delivered earlier paragraphs before a later paragraph was refused; the refusal does not retract messages already delivered.

Proactive turns

To message a contact when they have not started a turn, for example when a background job finishes, send a notice from your server:

Terminal
curl -X POST 'https://<host>/api/v1/developer/agents/<agent-id>/notice' \
  -H "Authorization: Bearer $KEIKI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"text":"The video export has finished.","phone":"+15551234567"}'

Keiki starts a turn for that conversation and delivers it to your app like any other: a keiki.turn pushed to dispatchUrl, claimed by your relay, or returned from /harness/inbox/next. The notice is a messages entry marked silent: true. Its text and content frame it for your model as a note from your platform rather than something the contact wrote; notice.text is the text your server sent (trimmed of leading and trailing whitespace), so read markers or job IDs from there rather than from the framed text. Messages your app sends through POST {turnUrl}/messages are delivered to the contact. When the turn carries only the notice, the payload also has silent: true and the turn's final answer is discarded, so complete the turn without sending anything when the contact does not need to hear about it. A notice that arrives while the contact is mid-conversation can share a turn with their messages; that turn is not silent and is answered as usual.

phone must name an existing conversation for the agent; a notice cannot open a conversation with a new identity. Omit phone to start a turn in each of up to 200 recent conversations. Outbound rules still apply to the messages the turn sends, including opt-outs and the inbound-first requirement on shared lines.

Bringing the user back after an external page

A channel provider can refuse further messages until the recipient replies. Opening a new turn with /notice does not reset that requirement: a notice is platform context, not a message from the recipient. Before sending the user to a login, code, or verification page, get a return link during the open turn and store it with your page's completion state:

TypeScript
import {  } from '@onkeiki/channels'

const  = ({ : ..,  })
const  = await .('Done')
if (. && ..) {
  // Save this URL for your page's final "Return to chat" button.
  await (..)
}

client is createTurnClient({ turnUrl: turn.keiki.turnUrl, turnToken }) from @onkeiki/channels. Native agents and the AI SDK, Flue, and Eve MCP connections can call get_return_link({ text: 'Done' }) for the same { url, channel } result. No destination number or bot name is accepted: Keiki derives it from the conversation's owned route, including the shared number bound to this contact and agent.

The default reply is Done; blank text also uses the default. Nonblank text is preserved, including surrounding whitespace. Text over 256 Unicode code points is rejected with HTTP 400 and error: 'return_link_text_too_long', never silently shortened. Phone-line chats use sms:<line>?&body=..., WhatsApp uses a wa.me link to the business number, and Telegram uses t.me/<bot>?start=<payload> when the recorded bot username is known. Telegram turns text into a URL-safe slug and rejects slugs longer than 64 characters with HTTP 400 and error: 'return_link_payload_too_long'. Both errors include a corrective message; TurnClient.returnLink() preserves their typed code, status: 400, and message. get_return_link reports a failed tool result. The agent receives /start <payload> as an ordinary inbound. A Telegram link opens the bot's private chat, including when generated from a group conversation.

Opening the link alone sends nothing. The user must press Send in their messaging app, or Start in Telegram. That real inbound lets the provider reset its reply requirement and starts a normal agent turn. Keiki does not reset provider state, auto-send, or bypass provider limits. App and device support for prefilled text varies.

url is null for channels without a supported deep link (Slack, Teams, email, A2A, web/API), or when the owned line/business number/bot username cannot be resolved. Show instructions to return to the existing chat instead. The returned channel is Keiki's identity channel; phone-line conversations use sms, including iMessage. Fetch while the turn credential is valid; the stored link contains no turn token and can be shown after the turn ends.

Held-back turns

Playground, internally steered, and agent-dispatch turns are held back: messages sent to the turn API are captured as the turn's answer and are not delivered to the contact. Deterministic prompt-guard rule matches are refused before they reach the app. Other flagged messages are delivered with screening.flagged so the app can warn its model; the Flue adapter adds the warning automatically. The payload's heldBack, silent, and quietLoop fields let the app apply the same distinction in its own loop.

Completion and errors

Complete the turn after all messages and tool calls have settled. Repeated completion requests are acknowledged as duplicates. Keiki releases the active turn token and slot after observing the outcome, cancellation, or deadline.

Push-mode cancellation is a signed keiki.turn.cancelled request with the turn, agent, and conversation identity:

JSON
{ "type": "keiki.turn.cancelled", "turnId": "…", "agentId": "…", "conversationId": "…" }

Dispatch failures are represented on the trace with structured codes, including signing_secret_missing, no_dispatch_url, unreachable, signature_rejected, app_rejected, relay_offline, turn_timeout, app_error, delivery_failed, and cancelled. Check the trace for the associated error and remediation hint.

A turn your app completes as failed is app_error with your error, except when the error starts with message_delivery_failed: and one of the turn's own /messages, /stream (including a live Slack stream write) or /actions calls did fail inside Keiki, or a widget came back unavailable with reason delivery_failed. That turn is delivery_failed, and its error is the failed call's reason, the channel's own when it gives one (for example Telegram's message is too long), so a send Keiki could not make is not reported as your app erroring. A widget or action the channel does not support is not a failed send.

Push dispatch accepts any HTTP 2xx response after reading its body; no acknowledgment JSON is required. Each attempt has a 10-second timeout and the existing 4 MiB response limit. HTTP 408, 429, and 5xx responses and transport failures are retried up to three attempts, with waits of 500 ms and 2 seconds. Redirects are not followed: app_rejected names the Location and asks you to set dispatchUrl to the final URL. Other 4xx responses are app_rejected, except 401/403 (signature_rejected).

Exhausted HTTP retries produce app_error, not unreachable. The message reports the last HTTP status and a short response snippet; differing statuses are listed instead of claiming every attempt returned the same status. Check the turn endpoint's logs. Transport failures use unreachable, naming the dispatch host and network error code; timeouts say the app did not respond within 10s.

When a turn fails with an error status, or with a connection that never reached your app, Keiki puts its messages back in the queue and dispatches them again after 15 s, 30 s, 60 s, 2 min, and 4 min, or after your Retry-After if it is longer (capped at 4 min). A turn someone is waiting on (an API caller, a peer agent, a live call), and a Slack or Teams thread (which is told the turn failed), get the failure instead. A message that arrives during the wait triggers the next dispatch early, in the same batch. Each new dispatch is a new turn with a new trace. A timeout or a connection dropped mid-request is not dispatched again, since your app may still be running that turn. After the fifth wait the turn fails as above.

Each external_dispatch span records attempt, timeoutMs, httpStatus, bodySnippet, and requestIds when an HTTP response is available, or an error message for a transport failure. Snippets are whitespace-collapsed and capped at 300 characters; JSON exposes only string error/message fields, and HTML uses the existing page-title extractor. Echoed signing-header values, whsec_ secrets, and HMAC signature patterns are redacted. Request IDs include x-vercel-id, cf-ray, x-request-id, x-amzn-requestid, and x-amz-cf-id when supplied. Signing headers are never recorded. The final error is also on the external_error span and trace. agents.harness_config.lastDelivery stores the latest failure's message, httpStatus, and bodySnippet; the dashboard shows that message rather than replacing it with generic connectivity advice. Playground and MCP test turns use these same push diagnostics and retry rules.

Relay mode

Relay mode uses the harness queue rather than posting directly to dispatchUrl. A connected relay authenticates with a harness API key, claims work from GET /api/v1/harness/turns/next, forwards the raw body and signature headers to the configured app, and reports the dispatch result through the harness completion route. The app then uses the same turn-scoped API as in push mode.

Inbox mode

Inbox mode is for an external agent that cannot receive pushes or is not always online. Authenticate with a harness API key and long-poll GET /api/v1/harness/inbox/next?wait=25 (the wait may be 0–30 seconds). A response is { "turn": null } when the wait expires, { "turn": null, "event": { ... } } for a reaction event, or { "turn": { ... } } with the turn, deadline, turnToken, and turn-scoped URL. Run the model loop, send each contact-facing reply through POST {turn.keiki.turnUrl}/messages, and complete the claimed turn through POST {turn.keiki.turnUrl}/complete. Give each message an idempotencyKey that is stable for that action.

Claims are leased. If an agent stops before completing a turn, the lease expires and a later poll can reclaim it with a rotated turn token; message idempotency state survives the reclaim. For a long-running turn, refresh its live lease with POST {turn.keiki.turnUrl}/lease and the turn token; the response includes the extended leaseExpiresAt. By default a claim, and each refresh, lasts as long as the turn's timeout (up to 10 minutes), so a turn held by a worker that died waits that long before another poll can reclaim it. A poller that refreshes while it works can pass leaseMs (15000–600000) on /inbox/next to claim for that long instead; each refresh then extends the lease and turn token by leaseMs, so a dead worker's turn is reclaimed within leaseMs. The lease never outlasts the turn's timeout, so refresh at least every min(leaseMs, timeoutMs) / 2: a turn whose lease lapses is reclaimed by another poll and its old turn token stops working. Only one turn for a conversation can be active at once. When a fresh claim is made, pending turns for that same conversation are merged into it in arrival order, except on Slack. Slack turns are claimed individually, even within the same thread, so each claim retains the verified requester used for personal connections. Other conversations remain independently claimable.

Nothing is sent to contacts while the agent is offline: ordinary inbox turns stay queued until a poller claims them. Test, steer, and other synchronous turns require a recent poll; otherwise the request fails with inbox_offline.

Connect over OAuth

Any MCP client can be an agent's harness with no key or turn token: add https://onkeiki.com/api/v1/harness/mcp as a remote MCP server. The first request answers 401 with OAuth discovery metadata for the harness scope, so the client opens Keiki in the browser. Sign in, pick an organization, pick an external-harness agent (or create one), and optionally pin one of its conversations; choosing Start a new conversation leaves the connection open to any of the agent's conversations. With Start a new conversation you can also enter your own phone number: for the next hour, its first text to the shared number with no join code joins this agent, and the connection is pinned to it. A number that already talks to another agent on the shared line, or is waiting to join one, is not pre-linked; that connection uses the join code. A new agent created on this screen is named after the asking app unless you name it. A client whose OAuth callback is on localhost but runs on another machine (a cloud sandbox) cannot be reached by your browser; after Approve, the page then shows a line to paste into the agent's chat, which has the agent open its own callback. The authorization code works once, for 5 minutes, and only with the client's PKCE verifier. The client may retry the same exchange once within 10 seconds; any other reuse revokes the connection. An agent with no connection of its own is put on inbox mode.

The connection lists the agent's tools plus next_message. Call next_message (wait, 0–120 seconds, default 25) to claim the next inbox turn; it returns { "message": { conversationId, channel, instructions, messages, history } }, and the channel tools (reply, reactions, ask_question, files) then act on that message. Calling it again completes the previous turn. When nothing arrives it returns { "message": null }, and an unpinned connection also gets startConversation: the shared number, the text a new contact sends to reach the agent, and an sms: link that opens that text ready to send. An unpinned connection on a shared line is also told this when it connects (in the MCP instructions), so the harness asks its user to text the join code first and their conversation links to the agent.

To keep listening, tell the agent to loop on next_message, for example: "Call next_message, answer each message with reply, and call it again after every reply or empty result, until I say stop." Setups for two clients:

Terminal
# Claude Code
claude mcp add --transport http keiki https://onkeiki.com/api/v1/harness/mcp

# opencode: in opencode.json, then run `opencode mcp auth keiki`
{ "mcp": { "keiki": { "type": "remote", "url": "https://onkeiki.com/api/v1/harness/mcp" } } }

No plan is needed. A plan-less agent reached this way answers on the shared line for 5 inbound and 5 outbound messages over its lifetime, counted on the agent, so reconnecting does not reset them. Inbound credit is spent once when a new inbound message on the shared line is recorded, regardless of which credential or dispatch mode handles it. Redeliveries, reclaimed turns, playground messages and open onboarding tests do not spend it; neither do reactions, opt-outs or empty events. Every send on the shared line counts, whichever credential made it. After that, inbound messages are dropped and sends fail with a message to add a plan. A plan lifts both caps. Viewers cannot use the connection; it needs a member or owner.

Connect dot

Give dot the harness API key and this instruction:

text
Poll GET /api/v1/harness/inbox/next?wait=25 with Authorization: Bearer <HARNESS_API_KEY>.
For every returned turn, run the agent on its messages. Send replies only through
POST <turn.keiki.turnUrl>/messages using Authorization: Bearer <turn.turnToken> and a stable
idempotencyKey for each action. Then POST <turn.keiki.turnUrl>/complete with
{"status":"completed"} (or {"status":"failed","error":"..."}). Complete every claimed turn;
refresh the turn lease before it expires if the agent needs more time.
For native replies and reactions use replyToMessageId on /messages and POST <turn.keiki.turnUrl>/actions.
A response with an event instead of a turn is a contact's reaction; read it and poll again.
if the process restarts, resume by polling again and use the newly returned turn token.
Never send a contact message outside the turn API.