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 module (Chat SDK adapters, external chat mirror, identity mapping and tool allowlist) and the Omni-channel Chat SDK 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 slice ships (see decisions).
Decisions
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
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
Object identity and tenant isolation
Durable Object names are built only on the server from resolved identifiers: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
statetied to the workspace and actor, and a check that the installer holdsMANAGE_GUILDin that guild. - Zalo OAs bind only from the OAuth callback for that OA; Zalo bots bind from a
token whose
getMeidentity 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
DiscordGatewayDOper shard carries every tenant guild; the guild maps to the tenant through the existingdiscord_integrationsbinding. - Bring-your-own bot (Pro option): the tenant supplies its own application (custom name and avatar). One gateway object per application.
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.
Zalo
Decision: paying tenants use official routes only:- Zalo Official Account API (gated on Zalo OA developer verification,
which is deferred; see 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-Tokenheader, andsendChatActionfor typing. In groups the bot answers only when mentioned. The apps/web module already supports this mode.
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 refusepersonal channels outside the root workspace until it ships.
- Acknowledgement text:
private.mira_personal_ack_versionsholds each version’s canonical text per locale with its SHA-256, unique on(version, locale)withlocalelimited toenandvi. Text rows are inserted only by an owner or migration session and stay unpublished.private.mira_personal_ack_publicationsholds 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_stateholds 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_optinsholds 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_idhas 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 inprivate.mira_personal_stateonce 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 thetenantstop 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 toTenantDOand 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 thebillingtenant stop (fence 2), andTenantDOalso 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
personalchannel 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 takesFOR SHAREon the workspace’sprivate.mira_personal_staterow 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 with40001instead 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
SessionContainerunder 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.
Personal-account controls
The internal tenant’s personal sessions run on the Mac desk host; a paying tenant’s opted-in sessions run in aSessionContainer. 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 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
- 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). - 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.
- 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.
- 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.
- Triage (group conversations and watch rules only): a cheap model with
structured output decides
ignore | reply | tag_owner | escalateand the reply tier. Direct messages from people with a reply rule skip triage. - Respond: the alarm handler builds the prompt, signals typing, streams the model output through the AI SDK and delivers it (see streaming).
- Settle: record the outbound send, release the unused reservation, and enqueue mirror, memory and usage work.
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), which writessend_startedwith 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 markeduncertain, 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/anthropicand@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) orbyok(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) andquality(frontier tier for the reply, cheap tier for triage). The tenant picks a preset or an explicit model from the model catalog. - 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.
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:
- Global: the
MIRA_CHANNELS_STOPPEDWorker 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. - Tenant: a durable set of stop reasons, each with an owner:
tenant(kill switch),operator(abuse suspension),billing(entitlement loss) andcap(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. - Channel: the channel’s persisted reason set and generation, with the same ownership rule.
- Personal channels also need current consent and no personal block, checked at the same points (see personal opt-in).
- Global: the
- 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
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 ownresponder 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). 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
versionandconsent_version, but never serves it on age alone. On official channels each turn starts with full recall carryingif_version(personal sessions use the separate addressing projection below, with no versions and its own cache namespace); the registry answersnot_modifiedor 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 anevent_idmonotonic per workspace and a dead-letter queue. Fills older than the cached version and fills for tombstoned people are dropped;revokeanddeletepurge 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 sharedmira-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 onlyregistry.recallandregistry.write. -
mira-fleet-signer: verification material for the internal tenant’s desk accounts and the per-desk Fleet keys and bearers. Signs onlyfleet.identity_verify,fleet.intent_submitandfleet.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 thepeople-registryaudience. 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 aregistry.writeslot are mutually exclusive for the same event;registry.recallmay 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
kidbefore signing with it.
Fleet access desks
For the internal tenant,mira-fleet-signer is the trusted ingress for the
Fleet access 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:
- 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 requireaskand model budget. Desk credentials carry no approval authority. - Fleet Slice 4 adds the owner generation to the desk config and enforces it at admission.
- 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.
Configuration
Data model
Postgres tables in theprivate 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.
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-tenantmira-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/channelsand/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 inpackages/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 thetenantstop reason and rejectoperator,billingandcap. - 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 underapps/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).
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.- Channel: Discord invite (shared bot) or BYO token; Zalo Bot token; WhatsApp Embedded Signup and Zalo OA OAuth once their onboarding completes (see decisions).
- Persona: name, purpose, tone, instructions; optional knowledge sources (workspace documents and URLs ingested through the existing memory and Drive paths).
- People and rules: default reply policy, per-person and group rules, quiet hours, escalation contact.
- Model: preset or explicit model; managed or BYO key.
- 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.
- 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.
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. 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.
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
with the first deployable slice.
Threat model
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 DELETErow trigger onmira_tenantscovers 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_optinsrows are consent evidence and survive deleting Mira for the audit retention period.
Migration
- Foundation: tables, API contracts, operator view (read-only), Worker skeleton with all three stop fences and the ledger; deployed with every channel off.
- 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.
-
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 carrydeskId,credentialVersionandownerGeneration. 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’deskIdandcredentialVersion, 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:- Quiesce: the fence stops starting sends and issuing tokens, and new admission stops.
- 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.
- Replace the desk-owner row and the channel’s send owner, and verify both by readback.
- Enable the new owner under a fresh generation. Provider ids, the identity HMAC key and replay state are preserved.
- 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.
- Order: Discord first (official, lowest risk), then Zalo Bot; Zalo OA and WhatsApp follow once their platform onboarding completes.
- Paying tenants: open after the internal tenant has run each official route for a full week within latency and error targets.
-
Personal opt-in (paying tenants): a separate slice, built in this
order and enabled only after independent security and privacy review:
- 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
personalconstraint. - APIs: tenant opt-in, revoke and status routes; the operator
personal-block and version-publish routes; the connect route accepting
personalfor a tenant with current consent (and their API contract rows); all with readback and audit. - Setup wizard: the versioned EN and VI acknowledgement and the personal connect flow.
- Runtime: per-account
SessionContainerhosting with the personal-account controls and the reduced registry projection. - 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.
- 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
(channel, account), redeem it online
immediately before every send or edit, refuse when redemption fails, and
report each result back to the fence.