> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Mira cloud channels

> Design for running Mira's Discord, WhatsApp and Zalo connectors and responder as a multi-tenant Cloudflare service configured from Tuturuuu.

**Status:** foundation in progress. The tables, RPCs, tenant and operator
APIs and the read-only operator view ship with every channel off; no channel
replies until the runtime slices pass their gates. Remaining
[open decisions](#open-decisions) are listed below. Pricing and cost of goods
are in [Mira managed pricing](https://docs.tuturuuu.com/platform/ai/mira-managed-pricing.md).

Mira runs as a managed, multi-tenant product: each Tuturuuu workspace that
enables Mira is a **tenant** with its own channels, persona, rules, people,
memory, keys, budgets and logs. Tuturuuu's own Mira is tenant #1 and uses the
same runtime as every paying tenant, with one documented exception: its
personal WhatsApp and Zalo sessions are hosted on the Mac desk host (see
[decisions](#decisions)).

## Scope and default

* **Scope:** inbound watchers, the responder loop and outbound delivery for
  Discord, WhatsApp and Zalo; tenant self-serve setup in the workspace; the
  operator view at `tuturuuu.com/admin/<wsId>/mira/channels`; usage metering and
  entitlements.
* **Default:** off. A channel replies only after its tenant enables Mira, the
  workspace holds the Mira entitlement, the channel is connected and passed
  the sandbox test, and every stop fence is open.
* **Builds on:** the apps/web [AI agent deployment](https://docs.tuturuuu.com/platform/ai/ai-agent-deployment.md)
  module (Chat SDK adapters, external chat mirror, identity mapping and tool
  allowlist) and the [Omni-channel Chat SDK](https://docs.tuturuuu.com/platform/ai/omni-channel-chat-sdk.md)
  boundary. The cloud runtime replaces the apps/web webhook loop and the
  self-hosted watchers; it keeps their data contracts.
* **Exceptions:** personal-account WhatsApp and Zalo automation runs only for
  the root (internal) workspace on the Mac desk host, and for paying tenants
  that opt in once the [personal opt-in](#personal-account-opt-in-paying-tenants)
  slice ships (see [decisions](#decisions)).

## Decisions

| Decision | Scope | Default | Exceptions |
| - | - | - | - |
| **Personal accounts stay on the Mac.** Mira's internal personal WhatsApp and Zalo accounts keep running on the Mac desk host. | Internal tenant personal sessions. The cloud runtime serves official channels (Discord bot, WhatsApp Business Cloud, Zalo OA and Bot) for every tenant, including the internal one, plus opted-in paying tenants' personal sessions (next row). | Host-side personal sessions get only the reduced registry projection, and that projection is off until the registry's personal-session setting is turned on. | No `SessionContainer` serves the internal tenant, and the cloud connect route refuses `personal` mode until the personal opt-in slice ships for paying tenants. |
| **Paying tenants may opt in to personal-account mode.** A tenant can connect its own personal WhatsApp or Zalo account after an explicit, recorded acknowledgement of the terms-of-service and ban risk. | Personal WhatsApp and Zalo accounts of paying tenants, through the [personal opt-in](#personal-account-opt-in-paying-tenants) design. | Off. Nothing is enabled until the slice is built and independently reviewed; then a tenant stays off until a Mira manager opts in. | The Tuturuuu owner's per-tenant personal block overrides any opt-in, and the tenant cannot clear it. The internal tenant keeps its Mac-hosted sessions. |
| **Meta and Zalo platform onboarding is deferred.** Tuturuuu is not onboarded as a Meta Tech Provider and has not completed Zalo OA developer verification. | WhatsApp Business Cloud (Embedded Signup) and Zalo OA connects for every tenant. | A well-formed connect answers `connect_unavailable` until a proof verifier is wired for its channel kind. The WhatsApp verifier and the Zalo OA path are not built until the onboarding is revisited, so a Zalo verifier that ships for Zalo Bot refuses `official` proofs with `invalid_proof`. | Discord (shared or bring-your-own bot) and Zalo Bot need no platform onboarding; their connects open when their proof verifiers ship. |

Regression coverage: `packages/internal-api/src/mira-channels.test.ts` (personal
connects are refused) and `apps/web/src/lib/mira-channels/service.test.ts`;
the database refuses `personal` channels outside the root workspace
(`apps/database/supabase/tests/mira-channel-tenants.sql`). The personal opt-in
slice keeps the refusal tests for tenants without current consent and adds its
acceptance suite (migration step 7.5).

## Architecture

```txt theme={null}
 Discord Gateway ──► DiscordGatewayDO (outbound WebSocket, per bot)
 Discord HTTP    ─┐
 WhatsApp Cloud  ─┼─► mira-tenant-signer | mira-fleet-signer (own routes) ─► mira-router ─► ConversationDO
 Zalo OA / Bot   ─┘   (signature, tenant lookup, rate limit)     (per conversation:
 Personal session ──► SessionContainer (opted-in tenants) ─────┘  ledger, order,
                                                                   lock, reply)
                                                                       │
                     TenantDO (per workspace: config snapshot, ◄───────┤
                     budget ledger, stop fence, quotas)                │
                                                                       ▼
                     LLM provider (OpenAI | Anthropic | Google) ◄── AI SDK
                                                                       │
                     mira-work Queue ──► mirror, memory writes, usage settlement,
                                         media copy, metrics export
```

All components live in one new Worker app, `apps/mira-channels`, configured with
`cf/config` like `apps/chat-realtime`. Portable logic (event normalization,
ledger rules, triage policy, prompt assembly, budget arithmetic) lives in a
framework-free package, `packages/mira-runtime`, with no `cloudflare:*`,
Next.js or request-global imports. The Worker injects storage, secrets, clock
and fetch.

### Components

| Component | Primitive | Responsibility |
| - | - | - |
| `mira-router` | Worker, service binding only | Has no public route. Exposes one entrypoint per signer domain, each bound only to that signer's script, and accepts an event only when the account belongs to the calling domain and the event matches the strict `InboundEvent` schema. Receives only verified, normalized `InboundEvent`s from the signers, applies per-account and per-sender rate limits, and routes to conversation objects. It never sees a raw provider request, header, secret or proof; its routing and rate state holds identifiers only. |
| `mira-tenant-signer` | Worker with its own public webhook routes | Verifies tenant channel events with the tenant provider credentials and signs People registry operations. Holds no Fleet material. See [event evidence](#event-evidence). |
| `mira-fleet-signer` | Worker with its own public webhook routes | Verifies the internal tenant's desk accounts and signs Fleet operations with the per-desk keys and bearers. Holds no tenant or registry material. |
| `DiscordGatewayDO` | Durable Object | Holds one outbound Gateway WebSocket per Discord application (and per shard when sharded). Heartbeats, resumes and identifies inside Discord's session budget. Runs inside the signer domain that owns the application, which treats its authenticated session as native verification, and forwards `MESSAGE_CREATE` events for linked guilds and DMs to the router. |
| `ConversationDO` | Durable Object, SQLite | One per tenant conversation. Replay ledger, ordering, burst coalescing, the per-conversation reply lock, rolling context, outbound send records and the owner-generation check before every send. Runs the responder from an alarm. |
| `TenantDO` | Durable Object, SQLite | One per tenant workspace. Versioned config snapshot, spend and token ledger with reservations, per-person rate limits, quiet hours, the tenant and channel stop fences. |
| `SessionContainer` | Cloudflare Container | Opted-in paying tenants only (see [personal opt-in](#personal-account-opt-in-paying-tenants)); the internal tenant's personal sessions stay on the Mac desk host. Runs a personal-account library that needs a long-lived Node process. Forwards signed connector envelopes to its domain's signer and executes only sends the owner fence dispatches. |
| `mira-work` | Queue + consumer | Off-critical-path work: Tuturuuu chat mirror, People & memory writes, usage settlement to Postgres, media copy to Drive, people snapshot invalidation, metrics export. |

### Object identity and tenant isolation

Durable Object names are built only on the server from resolved identifiers:

```txt theme={null}
ConversationDO  mira:conv:v1:<workspaceId>:<channelId>:<conversationKey>
TenantDO        mira:tenant:v1:<workspaceId>
```

`conversationKey` is a keyed hash of the provider account and provider
conversation id. Every object stores its `workspaceId` on first use and rejects
any request whose resolved tenant differs. A conversation object never receives
another tenant's config, keys, people snapshot or history. Secrets and leases
are fetched per workspace and held only in the owning object's instance
memory; module-scope caches of secrets, leases, provider clients or people
snapshots are forbidden, because objects of different tenants can share an
isolate.

### Channel binding

Routing by provider account is only as safe as the step that binds that
account to a tenant. A provider signature proves the event came from the
provider, not which tenant it belongs to. Therefore:

* `(provider, provider_account_id)` is unique across all tenants while bound.
  Re-binding requires the current tenant to unbind first; both steps are
  audited. Unbinding is refused while an operator, billing or cap stop is
  set, so a tenant cannot shed a stop it does not own; it purges the
  channel's vault variables and secret references, and an unbound channel row is
  kept (immutable) so its usage history and audit stay attached.
* The People registry's own channel binding is the authority for registry
  operations. Binding a channel writes the Mira binding and the registry
  binding in one flow and reports failure if either does not land; unbinding
  removes the registry binding first, which stops registry operations for that
  account immediately.
* WhatsApp numbers bind only from the Embedded Signup code exchange, after
  checking that the returned business account owns the `phone_number_id`.
* Discord guilds bind only from the OAuth install callback, with a signed
  single-use `state` tied to the workspace and actor, and a check that the
  installer holds `MANAGE_GUILD` in that guild.
* Zalo OAs bind only from the OAuth callback for that OA; Zalo bots bind from a
  token whose `getMe` identity is recorded.
* **Shared Discord bot DMs have no tenant.** By default a DM to the shared bot
  gets a fixed reply that names no tenant and spends no tenant budget. A DM
  routes to a tenant only through an explicit link the user starts from that
  tenant's guild (a button that records the user, guild and tenant).

## Per-channel decisions

### Discord

**Decision:** official bot. Two hosting modes, both cloud-only:

* **Shared Mira bot (default):** one Tuturuuu-owned Discord application that
  tenants install to their guild with an OAuth2 invite. One `DiscordGatewayDO`
  per shard carries every tenant guild; the guild maps to the tenant through
  the existing `discord_integrations` binding.
* **Bring-your-own bot (Pro option):** the tenant supplies its own application
  (custom name and avatar). One gateway object per application.

Gateway is required because message events are not delivered over HTTP. The
Interactions webhook (slash commands, buttons, the setup test) runs in the
tenant signer (or the Fleet signer for internal desks); it acknowledges within Discord's three-second window and
defers when the responder needs longer.

The bot reads messages that mention it, replies in threads and DMs, and needs
no privileged message-content intent for that. Passive reading of every guild
message (for watch rules) needs the privileged intent, which a shared bot can
hold only after Discord verification; until then passive watch is available
only on bring-your-own bots.

The WebSocket Hibernation API covers sockets a Durable Object accepts, not
outbound client sockets, so a gateway object stays resident while connected.
That costs duration for one object per shard, not per tenant, on the shared
bot. A watchdog alarm reconnects an evicted object; it runs only while the
application's connection lease is enabled and stops rearming when the lease
is revoked, the stop fence is set or the session budget is exhausted.

Discord allows 1,000 session starts (identifies) per application per day and
resets the bot token when that is exceeded, so the gateway object keeps a
durable identify counter, prefers resume (which does not count), and stops
reconnecting at 50 % of the daily budget. Gateway sends stay under 120 per
minute per connection. DMs arrive only on shard 0. REST calls share the 50
requests per second global limit per bot; interaction responses are exempt.

**Risk:** low. User-account automation (self-bots) is prohibited by Discord and
is not offered.

### WhatsApp

Gated on Meta Tech Provider onboarding, which is deferred (see
[decisions](#decisions)); the plan below applies once it completes.

**Decision:** paying tenants use only the official **WhatsApp Business Cloud
API**. Tuturuuu onboards as a Meta Tech Provider and offers Embedded Signup so a
tenant connects its own WhatsApp Business Account and number in the wizard.
Webhooks arrive at the tenant signer's route, signed with the Tuturuuu app secret, and
route by `phone_number_id` to the tenant channel.

Constraints the product surfaces honestly:

* Free-form replies are allowed only inside the 24-hour customer service
  window that a user message opens. Outside it, the tenant needs approved
  templates. Mira replies only inside the window and escalates to a human
  otherwise.
* Meta bills per delivered message. Service replies are free for the first
  1,000 per phone number per month and charged after that; templates are
  charged by category and market. Under the Tech Provider model the tenant's
  own payment method on its WhatsApp Business Account pays Meta directly, so
  these charges are not Tuturuuu cost of goods. The usage view shows the
  tenant's service-message count against the free tier.
* Embedded Signup admits 10 new business accounts per rolling seven days
  until Tuturuuu completes Meta's verification steps (200 after). Onboarding is
  throttled to that limit.
* Meta's policy limits WhatsApp Business assistants to the business's own
  purpose; general-purpose AI assistants are not allowed. The tenant persona is
  framed as that business's assistant, and the wizard states this rule.
* The Cloud API does not stream message edits. Mira sends the typing indicator
  immediately, then the reply as one message, or as paragraph-sized parts for
  long answers.
* The Groups API requires an Official Business Account and caps groups at
  eight participants, so Mira treats WhatsApp as one-to-one first and offers
  groups only to eligible accounts.

**Internal tenant:** the owner's personal account keeps the current unofficial
Web-client automation on the Mac desk host, with every limit below. Moving
that number to the Cloud API would remove it from the consumer app, so it
stays personal until the owner chooses a business number.

**Risk:** personal-account automation breaks WhatsApp's terms and can get the
number banned. Material; the owner decides whether the internal desk keeps it.

### Zalo

**Decision:** paying tenants use official routes only:

* **Zalo Official Account API** (gated on Zalo OA developer verification,
  which is deferred; see [decisions](#decisions)) for businesses with a verified OA on a tier that
  includes OpenAPI access (the tenant pays Zalo for the OA tier). OAuth v4 with
  PKCE for OA access tokens; the tenant object refreshes them using the
  returned `expires_in`. Each new single-use refresh token is written back to
  the vault by compare-and-swap before the old one is discarded; a failed
  write stops the channel and asks the tenant to reconnect, rather than
  losing the only valid token. Signed webhooks into the tenant signer. Consultation replies are
  free within Zalo's interaction window; reported per-user reply quotas inside
  that window must be confirmed against Zalo's official documentation before
  the OA route is offered, because a low quota would cap conversational use.
* **Zalo Bot platform** for tenants without an OA: a bot token, a webhook
  checked through the `X-Bot-Api-Secret-Token` header, and `sendChatAction`
  for typing. In groups the bot answers only when mentioned. The apps/web
  module already supports this mode.

**Internal tenant:** the owner's personal account keeps the `zca-js` route on
the Mac desk host, because a Zalo Web listener is a long-lived Node WebSocket
process with one active listener per account.

**Risk:** `zca-js` is unofficial automation and can trigger account locks or
bans. Material; the owner decides for the internal desk.

### Personal-account opt-in (paying tenants)

Personal-account automation breaks WhatsApp's and Zalo's terms and can get the
account locked or banned, so a paying tenant uses it only after an explicit,
recorded opt-in. The design below is not built; the connect route and the
database refuse `personal` channels outside the root workspace until it ships.

* **Acknowledgement text:** `private.mira_personal_ack_versions` holds each
  version's canonical text per locale with its SHA-256, unique on
  `(version, locale)` with `locale` limited to `en` and `vi`. Text rows are
  inserted only by an owner or migration session and stay unpublished.
  `private.mira_personal_ack_publications` holds one row per published
  version (version, actor, note, time), written only by the publish RPC. That
  RPC needs the Mira operator permission, a required note and compare-and-swap
  on the current version, refuses unless both locales exist, and runs the
  propagation below. The current version is the one in the newest publish
  row. Publishing halts every opted-in tenant's personal channels until a
  manager accepts the new text. Both tables have no update or delete grants
  and triggers reject update, delete and truncate, so a published text never
  changes. The setup wizard shows the current text before any personal
  connect; the accept RPC takes only the version and locale and computes the
  hash itself, never accepting text or a hash from the client. It refuses any
  version that is not current. Draft v1:
  * EN: "Personal-account automation breaks WhatsApp's and Zalo's terms of
    service. The account can be locked or banned permanently, and Tuturuuu
    cannot restore it. Messages in connected personal chats are sent to the AI
    provider Mira uses. You are responsible for telling your contacts that an
    AI will read and reply to their messages. Only use an account you accept
    the risk of losing."
  * VI: "Việc tự động hóa tài khoản cá nhân vi phạm điều khoản dịch vụ của
    WhatsApp và Zalo. Tài khoản có thể bị khóa hoặc cấm vĩnh viễn và Tuturuuu
    không thể khôi phục tài khoản đó. Tin nhắn trong các cuộc trò chuyện cá
    nhân đã kết nối sẽ được gửi đến nhà cung cấp AI mà Mira sử dụng. Bạn có
    trách nhiệm thông báo cho những người liên hệ của bạn rằng AI sẽ đọc và trả
    lời tin nhắn của họ. Chỉ sử dụng tài khoản mà bạn chấp nhận rủi ro bị mất."
* **Personal state:** `private.mira_personal_state` holds one row per
  workspace that ever opted in or was blocked: the personal block, the
  personal generation and the time Mira was deleted, if it was. It has no
  foreign key to workspaces or tenants and no delete path except the
  retention purge below, so deleting and re-enabling Mira cannot reset it.
* **Opt-in record:** `private.mira_personal_optins` holds one row per
  acceptance or revocation: workspace, kind, actor and time, plus the
  acknowledgement version, locale and server-computed SHA-256 for an
  acceptance (null for a revocation; the actor is null for a server-written
  one). It has no update or delete grants
  and a trigger rejects update, delete and truncate. `ws_id` has no foreign
  key to workspaces, so rows outlive the workspace as consent evidence. The
  only delete path is the retention purge, run by an owner session that sets
  a transaction-local purge flag. The trigger admits it only for a row whose
  superseding row for the same workspace is past the audit retention period,
  or that was created at or before the workspace's Mira deletion time in
  `private.mira_personal_state` once that time is past the period, and never
  for an existing workspace's newest row. A later deletion overwrites the
  deletion time. The state row goes with the workspace's last opt-in row.
  Only a Mira manager of a workspace with an active paid Mira entitlement,
  whose session is at MFA
  assurance level 2 verified within the last 15 minutes on the server, can
  accept; a manager without enrolled MFA is refused. A Mira manager revokes
  with an MFA assurance level 2 session, with no freshness window and no
  entitlement; the revocation that deletion appends is written by the server.
* **Consent is derived, not a stop reason:** a tenant has current consent
  while its newest opt-in row is an acceptance of the current version, its
  paid entitlement is active and Mira has not been deleted since that
  acceptance. No tenant, operator or system stop reason stands in for
  consent, so clearing a stop never resumes a channel without it.
* **Personal block:** the Tuturuuu owner's per-tenant block, set or cleared
  from the Admin operator view (Mira operator permission, a required note,
  compare-and-swap, audit). It lives in `private.mira_personal_state`, not in
  a stop reason and not in the `tenant` stop reason (kill switch). Neither a
  new acceptance, a revocation, clearing any stop reason nor deleting and
  re-enabling Mira clears it, and clearing it does not clear an abuse
  suspension.
* **Propagation:** accepting, revoking, setting or clearing the personal
  block, deleting Mira and publishing a version bump the personal generation
  in `private.mira_personal_state`, write first, push the new state
  synchronously to `TenantDO` and confirm by readback. Publishing bumps the
  generation of every workspace that has any opt-in row and pushes and
  confirms only for tenants with Mira enabled; the rest load the state on
  cold start. Accept and publish serialize on one lock
  (accept holds it shared, publish exclusive), so an acceptance cannot slip
  past a concurrent publish. Entitlement loss reaches the runtime through the
  `billing` tenant stop (fence 2), and `TenantDO` also revalidates consent
  against Postgres at least every five minutes, failing closed when it
  cannot. Lease grant, lease renewal, every recall, every model call and
  every send check consent and the personal block against that generation
  and fail closed when the state is stale or unknown. Losing consent or
  setting the block ends the session leases and stops the listener the way a
  stop does, so no contact's message is taken in after the lapse.
* **Default off, enforced in the database:** a trigger on every insert of a
  `personal` channel outside the root workspace, and on any update that makes
  one live or rebinds it (connection mode, workspace, a non-null account or
  credentials, or clearing a stop), refuses the row unless the tenant has
  current consent and no personal block. Any such change is checked even when
  the same update also sets a stop. An update that changes nothing else and
  only sets a stop, disables, marks the channel unbound or clears its account
  or credentials to null is always allowed, so revocation and the personal
  block can stop their own channels. The trigger takes `FOR SHARE` on the
  workspace's `private.mira_personal_state` row before reading consent, and
  the accept, revoke, block, publish and delete paths update that row (its
  personal generation), so under READ COMMITTED the trigger waits for them
  and under REPEATABLE READ or SERIALIZABLE it fails with `40001` instead of
  reading stale consent. It replaces the root-only check constraint.
* **Revocation:** commits at once and takes effect through derived consent.
  A durable, idempotent purge with bounded retries then revokes the connector
  keys, deletes the owning objects' auth-state rows and the wrapped per-tenant
  data key, purges the sealed session material from the vault and, as a best
  effort, logs the device out at the provider. The revoke readback reports the
  purge status, and the purge counts as complete only when no restorable
  session material remains.
* **People registry:** personal sessions get only the reduced projection: no
  memories, briefs, registry writes or Fleet operations, and only while the
  registry's personal-session setting is on, which is off by default.
* **Runtime:** a paying tenant's personal account runs in its own
  `SessionContainer` under the controls below. It has no fallback host; the
  Mac desk host serves only the internal tenant.
* **Pricing:** personal mode is not part of either plan yet; its price and the
  container cost are an open decision on the
  [pricing page](https://docs.tuturuuu.com/platform/ai/mira-managed-pricing.md#open-decisions).

### Personal-account controls

The internal tenant's personal sessions run on the Mac desk host; a paying
tenant's opted-in sessions run in a `SessionContainer`. The container rules
below apply to those containers, and the pacing, lease, sealed-session,
reconnect and stop rules apply to both hosts.

* One container per personal account, `max_instances = 1`, with a session
  lease in the tenant object so two runtimes never listen at once.
* Cloudflare Containers have no always-on guarantee and an ephemeral disk:
  an instance can stop on deploy rollouts or host maintenance and starts again
  from the image. Library auth state (the WhatsApp multi-file state is about
  850 small keys that change during normal use) is therefore stored in the
  owning Durable Object's SQLite, encrypted with a per-tenant data key,
  written in batches, and restored on start. The data key is wrapped by the
  versioned key-encryption key described in [secrets](#secrets) and rotated
  with it; only that tenant's session object unwraps it, in instance memory.
  The vault holds the long-lived root credential. Restarts are counted,
  because frequent re-logins from new addresses raise ban risk; above a daily
  restart budget the channel stops and pages the tenant's Mira managers and the
  Tuturuuu operator. Paying-tenant containers have no fallback host; the
  internal tenant's sessions run only on the Mac desk host.
* Human-like pacing: per-conversation send spacing, a per-day outbound cap,
  no unsolicited first messages, no bulk sends, quiet hours honored.
* The Zalo cookie session is sealed in the vault and written back by
  compare-and-swap when the library refreshes it. Session material never
  appears in container logs or on the container's disk outside the process's
  working memory.
* Reconnect with capped exponential backoff and a daily reconnect budget;
  repeated login failure or a lock signal stops the channel and pages the
  tenant's Mira managers and the Tuturuuu operator instead of retrying.

## Responder pipeline

### Ingress to reply

1. **Verify and route** (signer, then router): check the provider signature, drop
   non-message events, resolve the tenant channel, rate-limit by provider
   account and sender, then call `ConversationDO.ingest(event)`.
2. **Record** (conversation object): insert the provider event id into the
   ledger inside one SQLite transaction. A duplicate returns the stored
   outcome and does nothing else. The provider gets its acknowledgement only
   after the record commits, so a crash before commit is redelivered by the
   provider rather than lost.
3. **Coalesce:** a short burst window (default 700 ms, tunable per channel,
   zero for a single message in a DM) merges rapid messages from one sender
   into one turn.
4. **Gate:** check the global, tenant and channel stop fences, entitlement,
   quiet hours, per-person rules and budget (a reservation against the
   tenant object). A closed gate records the reason and, when the rules say
   so, tags or escalates instead of replying.
5. **Triage** (group conversations and watch rules only): a cheap model with
   structured output decides `ignore | reply | tag_owner | escalate` and the
   reply tier. Direct messages from people with a reply rule skip triage.
6. **Respond:** the alarm handler builds the prompt, signals typing, streams
   the model output through the AI SDK and delivers it (see
   [streaming](#streaming-per-channel)).
7. **Settle:** record the outbound send, release the unused reservation, and
   enqueue mirror, memory and usage work.

The responder runs in a conversation object alarm instead of a Queue consumer,
because an alarm fires immediately on the object that already holds the
conversation state and lock; a Queue hop adds batching delay to the critical
path. Queues carry everything that can finish after the reply. Every queue
has a dead-letter queue with a consumer and a bounded `max_retries`, because
Cloudflare deletes messages that exhaust retries when no dead-letter queue is
set.

### Exactly-once boundaries

* **Inbound:** at-least-once delivery from providers, deduplicated by the
  ledger key `(channel, provider account, provider event id)`.
* **Outbound:** at-most-once. The conversation object hands each send to the
  owner fence for its `(channel, account)` (see [migration](#migration)),
  which writes `send_started` with a deterministic idempotency key. Discord sends
  carry it as an enforced nonce. WhatsApp and Zalo have no send idempotency, so
  a send whose outcome is unknown after a crash is marked `uncertain`, never
  retried automatically, and shown to the operator. This guarantees no double
  send; the rare uncertain case is surfaced instead of silently resent.
* **Alarm retries:** each turn has a bounded attempt budget (default 3) and an
  age limit (default 10 minutes, then escalate). Attempts persist in SQLite and
  do not reset on restart. A completed or abandoned turn never reschedules.
  Each object has one multiplexed alarm (coalescing, responder, token refresh
  and watchdog deadlines in one table). The handler catches every error and
  records the attempt itself, so Cloudflare's automatic alarm retry never adds
  attempts outside the budget. The tenant token-refresh deadline is cleared
  while the tenant is stopped or disabled.
* **Replay horizon:** ledger keys are stored apart from conversation context
  and kept for at least the longest provider redelivery horizon (seven days
  for Meta). Events whose provider timestamp is older than the turn age limit
  are recorded and never answered. Discord interaction timestamps and Zalo
  event timestamps are checked against a five-minute window.

### Models and keys

* **Providers:** OpenAI, Anthropic and Google through `@ai-sdk/openai`,
  `@ai-sdk/anthropic` and `@ai-sdk/google`. A provider instance is created
  per tenant call with the key from the tenant's lease, so a key never
  crosses tenants or persists beyond the lease.
* **Key modes:** `managed` (Tuturuuu keys, metered through AI credits) or
  `byok` (the tenant's own key in its vault environment). Selected per tenant,
  overridable per channel.
* **Presets:** `fast` (cheap tier, short replies, triage on the same tier) and
  `quality` (frontier tier for the reply, cheap tier for triage). The tenant
  picks a preset or an explicit model from the [model catalog](https://docs.tuturuuu.com/platform/ai/model-catalog.md).
* **Prompt caching:** prompts are assembled stable-prefix first: system
  persona, tool schemas and tenant knowledge, then the person snapshot, then
  the conversation. Anthropic calls set cache breakpoints after the prefix and
  after the person snapshot; OpenAI calls set a per-tenant `promptCacheKey`;
  Gemini relies on implicit prefix caching. Cache hit ratio is a tracked metric.
* **Token budgets:** per-turn input ceiling (history is trimmed and
  summarized beyond it), per-turn output cap from the preset, and the shared
  output cap rules in [usage accounting guards](https://docs.tuturuuu.com/platform/features/usage-accounting-guards.md).

### Spend caps and the durable stop fence

The tenant object keeps a ledger per day and per billing month:

* A turn reserves its worst-case cost (input estimate plus output cap at the
  model's price) before calling the model, and settles to actual usage after.
  Missing prices fail closed.
* When a reservation would exceed the tenant's daily cap, monthly cap or plan
  quota, the turn does not run; the channel replies with the configured
  fallback (or stays silent) and the tenant is notified once per period.
* Stop fences, checked before every model call, every send and every
  reschedule, including inside racing callbacks:
  1. Global: the `MIRA_CHANNELS_STOPPED` Worker secret, flipped without a deploy.
     A durable global fence object, polled by every resident object at least
     every 30 seconds, backs the secret so a stop reaches running gateway
     objects and containers without a restart.
  2. Tenant: a durable set of stop reasons, each with an owner: `tenant`
     (kill switch), `operator` (abuse suspension), `billing` (entitlement
     loss) and `cap` (spend cap, cleared by the system at the next period or
     when a raised cap is saved; any raise clears it, and the next
     reservation that still exceeds a cap sets it again).
     The fence is closed while any reason remains. A resume clears only the
     reasons its caller owns, so a tenant manager cannot lift an operator or
     billing stop. Each change bumps the tenant generation.
  3. Channel: the channel's persisted reason set and generation, with the
     same ownership rule.
  4. Personal channels also need current consent and no personal block,
     checked at the same points (see
     [personal opt-in](#personal-account-opt-in-paying-tenants)).
* A stop ends resident work as well as new work: the gateway object drops the
  tenant's guilds from forwarding (or closes the socket for a stopped
  bring-your-own bot or a global stop), the session container stops its
  listener, and every Queue and dead-letter consumer checks the fences
  before acting.
* A stop does not delete pending turns; they are kept for resume and expire
  by age.

### Streaming per channel

| Channel | First visible signal | Delivery |
| - | - | - |
| Discord | Typing indicator at gate pass | Post after the first sentence, then edit at most once per second until done |
| WhatsApp Cloud | Typing indicator with read receipt | One message, or paragraph parts for long replies |
| Zalo OA / Bot | Typing action where supported | One message, or paragraph parts |
| Personal sessions | Library typing event | One message, paced |

Model output is sanitized before every send: Discord messages carry
`allowed_mentions` with no parsed mentions (reply-to only) and suppressed
embeds; markdown image links are removed and bare links are not unfurled on
every channel, so injected output cannot ping crowds or leak context through
crafted preview URLs.

### Memory and people

The responder reads people and memory only from the
People registry on tuturuuu.com. Each
tenant workspace has its own `responder` principal, registered when Mira is
enabled and revoked on disable or delete. Requests are signed with that
principal's Ed25519 key (method, path, body hash, audience, principal,
timestamp and a single-use nonce); there are no bearer tokens.

* **Evidence-bound recall:** every recall and write carries signer-issued
  event evidence from the tenant signer (see [event evidence](#event-evidence)).
  The registry derives the person and conversation from that evidence, so the
  request body carries no sender or conversation id. One provider event
  supports one recall and at most one write bundle.
* **Revalidated cache:** the conversation object keeps the last snapshot with
  its `version` and `consent_version`, but never serves it on age alone. On
  official channels each turn starts with full recall carrying `if_version`
  (personal sessions use the separate addressing projection below, with no
  versions and its own cache namespace); the registry answers
  `not_modified` or a fresh snapshot after live consent, suppression and
  status checks. If that check fails or misses its 150 ms budget, the turn
  runs with no person context and default behavior. Recall runs in parallel
  with the typing signal and prompt assembly.
* **Invalidation:** events `{event_id, workspace_id, person_id or
  conversation_id, version, consent_version, kind}` arrive on the work Queue
  with an `event_id` monotonic per workspace and a dead-letter queue. Fills
  older than the cached version and fills for tombstoned people are dropped;
  `revoke` and `delete` purge immediately.
* **Chat-safe projection:** recall returns enumerated rules and memories only
  about the current conversation or its members. In groups that excludes
  private memories, because everyone in the group reads the reply. Recalled
  content is data, never instructions; tools and sends are decided outside
  the model.
* **Writes** go through the Queue with idempotency key
  `(channel, provider account, provider event id)`, the same tuple used for
  enqueue, dedupe and receipt lookup everywhere, and provenance, consuming the event id in
  the shared replay table. Refusals (`consent_required`, `suppressed`,
  `deleting`, `revision_conflict`, `scope_denied`) are recorded as rejected
  with their reason, never retried as if transient.

### Reply rules

Rules mirror the registry's per-chat, per-person and per-channel model and
resolve chat before person before channel before tenant. The tenant default
is **never silent**: every message that addresses Mira (a direct message, a
mention, a reply to Mira or a ping of Mira's role) gets a reply or, for a
muted person, an acknowledgement. Groups get replies only when addressed.
Quiet hours shorten replies and never skip them. Mira never starts a
conversation. Commitments get a holding line and go to the escalation
target. An optional, expiring owner-instruction rule on a named group treats
the owner's untagged clear instructions as requests (triaged, then
acknowledged and relayed). The pure evaluation lives in
`@tuturuuu/mira-runtime` (`decideReply`).

### Event evidence

Verification and signing are split into two independently permissioned
Workers, each a separate script with its own public webhook routes, secrets
and scoped vault, service and storage bindings. Each provider webhook points
at the entry route of the domain that owns the account, so a secret-bearing
request (a Meta signature, a Zalo Bot secret header, a Discord signature)
never passes through shared infrastructure. Neither signer can reach the
other's credentials. The shared `mira-router` receives only verified,
normalized events, so it never sees a secret or a proof and cannot forge,
replay or redirect one.

* **`mira-tenant-signer`:** provider credentials for tenant channels and the
  People registry signing key. Signs only `registry.recall` and
  `registry.write`.

* **`mira-fleet-signer`:** verification material for the internal tenant's
  desk accounts and the per-desk Fleet keys and bearers. Signs only
  `fleet.identity_verify`, `fleet.intent_submit` and `fleet.digest_read`.

* **Credential scope:** provider credentials are scoped per provider app or
  account wherever the provider allows it (a Discord public key per
  application, a Zalo OA secret per OA app, a Zalo Bot secret per bot, a
  WhatsApp business token per tenant account). The Meta app secret is per
  Tuturuuu Meta app and lives only in the tenant signer; the internal desks
  use their own app or account credentials in the Fleet signer.

* **Rotation and revocation:** each provider secret is versioned. Rotation
  verifies with both versions during a bounded overlap, then removes the old
  one; revocation removes it immediately and fails closed. Both paths are
  rehearsed before launch and audited.

* **Admission records:** for every verified event the signer signs, with
  its admission key, the entire canonical normalized event (every field the
  runtime decides on: channel, account, event id, sender, conversation and
  type, addressing flags, timestamps and content hash) together with the
  destination conversation object name, workspace and issue time. The
  conversation object verifies the signature with the signer's public key
  and checks the destination and workspace against its own before
  ingesting, so the router cannot fabricate, alter (including substituting
  the sender for the same destination) or retarget an event.

* **Logging:** neither the signers nor the router log or trace raw headers,
  bodies, signatures or proofs. Invocation logs and tail consumers are off
  for the signers; errors carry codes only. Redaction is covered by tests in
  both signers and the router.

* **Native verification first:** Meta `X-Hub-Signature-256`, Zalo event
  signatures and the Zalo Bot secret header, Discord Ed25519 for
  interactions, and the gateway object's authenticated session for Gateway
  events. Where a provider offers native verification, nothing else is
  accepted.

* **Connector envelopes (personal sessions only):** a container signs an
  envelope binding the original timestamp, event id, account, sender,
  conversation, conversation type and content hash. Each connector key is
  limited to one account and is valid only while that account's live session
  lease is held; revoking the lease revokes the key. Because a compromised
  container could attest arbitrary senders for its account, these channels
  get **no Fleet operations and no registry writes**. Registry recall from
  them returns only a reduced projection (rules and owner-entered addressing
  facts for identities the owner confirmed; no memories or briefs), and only
  while the registry's personal-session setting is on, which it is not by
  default and rechecked on every recall. That projection carries only
  addressing facts and speech rules, plus a server-computed delivery (send,
  shorten, hold or draft) where a routing decision is needed; it has no ids,
  versions or `if_version`, is capped per session at one recall per event,
  and is cached in a separate namespace that full-recall callers never read.
  Otherwise they run with default behavior and no person context.

* **Typed private operations:** one typed operation per use, each owned by
  one signer as listed above. The owning signer derives parameters and the reply destination from the verified event and
  policy, builds and hashes the exact UTF-8 body, and sends it to a fixed
  endpoint per operation. The caller supplies no URL, body or account.

* **Separate key domains:** Fleet operations use the registered per-desk keys
  with the Fleet proof audience; registry operations use the versioned Mira
  registry key set (with `kid`) and the `people-registry` audience. Both
  verifiers reject a proof from the other domain. Internal Fleet desk
  accounts are never on the tenant registry path.

* **Allowlist per operation and conversation type:** Fleet operations only
  for the internal tenant's desks and only for verified private one-to-one
  conversations. Registry operations for any `(channel, account)` bound to the
  requesting workspace in the registry's live binding table, in one-to-one or
  group conversations, after the provider confirms the sender's membership.

* **Replay slots:** one atomic consume row per
  `(channel, provider account, provider event id)` with typed slots, owned by
  the Fleet consume wrapper. Fleet keeps one slot per event across all Fleet
  operations and desk ids. A Fleet slot and a `registry.write` slot are
  mutually exclusive for the same event; `registry.recall` may coexist with
  either. There is no standalone observe operation: observations travel in
  the write bundle. Queue work is keyed by the same
  `(channel, account, event)` tuple. Personal-session recall is outside this
  ledger: its one-recall-per-event cap is kept by the registry separately
  and never consumes a Fleet or registry-write slot. The write is a single
  bundle of every observation and memory derived from that event, committed
  atomically by the registry and consumed through its own replay wrapper; a
  retry with the same input hash returns the original receipt, and a
  different bundle for a consumed event is refused.

* **Freshness and budgets:** the original provider age is checked on every
  signing attempt, including Queue and object redelivery. Each provider event
  has one durable aggregate attempt limit (default 5) across all its slots
  and redeliveries, so a slot split never multiplies attempts. Live grant and stop
  generations are rechecked at admission and before each send or edit.
  Uncertain results are reconciled before any retry; terminal work never
  reschedules.

* **Fleet content routing:** Fleet-bound events (link codes, intents, digest
  questions) are diverted at the Fleet signer before any generic persistence,
  prompting or queueing, refused events included. Fleet answers are tool-free
  and use only the caller's authorized digest. Quotes go only to the Fleet's
  redacted display storage; quotes, claims, codes and digests never enter
  generic prompts, memory, the chat mirror or telemetry.

* **Rotation:** each desk has its own key and bearer. Rotation adds the new
  verifier to Web, switches the Fleet signer, then removes the old verifier;
  revocation removes the verifier first. Rollback re-registers the previous
  verifier only while its key is still held and unexpired. Registry keys
  rotate by publishing a new `kid` before signing with it.

### Fleet access desks

For the internal tenant, `mira-fleet-signer` is the trusted ingress for the
[Fleet access](https://docs.tuturuuu.com/platform/features/fleet-access.md) desks (Fleet Slice 4). Each
cloud desk has its own desk id, bearer and key. While the cloud runtime only
observes, its desk is not registered in `FLEET_DESKS`, and it performs no live
Fleet reads, writes, sends or backlog promotion.

Registration prerequisites:

1. Fleet Slice 4 ships `digest.read`: Web atomically consumes the event,
   resolves the linked actor and private conversation, and enforces live
   scope, stop and question quota before returning a scoped digest. Generated
   answers also require `ask` and model budget. Desk credentials carry no
   approval authority.
2. Fleet Slice 4 adds the owner generation to the desk config and enforces it
   at admission.
3. The independent Fleet review approves and these acceptance gates pass:
   * forged envelopes, group or wrong-conversation evidence, cross-tenant and
     cross-account substitution, and operation or body changes are refused;
   * Fleet proofs are refused by the registry and registry proofs by Fleet;
   * each event is consumed once across operations and desk ids, stale
     redelivery after restart is refused, and attempt budgets hold;
   * stop and revocation races at admission, dispatch and send are refused;
   * question quota and model budget are enforced;
   * key rotation, revocation and rollback work with in-flight events;
   * Fleet content never reaches prompts, memory, the mirror or telemetry,
     answers are tool-free and logs are redacted;
   * shadow performs zero Fleet effects; partial cutover, mixed versions and
     rollback with in-flight work are rehearsed, including a paused sender,
     a stale Web replica, clock skew, fence failover, delayed provider
     completion, lost provider receipts, an M4 returning after its token
     expired and an M4 returning after it redeemed a token, in both
     directions;
   * admission refuses any mismatch between the bearer's desk, the verifying
     key's desk and credential version, the claims and the live desk-owner
     row;
   * conversation objects reject router submissions that are fabricated,
     retargeted to another destination, or altered for the same
     destination (including a substituted sender);
   * the two signers cannot reach each other's credentials, provider secret
     rotation and revocation work, and no raw headers, bodies or proofs
     appear in logs or traces;
   * exact-commit CI and staging run on the emitted Worker, with Cloudflare
     operation counts, restart and poison-retry bounds, terminal scheduling
     and a hosted stop rehearsal recorded in the adoption guidance.

The owner-generation fence for cutover is described in [migration](#migration);
Fleet desks use the same fence.

## Configuration

### Data model

Postgres tables in the `private` schema, reached only by server-owned RPCs
from apps/web and the Worker. The Worker connects through Hyperdrive as a
dedicated least-privilege role with `EXECUTE` on the Mira RPCs and no table
grants; RLS does not apply to that role, so every RPC checks its workspace
argument against the stored channel binding.

| Table | Holds |
| - | - |
| `mira_tenants` | workspace id, enabled, plan entitlement snapshot, key mode, preset, caps, stop generation |
| `mira_channels` | tenant, channel kind, connection mode, provider account id, status, health, config version |
| `mira_channel_secret_refs` | vault environment and variable names per channel; never values |
| `mira_personas` | system prompt, tone, knowledge source refs, escalation contacts, versioned |
| `mira_rules` | per-person and per-group rules: reply, tag owner, escalate, mute; quiet hours |
| `mira_usage_daily` | settled messages, tokens (input, cached, output), cost, per tenant, channel, model and day |
| `mira_usage_receipts` | settlement receipt ids, so Queue redelivery never counts usage twice; pruned on Cloudflare after a retention window longer than Queue redelivery |
| `mira_audit_events` | append-only config, connect, stop, resume, export and delete events |
| `mira_personal_ack_versions` | personal opt-in acknowledgement texts per version and locale with their SHA-256 (insert-only; see [personal opt-in](#personal-account-opt-in-paying-tenants)) |
| `mira_personal_ack_publications` | one insert-only row per published acknowledgement version; the newest is current |
| `mira_personal_optins` | append-only personal opt-in acceptances and revocations |
| `mira_personal_state` | per-workspace personal block, personal generation and Mira deletion time; survives deleting Mira |

Every Admin save increments the tenant `config_version` and pushes the new
snapshot to the tenant object; the object also pulls on cold start and when
it sees a newer version on a conversation call. Existing `AI_AGENT_REGISTRY`
workspace-secret entries migrate into these tables per channel.

### Secrets

Connector tokens, the WhatsApp system user token, Zalo OAuth tokens, personal
session blobs and BYOK model keys live in a per-tenant `mira-connectors`
environment of the secrets vault, granted to the `mira-channels` workload
principal. That environment is labelled server-readable. The Worker reads
values with a one-hour lease bound to the workload, workspace and environment,
keeps them only in memory, and writes refreshed session blobs back by
compare-and-swap. Until the vault workload tier ships, the same interface is
served by an envelope-encrypted server-custody store whose key-encryption key
is a Worker secret (never stored in Postgres), versioned so rotation re-wraps
tenant keys without downtime. Every lease names a workspace, and the vault
checks it against the channel binding before releasing a value. Rotation
is detected by checking versions at each lease renewal and on cold start;
rotation callbacks are only hints. A value verified within the current,
unrevoked lease stays usable in instance memory until that lease ends (at
most one hour) even if the vault witness is unreachable, while new fetches
and renewals fail closed and a revoked lease drops plaintext at once. A failing
BYOK key stops the tenant's replies with a visible error; it never falls back
to managed keys. Values never appear in logs, metrics, Queue payloads, error
messages or API responses; provider and AI SDK errors are redacted before
`console.*`.

### Surfaces

* **Tenant self-serve** (workspace settings, entitlement-gated): the setup
  wizard, channel list, persona, rules, quiet hours, model and keys, caps,
  usage, health, export and delete.
* **Operator view** (`/admin/<wsId>/mira/channels` and
  `/mira/channels/<channel>` in apps/admin, under Fleet and
  Mastermind): every tenant's health, latency, cost, errors and abuse signals,
  operator suspension, the personal block, acknowledgement version publishing
  and the global stop. It shows no message content;
  uncertain-send and error records show metadata only. Content access needs
  an audited break-glass step.
* **Tenant API:** typed routes under `apps/web/src/app/api/v1/workspaces/[wsId]/mira/**`
  with zod contracts and clients in `packages/internal-api`, serving the
  tenant surfaces only. Reads require workspace membership with the Mira view
  permission; writes, connects, caps, kill switches and deletes require the
  Mira manage permission and are enforced in the route. Tenant routes accept
  only the `tenant` stop reason and reject `operator`, `billing` and `cap`.
* **Operator API:** a separate root-scoped surface under
  `apps/admin/src/app/api/v1/infrastructure/mira/**`, gated by
  root-workspace admin plus a dedicated Mira operator permission in the route
  (the same pattern as the abuse-intelligence routes). It serves cross-tenant
  health and cost reads, operator suspension, the personal block,
  acknowledgement version publishing and the global stop. It never
  reuses tenant routes, so tenant membership checks stay unwidened.
* **Writes on both surfaces:** kill switches write first and confirm by readback;
  the UI never shows optimistic success. Secret fields are write-only and show
  only connected state and timestamp.

### API contract

Tenant routes live under `apps/web/src/app/api/v1/workspaces/[wsId]/mira`;
operator routes under `apps/admin/src/app/api/v1/infrastructure/mira`.
Both validate bodies with zod schemas exported from `packages/internal-api`,
call only the `private.mira_*` RPCs, and return the RPC error code mapped to
HTTP (`40001` → 409, `42501` → 403, `P0002` → 404, `23505` → 409,
`22023` → 400).

| Method and path | Permission | Body | Response |
| - | - | - | - |
| `GET /workspaces/:wsId/mira` | Mira view | none | tenant settings, persona, bound channels with secret names and connected times, stop reasons and generations, `configVersion` |
| `PATCH /workspaces/:wsId/mira/settings` | Mira manage | `{ expectedConfigVersion, settings }` with `enabled`, `keyMode`, `preset`, `modelId`, `neverSilent`, `quietHours`, `dailyCapMicroUsd`, `monthlyCapMicroUsd` | `{ configVersion }` |
| `POST /workspaces/:wsId/mira/stop` | Mira manage | `{ channelId?, stopped, expectedGeneration }`; the reason is always `tenant` | `{ stopReasons, stopGeneration }`, confirmed by a readback |
| `POST /workspaces/:wsId/mira/channels/:kind/connect` | Mira manage | provider proof per kind and mode (Embedded Signup code, OAuth callback state, bot token); `personal` mode is refused | `{ channelId }`; failures return only `invalid_proof`, `expired_state` or `already_bound`, never provider text, and proof is never echoed or logged. `connect_unavailable` (503) while no verifier is wired for the kind, `invalid_request` (400) for an unknown kind and `not_found` (404) before the first settings save creates the tenant |
| `DELETE /workspaces/:wsId/mira/channels/:channelId` | Mira manage | none | `{ unbound }`; 403 while a stop the tenant does not own is set on the channel or the tenant; `vault_unavailable` (503) while the channel names vault secrets that cannot be purged first |
| `GET /workspaces/:wsId/mira/usage` | Mira view | `?from&to` (at most 400 days; defaults to the last 30 days) | daily usage per channel and model, money in micro-USD |
| `GET /infrastructure/mira/tenants` | root admin + Mira operator | `?after&limit` (limit at most 100) | per-tenant overview: enabled, stop reasons, channel counts, `lastErrorAt`, seven-day cost (micro-USD) and replies, plus seven-day error count and p95 first-token latency merged from Analytics Engine in one batched query; `metrics.status` is `unavailable` until the channel Worker emits them |
| `POST /infrastructure/mira/tenants/:wsId/stop` | root admin + Mira operator | `{ channelId?, stopped, expectedGeneration, note }`; the reason is always `operator`; `note` is required, at most 500 characters | `{ stopReasons, stopGeneration }`, confirmed by a readback |
| `GET /infrastructure/mira/global-stop` | root admin + Mira operator | none | `{ stopped, generation, updatedAt, updatedBy }` |
| `POST /infrastructure/mira/global-stop` | root admin + Mira operator | `{ stopped, expectedGeneration, note }` | the same shape as the read, confirmed by a readback |
| `GET /infrastructure/mira/audit` | root admin + Mira operator | `?wsId&before&limit` (limit at most 100) | audit rows: actor, workspace, channel, action, reason, old and new generation, note |

Billing adjusts caps through the same settings RPC with the `billing`
authority from its own server path; no HTTP route exposes that authority.

Permissions: Mira manage is `manage_ai_agents` and Mira view is
`view_ai_usage` (manage implies view), the permissions of the AI agent
deployment module the runtime builds on. The Mira operator permission is
`operate_mira_channels`, an explicit-grant permission (`EXPLICIT_GRANT_PERMISSIONS`
in `@tuturuuu/utils`): workspace creators, `admin` and default permissions
never imply it, the role editor cannot grant it, and database triggers refuse
it as a default permission, outside the root workspace, and for any API
session that enables it on a role or adds a member to a role holding it. A
grant runs on a database-owner session that sets
`tuturuuu.mira_operator_grant = 'owner'` for the transaction. The Admin
navigation shows Mira channels only to root admins holding it. Operator writes
are cookie-only, so each also needs same-origin intent: a JSON body, an
`Origin` equal to the request origin, `Sec-Fetch-Site` absent or
`same-origin`, and the `x-mira-operator-action: 1` header that the
internal-api client sends.

The channel route segment is one dynamic segment named `[channel]`: it holds
the channel kind under `connect` and the channel id on `DELETE`. Server code
reaches the RPCs through `@tuturuuu/internal-api/mira-channels-rpc`, which
parses every RPC result with the contract schemas and reports failures only
as typed codes. Unbinding purges the channel's named vault variables before
the unbind RPC runs; provider proof verifiers and the vault purger are wired
with the channel Worker and the vault workload tier.

Stop semantics: `stopped: false` clears only the caller's own reason (a
tenant clears `tenant`, an operator clears `operator`); other owners' reasons
stay set and are listed in the response. A stale `expectedGeneration`
returns 409, so two operators acting at once cannot silently undo each
other. Tenant and operator routes always send `expectedGeneration`; the RPC
accepts its absence only for system callers. Every stop change, tenant or operator, writes an audit row; operator
changes carry their note. The global fence row is the source the channel
Worker's fence object reads.

Operator routes are served at `tuturuuu.com/admin/api/v1/infrastructure/mira/**`.
Their client in `packages/internal-api` builds URLs from the Admin app base
path, never a fixed host, and the route sources keep app-relative imports so
they move with the Admin app unchanged. Operator routes are registered as
`ADMIN` in the Admin route inventory and tenant routes in the web inventory.
The dedicated Mira operator permission is granted to nobody by default; root
admin alone is not enough. Operator routes rely on the Admin session (MFA
assurance) and accept no scheduled caller. The Admin proxy refuses any
client `Authorization` header on these paths, so the session refresh and its
MFA, sign-out and ban checks always run, and the only bearer a route sees is
the app-session token that refresh attaches; the route also refuses API keys,
cron secrets and every other bearer.

### Setup wizard

Target: first reply in under ten minutes.

1. **Channel:** Discord invite (shared bot) or BYO token; Zalo Bot token;
   WhatsApp Embedded Signup and Zalo OA OAuth once their onboarding completes
   (see [decisions](#decisions)).
2. **Persona:** name, purpose, tone, instructions; optional knowledge sources
   (workspace documents and URLs ingested through the existing memory and
   Drive paths).
3. **People and rules:** default reply policy, per-person and group rules,
   quiet hours, escalation contact.
4. **Model:** preset or explicit model; managed or BYO key.
5. **Sandbox:** a simulated conversation through the real pipeline with sends
   captured instead of delivered, then a live round trip to the tenant's own
   account.
6. **Go live:** enable, with caps prefilled from the plan.

## Observability

Each turn writes one Workers Analytics Engine data point (tenant index; blobs
for channel, model, preset, outcome; doubles for timings, tokens and cost) and
no message content.

| Signal | Measure | Target |
| - | - | - |
| Ingress acknowledgement | provider request to response | p95 under 150 ms |
| First visible signal | provider event time to typing indicator | p95 under 500 ms |
| First token | provider event time to first model token, `fast` preset | p50 under 900 ms, p95 under 2 s |
| First content delivered | provider event time to first sent message, `fast` preset | p50 under 1.8 s, p95 under 4 s |
| Cost per message | settled cost per replied turn | tracked per tenant and preset |
| Errors | failed turns, uncertain sends, provider 4xx/5xx, reconnects | uncertain sends under 0.01 % |
| Saturation | alarm backlog, Queue depth and age, gateway session budget | alert on growth |

These feed the observability lane's golden-signal views and Mastermind; the
operator view reads them per tenant and the tenant view reads only its own.
The SLA target for paying tenants is 99.9 % monthly availability of the
ingress and responder, excluding provider outages.

## Cost model

Per-unit costs and assumptions are in
[Mira managed pricing](https://docs.tuturuuu.com/platform/ai/mira-managed-pricing.md#cost-of-goods).
The internal tenant's volume over the seven days to 2026-11-21 was about 80
inbound messages a day (Zalo about 51, mostly groups; Discord about 27; WhatsApp
under 5) and about 60 replies a day. Monthly: about 2,500 triaged messages and
1,800 replies.

| Item | Today's volume | 10× volume |
| - | - | - |
| Replies, `quality` preset | 1,800, about \$13.50 | 18,000, about \$135 |
| Triaged messages | 2,500, about \$0.25 | 25,000, about \$2.50 |
| Workers, Durable Objects, Queues, Analytics Engine | under \$0.10 | about \$1 |
| Discord gateway object | about \$4 | about \$4 |
| Personal-session containers (the internal tenant's sessions stay on the Mac; opted-in paying tenants add about \$8 per account per month on the `basic` class; their price is an open decision) | \$0 | \$0 |
| Total | about \$18 | about \$144 |
| Workers Paid base | \$5, shared with other Workers | \$5 |

Billable work is bounded per wake: one turn per alarm, at most three
attempts per turn, one gateway object per shard with a daily identify budget,
and a capped number of Queue retries before the dead-letter queue. The
runaway-work acceptance evidence (operation counts in normal and failure
cases, stop-versus-reschedule tests and the hosted stop procedure) is recorded
in the [Cloudflare adoption guidance](https://docs.tuturuuu.com/build/development-tools/oxc-cloudflare-adoption.md#runaway-work-and-cost-acceptance)
with the first deployable slice.

## Threat model

| Threat | Control |
| - | - |
| Malicious tenant reads another tenant's data | Server-built object names, stored tenant check in every object, per-workspace leases and principals, private tables reached only by RPCs that check the workspace against the stored channel binding (the Worker role has no table grants), no shared conversation state |
| Prompt injection from inbound messages or recalled memory | Inbound text and memory are data in the prompt, never instructions; tool allowlist per tenant; writes require a mapped Tuturuuu user with the needed permission; Fleet quotes never reach execution |
| Spoofed webhooks | Provider signature checks (Meta `X-Hub-Signature-256`, Zalo event signature, Discord Ed25519), tenant resolved from the verified provider account, not from the URL alone |
| Denial of wallet on managed keys | Reservations before model calls, daily and monthly caps, plan quotas, per-person and per-conversation rate limits, global and tenant stop fences |
| A tenant spams through Tuturuuu | Official-route rules (service window, no cold outreach), outbound rate limits, abuse signals in the operator view, operator suspension; a shared Discord bot abuser is cut off per guild |
| Credential theft | Vault environment per tenant, one-hour leases, no secrets in logs or payloads, rotation without deploy |
| Media and knowledge fetch SSRF | Media: exact provider media hosts only; the WhatsApp bearer is sent only to the Meta media host and never forwarded on a redirect. Knowledge URLs: DNS resolved and private, link-local and metadata addresses blocked, every redirect hop re-checked, size and time bounds, on a fetch path that carries no secrets |
| One tenant damages the shared Meta app or shared Discord bot | Templates only from tenant-approved, Meta-approved templates triggered by a person; a tenant is auto-suspended (operator reason) when Meta lowers its quality rating or flags it; caps and rate limits apply to BYOK and triage as well |
| Personal-session third parties | Container drops conversations outside the allowlist before forwarding; sends require a signed single-use command from the owning conversation object; container egress limited to the provider and its signer |
| Double send across runtimes | One owner generation per `(channel, account)`, enforced at Web admission and at the final send or edit boundary (see [migration](#migration)), at-most-once outbound |
| Personal-account ban | Internal tenant and explicitly opted-in paying tenants only, recorded risk acknowledgement, owner personal block per tenant, pacing and caps, session lease, stop on lock signal |

## Data lifecycle

* **Retention:** conversation context in objects is capped at the last 50
  turns and 30 days; the Tuturuuu chat mirror follows workspace retention.
* **Export:** a tenant exports its config, rules, usage and mirrored
  conversations as a workspace data export.
* **Delete:** disabling Mira stops all channels. For a workspace with a
  personal state or opt-in row, deleting Mira first upserts the state row,
  appends a server-written personal revocation, records the deletion time,
  bumps the personal generation and runs the personal revocation purge.
  Deleting the workspace itself cascades to the tenant rows, so a
  `BEFORE DELETE` row trigger on `mira_tenants` covers it. It makes the same
  database writes (state upsert, revocation row, deletion time, generation
  bump) and, in the same transaction, writes a durable purge job that
  captures the channel ids, secret-reference names and session objects
  before the cascade removes them. A bounded, idempotent Cloudflare consumer
  runs that job and records its purge status. The runtime stops when the
  job's push lands or at its next consent revalidation, within five minutes.
  The trigger is a no-op when the Mira delete path set its transaction-local
  deletion flag, so a Mira delete appends exactly one revocation. The purge
  job runs for every deleted tenant, also covering official-channel vault
  secrets. Deletion then revokes
  the service principal and vault grant, purges the vault variables named by
  the channel secret references before the tenant rows are removed (on the
  workspace-delete path, from the names the purge job captured), deletes
  tenant and conversation objects' storage, purges mirror rows and asks People
  & memory to apply its deletion fences. A per-person delete request
  propagates through the same fences and purges, within 24 hours,
  conversation-object context (indexed by a keyed sender hash), shadow
  drafts, uncertain-send records and mirror rows. Provider-side retention is
  outside Tuturuuu's control and is stated in the tenant data processing
  terms.
* **Model providers:** managed keys use each provider's zero-retention or
  no-training data settings where offered; the BYOK screen states that the
  tenant's own provider agreement applies.
* **Audit:** every config change, connect, stop, resume, export and delete is
  in `mira_audit_events`, and so is every personal opt-in, revocation,
  version publish and personal block change. `private.mira_personal_optins`
  rows are consent evidence and survive deleting Mira for the audit retention
  period.

## Migration

1. **Foundation:** tables, API contracts, operator view (read-only), Worker
   skeleton with all three stop fences and the ledger; deployed with every
   channel off.
2. **Shadow per channel (internal tenant):** the cloud runtime ingests the
   same events as the M4 receivers and drafts replies without sending. Drafts
   and latencies are compared with the M4 replies. Drafts live only in the
   conversation object's SQLite, readable by the owner through the operator
   view's break-glass path, and are deleted after 14 days.
3. **Cutover per channel:** one authoritative owner per `(channel, account)`
   decides which runtime may admit and send. Web's authoritative desk-owner
   row (Fleet Slice 4) holds the active desk id, credential version,
   account, generation and quiesce state, and the admission transaction
   checks all of them against the proof, whose signed claims carry
   `deskId`, `credentialVersion` and `ownerGeneration`. Every admission
   requires all of these to match: the desk id from the bearer, the desk id
   and credential version of the key that verified the signature, the claims'
   `deskId` and `credentialVersion`, and the live desk-owner row.
   Deployment-local configuration is not trusted for admission, so a stale
   Web replica holding retired credentials fails against the live row.

   Sends are **fence-owned**. A Durable Object per `(channel, account)`
   performs every final send or edit for the cloud runtime itself, after
   writing a durable send-start record. For the M4 runtime it issues a
   one-shot dispatch token, and the M4 must **redeem** that token online at
   the fence immediately before dispatching: the fence records the
   redemption durably, then answers, and only a redeemed token permits a
   send. Tokens are single-use, and an unredeemed token past its expiry on
   the fence's clock can never be redeemed, so a paused M4 that returns late
   cannot send. A redeemed token counts as in flight until the M4 reports its
   result or reconciliation shows its outcome; no timeout ends that wait. The
   fence keeps its quiesce state and redemptions durably, so a restart or
   failover resumes them. In either direction:

   1. Quiesce: the fence stops starting sends and issuing tokens, and new
      admission stops.
   2. Reconcile every started send and issued token from provider receipts
      (message ids, delivery or status events). Promotion is blocked while
      any started send could still take effect. The operator may clear an
      unresolved send only with evidence of both:
      * **the sender cannot reach the provider:** a verified stop of the
        sending process, or a provider-side send fence (the provider
        session or token that sender uses is revoked or rotated, or the
        provider revokes it). Revoking Fleet desk credentials alone is not
        enough, because it does not cut provider access;
      * **the request cannot still land:** a terminal provider receipt, or
        an acceptance bound the provider itself documents. Our own
        timeouts and elapsed idempotency windows do not count.
        If
        reconciliation does not finish within 15 minutes, the default is to
        abort: the current owner resumes under a fresh generation and the
        unresolved send stays marked uncertain for the operator, so a channel
        is never left without a sender. The abort neither resolves that send
        nor promotes anything; it is never retried, and it keeps blocking any
        later promotion until it is cleared with the two-part evidence above.
   3. Replace the desk-owner row and the channel's send owner, and verify
      both by readback.
   4. Enable the new owner under a fresh generation.
      Provider ids, the identity HMAC key and replay state are preserved.
4. **Rollback:** the same fence in reverse with the previous owner's valid
   credentials, under another fresh generation. The M4 receivers keep running
   observe-only until the owner retires them.
5. **Order:** Discord first (official, lowest risk), then Zalo Bot; Zalo OA
   and WhatsApp follow once their platform onboarding completes.
6. **Paying tenants:** open after the internal tenant has run each official
   route for a full week within latency and error targets.
7. **Personal opt-in (paying tenants):** a separate slice, built in this
   order and enabled only after independent security and privacy review:
   1. Database: the acknowledgement-version, publication, opt-in and
      personal-state tables with their reject and retention-purge triggers,
      the accept, revoke and publish RPCs, the per-tenant personal block, the
      deletion path's revocation, and the bind trigger that replaces the
      root-only `personal` constraint.
   2. APIs: tenant opt-in, revoke and status routes; the operator
      personal-block and version-publish routes; the connect route accepting
      `personal` for a tenant with current consent (and their API contract
      rows); all with readback and audit.
   3. Setup wizard: the versioned EN and VI acknowledgement and the
      personal connect flow.
   4. Runtime: per-account `SessionContainer` hosting with the
      personal-account controls and the reduced registry projection.
   5. Acceptance: opt-in; re-acknowledgement on a version bump; revocation
      with no restorable session material left; revocation and the personal
      block stopping their own channels; the personal block versus opt-in and
      stop clears; deleting and re-enabling Mira, and deleting the workspace,
      keeping the personal block, purging session material and requiring a
      fresh acceptance; the retention purge keeping consent evidence newer than
      a past deletion; bind racing revoke; publish racing
      accept; halt on stale state and resume only on current consent; refusal
      at a stale or missing AAL2; rejected update, delete and truncate on the
      acknowledgement, publication and opt-in tables; a client-supplied hash
      ignored; accepting a version that is not current refused; and refusal
      of every registry write and Fleet operation from personal sessions.

The M4 receivers need one change for cutover: obtain a one-shot dispatch
token from the owner fence for their `(channel, account)`, redeem it online
immediately before every send or edit, refuse when redemption fails, and
report each result back to the fence.

## Open decisions

Owner decisions are recorded in [decisions](#decisions). The price of
personal-account mode is open on the
[pricing page](https://docs.tuturuuu.com/platform/ai/mira-managed-pricing.md#open-decisions).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.