# Kordio Control API Source: https://docs.kordio.io/agents/api-reference/introduction Every control-layer endpoint, generated from the OpenAPI specification. This reference is generated from the spend control [OpenAPI specification](/agents/api-reference/openapi.yaml). Each endpoint page shows the request, parameters, response schema, and live examples. ## Base URL ``` https://api.kordio.io ``` ## Two credentials | Prefix | Credential | Used by | | ----------------------------------------------------- | ------------------------------------------- | ---------------------------- | | `/control/v1/agent/*` | Agent key, `krt_live_...` or `krt_test_...` | Your agent | | `/control/v1/workspaces/{slug}/*` | Identity bearer token | A person or your backend | | `/control/v1/cosign/verify`, `/.well-known/jwks.json` | None | Anyone verifying a signature | An agent key can never write policy, and a dashboard token can never authorize an action as an agent. See [authentication](/agents/authentication). ## Response envelope Single resources wrap the object in `data`: ```json theme={"dark"} { "data": { "id": "9b2ef0c1-...", "state": "pending" } } ``` The two authorize endpoints add the decision alongside it, and a cosignature when one was issued: ```json theme={"dark"} { "data": { }, "decision": { }, "cosignature": "eyJhbGciOi..." } ``` The `cosignature` key is **absent**, not `null`, when no signature was issued. Control-plane responses carry no `livemode` and no `request_id`. The ledger API includes both. If you are building one client for both, do not assume a shared envelope. ## Pagination Workspace lists take `limit` (default 50, clamped 1..200) and `starting_after`, which is the **id of the last record on the previous page** rather than an opaque cursor. ```bash theme={"dark"} curl "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents?limit=50&starting_after=9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json theme={"dark"} { "data": [], "has_more": false, "next_cursor": null } ``` Three things differ from [the ledger's pagination](/ledger/pagination): * The parameter is `starting_after`, not `cursor`. * `has_more` is true whenever a page filled to the limit, so a final page that exactly fills it still reports `true`. Fetch until you get an empty page rather than trusting the flag alone. * An unknown or foreign `starting_after` is ignored and returns the first page rather than an error. `GET /control/v1/workspaces` and `GET /control/v1/workspaces/{slug}/funds` are not paginated. Most lists are newest first. Memberships, invitations and policy modules are ascending, and policy modules paginate by `name` rather than by id. ## Idempotency | Endpoint | Mechanism | Missing | | ---------------------------------------- | ---------------------------- | ------------------------------ | | `POST /control/v1/agent/actions` | `Idempotency-Key` header | `422 idempotency_key_required` | | `POST /control/v1/agent/payment_intents` | `idempotency_key` body field | `400` | | Everything else | None | n/a | Keys are scoped per agent. A replay returns the original intent and the original decision, at the original status. ## Errors ```json theme={"dark"} { "error": { "message": "...", "code": "..." } } ``` See the [errors reference](/agents/errors) for every code, and for the rules that can appear in `decision.rule`. ## Next steps The five-minute path through these endpoints. The other API on this host. # Holding spend for a person Source: https://docs.kordio.io/agents/approvals What a 202 means, how an agent waits, and what an approver sees. Some spend should not be a machine's call. An approval threshold does not refuse the action; it parks it until a person decides. ## What your agent sees When a rule holds an action, the authorize call returns `202` and the intent is in state `requires_approval`: ```json 202 Accepted theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "state": "requires_approval", "action_type": "payment.create", "cost_cents": 240000, "currency": "USD" }, "decision": { "outcome": "requires_approval", "rule": "approval_threshold", "detail": { "threshold_cents": 100000, "requested_cents": 240000 }, "headroom": { "session_remaining_cents": 480000, "approval_threshold_cents": 100000 }, "policy_snapshot": [ { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "status": "active", "mode": "blocklist" } ] } } ``` There is no `cosignature`. Nothing has been authorized yet, and nothing mints one later either: approving moves the intent to `pending` and returns it, without a signature. The budget is reserved while the intent waits, so a held action cannot be quietly outspent by the next one. `headroom` was measured before that reservation, which is why it reads \$4,800 rather than what is left now. ## How your agent should wait Do not busy-poll, and do not treat a hold as a failure to retry around. Retrying with a new idempotency key creates a second held intent and asks a person the same question twice. Subscribe to `action.requires_approval` and `approval.resolved`. This is the one to use in production. `GET /control/v1/agent/actions/{id}` until `state` leaves `requires_approval`. Fine for a script. ```bash theme={"dark"} curl https://api.kordio.io/control/v1/agent/actions/$KORDIO_ACTION_ID \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" ``` ## What the person sees An approver who only sees "approve \$2,400?" is rubber-stamping. So there is an endpoint that answers what approving would actually do, before anyone clicks: ```bash theme={"dark"} curl "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents/$KORDIO_ACTION_ID/impact" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": { "amount_cents": 240000, "currency": "USD", "rule": "approval_threshold", "executed": false, "session": { "id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "budget_cents": 500000, "spent_cents": 260000, "remaining_cents": 240000, "returns_on_deny_cents": 240000, "open_holds": 2 }, "runtime": { "id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "name": "procurement agent", "mode": "live", "scopes": ["payment.*"] }, "windows": [ { "kind": "velocity", "window_seconds": 3600, "cap_cents": 500000, "spent_cents": 240000, "remaining_cents": 260000 } ], "spend_token": null } } ``` `session` is the budget and `runtime` is the agent, in the wire names this endpoint has always used. Three figures carry the decision. Budget is **already reserved** while an intent is held, so approving costs no further headroom. `returns_on_deny_cents` is what denying gives back. And `open_holds` counts the held intents competing for the same budget, including this one, which is how an approver sees that three pending approvals total more than the budget can cover. `executed` is always `false` here. The endpoint answers what approving would do, and Kordio never executes anything, so it has nothing else to report. `GET .../payment_intents/{id}/impact` is the same shape, plus the spend token the payment cites, if any. ## Resolving it ```bash theme={"dark"} curl -X POST \ "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents/$KORDIO_ACTION_ID/approve" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` Both calls require the `approve` capability, and both record `resolved_by_sub`, which is who decided, and emit `approval.resolved`. ### Actions and payments resolve the same way | | Action intent | Payment intent | | ------------ | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | | **Approved** | Moves to `pending`. Your agent proceeds as it would have on a `201`, then reports with `complete` or `fail`. | Moves to `pending`. Your agent settles on its own rail, then reports with `complete` or `fail`. | | **Denied** | Moves to `denied`, reservation released. | Moves to `denied`, reservation released, ledger release enqueued. | Approving grants authority. It never moves money: an approved payment is still waiting on your agent to execute it and say what happened. A denial is not a rate limit. Do not re-ask with a fresh idempotency key. If your agent genuinely needs a different action, that is a different action: new amount, new resource, new key. Resolving an intent that is not in `requires_approval` is a `422`, so a double-click cannot double-execute. ## Who can approve Approving is a capability, not a job title. `approve` is separate from `manage_policy`, so the person who authorises a payment need not be the person who can widen the rule that held it. Keep those apart. Segregation of duties is most of what an auditor is looking for here. What the product does not do for you: it will not route a hold to a named person, a rota, or a group, and it has no quorum. Anyone holding `approve` in the workspace can resolve any hold in it, one call resolves it, and `resolved_by_sub` records who. There is also no escalation and no expiry, so a hold that nobody answers waits, and its reservation waits with it. ## Next steps Wait on `approval.resolved` instead of polling. Why `approval.resolved` is not itself permission. # Agent keys and dashboard tokens Source: https://docs.kordio.io/agents/authentication Two credentials, trusted differently, and how to get the first one. Kordio Control has two callers, and they authenticate differently because they are trusted differently. An agent able to widen its own limits is not governed by them, so the separation is the point rather than a formality. | Caller | Credential | Reaches | | ---------------------------------------------------- | ------------------------ | --------------------------------- | | An **agent**, asking whether it may act | Agent API key, `krt_...` | `/control/v1/agent/*` | | A **person or your backend**, managing the workspace | Identity bearer token | `/control/v1/workspaces/{slug}/*` | An agent key can never write policy, and a dashboard token can never authorize an action as an agent. Integrating the ledger instead? It uses OAuth 2.0 client credentials, documented on [Ledger: OAuth client credentials](/ledger/authentication). Nothing on this page applies there. ## Getting your credentials Everything below needs a workspace and a dashboard token, so start here. 1. Sign up at [app.kordio.io](https://app.kordio.io) and create a workspace. You become its `owner`, which carries every capability. 2. Your **workspace slug** is the one in the console URL: `app.kordio.io/{slug}`. It is the `{workspace_slug}` path segment in every management call. 3. Your **dashboard token** is the identity token the console holds after sign-in. For scripting, mint one directly: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/auth/signin \ -H "Content-Type: application/json" \ -d '{"email": "you@example.com", "password": "..."}' ``` ```json 200 OK theme={"dark"} { "data": { "access_token": "eyJhbGciOi...", "refresh_token": "...", "user": { "id": "...", "email": "you@example.com" } } } ``` `access_token` is the dashboard token. It is short-lived; exchange the `refresh_token` at `POST /v1/auth/refresh` rather than re-sending credentials. If your account has MFA enabled, sign-in answers `401` with code `mfa_required` and a `pending_authentication_token` to complete at `POST /v1/auth/verify_mfa`. A dashboard token carries your full capability set in the workspace. It is not an agent credential and must never be given to an agent. Agents get an agent key, which cannot write policy. Set both for the rest of the docs: ## Agent keys This is the credential your agent carries. Create an agent and the key is returned exactly once: ```bash cURL theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/agents \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "procurement agent", "mode": "test", "scopes": ["payment.*"]}' ``` ```typescript TypeScript theme={"dark"} const res = await fetch( `https://api.kordio.io/control/v1/workspaces/${process.env.KORDIO_WORKSPACE}/agents`, { method: "POST", headers: { Authorization: `Bearer ${process.env.KORDIO_DASHBOARD_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify({ name: "procurement agent", mode: "test", scopes: ["payment.*"], }), }, ); const { data } = await res.json(); ``` ```python Python theme={"dark"} import os, requests res = requests.post( f"https://api.kordio.io/control/v1/workspaces/{os.environ['KORDIO_WORKSPACE']}/agents", headers={"Authorization": f"Bearer {os.environ['KORDIO_DASHBOARD_TOKEN']}"}, json={"name": "procurement agent", "mode": "test", "scopes": ["payment.*"]}, ) data = res.json()["data"] ``` ```json 201 Created theme={"dark"} { "data": { "id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "name": "procurement agent", "status": "active", "mode": "test", "scopes": ["payment.*"], "api_key_prefix": "krt_test_9f3", "api_key": "krt_test_9f3a1c7e42b8d05a6e1f8c3d", "last_used_at": null, "created_at": "2026-08-22T09:04:11Z", "starter_policy": { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "status": "active", "mode": "blocklist", "per_transaction_cap_cents": 50000, "approval_threshold_cents": 10000, "imports": [], "rules": [] } } } ``` Kordio stores only a digest and compares it in constant time. `api_key` cannot be shown again; if you lose it, rotate the agent. Keys are prefixed by mode, `krt_test_...` or `krt_live_...`, so a test key can never reach live data. The agent arrives with an active `starter_policy`: $500 on a single action, and anything over $100 held for a person. It governs from the first request, and it keeps governing until you disable it, so a threshold you write later does not replace it. Send `"skip_starter_policy": true` to create an agent with nothing attached, which denies everything with `no_policy` until you write a rule. Send it as a bearer token: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-4471" \ -H "Content-Type: application/json" \ -d '{"budget_id": "3f1c...", "action_type": "payment.create", "cost_cents": 12000}' ``` ### Scopes `scopes` restricts which action types a key may even ask about: an exact match (`payment.create`), a namespace wildcard (`payment.*`), or `*`. An empty array means unrestricted. A request outside the key's scopes is refused by an intrinsic rule before any policy runs, and the decision names `runtime_scope` as what refused it. Scope narrowly, and use one agent per workload. A key shared across two workloads buys you nothing and costs you the ability to revoke one of them without stopping the other. ### Rotating and revoking An agent is `active`, `suspended`, or `revoked`, changed with `PATCH /control/v1/workspaces/{slug}/agents/{id}`. Suspending stops new authorizations and leaves history intact; revoking is permanent. Neither rewrites decisions already made, and neither invalidates a cosignature already issued, which stays verifiable until it expires. Cosignature lifetime is minutes, so that window is small, but it is not zero. See [what Kordio guarantees](/agents/guarantees#revocation-is-not-retroactive). ## Dashboard tokens and capabilities Everything under `/control/v1/workspaces/{slug}/*` uses the identity token: creating agents, writing policy, reading intents, resolving approvals, managing billing. ```bash theme={"dark"} curl https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` Capabilities come from your role in that workspace, and the API enforces them: | Role | Capabilities | | -------- | ---------------------------------------------------- | | `owner` | `read`, `approve`, `manage_policy`, `manage_members` | | `admin` | `read`, `approve`, `manage_policy` | | `member` | `read` | | Capability | Lets you | | ---------------- | ---------------------------------------------------------------------------- | | `read` | See agents, policies, budgets, intents, funds, the audit trail | | `approve` | Resolve a held action | | `manage_policy` | Write policy, create and rotate agents, manage webhook endpoints | | `manage_members` | Invite and remove people, change roles, manage billing, delete the workspace | `approve` and `manage_policy` are deliberately separate. The person who authorises a payment need not be the person who can widen the rule that held it, which is most of what an auditor is looking for. Every role can read the audit trail, including `member`. An audit trail only some people can see is not much of one. ## Test and live Every credential is bound to one mode and the two never mix. A test agent key cannot touch live data, and a live agent cannot be created on a plan without live mode. Test mode runs the same policy engine, returns the same shapes, and issues real cosignatures. That is deliberate: you can prove an entire integration, including signature verification inside your own executor, before any money is at stake. Control-plane responses carry no `livemode` field. The mode is a property of the agent, so read it from `GET /control/v1/workspaces/{slug}/agents/{id}`, or from `agent_mode` inside a decision. The ledger API does echo `livemode` on every response, so do not write one client that assumes both. ## When something is refused | Status | Meaning | | ------ | ------------------------------------------------------------------------------------------------------------------------------- | | `401` | Missing (`runtime_key_required`) or unrecognised (`invalid_runtime_key`) credential. | | `403` | Recognised but not permitted: a capability you lack (`insufficient_role`), or a decision that was denied. | | `404` | The resource exists but not in a workspace or agent you can reach. Kordio does not confirm existence across a tenancy boundary. | A `404` where you expected a `403` is usually a workspace or agent mismatch, not a missing record. ## Next steps Put the check in front of a real spend. Every code and every rule that can refuse. # How a decision is reached Source: https://docs.kordio.io/agents/concepts Evaluation order, outcomes, states, and headroom. A decision is a pure function of the request. Kordio calls nothing while it decides, reads nothing but the fields you sent and the limits already on record, and answers in the same request: allowed, needs a person, or denied. ## The shape of the flow ```mermaid theme={"dark"} sequenceDiagram participant A as Agent participant K as Kordio participant X as Your executor participant R as Payment rail / API A->>K: POST /control/v1/agent/actions Note over K: intrinsic rules, then policy
first denial wins alt allowed K-->>A: 201 + decision + cosignature A->>X: execute, carrying the cosignature X->>X: verify signature and claims (offline) X->>R: perform the action A->>K: POST /actions/{id}/complete else requires_approval K-->>A: 202, budget reserved, no cosignature Note over K: a person approves or denies else denied K-->>A: 403 + the rule that refused end ``` The executor verifying the cosignature is the part that makes this enforcement rather than advice. A decision stored only in our database binds an executor that chooses to ask us, every time. A signature binds anything that checks it. ## Evaluation order Three **intrinsic rules** always run first. They cannot be disabled and they are not part of any policy you write: 1. `session_inactive`: the budget must be `active`. 2. `runtime_scope`: the agent's key must be scoped for this action type. 3. `session_budget`: the spend must fit the remaining budget. Then the rules compiled from each active policy run, oldest policy first, with imported modules compiled in ahead of a policy's own rules. **The first denial wins**, immediately. An approval requirement only stands if nothing denies. That ordering matters: a rule that would hold something for a human never overrides a rule that refuses it outright. **An agent with no active policy denies everything**, with the rule `no_policy`. The intrinsic rules do not count as a policy. This is fail-closed by design: an agent nobody has written rules for has no authority rather than unlimited authority. Two ways in: creating the agent with `skip_starter_policy: true`, or disabling the last policy it has. A new agent otherwise arrives with an active starter policy, so `no_policy` is a state you choose rather than one you land in. An `allowlist`-mode policy that matched no `allow` rule denies with `not_allowlisted`. Each allowlist policy is an independent gate, so attaching two means both must be satisfied. ## Outcomes and states are different vocabularies Two fields describe adjacent facts and they overlap without meaning the same thing. `decision.outcome` is what the policy engine answered. `data.state` is where the intent sits in its lifecycle. | `decision.outcome` | Status | Resulting `state` | What it means | | ------------------- | ------ | ------------------- | -------------------------------------------- | | `allowed` | `201` | `pending` | Authority granted. Nothing has happened yet. | | `requires_approval` | `202` | `requires_approval` | Parked for a person. Budget reserved. | | `denied` | `403` | `denied` | Refused. Nothing reserved. | An allowed payment lands in `pending` exactly like an allowed action does. Kordio executes nothing, so there is no state in which it has already spent on your behalf. `pending` means you hold the authority and have not yet said what you did with it. An intent leaves `pending` only when you report the outcome. So `requires_approval` and `denied` appear in both vocabularies and mean the same thing; every other value belongs to one or the other. Full state sets: * Action intent: `pending`, `requires_approval`, `completed`, `failed`, `denied`. * Payment intent: `pending`, `requires_approval`, `executed`, `failed`, `denied`. ## Why a budget and not just a cap A per-transaction cap stops one big mistake. It does nothing about the same reasonable-looking action happening nineteen times. A budget is the answer to that. You open one per run, every authorized action commits against it, and it is what the loop eventually runs into. Reservations are held while an action is pending or waiting on a person, and released when it fails or is denied. A budget is claimed with a single conditional update rather than a lock, so parallel sub-agents under one agent contend at the row instead of queueing behind each other. A budget has no expiry and no close endpoint. It stops spend by running out, not by ending, so an action nobody reports as `complete` or `fail` holds its reservation for good. Open a budget per run rather than reusing one. ## Headroom Every decision carries `headroom`, reporting what each limit had left when the decision was made, reduced to the tightest value per key. Read it as before, not after. Headroom is computed ahead of the reservation, so on an allowed decision `session_remaining_cents` still counts the amount you were just authorized to spend. Subtract `cost_cents` yourself if you want the figure after this action. Give it to your agent either way. An agent that knows it has \$380 left on the budget picks a cheaper vendor; an agent that only knows it was refused retries into the same wall. ## Policy snapshot Every decision also carries `policy_snapshot`: the active policies exactly as they read at the instant the decision was made, each with its typed columns, its `mode`, its `imports` and its `rules` array. That is what makes a decision auditable after the fact. Widen a cap next month and the decision recorded today still shows the narrower one, so "why was this allowed" has an answer that does not depend on the policy still existing. Each entry also carries `imported_rules`: the rules of every module the policy imports, resolved at decision time. The `imports` array names the modules, `imported_rules` records what they said, so editing a shared module next month does not quietly rewrite what today's decision was judged by. It is `[]` in exactly three cases, and each one means no policy ran: the agent has no active policy (`no_policy`), a spend token refused before the engine started, or the budget was claimed out from under the request between evaluation and reservation. An allowed decision always carries at least one policy. ## The remedy A refusal that only says what broke leaves the agent to guess, and agents guess by retrying into the same wall. Every denial and every hold therefore carries a `remedy`: what would have to change for the call to go through. ```json theme={"dark"} { "outcome": "denied", "rule": "per_transaction_cap", "detail": { "limit_cents": 50000, "requested_cents": 120000 }, "remedy": { "kind": "lower_amount", "max_cents": 50000, "summary": "A per-action cap applies. Retry at $500.00 or less." } } ``` Branch on `kind` in code, show `summary` to a person. The amount in `max_cents` is the real one: for a monthly cap it is what is left after this month's spend, not the cap itself, and for a budget it is what the budget has left rather than what was asked for. Three kinds an agent can act on alone: | `kind` | What to do | | ------------------------- | ---------------------------------------------------------------- | | `lower_amount` | Retry at `max_cents` or less | | `wait` | Retry after `retry_after_seconds`, or next month when it is null | | `use_pinned_counterparty` | Send to `resource` instead | The rest need a person: `raise_budget`, `reopen_budget`, `allow_resource`, `allow_action`, `grant_scope`, `create_policy`, `new_spend_token`, and `approve` on a hold. On `approve`, `max_cents` is the amount that would have cleared without anyone being asked. `remedy` is `null` on an allow, and on the rare denial with no mechanical cause, such as a free-form condition that matched. It is stored with the decision rather than recomputed, so it records the fix as it stood at the time even if the policy has moved on since. ## Policy version and frame hash Alongside the snapshot, every decision carries two digests. `policy_version` is a content digest of that snapshot. The same rules always hash to the same version and any edit produces a different one, so decisions group by the ruleset that judged them and the same request under the same version replays to the same outcome. It reads `pv_none` when no policy ran. `frame_hash` is a SHA-256 over the request frame: action type, resource, cost, currency, agent, budget, workspace and the whole `metadata` object. It binds the decision to the exact request that produced it, including metadata that no response echoes back. Unlike the snapshot, it is present on every decision, including the denials that never reached the policy engine. Both are repeated in the cosignature claims, so whoever executes the action can pin the decision without calling back. See [Cosignatures](/agents/cosignatures). ## Payments work like actions `POST /control/v1/agent/payment_intents` is a separate resource from `POST /control/v1/agent/actions`, but it behaves the same way: Kordio authorizes, you execute, you report back. It holds no funds and moves no money, so there is nothing it could execute on your behalf. One difference remains, and it will bite you if you assume symmetry. | | `/control/v1/agent/actions` | `/control/v1/agent/payment_intents` | | ------------ | ---------------------------------------------- | -------------------------------------------------- | | Idempotency | `Idempotency-Key` **header**, missing is `422` | `idempotency_key` **body field**, missing is `400` | | On `allowed` | `state: pending`, you execute | `state: pending`, you execute | | Reporting | You must call `complete` or `fail` | You must call `complete` or `fail` | The terminal success state differs in name only: an action ends `completed`, a payment ends `executed`. Both mean the same thing, that you told us the work went through. A payment is still evaluated as the action type `payment.create` with the counterparty as its resource, so an agent's caps, windows and allowlists apply across payments and other actions together. Spend on one consumes headroom for the other. ## Test and live An agent is `test` or `live`. Both run the same engine, evaluate the same policies, and return the same shapes, including cosignatures. The difference is that live agents authorize real money, and creating one needs a plan with live mode on it. You can therefore prove the entire integration, including cosignature verification inside your own executor, before anything is at stake. ## Next steps Every rule kind, and the condition language. What a `202` means and how it resolves. The properties this ordering is meant to give you. What the projection mirrors, and what it does not promise. # Verifying an authorization Source: https://docs.kordio.io/agents/cosignatures Check a signed decision offline, without trusting the agent that carries it. A decision stored in our database only binds an executor that chooses to ask us, and asks us every time. Anything already holding the means to act can act without checking, at which point a control layer is a log of advice that may have been ignored. So an allowed decision comes back signed. ## What is inside A **cosignature** is a compact JWS over the agent, budget, action, resource, amount and currency, expiring in minutes: ```json theme={"dark"} { "data": { "id": "9b2ef0c1-...", "state": "pending" }, "decision": { "outcome": "allowed", "rule": null }, "cosignature": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleV8xIn0..." } ``` The agent carries that string to whatever executes the action. The executor verifies it, and if it does not verify, the action does not happen. That is what makes Kordio a required signer without making it a custodian: we never hold your funds and never hold your keys. The JWS is `ES256` over these claims: | Claim | Meaning | | ------------------- | ----------------------------------------------------------------- | | `iss` | Always `kordio` | | `sub` | The agent that was authorized | | `jti` | The intent id, so a signature maps to exactly one decision | | `iat`, `nbf`, `exp` | Issued, not-before, expiry. Default lifetime is five minutes | | `workspace_id` | The workspace the decision belongs to | | `budget_id` | The budget envelope it was committed against | | `intent_id` | Same as `jti`, for readability | | `action_type` | What was authorized, for example `payment.create` | | `resource` | The counterparty or target, when one was given | | `amount_cents` | The amount authorized, in minor units | | `currency` | The currency of that amount | | `policy_version` | Digest of the rules that were in force when the decision was made | | `frame_hash` | SHA-256 over the full request frame, metadata included | For a payment intent, `action_type` is the literal `payment.create` and `resource` falls back to the payment's `counterparty`. ### Pinning the decision `policy_version` and `frame_hash` are what let a receipt outlive the policy that produced it. `policy_version` is a content digest of the resolved policy set: the same rules always produce the same version, any edit produces a different one, and a module imported by a policy counts, so changing a shared module moves the version of every policy that imports it. Two decisions carrying the same `policy_version` were judged by identical rules. Store it next to the receipt and "which limits applied here" has an answer six months later, whatever the policy says by then. `frame_hash` covers more than the claims do. The claims echo the action type, resource and amount; the frame hash is taken over those plus the currency, agent, budget, workspace and the whole `metadata` object. If you sent a purchase order number in `metadata`, the receipt is bound to that number even though no claim repeats it. Recompute the hash from the request you hold and a match proves the receipt is for that request and no other. Both claims are `null` on decisions recorded before your deployment started emitting them. Check the claims, not just the signature. A valid signature for $120 to one vendor is not authority to send $1,200 to another. A verifier that checks `exp` and the signature but not `amount_cents` and `resource` is not doing the job. ## Verify it offline The public keys are published as a standard JWKS: ``` GET https://api.kordio.io/.well-known/jwks.json ``` Cache it and verify locally. No call to Kordio is needed, in any language with a JOSE library. ```typescript TypeScript theme={"dark"} import { createRemoteJWKSet, jwtVerify } from "jose"; const jwks = createRemoteJWKSet( new URL("https://api.kordio.io/.well-known/jwks.json"), ); export async function checkAuthority( cosignature: string, expected: { actionType: string; resource: string; amountCents: number }, ) { const { payload } = await jwtVerify(cosignature, jwks, { issuer: "kordio" }); if (payload.action_type !== expected.actionType) throw new Error("wrong action"); if (payload.resource !== expected.resource) throw new Error("wrong counterparty"); if (payload.amount_cents !== expected.amountCents) throw new Error("wrong amount"); return payload; } ``` ```python Python theme={"dark"} from jwt import PyJWKClient, decode jwks = PyJWKClient("https://api.kordio.io/.well-known/jwks.json") def check_authority(cosignature: str, *, action_type: str, resource: str, amount_cents: int): key = jwks.get_signing_key_from_jwt(cosignature).key payload = decode(cosignature, key, algorithms=["ES256"], issuer="kordio") if payload["action_type"] != action_type: raise ValueError("wrong action") if payload["resource"] != resource: raise ValueError("wrong counterparty") if payload["amount_cents"] != amount_cents: raise ValueError("wrong amount") return payload ``` Offline verification is the important property. It means an authorization stays checkable when Kordio is slow, and past authorizations remain verifiable against the published keys whatever happens to us later. ## Or ask us Local verification cannot tell you whether the authorization has already been spent. A signature proves authority was granted, not that it is unused. The endpoint checks both: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/cosign/verify \ -H "Content-Type: application/json" \ -d '{"authorization": "eyJhbGciOi..."}' ``` The field is `authorization`, and you can send the token as an `Authorization: Bearer ` header instead. The endpoint is unauthenticated either way. ```json 200 OK theme={"dark"} { "data": { "valid": true, "reason": null, "intent_id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "action_type": "payment.create", "resource": "acme-supplies.example", "amount_cents": 12000, "currency": "USD", "expires_at": "2026-08-04T09:17:04Z" } } ``` An invalid cosignature is a `422`, not a `200` with `valid: false` in a success envelope: ```json 422 Unprocessable Entity theme={"dark"} { "data": { "valid": false, "reason": "already_settled" } } ``` | `reason` | Meaning | | ------------------ | -------------------------------------------------------------------------------------- | | `malformed` | Not a parseable JWS. | | `unknown_key` | Signed by a `kid` we do not publish. | | `expired` | Past `exp`. | | `not_yet_valid` | Before `nbf`. | | `wrong_issuer` | `iss` is not `kordio`. | | `bad_signature` | Signature does not verify against the key. | | `unknown_intent` | The `jti` names no intent we hold. | | `already_consumed` | The cosignature was already spent through `/control/v1/cosign/consume`. | | `already_settled` | The intent is no longer `pending` or `requires_approval`, so nothing is left to spend. | | `amount_mismatch` | The claim's amount no longer matches the record. | Use offline verification in the hot path and this endpoint where you need settlement state. It re-loads the intent and requires it to still be `pending` or `requires_approval`, which is the only check that can tell an unused authorization from a spent one. ## Rotation Keys rotate without invalidating authorizations already in flight. Retired keys keep verifying and stop signing, and both appear in the JWKS, so a cosignature issued a minute before a rotation still checks out. If cosigning is not configured on a deployment, the JWKS returns an empty set and decisions come back with **no** `cosignature` field rather than an unverifiable one. Treat a missing key as "not authorized to execute", never as "authorized without a signature". ## Spending it `POST /control/v1/cosign/verify` answers whether authority exists and does not change anything, so a relying party can ask twice without being punished for checking. `POST /control/v1/cosign/consume` spends it. The first call returns the same body as verify; every call after it fails with `already_consumed`, and verify reports `already_consumed` from then on too. Neither endpoint needs a credential, so treat consuming as the act of claiming the authority. Use consume at the moment you act on the decision, not when you receive it. A cosignature is otherwise replayable until the executor reports the action finished, and for a counterparty "valid" means pay. ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/cosign/consume \ -H "Content-Type: application/json" \ -d '{"authorization":"'"$COSIGNATURE"'","consumed_by":"acme-executor"}' ``` `consumed_by` is optional and recorded against the workspace, so a dispute can name who spent it. ## Next steps Signature lifetime, revocation, and what a cosignature does not promise. The verify endpoint and the JWKS document. # Errors Source: https://docs.kordio.io/agents/errors Every code spend control returns, and every rule that can refuse. Kordio Control has two kinds of failure and they are not the same thing. A **refusal** is a policy answer with a full decision in the body. An **error** is a request that could not be evaluated at all. ## A denial is not an error A denied decision answers `403` and carries the whole decision, not just a code: ```json 403 Forbidden theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "state": "denied" }, "decision": { "outcome": "denied", "rule": "per_transaction_cap", "detail": { "limit_cents": 50000, "requested_cents": 120000 }, "headroom": { "session_remaining_cents": 380000, "per_action_cap_cents": 50000 }, "policy_snapshot": [ { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "status": "active", "mode": "blocklist", "imports": [], "per_transaction_cap_cents": 50000, "velocity_cap_cents": null, "velocity_window_seconds": null, "monthly_cap_cents": null, "approval_threshold_cents": null, "counterparty_allowlist": [], "rules": [] } ] } } ``` `headroom` is measured before the reservation, so on an allowed decision it still counts the amount you were just authorized to spend. `policy_snapshot` is the policy as it read at that instant, which is what lets a decision be re-read months later against a rule that has since changed. A `403` from the agent API is a policy answer, not a transport failure. Do not retry it with a fresh idempotency key: that asks the same question again and, for a held action, asks a person twice. Change the action or change the policy. ### Rules that can refuse `decision.rule` names what decided. Rules created through the typed policy columns report under the column's name, not the underlying kind. See [the mapping table](/agents/policies#the-typed-columns-and-the-rule-name-each-produces). | `decision.rule` | Why | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `no_policy` | The agent has no active policy, so nothing is authorized for it yet. | | `session_inactive` | The budget is not `active`. Nothing in the API moves a budget out of `active` today, so in practice a budget that has run out denies with `session_budget` instead. | | `runtime_scope` | The agent key is not scoped for this `action_type`. | | `session_budget` | The action does not fit the remaining budget envelope. | | `per_transaction_cap` | Over the per-action ceiling set by `per_transaction_cap_cents`. | | `velocity_cap` | Over the rolling-window cap set by `velocity_cap_cents`. | | `monthly_cap` | Over the calendar-month cap set by `monthly_cap_cents`. | | `counterparty_allowlist` | The counterparty is not on `counterparty_allowlist`. | | `cost_cap` | Over a `cost_cap` rule written in the `rules` array. | | `spend_window` | Over a `spend_window` rule written in the `rules` array. | | `monthly_spend_cap` | Over a `monthly_spend_cap` rule written in the `rules` array. | | `rate_limit` | Too many actions in the window, regardless of amount. | | `action_allowlist` | This action type is not permitted. | | `resource_allowlist` | This resource is not permitted. | | `not_allowlisted` | An allowlist-mode policy matched no `allow` rule. | | `spend_token_unusable` | The token is not `issued`, or has expired. | | `spend_token_ceiling` | The amount exceeds the token's ceiling. | | `spend_token_counterparty` | The token is pinned to a different counterparty. | A rule written with a custom `rule_name` reports under that name instead. An `approval_threshold` never appears as a denial. It does not refuse; it answers `202` and holds the action. See [holding spend for a person](/agents/approvals). ### What `detail` carries `decision.detail` is keyed by the rule that decided, not by a shared schema. Read it by rule: | Rule | `detail` keys | | ---------------------------------------------- | -------------------------------------------------- | | `no_policy` | `message` | | `session_inactive` | `status` | | `runtime_scope` | `action_type`, `scopes` | | `session_budget` | `remaining_cents`, `requested_cents` | | `cost_cap`, `per_transaction_cap` | `limit_cents`, `requested_cents` | | `spend_window`, `velocity_cap` | `limit_cents`, `window_seconds`, `projected_cents` | | `monthly_spend_cap`, `monthly_cap` | `limit_cents`, `projected_cents` | | `rate_limit` | `limit`, `window_seconds`, `projected` | | `approval_threshold` | `threshold_cents`, `requested_cents` | | `action_allowlist` | `action_type`, `allowed` | | `resource_allowlist`, `counterparty_allowlist` | `resource`, `allowed` | | `not_allowlisted` | `policy_id` | | A `condition` rule | `rule_id`, `matched` | | `spend_token_unusable` | `status` | | `spend_token_ceiling` | `ceiling_cents`, `requested_cents` | | `spend_token_counterparty` | `pinned`, `requested` | The amount ceilings report `limit_cents`, not `max_cents`, and the approval threshold reports `threshold_cents`, not `above_cents`. Those are the names you wrote the rule with, not the names it answers with. An allowed decision has `rule: null` and `detail: {}`. Nothing decided it; nothing refused. ## Error envelope Everything that is not a decision returns: ```json theme={"dark"} { "error": { "message": "Agent is not scoped for tool.invoke", "code": null } } ``` Switch on `code` where it is present. `message` is for humans and may change. `code` is `null` for most validation failures; only the codes below ever set it. Branch on the HTTP status first and treat `code` as a refinement, not as the primary signal. ## Codes ### runtime\_key\_required `401` - No agent key was presented. Send `Authorization: Bearer krt_...`. ### invalid\_runtime\_key `401` - The key was not recognised, or its agent is suspended or revoked. ### identity\_token\_required `401` - No dashboard token was presented on a `/control/v1/workspaces/*` or `/v1/account` call. Agent keys do not reach these routes; send a WorkOS access token. ### invalid\_identity\_token `401` - The dashboard token was rejected: malformed, expired, or signed by something this environment does not trust. ### budget\_ceiling `422` - The budget asked for is larger than the agent's `max_budget_cents`, which is set from the dashboard and cannot be raised with an agent key. The body carries `ceiling_cents` and `requested_cents` so the caller can open a smaller one rather than guess. ### parent\_budget\_exhausted `422` - A child budget was asked for that is larger than the parent has left. Children reserve from their parent when they are opened, so several children cannot sum past it. `ceiling_cents` is what the parent actually has left. ### insufficient\_role `403` - Your membership does not carry the capability this call requires. Approving needs `approve`; writing policy and managing agents need `manage_policy`; members and billing need `manage_members`. ### idempotency\_conflict `409` - A request with this `Idempotency-Key` is still in flight, so there is no stored response to replay yet. Wait and retry with the same key; do not mint a new one. ### idempotency\_key\_required `422` - `POST /control/v1/agent/actions` requires an `Idempotency-Key` **header**. Note the status: this is a `422`, not a `400`. `POST /control/v1/agent/payment_intents` does **not** use that header. It requires an `idempotency_key` field in the body, and its absence is a `400`. The two authorize endpoints are asymmetric here. ### authorization\_required `400` - `POST /control/v1/cosign/verify` was called with no token, in neither the `authorization` body field nor an `Authorization` header. ### rate\_limited `429` - Back off per the `Retry-After` header. Agent endpoints allow 1200 requests per minute per key; workspace endpoints allow 300. ### billing\_unavailable `503` - Billing could not be reached, so a call that had to check entitlement could not be answered. Authorization is unaffected; retry. ### identity\_unavailable `503` - The identity provider could not be reached during sign-in. ### identity\_not\_configured `503` - This deployment has no identity provider configured. ### mfa\_required `401` - Sign-in needs a second factor. The response carries `pending_authentication_token` and `authentication_challenge_id` alongside `error`; complete at `POST /v1/auth/verify_mfa`. ### email\_verification\_required `401` - The account exists but its email is unverified. The response carries `pending_authentication_token`; complete at `POST /v1/auth/verify_email`. ### invalid\_signature `401` - An inbound billing webhook failed HMAC verification. ## Statuses without a code | Status | When | | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | A required body parameter is missing. | | `404` | The budget, intent or workspace does not belong to you. Kordio does not confirm existence across a tenancy boundary, so this is a `404` rather than a `403`. | | `422` | The request was understood but cannot be applied: a rule that would not compile, an import naming an unknown module, an intent resolved from the wrong state, a module still imported by a policy. | | `500` | Unexpected. Retry; if it persists, contact support. | ## Next steps Why the first denial wins, and what fails closed. The rules behind every name in the table above. # What Kordio guarantees Source: https://docs.kordio.io/agents/guarantees The properties spend control holds, and the ones it deliberately does not. Infrastructure is judged on its failure modes, not its definitions, so each entry below is a property followed by the failure it removes, and the limits get the same treatment as the guarantees. ## Decisions fail closed **An agent with no active policy denies everything**, with the rule `no_policy`. The three intrinsic rules do not count as a policy. An agent also arrives with an active starter policy unless you ask for it not to, so the default path never passes through `no_policy` at all. *What this removes:* the window between creating an agent and writing its rules, during which a misconfigured agent would otherwise have unlimited authority. The common failure in policy-engine deployments is a default-allow gap at setup time. There is none here, in either direction: an agent with no rules refuses, and an agent you have not got to yet already has some. ## The first denial wins, and cannot be overridden Rules are evaluated in a fixed order: intrinsic rules, then each active policy oldest first, with imported modules ahead of a policy's own rules. The first denial short-circuits the entire evaluation. *What this removes:* a permissive rule silently re-enabling something a stricter rule refused. An `allow` never overrides a `deny`, and a `require_approval` never converts a denial into a question for a person. Rule order cannot produce a weaker outcome than the strictest rule that matched. ## Scopes are checked before policy An agent key carries an action-type allowlist enforced by an intrinsic rule, so a request outside it is refused as `runtime_scope` before any policy is consulted. *What this removes:* a policy misconfiguration granting an agent authority over action types it was never issued for. Scope is a property of the credential, not of the rules attached to it. ## Reservations are released, not stranded Budget is reserved when an action is authorized or held, and released when it fails, is denied, or its approval is refused. *What this removes:* budget stranded by an action that was refused, failed, or turned down by a person. What it does **not** remove: an intent left `pending` because nobody called `complete` or `fail` holds its reservation for good. A budget has no expiry and no close endpoint, so nothing sweeps that up later. Reporting the outcome is part of the contract. ## Replay returns the original decision, not a new one Each `(agent, idempotency_key)` maps to exactly one intent forever. A replay returns the stored intent **and the stored decision**, at the original HTTP status. *What this removes:* a retry under network failure double-reserving budget, and a retry after a policy change silently getting a different answer than the one already acted on. The decision is the record, not a recomputation. The key is matched on its own, though. Reuse one with a different amount and you get the first decision back, not an error, so the key has to be as specific as the action it stands for. ## Concurrent spend contends without queueing A budget is claimed with a single conditional update rather than a lock. *What this removes:* both the race where parallel sub-agents each read sufficient budget and both succeed, and the serialization bottleneck that a lock would impose on a fan-out. Exactly one claimant wins each contested update. The same applies to spend tokens: if two payments cite one token at once, exactly one consumes it, and the loser releases its reservation and fails with `spend_token_unusable`. ## Every decision is recorded, including refusals A denied action still writes an intent, in state `denied`, alongside an audit event. The audit log is append-only and rejects deletion at the model layer. *What this removes:* "we don't know what it tried to do." A refusal that leaves no trace is a refusal you cannot audit, and the interesting question after an incident is usually what the agent attempted, not what it completed. Every role can read the audit trail, including `member`. ## The ledger is never in the authorization path Where a workspace has the ledger enabled, reservations are mirrored into it asynchronously. *What this removes:* a slow, unavailable, or absent ledger delaying or changing a decision. A projection can lag; it can never gate. Authorization behaves identically on a workspace with no ledger at all. The gap is observable as `unprojected_cents` on the workspace funds endpoint. ## Revocation is not retroactive Suspending or revoking an agent stops new authorizations. It does **not** rewrite decisions already made, and it does **not** invalidate a cosignature already issued. *What this removes:* nothing. This is a limit, stated so you can size it. A cosignature's default lifetime is five minutes, so revoking a compromised agent leaves at most that window in which an already-issued signature still verifies offline. If that window matters to you, verify through `POST /control/v1/cosign/verify` rather than locally: it re-checks the intent's state and will report `already_settled` for anything spent. ## Test and live never mix Every credential is bound to one mode. Keys are prefixed `krt_test_` or `krt_live_`, and a test key cannot reach live data. *What this removes:* a load test or a demo consuming real budget or producing real payments. ## What Kordio does not guarantee A control layer that overclaims is worse than one that does not exist, so here is what this one will not do for you. ### It cannot govern a path that does not ask Kordio holds no funds, no accounts, and none of your credentials. An executor that never calls us and never verifies a cosignature is not governed by us, no matter what your policy says. The control layer binds the paths you route through it, and the completeness of that routing is your responsibility, not ours. ### It has no opinion on what you do when we are unreachable If the authorize call times out, nothing on our side decides what happens next. Your code does. Fail closed: treat a transport failure as a refusal and do not execute. That is the only choice consistent with having a control layer at all. An agent that spends whenever Kordio is unreachable has a control layer exactly as long as the network is up. Retry with the **same** idempotency key, which is safe by construction: if the original request did land, you get the original decision back rather than a second reservation. ### A cosignature proves authority was granted, not that it is unused Offline verification checks the signature, the claims, and the expiry. It cannot see settlement state. If double-execution is a risk in your architecture, verify through the endpoint, which re-loads the intent and refuses anything already settled. ### Simulation is not free of side effects `POST /control/v1/agent/actions/simulate` creates no intent and reserves no budget, but it does write an `action.simulated` audit event. Policy previews on the dashboard side write nothing at all, so use those if you need a genuinely silent evaluation. ## Next steps The evaluation order these properties come from. What the projection promises, and what it does not. # Require a person above a threshold Source: https://docs.kordio.io/agents/guides/approval-threshold Hold spend over a limit, and let the agent wait instead of failing. The useful thing about an approval is that it is not a refusal. The action does not fail, the agent does not retry, and the budget it asked for is held for it while a person decides. Getting that right is mostly about what your agent does with a `202`. ## Before you start ```bash Identifiers theme={"dark"} export KORDIO_AGENT_ID="7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2" export KORDIO_BUDGET_ID="3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83" ``` The amounts here assume the agent's starter policy is disabled, as the [quickstart](/agents/quickstart) does in step 2. Leave it on and it holds anything over \$100 for a person before your own rules get a say. ## 1. Set the threshold `approval_threshold_cents` is the shorthand. It compiles to an `approval_threshold` rule and reports as one: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"approval_threshold_cents\": 20000, \"velocity_cap_cents\": 200000, \"velocity_window_seconds\": 3600 }" ``` ```json 201 Created theme={"dark"} { "data": { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "status": "active", "mode": "blocklist", "approval_threshold_cents": 20000, "velocity_cap_cents": 200000, "velocity_window_seconds": 3600, "rules": [], "created_at": "2026-08-22T13:02:55Z" } } ``` To hold on something other than an amount, write a `condition` rule with `"effect": "require_approval"` instead. [Passing facts from your own service](/agents/guides/metadata-facts) holds a payment on how new the buyer is, and reaches the same `202`. ## 2. Your agent gets a 202 ```bash theme={"dark"} ACTION=$(curl -s -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-9120-attempt-1" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"resource\": \"acme-supplies.example\", \"cost_cents\": 24000 }") export KORDIO_ACTION_ID=$(echo "$ACTION" | jq -r '.data.id') ``` ```json 202 Accepted theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "action_type": "payment.create", "resource": "acme-supplies.example", "cost_cents": 24000, "currency": "USD", "state": "requires_approval" }, "decision": { "outcome": "requires_approval", "rule": "approval_threshold", "detail": { "above_cents": 20000 }, "headroom": { "session_remaining_cents": 50000 } } } ``` There is no `cosignature`, because nothing is authorized yet. The 24000 is already reserved against the budget, so the next action in the same run cannot quietly spend it while this one waits. ## 3. Wait, do not retry A `202` is not a transient failure. Retrying it under a fresh `Idempotency-Key` creates a second held intent, reserves the budget twice, and asks a person the same question twice. Reuse the same `Idempotency-Key` if you must retry the call itself. Kordio replays the original decision rather than holding the spend again. In production, subscribe to `action.requires_approval` and `approval.resolved` and let the [webhook](/agents/webhooks) wake the run back up. In a script, read the intent back: ```bash theme={"dark"} curl -s https://api.kordio.io/control/v1/agent/actions/$KORDIO_ACTION_ID \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" ``` ```json 200 OK theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "cost_cents": 24000, "state": "requires_approval", "resolved_by_sub": null, "resolved_at": null } } ``` ## 4. What the approver sees An approver looking at "approve \$240?" is rubber-stamping. One call answers what approving would actually do, and it is the same shape for a payment intent: ```bash theme={"dark"} curl -s "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents/$KORDIO_ACTION_ID/impact" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": { "amount_cents": 24000, "currency": "USD", "rule": "approval_threshold", "executed": false, "session": { "id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "budget_cents": 50000, "spent_cents": 24000, "remaining_cents": 26000, "returns_on_deny_cents": 24000, "open_holds": 1 }, "runtime": { "id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "name": "procurement agent", "mode": "test", "scopes": ["payment.*", "tool.invoke"] }, "windows": [ { "kind": "velocity", "window_seconds": 3600, "cap_cents": 200000, "spent_cents": 24000, "remaining_cents": 176000 } ], "spend_token": null } } ``` `session` is the budget and `runtime` is the agent, in the wire names the API has always used. Two numbers carry most of the decision: `returns_on_deny_cents` is what denying gives back, and `open_holds` counts every other intent competing for the same budget, which is how an approver notices that three pending approvals total more than the budget can cover. The console shows the same facts on the Approvals page, where the queue can be narrowed to live or test agents. ## 5. Resolve it ```bash theme={"dark"} curl -s -X POST \ "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents/$KORDIO_ACTION_ID/approve" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "cost_cents": 24000, "state": "pending", "resolved_by_sub": "user_01J8XQ2M4K7T", "resolved_at": "2026-08-22T13:19:40Z" } } ``` The intent is now `pending`, exactly as if it had come back `201`, and `approval.resolved` fires. Your agent executes and reports the outcome with `complete` or `fail`, and the reservation is only released when it does. Denying instead moves the intent to `denied` and returns the reservation: ```bash theme={"dark"} curl -s -X POST \ "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents/$KORDIO_ACTION_ID/deny" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"reason": "duplicate of order 9119"}' ``` ```json 200 OK theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "state": "denied", "failure_reason": "duplicate of order 9119", "resolved_by_sub": "user_01J8XQ2M4K7T", "resolved_at": "2026-08-22T13:21:02Z" } } ``` Resolving an intent that is not in `requires_approval` is a `422`, so a double click cannot double execute. ## What approvals do not do Approving is a capability, not a queue with routing. Owners and admins hold `approve`; members hold `read` only. Say this out loud to whoever runs the process, because the product does not enforce any of it for you: * Kordio does not route a hold to a named person, a group, or an on-call rota. Anyone with `approve` in the workspace can resolve any hold in it. * There is no quorum. One approval resolves the intent, and `resolved_by_sub` records who. * There is no escalation and no expiry. A hold waits until somebody answers it, and its reservation waits with it. * An approved intent carries no cosignature. Cosignatures are issued on the authorize call and only for an `allowed` decision, so an executor that gates on one should read the intent state for this path instead. ## Next steps Prove the threshold on a test agent before it holds real money. Wake the run on `approval.resolved` instead of polling. The reference for states, capabilities, and the payment path. Why `approval.resolved` is not itself permission. # Pass facts from your own service Source: https://docs.kordio.io/agents/guides/metadata-facts Compute a fact your side, send it in metadata, compare it in a rule. Most rules people ask for sound like missing features and are actually one missing fact. "Hold any payment to a buyer whose account is less than 30 days old" reads like it needs a buyer model, a join, and a release. It needs a number, computed by the service that already knows it, sent on the request. ## Before you start ```bash Identifiers theme={"dark"} export KORDIO_AGENT_ID="7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2" export KORDIO_BUDGET_ID="3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83" ``` The amounts here assume the agent's starter policy is disabled, as the [quickstart](/agents/quickstart) does in step 2. Leave it on and it holds anything over \$100 for a person before your own rules get a say. ## What a rule can read A decision is a pure function of the request. Kordio never calls out to your service while it decides, so a rule reads seven facts Kordio holds (`action_type`, `resource`, `cost_cents`, `currency`, `agent_id`, `agent_mode`, `budget_id`) and any `metadata.*` dot path you attached. `metadata` is the extension point. Anything your side can work out before it asks for authorization, a rule can decide on. | The fact | Who holds it | How the rule gets it | | -------------------------------------------------- | ------------ | ---------------------------------- | | Amount, counterparty, agent, budget | Kordio | Read the field directly. | | Buyer account age, order total, seat count, region | You | Compute it, send it in `metadata`. | ## 1. Send the fact you already have Your service knows when the buyer signed up. Turn that into a number before the call: ```typescript TypeScript theme={"dark"} const accountAgeDays = Math.floor( (Date.now() - buyer.createdAt.getTime()) / 86_400_000, ); const res = await fetch("https://api.kordio.io/control/v1/agent/payment_intents", { method: "POST", headers: { Authorization: `Bearer ${process.env.KORDIO_AGENT_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ budget_id: process.env.KORDIO_BUDGET_ID, amount_cents: 18_000, counterparty: "acme-supplies.example", idempotency_key: "order-8812-attempt-1", metadata: { order_id: "8812", account_age_days: accountAgeDays }, }), }); ``` ```json 201 Created theme={"dark"} { "data": { "id": "6f0a3d51-9c27-4b18-8e34-2a5d7b0c9e46", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "amount_cents": 18000, "currency": "USD", "counterparty": "acme-supplies.example", "state": "pending", "idempotency_key": "order-8812-attempt-1" }, "decision": { "outcome": "allowed", "rule": null, "detail": {}, "headroom": { "session_remaining_cents": 50000 } }, "cosignature": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleV8xIn0..." } ``` Nothing reads `account_age_days` yet. The fact is on the request and no rule mentions it. ## 2. Compare it in one predicate Now the feature request becomes a rule. Hold a payment when the buyer is new, and hold it just as firmly when nobody said how old the buyer is: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"rules\": [ { \"kind\": \"condition\", \"effect\": \"require_approval\", \"rule_name\": \"new_buyer_needs_a_person\", \"action_types\": [\"payment.create\"], \"when\": { \"field\": \"metadata.account_age_days\", \"operator\": \"lt\", \"value\": 30 } }, { \"kind\": \"condition\", \"effect\": \"require_approval\", \"rule_name\": \"unknown_buyer_needs_a_person\", \"action_types\": [\"payment.create\"], \"when\": { \"field\": \"metadata.account_age_days\", \"operator\": \"exists\", \"value\": false } } ] }" ``` ```json 201 Created theme={"dark"} { "data": { "id": "d93b6a04-2f71-4c85-9b13-8e0d5a7c26f9", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "status": "active", "mode": "blocklist", "rules": [ { "rule_name": "new_buyer_needs_a_person", "id": "4c1e8f60-7a29-4d03-b5e8-9f2a1c740db6" }, { "rule_name": "unknown_buyer_needs_a_person", "id": "e70b5c39-1d84-4f26-a903-6b8e2d5f4107" } ], "created_at": "2026-08-22T11:20:07Z" } } ``` The same payment, from a buyer who signed up twelve days ago, now waits for a person: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/payment_intents \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"amount_cents\": 18000, \"counterparty\": \"acme-supplies.example\", \"idempotency_key\": \"order-8813-attempt-1\", \"metadata\": { \"order_id\": \"8813\", \"account_age_days\": 12 } }" ``` ```json 202 Accepted theme={"dark"} { "data": { "id": "8d5c2e70-4b91-4a36-9c07-1f6a3d80b524", "amount_cents": 18000, "counterparty": "acme-supplies.example", "state": "requires_approval", "idempotency_key": "order-8813-attempt-1" }, "decision": { "outcome": "requires_approval", "rule": "new_buyer_needs_a_person", "detail": { "rule_id": "4c1e8f60-7a29-4d03-b5e8-9f2a1c740db6", "matched": { "field": "metadata.account_age_days", "operator": "lt", "value": 30 } }, "headroom": { "session_remaining_cents": 32000 } } } ``` ## What to watch when you send facts **A missing fact never raises.** It resolves to nil and the predicate is false, so the rule quietly does not fire. That is why the second rule above exists: `exists` is the only operator that tells "absent" apart from "false". **Ordered comparisons are numeric.** `gt`, `gte`, `lt` and `lte` accept a number or a string that parses as one, so `29` and `"29"` both work. Anything else compares as `false` rather than erroring, which means a typo in a path fails silently. **Dot paths go as deep as your object.** `metadata.buyer.account_age_days` reads a nested object, so you can send the shape your service already produces. **Facts can be compared to each other.** A predicate can take a `value_field` instead of a `value` and compare two things on the same request, which is how a refund gets capped at the order it belongs to. See [stop an agent over-refunding](/agents/guides/refund-ceiling). Send only what a rule needs to read. `metadata` is stored on the action intent, returned by the API, and visible to anyone with `read` on the workspace, so it is the wrong place for card numbers, tokens, or anything you would not put in an audit log. ## Metadata decides, decision\_context records On `POST /control/v1/agent/payment_intents` the two fields look interchangeable and are not. `decision_context` is provenance: it is stored on the payment intent and never evaluated. `metadata` is evaluated and, on the payment path, not stored. | | Read by rules | Stored on the intent | | --------------------------------------------------------- | ------------- | -------------------- | | `metadata` on `/control/v1/agent/actions` | Yes | Yes | | `metadata` on `/control/v1/agent/payment_intents` | Yes | No | | `decision_context` on `/control/v1/agent/payment_intents` | No | Yes | So a payment whose approval hinged on `account_age_days` should carry the number in both: `metadata` so the rule can hold it, `decision_context` so the record says why. ## Next steps What happens to the payment this rule just held. Compare one field on the request to another. Every operator, and what each one does to a missing field. Why the first denial wins, and where approvals sit in the order. # Roll a policy out safely Source: https://docs.kordio.io/agents/guides/policy-rollout Preview a draft, prove it on a test agent, then turn it on live. A policy is the thing standing between an agent and your money, so the expensive mistakes are both directions: a rule that refuses work you meant to allow, and a rule that allows work you meant to refuse. Three steps separate writing a rule from letting it decide anything real. ## Before you start ```bash Identifiers theme={"dark"} export KORDIO_TEST_AGENT_ID="7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2" export KORDIO_LIVE_AGENT_ID="b4e91f27-08c5-4d63-a71e-5f3b2c8d09a4" export KORDIO_BUDGET_ID="3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83" ``` `KORDIO_AGENT_KEY` is the test agent's key. A policy belongs to one agent, so the two agent ids matter: rolling out means writing the rules against the live agent once they behave. The amounts here assume the agent's starter policy is disabled, as the [quickstart](/agents/quickstart) does in step 2. Leave it on and it holds anything over \$100 for a person before your own rules get a say. ## 1. Preview the draft against nothing `policy_previews` evaluates a policy you have not saved, on a request that never happened: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policy_previews \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_TEST_AGENT_ID\", \"action_type\": \"payment.create\", \"resource\": \"acme-supplies.example\", \"cost_cents\": 24000, \"metadata\": { \"account_age_days\": 12 }, \"policy\": { \"per_transaction_cap_cents\": 50000, \"rules\": [ { \"kind\": \"condition\", \"effect\": \"require_approval\", \"rule_name\": \"new_buyer_needs_a_person\", \"action_types\": [\"payment.create\"], \"when\": { \"field\": \"metadata.account_age_days\", \"operator\": \"lt\", \"value\": 30 } } ] } }" ``` ```json 200 OK theme={"dark"} { "data": { "outcome": "requires_approval", "rule": "new_buyer_needs_a_person", "detail": { "rule_id": "0b6d9a41-5e28-4c17-83f9-2d4a7b0e6c53", "matched": { "field": "metadata.account_age_days", "operator": "lt", "value": 30 } }, "headroom": { "session_remaining_cents": 100000 } } } ``` No policy, no intent, no reservation, no audit event. The `rule_id` is minted for that one evaluation and thrown away, so it will not match the id the rule gets when you save it. `imports` resolve against the modules the workspace really has, so a draft that builds on a saved module previews honestly. `session_budget_cents` sets the synthetic budget and defaults to `100000`. Previewing needs only the `read` capability, deliberately, because it changes nothing. Two things preview will not tell you. It evaluates the draft alone, so it says nothing about how the draft interacts with the agent's other active policies, and window rules read the agent's real recent usage rather than a clean slate. ## 2. Let a test agent run into it Save the draft against the test-mode agent: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_TEST_AGENT_ID\", \"per_transaction_cap_cents\": 50000, \"rules\": [ { \"kind\": \"condition\", \"effect\": \"require_approval\", \"rule_name\": \"new_buyer_needs_a_person\", \"action_types\": [\"payment.create\"], \"when\": { \"field\": \"metadata.account_age_days\", \"operator\": \"lt\", \"value\": 30 } } ] }" ``` ```json 201 Created theme={"dark"} { "data": { "id": "f28c0b95-4a71-4e30-96d2-7c1b5a8e0f36", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "status": "active", "mode": "blocklist", "per_transaction_cap_cents": 50000, "rules": [ { "rule_name": "new_buyer_needs_a_person", "id": "4c1e8f60-7a29-4d03-b5e8-9f2a1c740db6" } ], "created_at": "2026-08-22T14:41:09Z" } } ``` A test agent runs the same engine, the same rules, and the same shapes as a live one. Replay yesterday's real requests through it, either as real authorizations or through `simulate`, which records an `action.simulated` audit event and reserves nothing: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/actions/simulate \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"cost_cents\": 24000, \"metadata\": { \"account_age_days\": 12 } }" ``` ```json 200 OK theme={"dark"} { "data": { "outcome": "requires_approval", "rule": "new_buyer_needs_a_person", "detail": { "rule_id": "4c1e8f60-7a29-4d03-b5e8-9f2a1c740db6", "matched": { "field": "metadata.account_age_days", "operator": "lt", "value": 30 } }, "headroom": { "session_remaining_cents": 50000 } } } ``` Unlike preview, this runs every active policy on the agent, which is the number you actually care about before promoting anything. ## 3. Read what it held, test agents only Held intents can be narrowed to one agent mode, so a live queue is not polluted by a rehearsal: ```bash theme={"dark"} curl -s "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/action_intents?agent_mode=test&state=requires_approval" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": [ { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "action_type": "payment.create", "cost_cents": 24000, "state": "requires_approval", "metadata": { "account_age_days": 12 } } ], "has_more": false, "next_cursor": null } ``` The console does the same thing on the Approvals page, where the queue filters to all agents, live agents, or test agents. `agent_mode` accepts `live` or `test`, and anything else is a `400` rather than a silent full listing, because answering a narrowed question about held money with every intent in the workspace is the wrong way to be wrong. The same filter works on `payment_intents`. ## 4. Promote it to the live agent Write the proven rules against the live agent. Create it turned off, check it reads the way you expect, then flip it: ```bash theme={"dark"} POLICY=$(curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_LIVE_AGENT_ID\", \"status\": \"disabled\", \"per_transaction_cap_cents\": 50000, \"rules\": [ { \"kind\": \"condition\", \"effect\": \"require_approval\", \"rule_name\": \"new_buyer_needs_a_person\", \"action_types\": [\"payment.create\"], \"when\": { \"field\": \"metadata.account_age_days\", \"operator\": \"lt\", \"value\": 30 } } ] }") export KORDIO_POLICY_ID=$(echo "$POLICY" | jq -r '.data.id') ``` ```json 201 Created theme={"dark"} { "data": { "id": "31d70e6a-8c45-4b29-9f07-2e6a4d13b805", "agent_id": "b4e91f27-08c5-4d63-a71e-5f3b2c8d09a4", "status": "disabled", "mode": "blocklist", "per_transaction_cap_cents": 50000, "rules": [ { "rule_name": "new_buyer_needs_a_person", "id": "9e3c5b18-6f04-4a72-b81d-0c7e2a94f56b" } ], "created_at": "2026-08-22T15:06:12Z" } } ``` A `disabled` policy is still validated when you save it, and is left out of evaluation entirely. Turn it on when the diff reads right: ```bash theme={"dark"} curl -s -X PATCH https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies/$KORDIO_POLICY_ID \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"status": "active"}' ``` ```json 200 OK theme={"dark"} { "data": { "id": "31d70e6a-8c45-4b29-9f07-2e6a4d13b805", "agent_id": "b4e91f27-08c5-4d63-a71e-5f3b2c8d09a4", "status": "active", "per_transaction_cap_cents": 50000, "updated_at": "2026-08-22T15:07:33Z" } } ``` Disabling is not a safe rollback for an agent's only policy. An agent with no active policy denies everything with the rule `no_policy`, so turning the last one off stops the agent rather than opening it up. Roll back by editing the rule, or by activating the policy you are replacing before disabling this one. Both agents now carry the same rules twice. A [policy module](/agents/policies#reusable-modules) removes the duplication, at a price worth knowing: editing a module changes every policy that imports it, so a module shared by the test and live agents reaches live the moment you save it. Share the module once the rule is settled, not while you are still tuning it. ## Next steps The other half of a safe first run. Resolve the holds this rollout produced. The rule kinds, modules, and the preview endpoint in full. Evaluation order, and why the first denial wins. # Stop an agent over-refunding Source: https://docs.kordio.io/agents/guides/refund-ceiling Cap a refund at the order it belongs to, with one condition rule. A refund agent rarely fails by refunding one enormous amount. It fails by refunding $90 against a $40 order, quietly, on an order it misread, because the ceiling it was given was a number and the order total is a different number on every request. ## Before you start The agent and budget below come from the [quickstart](/agents/quickstart). Export the two ids it printed, and scope the agent for `refund.create` so its key may ask about refunds at all: ```bash Identifiers theme={"dark"} export KORDIO_AGENT_ID="7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2" export KORDIO_BUDGET_ID="3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83" ``` ## Why a cap cannot express this `per_transaction_cap_cents` and `cost_cap` compare `cost_cents` to a number you wrote when you saved the policy. That number cannot be "whatever this order was worth", so the tightest cap you can write is the largest order you ever expect, which is far too loose for the smallest one. A condition predicate can compare a field to another field on the same request instead of to a literal, using `value_field`: ```json theme={"dark"} { "field": "cost_cents", "operator": "gt", "value_field": "metadata.order_total_cents" } ``` Both sides resolve the same way, so `value_field` accepts exactly the names the left side accepts: `action_type`, `resource`, `cost_cents`, `currency`, `agent_id`, `agent_mode`, `budget_id`, or any `metadata.*` dot path. The [condition language](/agents/policies#the-condition-language) covers the rest of the grammar. ## 1. Write the ceiling ```bash theme={"dark"} POLICY=$(curl -s -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"rules\": [ { \"kind\": \"condition\", \"effect\": \"deny\", \"rule_name\": \"refund_exceeds_order\", \"action_types\": [\"refund.create\"], \"when\": { \"field\": \"cost_cents\", \"operator\": \"gt\", \"value_field\": \"metadata.order_total_cents\" } } ] }") export KORDIO_POLICY_ID=$(echo "$POLICY" | jq -r '.data.id') ``` ```json 201 Created theme={"dark"} { "data": { "id": "c41d7b28-9e05-4a63-b7f1-6d2c8e30a915", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "status": "active", "mode": "blocklist", "imports": [], "rules": [ { "kind": "condition", "effect": "deny", "rule_name": "refund_exceeds_order", "action_types": ["refund.create"], "when": { "field": "cost_cents", "operator": "gt", "value_field": "metadata.order_total_cents" }, "id": "b8e4f072-3c19-4d5a-8e26-0f7a91c4b3d8" } ], "per_transaction_cap_cents": null, "counterparty_allowlist": [], "created_at": "2026-08-22T10:04:18Z", "updated_at": "2026-08-22T10:04:18Z" } } ``` `action_types` is an exact list, not a prefix. To cover a family of refund types, drop it and match `action_type` with `starts_with` inside the expression instead. ## 2. Refuse a refund that arrives without an order total A field that is not on the request resolves to nil, and nil does not compare. It does not fall back to zero. So a refund that omits `metadata.order_total_cents` makes the predicate false, the rule does not fire, and the refund goes through. A `value_field` rule is silent when the fact is missing, which is the direction that costs you money. Pair it with an `exists` test whenever the fact is mandatory. Add the guard by sending the full `rules` array back. An update replaces the array rather than merging into it, and each rule keeps its `id` only if you send the `id` back with it: ```bash theme={"dark"} curl -X PATCH https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies/$KORDIO_POLICY_ID \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "rules": [ { "id": "b8e4f072-3c19-4d5a-8e26-0f7a91c4b3d8", "kind": "condition", "effect": "deny", "rule_name": "refund_exceeds_order", "action_types": ["refund.create"], "when": { "field": "cost_cents", "operator": "gt", "value_field": "metadata.order_total_cents" } }, { "kind": "condition", "effect": "deny", "rule_name": "refund_missing_order_total", "action_types": ["refund.create"], "when": { "field": "metadata.order_total_cents", "operator": "exists", "value": false } } ] }' ``` ```json 200 OK theme={"dark"} { "data": { "id": "c41d7b28-9e05-4a63-b7f1-6d2c8e30a915", "status": "active", "rules": [ { "rule_name": "refund_exceeds_order", "id": "b8e4f072-3c19-4d5a-8e26-0f7a91c4b3d8" }, { "rule_name": "refund_missing_order_total", "id": "1a7c5d93-8b04-4e21-9f6d-3c0b8a52e7f1" } ], "updated_at": "2026-08-22T10:06:41Z" } } ``` A rule you resend without its `id` is assigned a fresh one, and a decision recorded last week then names a rule id that no longer exists in the policy. Keep the ids. ## 3. Send the order total with the refund The agent asks before it refunds, and carries the order total it is refunding against: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: refund-4471-attempt-1" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"refund.create\", \"resource\": \"order-4471\", \"cost_cents\": 2500, \"metadata\": { \"order_id\": \"4471\", \"order_total_cents\": 4000 } }" ``` ```json 201 Created theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "action_type": "refund.create", "resource": "order-4471", "cost_cents": 2500, "currency": "USD", "state": "pending", "metadata": { "order_id": "4471", "order_total_cents": 4000 }, "trace_id": "5e8c1a47-2b93-4d06-a7f1-9c3e05b8d24a" }, "decision": { "outcome": "allowed", "rule": null, "detail": {}, "headroom": { "session_remaining_cents": 38000 } }, "cosignature": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleV8xIn0..." } ``` A refund is money leaving, so it reserves budget like any other spend. Report it with `complete` or `fail` once your rail has answered. ## 4. Watch it refuse Same order, an amount above what the order was worth: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: refund-4471-attempt-2" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"refund.create\", \"resource\": \"order-4471\", \"cost_cents\": 9000, \"metadata\": { \"order_id\": \"4471\", \"order_total_cents\": 4000 } }" ``` ```json 403 Forbidden theme={"dark"} { "data": { "id": "2c7f4b81-0d63-4a19-8e05-1b9c6f3a7d24", "action_type": "refund.create", "cost_cents": 9000, "state": "denied", "metadata": { "order_id": "4471", "order_total_cents": 4000 } }, "decision": { "outcome": "denied", "rule": "refund_exceeds_order", "detail": { "rule_id": "b8e4f072-3c19-4d5a-8e26-0f7a91c4b3d8", "matched": { "field": "cost_cents", "operator": "gt", "value_field": "metadata.order_total_cents" } }, "headroom": { "session_remaining_cents": 35500 } } } ``` `detail.matched` is the predicate that fired, echoed back with the `value_field` intact, so the record of the denial says which two numbers were compared rather than just naming a rule. ## What write time catches Both mistakes are refused when you save the policy, not when an agent is waiting on an answer: | You wrote | You get | | ------------------------------ | ------------------------------------------------------------------- | | `"value_field": "order_total"` | `422`, `Unknown field "order_total"` | | both `value` and `value_field` | `422`, `Expression compares to a value and a value_field, pick one` | ```json 422 Unprocessable Entity theme={"dark"} { "error": { "message": "Validation failed: Rules Expression compares to a value and a value_field, pick one", "code": null } } ``` Book refunds on `/control/v1/agent/actions`. The payment endpoint always evaluates as `payment.create`, whatever you send it, so it cannot carry a `refund.create` action type. ## Next steps Where `metadata.order_total_cents` comes from, and what else belongs there. Preview this rule before it ever decides anything real. Every rule kind, operator, and combinator. Every rule that can appear in `decision.rule`. # Give an agent a budget for one run Source: https://docs.kordio.io/agents/guides/session-budget Open a budget, spend against it, and stop a loop at the envelope. A per-transaction cap stops one big mistake. It does nothing about the same reasonable-looking \$340 charge happening nineteen times, which is the failure agents actually have. A budget is the control that answers that one, and it is the first thing to reach for on any run. ## Before you start The amounts here assume the agent's starter policy is disabled, as the [quickstart](/agents/quickstart) does in step 2. Leave it on and it holds anything over \$100 for a person before your own rules get a say. ## 1. Open one for the run An agent opens its own budget with its own key. Open it where the run starts, not where the process starts: ```bash theme={"dark"} BUDGET=$(curl -s -X POST https://api.kordio.io/control/v1/agent/budgets \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d '{"budget_cents": 50000, "currency": "USD"}') export KORDIO_BUDGET_ID=$(echo "$BUDGET" | jq -r '.data.id') ``` ```json 201 Created theme={"dark"} { "data": { "id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "parent_budget_id": null, "budget_cents": 50000, "spent_cents": 0, "remaining_cents": 50000, "currency": "USD", "status": "active", "created_at": "2026-08-22T09:11:52Z" } } ``` How large a budget an agent may open is capped by the agent's `max_budget_cents`, which is set from the console and cannot be raised with an agent key. Ask for more and the call is refused before anything exists: ```json 422 Unprocessable Entity theme={"dark"} { "error": { "message": "This agent may not open a budget above $1000.00", "code": "budget_ceiling" }, "ceiling_cents": 100000, "requested_cents": 250000 } ``` ## 2. Spend against it Every authorization names the budget, and an allowed one reserves from it immediately: ```bash theme={"dark"} ACTION=$(curl -s -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-4471-attempt-1" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"resource\": \"acme-supplies.example\", \"cost_cents\": 12000 }") export KORDIO_ACTION_ID=$(echo "$ACTION" | jq -r '.data.id') ``` ```json 201 Created theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "cost_cents": 12000, "state": "pending" }, "decision": { "outcome": "allowed", "rule": null, "detail": {}, "headroom": { "session_remaining_cents": 50000 } }, "cosignature": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleV8xIn0..." } ``` The reservation is held until you report what happened. `complete` keeps it, `fail` gives it back: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/actions/$KORDIO_ACTION_ID/fail \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d '{"reason": "vendor returned 502"}' ``` ```json 200 OK theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "cost_cents": 12000, "state": "failed", "failure_reason": "vendor returned 502" } } ``` Nothing sweeps a reservation that was never reported. An agent that dies between the `201` and the `complete` leaves its budget held for good, so open a budget per run and let it end with the run rather than reusing one across runs. ## 3. Watch the loop hit the wall A budget refuses on the total, not on the individual amount, and it refuses before any rule you wrote gets a say. The nineteenth reasonable charge is the one that stops: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-4489-attempt-1" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"resource\": \"acme-supplies.example\", \"cost_cents\": 12000 }" ``` ```json 403 Forbidden theme={"dark"} { "data": { "id": "2c7f4b81-0d63-4a19-8e05-1b9c6f3a7d24", "cost_cents": 12000, "state": "denied" }, "decision": { "outcome": "denied", "rule": "session_budget", "detail": { "remaining_cents": 2000, "requested_cents": 12000 }, "headroom": { "session_remaining_cents": 2000 } } } ``` `session_budget` is one of three intrinsic rules that run ahead of every policy and cannot be switched off. Give `headroom` to your agent: one that knows it has \$20 left picks a cheaper option, and one that only knows it was refused retries into the same wall. Subscribe to `budget.low` to hear about it early. It fires when a budget drops to 10% or less of its size, after an executed payment. ## 4. Split it between sub-agents A budget can open a child budget, and the child reserves its whole size from the parent when it opens. Children therefore cannot sum past what the parent has left: ```bash theme={"dark"} curl -s -X POST https://api.kordio.io/control/v1/agent/budgets \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{\"budget_cents\": 20000, \"parent_budget_id\": \"$KORDIO_BUDGET_ID\"}" ``` ```json 201 Created theme={"dark"} { "data": { "id": "c6a83f10-27d9-4b54-8e1f-0a95d3c72b68", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "parent_budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "budget_cents": 20000, "spent_cents": 0, "remaining_cents": 20000, "currency": "USD", "status": "active", "created_at": "2026-08-22T09:14:20Z" } } ``` Hand the child id to the sub-agent and it can spend $200 of the parent's $500, whatever it is told to do. A child that asks for more than the parent has left is refused with `parent_budget_exhausted`, again before anything exists. ## What a budget is not * It is not a time limit. A budget has no expiry and no close endpoint, so it stops spend by running out, not by ending. Size it for one run. * It is not per counterparty or per action type. Narrow those with a policy rule; the budget counts every authorized action the run makes. * It is not shared between agents. A budget belongs to the agent that opened it, and a child budget must belong to the same agent as its parent. * It is not money. Kordio holds no funds. A budget is authority to spend on your own rails, and spend on actions and payments draws down the same number. ## Next steps Add rules to the run once the envelope is in place. Narrow one payment inside the budget to one vendor, once. Where the budget sits in the evaluation order. `budget_ceiling`, `parent_budget_exhausted`, and the rest. # Kordio Control Source: https://docs.kordio.io/agents/index Decide what an agent may do before it does it, and sign the answer. Kordio Control answers one question, the same way for a payment, a paid tool call, or anything else an agent asks for: **may this agent take this action, right now?** The answer comes back in the same request, naming the rule that decided, and an allowed answer comes back signed. This is Kordio Control, and it is in early access. Gate your first action in test mode, in about five minutes. Evaluation order, states, outcomes, and headroom. ## The vocabulary These are the words in the wire format, not a conceptual model laid over it, so they are worth learning exactly. ### Agent A scoped identity for one agent workload. Holds a hashed `krt_` API key, a mode (`test` or `live`), and a list of action types the key may even ask about. Use one per workload, so you can revoke one without stopping the rest. ### Budget An envelope for one run. Spend is committed against it, and it is the unit that stops a loop rather than a single mistake. How large a budget an agent may open is capped by the agent's `max_budget_cents`, which is set from the dashboard and cannot be raised with an agent key. Budgets delegate to child budgets, and a child reserves from its parent when it opens, so children cannot sum past what the parent has left. A budget has no expiry and no close endpoint; it ends by running out. ### Policy The rules attached to an agent. Caps, windows, rate limits, allowlists, approval thresholds, and a condition language for everything they do not cover. The rule kinds are a closed set; `condition` is the extension point. Policy is data, not code, so it validates when you write it, not when an agent is waiting. ### Action One request for authorization, and the record it leaves. An action carries an `action_type`, an optional `resource`, and a `cost_cents`. Payments are a separate resource, `payment_intent`, evaluated under the same policy. ### Decision What came back: an `outcome` of `allowed`, `requires_approval` or `denied`, the `rule` that produced it, the `headroom` each limit had left, and a `policy_snapshot` of the rules as they read at that instant. ### Cosignature A short-lived ES256 signature over an allowed decision, so whoever executes the action can verify the authority without calling us, and without trusting the agent that carried it. ## What Kordio never does Kordio holds no funds, no accounts, and none of your credentials. It decides and it signs; your own rails and your own keys execute. That is a deliberate limit with a consequence worth stating plainly: an executor that never checks with Kordio and never verifies a cosignature is not governed by it. The control layer binds the paths you route through it. ## Next steps Every rule kind, the typed shorthands, and the condition language. Ordering, reservations, replay, and the failure modes. Check a cosignature offline, without calling us. Every endpoint, generated from the OpenAPI spec. # Where the ledger fits Source: https://docs.kordio.io/agents/ledger-projection What the projection mirrors into the books, and what it does not promise. Where a workspace has the ledger enabled, the reservations spend control takes are mirrored into it as balanced postings your finance team can reconcile. You do not write those postings, and you do not need to read the ledger docs to use spend control. What that buys you is that "what did this agent spend last month" becomes a balance query rather than an archaeology project across application logs. It is a capability you switch on, not a property of the platform: without it, authorization is unchanged and there are no postings. ## The account layout Each workspace owns its own books, and each agent owns an account inside them, named `spend:{agent_id}`, so the accounting graph mirrors your agent topology without you designing one. ```bash theme={"dark"} curl https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/funds \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": { "available_cents": 260000, "held_cents": 240000, "committed_cents": 240000, "ledger_committed_cents": 228000, "unprojected_cents": 12000, "currency": "USD", "ledger_ready": true, "accounts": [ { "account_id": "spend:7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "agent_name": "procurement agent", "committed_cents": 228000, "held_cents": 240000, "currency": "USD" } ] } } ``` ## Reading the figures | Field | Means | | ------------------------ | ---------------------------------------------------------------------- | | `available_cents` | Unspent budget across every active budget. | | `held_cents` | Reserved by intents waiting on a person. | | `committed_cents` | Spent, as the control layer sees it. This is the authoritative number. | | `ledger_committed_cents` | Posted to the ledger so far. | | `unprojected_cents` | The gap between the two, floored at zero. | `unprojected_cents` is the one to understand. It is normally near zero and transiently non-zero while projections settle. A persistently growing value means projections are backing up. That is worth an alert, and never a reason to distrust `committed_cents`, which does not depend on the ledger at all. ## The projection is never in the authorization path A slow or unavailable ledger can delay a posting. It can never delay or change a decision. If the ledger is unreachable, this endpoint degrades rather than failing: `ledger_ready` comes back `false`, `accounts` is empty, and `ledger_committed_cents` reads zero. The control-plane figures above it stay correct throughout. `ledger_ready: false` means "we could not read the books", not "the books are wrong". Treat it as a monitoring signal, not a spend signal. ## Using the books directly The projected postings are ordinary ledger transactions, so everything in the [ledger concepts](/ledger/concepts) applies to them: balances at any instant, statements over a window, reconciliation against an external snapshot, and the reports. Two things are worth knowing before you query them: * **Intents carry `ledger_transaction_id`** once projected, so you can go from a decision to its postings directly rather than matching on amount and timestamp. * **The ledger knows nothing about agents.** It speaks accounts, postings, transactions and balances. `spend:{agent_id}` is just an account id we chose; no ledger code path treats it specially. ## Availability Check **Billing** in the [console](https://app.kordio.io) for whether the ledger is on for your workspace. Kordio Control works either way. Without it, decisions, reservations and the audit trail all behave exactly as documented. What you lose is the projected postings and the ledger-side figures on [workspace funds](#reading-the-figures), not any part of authorization. ## Next steps Write to the books yourself, alongside the projection. Match projected spend against what the rail actually charged. # Writing a policy Source: https://docs.kordio.io/agents/policies Caps, windows, allowlists, and the condition language. A policy is data, not code. It always terminates, it is validated when you write it rather than when an agent is waiting, it diffs in review, and any UI can render it. A policy engine standing in front of money should be analysable, not Turing-complete. ## Your first policy A policy carries two things: **typed columns** for the common cases, and a general **`rules` array** for everything else. The columns are shorthand that compiles into the same rules, so use them when they fit. ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"per_transaction_cap_cents\": 50000, \"approval_threshold_cents\": 20000, \"velocity_cap_cents\": 200000, \"velocity_window_seconds\": 3600 }" ``` Never more than $500 in one action, hold anything over $200 for a person, and never more than \$2,000 in any rolling hour. The third rule is the one that catches a retry loop. ### The typed columns, and the rule name each produces This mapping matters, because the name you see in `decision.rule` is **not** the underlying rule kind: | Column | Compiles to | `decision.rule` | | ------------------------------------------------ | -------------------- | ------------------------ | | `per_transaction_cap_cents` | `cost_cap` | `per_transaction_cap` | | `velocity_cap_cents` + `velocity_window_seconds` | `spend_window` | `velocity_cap` | | `monthly_cap_cents` | `monthly_spend_cap` | `monthly_cap` | | `approval_threshold_cents` | `approval_threshold` | `approval_threshold` | | `counterparty_allowlist` | `resource_allowlist` | `counterparty_allowlist` | Write the same limit in the `rules` array instead and it reports under its `rule_name`, which defaults to the kind. Both are fine; just do not expect a cap set through `per_transaction_cap_cents` to come back as `cost_cap`. ## Rule kinds | Kind | Settings | What it does | | -------------------- | ------------------------------- | ------------------------------------------------------------------------------- | | `cost_cap` | `max_cents` | Refuses a single action above the ceiling. | | `spend_window` | `max_cents`, `window_seconds` | Refuses once spend in a rolling window exceeds the cap. | | `monthly_spend_cap` | `max_cents` | Refuses once calendar-month spend exceeds the cap. | | `rate_limit` | `max_actions`, `window_seconds` | Refuses on count rather than amount. Catches loops that spend nothing per call. | | `approval_threshold` | `above_cents` | Holds for a person instead of refusing. | | `action_allowlist` | `allow` | Only these action types are permitted. | | `resource_allowlist` | `allow` | Only these counterparties or resources are permitted. | | `condition` | `when`, `effect` | A boolean expression over the action. | That table is the whole registry. There is no way to define a rule kind of your own, and no `kind` outside those eight will save. Every kind takes an optional `rule_name`, echoed back in the decision, and every kind except `action_allowlist` takes an optional `action_types` array to scope it; an empty array means all action types. Every rule is assigned a stable `id` on write, so a decision read months later can still name the exact rule that produced it. An unknown kind, or a missing setting, is rejected when the policy is written. Never when an agent is waiting on an answer. Two things the rule kinds deliberately do not do, because people ask. `rate_limit` and `spend_window` count across the whole agent and can only be narrowed by `action_types`: there is no grouping by counterparty, by resource, or by a metadata key. And nothing reads the clock beyond a rolling window, so there is no time-of-day or day-of-week condition. Where a fact like that matters, compute it on your side and send it in `metadata`, which a `condition` rule can read. An `allow` array that is empty is a no-op, not a deny-all. To deny by default, use `mode: "allowlist"` instead. Window rules count both action intents in `pending`, `requires_approval` or `completed`, and payment intents in `pending`, `requires_approval` or `executed`. Spend on one consumes the other's headroom. ## The condition language `condition` is the open one: a boolean expression over the action, with an effect. ```json theme={"dark"} { "kind": "condition", "effect": "deny", "rule_name": "engineering_vendors_only", "when": { "all_of": [ {"field": "action_type", "operator": "starts_with", "value": "payment."}, {"any_of": [ {"field": "resource", "operator": "in", "value": ["api.openai.com", "api.anthropic.com"]}, {"field": "metadata.preapproved", "operator": "eq", "value": true} ]}, {"not": {"field": "cost_cents", "operator": "gt", "value": 50000}} ] } } ``` **Effects** are `deny` (the default), `allow`, or `require_approval`. **Combinators** are `all_of`, `any_of` and `not`, nestable to ten levels. An empty `all_of` or `any_of` is rejected at write time. **Fields** are `action_type`, `resource`, `cost_cents`, `currency`, `agent_id`, `agent_mode`, `budget_id`, and any `metadata.*` dot path. A `metadata.*` rule reads the `metadata` object on the request, on both `POST /control/v1/agent/actions` and `POST /control/v1/agent/payment_intents`. On the payment endpoint `decision_context` is provenance and is never evaluated, so send anything a rule must see as `metadata`. A payment is evaluated as `action_type` `payment.create` with the counterparty as its `resource`, so the same rule covers both endpoints. **Operators** are `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `not_in`, `contains`, `starts_with`, `ends_with`, `exists`. A predicate compares to a literal `value`, or to another field on the same request with `value_field`, which accepts exactly the names the left side accepts. Sending both is rejected at write time. That is how a refund gets capped at the order it belongs to: see [stop an agent over-refunding](/agents/guides/refund-ceiling). A missing field never raises. It fails to match. Unknown fields and operators are rejected at write time. The ordered comparisons (`gt`, `gte`, `lt`, `lte`) are numeric. A non-numeric operand makes the comparison `false` rather than an error, so a typo in a `metadata.*` path silently fails to match rather than blowing up. Use `exists` when you need to tell "absent" from "false". ## Blocklist and allowlist A policy is `blocklist` by default: the action is permitted unless a rule denies it. Set `mode: "allowlist"` and it inverts. The action is denied unless one of that policy's `allow` rules matches, reported as the rule `not_allowlisted`. A `deny` rule still overrides an `allow`. Each allowlist policy is an independent gate. Attach two and both must be satisfied. Allowlist mode is the right default for an agent that touches real money. Start by denying everything and naming what you permit, rather than trying to enumerate every way an agent could go wrong. ## Reusable modules Modules are named rule sets scoped to a workspace. A policy imports them by name and they compile in ahead of its own rules. ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policy_modules \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "vendor-allowlist", "rules": [ {"kind": "resource_allowlist", "allow": ["acme-supplies.example"]} ]}' ``` ```json theme={"dark"} { "agent_id": "7d2a...", "imports": ["vendor-allowlist"], "rules": [] } ``` Modules are addressed by `name`, not by id, so `GET /control/v1/workspaces/{slug}/policy_modules/vendor-allowlist` reads one back. Editing a module changes every policy importing it. A policy importing an unknown module will not save, and a module still imported by a policy will not delete. Modules do not import other modules, so composition is one level deep and cannot cycle. ## Test before you apply Never guess what a policy does. Preview a draft you have not saved: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policy_previews \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"action_type\": \"payment.create\", \"cost_cents\": 75000, \"policy\": { \"per_transaction_cap_cents\": 50000 } }" ``` ```json 200 OK theme={"dark"} { "data": { "outcome": "denied", "rule": "per_transaction_cap", "detail": { "limit_cents": 50000, "requested_cents": 75000 }, "headroom": { "session_remaining_cents": 100000, "per_action_cap_cents": 50000 }, "policy_snapshot": [ { "id": null, "status": "active", "mode": "blocklist", "imports": [], "per_transaction_cap_cents": 50000, "counterparty_allowlist": [], "rules": [] } ] } } ``` The denial reports `limit_cents`, not the `per_transaction_cap_cents` you wrote. The column name is the input; `detail` speaks in the compiled rule's terms. Nothing is persisted: no policy, no budget, no intent, no audit event. `imports` resolve against the workspace's real saved modules, so you can preview a draft that builds on modules already in place. `session_budget_cents` sets the synthetic budget and defaults to `100000`. Previewing needs only the `read` capability, deliberately: it is not a mutation. The same evaluation is available to your agent at `POST /control/v1/agent/actions/simulate`, which does record an `action.simulated` audit event. ## Next steps What `approval_threshold` produces, and how it resolves. A single-use ceiling that narrows a policy for one payment. Every rule that can appear in `decision.rule`. The full policy schema. # Authorize an agent action Source: https://docs.kordio.io/agents/quickstart Gate your first agent action in test mode, with one HTTP call. By the end of this page an agent of yours asks Kordio before it spends, and Kordio answers `allowed`, `requires_approval`, or `denied`, naming the rule that decided. **Wrong page?** This gates what an agent is allowed to spend, before it spends it. If you are here to post double-entry transactions and read balances, you want the [Ledger quickstart](/ledger/quickstart) instead. Everything here runs in test mode, which uses the same policy engine as live, so the integration you write now is the one you ship. ## 0. Get your credentials Sign up at [app.kordio.io](https://app.kordio.io), create a workspace, and mint a dashboard token. The full walkthrough is on [getting your credentials](/agents/authentication#getting-your-credentials). ## 1. Create an agent An **agent** is a scoped identity for one workload. It carries its own API key and its own permitted action types. ```bash theme={"dark"} AGENT=$(curl -s -X POST \ https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/agents \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"procurement agent","mode":"test","scopes":["payment.*","tool.invoke"]}') export KORDIO_AGENT_ID=$(echo "$AGENT" | jq -r '.data.id') export KORDIO_AGENT_KEY=$(echo "$AGENT" | jq -r '.data.api_key') export KORDIO_STARTER_POLICY_ID=$(echo "$AGENT" | jq -r '.data.starter_policy.id') ``` ```json 201 Created theme={"dark"} { "data": { "id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "name": "procurement agent", "status": "active", "mode": "test", "scopes": ["payment.*", "tool.invoke"], "max_budget_cents": 100000, "api_key_prefix": "krt_test_9f3", "api_key": "krt_test_9f3a1c7e42b8d05a6e1f8c3d", "created_at": "2026-08-22T09:04:11Z", "starter_policy": { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "status": "active", "mode": "blocklist", "per_transaction_cap_cents": 50000, "approval_threshold_cents": 10000, "imports": [], "rules": [] } } } ``` `api_key` is returned exactly once and starts with `krt_test_`. Store it the way you store any other secret; Kordio keeps only a digest and cannot show it to you again. `scopes` restricts which action types this key may even ask about. **An empty array means unrestricted, not blocked.** Name the action types you expect, and keep one agent per workload so you can revoke one without stopping the rest. **Read `starter_policy` before you go further.** A new agent arrives governed rather than open: a single action is capped at $500, and anything over $100 is held for a person. Nothing you write later replaces it, so step 2 retires it. Pass `"skip_starter_policy": true` to create an agent with no policy at all, which denies everything until you write one. ## 2. Write your own policy The starter policy is a floor, not the policy you want. Write yours alongside it: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"agent_id\": \"$KORDIO_AGENT_ID\", \"per_transaction_cap_cents\": 50000, \"approval_threshold_cents\": 200000, \"velocity_cap_cents\": 200000, \"velocity_window_seconds\": 3600 }" ``` That policy says: never more than $500 in one action, hold anything over $2,000 for a person, and never more than \$2,000 in any rolling hour. The third rule is the one that catches a retry loop. The first two, on their own, would let nineteen individually reasonable \$340 charges through. Both policies are active now, and both run. Where two rules answer the same question the tighter one decides, so the starter's $100 threshold would still govern, not your $2,000 one. Retire it now that your rules cover its ground: ```bash theme={"dark"} curl -X PATCH \ https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/policies/$KORDIO_STARTER_POLICY_ID \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{"status": "disabled"}' ``` ```json 200 OK theme={"dark"} { "data": { "id": "a05f8c37-6b12-4d94-8207-c3e1b9d6a4f8", "status": "disabled" } } ``` **Do that in this order, and never disable an agent's last active policy.** An agent with no active policy denies everything, with the rule `no_policy`. That is deliberate and fail-closed: an agent nobody has written rules for has no authority rather than unlimited authority. ## 3. Open a budget A **budget** is the envelope for one run. Every authorized action commits against it, which makes it the thing that stops a loop rather than a single mistake. ```bash cURL theme={"dark"} BUDGET=$(curl -s -X POST https://api.kordio.io/control/v1/agent/budgets \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d '{"budget_cents": 50000, "currency": "USD"}') export KORDIO_BUDGET_ID=$(echo "$BUDGET" | jq -r '.data.id') ``` ```typescript TypeScript theme={"dark"} const res = await fetch("https://api.kordio.io/control/v1/agent/budgets", { method: "POST", headers: { Authorization: `Bearer ${process.env.KORDIO_AGENT_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ budget_cents: 50_000, currency: "USD" }), }); const { data: budget } = await res.json(); ``` ```python Python theme={"dark"} import os, requests res = requests.post( "https://api.kordio.io/control/v1/agent/budgets", headers={"Authorization": f"Bearer {os.environ['KORDIO_AGENT_KEY']}"}, json={"budget_cents": 50_000, "currency": "USD"}, ) budget = res.json()["data"] ``` ```json 201 Created theme={"dark"} { "data": { "id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "agent_id": "7d2a6c15-3f89-4b02-9e64-8a15d7c0b3f2", "parent_budget_id": null, "budget_cents": 50000, "spent_cents": 0, "remaining_cents": 50000, "currency": "USD", "status": "active", "created_at": "2026-08-04T09:11:52Z" } } ``` ## 4. Ask before you spend This is the call that matters. Put it in front of the action, not after it. ```bash cURL theme={"dark"} ACTION=$(curl -s -w '\n%{http_code}' -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-4471-attempt-1" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"resource\": \"acme-supplies.example\", \"cost_cents\": 12000 }") export KORDIO_ACTION_ID=$(echo "$ACTION" | head -n-1 | jq -r '.data.id') echo "$ACTION" | tail -n1 # the status code you branch on ``` ```typescript TypeScript theme={"dark"} const res = await fetch("https://api.kordio.io/control/v1/agent/actions", { method: "POST", headers: { Authorization: `Bearer ${process.env.KORDIO_AGENT_KEY}`, "Idempotency-Key": "order-4471-attempt-1", "Content-Type": "application/json", }, body: JSON.stringify({ budget_id: budget.id, action_type: "payment.create", resource: "acme-supplies.example", cost_cents: 12_000, }), }); const body = await res.json(); switch (res.status) { case 201: /* execute, then report in step 5 */ break; case 202: /* held for a person. stop and wait */ break; case 403: /* denied. do not execute */ break; } ``` ```python Python theme={"dark"} res = requests.post( "https://api.kordio.io/control/v1/agent/actions", headers={ "Authorization": f"Bearer {os.environ['KORDIO_AGENT_KEY']}", "Idempotency-Key": "order-4471-attempt-1", }, json={ "budget_id": budget["id"], "action_type": "payment.create", "resource": "acme-supplies.example", "cost_cents": 12_000, }, ) body = res.json() # 201 execute, 202 held for a person, 403 denied ``` ```json 201 Created theme={"dark"} { "data": { "id": "9b2ef0c1-6a3d-4e75-8c19-2f4b7d5a0e63", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "action_type": "payment.create", "resource": "acme-supplies.example", "cost_cents": 12000, "currency": "USD", "state": "pending", "trace_id": "5e8c1a47-2b93-4d06-a7f1-9c3e05b8d24a", "created_at": "2026-08-22T09:12:04Z" }, "decision": { "outcome": "allowed", "rule": null, "detail": {}, "headroom": { "session_remaining_cents": 50000, "per_action_cap_cents": 50000, "approval_threshold_cents": 200000, "velocity_cap_remaining_cents": 200000 }, "policy_snapshot": [ { "id": "c41d7b28-9e05-4a63-b7f1-6d2c8e30a915", "status": "active", "mode": "blocklist", "imports": [], "per_transaction_cap_cents": 50000, "approval_threshold_cents": 200000, "velocity_cap_cents": 200000, "velocity_window_seconds": 3600, "monthly_cap_cents": null, "counterparty_allowlist": [], "rules": [] } ] }, "cosignature": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleV8xIn0..." } ``` `policy_snapshot` carries every active policy. Leave the starter enabled and it appears here too, with `headroom` reduced to the tightest value per key, which is how a threshold you wrote can be quietly overruled by one you did not. Read the status code, not the body, to branch: | Status | Outcome | What your agent does | | ------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `201` | `allowed` | Execute, then report the result in step 5. | | `202` | `requires_approval` | Stop. A person has to resolve it. Poll `GET /control/v1/agent/actions/{id}` or wait for your webhook. Do not call `complete`: it is a `422` from any state but `pending`. | | `403` | `denied` | Do not execute. `decision.rule` names what refused. | `Idempotency-Key` is required, and its absence is a `422`, not a `400`. Reuse the same key when you retry and Kordio replays the original decision instead of reserving the budget twice. The key is matched on its own: a replay returns the first decision even if you changed the amount or the counterparty underneath it, so give a genuinely different action a genuinely different key. `decision.headroom` reports what every limit had left, and `decision.policy_snapshot` is the policy exactly as it read at that moment. Both are measured **before** the reservation, so `session_remaining_cents` above is still the full \$500: subtract `cost_cents` yourself for the figure after this action. Surface headroom to your agent so it can pick a cheaper path instead of retrying into the same wall. Raise `cost_cents` past your \$2,000 threshold and this call answers `202` instead, with no `cosignature`. That is the product working, not a failure. See [holding spend for a person](/agents/approvals) for what happens next. ## 5. Report what happened Kordio holds the budget reservation until you say how the action ended. ```bash theme={"dark"} curl -X POST \ https://api.kordio.io/control/v1/agent/actions/$KORDIO_ACTION_ID/complete \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" ``` If it failed, say so instead. The reservation is released and the budget goes back: ```bash theme={"dark"} curl -X POST \ https://api.kordio.io/control/v1/agent/actions/$KORDIO_ACTION_ID/fail \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d '{"reason": "vendor returned 502"}' ``` Skipping this step is the most common integration mistake, and nothing sweeps up after it. A budget has no expiry and no close endpoint, so an action that is never completed or failed holds its share of the budget for good. Open a budget per run and let it end with the run. Payments report the same way, through `POST /control/v1/agent/payment_intents/:id/complete` and `/fail`. Kordio authorizes the spend and hands you a cosignature; your own rail moves the money. See [the payments section](/agents/concepts#payments-work-like-actions). ## 6. Try it without spending anything `simulate` runs the whole policy evaluation and records no intent and no reservation. Use it in tests, and in your own UI to show someone what a policy would do before they save it. ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/agent/actions/simulate \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"action_type\": \"payment.create\", \"cost_cents\": 999999 }" ``` ```json 200 OK theme={"dark"} { "data": { "outcome": "denied", "rule": "session_budget", "detail": { "remaining_cents": 38000, "requested_cents": 999999 }, "headroom": { "session_remaining_cents": 38000, "per_action_cap_cents": 50000, "approval_threshold_cents": 200000, "velocity_cap_remaining_cents": 188000 }, "policy_snapshot": [ { "id": "c41d7b28-9e05-4a63-b7f1-6d2c8e30a915", "status": "active", "mode": "blocklist" } ] } } ``` It always returns `200`, whatever the outcome, and the decision has no `id` because no intent was created. `policy_snapshot` is abbreviated here; the real one repeats every column of every active policy. ## Next steps Every rule kind, the typed shorthands, and the condition language. Check the cosignature offline, in your executor. What `202` means and how the queue resolves. Every field on every endpoint. # Spend tokens Source: https://docs.kordio.io/agents/spend-tokens A single-use ceiling an agent mints against its own budget. A spend token is a single-use ceiling an agent mints against one of its own budgets and presents later on a payment. It turns "this agent may spend $200" into "this agent may spend $200, once, to this vendor." A spend token only ever **narrows**. It cannot widen a policy, raise a cap, or authorize something policy would refuse. It is a self-imposed constraint an agent commits to in advance, not a grant of authority. ## When you would use one The pattern is a planning step that runs before an execution step, often in a different process or a different agent. A planner decides it will buy one thing from one vendor for at most \$200. It mints a token pinned to that vendor at that ceiling and hands the token id to whatever does the buying. The executor cannot then spend more, spend it twice, or spend it somewhere else, even though it holds an agent key whose policy would allow all three. Without the token, the executor's authority is whatever the policy allows for the rest of the budget. With it, the authority is what the planner actually intended. ## Minting one ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/agent/spend_tokens \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"amount_ceiling_cents\": 20000, \"counterparty\": \"acme-supplies.example\", \"expires_at\": \"2026-08-04T18:00:00Z\" }" ``` ```json 201 Created theme={"dark"} { "data": { "id": "b81d4f2c-7a06-4e39-95c2-1f8b3d0a6e57", "budget_id": "3f1c8a92-5d41-4c8e-9f2b-7a6e1d0c4b83", "amount_ceiling_cents": 20000, "counterparty": "acme-supplies.example", "expires_at": "2026-08-04T18:00:00Z", "status": "issued", "consumed_at": null, "created_at": "2026-08-04T09:20:33Z" } } ``` `counterparty` and `expires_at` are both optional. A token with neither is just a one-shot ceiling, and one with no `expires_at` never expires: it sits `issued` until something spends it. Set an expiry when the plan it encodes has a shelf life, which is most of the time. ## Spending against one Cite it by id on the payment: ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/agent/payment_intents \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Content-Type: application/json" \ -d "{ \"budget_id\": \"$KORDIO_BUDGET_ID\", \"amount_cents\": 12000, \"counterparty\": \"acme-supplies.example\", \"spend_token_id\": \"b81d4f2c-7a06-4e39-95c2-1f8b3d0a6e57\", \"idempotency_key\": \"order-4471\" }" ``` ## How it is evaluated The token is checked **first**, and it can only refuse. If it refuses, the policy engine never runs. | `decision.rule` | Why | | -------------------------- | ------------------------------------------------------------------------------------------------------ | | `spend_token_unusable` | Status is not `issued`, or the token has expired. `detail` carries `status`. | | `spend_token_ceiling` | `amount_cents` exceeds `amount_ceiling_cents`. `detail` carries `ceiling_cents` and `requested_cents`. | | `spend_token_counterparty` | The token is pinned to a different counterparty. `detail` carries `pinned` and `requested`. | If the token passes, normal policy evaluation runs on top. A token for $200 against a policy that caps payments at $150 authorizes $150, not $200. The tighter constraint always wins. Because the token short-circuits, a token refusal is the one denial that carries an empty `policy_snapshot` and an empty `headroom`. No policy ran, so there is nothing to report. On any non-denied outcome the token is consumed and moves to `status: consumed`. It cannot be presented again. A spend token is not a substitute for policy. Anything holding an agent key can mint one, so a token constrains only the code path that agrees to present it. Policy constrains every path. Use tokens to narrow what a specific execution step may do, never as the only limit on an agent. ## Lifecycle `status` moves from `issued` to `consumed`, or to `expired` when its `expires_at` passes. Expiry is swept in the background and emits both a `spend_token.expired` audit event and a `spend_token.expired` webhook, so you can react to a plan that was made and never executed. There is no endpoint that cancels an unused token. Consumption races safely: if two payments cite the same token at once, exactly one consumes it. The loser releases its budget reservation and the intent moves to `failed` with `spend_token_unusable`. ## Reading them back Minting is agent-side only. From the dashboard side the tokens are read-only: ```bash theme={"dark"} curl "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/spend_tokens?budget_id=$KORDIO_BUDGET_ID" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` A token cited by a held payment also appears on that payment's approval impact, so an approver sees the ceiling and the pinned counterparty before deciding. ## Next steps The limits a token narrows, rather than replaces. What an approver sees, including the token. # Webhooks Source: https://docs.kordio.io/agents/webhooks Subscribe to control-layer events and verify signed deliveries. Webhooks push a signed copy of every control-layer state change to an endpoint you control. The one you actually need is `action.requires_approval` paired with `approval.resolved`: that pair is how an agent waits on a person without polling. Ledger events are a separate subscription with a different registration endpoint and a different event set. See [Ledger: webhooks](/ledger/webhooks). The signature scheme is identical, so one verification routine covers both. ## Register an endpoint Endpoints are per workspace and need the `manage_policy` capability. ```bash theme={"dark"} curl -X POST https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/webhook_endpoints \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "url": "https://app.example.com/webhooks/kordio", "enabled_events": ["action.requires_approval", "approval.resolved", "budget.low"] }' ``` ```json 201 Created theme={"dark"} { "data": { "id": "c93f7b21-4e08-4a56-b7d3-05e2a9c14f60", "url": "https://app.example.com/webhooks/kordio", "enabled_events": ["action.requires_approval", "approval.resolved", "budget.low"], "status": "active", "secret": "whsec_4bSFH1YTkjwsgiMrHMwWJfJTIzsov60WxxsziZAE", "created_at": "2026-08-04T09:30:00Z" } } ``` `secret` is returned exactly once, at creation. Store it immediately. If you lose it, rotate the endpoint with `POST /control/v1/workspaces/{slug}/webhook_endpoints/{id}/rotate`, which mints a new one and stops the old one verifying immediately. An **empty** `enabled_events` array subscribes to every event type, not none. Name the types you handle. ## Event types A payment fires both spellings. Anything whose `action_type` starts with `payment.` emits the `payment.*` event and its `action.*` equivalent, whichever endpoint booked it, so an endpoint subscribed to either name hears about it. | Type | Fires when | | --------------------------- | --------------------------------------------------------------------------------------------------------- | | `action.requires_approval` | A rule held an action for a person. **The one to subscribe to.** | | `action.completed` | An agent reported an authorized action succeeded. | | `action.failed` | An agent reported it failed; the reservation is released. | | `payment.requires_approval` | A payment is held for a person. | | `payment.executed` | An agent reported an authorized payment went through. | | `payment.failed` | A payment failed; the reservation is released. | | `approval.resolved` | A person approved or denied. On the payment path the payload carries `resolution`. | | `budget.low` | A budget dropped to 10% or less of its size. Only a completed payment fires it, never a completed action. | | `spend_token.expired` | A spend token passed its expiry unused. | An unrecognised name in `enabled_events` is rejected with a `422` at registration. Never treat `approval.resolved` as permission on its own. It tells you a decision was made, not what it was, and an approved intent carries no cosignature. Read the outcome, and for anything that moves money verify the [cosignature](/agents/cosignatures) at the point of execution. ## Delivery shape ```json theme={"dark"} { "id": "e0a4c72f-1b95-4d68-a3f0-7c25e91b4d38", "type": "action.requires_approval", "created_at": "2026-08-04T09:31:12Z", "data": { } } ``` Header: `Kordio-Signature: t=,v1=`, an HMAC-SHA256 over `.` keyed by the endpoint secret. ## Verify the signature ```typescript Handler theme={"dark"} app.post( "/webhooks/kordio", express.raw({ type: "application/json" }), (req, res) => { const sig = req.headers["kordio-signature"] as string; if (!verifySignature(req.body.toString(), sig, process.env.KORDIO_WEBHOOK_SECRET!)) { return res.status(401).json({ error: "invalid signature" }); } const event = JSON.parse(req.body.toString()); if (event.type === "approval.resolved") { // resume the agent } res.json({ received: true }); }, ); ``` ## Respond and retry A delivery succeeds on any `2xx`. Anything else, including a timeout or a connection error, is retried with polynomial backoff for up to eight attempts, after which the delivery is marked failed with its last error recorded. The ledger API retries on a different schedule; if you point both at one handler, do not assume a shared budget. Return `2xx` quickly and do heavy work asynchronously. Events carry stable ids, so treat handlers as at-least-once and deduplicate on the event `id`. ## If you would rather poll Everything a webhook reports is also readable. The audit trail is the durable version of the same story: ```bash theme={"dark"} TRACE_ID="5e8c1a47-2b93-4d06-a7f1-9c3e05b8d24a" # from decision.data.trace_id curl "https://api.kordio.io/control/v1/workspaces/$KORDIO_WORKSPACE/audit_events?trace_id=$TRACE_ID" \ -H "Authorization: Bearer $KORDIO_DASHBOARD_TOKEN" ``` Filtering by `trace_id` pulls one action's whole history across authorization, approval and outcome. Every role can read it, including `member`. ## Next steps The flow these events drive. Endpoint management and the audit events API. # Where a control layer fits Source: https://docs.kordio.io/agents/why Why a prompt, an if statement, and a card limit each stop short. Everyone builds the first version of this themselves, and it is always a prompt, an `if` statement, or a card limit. Each one works until the day it matters, and the day it matters is the only day it was for. ## A prompt is not a limit The first version is a rule in the system prompt. A prompt is advice to a model that is free to ignore it, and it leaves no record you can hand anyone afterwards. Policy in Kordio is data, not code. It validates when you write it rather than when an agent is waiting, it diffs in review, any UI can render it, and the decision it produced is still on record months later, naming the exact rule. ## Your orchestrator cannot constrain itself The second version is `if amount > 500` in the orchestrator. This is real enforcement, and it is the honest competitor to this product, so here is the honest objection to it. It lives inside the thing it is supposed to constrain. Shipping a new agent means writing it again. Changing a limit means a deploy. Nothing outside that process can say what was permitted or why, which means the answer to "who approved this" is a code review from six weeks ago. And the check and the spend are in the same trust domain, so anything that compromises the agent compromises the limit at the same moment. The value of moving it out is not that the logic is better. It is that the logic is somewhere the agent cannot reach. ## A card limit stops one mistake, not nineteen Spend controls on a card or a virtual account are real enforcement, and for a single ceiling they are enough. What they do not see is intent. A retry loop making the same reasonable-looking charge nineteen times is nineteen approvals, each individually under the limit. Neither does a card cover the paid API call that is not a card transaction at all, which is where most agent spend actually goes. Kordio runs before the rail, applies caps, windows, rate limits and allowlists across payments and tool calls together, and holds anything over a threshold for a person. Use both. The card is the floor under everything; the control layer is what knows what this agent was doing. ## Agent payment protocols answer a different question AP2, ACP and the trusted-agent work at the card networks are standardising how an agent proves *who it is* at checkout. That is real and worth adopting. None of them decides whether your agent should be spending your money at all, and none covers the paid tool call that is not a payment. They authenticate; Kordio authorises. If you adopt one, Kordio still runs first and answers the question the protocol does not ask. ## What Kordio deliberately does not do Kordio holds no funds, no accounts, and none of your credentials. It decides and it signs; your own rails and your own keys execute. That limit has a consequence worth stating plainly: an executor that never checks with Kordio and never verifies a cosignature is not governed by it. The control layer binds the paths you route through it. Put the check in front of the spend, in code your agent cannot skip, and verify the signature where the action is actually carried out. ## Next steps Gate a real action in test mode, in about five minutes. Ordering, reservations, replay, signature lifetime, and what happens when we are down. # Account statement for a period Source: https://docs.kordio.io/api-reference/accounts/account-statement-for-a-period /ledger/api-reference/openapi.yaml get /ledger/v1/accounts/{id}/statement Opening balance at `from`, every posting in `[from, to)` ordered by `value_date` ascending, closing balance at `to`. The auditor's per-account view. # Create an account Source: https://docs.kordio.io/api-reference/accounts/create-an-account /ledger/api-reference/openapi.yaml post /ledger/v1/accounts # Define an account template Source: https://docs.kordio.io/api-reference/accounts/define-an-account-template /ledger/api-reference/openapi.yaml post /ledger/v1/account_templates A template names a reusable shape for accounts: accounting type, allowed currencies, balance sign rule. When `POST /v1/accounts` is called with `template: `, the request is validated against the template before insert. Templates are immutable; create a new name to evolve. # Get an account Source: https://docs.kordio.io/api-reference/accounts/get-an-account /ledger/api-reference/openapi.yaml get /ledger/v1/accounts/{id} # Get an account template Source: https://docs.kordio.io/api-reference/accounts/get-an-account-template /ledger/api-reference/openapi.yaml get /ledger/v1/account_templates/{name} # Get an account's balance (current or point-in-time) Source: https://docs.kordio.io/api-reference/accounts/get-an-accounts-balance-current-or-point-in-time /ledger/api-reference/openapi.yaml get /ledger/v1/accounts/{id}/balance Pass `?at=` for a historical balance computed from `value_date` on each posting. Without `at`, returns the current balance from the actor's in-memory state. # Get the rolled-up balance for an account category Source: https://docs.kordio.io/api-reference/accounts/get-the-rolled-up-balance-for-an-account-category /ledger/api-reference/openapi.yaml get /ledger/v1/accounts/{id}/category_balance Returns the aggregate balance across all accounts under the same category as the addressed account (e.g. the sum of every `accounts_receivable:*` account). Useful for treasury-level dashboards that want a single number per category. # List account templates Source: https://docs.kordio.io/api-reference/accounts/list-account-templates /ledger/api-reference/openapi.yaml get /ledger/v1/account_templates # List accounts Source: https://docs.kordio.io/api-reference/accounts/list-accounts /ledger/api-reference/openapi.yaml get /ledger/v1/accounts # List postings on an account Source: https://docs.kordio.io/api-reference/accounts/list-postings-on-an-account /ledger/api-reference/openapi.yaml get /ledger/v1/accounts/{id}/postings # Authorize an action Source: https://docs.kordio.io/api-reference/actions/authorize-an-action /agents/api-reference/openapi.yaml post /control/v1/agent/actions The call that goes in front of the spend. Runs the full policy evaluation, reserves budget against the budget, records an intent, and returns the decision. Branch on the **status code**, not the body. An intent is recorded even when the outcome is `denied`, so a refusal is auditable. An agent with no active policy denies everything, with rule `no_policy`. This is deliberate and fail-closed: write a policy before you expect an allow. # Read an action intent Source: https://docs.kordio.io/api-reference/actions/read-an-action-intent /agents/api-reference/openapi.yaml get /control/v1/agent/actions/{id} The current state of one intent. This is what you poll while an action sits in `requires_approval`, if you are not using webhooks. # Report failure Source: https://docs.kordio.io/api-reference/actions/report-failure /agents/api-reference/openapi.yaml post /control/v1/agent/actions/{id}/fail The action failed. Releases the reservation back to the budget and moves the intent from `pending` or `requires_approval` to `failed`. # Report success Source: https://docs.kordio.io/api-reference/actions/report-success /agents/api-reference/openapi.yaml post /control/v1/agent/actions/{id}/complete The action succeeded. Settles the reservation and moves the intent from `pending` to `completed`. Reporting is not optional. An intent left `pending` holds its budget until the session closes. # Simulate an action Source: https://docs.kordio.io/api-reference/actions/simulate-an-action /agents/api-reference/openapi.yaml post /control/v1/agent/actions/simulate Runs the same evaluation and records nothing: no intent, no reservation, no budget consumed. Always `200`, whatever the outcome. Use it in tests, and in your own UI to show someone what a policy would do before they save it. Note that a simulation does write an `action.simulated` audit event, so simulations are still visible in the trail. # Create an agent Source: https://docs.kordio.io/api-reference/agents/create-an-agent /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/agents Requires the `manage_policy` capability. The response carries `api_key` exactly once. Kordio stores only a digest and compares it in constant time; if you lose the key, rotate the agent. Unless `skip_starter_policy` is set, the agent is created with an active starter policy that caps a single action at 50000 cents and holds anything above 10000 cents for a person. It is returned as `starter_policy`, and it stays in force until you disable it. Creating an agent consumes plan headroom, and creating a `live` agent requires a plan with live mode. Either limit returns `422`. # List agents Source: https://docs.kordio.io/api-reference/agents/list-agents /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/agents # Read an agent Source: https://docs.kordio.io/api-reference/agents/read-an-agent /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/agents/{id} # Update an agent Source: https://docs.kordio.io/api-reference/agents/update-an-agent /agents/api-reference/openapi.yaml patch /control/v1/workspaces/{workspace_slug}/agents/{id} Requires `manage_policy`. Use this to suspend, revoke, or re-scope an agent. Suspending stops new authorizations and leaves history intact. Revoking is permanent. Neither rewrites decisions already made, and neither invalidates a cosignature already issued, which stays verifiable until it expires. # Approve a held action Source: https://docs.kordio.io/api-reference/approvals/approve-a-held-action /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/action_intents/{id}/approve Requires the `approve` capability. Moves the intent from `requires_approval` to `pending`. It does **not** execute anything. The agent still executes and still reports the outcome with `complete` or `fail`. Records `resolved_by_sub` and emits `approval.resolved`. # Approve a held payment Source: https://docs.kordio.io/api-reference/approvals/approve-a-held-payment /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/payment_intents/{id}/approve Requires `approve`. This grants authority; it does not move money. The intent returns to `pending` and the agent settles it on its own rail, exactly as it does for an approved action. # Deny a held action Source: https://docs.kordio.io/api-reference/approvals/deny-a-held-action /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/action_intents/{id}/deny Requires `approve`. Moves the intent to `denied` and releases the reserved budget back to the budget. # Deny a held payment Source: https://docs.kordio.io/api-reference/approvals/deny-a-held-payment /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/payment_intents/{id}/deny Requires `approve`. Releases the reservation and enqueues the ledger release. # List action intents Source: https://docs.kordio.io/api-reference/approvals/list-action-intents /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/action_intents Filter by `state=requires_approval` for the approval queue. # List payment intents Source: https://docs.kordio.io/api-reference/approvals/list-payment-intents /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/payment_intents # Read a payment intent Source: https://docs.kordio.io/api-reference/approvals/read-a-payment-intent /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/payment_intents/{id} # Read an action intent Source: https://docs.kordio.io/api-reference/approvals/read-an-action-intent /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/action_intents/{id} # What approving this payment would do Source: https://docs.kordio.io/api-reference/approvals/what-approving-this-payment-would-do /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/payment_intents/{id}/impact The same summary as the action-intent impact call, plus the spend token the payment cites, if any. # What approving this would do Source: https://docs.kordio.io/api-reference/approvals/what-approving-this-would-do /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/action_intents/{id}/impact Everything an approver needs to decide, before they click: the amount, the rule that held it, the budget it draws on, how much comes back if it is denied, how many other holds compete for the same budget, and every window it consumes. Budget is already reserved while an intent is held, so approving costs no further headroom. `returns_on_deny_cents` is what denying gives back. An approver who only sees "approve $2,400?" is rubber-stamping. This is the call that fixes that. # List audit events Source: https://docs.kordio.io/api-reference/audit-events/list-audit-events /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/audit_events The append-only record of everything the control layer did. Every role can read it, including `member`. An audit trail only some people can see is not much of one. Filter by `trace_id` to pull the whole story of one action across authorization, approval and outcome. # Read an audit event Source: https://docs.kordio.io/api-reference/audit-events/read-an-audit-event /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/audit_events/{id} # Delete an OAuth client Source: https://docs.kordio.io/api-reference/auth/delete-an-oauth-client /ledger/api-reference/openapi.yaml delete /ledger/v1/oauth_clients/{id} Removes the client. In-flight access tokens minted by it remain valid until their natural expiry (JWTs are stateless); no new tokens can be issued. # Get an OAuth client Source: https://docs.kordio.io/api-reference/auth/get-an-oauth-client /ledger/api-reference/openapi.yaml get /ledger/v1/oauth_clients/{id} # List OAuth clients Source: https://docs.kordio.io/api-reference/auth/list-oauth-clients /ledger/api-reference/openapi.yaml get /ledger/v1/oauth_clients Lists every client in the tenant. Secrets are **never** returned on this endpoint, only on create + rotate. Requires `ledger:clients:read`. # Register an OAuth client Source: https://docs.kordio.io/api-reference/auth/register-an-oauth-client /ledger/api-reference/openapi.yaml post /ledger/v1/oauth_clients Mints a new client. The response includes `client_secret`, the **only** time it is returned. Store it before discarding the response. Requires `ledger:clients:write`. `Idempotency-Key` header is accepted. # Rotate the client secret Source: https://docs.kordio.io/api-reference/auth/rotate-the-client-secret /ledger/api-reference/openapi.yaml post /ledger/v1/oauth_clients/{id}/rotate_secret Mints a new client secret and returns the plaintext **once**. The previous secret remains valid for `POST /oauth/token` for 24 hours after rotation, then is destroyed (sweeper job). Re-rotating before the prior overlap window closes is rejected with `rotation_in_progress` (409) to prevent a 3-key chain. `Idempotency-Key` header is accepted. # Issue an access token Source: https://docs.kordio.io/api-reference/authentication/issue-an-access-token /ledger/api-reference/openapi.yaml post /oauth/token RFC 6749 section 4.4 client_credentials. Authenticate with HTTP Basic (`client_id:client_secret`) **or** with `client_id` and `client_secret` in the form body. Tokens are HS256 JWTs valid for one hour. They carry `tenant_id`, `mode`, and the granted `scope`. Decode them at jwt.io to inspect. # Buy prepaid volume Source: https://docs.kordio.io/api-reference/billing/buy-prepaid-volume /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/billing/packs Requires `manage_members`. # Cancel the subscription Source: https://docs.kordio.io/api-reference/billing/cancel-the-subscription /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/billing/cancel Requires `manage_members`. Cancels at period end; the plan keeps entitling until then. # Open the billing portal Source: https://docs.kordio.io/api-reference/billing/open-the-billing-portal /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/billing/portal Requires `manage_members`. # Re-sync billing state Source: https://docs.kordio.io/api-reference/billing/re-sync-billing-state /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/billing/refresh Requires `manage_members`. Pulls the current subscription from the billing provider rather than waiting for the next webhook. # Read plan and entitlements Source: https://docs.kordio.io/api-reference/billing/read-plan-and-entitlements /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/billing The current plan, subscription, entitlement usage, prepaid volume, and the plan catalogue. Console-facing; agents never call this. # Start a plan checkout Source: https://docs.kordio.io/api-reference/billing/start-a-plan-checkout /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/billing/checkout Requires `manage_members`. Returns a hosted checkout URL, or, if the workspace is already subscribed, changes the plan in place. # List budgets Source: https://docs.kordio.io/api-reference/budgets/list-budgets /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/budgets # Open a budget Source: https://docs.kordio.io/api-reference/budgets/open-a-budget /agents/api-reference/openapi.yaml post /control/v1/agent/budgets A budget is the budget envelope for one agent run. Every authorized action commits against it, and it is what a runaway loop runs into. Budget is claimed with a single conditional update rather than a lock, so parallel sub-agents under one agent contend at the row instead of queueing. # Read a budget Source: https://docs.kordio.io/api-reference/budgets/read-a-budget /agents/api-reference/openapi.yaml get /control/v1/agent/budgets/{id} Read the remaining budget on a budget. # Read a budget Source: https://docs.kordio.io/api-reference/budgets/read-a-budget-1 /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/budgets/{id} # Cosignature public keys Source: https://docs.kordio.io/api-reference/cosignatures/cosignature-public-keys /agents/api-reference/openapi.yaml get /.well-known/jwks.json The public keys for offline cosignature verification. Unauthenticated, unthrottled, and cacheable. Retired keys stay published and keep verifying; they simply stop signing. A cosignature issued a minute before a rotation still checks out. When cosigning is not configured on a deployment this returns an empty key set rather than an error, and decisions come back with no `cosignature` field rather than an unverifiable one. # Verify a cosignature Source: https://docs.kordio.io/api-reference/cosignatures/verify-a-cosignature /agents/api-reference/openapi.yaml post /control/v1/cosign/verify Unauthenticated. Checks the signature and, beyond that, whether the underlying intent is still spendable and still carries the amount the token claims. That statefulness is the reason to use this endpoint rather than local verification: a signature proves authority was granted, not that it has not already been used. An intent that has already been spent reports `already_settled`. For the hot path, verify offline against the JWKS instead. This endpoint is for when you need settlement state. Send the token either as the body field `authorization` or as an `Authorization: Bearer ` header. # Verify a cosignature and spend it Source: https://docs.kordio.io/api-reference/cosignatures/verify-a-cosignature-and-spend-it /agents/api-reference/openapi.yaml post /control/v1/cosign/consume Unauthenticated. Does everything `verify` does, and then marks the authority spent so the same cosignature cannot be presented twice. Use this when you are the executor and you are about to act. `verify` answers "is this good?"; `consume` answers "is this good, and it is mine now". A second call with the same cosignature reports `already_settled`. Send the token either as the body field `authorization` or as an `Authorization: Bearer ` header. # Fetch one event Source: https://docs.kordio.io/api-reference/events/fetch-one-event /ledger/api-reference/openapi.yaml get /ledger/v1/events/{id} # List events Source: https://docs.kordio.io/api-reference/events/list-events /ledger/api-reference/openapi.yaml get /ledger/v1/events Same payloads webhooks deliver. Use for backfill, debugging, or as a polling alternative to webhooks. # Read workspace funds Source: https://docs.kordio.io/api-reference/funds/read-workspace-funds /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/funds Committed, held and available spend across every active session in the workspace, plus what the ledger has caught up on. `unprojected_cents` is the gap between what the control layer has committed and what the ledger has posted. It is normally near zero and transiently non-zero while projections settle. If the ledger is unavailable this degrades rather than failing: `ledger_ready` comes back `false`, `accounts` is empty, and the control-plane figures are still correct. # Create a ledger Source: https://docs.kordio.io/api-reference/ledgers/create-a-ledger /ledger/api-reference/openapi.yaml post /ledger/v1/ledgers # Get a ledger Source: https://docs.kordio.io/api-reference/ledgers/get-a-ledger /ledger/api-reference/openapi.yaml get /ledger/v1/ledgers/{id} # List ledgers in the caller's organization Source: https://docs.kordio.io/api-reference/ledgers/list-ledgers-in-the-callers-organization /ledger/api-reference/openapi.yaml get /ledger/v1/ledgers # Update a ledger Source: https://docs.kordio.io/api-reference/ledgers/update-a-ledger /ledger/api-reference/openapi.yaml patch /ledger/v1/ledgers/{id} # Accept an invitation Source: https://docs.kordio.io/api-reference/members/accept-an-invitation /agents/api-reference/openapi.yaml post /control/v1/invitations/accept # Add a member Source: https://docs.kordio.io/api-reference/members/add-a-member /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/memberships Requires `manage_members`. Consumes plan member headroom. # Change a member's role Source: https://docs.kordio.io/api-reference/members/change-a-members-role /agents/api-reference/openapi.yaml patch /control/v1/workspaces/{workspace_slug}/memberships/{id} Requires `manage_members`. A change that would leave the workspace with no owner is refused. # Invite someone Source: https://docs.kordio.io/api-reference/members/invite-someone /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/invitations Requires `manage_members`. A new invitation for an email with an open one supersedes it. # List members Source: https://docs.kordio.io/api-reference/members/list-members /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/memberships # List open invitations Source: https://docs.kordio.io/api-reference/members/list-open-invitations /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/invitations # Look up an invitation Source: https://docs.kordio.io/api-reference/members/look-up-an-invitation /agents/api-reference/openapi.yaml get /control/v1/invitations/lookup Resolve an invitation token before accepting it, so your UI can show what is being joined and whether the signed-in account matches. # Remove a member Source: https://docs.kordio.io/api-reference/members/remove-a-member /agents/api-reference/openapi.yaml delete /control/v1/workspaces/{workspace_slug}/memberships/{id} Requires `manage_members`. Removing the last owner is refused. # Revoke an invitation Source: https://docs.kordio.io/api-reference/members/revoke-an-invitation /agents/api-reference/openapi.yaml delete /control/v1/workspaces/{workspace_slug}/invitations/{id} Requires `manage_members`. # Return the caller's organization context Source: https://docs.kordio.io/api-reference/organizations/return-the-callers-organization-context /ledger/api-reference/openapi.yaml get /ledger/v1/organizations/me Resolves the calling client's organization and membership in one round trip. Useful as a session bootstrap. # Authorize a payment Source: https://docs.kordio.io/api-reference/payment-intents/authorize-a-payment /agents/api-reference/openapi.yaml post /control/v1/agent/payment_intents Evaluated as the action type `payment.create` with the counterparty as its resource, so an agent's caps, windows and allowlists apply across payments and other actions together. Spend on one consumes headroom for the other. One difference from `POST /v1/agent/actions` that will bite you if you assume symmetry: - **Idempotency is a body field here**, `idempotency_key`, not the `Idempotency-Key` header. A missing one is a `400`, not a `422`. Kordio authorizes the payment; it never moves the money. An allowed payment comes back `pending` with a cosignature. Settle it on your own rail, then report the outcome with `complete` or `fail`. # Read a payment intent Source: https://docs.kordio.io/api-reference/payment-intents/read-a-payment-intent /agents/api-reference/openapi.yaml get /control/v1/agent/payment_intents/{id} # Report that it did not Source: https://docs.kordio.io/api-reference/payment-intents/report-that-it-did-not /agents/api-reference/openapi.yaml post /control/v1/agent/payment_intents/{id}/fail Your rail refused or errored. Moves the intent to `failed` and releases the reservation back to the budget. # Report that the money moved Source: https://docs.kordio.io/api-reference/payment-intents/report-that-the-money-moved /agents/api-reference/openapi.yaml post /control/v1/agent/payment_intents/{id}/complete Your rail settled the payment. Moves the intent from `pending` to `executed` and keeps the reservation spent. Reporting is not optional. An intent left `pending` holds its budget until the budget closes. # Simulate a payment Source: https://docs.kordio.io/api-reference/payment-intents/simulate-a-payment /agents/api-reference/openapi.yaml post /control/v1/agent/payment_intents/simulate Evaluates without reserving or recording anything. Always `200`. # Close a period Source: https://docs.kordio.io/api-reference/periods/close-a-period /ledger/api-reference/openapi.yaml post /ledger/v1/period_closes Snapshots the trial balance at `period_end` and locks the window. After close, any new transaction with `value_date` inside the window is rejected with `period_closed`. Enforced both in the coordinator and by a DB trigger. Overlapping closes are rejected with `already_exists`. # Fetch a close with full trial-balance snapshot Source: https://docs.kordio.io/api-reference/periods/fetch-a-close-with-full-trial-balance-snapshot /ledger/api-reference/openapi.yaml get /ledger/v1/period_closes/{id} # List period closes Source: https://docs.kordio.io/api-reference/periods/list-period-closes /ledger/api-reference/openapi.yaml get /ledger/v1/period_closes # Reopen a closed period Source: https://docs.kordio.io/api-reference/periods/reopen-a-closed-period /ledger/api-reference/openapi.yaml post /ledger/v1/period_closes/{id}/reopen Records who reopened and when. Use sparingly; every reopen invalidates a previously-signed period report. The original close row is preserved with `reopened_at` + `reopened_by_label` for audit. # Create a policy Source: https://docs.kordio.io/api-reference/policies/create-a-policy /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/policies Requires `manage_policy`. A policy carries two things: typed spend columns for the common cases, and a general `rules` array. The columns are desugared into rules at compile time, so they are shorthand, not a separate mechanism. Everything is validated when you write it, never when an agent is waiting. An unknown rule kind, a missing setting, or an import naming a module that does not exist all fail here with a `422`. # List policies Source: https://docs.kordio.io/api-reference/policies/list-policies /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/policies # Read a policy Source: https://docs.kordio.io/api-reference/policies/read-a-policy /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/policies/{id} # Update a policy Source: https://docs.kordio.io/api-reference/policies/update-a-policy /agents/api-reference/openapi.yaml patch /control/v1/workspaces/{workspace_slug}/policies/{id} Requires `manage_policy`. # Create a policy module Source: https://docs.kordio.io/api-reference/policy-modules/create-a-policy-module /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/policy_modules Requires `manage_policy`. A module is a named rule set scoped to the workspace. Policies import it by name and its rules compile in ahead of their own. Editing a module changes every policy that imports it. Modules cannot import other modules, so composition is one level deep and cannot cycle. # Delete a policy module Source: https://docs.kordio.io/api-reference/policy-modules/delete-a-policy-module /agents/api-reference/openapi.yaml delete /control/v1/workspaces/{workspace_slug}/policy_modules/{name} Requires `manage_policy`. A module still imported by a policy will not delete. # List policy modules Source: https://docs.kordio.io/api-reference/policy-modules/list-policy-modules /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/policy_modules Sorted by name, ascending. # Read a policy module Source: https://docs.kordio.io/api-reference/policy-modules/read-a-policy-module /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/policy_modules/{name} Modules are addressed by `name`, not by id. # Update a policy module Source: https://docs.kordio.io/api-reference/policy-modules/update-a-policy-module /agents/api-reference/openapi.yaml patch /control/v1/workspaces/{workspace_slug}/policy_modules/{name} Requires `manage_policy`. `name` is ignored on update; a module cannot be renamed while policies reference it. # Preview a draft policy Source: https://docs.kordio.io/api-reference/policy-previews/preview-a-draft-policy /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/policy_previews Evaluate a policy you have not saved against a synthetic action, and get back the decision it would produce. Nothing is persisted: no policy, no session, no intent, and no audit event. This is the call behind a "what would this do?" affordance in your own console. Requires only the `read` capability, deliberately. Previewing is not a mutation. `imports` resolve against the workspace's real saved modules, so you can preview a draft that builds on modules already in place. # List postings, tenant-wide Source: https://docs.kordio.io/api-reference/postings/list-postings-tenant-wide /ledger/api-reference/openapi.yaml get /ledger/v1/postings Cross-account list. Filter with `reconciled=true|false` to narrow to settled or open postings; pass `account=` to scope to one account. For per-account history with the same tags filter, use `GET /v1/accounts/:id/postings`. # Fetch a single run with its snapshot Source: https://docs.kordio.io/api-reference/reconciliation/fetch-a-single-run-with-its-snapshot /ledger/api-reference/openapi.yaml get /ledger/v1/reconciliation_runs/{id} # List historic reconciliation runs Source: https://docs.kordio.io/api-reference/reconciliation/list-historic-reconciliation-runs /ledger/api-reference/openapi.yaml get /ledger/v1/reconciliation_runs # Manually mark a posting as reconciled Source: https://docs.kordio.io/api-reference/reconciliation/manually-mark-a-posting-as-reconciled /ledger/api-reference/openapi.yaml post /ledger/v1/postings/{id}/reconciliations For ad-hoc cleanups when the automated matcher couldn't pair an item. Already-reconciled postings are returned untouched. # Run a reconciliation Source: https://docs.kordio.io/api-reference/reconciliation/run-a-reconciliation /ledger/api-reference/openapi.yaml post /ledger/v1/reconciliation_runs Match a snapshot of external items against unreconciled postings. Matching is per-currency, per-amount, with a default 24-hour `value_date` window. Optional `account_id` on each item narrows the candidate pool. The response surfaces three sets: `matched`, `unmatched_external` (items we couldn't pair), and `unmatched_internal` (postings in the time window that no external item claimed; only populated when `from`/`to` bound the query). Idempotent: matched postings get marked once. Items are stored as external transactions keyed by `(source, external_id)`. Re-running the same snapshot reports already-matched items in `matched` with their original attribution; nothing is double-marked. Items may carry `reference_rail`, `reference_kind`, and `reference_value` (all three or none). When the triple resolves to a transaction external ref, that posting is matched first with strategy `external_ref` (exact amount required). # Balance sheet (assets / liabilities / equity) Source: https://docs.kordio.io/api-reference/reports/balance-sheet-assets-liabilities-equity /ledger/api-reference/openapi.yaml get /ledger/v1/reports/balance_sheet Point-in-time balance sheet computed against `value_date`. Pass `?at=` for a historical view; omit for current. `currency` may be passed to scope the report to a single currency. # Cash flow over a period Source: https://docs.kordio.io/api-reference/reports/cash-flow-over-a-period /ledger/api-reference/openapi.yaml get /ledger/v1/reports/cash_flow Cash movement broken out by category over `[from, to)`. Uses `value_date`. # Funds segregation snapshot Source: https://docs.kordio.io/api-reference/reports/funds-segregation-snapshot /ledger/api-reference/openapi.yaml get /ledger/v1/reports/fund_segregation Per-currency totals of `client_held` vs. `custody_held` accounts plus a delta and a custody breakdown. Feeds regulator-style client-money reports (EMI, CASP, etc.). The platform itself does not interpret the classification beyond grouping. Classifications and custody tags are set by the customer on accounts or inherited from account templates. The default classification is `neutral`, so existing ledgers report an empty `by_currency` until accounts are tagged. On-demand only at v1: no snapshot history is kept (see Q2 of `docs/decisions/2026-05-27-platform-open-questions.md`). # Income statement (revenue / expense over a period) Source: https://docs.kordio.io/api-reference/reports/income-statement-revenue-expense-over-a-period /ledger/api-reference/openapi.yaml get /ledger/v1/reports/income_statement Revenue and expense totals over `[from, to)`. Both `from` and `to` are ISO 8601 instants and use `value_date` for inclusion. # Total reserved per currency per counterparty Source: https://docs.kordio.io/api-reference/reports/total-reserved-per-currency-per-counterparty /ledger/api-reference/openapi.yaml get /ledger/v1/reports/reserves_outstanding Sums the posted balance of every `account_kind = "reserve"` account in the ledger, grouped by `(counterparty_ref, currency)`. Empty when no reserves exist. # Trial balance as of a timestamp Source: https://docs.kordio.io/api-reference/reports/trial-balance-as-of-a-timestamp /ledger/api-reference/openapi.yaml get /ledger/v1/reports/trial_balance Every account's balance, with per-currency debit/credit totals. A healthy ledger has `totals_by_currency[X].residual == 0` for every currency. The `healthy` boolean rolls this up. Uses `value_date` for the cutoff. Pass `?at=` for a historical view; omit for current. # Claw funds from a reserve into an operator account Source: https://docs.kordio.io/api-reference/reserves/claw-funds-from-a-reserve-into-an-operator-account /ledger/api-reference/openapi.yaml post /ledger/v1/reserves/{id}/claw Books a balanced transaction debiting the reserve and crediting `operator_account_id`. Used when the held-back funds are forfeited to the operator (e.g. a chargeback lost by the merchant, an expired escrow window). The `reason_code` is persisted in transaction metadata for audit. # Release funds from a reserve to a target account Source: https://docs.kordio.io/api-reference/reserves/release-funds-from-a-reserve-to-a-target-account /ledger/api-reference/openapi.yaml post /ledger/v1/reserves/{id}/release Books a balanced transaction debiting the reserve and crediting `target_account_id`. The target need not be the original source. Idempotent on `Idempotency-Key`. # Sweep funds into a reserve account Source: https://docs.kordio.io/api-reference/reserves/sweep-funds-into-a-reserve-account /ledger/api-reference/openapi.yaml post /ledger/v1/reserves Creates a reserve account (if it doesn't yet exist) for the `(template, counterparty_ref, currency)` triple and books a balanced transaction that debits the source account and credits the reserve. Reserves model holdbacks, escrow, FX holds, and any other case where unrestricted funds need to be earmarked for a named counterparty. Listing and balance reads use the standard `/v1/accounts` surface (`?kind=reserve&counterparty_ref=`). The platform does NOT auto-release on `expires_at`; that's customer policy. # Create a source Source: https://docs.kordio.io/api-reference/sources/create-a-source /ledger/api-reference/openapi.yaml post /ledger/v1/sources A source names an external system you reconcile against (a PSP, bank, exchange). Per-source defaults (`default_strategy`, `default_window_seconds`, `default_tolerance_minor_units`, `default_account_id`) apply to source-scoped runs. Names are unique per ledger, lowercased. Creating a name that an inline `POST /v1/reconciliation_runs` already used implicitly promotes that source and applies the provided defaults. # Disable the source's inbound endpoint Source: https://docs.kordio.io/api-reference/sources/disable-the-sources-inbound-endpoint /ledger/api-reference/openapi.yaml delete /ledger/v1/sources/{id}/inbound # Enable or rotate the source's hosted inbound endpoint Source: https://docs.kordio.io/api-reference/sources/enable-or-rotate-the-sources-hosted-inbound-endpoint /ledger/api-reference/openapi.yaml post /ledger/v1/sources/{id}/inbound Mints an inbound URL and signing secret. The plaintext secret is returned once in this response and never again; calling again rotates both token and secret, invalidating the old pair immediately. Push payloads to the returned `inbound_url` signed with Kordio-Inbound-Signature: t=,v1= where `v1 = HMAC-SHA256(secret, ".")`. Timestamps more than 5 minutes off are rejected. The payload is `{"items": [...]}` (or one item object) with the same fields as the batch ingest endpoint; ingestion is idempotent the same way. The source's `kind` selects the payload adapter; `custom` uses this generic scheme. # Exclude an external transaction from matching Source: https://docs.kordio.io/api-reference/sources/exclude-an-external-transaction-from-matching /ledger/api-reference/openapi.yaml post /ledger/v1/external_transactions/{id}/ignore Marks an open row `ignored` (provider fees booked elsewhere, test rows). Idempotent on already-ignored rows. Matched rows are rejected with `invalid_state`; unmatch first. Emits `external_transaction.ignored`. # Fetch a source Source: https://docs.kordio.io/api-reference/sources/fetch-a-source /ledger/api-reference/openapi.yaml get /ledger/v1/sources/{id} # Fetch an external transaction Source: https://docs.kordio.io/api-reference/sources/fetch-an-external-transaction /ledger/api-reference/openapi.yaml get /ledger/v1/external_transactions/{id} # Hosted inbound push endpoint Source: https://docs.kordio.io/api-reference/sources/hosted-inbound-push-endpoint /ledger/api-reference/openapi.yaml post /ledger/v1/inbound/sources/{token} Unauthenticated except for the per-source HMAC signature (see the enable endpoint). Unknown or disabled tokens 404. Never runs matching; queue a run or rely on your scheduled runs. # Ingest external transactions (idempotent batch) Source: https://docs.kordio.io/api-reference/sources/ingest-external-transactions-idempotent-batch /ledger/api-reference/openapi.yaml post /ledger/v1/sources/{source_id}/external_transactions Stores up to 1000 external money-movement rows. Idempotent on `(source, external_id)`: re-submitting a row never mutates the stored copy and reports `replayed`. Invalid rows report `error` per item without blocking the rest. Amounts are integer minor units. `occurred_at` (alias `at`) is ISO 8601. `reference_rail`/`reference_kind`/`reference_value` must be provided together; they join against transaction external refs during matching. `raw` retains the provider payload. # List external transactions Source: https://docs.kordio.io/api-reference/sources/list-external-transactions /ledger/api-reference/openapi.yaml get /ledger/v1/external_transactions `status=open` is the break list. Filter by `source_id`, `currency`, and `from`/`to` on `occurred_at`. Newest first. # List reconciliation sources Source: https://docs.kordio.io/api-reference/sources/list-reconciliation-sources /ledger/api-reference/openapi.yaml get /ledger/v1/sources # Manually match an external transaction to postings Source: https://docs.kordio.io/api-reference/sources/manually-match-an-external-transaction-to-postings /ledger/api-reference/openapi.yaml post /ledger/v1/external_transactions/{id}/match The postings must be unreconciled, share the row's currency, and sum exactly to its amount; otherwise 422 with the residual in the hint. Records a match with strategy `manual` and emits `reconciliation.match_created`. # Match audit trail for an external transaction Source: https://docs.kordio.io/api-reference/sources/match-audit-trail-for-an-external-transaction /ledger/api-reference/openapi.yaml get /ledger/v1/external_transactions/{id}/matches Includes reversed matches (`reversed_at` set). # Run reconciliation for a source Source: https://docs.kordio.io/api-reference/sources/run-reconciliation-for-a-source /ledger/api-reference/openapi.yaml post /ledger/v1/sources/{source_id}/reconciliation_runs Draws open external transactions for the source (optionally bounded by `from`/`to` on `occurred_at`) and matches them. Strategy, window, and tolerance default from the source. Runs with at most 500 open items execute synchronously and return the full result. Larger runs return `status: queued` with empty arrays; poll `GET /v1/reconciliation_runs/{id}` and subscribe to `reconciliation.run_completed`. One queued or running run per source; a second request returns `run_in_progress` (409). Inline `items` are rejected here. # Undo a match Source: https://docs.kordio.io/api-reference/sources/undo-a-match /ledger/api-reference/openapi.yaml post /ledger/v1/external_transactions/{id}/unmatch Reopens the matched postings, stamps the match row `reversed_at` (kept for audit), returns the row to `open`, and emits `reconciliation.match_reversed`. # Update a source's defaults Source: https://docs.kordio.io/api-reference/sources/update-a-sources-defaults /ledger/api-reference/openapi.yaml patch /ledger/v1/sources/{id} # List spend tokens Source: https://docs.kordio.io/api-reference/spend-tokens/list-spend-tokens /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/spend_tokens Read-only. Tokens are minted on the agent side only. # Mint a spend token Source: https://docs.kordio.io/api-reference/spend-tokens/mint-a-spend-token /agents/api-reference/openapi.yaml post /control/v1/agent/spend_tokens A spend token is a single-use ceiling an agent mints against one of its own budgets and presents later on `POST /v1/agent/payment_intents` via `spend_token_id`. It only ever narrows. A token cannot widen a policy, raise a cap, or authorize something policy would refuse. When a payment cites one, the token is checked first, and if the token itself refuses, the policy engine never runs. Pin it to a `counterparty` when you know the payee in advance. That turns "this agent may spend $200" into "this agent may spend $200, once, to this vendor". # Read a spend token Source: https://docs.kordio.io/api-reference/spend-tokens/read-a-spend-token /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/spend_tokens/{id} # Capabilities, guarantees, and limits of this deployment Source: https://docs.kordio.io/api-reference/system/capabilities-guarantees-and-limits-of-this-deployment /ledger/api-reference/openapi.yaml get /ledger/v1/_meta/capabilities Self-describing contract surface. Hit once at boot to discover what's wired up, what the ledger promises, and what the hard limits are, instead of hardcoding assumptions. Three independent version fields: * `ledger_capabilities_version`: calendar-versioned shape of this document. Bumps when sections are added/renamed/removed. Pin against this if you parse the body. * `api_version`: the URL-prefix version (`v1`). Bumps on breaking changes to resource paths or shapes. * `release`: the running build. Useful for debugging; do not gate behavior on it. # Liveness + DB probe Source: https://docs.kordio.io/api-reference/system/liveness-+-db-probe /ledger/api-reference/openapi.yaml get /healthz # RFC 8414 authorization server metadata Source: https://docs.kordio.io/api-reference/system/rfc-8414-authorization-server-metadata /ledger/api-reference/openapi.yaml get /.well-known/oauth-authorization-server Discovery document for OAuth clients. Tells tooling where the token endpoint is, what grant types and scopes are supported, what signing algorithms we use. # Fetch an export Source: https://docs.kordio.io/api-reference/tenant/fetch-an-export /ledger/api-reference/openapi.yaml get /ledger/v1/exports/{id} Returns the export row. Poll until `status` is `ready`, then download from `download_urls` before `expires_at`. # Queue an async export of the tenant's data Source: https://docs.kordio.io/api-reference/tenant/queue-an-async-export-of-the-tenants-data /ledger/api-reference/openapi.yaml post /ledger/v1/exports Queues a background job that streams the tenant's data (accounts, transactions, postings, events, period_closes, reconciliation_runs, webhook_endpoints, with secrets stripped) into NDJSON files and returns signed `download_urls` valid for 7 days. Poll `GET /v1/exports/{id}` to wait for `status: "ready"`. Idempotent on `Idempotency-Key`: replaying the same key returns the original row (with header `idempotent-replayed: true`). # Redact tenant metadata and party references Source: https://docs.kordio.io/api-reference/tenant/redact-tenant-metadata-and-party-references /ledger/api-reference/openapi.yaml post /ledger/v1/tenants/me/anonymize Right-of-erasure. Wipes `metadata` on every transaction, posting, account, event, and webhook delivery payload owned by the tenant, and replaces party-reference keys (`counterparty_ref`, `sender_party_id`, `recipient_party_id`) with the literal string `REDACTED`. Postings, balances, value dates, currencies, and amounts remain. That is the financial substance retention law requires us to keep. See `docs/decisions/2026-05-27-platform-open-questions.md` (Q6) for the full rationale. Irreversible. All-or-nothing per tenant. Auth: requires `ledger:write` AND a bearer token issued in the last 5 minutes. A stale token returns `401 fresh_authentication_required`. # Commit pending postings Source: https://docs.kordio.io/api-reference/transactions/commit-pending-postings /ledger/api-reference/openapi.yaml post /ledger/v1/transactions/{id}/commit Finalizes any `pending: true` postings on a transaction. Idempotent on `Idempotency-Key`: replays return the original result without re-emitting events. # Create a transaction Source: https://docs.kordio.io/api-reference/transactions/create-a-transaction /ledger/api-reference/openapi.yaml post /ledger/v1/transactions Write a balanced set of postings. Replays of the same `Idempotency-Key` return the original transaction with status 200. Set `?dry_run=true` to validate without writing: no idempotency key required, no events emitted, no balance changes. # Create many transactions in one call Source: https://docs.kordio.io/api-reference/transactions/create-many-transactions-in-one-call /ledger/api-reference/openapi.yaml post /ledger/v1/transactions/bulk Each item carries its own `idempotency_key`. The header `Idempotency-Key` is ignored on this endpoint; bulk callers must inline keys. Returns a `bulk_result` with one entry per input in the same order. Status per entry: `created`, `replayed`, or `error`. On any failure the response status is `207 Multi-Status` (or `201` if every item succeeded). **Atomic mode is partial today.** `"atomic": true` flags the intent; failures are still surfaced per-item. Full rollback of prior successes is not implemented yet; reverse them manually if you need rollback semantics. We do not silently drop the request. # Get a transaction Source: https://docs.kordio.io/api-reference/transactions/get-a-transaction /ledger/api-reference/openapi.yaml get /ledger/v1/transactions/{id} # List transactions Source: https://docs.kordio.io/api-reference/transactions/list-transactions /ledger/api-reference/openapi.yaml get /ledger/v1/transactions # Look up a transaction by external reference Source: https://docs.kordio.io/api-reference/transactions/look-up-a-transaction-by-external-reference /ledger/api-reference/openapi.yaml get /ledger/v1/transactions/lookup Returns the transaction that previously recorded a given external reference (e.g. a blockchain tx hash, a custody deposit id, a settlement confirmation id). All three of `rail`, `kind`, `value` are required and form the lookup tuple. Use this to verify whether an external event has already been booked before deciding to write a new transaction. # Not allowed, the ledger is append-only Source: https://docs.kordio.io/api-reference/transactions/not-allowed-the-ledger-is-append-only /ledger/api-reference/openapi.yaml delete /ledger/v1/transactions/{id} Returns `405` with a hint pointing at `/reverse`. This is intentional: corrections must be auditable transactions, not silent deletes. # Refund a transaction (partial or full) Source: https://docs.kordio.io/api-reference/transactions/refund-a-transaction-partial-or-full /ledger/api-reference/openapi.yaml post /ledger/v1/transactions/{id}/refund Books an inverse transaction for the requested amount, scaling every leg of the original (including legs in other currencies) by `amount / gross_in(currency)`. Banker's rounding; residual on the largest leg per currency, so the new transaction is balanced per currency. `currency` is the base currency the caller is refunding. For single-currency originals it may be omitted and is inferred. For multi-currency originals it is **required**; omitting it returns `refund_currency_required` (422). Sum of prior refunds is tracked per currency: a 100% USDC refund does not block a later 100% BTC refund on a USDC+BTC original. Refunds that would exceed the original's remaining amount in the requested currency return `partial_refund_exceeds_original` (422). Idempotent on `Idempotency-Key`. # Reverse a transaction Source: https://docs.kordio.io/api-reference/transactions/reverse-a-transaction /ledger/api-reference/openapi.yaml post /ledger/v1/transactions/{id}/reverse Creates a new transaction with each posting's direction flipped and writes a bidirectional link via `reverses` / `reversed_by`. Idempotent on `Idempotency-Key`. # Update transaction metadata Source: https://docs.kordio.io/api-reference/transactions/update-transaction-metadata /ledger/api-reference/openapi.yaml patch /ledger/v1/transactions/{id} Metadata is the only mutable field on a transaction. Any other field returns `409 immutable_field`. To correct posted data, write a reversal. # Create a webhook endpoint Source: https://docs.kordio.io/api-reference/webhook-endpoints/create-a-webhook-endpoint /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/webhook_endpoints Requires `manage_policy`. The response carries `secret` exactly once. Store it immediately; if you lose it, rotate the endpoint. An empty `enabled_events` array subscribes to **every** event type. Name the ones you handle instead. # Delete a webhook endpoint Source: https://docs.kordio.io/api-reference/webhook-endpoints/delete-a-webhook-endpoint /agents/api-reference/openapi.yaml delete /control/v1/workspaces/{workspace_slug}/webhook_endpoints/{id} Requires `manage_policy`. # List webhook endpoints Source: https://docs.kordio.io/api-reference/webhook-endpoints/list-webhook-endpoints /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/webhook_endpoints # Read a webhook endpoint Source: https://docs.kordio.io/api-reference/webhook-endpoints/read-a-webhook-endpoint /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/webhook_endpoints/{id} # Rotate a signing secret Source: https://docs.kordio.io/api-reference/webhook-endpoints/rotate-a-signing-secret /agents/api-reference/openapi.yaml post /control/v1/workspaces/{workspace_slug}/webhook_endpoints/{id}/rotate Requires `manage_policy`. Returns a new `secret`, once. The previous secret stops verifying immediately. # Count failed deliveries for an endpoint Source: https://docs.kordio.io/api-reference/webhooks/count-failed-deliveries-for-an-endpoint /ledger/api-reference/openapi.yaml get /ledger/v1/webhook_endpoints/{id}/deliveries/failed_count Returns the count of deliveries that exhausted their retries (`status == failed`) for this endpoint. `since` accepts either an ISO-8601 timestamp or a relative duration (`24h`, `7d`, `1h`). Unparseable values are ignored. # Enqueue a synthetic test delivery Source: https://docs.kordio.io/api-reference/webhooks/enqueue-a-synthetic-test-delivery /ledger/api-reference/openapi.yaml post /ledger/v1/webhook_endpoints/{id}/test_send Creates a `webhook_delivery` row for `:id` carrying a synthetic event. The synthetic event is NOT persisted to `/v1/events`; test sends shouldn't pollute the durable event tail subscribers consume. The DeliveryWorker delivers it like any other. `event_type` defaults to `"webhook.test"`. `payload` defaults to `{"ping": true, "test": true}`. Both are optional. # Fetch a webhook delivery Source: https://docs.kordio.io/api-reference/webhooks/fetch-a-webhook-delivery /ledger/api-reference/openapi.yaml get /ledger/v1/webhook_deliveries/{id} # Get a webhook endpoint Source: https://docs.kordio.io/api-reference/webhooks/get-a-webhook-endpoint /ledger/api-reference/openapi.yaml get /ledger/v1/webhook_endpoints/{id} # List recent deliveries for an endpoint Source: https://docs.kordio.io/api-reference/webhooks/list-recent-deliveries-for-an-endpoint /ledger/api-reference/openapi.yaml get /ledger/v1/webhook_endpoints/{id}/deliveries Returns the recent webhook deliveries for `:id`, newest-first, with full request/response detail so an integrator can debug a failing handler without DB access. `request_headers` is sanitized: any header containing `authorization`, `secret`, or `cookie` is redacted. The `Kordio-Signature` header is preserved (HMAC, not the key) so the value can be verified. # List webhook endpoints Source: https://docs.kordio.io/api-reference/webhooks/list-webhook-endpoints /ledger/api-reference/openapi.yaml get /ledger/v1/webhook_endpoints # Re-enqueue a delivery Source: https://docs.kordio.io/api-reference/webhooks/re-enqueue-a-delivery /ledger/api-reference/openapi.yaml post /ledger/v1/webhook_deliveries/{id}/redeliver Inserts a NEW `webhook_delivery` row referencing the same event + endpoint. The source row is not modified. The DeliveryWorker picks up the new row on its next tick. Replaying the same `Idempotency-Key` returns the original new row. # Register a webhook endpoint Source: https://docs.kordio.io/api-reference/webhooks/register-a-webhook-endpoint /ledger/api-reference/openapi.yaml post /ledger/v1/webhook_endpoints The response includes `signing_secret`, the **only** time it is returned. Store it before discarding the response. # Remove an endpoint Source: https://docs.kordio.io/api-reference/webhooks/remove-an-endpoint /ledger/api-reference/openapi.yaml delete /ledger/v1/webhook_endpoints/{id} # Rotate the signing secret Source: https://docs.kordio.io/api-reference/webhooks/rotate-the-signing-secret /ledger/api-reference/openapi.yaml post /ledger/v1/webhook_endpoints/{id}/rotate_secret Mints a new signing secret and returns the plaintext **once**. The previous secret remains valid for inbound signature verification for 24 hours after rotation, then is destroyed (sweeper job). Outgoing deliveries sign with the current secret only; Kordio does not dual-sign. Re-rotating before the prior overlap window closes is rejected with `rotation_in_progress` (409) to prevent a 3-key chain. Body accepts no params today; `Idempotency-Key` header supported. # Update endpoint settings Source: https://docs.kordio.io/api-reference/webhooks/update-endpoint-settings /ledger/api-reference/openapi.yaml patch /ledger/v1/webhook_endpoints/{id} # Create a workspace Source: https://docs.kordio.io/api-reference/workspaces/create-a-workspace /agents/api-reference/openapi.yaml post /control/v1/workspaces The caller becomes its `owner`. # Delete a workspace Source: https://docs.kordio.io/api-reference/workspaces/delete-a-workspace /agents/api-reference/openapi.yaml delete /control/v1/workspaces/{workspace_slug} Requires the `manage_members` capability. You must echo the slug back in `confirm`. # Export a workspace Source: https://docs.kordio.io/api-reference/workspaces/export-a-workspace /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug}/export A full JSON dump of the workspace: agents, policies, policy modules, budgets, spend tokens, action and payment intents, audit events, memberships, webhook endpoints, entitlement grants and the subscription. Requires `manage_members`. # List your workspaces Source: https://docs.kordio.io/api-reference/workspaces/list-your-workspaces /agents/api-reference/openapi.yaml get /control/v1/workspaces Every workspace the caller is a member of. This is the one list on the control plane that is not paginated. # Read a workspace Source: https://docs.kordio.io/api-reference/workspaces/read-a-workspace /agents/api-reference/openapi.yaml get /control/v1/workspaces/{workspace_slug} # Changelog Source: https://docs.kordio.io/changelog Updates and breaking changes across both Kordio APIs. ## Money is now a JSON string everywhere Every monetary field in the Kordio API (amounts, balances, and report totals) is now serialized as a **decimal string of integer minor units** matching `^-?\d+$`, for example `"100"`, `"25500000"`, or `"1000000000000000001"`. This is a breaking correctness fix. The wire format was previously inconsistent: posting `amount` was a string, but balances and report totals (`posted`, `pending`, `available`, trial-balance and statement totals, and so on) were JSON numbers. A JSON `number` silently loses precision above `2^53`, which is only about `0.009` ETH at 18 decimals, so high-value or 18-decimal token balances could come back wrong. Making every money field a string removes that whole class of corruption. There is no live customer, so this lands directly in v1 with no deprecation window. ### Before ```json theme={"dark"} { "object": "balance", "posted": 9700000, "pending": 0, "available": 9700000 } ``` ### After ```json theme={"dark"} { "object": "balance", "posted": "9700000", "pending": "0", "available": "9700000" } ``` ### What you need to do Parse every money field with a big-integer or arbitrary-precision decimal type, not `Number`: ```diff theme={"dark"} - const posted = balance.posted; // JS number, lossy above 2^53 + const posted = BigInt(balance.posted); // exact ``` Writes are unaffected for senders: `amount` still accepts an integer **or** a decimal string on the way in. Reads always return a string. The per-currency `currency_decimals` field (an integer count, not money) is unchanged, so you keep formatting display values the same way. # Kordio documentation Source: https://docs.kordio.io/index Two APIs on one host. Pick the one you are integrating. Kordio is the financial control plane: the rules and the record for money your software moves. Control decides what is allowed before it happens, and Ledger records what did. They are two APIs on one host, sharing an account and a set of test-mode credentials, and you can use either one on its own. Your software asks before it spends. You get `allowed`, `requires_approval`, or `denied` in the same request, naming the rule that decided, plus a signed grant your executor can verify without trusting the caller that carries it. Kordio Control, in early access. **Start here if** something other than a person can start a payment or a paid API call on your behalf. Double-entry accounting over HTTP. Post balanced transactions, read balances and statements at any instant, and reconcile against the outside world. Debits equal credits per currency or the write is rejected. **Start here if** you need an auditable record of what money meant, separate from whatever moved it. ## The call each one is about One call from each, so you can recognize which one you need. ```bash Kordio Control theme={"dark"} curl -X POST https://api.kordio.io/control/v1/agent/actions \ -H "Authorization: Bearer $KORDIO_AGENT_KEY" \ -H "Idempotency-Key: order-4471" \ -d '{"budget_id":"3f1c...","action_type":"payment.create","cost_cents":12000}' # 201 allowed, 202 requires_approval, 403 denied ``` ```bash Ledger theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/transactions \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Idempotency-Key: invoice_001" \ -d '{"postings":[ {"account":"cash:usd","amount":"1000","currency":"USD","direction":"debit"}, {"account":"revenue","amount":"1000","currency":"USD","direction":"credit"}]}' ``` ## Which credential do I have? The most common way to arrive here is holding a string somebody else generated. | If you are holding | You want | | ---------------------------------- | --------------------------------------------------------------------------- | | A key starting `krt_` | [Kordio Control: runtime keys](/agents/authentication) | | A `client_id` and `client_secret` | [Ledger: OAuth client credentials](/ledger/authentication) | | A dashboard login and nothing else | [Getting your credentials](/agents/authentication#getting-your-credentials) | ## Using both? Start with spend control. Where the ledger is enabled, the reservations it takes are mirrored into the books as balanced postings: each workspace owns its books and each agent owns an account inside them. You do not write those postings yourself, and you do not need to read the ledger docs to ship the control layer. Control decides what may happen; Ledger records what did. They are two API surfaces with their own authentication, which is why they have their own reference sections. Check **Billing** in the [console](https://app.kordio.io) for what your workspace has today, including whether the ledger projection is on. ## New to the problem, not the API? What sits between an agent and a payment rail, and who each half of this is for. Why a prompt, a hard-coded cap, and a card limit each stop short. # Ledger API Source: https://docs.kordio.io/ledger/api-reference/introduction Every ledger endpoint, generated from the OpenAPI specification. This reference is generated from the ledger [OpenAPI specification](/ledger/api-reference/openapi.yaml). Each endpoint page shows the request, parameters, response schema, and live examples. ## Base URL ``` https://api.kordio.io ``` OAuth lives at `/oauth/token`; ledger resources live under `/ledger/v1`. Looking for `/control/v1/agent/*`? Those belong to the other API on this host. See the [spend control API reference](/agents/api-reference/introduction). ## Authentication Every call carries a Bearer access token from the `client_credentials` grant. Reads need `ledger:read`; writes need `ledger:write`; period-close mutations need `ledger:period_close`. Scopes do not imply each other. See [Authentication](/ledger/authentication). ## Response envelope Single-resource responses wrap the object in `data` alongside `livemode` and `request_id`: ```json theme={"dark"} { "data": { "object": "account", "id": "cash:usd" }, "livemode": false, "request_id": "req_..." } ``` Every resource carries an `object` tag, and `request_id` is also returned as the `X-Request-Id` header. Quote it when contacting support. Lists are flat, with `data`, `has_more` and `next_cursor`. A `total` is present on some lists and absent on others, so treat it as optional. See [Pagination](/ledger/pagination). Failures carry `error.{code,message,hint,docs_url}`; see the [errors reference](/ledger/errors). ## CSV output Report endpoints also return CSV, via `?format=csv` or an `Accept: text/csv` header. If both are present, the header wins. Only read endpoints offer CSV. ## Discover before you hardcode `GET /v1/_meta/capabilities` reports the feature flags, hard limits, plan, tenant status and organization model in force for your tenant. Negotiate against it rather than baking limits into your client. ## Not on this API Some surfaces are deliberately dashboard-only, so that a leaked machine credential cannot use them: inviting members, changing roles, transferring ownership, and the 1-click connector onboarding flow. Connector *sync history* is readable at `GET /v1/sources/{id}/syncs`, but connecting, syncing and disconnecting are console operations. ## Next steps The shortest path through these endpoints. The other API on this host. # OAuth client credentials Source: https://docs.kordio.io/ledger/authentication Mint a token, pick scopes, and keep test and live apart. The ledger API uses the OAuth 2.0 `client_credentials` grant. A client has a `client_id`, a `client_secret` shown once, a mode (`test` or `live`), and a set of granted scopes. Integrating spend control instead? It uses agent keys and dashboard tokens, documented on [Kordio Control: agent keys and dashboard tokens](/agents/authentication). Nothing on this page applies there. ## Mint an access token Send your credentials as HTTP Basic auth, or as form fields. ```bash HTTP Basic theme={"dark"} curl -X POST https://api.kordio.io/oauth/token \ -u "$KORDIO_CLIENT_ID:$KORDIO_CLIENT_SECRET" \ -d 'grant_type=client_credentials&scope=ledger:read ledger:write' ``` ```bash Form body theme={"dark"} curl -X POST https://api.kordio.io/oauth/token \ -d 'grant_type=client_credentials' \ -d "client_id=$KORDIO_CLIENT_ID" \ -d "client_secret=$KORDIO_CLIENT_SECRET" \ -d 'scope=ledger:read ledger:write' ``` ```json 200 OK theme={"dark"} { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "scope": "ledger:read ledger:write" } ``` Mint on demand and cache until shortly before expiry. A token stored once and never refreshed becomes a dead integration within the hour. The token carries your tenant, mode, and scopes. There is no `?test=` parameter: the client's mode decides which dataset you touch. ## Scopes | Scope | Grants | | ---------------------- | ------------------------------------------------------------------------------------------------------------------- | | `ledger:read` | Read accounts, balances, transactions, postings, events, reports | | `ledger:write` | Create, patch, reverse, commit and refund transactions and accounts; manage webhook endpoints, sources and reserves | | `ledger:period_close` | Close and reopen accounting periods | | `ledger:clients:read` | List and inspect OAuth clients (never returns secrets) | | `ledger:clients:write` | Create, rotate and delete OAuth clients | Rate limits are per client and per class: 100 reads a second and 20 writes a second, answered with `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`, and a `Retry-After` on a `429`. **Scopes do not imply each other.** `ledger:write` does not grant `ledger:read`. A client that both lists and creates needs both scopes named explicitly in the token request. This is the most common cause of an unexpected `403` on a first integration. Reading period closes needs only `ledger:read`; only the mutations need `ledger:period_close`. A token missing the scope an endpoint requires returns `403` with code `insufficient_scope`, plus a `WWW-Authenticate` header naming the scope it wanted. ## Managing clients Clients are self-service, with their own scopes: ```bash theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/oauth_clients \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{"name": "billing worker", "scopes": ["ledger:read", "ledger:write"]}' ``` Secrets are shown in plaintext exactly once, at creation or rotation; only a SHA-256 hash is stored. Rotating with `POST /v1/oauth_clients/{id}/rotate_secret` keeps the **previous secret valid for 24 hours**, so you can roll a deployment without downtime. Rotating again inside that window returns `409 rotation_in_progress`; pass `?force=true` to destroy the old secret immediately. ## Discovery The authorization server publishes RFC 8414 metadata at `GET /.well-known/oauth-authorization-server`, so tooling can discover the token endpoint, grants, scopes and signing algorithms without hard-coding them. Token-endpoint failures follow RFC 6749: `invalid_client`, `invalid_grant`, `invalid_scope`, `unsupported_grant_type`. ## Test and live Every client is bound to one mode and the two never mix. Live and test data are segregated at the storage level, so a test client cannot read or write live rows. Responses echo `livemode` so you can confirm which dataset you touched: ```json theme={"dark"} { "data": { "object": "account", "id": "cash:usd" }, "livemode": false, "request_id": "req_..." } ``` Mode is a property of the **ledger**, not the organization. One organization can hold several ledgers, and each carries its own mode. See `GET /v1/ledgers`. ## Step-up authentication One operation requires more than a valid token. `POST /v1/tenants/me/anonymize` needs `ledger:write` **and** a token issued within the last five minutes, or it returns `401 fresh_authentication_required`. Mint a fresh token immediately before calling it. ## Next steps Use the token you just minted. Every code the ledger returns, with hints. # Ledger concepts Source: https://docs.kordio.io/ledger/concepts Double-entry, corrections, idempotency, multi-currency, value dates. The ledger has one correctness rule and a handful of consequences that follow from it. Everything below is one of those consequences. ## Double-entry, balanced per currency Every transaction is a set of postings that move together. A posting names an account, an amount, a currency, and a direction (`debit` or `credit`). The ledger accepts a transaction only when its debits equal its credits in every currency it touches: ``` sum(debits) == sum(credits) for each currency ``` This is the entire correctness model. There is no other validation of whether a transaction "makes sense", because the balance rule is what makes a double-entry ledger trustworthy. A transaction that does not balance is rejected with `unbalanced` (`422`). Accounts carry one of five accounting types: `asset`, `liability`, `revenue`, `expense`, or `equity`. The type is informational for reporting; the balance rule applies regardless of type. ### Integer minor units Amounts are integers in the currency's smallest unit: cents for `USD`, satoshis for `BTC`, the base unit for a stablecoin. Floats are rejected at the schema. This removes rounding ambiguity from the wire format. Each response reports `currency_decimals` so you can format the value for display. The ledger does not police the currency symbol. Post in one it does not recognize and the write succeeds, but the response carries `unknown_currency: true` and a null `currency_decimals`, which means nothing can format it for you. Display the integer as it stands until you know the scale. **Money is a JSON string, not a number.** Every monetary field (amounts, balances, and report totals) is serialized as a decimal string of integer minor units, for example `"9700000"` or `"1000000000000000001"`, matching `^-?\d+$`. This is deliberate: an 18-decimal token can exceed `2^53`, where a JSON `number` silently loses precision. Parse every money field with a big-integer or arbitrary-precision decimal type, never with a JS `number` or `parseInt`. On write, `amount` still accepts an integer or a decimal string; reads always return a string. ## Append-only and corrections Postings are never edited. The economic columns of a posting (amount, direction, currency, account) are immutable once written. You do not "fix" a transaction in place; you post a new one that offsets it. There are two correction primitives: * **Reversal** undoes a transaction in full. `POST /v1/transactions/{id}/reverse` books an inverse transaction that references the original. The new transaction links back via `reverses`, and the original gains a `reversed_by` pointer. * **Refund** offsets a transaction partially or fully. `POST /v1/transactions/{id}/refund` books an inverse for the requested `amount`, proportionally scaling each leg so the result still balances per currency. Scaling uses banker's rounding and puts any residual minor unit on the largest leg, so a refund of a third never leaks a cent. A reversal also moves the original's `status` to `archived`. It stays readable and still counts toward balances alongside its reversal; `archived` only tells you it has been undone. Transaction `metadata` is the one mutable surface, changed with `PATCH /v1/transactions/{id}`, which merges by default. Pass `merge: false` to replace the object. The postings themselves stay frozen. There is no delete: `DELETE /v1/transactions/{id}` answers `405`. Because history is append-only, the events tail is your audit log. Nothing is silently rewritten, so you can always replay what happened. ## Idempotency Every write accepts an `Idempotency-Key` header. The key, scoped to your ledger, maps to exactly one transaction forever. Replaying a request with the same key returns the original transaction with a `200` and an `Idempotent-Replayed: true` header, instead of writing a duplicate. Keys match `^[A-Za-z0-9_:.-]+$` and are capped at 255 bytes. ```bash theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/transactions \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: invoice_001" \ -d '{"postings":[ ... ]}' ``` Use a key that is unique per logical operation (an invoice id, a job id), not per HTTP attempt. Retries of the same logical write should reuse the key. A write without an idempotency key is rejected with `missing_idempotency_key` (`422`). The key is matched on its own. Nothing compares the body you sent this time to the body that created the transaction, so reusing a key with different postings returns the first transaction and writes nothing, quietly. A different economic event needs a different key. To validate a transaction without writing it, pass `?dry_run=true`. A dry run needs no idempotency key, emits no events, and changes no balances; it returns a summary telling you whether the postings balance. ## Multi-currency Currency is a first-class primitive, not an afterthought. Account currency is chosen at creation and immutable. A transaction may touch several currencies at once; the balance rule applies independently per currency. When a transaction spans more than one currency (for example moving value through an FX leg), the ledger records the exchange-rate snapshot on the transaction so the rate is preserved for audit and replay. Downstream reports read that recorded rate rather than recomputing from current market data. Operations that need a per-currency contract take a `currency` argument explicitly. A refund of a multi-currency transaction **requires** `currency` to disambiguate which leg you are refunding; omitting it returns `refund_currency_required` (`422`). The platform never silently falls back to "the original's currency". ## Value-date semantics Each posting has a `value_date`: the instant the movement is economically effective. Point-in-time balance and statement queries use `value_date`, not the time the row was inserted. Read a historical balance by passing `?at=` on the balance endpoint: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/accounts/cash:usd/balance?at=2026-04-15T00:00:00Z" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` This computes the balance as of that instant from each posting's `value_date`. Account statements work the same way: `GET /v1/accounts/{id}/statement?from=...&to=...` returns the opening balance, every posting in the window ordered by `value_date`, and the closing balance. ## Next steps Cursor pagination and inlining related objects. Event delivery, signatures, and replay. Every error code, with hints. Every endpoint, generated from the spec. # Errors Source: https://docs.kordio.io/ledger/errors Every error code the ledger returns, with its status and a hint. Failures return a machine-readable `code`, a human `message`, an actionable `hint`, and a `docs_url` linking to the matching anchor on this page. Some errors add a `param` naming the offending field and a typed `details` map. ```json theme={"dark"} { "error": { "code": "unbalanced", "message": "transaction does not balance", "hint": "debits must equal credits per currency in the transaction", "docs_url": "https://docs.kordio.io/ledger/errors#unbalanced" }, "livemode": false, "request_id": "req_..." } ``` Switch on `code`. It is stable across versions. Do not parse `message`; it is for humans and may change. Where a code has no explicit status of its own, it answers `422`, so treat `422` as the general "understood but cannot be applied" rather than as one specific fault. Kordio Control returns a different envelope and a different set of codes. See [Kordio Control: errors](/agents/errors). ## General ### invalid\_request `422` - The payload is malformed or missing required fields. When a specific field is at fault, `param` and `details.fields` identify it. ### unauthorized `401` - No valid access token was presented. Include a Bearer token from `POST /oauth/token`. ### forbidden `403` - The token is valid but not permitted to perform this operation. ### insufficient\_scope `403` - The token lacks the scope this endpoint requires. Scopes do not imply each other: `ledger:write` does not grant `ledger:read`. Re-request the token with both. See [Scopes](/ledger/authentication#scopes). ### not\_found `404` - The resource does not exist. Verify the id and that it belongs to your tenant and ledger. ### rate\_limited `429` - Back off per the `Retry-After` header and retry. ### internal\_error `500` - Unexpected. Retry; if it persists, contact support. ## Write semantics ### missing\_idempotency\_key `422` - A write was sent without the required `Idempotency-Key` header. Supply a key unique per logical request. See [Idempotency](/ledger/concepts#idempotency). ### unbalanced `422` - The transaction's debits do not equal its credits in some currency. See [Double-entry](/ledger/concepts#double-entry-balanced-per-currency). ### currency\_mismatch `422` - A posting's currency does not match the account it targets. Every posting must use its account's currency. ### unknown\_account `422` - A posting references an account that does not exist. Create it before posting against it. ### already\_exists `409` - A resource with the same identifier or idempotency key already exists. Pick a different id, or patch the existing resource. ### already\_reversed `409` - The transaction has already been reversed. Fetch it and inspect `reversed_by`. ### immutable\_field `409` - You tried to change a field that cannot change after creation, such as a posting's economic columns or an account's currency. ### insufficient\_funds `422` - The source account would exceed its overdraft policy. The write was not applied. ### account\_closed `409` - The posting targets a closed account. Reopen nothing: post to a different account, or correct the entry that closed it. ### account\_balance\_nonzero `409` - You tried to close an account whose posted or pending balance is not zero. Move the remaining value out first. ### period\_closed `409` - The `value_date` falls in a closed period. Book into the current open period, or reopen the period. ### period\_close\_imbalanced `422` - The trial balance at `period_end` does not net to zero in some currency, so the period was not closed. `details.residual_by_currency` names the gap. Fix it, or close with `force: true`, which records who forced it. ### precondition\_failed `409` - An `If-Match` or `If-Unmodified-Since` precondition was not satisfied. ### duplicate\_external\_ref `409` - An `external_ref` with this `(rail, kind, value)` is already attached to another transaction. ### partial\_refund\_exceeds\_original `422` - The refund amount plus prior partial refunds in this currency exceeds the original gross. See `details.remaining_by_currency`. ### refund\_currency\_required `422` - The original transaction is multi-currency, so you must pass `currency` to disambiguate which leg you are refunding. See [Multi-currency](/ledger/concepts#multi-currency). ### account\_template\_unknown `422` - The referenced account template does not exist. Create it first via `POST /v1/account_templates`, or omit `template` to use raw account fields. ### invalid\_state `409` - The resource is not in a state that permits this operation. ### run\_in\_progress `409` - A reconciliation run for this source is already queued or running. One at a time per source. Wait for `reconciliation.run_completed`. ## Credentials and lifecycle ### rotation\_in\_progress `409` - The previous secret is still inside its 24-hour overlap window. Wait, or pass `?force=true` to destroy it now. ### webhook\_endpoint\_disabled `409` - The endpoint is disabled. Re-enable it via `PATCH /v1/webhook_endpoints/{id}` before sending. ### fresh\_authentication\_required `401` - This destructive operation requires a token issued within the last five minutes. Mint a fresh one and retry. ### tenant\_suspended `403` - Your tenant is suspended. Contact support. ### plan\_required `402` - Your plan does not include this operation. Check **Billing** in the console. ## OAuth These follow RFC 6749 section 5.2 at the token endpoint. ### invalid\_client `401` - The `client_id` or `client_secret` is wrong, or the client is disabled. ### invalid\_grant `422` - The `grant_type` or its parameters are invalid. ### invalid\_scope `422` - The requested scope is not granted to this client. ### unsupported\_grant\_type `422` - Only `client_credentials` is supported today. ## Next steps The rules these codes enforce. Which codes each endpoint can return. # Feeds Source: https://docs.kordio.io/ledger/feeds Ingest external money movement and work the break queue. A feed is a recurring stream of external money movement (a PSP export, a bank statement, exchange withdrawals) that you reconcile against the ledger. Two resources model it: * A `source` names the external system and carries matching defaults. * An `external_transaction` is one stored row from that system, with a status: `open`, `matched`, or `ignored`. The ledger never connects to your providers and never holds their credentials. You push rows in, by API call or by pointing a webhook at the hosted inbound endpoint. ## Create a source ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "stripe", "default_strategy": "exact", "default_window_seconds": 86400, "default_tolerance_minor_units": 0, "default_account_id": "cash:usd" }' ``` Names are unique per ledger and lowercased. `default_account_id` scopes matching to one account for rows that do not carry their own `account_id`. A name already used by an inline `POST /v1/reconciliation_runs` exists as an implicit source; creating it explicitly promotes it and applies your defaults. ## Ingest rows ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/external_transactions" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "items": [ { "external_id": "txn_1OqIJq", "amount": "1000000", "currency": "USD", "occurred_at": "2026-05-14T09:00:00Z", "reference_rail": "stripe", "reference_kind": "charge", "reference_value": "ch_3NqXcd", "raw": { "fee": 30, "type": "charge" } } ] }' ``` Up to 1000 items per request. Ingestion is idempotent on `(source, external_id)`: a re-pushed row never mutates the stored copy and reports `replayed`. Invalid rows report `error` per item without blocking the rest. Amounts are integer minor units, sent as a JSON string (an integer is also accepted on write) and always returned as a string. Parse money with a big-integer or decimal type, never a JS `number`. `raw` retains the provider payload for audit. `reference_rail`, `reference_kind`, and `reference_value` must be provided together. When the triple resolves to a [transaction external ref](/ledger/api-reference/introduction), matching pairs that transaction's posting first, exactly, with strategy `external_ref`. Write the same triple on both sides when you book the internal transaction and reconciliation stops depending on amount heuristics. ## Run reconciliation per source ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/reconciliation_runs" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "from": "2026-05-14T00:00:00Z", "to": "2026-05-15T00:00:00Z" }' ``` The run draws the source's `open` rows in the window. Strategy, window, and tolerance default from the source. Matching passes run in order: `external_ref`, then `exact`, then `sum_in_window` when requested. Runs with at most 500 open rows execute synchronously and return the full result. Larger runs return `status: queued`; a worker executes them. Poll `GET /v1/reconciliation_runs/{id}` or subscribe to `reconciliation.run_completed`. One queued or running run per source; a second request returns `run_in_progress`. ## Work the break queue ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/external_transactions?status=open&source_id={id}" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` `status=open` after a run is your break list, durable across runs. Three actions resolve a break: * `POST /v1/external_transactions/:id/ignore` with a `reason`: the row should never match (provider fee booked elsewhere, test row). Emits `external_transaction.ignored`. * `POST /v1/external_transactions/:id/match` with `posting_ids`: manual attribution. The postings must be unreconciled, share the row's currency, and sum exactly to its amount; otherwise 422 with the residual in the hint. Emits `reconciliation.match_created`. * `POST /v1/external_transactions/:id/unmatch`: undo a match. Postings reopen, the match row is kept with `reversed_at` for audit, the row returns to `open`. Emits `reconciliation.match_reversed`. `GET /v1/external_transactions/:id/matches` is the audit trail, including reversed matches. ## Hosted inbound endpoint Instead of polling and pushing from a cron, mint a per-source push URL: ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/inbound" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` The response contains `inbound_url` and a one-time `inbound_secret`. Calling again rotates both; `DELETE` disables. Sign every push over the exact raw body: ```bash theme={"dark"} BODY='{"items":[{"external_id":"txn_1","amount":"1000000","currency":"USD","occurred_at":"2026-05-14T09:00:00Z"}]}' T=$(date +%s) SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //') curl -X POST "$INBOUND_URL" \ -H "Content-Type: application/json" \ -H "Kordio-Inbound-Signature: t=$T,v1=$SIG" \ -d "$BODY" ``` Timestamps more than 5 minutes off are rejected. Unknown or disabled URLs 404. The endpoint ingests with the same idempotency as the batch API and never runs matching; runs stay explicit. A source's `kind` selects the payload adapter; `custom` is this generic scheme, and provider-specific adapters slot in per source without an API change. Re-posting to the enable endpoint is idempotent and keeps the existing URL. Pass `{"rotate": true}` to mint a new token and secret, or `{"provider_secret": "..."}` to store a secret issued by the provider instead of a minted one; the response then carries no plaintext secret. ### Cobo Create the source with `kind: "cobo"` and Cobo's webhook public key, then paste the `inbound_url` into the Cobo console as a webhook endpoint. No signing secret is involved; the endpoint verifies Cobo's Ed25519 signature (`BIZ-TIMESTAMP` and `BIZ-RESP-SIGNATURE` headers) against the key. ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "cobo", "kind": "cobo", "metadata": { "cobo": { "public_key": "" } } }' ``` Only terminal success transaction callbacks ingest (status `Success`, `Succeeded`, or `Completed`); pending, confirming, and failed callbacks are acknowledged and skipped, as are non-transaction events. Deposits are positive, withdrawals negative. Amounts convert from Cobo's decimal asset units to integer minor units, and each row carries a reference triple (`reference_rail` is the chain, for example `eth`, with `reference_kind: "tx_hash"`), so external-ref matching works out of the box. Redeliveries of the same `transaction_id` report `replayed`. ## Recipe: reconcile Stripe payouts 1. Book your internal transaction with an external ref when the charge settles: `{ "rail": "stripe", "kind": "charge", "value": "ch_3NqXcd" }`. 2. Nightly, list Stripe balance transactions and push them: ```bash theme={"dark"} curl -s "https://api.stripe.com/v1/balance_transactions?limit=100" \ -u "$STRIPE_KEY:" | jq '{items: [.data[] | { external_id: .id, amount: .amount, currency: (.currency | ascii_upcase), occurred_at: (.created | todate), reference_rail: "stripe", reference_kind: "charge", reference_value: .source, raw: {fee: .fee, type: .type} }]}' | curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/external_transactions" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d @- ``` 3. Queue a run for the day and alert on `reconciliation.run_completed` when `unmatched_count > 0`. Re-running the script is safe; pages overlap and rows replay. The same mapping works from a Stripe webhook handler that forwards `balance.available` or `charge.succeeded` payloads to the inbound URL. ## Next steps Inline snapshot runs and the matching model. Event types and signature verification. Cursors on the external transactions list. Sources and external transactions endpoints. # Ledger API Source: https://docs.kordio.io/ledger/index A programmable double-entry system of record over HTTP. You model accounts, post balanced transactions, and read balances over a plain HTTP API. The ledger guarantees the accounting invariants; you write the business logic. You get primitives, not opinions, which is why a treasury startup, a marketplace, an FX desk and a SaaS company billing its own usage all build on the same four. From credentials to a posted transaction, in four calls. Double-entry, corrections, idempotency, multi-currency, value dates. ## The four primitives ### Account A named bucket of value in one currency. You choose the `id`, which may hold letters, digits, `_`, `:`, `.` and `-`, and the `currency`. Both are immutable once set. Accounts carry one of five accounting types (`asset`, `liability`, `revenue`, `expense`, `equity`), which are informational for reporting. ### Posting One line of a transaction. It says: this account moved by this amount, in this direction (`debit` or `credit`), in this currency, effective at this `value_date`. ### Transaction A set of postings that move together. The ledger enforces `sum(debits) == sum(credits)` per currency, and rejects anything that does not balance. That is the whole correctness model. There is no validation of whether a transaction "makes sense", because the balance rule is what makes a double-entry ledger trustworthy. ### Balance The net of an account's postings, now or at a historical instant. Derived from postings, never stored, and computed from `value_date` rather than insertion time. ## A balanced transaction ```json theme={"dark"} { "postings": [ { "account": "cash:usd", "amount": "1000", "currency": "USD", "direction": "debit" }, { "account": "revenue:subscriptions", "amount": "1000", "currency": "USD", "direction": "credit" } ] } ``` Monetary values cross the wire as JSON strings of integer minor units. [Parse them with a big-integer type](/ledger/concepts#integer-minor-units), never a JS `number`. ## What makes it safe Postings are never edited. You correct with a reversal or a refund that references the original. Every write carries an `Idempotency-Key`. A replay returns the original transaction. Currency is first class. No code path assumes one, and the balance rule applies per currency. Replayable runs that match an external snapshot against postings. ## Who uses this Anyone who needs an auditable record of what money meant, separate from whatever moved it. Kordio's own spend control is one such customer: where the projection is enabled, agent spend arrives here as balanced postings. The ledger itself knows nothing about agents. It speaks accounts, postings, transactions and balances, and it does not move money either. ## Next steps Versus Postgres, a processor, accounting software, and the other ledger APIs. Every endpoint, generated from the OpenAPI spec. # Invariants Source: https://docs.kordio.io/ledger/invariants What the ledger makes impossible, and the bug class each rule removes. Most systems store state and hope it stays correct. A ledger inverts that: it is built so that incorrect states cannot be represented at all. Each invariant below is a constraint that makes one kind of money corruption impossible, written as a guarantee followed by the bug class that becomes possible the moment the invariant does not hold. ## The root invariant: the ledger is always replayable There is one principle underneath all the others. The postings are the only source of truth, and every balance, statement, and report is a deterministic function of them. State is never authoritative on its own. It can always be thrown away and reconstructed by replaying the postings, and the reconstruction is always identical. If that holds, you can always answer "is this number real?" by recomputing it from the entries. Every other invariant on this page exists to keep the log clean enough that the replay is always exact: the entries must be immutable (so the past does not move), value must be conserved (so the total is meaningful), writes must be atomic and idempotent (so the log has no torn or duplicated entries), and history must be deterministic (so two replays agree). Lose replayability and the ledger stops being a system of record and becomes just another database you have to trust. The invariants below are grouped by what they protect: the shape of the log, the conservation of value, the way writes happen, and the ability to reconstruct and reconcile. ## Structural invariants: the shape of the log ### Entries are immutable and append-only A posting's economic meaning never changes once written. You correct by appending a reversal or refund that references the original, never by editing it. The economic columns (`amount`, `direction`, `currency`, `account_id`) are frozen by a `BEFORE UPDATE` trigger; only a commit-pending flag and the reconciliation fields may ever change. **What breaks if it fails:** the past becomes editable. An audit can no longer trust that an entry says today what it said when it was written, a dispute has no fixed record to point at, and replay produces a different history every time you run it. Append-only is what makes the log a record rather than a guess. ### Live and test data never interleave Each OAuth client is bound to one mode, and live and test data are segregated at the storage level. The mode of your token decides which dataset you touch. **What breaks if it fails:** test traffic contaminates real balances. A load test or a demo could inflate a production total, and you could no longer tell synthetic movements from real ones. ### Amounts are integer minor units, and currency is immutable Every amount is stored as an exact integer in the currency's smallest unit (cents, satoshis, or the base unit of an 18-decimal token); floats are rejected at the schema. An account's `currency` is set at creation and can never change. **What breaks if it fails:** floating point reintroduces sub-cent drift that accumulates and never reconciles, and a mutable currency would silently reinterpret every historical posting on the account, changing what past entries mean after the fact. The same exactness applies on the wire: every monetary field is serialized as a JSON string of integer minor units. [Parse them with a big-integer type](/ledger/concepts#integer-minor-units). ## Financial invariants: conservation of value These are the accounting laws, and between them they make value a conserved quantity: it moves, and it cannot appear or vanish. ### Debits equal credits, per currency Every transaction balances in every currency it touches. Value is only ever moved between accounts, never created or destroyed. This is checked in application code and again by deferred Postgres triggers that fire at `COMMIT`, so a multi-posting transaction is validated as a whole. **What breaks if it fails:** money is conjured or lost. The trial balance stops summing to zero, no total can be trusted, and you are left unable to prove that the funds you report actually exist. ### Balances are derived, never stored A balance is a function of the postings beneath it. There is no balance column. A hot account keeps a running total in memory as a cache, but the postings are always the authority; if the cache and the postings ever disagreed, the postings win. **What breaks if it fails:** a stored balance becomes a second source of truth that can drift from the entries it claims to summarize. You end up with two numbers that disagree and no principled way to say which is real. A derived balance cannot drift, because there is nothing to drift from. ```mermaid theme={"dark"} flowchart LR A[Balance stored as a column] --> B[Entries update but the cached total does not] B --> C[Stored balance drifts from its postings] C --> D[Two sources of truth disagree] D --> E[No way to tell which number is real] ``` ## Execution invariants: how writes happen ### Transactions are atomic A transaction and all of its postings commit together or not at all. The coordinator writes them inside a single database transaction; if any part fails, including the balance check at `COMMIT`, the whole write rolls back. **What breaks if it fails:** a half-written transaction lands, with some postings present and their counterparties missing. That single torn write violates conservation directly: the ledger no longer balances, and the gap is permanent. ```mermaid theme={"dark"} flowchart LR A[No atomicity] --> B[Some postings commit, others fail] B --> C[Transaction no longer balances] C --> D[Value created or destroyed] D --> E[Trial balance stops summing to zero] ``` ### Operations are idempotent Each `(ledger_id, idempotency_key)` maps to exactly one transaction forever, enforced by a unique index. A replay returns the original transaction and a replayed marker, and because the database enforces uniqueness, a race between two identical requests still yields exactly one transaction. **What breaks if it fails:** a retry under failure double-posts. This is the classic duplicate-charge bug: the network times out, the client retries, and the same economic event is recorded twice. ```mermaid theme={"dark"} flowchart LR A[No idempotency] --> B[Client retries after a timeout] B --> C[Same operation posts twice] C --> D[Balance inflated] D --> E[Reconciliation never ties out] ``` ### Writes to an account are serialized Every active account is served by a single process that serializes the writes to it, so concurrent operations on one account apply in a defined order rather than racing. **What breaks if it fails:** balance-dependent decisions race. Two concurrent debits could both read a sufficient balance and both succeed, driving a non-negative account below zero. Serialization is what makes "check the balance, then post" safe under concurrency. ## Reconciliation invariants: the log proves itself ### Replay is deterministic Recomputing balances and reports from the postings always produces the same result. This is the root invariant in practice, and it holds over the postings, which is why the postings are the thing to recompute from. **What breaks if it fails:** an audit run today and the same audit run tomorrow over unchanged data disagree. You can report a number but you cannot prove it, which is the one thing a system of record exists to do. The events stream (`GET /v1/events`) is a durable, replayable tail of state changes, and it is a weaker guarantee than the postings. An event is written just after its transaction commits rather than inside the same transaction, so a crash in that window can lose one event without losing the transaction. Rebuild a downstream view from events; settle a dispute from postings. ### Point-in-time history is stable Historical balances and statements are computed from each posting's `value_date`, when the movement is economically effective, not from when the row happened to be inserted. The same question at the same instant always returns the same answer. **What breaks if it fails:** "what was my balance on March 1" has no stable answer. Restating a period later, or inserting a backdated correction, would shift historical balances depending on insertion timing rather than economic date. ## Why this framing matters None of these is a feature you switch on. They are constraints that take whole categories of failure out of the space of things that can happen at all: no torn writes, no duplicated charges, no drifting balances, no editable history. You get to reason about your integration in terms of what the ledger makes impossible, which is a stronger position than trusting that it usually does the right thing. ## Next steps What you would have to build to enforce these invariants yourself. How value moves through accounts as balanced postings. The replay and audit invariants put to work. Double-entry, corrections, idempotency, multi-currency, value dates. # Money flows Source: https://docs.kordio.io/ledger/money-flows How value moves through accounts as balanced postings. Every movement of value in the ledger is a transaction made of balanced postings. A posting names an `account`, an `amount` in minor units, a `direction` (`debit` or `credit`), and a `currency`, and a transaction is valid only when its debits equal its credits in every currency it touches. The account ids below (`cash`, `revenue`, `assets:bank`, `fees`) are illustrative names you choose; the platform attaches no meaning to them. Amounts below are written as bare numbers for readability. On the wire every monetary value is a JSON string of integer minor units. [Parse them with a big-integer type](/ledger/concepts#integer-minor-units). ## A simple credit into one account The smallest transaction moves value between exactly two accounts. To record 10.00 USD of revenue, you debit `cash` and credit `revenue`. The amounts are equal, so the transaction balances. ```mermaid theme={"dark"} flowchart LR T["Transaction (USD)"] T -->|debit 1000| cash["cash"] T -->|credit 1000| revenue["revenue"] ``` | account | amount | direction | currency | | --------- | ------ | --------- | -------- | | `cash` | `1000` | `debit` | `USD` | | `revenue` | `1000` | `credit` | `USD` | Debits total `1000`, credits total `1000`. The write is accepted. ## A transfer between two accounts A transfer is the same shape: value leaves one account and lands in another. To move 25.00 USD from `cash` into `assets:bank`, credit the source and debit the destination. ```mermaid theme={"dark"} flowchart LR T["Transaction (USD)"] T -->|credit 2500| cash["cash"] T -->|debit 2500| bank["assets:bank"] ``` | account | amount | direction | currency | | ------------- | ------ | --------- | -------- | | `cash` | `2500` | `credit` | `USD` | | `assets:bank` | `2500` | `debit` | `USD` | The two accounts net out against each other and the transaction balances. ## A reversal You never edit a transaction to undo it. You append a reversal, which is a new transaction that posts the inverse of every leg and references the original. Reverse the simple credit above with `POST /v1/transactions/{id}/reverse`. ```mermaid theme={"dark"} flowchart LR O["Original (USD)"] R["Reversal (USD)"] O -->|debit 1000| cash["cash"] O -->|credit 1000| revenue["revenue"] R -->|credit 1000| cash R -->|debit 1000| revenue R -.reverses.-> O ``` The reversal's postings, the inverse of the original: | account | amount | direction | currency | | --------- | ------ | --------- | -------- | | `cash` | `1000` | `credit` | `USD` | | `revenue` | `1000` | `debit` | `USD` | After both transactions, the net effect on `cash` and `revenue` is zero. Both remain in history: the reversal links back via `reverses`, the original gains a `reversed_by` pointer, and the original's `status` moves to `archived`. Archived means undone, not hidden, so filter on it deliberately when you list transactions. ## A partial refund A refund offsets part of a transaction. `POST /v1/transactions/{id}/refund` books an inverse for the requested `amount`, scaling each leg proportionally so the result still balances per currency. Refund 4.00 USD of a 10.00 USD transaction that had a 1.00 USD fee. ```mermaid theme={"dark"} flowchart LR O["Original 1000 + 100 fee (USD)"] R["Refund 40% (USD)"] O -->|debit 1100| cash["cash"] O -->|credit 1000| revenue["revenue"] O -->|credit 100| fees["fees"] R -->|credit 440| cash R -->|debit 400| revenue R -->|debit 40| fees R -.refunds.-> O ``` The refund scales every leg by `400 / 1000`, rounds half to even, and puts any leftover minor unit on the largest leg, so the result still balances: | account | amount | direction | currency | | --------- | ------ | --------- | -------- | | `cash` | `440` | `credit` | `USD` | | `revenue` | `400` | `debit` | `USD` | | `fees` | `40` | `debit` | `USD` | Debits total `440`, credits total `440`. The fee leg is reversed in proportion, so a partial refund never leaves the fee account stranded. ## A multi-currency transaction A single transaction may touch more than one currency. The balance rule applies independently per currency: debits must equal credits within `USD` and, separately, within `EUR`. Record an FX leg that takes in 1000 minor units of `EUR` and pays out 1080 minor units of `USD`. ```mermaid theme={"dark"} flowchart LR T["Transaction (EUR + USD)"] T -->|credit 1000 EUR| eurbank["assets:bank:eur"] T -->|debit 1000 EUR| fx["fx:eur"] T -->|credit 1080 USD| fxusd["fx:usd"] T -->|debit 1080 USD| usdbank["assets:bank:usd"] ``` | account | amount | direction | currency | | ----------------- | ------ | --------- | -------- | | `assets:bank:eur` | `1000` | `credit` | `EUR` | | `fx:eur` | `1000` | `debit` | `EUR` | | `fx:usd` | `1080` | `credit` | `USD` | | `assets:bank:usd` | `1080` | `debit` | `USD` | `EUR` debits equal `EUR` credits, and `USD` debits equal `USD` credits, so the transaction balances. When a transaction spans currencies, the ledger records an FX snapshot on the transaction (`exchange_rate`, `base_currency`, `quote_currency`) at write time. Downstream reports read that recorded rate for audit and replay rather than recomputing from current market data. ## Next steps The rules behind these shapes, in prose. The guarantees that keep every transaction balanced. Post your first transaction in four calls. Every endpoint, generated from the spec. # Pagination and expand Source: https://docs.kordio.io/ledger/pagination Walk lists with cursors and inline related objects. Ledger lists page with cursors and return a flat envelope, and most of them can inline related objects instead of making you fetch them. Most, not all: the exceptions are named below, and they are the ones that will quietly truncate on you. ## List envelope Every list endpoint returns a flat envelope. The `data` array holds the page; `has_more` and `next_cursor` drive pagination. ```json theme={"dark"} { "object": "list", "data": [ { "object": "account", "id": "cash:usd", "type": "asset", "currency": "USD" }, { "object": "account", "id": "revenue:subscriptions", "type": "revenue", "currency": "USD" } ], "has_more": false, "next_cursor": null, "livemode": false, "request_id": "req_..." } ``` ## Cursor pagination Request a page, and if `has_more` is `true`, pass the `next_cursor` value back as the `cursor` parameter to get the next page. ```bash theme={"dark"} # First page curl "https://api.kordio.io/ledger/v1/transactions?limit=50" \ -H "Authorization: Bearer $KORDIO_TOKEN" # Next page curl "https://api.kordio.io/ledger/v1/transactions?limit=50&cursor=" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` The `limit` parameter defaults to `50`, with a minimum of `1` and a maximum of `200`, on transactions, accounts and events. Two posting lists differ: `GET /v1/postings` and `GET /v1/accounts/{id}/postings` default to `100` and allow up to `500`, and their cursor is a posting id rather than an opaque token. Read `next_cursor` and pass it back either way, and do not assume one limit across the API. Treat every cursor as opaque even where it currently looks like an id. Do not decode or construct one; the encoding is an implementation detail that may change between releases. A cursor is a position, not a row, so one pointing at a since-deleted resource still paginates correctly. Pass it back verbatim until the list reports `has_more: false`. A typical loop: ```bash theme={"dark"} cursor="" while :; do page=$(curl -s "https://api.kordio.io/ledger/v1/transactions?limit=200&cursor=$cursor" \ -H "Authorization: Bearer $KORDIO_TOKEN") # process page.data has_more=$(echo "$page" | jq -r '.has_more') [ "$has_more" = "true" ] || break cursor=$(echo "$page" | jq -r '.next_cursor') done ``` ### Lists that do not paginate `GET /v1/reconciliation_runs`, `GET /v1/webhook_endpoints` and `GET /v1/period_closes` always answer `has_more: false` and `next_cursor: null`, whatever `limit` you pass. Reconciliation runs cap at 200 and default to 50. That matters because the flag lies rather than erroring: a workspace with 300 runs sees 50 and a `has_more` of `false`. Narrow with filters rather than paging, and do not build a "fetch everything" loop on these three. ## Filtering lists List endpoints accept filters in the query string. The available filters depend on the resource. For example, list transactions by metadata: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/transactions?metadata[invoice]=inv_8721" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` Accounts can be filtered by `type`, `currency`, and other fields; events by `type` and time window. See each endpoint in the [API reference](/ledger/api-reference/introduction) for its filter set. ## Expanding related objects By default, a transaction's postings reference their account by `id`. Use `?expand=` to inline related objects in a single response instead of making follow-up calls. Two expansions are available: | Value | Effect | | ------------------ | --------------------------------------------------------------------- | | `postings.account` | Inlines each posting's full account object | | `balances` | Adds the post-commit balance of every account the transaction touched | `expand` is a comma-separated list: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/transactions/3061ec4e-c959-49ba-a0f6-99186a7bd5d8?expand=postings.account,balances" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` Expansion works on both single-resource reads and list endpoints, and is also accepted when creating a transaction so the create response can carry the inlined accounts and resulting balances. Kordio Control paginates differently: `starting_after` takes a record id rather than an opaque cursor, and its `has_more` can be `true` on a final full page. See the [spend control API reference](/agents/api-reference/introduction#pagination). ## Next steps Walking the events tail after an outage. The filter set on each list endpoint. # Post your first transaction Source: https://docs.kordio.io/ledger/quickstart From credentials to a posted transaction and a balance. Five calls take you from nothing to a posted transaction and a balance you can read back. Every one of them matches the [API reference](/ledger/api-reference/introduction). **Wrong page?** This is the ledger: accounts, postings, balances, reconciliation. If you are here to decide whether your software may spend before it does, start with [Kordio Control: authorize an agent action](/agents/quickstart). The base URL is `https://api.kordio.io`. OAuth lives at `/oauth/token`; ledger resources live under `/ledger/v1`. ## 1. Get your client credentials Create an OAuth client from the dashboard, or use one seeded for you in development. A client has a `client_id`, a `client_secret` (shown once), a mode (`test` or `live`), and a set of granted scopes. Read operations need `ledger:read`; writes need `ledger:write`, and neither implies the other. ## 2. Mint an access token Exchange your credentials for a short-lived token using the `client_credentials` grant. Send the credentials as HTTP Basic auth. ```bash theme={"dark"} export KORDIO_TOKEN=$(curl -s -X POST https://api.kordio.io/oauth/token \ -u "$KORDIO_CLIENT_ID:$KORDIO_CLIENT_SECRET" \ -d 'grant_type=client_credentials&scope=ledger:read ledger:write' \ | jq -r '.access_token') ``` ```json 200 OK theme={"dark"} { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "scope": "ledger:read ledger:write" } ``` The token carries your tenant, mode, and scopes, and is valid for one hour. There is no `?test=` flag: the client's mode decides whether you touch test or live data. See [Authentication](/ledger/authentication) for the full flow. ## 3. Create two accounts An account is a named bucket of value in one currency. You choose the `id`. Create one asset account and one revenue account, both in `USD`. ```bash theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/accounts \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{"id":"cash:usd","name":"Cash","type":"asset","currency":"USD"}' curl -X POST https://api.kordio.io/ledger/v1/accounts \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{"id":"revenue:subscriptions","name":"Subscriptions","type":"revenue","currency":"USD"}' ``` Each call returns the created account inside the standard envelope: ```json theme={"dark"} { "data": { "object": "account", "id": "cash:usd", "name": "Cash", "type": "asset", "currency": "USD", "currency_decimals": 2, "currency_kind": "fiat", "metadata": {}, "created_at": "2026-05-14T10:23:45.123456Z" }, "livemode": false, "request_id": "req_3LhM8XKx9q4hQv" } ``` ## 4. Post a balanced transaction A transaction is a set of postings that balance per currency. Move 10.00 USD (`1000` minor units) from cash into revenue. Writes require an `Idempotency-Key` so retries never double-post. ```bash theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/transactions \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: invoice_001" \ -d '{"postings":[ {"account":"cash:usd","amount":"1000","currency":"USD","direction":"debit"}, {"account":"revenue:subscriptions","amount":"1000","currency":"USD","direction":"credit"} ]}' ``` Amounts are JSON strings of integer minor units. [Parse them with a big-integer type](/ledger/concepts#integer-minor-units), never a JS `number`. The response includes the transaction and its postings: ```json theme={"dark"} { "object": "transaction", "id": "3061ec4e-c959-49ba-a0f6-99186a7bd5d8", "idempotency_key": "invoice_001", "reverses": null, "reversed_by": null, "metadata": {}, "postings": [ { "object": "posting", "account": "cash:usd", "amount": "1000", "currency": "USD", "direction": "debit", "pending": false }, { "object": "posting", "account": "revenue:subscriptions", "amount": "1000", "currency": "USD", "direction": "credit", "pending": false } ], "created_at": "2026-05-14T15:53:31.291591Z" } ``` Replaying the same `Idempotency-Key` returns this same transaction with a `200` and an `Idempotent-Replayed: true` header, instead of creating a new one. It returns the original whatever you sent the second time, so give a different transaction a different key. To validate a transaction without writing it, add `?dry_run=true` and omit the idempotency key. ## 5. Read the balance Balances are derived from the postings rather than stored, so this number is recomputed from what you just wrote: ```bash theme={"dark"} curl https://api.kordio.io/ledger/v1/accounts/cash:usd/balance \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` ```json 200 OK theme={"dark"} { "data": { "object": "balance", "account": "cash:usd", "currency": "USD", "currency_decimals": 2, "posted": "1000", "pending": "0", "available": "1000" }, "livemode": false, "request_id": "req_..." } ``` You can read a historical balance by passing `?at=`, which computes the balance from each posting's `value_date`. See [value-date semantics](/ledger/concepts#value-date-semantics). ## Next steps Double-entry, corrections, idempotency, multi-currency, and value dates. Subscribe to events, verify signatures, and replay from the events tail. Walk list endpoints with cursors and inline related objects. Every endpoint, generated from the OpenAPI spec. # Reconciliation Source: https://docs.kordio.io/ledger/reconciliation Match the books against the outside world, and prove it tied out. Reconciliation is the real problem most fintech teams are solving when they reach for a ledger. The questions are concrete and they come from finance, support, and engineering at once: * Why is this balance 1023.17? * Which transaction changed it? * What happened between date X and date Y? * Does it match an external system, such as an external processor or your bank statement? Each one is answered with the same primitives you already use to write. Because balances are derived from postings and history is append-only, every answer traces back to a durable record you can fetch. ## Why is this balance 1023.17? A balance is not a stored number that someone could have edited. It is derived from the account's postings, so you can always open it up and see the entries that produced it. List the postings on the account: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/accounts/cash:usd/postings" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` For a period view with opening and closing balances around the same postings, use the account statement: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/accounts/cash:usd/statement?from=2026-04-01T00:00:00Z&to=2026-05-01T00:00:00Z" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` The statement returns the opening balance at `from`, every posting in the window ordered by `value_date`, and the closing balance at `to`. The opening balance plus the postings always equals the closing balance, so the number is never a mystery. The statement does not paginate. It takes a `limit`, defaulting to 500 and capped at 5000, and reports `truncated: true` when it hit that limit, which is the only sign that entries are missing. Check the flag, and narrow the window rather than raising the limit. ## Which transaction changed it? Every posting belongs to exactly one transaction. The postings list and the account statement both carry the transaction reference for each entry, so you can go from "this line moved the balance" to "this transaction caused it" in one hop. Fetch the transaction to see all of its legs, its metadata, and any reversal links: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/transactions/{id}" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` Because corrections are new transactions rather than edits, a reversed or refunded transaction still shows in history with its `reverses` and `reversed_by` links intact. Nothing disappears. ## What happened between date X and Y? The account statement is the per-account answer. It bounds the postings by `value_date`, so a point-in-time question gets a point-in-time answer: the result is computed from when each movement was economically effective, not from when the row was inserted. ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/accounts/cash:usd/statement?from=2026-04-01T00:00:00Z&to=2026-04-15T00:00:00Z" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` For a tenant-wide, replayable view of everything that changed, read the durable events tail: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/events" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` Every successful write emits an event, and the list is replayable, so a consumer that fell behind can catch up from where it stopped. Together the statement (per account) and the events tail (tenant-wide) cover both "what did this account do?" and "what did the whole ledger do?" over a window. Treat the tail as the operational record and the postings as the authority. Events are written just after the transaction they describe commits, not inside it, so a process that dies in that window leaves a transaction with no event. Recomputing from postings always agrees with itself; replaying events is how you catch up, not how you audit. ## Does it match an external system? This is reconciliation proper: comparing your ledger against an external source of truth, such as an external processor or your bank statement. You bring a snapshot of external items, and the ledger matches them against your unreconciled postings. ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/reconciliation_runs" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "source": "acme_processor", "external_reference": "acme:2026-05-14", "from": "2026-05-14T00:00:00Z", "to": "2026-05-15T00:00:00Z", "items": [ { "external_id": "ext_abc", "amount": "1000000", "currency": "USD", "at": "2026-05-14T09:00:00Z" }, { "external_id": "ext_def", "amount": "500000", "currency": "USD", "at": "2026-05-14T14:00:00Z" } ] }' ``` Matching is per currency and per amount within a time window. The response surfaces three sets: `matched`, `unmatched_external` (items with no posting to pair), and `unmatched_internal` (postings in the window that no external item claimed). The unmatched sets are your break list. Every monetary value here is a JSON string of integer minor units. [Parse them with a big-integer type](/ledger/concepts#integer-minor-units). On write, `amount` also accepts an integer. Runs are replayable. Items are stored as external transactions keyed by `(source, external_id)`, so matched postings are marked once. A re-run of the same snapshot reports already-matched items in `matched` with their original attribution; nothing is double-marked. Fetch a past run with its full snapshot: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/reconciliation_runs/{id}" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` ## Durable feeds and breaks Inline snapshots work for one-off checks. For a recurring feed, create a source and ingest rows once; they persist with a status (`open`, `matched`, `ignored`) and `GET /v1/external_transactions?status=open` is your break list across runs. ```bash theme={"dark"} curl -X POST "https://api.kordio.io/ledger/v1/sources" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "stripe", "default_window_seconds": 86400 }' curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/external_transactions" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "items": [ { "external_id": "txn_1OqIJq", "amount": "1000000", "currency": "USD", "occurred_at": "2026-05-14T09:00:00Z" } ] }' curl -X POST "https://api.kordio.io/ledger/v1/sources/{id}/reconciliation_runs" \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "from": "2026-05-14T00:00:00Z", "to": "2026-05-15T00:00:00Z" }' ``` Ingestion is idempotent on `(source, external_id)`; re-pushed rows report `replayed`. Rows carrying a `reference_rail`/`reference_kind`/`reference_value` triple match their transaction's posting first (strategy `external_ref`), before amount heuristics run. Work the break list with `POST /v1/external_transactions/:id/ignore` (a row that should never match, with a reason), `/match` (manual attribution to postings that sum exactly to the row's amount), and `/unmatch` (undo; the match row is kept as audit). Each emits an event, so webhooks can drive a breaks workflow. See [Feeds](/ledger/feeds) for the full workflow, the hosted inbound push endpoint, and a Stripe recipe. For the comparison basis itself, the reports endpoints give you ledger-side totals to check against the external figures. Use the trial balance for per-currency debit and credit totals across every account: ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/reports/trial_balance?at=2026-05-14T23:59:59Z" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` The trial balance is computed from `value_date`, so an "as of" figure is reproducible. It reports `totals_by_currency` with a `residual` per currency and a top-level `healthy` boolean, which is true only when every residual is zero. Alert on `healthy`, not on your own subtraction. External systems named here, such as a processor or a bank, are your own integrations. The ledger is your system of record for what the money means; reconciliation is how you prove it agrees with the systems that moved it. ## Next steps Durable external feeds, the break queue, and the inbound push endpoint. Why balances are always derivable from postings. Drive a breaks workflow off `reconciliation.run_completed`. Every endpoint, generated from the spec. # Webhooks Source: https://docs.kordio.io/ledger/webhooks Subscribe to ledger events, verify signatures, and replay from the tail. Webhooks push a signed copy of every state-changing ledger event to an endpoint you control. The same payloads are also available to pull from the [events tail](#events-tail-and-replay), so you can choose push, pull, or both. Kordio Control events are a separate subscription, registered per workspace with a different event set and a different retry schedule. See [Kordio Control: webhooks](/agents/webhooks). The signing algorithm is the same, so the routine below verifies either, but read the header name off the request rather than hard-coding one. ## Register an endpoint Ledger endpoints are per tenant and need `ledger:write`. ```bash theme={"dark"} curl -X POST https://api.kordio.io/ledger/v1/webhook_endpoints \ -H "Authorization: Bearer $KORDIO_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "url": "https://app.example.com/webhooks/kordio-ledger", "enabled_events": ["transaction.created", "transaction.reversed"] }' ``` ```json 201 Created theme={"dark"} { "data": { "object": "webhook_endpoint", "id": "whe_...", "url": "https://app.example.com/webhooks/kordio-ledger", "enabled_events": ["transaction.created", "transaction.reversed"], "signing_secret": "whsec_test_4bSFH1YTkjwsgiMrHMwWJfJTIzsov60WxxsziZAE" }, "livemode": false, "request_id": "req_..." } ``` `signing_secret` is returned only once, at creation. Store it immediately. If you lose it, rotate the endpoint's secret to mint a new one. The field is `signing_secret` here and `secret` on the spend control side. The two APIs differ; do not share a parser. ## Event types | Type | Fires when | | ------------------------------------ | ------------------------------------------------------------------------------------------- | | `account.created` | An account is created | | `account.closed` | An account is closed. Its balance was zero, or the close was refused | | `account.classification_changed` | An account's classification changes | | `transaction.created` | A transaction is written | | `transaction.updated` | A transaction's metadata is patched | | `transaction.committed` | A pending transaction is committed | | `transaction.reversal_created` | A reversal transaction is created (fires before `transaction.reversed`) | | `transaction.reversed` | The original is linked to its reversal | | `transaction.refund_created` | A refund is created; payload carries `refunds` and `refund_amount` | | `webhook_endpoint.secret_rotated` | An endpoint's signing secret is rotated | | `reconciliation.run_completed` | A run finishes; payload carries `matched_count`, `unmatched_count`, `pass_counts`, `status` | | `reconciliation.match_created` | A manual match is recorded | | `reconciliation.match_reversed` | A match is undone; the postings reopen | | `reconciliation.break_auto_resolved` | A match absorbed a residual within the run's tolerance | | `external_transaction.ignored` | An ingested row is excluded from matching; payload carries `reason` | | `period.closed_forced` | A period was closed over an imbalance, with `forced_by_label` recorded | | `period.reopened` | A closed period is reopened | Ingestion itself emits no per-row events; a 10k-row batch would flood the stream. Use `reconciliation.run_completed` plus `GET /v1/external_transactions?status=open` for the break workflow. Additional `oauth_client.*`, `member.*`, `tenant.*` and `reserve.*` events exist for account-management surfaces. Subscribe only to what you handle. A plain period close emits nothing. Only `period.closed_forced` fires, so a subscriber cannot use these events to learn that a period closed cleanly; read `GET /v1/period_closes` for that. `transaction.reversal_created` is emitted before `transaction.reversed` on purpose. A subscriber rebuilding state from the tail can apply the new transaction before applying the link from the original to its reversal. ## Verify the signature Each delivery includes a `Kordio-Signature` header: an HMAC-SHA256 over `.`, keyed by the endpoint's signing secret. ## Respond and retry A delivery succeeds on any `2xx`. Any non-`2xx`, timeout, or network error is retried with exponential backoff: | Attempt | Delay after previous failure | | ------- | ---------------------------- | | 1 | 30 seconds | | 2 | 5 minutes | | 3 | 1 hour | | 4 | 6 hours | | 5 | 24 hours | After the fifth failed attempt the delivery is marked dead. Return `2xx` quickly and do heavy work asynchronously. Events carry stable ids, so treat handlers as at-least-once and deduplicate on the event `id`. You can inspect deliveries for an endpoint, count failures, redeliver a specific delivery, or send a test event from the [webhook endpoints API](/ledger/api-reference/introduction). ## Events tail and replay Every state-changing operation also lands in the durable events log, with the same payloads webhooks deliver. If an endpoint was down or you need to backfill, pull from the tail instead of relying on retries. ```bash theme={"dark"} curl "https://api.kordio.io/ledger/v1/events?type=transaction.created&since=24h" \ -H "Authorization: Bearer $KORDIO_TOKEN" ``` The events list is cursor-paginated, newest first, and filterable by `type` and time. `since` takes an ISO 8601 timestamp or a relative form like `24h`, `7d` or `30m`. Fetch a single event with `GET /v1/events/{id}`. This is the safe way to rebuild state after an outage, and it is not the audit trail. An event is written just after its transaction commits, so a crash in that window loses the event and keeps the transaction. The postings are what an audit reads. ## Next steps The workflow `reconciliation.run_completed` drives. Walking the events tail with cursors. # Why a ledger API Source: https://docs.kordio.io/ledger/why Versus Postgres, a processor, accounting software, and other ledger APIs. A ledger is the one component you can build yourself and regret for years, and the regret arrives late enough that the decision looks fine for the first eighteen months. ## You start on Postgres Almost everyone does, and it works until it doesn't. The first retried request that double-posts, the first balance that is off by a cent, the first reconciliation that will not tie out: each one sends you back to rebuild an invariant you did not know you needed yet. Balanced-per-currency enforcement, append-only history, idempotency, atomic multi-posting writes, derived balances that stay fast, multi-currency, point-in-time history, reconciliation. You end up building the ledger anyway, one incident at a time, in production, with real money on it. Kordio is that correctness layer, already built and enforced. The full argument, including where Postgres genuinely is the right tool (we run on it), is on [why not just use Postgres?](/ledger/why-not-postgres). ## A processor moves the money, not the meaning A payment processor like Stripe authorizes, captures, and settles payments across the card networks and bank rails. It is very good at moving money. It never becomes your system of record for what that money meant. The processor tells you a charge succeeded. It does not tell you which accounts that charge affected, in what currency, or what your balances are as a result. That is the ledger's job, and you still need it. A common setup is to take payments through a processor and write the corresponding transactions into Kordio as the record of truth. Kordio is not a payment processor. It does not touch card or bank rails. It records and proves the accounting behind whatever moved the money. ## Accounting software answers your finance team, not your product Accounting software like QuickBooks or Xero maintains your company's books, produces statements for tax and compliance, and is operated by humans through a UI on a periodic close cycle. It answers your finance team. Your product asks different questions, at a different speed. It needs a programmable system of record it writes to in real time over an API, as transactions happen, at the granularity of your application's own accounts. That is a developer ledger. Many companies run both, with the ledger feeding summarized figures into their accounting system. ## Versus other developer ledger APIs Fragment.dev and similar developer ledger APIs sit in the same category as Kordio, so here the question is not category but where each one draws its lines. Compare on the axes that change how your system behaves under real money, not on surface ergonomics. * **Where correctness is enforced.** Kordio enforces the invariants in the database itself, with deferred Postgres triggers that reject an unbalanced or mutated write at `COMMIT`, not only in an application layer a future code path can route around. The guarantees are published on the [invariants](/ledger/invariants) page so you can hold the platform to them rather than infer them. * **Opinionated or unopinionated semantics.** Kordio ships primitives, not a vertical. It bakes in no domain vocabulary: you define the accounting graph with account templates, and the platform guarantees the invariants, never the business meaning. A ledger that models your domain for you is faster on day one and a wall on day one hundred, when your model and its model disagree. * **Reconciliation as a primitive, not a report.** Reconciliation here is a first-class operation: replayable runs that match an external snapshot against postings and mark what tied out. For most teams reconciliation is the actual job, so whether it is a primitive or a spreadsheet you rebuild each month is a real axis. * **Event and state model.** Every write emits a durable, replayable event, and balances are derived rather than stored, so consumers can rebuild their view from the log and you can always reconstruct state exactly. A ledger whose balances are stored is a ledger that can disagree with itself. * **Multi-currency depth.** No code path assumes a single currency, and a cross-currency transaction records an FX snapshot at write time, so a restatement years later reproduces the original rate instead of guessing. **Pick Kordio if** you want correctness guaranteed at the database layer, a ledger that stays out of your domain model, and reconciliation plus a replayable event log as primitives rather than homework. **Look elsewhere if** you want a turnkey product that models a specific vertical for you and you are willing to inherit its assumptions to move faster on day one. ## Next steps From credentials to a posted transaction. The guarantees, and the bug class each one makes impossible. # Why not just use Postgres? Source: https://docs.kordio.io/ledger/why-not-postgres Why a correct ledger is not a schema problem. This is a fair question, and the honest answer starts by agreeing. Postgres is an excellent foundation for a ledger, and Kordio runs on Postgres. The trap is not the database, it is treating a ledger as a schema problem: a couple of tables and some constraints. A correct ledger is a distributed correctness system, and the failure mode when you get it wrong is the worst kind. It does not crash. It returns success and silently corrupts money, and you find out weeks later when the numbers do not add up. ## The breaking point: when Postgres stops being enough A single row updated under one transaction with a `CHECK` constraint is genuinely safe. Postgres handles that perfectly, and you do not need a ledger for it. Correctness stops being a property of one transaction the moment money moves between more than one place. **Stop hand-rolling ledger logic on Postgres the moment money moves between more than one account or crosses a system boundary (a retry, an external system, a cached balance).** Before that, a table and a `CHECK` constraint are genuinely enough. After it, correctness lives across transactions, across processes, and across time, which is exactly where a single database transaction stops protecting you. This is the inflection point engineers look for, and it arrives earlier than most expect: the first time you have two accounts, or the first time a client can retry a request. After that, "we will add a real ledger later" means shipping on top of a foundation that can already corrupt itself. ## ACID is not a financial correctness system **ACID guarantees are necessary but not sufficient for financial correctness.** They protect a single transaction. They do not protect a ledger. The strongest objection to this page is true: Postgres gives you ACID, plus constraints, plus careful design. You should use all of it. But ACID's scope is one database transaction, and financial correctness lives in the gaps ACID was never meant to cover. * **Across transactions over time.** ACID makes each write atomic. It does not make a sequence of writes economically coherent. That a reversal exactly offsets its original, that a closed period stays closed, that a refund never exceeds what was captured: these are invariants over the history, not properties of one row update. * **Across retries and external systems.** A client sends a request, the network times out after the row commits but before the response, and the client retries. ACID has no idea those two HTTP calls are the same intent. Deduplication across that boundary is yours to build: idempotency keys, a uniqueness guarantee, and a replay path that returns the original. * **Across derived state.** A cached balance and the postings it summarizes are two representations of the same fact. ACID keeps one transaction internally consistent. It does not keep a materialized total in sync with the rows beneath it as both evolve. * **Across concurrency on business rules.** Isolation stops dirty reads. It does not stop a "check the balance, then post" sequence from racing two concurrent debits that each saw enough funds. Preventing that is concurrency control you design, not a flag you set. So ACID is not the financial correctness system. It is the primitive you then have to build the financial correctness system on top of. The work is the part ACID does not do for you. ## What eventually breaks when money scales These are not risks you might hit. Under load they are scheduled events. The concurrency you never reproduce at ten writes a second arrives on its own at a thousand, and the retry your tests never fired, a flaky network fires a hundred times a day. It is a question of throughput and time, not luck. And every one of these failures returns `200 OK` at the moment it happens. * **A retry duplicates a charge.** The insert commits, the response is lost, the client retries. With no idempotency key enforced by a unique index, the same economic event is recorded twice. The customer is debited twice and you hear about it from support. * **Concurrent writes drive a balance negative.** Two requests debit one account at once. Each reads a sufficient balance, each passes the non-negative check, both commit. The account goes negative. A `CHECK` on a stored balance column would only catch it by reintroducing a stored balance that can drift; the correct fix is serializing writes per account, which is a concurrency-control system, not a constraint. * **A partial failure leaves the ledger unbalanced.** A write lands some postings and then the process dies, or one code path inserts a posting outside the surrounding transaction. Debits and credits no longer match. Conservation is broken and the gap is permanent. * **A race creates phantom funds.** Operations across accounts interleave in an order no one intended, and value appears that was never deposited. These are the worst bugs: nondeterministic, timing-dependent, and invisible to a single-threaded test. * **A reconciliation mismatch surfaces weeks later.** None of the above fails loudly. The system keeps returning success while the corruption sits in the data, and thousands of later transactions build on the bad state before anyone compares totals against a bank or a processor and finds they do not agree. ```mermaid theme={"dark"} flowchart LR A[Write returns 200 OK] --> B[Corruption is latent in the data] B --> C[Thousands of transactions build on it] C --> D[Weeks later, reconciliation does not tie out] D --> E[You unwind state with real money on it] ``` The throughline is silence. A ledger built wrong does not page you. It keeps working, and the cost compounds with every transaction written on top of the corruption. ## What you are actually signing up to build Not a schema. A distributed correctness system that holds money invariants across retries, concurrency, external systems, derived state and time. Getting any single piece below wrong corrupts money without telling you. * Balanced-per-currency enforcement, deferred to `COMMIT` so multi-posting writes check as a whole. * Append-only history with the economic columns frozen, so the past cannot be rewritten. * Idempotency that survives concurrent identical requests across the network boundary. * Atomic multi-posting writes that roll back entirely on any failure. * Per-account serialization so balance-dependent decisions cannot race. * Derived balances that stay fast without becoming a second source of truth. * Multi-currency with an FX snapshot recorded at write time, a stable API and error contract, webhooks and a replayable events tail, value-date point-in-time history, and reconciliation against external systems. Every hour spent building and maintaining that system is an hour not spent on your product, and the ledger is rarely your differentiator. ## Where Kordio fits Kordio is that correctness system, offered as an API. The [invariants](/ledger/invariants) are enforced for you in application code and in Postgres triggers, idempotency holds across the network boundary, writes are serialized per account, balances are derived, and multi-currency, point-in-time history, and reconciliation are built in. You write the business logic, and the ledger cannot enter an impossible state. ## Next steps The states the ledger makes impossible. The category and where you arrive at the need. Where silent corruption would otherwise surface. From credentials to a posted transaction in four calls. # Where Kordio fits Source: https://docs.kordio.io/positioning What Kordio is, what sits underneath it, and whether you need it. Money leaves your company on software's say-so now. A job pays an invoice on a schedule, a workflow issues a refund, an agent buys what it was told to buy. Give any of them a credential and it can spend: the card sees a valid card, the API key sees a valid key, and both are right, because neither was ever told what this caller is for. ## What Kordio is Kordio is the financial control plane: the rules and the record for money your software moves. It has two halves, and four words separate them. **Control decides. Ledger records.** | Half | The question it answers | Availability | | ------------------ | -------------------------- | ------------ | | **Kordio Control** | What is allowed to happen? | Early access | | **Kordio Ledger** | What happened? | Live | Kordio moves nothing and holds nothing. No custody, no rails, no execution, and none of your credentials. Your own executor acts on Kordio's answer, on your own rails, with your own keys. That is the architecture, not a disclaimer: a control plane does not forward the packets. Control works the way a preflight check works. Before your software pays a vendor, buys on a marketplace, books a trip, or calls a paid tool, it asks. The answer comes back in the same request: allowed, needs a person, or denied, naming the rule that decided and reporting the headroom left on every limit. Allowed answers come back signed, so whatever executes can verify the authority instead of trusting the caller that carried it. Kordio is a required signer, never a custodian. That governs any action type, not only payments, and it is not tied to a payment rail. An action type is a dotted string like `payment.create`, `order.place`, `booking.create` or `tool.invoke`. Kordio never executes any of them, so nothing in the model assumes a card, a bank, a chain, or a marketplace on the other side. One agent's caps, windows and allowlists apply across all of them together, so spend on one consumes headroom for the other. ## The ledger underneath Kordio Ledger is the other half: a double-entry system of record you write to over HTTP. Accounts, balanced postings, derived balances, point-in-time history, and reconciliation, period close, trial balance and account statements as first-class operations rather than reports you rebuild each month. It is a real general-purpose ledger rather than an audit log wearing accounting vocabulary, and you can use it on its own. Where a workspace has the ledger enabled, the reservations Control takes are mirrored into it as balanced postings, so agent spend and the books do not have to be tied together by hand later. The projection never sits in the authorization path, so a slow ledger cannot delay or change a decision, and a workspace with no ledger authorizes exactly the same way. Check **Billing** in the [console](https://app.kordio.io) for what your workspace has today. ## Is this for you? **Yes, if something other than a person can start a payment or a paid API call.** A settlement job, a refund workflow, an agent buying supplies, booking freight, managing ad budget, or just burning through model and tool spend at a rate nobody predicted. You want a rule that runs before the money moves and a record afterwards that names what permitted it. That is [spend control](/agents/why). **Yes, if you also need an auditable money system of record.** A treasury product, a marketplace splitting funds, an FX desk, a SaaS company billing its own usage. That is the [ledger](/ledger/why). **No, if you only need bookkeeping for your own company's taxes and statements.** That is what accounting software is for. **The decision boundary.** The moment something non-human can initiate spend you would want to review, you are at the layer this product serves. Before that, a hard-coded cap in your own code is fine. After it, the question is not whether you have a control plane but whether it can be bypassed, and whether it can prove what it permitted. ## Next steps Why a prompt, an `if` statement, a card limit, and AP2 each stop short. Versus Postgres, versus a processor, versus accounting software, versus the other ledger APIs.