# 09 — Tools, identity, permissions and governed actions

**Status:** Draft. Written 2026-11-07. Contracts copied from Keiki where they are good;
header names changed once to `Charla-*`.

## 1. Tool kinds

| `execution_type` | How it runs | Where |
|---|---|---|
| `builtin` | Platform tools: `reply`, `send_card`, `send_file`, `react_to_message`, `update_message`, `delete_message`, `typing`, `get_return_link`, `conversation_search`, `conversation_read`, `escalate`, `resolve_escalation`, `action_respond`, `request_user_secret`, `download_attachment`, `payments_*`, `create_loop`… | `apps/runtime` |
| `webhook` | HTTP POST to tenant URL with `{ input, context }`, signed | runtime → tenant |
| `calendar` | A template's appointment tool bound to the org's connected calendar (Google Calendar first): Charla computes the slots and books in it, no tenant URL ([ADR-0020](adr/0020-calendar-appointments.md)) | `apps/runtime` → provider |
| `mcp` | Tool from a connected MCP server (Streamable HTTP), per-agent or per-sender credentials | runtime via Mastra `MCPClient` toolsets |
| `code` | Model-authored or tenant-authored code in a sandbox (Later) | E2B |
| `capability` | Tool declared by an installed capability manifest (`mcp`, `openapi`, `codemode` runtimes) | per runtime |
| `client` | Tool declared by the caller of the OpenAI-compatible API; run is parked server-side 24 h | caller |

A builtin may declare a fixed `ToolPolicy` in code (`BUILTIN_TOOL_POLICIES`, `packages/domain/src/builtin-tool-policy.ts`):
the dispatcher enforces it like a tenant tool's (scopes, `approval`, `approvalProof`), and a
builtin without one stays open (`allow`, no scopes). The base policy never comes from the
tenant's database. An agent can only **harden** it with a `tools` row of `execution_type =
builtin` named like the builtin and listed in `config.toolIds`: `ToolsRepo.insert` and
`updatePolicy` reject (`ToolPolicyError`, `invalid_tool_policy`) any key that would relax the code's
policy, and the runtime merges the two taking the stricter value of every field
(`hardenToolPolicy`), so a stored relaxation is ignored. A governed builtin's `approvalFallback`
is always `refuse`. Such rows are never offered as tools; they only carry the override.

The `payments_*` builtins (`payments_request`, `payments_request_status`,
`payments_cancel_request`, `payments_request_refund`) declare a policy in code and go through the
same hooks as any tool (§3); the refund is a governed action with `approvalProof: verified`
([ADR-0019](adr/0019-agent-payments.md), [14 §5](14-billing-and-plans.md)).

### 1.1 Webhook tool contract

Request:

```http
POST https://tenant.example/tools/reschedule_booking
Content-Type: application/json
Charla-Timestamp: 1794000000
Charla-Signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>
Charla-Trace-Id: trn_01J…
Charla-Internal: true              # only on steered/test turns
Idempotency-Key: trn_01J…:3:reschedule_booking

{
  "input": { "booking_id": "bk_42", "new_time": "2026-11-12T15:00:00-06:00", "walkthrough": "…" },
  "context": {
    "agent": { "id": "agt_…", "externalRef": "org_acme_42" },
    "conversation": { "id": "conv_…", "channel": "whatsapp", "identity": "+5215512345678" },
    "contact": { "externalId": "5215587654321", "displayName": "Ana" },
    "principal": { "userId": "usr_9f2", "role": "customer", "scopes": ["bookings:write"] } ,
    "approval": { "actionId": "act_…", "decidedVia": "whatsapp_button", "decidedBy": { "userId": "usr_9f2" } },  // only when policy ask and approved
    "preflight": false,
    "internal": false,
    "messages": [ /* inbound messages of this turn when internal */ ],
    "attachments": { "att_…": { "filename": "recibo.pdf", "mime_type": "application/pdf", "size": 12345, "sha256": "…", "url": "https://… (15 min)", "expires_at": "2026-11-07T18:15:00Z" } },
    "locale": "es-MX",
    "now": "2026-11-07T18:00:00Z"
  }
}
```

Response: any JSON is the tool result. Optional top-level fields read by the platform:
`delivered` (string or string[] ≤ 10 × 2,000 chars, recorded as agent messages),
`presentation` (`choice | confirm | flow | url`), `card` (approval summary blocks, when this is a
preview tool). Non-2xx → tool failure with the body (first 2,000 chars) as reason. Timeout
default 30 s, max 120 s. The tenant **must** verify signature over raw bytes with a 5-minute
tolerance and re-check resource ownership against `context.principal`, never against ids the
model put in `input`.

Verifying a request (Node, tenant side). Read the body as raw bytes before any JSON parser
touches it; a re-serialised body does not match:

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyCharla(rawBody: string, headers: Headers, secret: string): boolean {
  const ts = Number(headers.get("charla-timestamp"));
  const given = headers.get("charla-signature") ?? "";
  if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
  const expected = `sha256=${createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex")}`;
  return given.length === expected.length && timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}
```

Platform behaviour (T-052, `apps/runtime/src/mastra/tools/webhook-tool.ts`):

- The secret is `tools.config.secretRef` (an org secret name) or the org secret
  `TOOL_SIGNING_SECRET`; without one the call is not sent and the model reads
  `{ error: 'signing_secret_missing' }`. Extra headers in `tools.config.headers` may use
  `{{secret.NAME}}`; `Content-Type`, `Idempotency-Key` and `Charla-*` cannot be overridden.
- `Idempotency-Key` is `<turnId>:<step>:<toolName>`, where `step` is the call's ordinal in the
  turn fixed by its `tool_calls` row: a retried or recovered call keeps it. We never retry a POST
  ourselves.
- `Charla-Internal: true` and `context.internal: true` on steered (held-back) and test turns.
- Failures the model reads instead of an exception: non-2xx `{ error: 'tool_failed', status,
  body }`, `{ error: 'timeout', timeoutMs }`, `blocked_url`, `redirect_blocked`,
  `response_too_large`, `network_error`. A 2xx body that is not JSON becomes `{ text }`.
- `delivered` is stored as agent messages (`status: delivered`, never queued) and removed from
  the result; results over 64 kB reach the model and `tool_calls.result` as
  `{ truncated: true, bytes, text }`.
- A tool whose `webhookUrl` is not public HTTPS (`http://`, credentials, a port other than 443,
  `localhost`, a private address literal or a host resolving to one) is not offered and is set
  `enabled = false` with `disabled_reason` (`url_scheme`, `url_private_address`…).

**Presentations** (T-042; any tool kind, not only webhooks: the dispatcher's `afterToolCall` hook
reads the result of every tool). Phase 1 takes `choice` and `confirm`; `flow` / `url` answer
`unsupported_presentation` until Phase 2:

```json
{ "presentation": {
    "type": "choice", "id": "slot",              // id: 1–128, stable per question
    "text": "¿Qué día te viene mejor?",           // body of the interactive message
    "options": [{ "id": "jueves", "label": "Jueves 10:00", "description": "opcional" }],
    "allowFreeText": false } }                    // ≤ 10 options, labels ≤ 80
{ "presentation": { "type": "confirm", "id": "cancel", "text": "¿Cancelo la cita?",
    "confirmLabel": "Sí, cancelar", "cancelLabel": "No" } }   // default Sí/No by locale
```

The platform validates the shape, then checks the channel render (WhatsApp: button labels ≤ 20,
list rows ≤ 24, body ≤ 1,024) before storing anything, opens a `presentation_intents` row
(`docs/06` §2.6; idempotent by tool + `id` in the conversation, supersedes the open one, expires
in 24 h), queues the buttons with ids `pi_<intent id>:<option id>` and adds
`presentationDelivery: { state, messageId, reason[, issues] }` to the result the model sees:
`accepted` (queued; `reason: duplicate` when the same tool and `id` were already shown and nothing
new was sent), `failed` (`invalid_presentation` with `issues`, `internal_error`), `unavailable`
(`unsupported_presentation`, `unsupported_channel`, `window_closed`) or `unknown`
(`enqueue_failed`: may have gone out, do not retry). Labels are never truncated. The contact's
answer is **not** the tool result: ingress records the first valid tap (or text, with
`allowFreeText`) on the intent and the agent reads it on the next turn as `[Button pressed by Ana;
action=slot:jueves; label=Jueves 10:00]`. Stale, duplicate and out-of-set taps change nothing and
still reach the agent as normal messages.

`context.attachments` holds at most 10 attachments, all of the call's conversation; `url` is a
presigned GET valid 15 minutes (`expires_at`). Ids of another conversation, unknown ids and files
whose retention ends within those 15 minutes are omitted, never signed; a cross-conversation id is logged as a security event.

### 1.1.1 Tools installed from a template (T-151)

Installing a T-094 template from the gallery creates one webhook tool per `template.tools`
entry on the new agent, all referenced by its first version (`toolIds`):

- **URL:** one base URL per template; each tool calls `<base>/<tool name>` (the example
  above). Checked with `parseSafeUrl` when saved (public HTTPS, no credentials, port 443, no
  private or `localhost` host, no query or fragment); the runtime still checks it at call time.
- **Secrets:** the template's `requiredSecrets` are org secrets of kind `developer` under the
  names it declares. `TOOL_SIGNING_SECRET` is the tool's `secretRef`; the system's key (at most
  one per template) is sent as `Authorization: Bearer {{secret.<NAME>}}` in `config.headers`.
  A name already stored as `developer` counts (blank keeps it; a new value replaces it for the
  whole org); a name of another kind (`channel`, `webhook`, `byok`…) is refused and nothing is
  created. Values are sealed before the transaction (the KMS call) and written with
  `SecretsRepo.put` inside it, with the agent, tools, version and audit row; they never reach
  the version, `audit_log` (names only), logs or the action's answer.
- **State:** a tool is on only with a URL and every secret it references stored. Otherwise it
  is `enabled = false` with `disabled_reason = 'needs_setup'` ("Skip and create agent" leaves
  them all so) and the runtime does not offer it (`ToolsRepo.listEnabled`): the agent answers
  without it. `config.setup` names the template (`vertical`, `locale`).
- **Completing later:** the editor's Tools tab links each `needs_setup` tool to
  `/[org]/agents/<id>/connect`, which saves the base URL and keys and turns on the tools that
  end up complete (`agent.tools.connect` in `audit_log`); the version is not touched.
- **Payments (#435):** a template that charges declares `payments: { purpose: "deposit" }`
  (restaurant, salon, dental; never `config.features.payments`). The install sets
  `features.payments` with `installedPayments`: on with the provider of a connection the org
  already has `active` (the country's default first); otherwise off, `{ enabled: false,
  provider: <country default>, disabledReason: "needs_setup" }`, and the editor's Behaviour tab
  links to «Ajustes › Pagos» (`/[org]/settings/payments`) with a switch to turn them on once a
  provider is connected. A Tier B country gets no `features.payments`. The answer and the
  `agent.create` audit row say `payments: enabled | needs_setup`. The prompt's deposit rule
  reads the amount from the info tool's payments topic, charges once after the booking is
  confirmed, never calls a link paid before `payments_request_status` says `paid`, only proposes
  refunds (`payments_request_refund`, approved in the dashboard) and, without the tools, asks
  for no payment. Its eval cases run in the `payments` world
  (`apps/runtime/src/evals/template-payments.fixture.ts`).

### 1.2 MCP connections
- Per agent: `{ name, endpoint, kind: mcp | openapi, auth_mode: public | headers | oauth,
  headers (values may be `{{secret.NAME}}`), default_permission: allow | ask | deny, icon_url }`.
  Max 10, one per endpoint. Discovery at connect; `status: connected | connected_no_tools |
  needs_auth | error`.
- Implemented in T-053 (`apps/runtime/src/mcp`), over `safeFetch` (T-051) as the client's
  `fetch` plus `allowedHosts`: `connect` checks the endpoint (public HTTPS on port 443 only: a
  private, loopback or link-local address ends as `status: error` and nothing is sent; a response
  over 1 MB fails),
  lists the server's tools once and stores them in `discovered_tools`; `401`/`403` is
  `needs_auth`. A turn's tools are rebuilt from that stored catalogue, named
  `<connection>__<tool>`, so offering them opens no connection; the first call connects a client
  that is kept per connection and disconnected after 10 idle minutes. Header templates are
  resolved on every request, so a rotated secret applies at once and no credential is cached;
  tool results and errors pass through the secret redactor before the model sees them, and are
  untrusted input like any tool result.
- `default_permission`: `allow` tools are offered; `deny` tools are never exposed; `ask` tools
  are reported apart (`needsApproval`) and **not offered until the approval dispatcher exists**
  (T-061), so they can never run unapproved.
- Per sender credentials via identity webhook `mcpHeaders` or `PUT
  /deployments/:ref/mcp-senders` keyed `{ channel: whatsapp, user_id: <wa_id> }`, `{ channel:
  api, conversation_id }`, stored in `mcp_sender_credentials` under the connection's name. A
  connection chooses whose credential its calls carry with `credentials`
  ([ADR-0022](adr/0022-per-person-connections.md) §2.1, Proposed; implemented in #651):
  - `agent` (the default): the connection's own `headers`, for every sender; sender headers are
    never read. A connection without the field is `agent` (Q12, **default, pending the Lead's
    confirmation**): sender headers never switch a connection implicitly, since the senders
    without an entry would then fall back to the agent's headers.
  - `per_sender`: no `headers` and no `auth_mode` of its own (the repository refuses them,
    `invalid_credentials`). Each call carries only the headers of the turn's sender, read from
    `mcp_sender_credentials` by `(org, agent, connection, sender)` inside `withOrg` on every
    request (`apps/runtime/src/mcp/credentials.ts`), registered with the secret redactor, never
    kept in the client. The sender is `senderKey(channel, externalId)` of the turn's own channel.
  - Eligibility, checked before any credential is read: only a DM, and only a sender the
    provider vouches for (an erased contact's tombstone is not). Elsewhere the connection's
    tools are not offered (`personal_connection_not_allowed`, `no_provider_evidence`).
  - Clients are cached per connection and, for `per_sender`, per sender: two senders never
    share one, concurrent calls of one sender share one `connect`. At most 500 cached clients
    per process (Q14, **default, pending the Lead's confirmation**), the least recently used is
    disconnected past that; 10 idle minutes and shutdown disconnect them as for `agent`. A call
    cancelled by the turn (`AbortSignal`) or refused by the server drops its client, so the
    next call builds a fresh one.
  - Results to the model, with the connection's name only (ADR-0022 §2.6, no `linkSent`: with
    tenant-delivered headers Charla sends no link; the words for the person come from the
    deployment or the identity webhook's `reply`): no entry → `{ status:
    "account_not_connected", connection }` and no request reaches the server; `401`/`403` with
    the sender's headers → `account_expired`, nothing of the agent changes; `5xx`, network
    error or timeout → `{ status: "tool_failed", connection, reason: "provider_unavailable" }`.
    Metric: `charla_mcp_sender_credentials_total{outcome}`.
  - Discovery of a `per_sender` connection sends no credential (it has none, and a sender's
    would be someone else's): its server must answer `initialize` and `tools/list` without
    one, or the connection ends `needs_auth`.
- A connection may instead name an agent-declared OAuth connector with `personalConnection:
  "<name>"` (`mcp_connections.personal_connection`, #677; ADR-0022 §2.1 (b), §2.5 below). Its
  calls carry only `Authorization: Bearer <the turn's contact's access token>`, read on every
  request with `createPersonConnectionsService().credential` by `(org, agent, contact,
  "agent:<name>")`; the row has no `headers`, `auth_mode: public` and `credentials: agent` (the
  repository refuses anything else, `invalid_credentials`), and discovery sends no credential.
  - Offered only in a DM with provider evidence and with the turn's contact; elsewhere its tools
    are not offered. Clients are cached per connection and contact, never per turn, and keep no
    token; the turn of each call (where a link goes) is passed per call.
  - Results, with the connector's display name (§2.5): no usable connection →
    `account_not_connected` / `account_expired` / `account_revoked` with `linkSent`, the link queued by the
    platform and no request to the server; a `401` with the token → the row goes `expired` and a
    reconnection link is sent; `5xx`, network error or timeout → `tool_failed`
    (`provider_unavailable`), the connection unchanged.
- MCP `ask` tools use the governed-action lifecycle but cannot carry `requiredScopes`,
  `previewTool`, `freshnessFields` (copied limitation; revisit).
- Users may add their own MCP sources at runtime (`mcp_add_source` with OAuth link) when the
  agent enables it. Later.

## 2. Identity and principals

### 2.1 Principal
```json
{ "channel": "whatsapp", "externalUserId": "5215587654321", "displayName": "Ana López",
  "userId": "usr_9f2", "role": "customer", "scopes": ["orders:read", "bookings:write"],
  "addressing": { "mentionsAgent": true, "mentionsOthers": false, "isDm": true } }
```
Only `userId`, `role`, `scopes` come from the tenant and only `scopes` are compared. The model
sees a `# Speaker` line with name, id, role and scopes (or "unknown"); never emails, tokens or
headers.

### 2.2 Identity webhook
Request (once per new sender per conversation; again on TTL expiry; signed like tools):

```json
{ "agent": { "id": "agt_…", "externalRef": "org_acme_42" },
  "sender": { "channel": "whatsapp", "identity": "+5215512345678", "userId": "5215587654321", "displayName": "Ana López", "isDm": true,
              "messages": [{ "id": "wamid.…", "text": "hola" }] },
  "conversation": { "id": "conv_…" } }
```

Response:

| Field | Semantics |
|---|---|
| `userId` | Tenant's id; `null` or HTTP 404 = unknown → principal with no scopes |
| `role` | Free text for prompt/dashboard |
| `scopes` | Opaque strings |
| `ttlSeconds` | Default 900, max 86,400, 0 = resolve every turn |
| `mcpHeaders` | `{ "<connection>": { "<header>": "<value>" } }` |
| `reply` | Deterministic text (≤ 2,000) that answers the inbound **without** history, model or tool runs (e.g. "Vincula tu cuenta en https://…"). Never cached. |

Failure modes (copied verbatim in spirit): timeout, non-2xx, missing webhook → turn runs, every
tool with `requiredScopes` is refused, model is told "no pude verificar quién habla". Never
default-allow. Cache eviction: `DELETE /deployments/:ref/identity/cache?channel=&user_id=`.

Agents without an identity webhook can get scopes from grants an owner or admin gives a
specific contact in the dashboard, bounded by the scopes the agent's tools declare; with a
webhook, the webhook wins ([ADR-0018](adr/0018-dashboard-scope-grants.md)).

A tool declares a scope in two ways: exactly in `requiredScopes`, or as an `argScopes` prefix
(§3). A grant can give `<prefix><value>` under a declared prefix, with a value of 1 to 200
characters (`resident:unit:502` under `resident:unit:`), so an agent without a webhook can still
use tools bound to a unit. A bare prefix (`resident:unit:`) or a string under a prefix no tool
declares (`resident:units:502`) is refused with `scope_not_declared` (#587). On the contact page,
each declared prefix shows a text field. The values typed there are separated by commas or spaces,
and each one becomes `<prefix><value>`. The repository checks every scope again
(`isDeclaredScope`).

Implementation (#398): `scope_grants` (one row per agent and contact, `docs/06` §2.6) is read by
the resolver only when the agent has no `harness_config.identity` and the conversation is a DM.
An active grant (not revoked, not expired) gives `status: ok`, `source: grant` and the grant's
scopes that the turn's tools still declare, exactly or under an `argScopes` prefix
(`declaredScopesOf` → `effectiveGrantScopes`); a contact without one is
`unknown` when other contacts of the agent hold grants (refusal `missing_scopes`), else the
principal stays `error`/`not_configured` as before. With a webhook (also an invalid config or a
failing call) grants are never read. Approval buttons resolve the presser the same way, bounded
by the proposed tool's scopes. The principal carries `source` (`webhook | grant`); the turn's
root span records `principalStatus`, `principalSource` and `principalScopes`. The grant only
feeds the principal: `requiredScopesHook`, approvals and previews run unchanged.

Implementation (T-054): the steer worker resolves the principal after the stop-command check and
before touching a running turn. The webhook URL and the name of its signing secret live in
`agents.harness_config.identity` until `deployments` exists. `principal.status` is `ok` (known
user, with scopes), `unknown` (`userId: null` or 404, no scopes) or `error` (timeout after 5 s,
non-2xx, invalid body, missing secret, no webhook, SSRF refusal; no scopes, reason only in logs
and metrics). A `reply` is queued to `deliver` as a platform reply (`identityReply`, job id
`identity-<newest message id>`) and the batch is acknowledged without a turn. Metrics:
`charla_identity_webhook_calls_total{outcome,error}` and `charla_identity_webhook_latency_ms`.

API channel (#589): the chat completions service (`apps/runtime/src/openai/service.ts`) resolves
the principal the same way before each turn, with the same resolver and cache, after it stores
the caller's message and before the model runs. The contact is `apiContactId(key, user)`, so the
webhook receives `sender.channel: "api"`, `sender.identity` = the agent's implicit `api` identity
and `sender.userId` = `<key id>:user:<user>` (the key id alone when the request has no `user`):
the key id names the key that authenticated, and the tenant maps the `user` it issued under it.
Without a webhook, the contact's dashboard grant applies (an API conversation is a DM). Trust
model: the request's `user` is the key holder's claim, never a scope source; scopes come only
from the tenant's webhook or an owner's grant to that exact key and `user`, and nothing in the
request body can add one. A failure leaves the principal `error` (warning logged unless no
webhook is configured), so scoped tools stay refused. A `reply` answers the request with that
text and no turn (stored as a `system` message, `charla.trace_id: null`). The model still sees
only the `user`, never the key id (`readableExternalId`). The turn's root span carries
`principalStatus`, `principalSource` and `principalScopes` as on other channels.

### 2.3 Conversation authentication (account linking on a phone channel)
One number → one agent → one conversation per verified sender → that sender's account.
Unlinked sender gets the deterministic `reply` with a short-lived, single-use link; OAuth
authenticates the **app account**; before binding, the tenant completes a challenge from the same
verified sender (we pass recent `messages[]` ids/text). Imported numbers without provider evidence
and group chats never get identity-scoped tools. Account deletion revokes bindings; recycled
numbers get a non-authorising tombstone.

The design is proposed in [ADR-0023](adr/0023-partner-deployments-and-account-linking.md) §3
(#650; its defaults are pending the Lead, docs/18): the platform issues the link, never the model;
the challenge is a 6-digit code the tenant shows after sign-in, typed in the same chat and
intercepted by `steer` before any turn; the binding lives in Charla (`account_links`, one per org,
agent and contact) and supplies the `userId`, while scopes still come from the identity webhook;
link and code last 15 min, 5 wrong codes cancel the request, a binding lapses after 180 days
without a turn; the tenant revokes with `DELETE …/account-links`; a recycled WhatsApp number is
tombstoned on Kapso's `user_changed_number` signal (to verify, docs/18 F1). It composes with a
per-person connection (ADR-0022): neither replaces the other.

**Implemented in #657**, the end of a binding in #658 (below). The tenant's side of the contract:

- **Config:** `harness_config.identity.linking: { linkUrl, confirmUrl, secret }` next to the
  identity webhook; `secret` is the name of an org secret. Without `linking` nobody is asked to
  link and the webhook works as in §2.2. The runtime needs `PUBLIC_BASE_URL` (where
  `apps/web` serves the link); without it no link is sent.
- **The link:** an unlinked DM sender's message gets a platform reply (no turn) with a
  «Vincular cuenta» button (`cta_url` on WhatsApp, a URL button on Telegram, `label: url`
  elsewhere) to `<PUBLIC_BASE_URL>/link/<token>`. While that link is live, later messages do run a
  turn: the principal is `unknown` with `reason: link_required, linkSent: true`, and scoped tools
  are refused with `link_required` telling the model the link was already sent. The token is
  derived from the request id and the platform data key at send time, so the `deliver` job carries
  only `{ requestId, keyVersion, label }`; only its SHA-256 is stored.
- **The redirect:** `GET /link/<token>` answers `302` to `linkUrl?link_request=<value>` with
  `Referrer-Policy: no-referrer` and `Cache-Control: no-store`. `<value>` is
  `base64url(JSON).base64url(HMAC-SHA256(secret, first part))` with claims
  `{ org, agent, request, nonce, exp }` (`verifyLinkRequest` in `@charla/domain` shows the check);
  no phone number or channel id. An unknown, expired, cancelled or used link is the same `410`
  page telling the person to write to the chat for a new one; a missing secret is `503`.
  Opening the link never consumes it.
- **The code:** the tenant shows a 6-digit code bound to `request`. A lone 6-digit message
  («123456», «123 456») from the contact with an open request is handled by `steer` before the
  turn and its stored text is replaced by `[código de vinculación]`. The runtime POSTs
  `{ requestId, code }` to `confirmUrl`, signed like the identity webhook (`Charla-Timestamp`,
  `Charla-Signature`), 5 s timeout. Answers: `2xx { userId: "<id>" }` links; `2xx { userId: null }`
  or `400/404/409/422` is a wrong code (counted; the fifth cancels the request); anything else
  (timeout, `5xx`, a bad body) is `tenant_link_unavailable` and the code stays valid until the
  request's TTL. The tenant **must** answer a repeated `requestId` with the same answer: the runtime
  replays it after a crash.
- **After linking:** the identity cache of the sender is evicted and the next turn calls the
  identity webhook with `sender.userId` = the tenant's id; the principal's `userId` is the
  binding's, the scopes are the webhook's (a `userId: null` answer leaves it `unknown`).
- **Eligibility:** DMs on `whatsapp`, `telegram`, `instagram` and `messenger` only
  (`LINKABLE_CHANNELS`; default, pending the Lead's confirmation). Groups and other channels get
  `reason: linking_not_allowed`, no link and no webhook call. «cancelar» cancels an open request.
- Contact texts are in the agent runtime's strings (`accountLink`, es-419 and pt-BR, also pt-PT,
  it, en); the link page speaks Spanish or Portuguese after the agent's locale.

**End of a binding (#658).** Four causes; each leaves the row `revoked` or `tombstoned` (never
reactivated: linking again inserts a new row), cancels the contact's open link request, evicts
the identity cache of that sender on that agent and writes `account_link.revoke` or
`account_link.tombstone` in `audit_log` (ids and `revokedBy`, never the tenant's `userId`), all in
one transaction (`AccountLinksRepo` in `packages/domain`). The next message of the sender finds no
`linked` row, so it gets a new link and nothing of the old binding: the resolver reads the
binding before the cache.

- **Tenant:** `DELETE /api/v1/deployments/:external_ref/account-links?channel=&user_id=`
  (`deployments:write`, every agent of the client org, also while the deployment is `deleting`)
  and `DELETE /api/v1/developer/agents/:agentId/account-links?channel=&user_id=`
  (`people:write`). Always `204`, also for an unknown user or a repeat; `400` for a bad query.
- **Owner or admin:** «Revocar vínculo» on the contact's page, one per linked agent
  (`revoked_by = member:<id>`; default, pending the Lead's confirmation).
- **DSAR erasure:** step 1 deletes the contact's `account_links` and `account_link_requests` in
  the transaction that deletes `mcp_sender_credentials`.
- **Recycled number:** Kapso's `system` message `user_changed_number` (or the older
  `customer_changed_number`) becomes `contact_number_changed` in `@charla/channels`; the ingress
  tombstones the old number's bindings (`revoked_by = provider`). A repeat finds nothing `linked`
  and adds no tombstone. The payload shape is to be verified (docs/18 F1). Telegram ids do not
  follow the phone number: nothing is tombstoned there.
- **Inactivity:** `account-link-sweep` (maintenance, daily 04:40 UTC, `SKIP LOCKED` batches per
  org, repeatable) revokes bindings 180 days after their last turn (`last_used_at`, else
  `linked_at`); the resolver ends a lapsed one itself if the contact writes before the sweep.
- **A turn under way** keeps the principal it resolved; the next one has none, so its scoped
  tools are refused (`link_required`).

### 2.4 Passwordless web sign-in from chat
A `cta_url` / Flow link carries a single-use token (query string; WhatsApp cannot hide
fragments). Tenant backend exchanges it: `POST /api/v1/developer/sessions/exchange { token }` →
`{ agent_id, conversation_id, contact, principal, expires_at }` (scope `people:read`). Token is
consumed on first exchange.
Proposed in [ADR-0023](adr/0023-partner-deployments-and-account-linking.md) §4 (Q13, #659):
the token lives 10 min, only its hash is stored, it is exchanged only with a key of the agent's
org, and an expired, used or foreign token is the same `404`.

### 2.5 Per-person connections (a person's own provider account)
Proposed in [ADR-0022](adr/0022-per-person-connections.md) (#632; L-5 and L-6 are defaults pending
the Lead), implemented in #634. Not the same as §2.3: account linking authenticates the person in
the **tenant's** app and yields scopes; a per-person connection gives the agent a credential of a
**third-party provider** account (the person's Google Calendar), for that person only.

- **Source, one per connection** (L-5): per-sender MCP headers delivered by the tenant (§1.2,
  `credentials: "per_sender"`), or Charla's own OAuth per contact for hosted agents: built-in
  connectors and agent-declared OAuth connectors that `webhook` tools or MCP connections name with
  `personalConnection`. Never a fallback to the operator's, the business's (ADR-0020) or another
  contact's credential.
- **First connector** (L-6): Google Calendar through ADR-0020's Google application, no new scope;
  100 test users and weekly reconnection until the consent screen is verified (#501). No other
  connector is available until its own issue validates it.
- **Binding:** org, agent and the contact (one channel identity, no cross-channel link). DM only;
  group turns and imported numbers without provider evidence never use a personal credential.
- **Lifecycle:** a single-use link (15 min, sent by the platform, never by the model) →
  `pending` → `connected` → `expired` / `revoked` → reconnection on the same row. Conversation,
  memory, workflow state and follow-ups survive; tokens do not.
- **Results:** `account_not_connected`, `account_expired`, `account_revoked` with the connection's
  display name only; a provider that is down is `tool_failed` (`provider_unavailable`) and never
  changes the connection.

What runs today (agent-declared OAuth connectors on `webhook` tools and, since #677, on MCP
connections with `personalConnection`, §1.2):

- **Declaration.** The agent config lists `personalConnections: [{ name, displayName,
  authorizeUrl, tokenUrl, revokeUrl?, clientId, clientSecret: "{{secret.NAME}}", scopes }]` (at
  most 5); a webhook tool names one with `tools.config.personalConnection: "<name>"`. Its calls
  carry `Authorization: Bearer <the contact's access token>` (any tenant `Authorization` header is
  dropped), next to the usual signature (`secretRef`).
- **Lookup, in code.** Only `(org, agent, contact, "agent:<name>")` inside `withOrg`
  (`createPersonConnectionsService().credential`); only in a DM with provider evidence
  (`senderEligibility`, the same rule as `per_sender`). A group turn answers
  `{ status: "group_not_allowed", connection, linkSent: false }` and offers no link.
- **Results the model reads.** `account_not_connected` / `account_expired` / `account_revoked`
  with `{ connection, linkSent }`; a 401 to a call with the token moves the row to `expired`
  (grant deleted) and sends a reconnection link; a 5xx, timeout or network error is
  `{ status: "tool_failed", connection, reason: "provider_unavailable" }`.
- **Link.** `<PUBLIC_BASE_URL>/connect/<orgId>.<random>` (only the SHA-256 is stored), 15 minutes,
  one per turn and connector (`pcl_` id derived from the turn); a newer link spends the older
  ones. The platform queues it on `deliver` as a card with one `LinkButton` where the channel has
  `cta_url` (WhatsApp, Telegram), a text with the URL otherwise. Held-back and silent turns, and a
  runtime without `PUBLIC_BASE_URL`, send none (`linkSent: false`).
- **Connect page and callback** (`apps/web`, public routes): `GET /connect/<token>` shows the agent,
  the connector and its scopes with «Conectar» / «Cancelar» (a GET changes nothing, so link
  previews are harmless); «Conectar» redirects with a `state` HMAC-signed under the connector's
  client secret (org, connection, link, nonce, link expiry) and PKCE S256. `GET
  /connect/callback` verifies the state, exchanges the code once through `safeFetch` and, in one
  transaction, consumes the link (`WHERE consumed_at IS NULL`), seals the grant (`PERSON_…`
  secret) and sets the row `connected`. The connection is the state's, never the browser
  session's. A repeated callback finds the link consumed (no second exchange); a provider outage
  shows an error and leaves the link valid; «Cancelar» deletes a `pending` row.
- **Back in the chat.** The callback queues `person-connection-notice` (`{ orgId, linkId }`, job id
  per link); the runtime's worker sends a platform note under `Idempotency-Key
  person-connection:<link>`, so retries, restarts and repeated callbacks wake the agent once. If
  the turn that asked for the link was cancelled, the note only confirms the connection. The note
  tells the agent to call the tool again (which checks the account first) and not to repeat on its
  own a write whose outcome is unknown.
- **Provider errors** (#635, `personalCallVerdict` / `refreshVerdict` in
  `packages/domain/src/person-connections/provider-errors.ts`, one test per code): a `401` is
  expired access unless the provider names a revocation (`token_revoked`, `access_revoked`,
  `revoked`, `consent_revoked`, in the body or in `WWW-Authenticate`), which is revoked access; a
  `403` is revoked only when it names one, otherwise the tool's own failure; `5xx`, `429`, `408`,
  timeouts and network errors are `provider_unavailable`. At the token endpoint `invalid_grant`
  (and any other `400`/`401`) is a spent grant, `invalid_client` is Charla's client and changes
  nothing.
- **Refresh, once, under a lock.** A token past its date (30 s margin) or refused with a `401` is
  renewed with the grant's refresh token, under the Redis lock `person-connection-refresh:<id>`
  (TTL 30 s, renewed while it runs; a turn waits up to 20 s and then answers
  `provider_unavailable`). Under the lock the grant is read again: a turn that waited uses the
  token the first one stored, so two turns make one refresh. A refused call is repeated once with
  the new token (same body and `Idempotency-Key`; a `401` did nothing at the provider); refused
  again, the row goes `expired`. A runtime that dies mid-refresh leaves the lock to lapse and the
  next turn refreshes again. A rotated refresh token the provider issued but Charla never stored
  is a spent grant: the person reconnects.
- **Results.** Each one carries `instructions` for the model: lost access is never «I cannot do
  that» nor a system error and the request stays pending; `tool_failed` says the connection is
  fine and that a write with an unknown outcome is not repeated without asking (docs/21 §3.3).
  The link message says why it is sent: first connection, expired access («Tu acceso a … caducó»)
  or a disconnected account, with a «Reconectar cuenta» button.
- **Disconnecting from Charla** (`revoke` / `revokeFor`): the contact with the builtin
  `disconnect_account` (offered in a DM of an agent with `personalConnections`, only for the
  turn's own binding), or a member (`member:<id>`). Charla calls the connector's `revokeUrl`
  (RFC 7009, best effort), deletes the sealed grant, spends the live links, sets `revoked` with
  `revoked_by` and records `person_connection.revoke`. The next call answers `account_revoked`
  and sends a link; reconnection reuses the row. A provider that reports a revocation sets
  `revoked_by: provider` without calling it back.

- **Built-in Google Calendar** (#678, ADR-0022 §2.2): an agent turns it on with
  `builtinConnections: ["google_calendar"]`; the host has it when Charla's Google client is set
  (`CALENDAR_GOOGLE_CLIENT_ID` / `_SECRET`, the same as ADR-0020's). Its connector key is
  `google_calendar` and its builtins are `google_calendar_list_events`, `google_calendar_busy`
  (open) and `google_calendar_create_event` (`approval: ask` in code, `approvalFallback: refuse`,
  10 per conversation and hour: the contact confirms with a button, and the approved action
  creates the event with an id derived from the action). Before proposing, a contact without a
  usable connection gets the link instead of a confirmation. They only touch the contact's
  `primary` calendar with the contact's token; they never read `calendar_connections`, and a
  business connection is never a person's credential. Scopes: `calendar.events` and
  `calendar.freebusy`, a subset of ADR-0020's list (no new scope, so #501's verification stands).
  The same lifecycle as above: a refused refresh (`invalid_grant`) leaves the row `expired` and
  sends the reconnection link; `disconnect_account` takes «Google Calendar».

Not yet: the sweep of expired links, DSAR export and erasure, retention and agent deletion (#679),
and the contact's page where a member disconnects a connection (the dashboard's management page).

## 3. Tool policy

```ts
type ToolPolicy = {
  approval?: 'allow' | 'ask'                   // default allow
  requiredScopes?: string[]                    // proposer and approver must hold all
  argScopes?: Record<string, string>           // { unit: 'resident:unit:' }: speaker must hold resident:unit:<args.unit>
  previewTool?: string                         // must have run this turn with same canonical args
  freshnessFields?: string[]                   // dot paths into preview output re-checked at approval
  descriptionArg?: string                      // model-authored walkthrough shown on card, excluded from hash
  approvalProof?: 'any' | 'verified'           // verified = Flow, dashboard, Slack button, signed link; words/buttons = any
  approvalFallback?: 'refuse' | 'tool'         // when no ask surface exists
  preflight?: boolean                          // webhook: call once with context.preflight=true before asking
  card?: ApprovalCard                          // summary blocks template with $.input.<path>
  rateLimit?: { perConversationPerHour?: number }  // addition
}
```

Enforcement order in the dispatcher: scope check on the speaker → `approval` → preview pairing
(same agent + conversation, ≤ 24 h, canonical args) → `preflight` → persist action → render
approval → return `approval_requested`. Refused scope → structured result naming who lacked
which scope; the model relays, never routes around.

Implementation (T-055): `toolPolicySchema` (`packages/domain`) is strict, so `ToolsRepo.insert`
rejects unknown keys with `ToolPolicyError` (`invalid_tool_policy`). The `requiredScopesHook`
(`packages/agent-runtime/src/scopes.ts`) is the dispatcher's first `beforeToolCall` hook on
every agent. Scopes are opaque strings compared by exact equality; tools without
`requiredScopes` (and builtins without a policy, §1) stay open. A refused call never runs, is recorded as
`tool_calls.status = refused_scope`, and the model gets:

```json
{ "status": "refused_scope", "reason": "missing_scopes", "tool": "update_plan",
  "missing": ["billing:write"], "speaker": "Ana (usr_9f2)",
  "message": "No puedo ejecutar `update_plan`: Ana (usr_9f2) no tiene el permiso `billing:write`. Explícaselo y ofrece una alternativa; no intentes otra herramienta para lograr lo mismo." }
```

`reason` is `missing_scopes` (an `unknown` speaker or no principal holds none),
`identity_unavailable` (`principal.status = 'error'`), `group_not_allowed` (group chats: the
steer worker never calls the identity webhook there) or `invalid_policy` (a stored
`requiredScopes` that does not parse). `message` is in the turn's language.

Arguments bound to scopes (#585): `argScopes` maps a top-level argument of the call to a scope
prefix, and the same hook adds `<prefix><value>` to the scopes the call requires. With
`{ unit: "resident:unit:" }`, `register_visitor({ unit: "601" })` needs `resident:unit:601`, so
the model can only act for a unit the identity webhook gave the speaker; whatever it was told,
another unit is refused with `missing_scopes` naming that scope. The value is compared exactly
(no trimming or case folding). A bound argument that is missing, not a string, empty or over 200
characters is never granted. An `argScopes` that does not parse refuses with `invalid_policy`.
The tenant's webhook returns one scope per unit the person may act for (`resident:unit:502`).
Without a webhook, a dashboard grant can give the same scope (§2.2). Whoever approves the action
is bound the same way, from the arguments stored in the action (§4.3).

Implementation (T-061): `approvalHook` (`packages/agent-runtime/src/approval.ts`) runs right
after `requiredScopesHook`. Fields are read one by one; an `approval` value that does not parse
counts as `ask`. Without a decision surface (`any`: a channel with reply buttons, or the API,
whose caller decides with its own button; `verified`: the dashboard, so every channel, §4.3) or without the host gateway, `approvalFallback: refuse` (default) answers `{ status: 'approval_unavailable' }`
(`tool_calls.status = cancelled`) and `tool` runs the call without `context.approval`. `preflight`
calls the webhook once with `context.preflight: true` (`Idempotency-Key` suffixed `:preflight`);
a non-2xx answer is `{ status: 'preflight_rejected', detail }`. Otherwise the `pending` action is
stored (`group_id = grp_<turnId>`, proposer principal, exact `args`) and the model gets:

```json
{ "status": "approval_requested", "actionId": "act_…", "tool": "update_plan",
  "message": "`update_plan` necesita aprobación antes de ejecutarse y ya se pidió (acción act_…). Dile al contacto en una frase corta que le llegó un botón para confirmarla y que queda pendiente de aprobación hasta que la confirme; …" }
```

The message names the button because an `any` action is always put to the contact with one (the
card on Telegram and WhatsApp, the caller's app on the API): told only that it waits, the model
said «aguardando aprovação» and never told the person what to tap (#594).

Builtins (§1): `approvalPolicyOf`, `requiredScopesOf` and `readApprovalProof` read a builtin's
policy (`toolId === null`) from code, hardened by the agent's override (`builtinPolicyOf`). An
`ask` builtin is proposed like a tenant tool; its action stores `tool_id = builtin:<name>` (the
column has no foreign key to `tools`). At decision time `ActionDecisions` rebuilds the policy from
code (never from the action), checks the proof grade, the approver's scopes and the args hash
(§4.2), and runs exactly the stored `args` through `runBuiltin` (the builtin's own executor);
without one the action fails `unsupported_tool` and nothing runs.

Implementation (T-064): with `previewTool`, the pairing runs after the surface check and before
`preflight`. `ToolCallsRepo.findMatchingPreview` looks for the newest `ok` call of the preview
tool in the conversation (any turn, ≤ 24 h) whose `canonicalHash(args, descriptionArg)` equals
the proposal's (`tool_calls` keeps no hash; it is computed with the same canonicalisation). None
→ nothing is proposed (`tool_calls.status = preview_required`) and the model gets:

```json
{ "status": "preview_required", "tool": "update_customer_plan", "previewTool": "preview_plan_change",
  "message": "Antes de proponer `update_customer_plan` tienes que ejecutar `preview_plan_change` …" }
```

The action stores `preview_tool_call_id`, `preview_output` and `freshness_snapshot`. On approve,
after the hash check, `ActionDecisions` re-runs the preview webhook with the stored args minus
`descriptionArg` (no `context.approval`, `Idempotency-Key: action:<id>:preview`) and compares only
the declared paths (deep equality, key order ignored). A failed refresh fails closed: `failed`,
`preview_refresh_failed`, `Could not refresh preview: …`. A changed path moves the action to
`superseded` (event detail `{ reason: 'preview_changed', changes, supersededBy }`), stores a new
`pending` one (same turn, group and args; fresh preview; no `preview_tool_call_id`), calls
`onProposed` with the approver's text ("Los datos cambiaron: … Revisa y aprueba de nuevo.") for
the new card (T-062), and the continuation note tells the agent the new id. Proposing the same
tool with the same hash in a later turn supersedes the older `pending` action (`reason:
'reproposed'`); a different hash does not.

### 3.1 Template tools with external effects

A confirmation that lives only in the prompt is not a guarantee: text the model reads (a
document, a tool result, a forwarded message) can talk it past the confirmation, as a document
did with `create_work_item` in #576. Every template tool with an external effect therefore has a
guarantee in code, or a written reason why it does not need one (#581). The options are
`approval: "ask"`, a guard in the executor, or none because the effect is reversible and
harmless. `ask` needs a decision surface (§4.3). The customer templates run on WhatsApp, which
has reply buttons. The personal ones run on Telegram, which has them too. On the API, the
caller's app decides an `ask` tool for its user (§4.3, «API caller's button»). Read-only tools are
left out of the table.

| Template | Tool | Guarantee | Why |
|---|---|---|---|
| company-knowledge | `create_work_item` | `ask` | The agent reads documents that other people write; #576. |
| back-office | `apply_billing_adjustment` | `ask` + `previewTool` + `freshnessFields` + `preflight` (+ scope) | It changes what a customer is billed. `billing:write` for whoever proposes and approves; a preview (`preview_billing_adjustment`) with the same arguments must have run first; at approval the preview runs again and a changed `current_total`, `new_total` or `invoice_version` supersedes the action with a new card. The agent reads documents that other people write, as in #576. |
| back-office | `classify_document` | scope | `ops:write`. A category on a pending document, which the team can change again; nothing leaves the company. |
| condo | `book_amenity` | `ask` + scope on `unit` | The resident confirms with a button and the administration approves. The button is tapped by whoever writes and the administration does not see who asked, so `unit` is bound to `resident:unit:<unit>`: nobody books in another unit's name. |
| condo | `register_visitor` | `ask` + scope on `unit` | The tool lets a third party into the building, which cannot be undone once they are in. The template already asks for a button for amenities, so this adds one tap to the same flow. The button is tapped by whoever writes, so `unit` is bound to the speaker's `resident:unit:<unit>` (`argScopes`, §3): a contact cannot register a visit for a unit it does not live in. |
| condo | `create_maintenance_ticket` | scope on `unit` | In an emergency, the agent registers an urgent ticket without waiting, so a button would delay it. `unit` is the reporter's own unit (`resident:unit:<unit>`) and the place of the problem goes in the description, so a verified resident files at once, also for a common area. A contact nobody verified gets no ticket, but `escalate` has no scope and still alerts the administration and the front desk: the emergency never waits for verification. The administration triages every ticket before anyone visits, and a wrong ticket is closed. |
| dental, salon | `book_appointment`, `reschedule_appointment` | executor | On the calendar: ownership (a contact moves only its own appointments), idempotency key, availability, 10 writes per conversation per hour and at most 3 open appointments per contact ([ADR-0020](adr/0020-calendar-appointments.md) §2.4, §2.5, §2.8). The contact can cancel a wrong booking. A button on every booking would add a step to the template's main flow. |
| restaurant | `create_reservation`, `modify_reservation` | executor | The same calendar guards, plus seat capacity under a lock per area (ADR-0020 §2.11). |
| dental, salon, restaurant | `cancel_appointment`, `cancel_reservation` | `ask` | A cancelled slot can go to someone else, so it cannot be taken back. |
| real-estate | `schedule_showing` | `ask` | The contact confirms with a button and the advisor confirms after that. |
| real-estate | `create_lead` | none | It records the contact's own interest for the agency the contact is already talking to. No third party is involved, and a spurious lead costs the advisor one call. |
| personal-assistant | `save_note`, `create_task`, `complete_task` | scope | `personal:write`, and only the person's own data: the system filters by principal. `create_task` is idempotent by `source_ref` (`duplicate: true`). A note or task injected from an event description shows up in the person's own list, and a completed task can be reopened in the system. |
| personal-assistant | `delete_task` | `ask` (+ scope) | Deleting cannot be undone. |
| study-coach | `update_study_plan`, `record_quiz_result` | scope | `learning:write`. The student's own plan and progress, reversible, and nothing leaves the student. |
| client-handover | `create_folder`, `create_document_from_template` | scope | `clients:write`. They stay inside the company and are idempotent (an existing folder or document comes back with its id and `created: false`), so a retry or a repeated request never duplicates. The tenant's system refuses them for a handover that is not approved (`handover_not_approved`). |
| client-handover | `share_with_client` | `ask` (+ scope) | It gives someone outside the company access, and the agent reads handover notes that other people write. |

When a webhook of the business replaces the calendar, the executor guards are that system's.
The condo template's read tools bind `unit` too: `get_account_balance` (on top of
`resident:unit`) and `get_ticket_status` only read for a unit the identity webhook gave the
speaker, so a verified resident of 502 cannot read 601's balance or requests. `get_ticket_status`
also takes a `ticket_id`, which is not bound: the binding proves the `unit`, and the tenant's
webhook must answer only tickets of that unit, ignoring a `ticket_id` that belongs to another.

## 4. Governed actions

### 4.1 State machine
```
pending → executing → completed
                   ↘ failed
                   ↘ superseded   // preview changed at approval (T-064): nothing ran
        ↘ declined
        ↘ superseded
        ↘ expired (24 h)          // addition: explicit terminal state
executing (stale > turn_deadline) → failed (executor_lost)   // addition: sweeper
```

The sweeper (T-066) is the `maintenance` task `action-sweep`, every 5 minutes on the `scheduler`
role. Per org, in batches of 100 claimed with `FOR UPDATE SKIP LOCKED` (replicas and a decision in
flight never take the same row), as `actor { type: system, component: action-sweeper }`:
`pending` past `expires_at` → `expired`; `executing` with `decided_at` older than the agent's
`turn_deadline_ms` → `failed` with `error.code = executor_lost` (never `expired`). The
`action.expired` / `action.failed` event is published in the same transaction (T-083 bus), and a
platform note (notice turn, key `action:<id>:<status>`) wakes the agent, which tells the contact
the request expired and they can ask again, or that the outcome could not be confirmed. Outside the
24 h window that reply follows `windowPolicy` (T-081).

### 4.2 Canonicalisation and hash
`args_hash = sha256(JSON.stringify(sortKeysDeep(omit(args, [descriptionArg]), dropUndefined)))`.
The stored call replays **exactly** the stored `args`; Mastra's `approveToolCall` is invoked
only after the stored hash matches the pending tool call's args.

### 4.3 Decision surfaces
| Surface | Proof grade | How it arrives |
|---|---|---|
| WhatsApp reply buttons `act_<id>:approve` | any | `interactive.button_reply` |
| WhatsApp Flow (encrypted screen) | verified | `nfm_reply` with signed payload |
| Words in chat | any (decline always allowed) | model calls `action_respond { actionId | groupId, decision, words }` |
| API caller's button (`api` channel) | any | `POST /api/v1/openai/actions/:actionId/decide`, `via: api_button` (#580) |
| Dashboard (owner/admin) | verified | `POST /api/webapp/agents/:id/actions/:actionId/decide` |
| Slack / Teams button | verified | interaction payload |
| Signed magic link (email/SMS) | verified | single-use token |
| Partner API | verified | `POST /api/v1/developer/actions/:id/decide` (Keiki lacks this; we add it) |

`ActionDecisions.decide(actionId, decision, decider, via)` (T-061) is the only path that runs a
governed call: not `pending` → the record as is; approve → the approver's principal must hold
the tool's `requiredScopes`. It must also hold the scopes that the action's stored `args` bind
under `argScopes` (`missingApproverScopes`, #587). Otherwise the answer is
`requires_speaker_scopes` naming the missing scopes, and the action stays `pending`. Those are
the arguments the proposal stored, never ones a model proposes again: a neighbour of 601 cannot
approve a visit for 502 from the API, and an argument changed after the proposal is the one
required. A policy that does not parse fails closed. Team members are authorised by role on the
dashboard. Then → `executing` under the row lock →
`canonicalHash(args) ≠ args_hash` fails it with `args_mismatch` → the stored call runs with
`context.approval { actionId, decidedVia, decidedBy }` → `completed | failed`. Decline records
the reason in the event and the platform note. Every outcome starts a continuation turn (notice)
so the agent reports it.

Proof grade (T-063): `approvalProof` is read like the other fields (default `any`; a value that
does not parse counts as `verified`). An approve from an `any` surface (`whatsapp_button`,
`chat_words`) on a `verified` tool answers `approval_requires_verified_surface` and leaves the
action `pending`; a decline is recorded from any surface.

A `verified` action is never put to the contact: the gateway (`hasDecisionSurface`) takes the
dashboard as its surface on any channel (Telegram without buttons, the API), the contact gets a
text without buttons instead of the card (`approvalReply.pendingReview`, «La revisa el equipo»,
under the card's `<actionId>:ask` job) and the model reads `approval.requestedVerified`: tell the
contact the business reviews it and never ask them to approve. The grade is the hook's policy or
the gateway's own reading of the tool, `verified` if either says so.

The team hears of it by email (`apps/runtime/src/actions/pending-notice.ts`): after the proposal
commits, the gateway emails `settings.notifications.ownerEmail` (as balance and line-quality
notices do) and every owner and admin with a verified email, the roles that decide on the
dashboard. Once per action: a replayed step finds the action, the same call proposed in a later
turn replaces a pending one already notified, and each recipient's provider idempotency key is
`pending-approval-<actionId>-<hash of the address>`. The email names the agent and the tool and
links the action's page (`/<org slug>/actions/<actionId>`); never the contact, the arguments or
the card, and nothing in it decides (that would be a signed link, another `verified` surface).

Words in chat (T-063): the builtin `action_respond { actionId | groupId, decision, words }` is
offered while the conversation has a `pending` action (`turn.actionState`, which carries each
action's `groupId`). `words` must appear (case, spacing and surrounding punctuation aside) in one
of this turn's contact messages, else `{ status: 'error', error: 'words_not_from_contact' }` and
nothing is decided; that message is the `decision_message_id`. Only `pending` actions of the
turn's own conversation can be named (`not_found` otherwise). The decider is the turn's
principal (an unknown speaker is stored as the contact with no scopes), `via: chat_words`, and
the words go into the decision event's `detail.words` (on a decline also as the reason). The
tool result carries each outcome (`completed | failed | declined | expired | already_decided |
approval_requires_verified_surface | requires_speaker_scopes`), so no continuation turn is
started. `groupId` decides the group's pending actions one by one in proposal order (T-065
refines order and stop-at-first-failure).

API caller's button (#580): the `api` channel (agents as models, `docs/10` §3) has no reply
buttons and no outbound channel, so its surface is the caller's own app. `hasDecisionSurface`
takes the API as a surface for `any` actions (`hasApiSurface`); the gateway stores the `pending`
action as on any channel but sends no card job (nothing could deliver it). The chat completion
returns the actions its turn proposed that are still `pending` in `charla.pending_actions` (`id`,
`group_id`, `tool`, `description`, `card`, `status`, `expires_at`; never `args`), also on the last
chunk of a streamed answer. The app shows the card to its user and sends their answer with
`POST /api/v1/openai/actions/:actionId/decide { decision, user?, reason? }` and the same
`x-conversation-id`. `apps/web` authenticates the key (`agents:chat`) and validates the body; the
runtime (`apps/runtime/src/openai/decisions.ts`) answers `404 action_not_found` unless the action
is in an `api` conversation of the same org whose contact is `apiContactId(key, user)` and whose
thread is that `x-conversation-id` (and, for an agent-bound key, of its agent): a key, a `user`
or a conversation never decides another's action. With the agent's gateway off it answers
`403 gateway_disabled`. A non-pending action comes back as is (`changed: false`), so a replay or a
late second answer runs nothing. Otherwise it resolves the person's principal as a button press
does (identity webhook or dashboard grant, for the tool's scopes) and runs `decide` with
`via: api_button`, proof grade `any` (`ANY_PROOF_VIAS`): `expires_at`, the approver's scopes
(`403 requires_speaker_scopes`, still pending), the row lock and the args hash are `decide`'s, and
a `verified` tool answers `409 approval_requires_verified_surface`. The answer carries the action
after the decision (`completed` with its `result`, `failed`, `declined`, `expired`). There is no
continuation turn and no result message: the caller has the outcome, and the agent reads it in
the next turn's `# Acciones`. The turn that proposes resolves the same principal first (§2.2,
«API channel»), so a scoped `ask` tool is refused for scopes before any approval step unless the
webhook or a grant gives the contact that scope.

Why a request and not the chat: the chat completion's text is the model's (and, through tool
results, a document's), so nothing in it can approve. `action_respond` still accepts the
contact's own words on the API as on any channel (they must appear in the user message, «Words in chat» above),
but an instruction injected in a document (KB-160 in company-knowledge) can at most propose.
Trust: the API key holder answers for its users, as the business's WhatsApp number answers for
whoever holds the phone, which is why the grade is `any`, not `verified`.

Dashboard (T-063): owners and admins decide with `POST /api/webapp/agents/:agentId/actions/
:actionId/decide` (`docs/10` §2.9). `apps/web` authorises the member and checks that the action
belongs to that org (RLS) and agent, then forwards to the runtime's `POST /internal/actions/
:actionId/decide`, which runs `decide` with `decider: { type: 'member', memberId, role }` and
`via: dashboard` (grade `verified`).

Approver scopes are checked separately from the proposer's; the record keeps both. Second
press is a no-op; concurrent presses execute once (row lock). Groups: actions from one turn share
`group_id`; ≥ 2 pending → "Aprobar todo / Rechazar todo"; approve-all runs in order and stops at
the first failure.

`ActionDecisions.decideGroup(groupId, decision, decider, via)` (T-065) takes the group's `pending`
actions in proposal order and decides them **one after the other** through `decide`'s own checks
(lock, scopes, hash), never in parallel. Approve all stops at the first action that does not end
`completed` (`failed`, `superseded`, `expired`, `requires_speaker_scopes`); the later ones are
returned `skipped` and stay `pending`, decidable on their own. Decline all declines every one.
The result lists one entry per action; the agent gets a single continuation note with every
outcome and a `groupPending` line per skipped action (idempotency `group:<groupId>:<hash>`). A
group with nothing pending is `not_found`. The group card (`renderApprovalGroup`, `@charla/channels`)
numbers the summaries and carries the buttons `grp_<turnId>:approve|decline` (= `<group_id>:…`;
`replyRoute` → `group`, `parseDecisionReply`); sending it in place of the single cards, routing the
press in ingress and the dashboard's `POST /api/webapp/agents/:id/actions/groups/:groupId/decide`
follow the single-action surfaces (T-062, T-063). The dashboard route is built in T-136: `apps/web`
checks the role and that the group has a `pending` action of that agent in the org, then the runtime's
`POST /internal/actions/groups/:groupId/decide` runs `decideGroup` with the member as decider and
`via: dashboard`.

### 4.4 Approval summary (channel-agnostic card)
Keiki's `VaultCard` schema kept as our `ApprovalCard`: `{ v: 1, blocks: (header | fields | text |
email | image | note | divider)[], theme? }`, `$.path` templating, preview-tool override,
limits (1–20 blocks, 20 fields, 200/8,000 chars). Rendered as WhatsApp interactive (header +
flattened body + Approve/Decline), Flow screen, Block Kit, or dashboard panel. Invariants: exactly
two decision buttons, visible real tool name, "what runs is the stored call".

(T-062) The card is built at proposal from the stored call, never from the model's text: a valid
preview `card` (T-064) wins, then `policy.card` filled from the arguments, then one
`argument: value` field per argument after the `descriptionArg` walkthrough. Templating: a string
that is exactly `$.input.<path>` (`$.input.items.0.name`) reads the argument; arrays join with
`, `, `{ email, name }` reads `Name <email>`, other objects as JSON, missing or empty values drop
their field or block; labels are literal; resolved values are cut to the limits. The filled card
is stored in `actions.card` (snapshot) and sent once per action (`<actionId>:ask`). A tap arrives
as `button_reply`; ingress stores it, never steers, and queues the `action-decision` job (ingress
outbox kind `action_decision`). The runtime checks the action belongs to the conversation, refuses
`approvalProof: verified` with an explanation (the button proves nothing more than words),
resolves the presser's principal (T-054) and calls `decide` with `via: whatsapp_button`. Not
pending, expired or another conversation's → "Esta solicitud ya no está activa"; missing scopes →
"no tienes permiso", still pending. After the decision `onSettled` sends `Aprobado por <decider> ·
Hecho`, `Aprobado por … · No se pudo completar: <error>` or `Rechazado por …` as a `system`
message (WhatsApp cannot edit the card); the continuation turn lets the agent report too.

### 4.5 Action state in the prompt
Every turn gets a `# Acciones` section listing open and recently closed actions with status,
summary, decider and result so the agent reports facts and never proposes twice.

Implemented in T-068. The turn builder reads `ActionsRepo.listStateForConversation`: open actions
(`pending`, `executing`) plus those settled in the last 24 h, at most 50. `actionStateOf` keeps
only the walkthrough (`descriptionArg`), the decider's name, a short result (the result's `id`,
`reference`… or its clipped JSON) and the error; `args` never reach the prompt.
`buildActionStateSection` (`packages/agent-runtime/src/prompt.ts`) writes one line per action,
in the agent's locale:

```text
- [pending] act_01 · update_customer_plan · "Enterprise, 2.400 €/mes" · propuesta hace 3 min · esperando aprobación · grupo grp_…
- [completed] act_02 · create_subscription · "Plan Pro mensual" · aprobada por Ana hace 2 h → sub_8Kq2
- [failed] act_03 · issue_refund · "Reembolso de 300 MXN" · aprobada por Ana hace 1 h · motivo: card_declined: …
```

At most 10 lines: open actions first (the model needs their ids for `action_respond`), then the
most recently updated; a final line counts the hidden ones. The section ends with the rules: report
this state, never from memory; one short sentence when proposing and never propose again what is
`[pending]`; never say a `[pending]` or `[executing]` action happened; `action_respond` only on an
explicit decision. Texts live in `src/strings/*.ts` (`actionState`) for es, pt-BR, pt-PT, it, en.
A decided action without a principal decider is shown as decided by the team.

### 4.5.1 Tools called by workflow nodes (T-164)
A `tool` node of an agent workflow (`docs/07` §14) calls its tool without the model, with
arguments taken from expressions. It is governed exactly like the model's call, because it runs
the same dispatched tool the model is offered: `requiredScopes` against the turn's speaker
(T-055), `approval: 'ask'` with its `approvalFallback`, `preflight` and `previewTool` (T-061,
T-064), the `afterToolCall` hooks and the `tool_calls` row (`toolCallId = wf_<node>_<turnId>`).
A refusal (`refused_scope`, `approval_unavailable`, `preflight_rejected`, `preview_required`) is
the node's failure branch, as `tool.ok = false` with that `tool.status`. A node never calls a
platform builtin; the `handoff` node runs `escalate` the same governed way.

An `ask` tool proposes a `pending` action and the approval card as in §4.3, and the turn ends
`approval_requested`. The workflow never moves past the node by itself, and the model cannot move
it either: the contact may keep writing and the agent answers that it is pending. The decision
runs the stored call once (§4.1); the continuation turn reads the decided action and takes the
node's success branch (`completed`) or its failure branch (`failed`, `declined`, `expired`,
`superseded`) without calling the tool again. Decisions keep their surfaces and proofs (§4.3):
a node is not a decision surface.

### 4.6 Lifecycle webhooks
`action.pending | executing | completed | failed | declined | superseded | expired` to the
deployment's `actions.webhook_url` with the public record, signed, 5 s timeout, no retries, never
blocking. `view_url` with `{actionId}`, `{groupId}`, `{conversationId}`, `{toolName}`.

Implementation (T-067, `apps/runtime/src/actions/webhooks.ts`):

- Config `{ viewUrl?, webhookUrl?, secretRef? }` lives in `agents.harness_config.actions` until
  `deployments` exists. `viewUrl` is `https://` and only uses the four placeholders; `secretRef`
  (an org secret, T-050) is required with `webhookUrl`. `checkActionsConfig` is the save-time
  check: public HTTPS (`url_scheme`, `url_private_address`…) and a secret of ≥ 16 characters
  (`secret_missing`, `secret_too_short`). Sending checks the secret again and `safeFetch` the URL.
- Every transition (gateway proposal and supersession, decisions, executor, sweeper) hands the
  committed row to `emit`, which returns at once; webhooks of one action leave in transition order.
- Body: the `docs/10` §5 envelope, `type: "charla.action.<status>"`, `data: { action:
  PublicActionRecord, viewUrl: string | null }` (`viewUrl` resolved, each value
  `encodeURIComponent`-ed). Any resolved secret value in the body (e.g. in `args` or `result`) is
  replaced by `[redacted NAME]` before signing.
- Headers: `Charla-Timestamp` + `Charla-Signature: sha256=<hex>` (the tool-request format of §1.1,
  same verification code), `Charla-Event-Id`, `Charla-Event-Type`.
- Each send is one `action_webhook_attempts` row (`delivered` on 2xx, else `failed` with the
  reason). An agent without `actions.webhookUrl` sends and records nothing.

## 5. Human-in-the-loop

- **Approvals** (above).
- **Handoffs**: `escalation` config routes to dashboard queue (always), Slack thread, email,
  webhook, **WhatsApp team number/group** (addition). Reply = takeover; `//` internal; `@agent
  nota` hands back with a note; hold lapses 30 min after last team reply on non-escalated
  conversations; unclaimed escalation auto-closes after 7 days; the agent may close its own
  escalation with `resolve_escalation { summary }`. Implemented in T-073: the tool is offered
  with `escalate` while the conversation has an open handoff, and closes it only when it is
  `kind = escalation`, opened by this agent and still `waiting`; a `taken` handoff (a member
  holds it), a manual takeover or a work item is refused with the reason (`taken_by_team`,
  `not_opened_by_agent`). Closing writes a `system` line to the transcript ("Escalado resuelto
  por el agente: …", never sent to the contact) and publishes `handoff.resolved`
  (`resolvedBy: agent`). The `maintenance` task `handoff-sweep` runs daily at 04:00 UTC and
  moves `waiting` handoffs opened 7+ days ago to `stale` (`resolvedBy: system`), in batches
  claimed with `FOR UPDATE SKIP LOCKED`, one `withOrg` transaction per org; `taken` ones are
  never touched. Team messages stay in history with role
  `team`. A human reply after the 24 h window must go out as a template (dashboard shows the
  constraint and offers the org's templates).
  Routes (T-071, `apps/runtime/src/handoffs/notifier.ts`): each configured route is notified
  independently when a handoff opens and records its attempt on the handoff. Email (Resend;
  Mailpit locally) carries reason, summary and the dashboard link, never the transcript. The team
  number gets a card with Tomar / Ver (`hnd_<id>:claim|view`) while its 24 h window is open, the
  approved `handoff_notificacion` template otherwise, or nothing. Tomar claims for the member whose
  `members.whatsapp_number` pressed it; replying to the contact happens in the dashboard (T-072).
  Implementation (T-072): the dashboard's `POST /api/webapp/conversations/:id/messages` takes
  over in one transaction (`held`, `held_by_member_id`, `held_until`; a `waiting` handoff is
  claimed), then aborts the running turn (abort flag + `abortThreadStream`) and drops the
  pending `steer` job and buffer; `deliver` refuses agent replies while held
  (`conversation_held`). Contact messages while held are stored, shown to the team and never
  steered. Hand-back (`/handback { note? }`) and the `hold-sweep` (every minute) resume the agent
  with a notice turn whose platform note quotes the hold labelled `Equipo` / `Contacto`, because
  the agent's memory never saw those messages.
  Queue (T-176, `/[org]/handoffs`): a `taken` handoff is released or resolved only by its
  claimer or an owner/admin (`403 not_claimer`); `release { note? }` also hands a conversation a
  member holds back to the agent through the hand-back above, with the note.
  Template mode (T-134): outside the window the text route answers `409 window_closed` with the
  number's approved templates the inbox can fill (body variables only); the composer sends one
  through `POST /api/webapp/conversations/:id/templates { name, language, variables }`
  (`Idempotency-Key`), which takes over exactly like a text and queues the `template` intent on
  `deliver` with `role: team`. Unknown or unapproved templates are `409 template_unavailable`,
  a wrong variable count `400 invalid_variables`, and neither silences the agent.
- **Notices**: `POST /api/v1/developer/agents/:id/notice { text, contact?, conversation? }`
  starts a silent turn; text is for the agent, never forwarded.
- **Work items**: `POST /api/v1/developer/handoffs` with `subject` or `conversation`, `actions`
  bound to saved webhooks or capability tools, optional `form` JSON Schema, `Idempotency-Key`.

## 6. Secrets handling
- Org developer secrets (`PUT /api/v1/developer/secrets/:NAME`), BYOK secrets, channel
  credentials, per-sender MCP headers, personal secrets: all AES-256-GCM, write-only.
- BYOK secrets are kind `byok`, one per model provider, named `BYOK_<PROVIDER>`
  (`BYOK_ANTHROPIC`, `BYOK_OPENAI`, `BYOK_GOOGLE`; `@charla/domain` `secrets/byok.ts`); the
  `BYOK_` prefix is reserved. Written from the dashboard settings (T-137, Pro and above).
- Payment provider tokens (Mercado Pago OAuth) are kind `payment`, one per connection, named
  `PAYMENT_<PROVIDER>_<connection id>`; the `PAYMENT_` prefix is reserved. Only the provider
  adapter decrypts them; never in tool results or job payloads ([ADR-0019](adr/0019-agent-payments.md)).
- Per-person connection tokens are kind `person_connection`, one per connection, named
  `PERSON_<CONNECTOR>_<connection id>`; the `PERSON_` prefix is reserved
  ([ADR-0022](adr/0022-per-person-connections.md) §2.8, Proposed).
- `{{secret.NAME}}` placeholders resolved host-side at call time; stripped from errors, traces,
  tool args and prompts; prefix-matched pastes redacted as `[redacted NAME]`.
- Personal secrets (Later): single-use 15-minute link bound to conversation and person; injected
  as env for one sandbox command; `needsAuth` structured result when missing.

## 7. Prompt safety
- Input processors: prompt-injection detector (flag, not block, by default: annotate the message
  with a warning like Keiki's prompt guard; block only for deterministic known attacks), PII
  redaction for traces/exports (configurable), moderation for regulated verticals.
- Output processors: unsupported-claim guard (an outbound claiming "listo/pagado/reservado"
  without a matching successful tool call is rewritten or flagged), channel length guard,
  markdown stripping for WhatsApp (`noMarkup`), secret redaction.
  Implemented in T-046 (`apps/runtime/src/mastra/processors/`): Markdown stripping and the length
  guard run on WhatsApp, Telegram and SMS; the claim guard runs on every channel. A claim of a
  family (booking, payment, send, cancel, mark) is supported by a successful call of a tool whose
  name matches that family (`toolFamilies`; read-only `get_/list_/check_…` tools never count).
  Every unsupported claim raises an `unsupported_claim` signal at the end of the turn; with
  `features.guards.strictClaims` the claim is also rewritten to "requested, I'll confirm" in the
  stream, before delivery. That rewrite cannot be an `abort` in `processOutputResult`: steer
  delivers paragraphs while the run is streaming, so by then the contact has read the claim.
