Skip to main content

Service, MCP, and HTTP reference

A mission manifest decides the order of the work. When your agent host wants to decide that itself, the same engine is available three ways. All three share one authority engine, one budget ledger, one invocation pipeline, and one signed receipt chain, so a host enforces the same bounds and keeps the same record that a mission run does.

SurfaceHow you reach itAuthentication
Writ.ServiceA .NET class library: IWritServiceIn-process
writ-mcpAn MCP server over stdioThe process boundary; the role is set by the launch command
writ-apiJSON endpoints under /v1, bound to loopback by defaultAuthorization: Bearer <token>, one token per role

Writ.Service, writ-mcp, and writ-api are separate programs from the writ CLI: see Writ's programs. The operator commands on this page (writ issue, writ approvals, writ revoke, and writ reconcile with --service-db) are part of the writ CLI.

A credential (a writ) crosses every surface as an opaque string. It is a bearer token: it authorizes spend up to its bounds, so hold it like one. No result ever echoes it back except the one returned by issue or delegate.

Roles​

A service host serves two roles.

  • Agent: runs capability calls under a writ it holds, asks what a writ can still spend, narrows its writ for a sub-agent, revokes a writ it delegated, and reads the host's status, receipts and pending approvals. It reads the host's own workspace, and any workspace where it presents a live writ. It verifies receipt chains.
  • Operator: everything the agent does, plus issuing root writs, approving and denying held spends, revoking any writ, reconciling payments whose outcome is unknown, and reading any workspace.

A writ comes from the operator, and a spend over a threshold waits for the operator's decision.

writ-mcp​

writ-mcp serves the agent role. Add --role operator to its launch command for an operator's own client; that adds writ_issue, writ_approve, writ_deny, writ_revoke, writ_reconciliations and writ_reconcile. The role is set only by the launch command, never by an environment variable.

On an agent-role server, a call to one of those six tools returns ok: false, errorCode: "operator_only", retry: "final", and operatorCommand, the CLI line the operator runs instead. A read that names another workspace without presenting a writ returns errorCode: "workspace_not_allowed". writ_status reports the server's role and, for the agent role, a bootstrap line that says how the operator issues a writ.

writ-api​

writ-api takes one token per role.

VariableReaches
WRIT_API_AGENT_TOKENThe agent routes (marked agent below), with reads in the host's own workspace and in any workspace where the caller presents a live writ.
WRIT_API_OPERATOR_TOKENEvery route.

Both tokens are compared in constant time on every request. The agent token on an operator route gets 403 with errorCode: "operator_only", operatorRoutesEnabled, and operatorCommand; on a read of another workspace without a writ it gets 403 with errorCode: "workspace_not_allowed". The host starts only with at least one token, with two different tokens, and with at most one of WRIT_API_TOKEN and WRIT_API_AGENT_TOKEN.

A host configured with only WRIT_API_TOKEN uses it as the agent token, and its operator routes answer 403 operator_only with operatorRoutesEnabled: false (the startup log says so). To turn the operator routes on, set WRIT_API_OPERATOR_TOKEN to a different value and send it for issuing, approving, denying, revoking and reconciling.

The operator CLI​

The operator also acts on the host's database directly:

writ issue --service-db ./.writ/writ.db --principal researcher --budget 200 --per-call 25
writ approvals list --service-db ./.writ/writ.db
writ approvals approve 3 --service-db ./.writ/writ.db
writ revoke 1 --service-db ./.writ/writ.db
writ reconcile --service-db ./.writ/writ.db --invocation 12 --resolve not-paid

Run every host that shares one database (writ-mcp and writ-api on the same WRIT_DB_PATH) with the same WRIT_ROOT_KEY. Run these with the host's settings in the environment, including its WRIT_ROOT_KEY. Each command first checks that key against the database: the host records its key there when it starts, so start the host once before the first command. The commands work on a database at this build's schema version and do not upgrade it; to upgrade, stop the host and run writ db upgrade. writ issue prints the writ's credential for you to hand to the agent. operatorCommand and the agent's next steps write the database path as <WRIT_DB_PATH>.

Setting up the host​

The roles hold when the operator's configuration stays the operator's:

  • Run the host under a different OS account from the agent, and keep the host's database, its WRIT_ROOT_KEY, and its launch configuration readable only by that account.
  • Give the agent the agent token or an agent-role server entry, and keep the operator token and any --role operator entry in the operator's own client.
  • Set the same persistent WRIT_ROOT_KEY for the host and for the operator CLI.
  • An agent-role caller reads every approval and receipt of the host's own workspace (WRIT_WORKSPACE). To keep agents from reading each other's records, issue their writs in other workspaces; each agent then reads its own records by presenting its writ.

Operations​

OperationRoleIWritServiceMCP toolHTTP
What this host servesagentDescribewrit_statusGET /v1/status
Mint a root writoperatorIssueCredentialAsyncwrit_issuePOST /v1/credentials
Narrow a writ for a sub-agentagentDelegateAsyncwrit_delegatePOST /v1/credentials/delegate
What a writ can still spendagentGetBudgetAsyncwrit_budgetPOST /v1/credentials/budget
Run one capability callagentInvokeAsyncwrit_invokePOST /v1/invocations
Revoke a writ and its subtreeoperatorRevokeAsyncwrit_revokePOST /v1/credentials/{id}/revoke
Revoke a writ you delegated, or your ownagentRevokeDelegatedAsyncwrit_revoke_delegatedPOST /v1/credentials/revoke-delegated
The delegation chain, as boundsoperatorGetChainAsync—GET /v1/credentials/{id}/chain
The signed work recordagentGetReceiptsAsyncwrit_receiptsGET /v1/receipts; with a writ, POST /v1/credentials/receipts
Verify a receipt chainagentVerifyChainAsyncwrit_verifyPOST /v1/receipts/verify
Spends waiting on a human (read-only)agentListApprovalsAsyncwrit_approvalsGET /v1/approvals; with a writ, POST /v1/credentials/approvals
Approve or deny oneoperatorApproveAsync / DenyAsyncwrit_approve / writ_denyPOST /v1/approvals/{id}/approve / deny
Payments waiting on reconciliationoperatorListReconciliationsAsyncwrit_reconciliationsGET /v1/reconciliations, GET /v1/reconciliations/{invocationId}
Reconcile oneoperatorReconcileAsyncwrit_reconcilePOST /v1/reconciliations/{invocationId}/resolve

GET /health needs no token. IWritService itself has no roles: it is a library, and the host that wraps it decides who reaches what.

Every business failure is a typed result, never an exception: ok: false, a stable errorCode, and a caller-safe error sentence. Over HTTP the same result arrives as application/problem+json with the errorCode extension.

errorCodeMeaningHTTP status
invalid_requestThe request is malformed. Nothing was created or spent.400
unknown_capabilityThe capability is not in this host's catalog.404
not_foundThe named credential or approval does not exist here, or the invocation is not pending reconciliation.404
deniedAuthority verification refused the call, or the writ you presented is not a live writ in that workspace.403
operator_onlyThe action needs the operator role and the caller holds the agent role. Nothing was done; operatorCommand names the command the operator runs instead.403
workspace_not_allowedAn agent-role read named a workspace other than the host's own and presented no writ. Nothing was read.403
budget_exceededThe chain-wide budget reserve failed. Nothing ran or was paid.409
approval_requiredThe spend needs a human. Nothing ran or was paid.202 (not an error)
execution_failedThe capability call failed.502
replayedThe payment reference was already settled.409
pending_reconciliationThe wallet outcome is unknown and the hold is retained. Do not retry.409
widening_rejectedA delegation asked for more than its parent holds.400
conflictThis exact credential already exists.409
in_progressA call with this idempotency key is still in flight. Nothing new was reserved or paid.409
idempotency_conflictThis idempotency key was already used for a different request. Nothing ran.422
verification_failedA receipt chain did not verify.422
internal_errorSomething unexpected failed; the detail is logged host-side.500

Acting on a writ you hold​

Four agent operations take the writ you hold as credential and act only on that writ and the writs delegated beneath it: three reads, which work in any workspace where the writ is live, and revoking a writ you delegated. Writ verifies the writ in full on every call: its signature under the host's key, its workspace, every expiry on it and its chain, and that nothing on its chain is revoked.

Reading your own records​

Pass credential (and workspace, when the writ is not in the host's own workspace) to writ_receipts, writ_approvals or writ_verify. Over HTTP, send it in a POST body to /v1/credentials/receipts, /v1/credentials/approvals or /v1/receipts/verify.

ReadWhat it covers
writ_receiptsThe receipts of your writ and of every writ delegated beneath it, in chain order, with scope: "writ". Each receipt carries every field of the unscoped view; previousReceiptHash is present when the receipt before it on the chain is also yours (or it is the first receipt of the workspace), and omitted when that receipt belongs to another writ. A sibling's, a parent's or another principal's receipts are not included. The exportable JSONL and the chain's terminal are the whole workspace's, so they are not returned here.
writ_approvalsThe pending requests raised under your writ or a writ beneath it.
writ_verifyWrit checks the workspace's whole chain and answers for your receipts: receiptCount and the terminal are your last receipt, a pinned head names your last receipt, and problems in other writs' receipts appear as one count without their ids. jsonl and publicKeyHex cannot be combined with credential.

Sequence numbers are the workspace chain's own. A writ that does not verify as a live writ of the named workspace gets denied with one message, the same whether the workspace exists or not.

Revoking a writ you delegated​

writ_revoke_delegated (HTTP POST /v1/credentials/revoke-delegated) takes the writ you hold as credential and the credentialId of the writ to revoke: one that writ_delegate returned for a writ beneath yours, or your own writ's id. The target and every writ beneath it stop verifying at once, exactly as with the operator's revoke. A sibling, an ancestor, another principal's writ and an id that does not exist all get the same denied answer. Revoking an already revoked writ answers ok: true with changed: false. The signed audit event names your writ (principal, credential id, macaroon hash).

Reconciliation on a service host​

When a wallet payment's outcome is unknown, the call keeps its budget hold and waits for the operator. The operator role resolves it in process with writ_reconciliations and writ_reconcile (HTTP GET /v1/reconciliations and POST /v1/reconciliations/{invocationId}/resolve with the operator token), or out of band with writ reconcile --service-db. Both paths call the same reconciliation service, so the same rules apply.

  • Without resolve, the host asks its wallet about the payment by hash. A simulated host has no wallet, and walletLookupAvailable in the list says whether this host has one.
  • With resolve: "paid" or "not-paid", your attestation decides it and is recorded in the signed audit log. Check the payment in your wallet by its hash first. Pass decidedBy (a name of at most 128 characters, no control or line-separator characters) to record who decided; the audit event's actor is then host-operator:<name>.
  • "not-paid" on a hold with a payment hash follows the rule of writ reconcile: the host's wallet must report the payment failed. Otherwise the answer carries refusalCode (wallet_reports_paid, wallet_cannot_confirm or no_lookup_wallet) and nothing changes. When you have checked the payment yourself and it failed, add allowUnconfirmedNotPaid: true, as --allow-unconfirmed-not-paid does; walletCheck in the answer and the audit event records which way it was accepted.
  • A recorded payment proof settles the call as paid at the proven amount and refuses not-paid.
  • A row that stays unresolved answers pending_reconciliation (HTTP 409) and keeps its hold.
  • A resolve is safe to retry: nothing moves twice. Once a row is resolved it is no longer pending, so a second resolve answers not_found.
  • proofJournalPendingLines counts proofs in the host's proof journal that are not yet applied. Apply them with writ reconcile --service-db <WRIT_DB_PATH> --apply-proof-journal before you resolve a row as not paid.

Remaining budget​

An agent told to "stop when the budget runs out" asks what remains instead of learning it from a refusal. The query is read-only: it reserves nothing and changes nothing.

You present the writ itself, so you can only ask about a writ you hold. Writ checks that it is live first. A writ that is unregistered, revoked, expired, or whose chain is broken is refused with denied, the same as an invocation would be.

Every number takes the tightest value across the whole delegation chain. A reserve has to fit on every capped hop, so a sibling that spent your parent's budget shrinks what you can do even when your own slice is untouched.

FieldMeaning
remainingSatsThe minimum, over every capped link, of limit − reserved − spent. What your next calls can still reserve in total. null when no link declares a total cap.
depth, bindingDepthYour writ's depth in its chain and the depth of the link that sets remainingSats (0 = the root). bindingIsAncestor is true when a parent binds, not your writ. Links are named by depth only: an ancestor's identity and per-hop detail are on the operator-facing chain endpoint (GET /v1/credentials/{id}/chain), not in this answer.
totalLimitSats, spentSats, reservedSatsThe binding link's own numbers. A parent's spentSats includes spend by every writ delegated beneath it.
overCapSatsSats that moved under the binding link beyond spentSats: a payment proven after its hold was released, when the link's cap was already full. spentSats + overCapSats is what moved. Usually 0; null when no link declares a total cap. Every link with room is charged the full proven amount, so only a full link reports over-cap spend.
perCallMaxSatsThe tightest per-call cap on the chain, set by the link at perCallBindingDepth. A capability's own price ceiling can be lower still: see writ_status.
maxNextCallSatsmin(remainingSats, perCallMaxSats): the most one next call can reserve.
expiresAtThe earliest expiry on the chain, set by the link at expiryBindingDepth.
ownYour writ's own link: limitSats, reservedSats, spentSats, remainingSats, perCallMaxSats, expiresAt, and overCapSats.

Over HTTP the query is a POST with the credential in the body. It is never a GET, because a bearer credential in a URL ends up in proxy and access logs.

curl -s -X POST http://127.0.0.1:8787/v1/credentials/budget \
-H "Authorization: Bearer $WRIT_API_AGENT_TOKEN" -H "Content-Type: application/json" \
-d '{"credential": "<the writ>"}'
{
"ok": true,
"credentialId": 2,
"totalLimitSats": 100,
"spentSats": 30,
"reservedSats": 0,
"overCapSats": 0,
"remainingSats": 70,
"depth": 1,
"bindingDepth": 0,
"bindingIsAncestor": true,
"perCallMaxSats": 25,
"perCallBindingDepth": 1,
"maxNextCallSats": 25,
"expiresAt": "2026-11-13T18:15:00+00:00",
"expiryBindingDepth": 1,
"own": { "limitSats": 80, "reservedSats": 0, "spentSats": 0, "remainingSats": 80, "perCallMaxSats": 25, "expiresAt": "2026-11-13T18:15:00+00:00", "overCapSats": 0 }
}

In this example the writ's own slice is 80 sats and untouched, but a sibling spent 30 of the parent's 100, so the parent binds at 70.

Refusal reason codes​

Every non-success invoke result carries two codes. errorCode is the coarse class in the table above. reasonCode names the exact refusal, one code per refusal path, so an agent with no human in the loop can decide what to do without parsing the error sentence. retry says what that decision is:

  • final: this writ will not get this call through, whatever you retry. Stop, or ask the operator.
  • retry_with_change: worth a different attempt. Try another capability or provider, a cheaper call, or the right workspace.
  • retry_later: worth the same call later, after a human approves or a transient fault clears.

The MCP tool returns reasonCode and retry beside errorCode. Over HTTP they are reasonCode and retry extensions on the problem+json body (with invocationId and receiptId when there is one); a 202 approval answer carries them in its body. A success has neither. Codes are stable: a published code is never renamed or reused.

reasonCodeerrorCoderetryMeaning
invalid_requestinvalid_requestretry_with_changeThe request is malformed: a missing credential or capability, bad query JSON, a negative threshold.
capability_not_servedunknown_capabilityretry_with_changeThe capability is not in this host's catalog. Pick one from writ_status.
credential_malformeddeniedfinalThe credential cannot be parsed, or one of its caveats is malformed.
credential_signature_invaliddeniedfinalThe credential does not verify under this host's authority key: tampered, minted by another host, or minted before an ephemeral-key restart.
workspace_mismatchdeniedretry_with_changeThe credential belongs to a different workspace.
principal_mismatchdeniedfinalThe credential's principal caveats are missing or contradict each other.
capability_out_of_scopedeniedretry_with_changeThe capability is outside the writ's scope. Call something within it.
capability_not_in_setdeniedretry_with_changeThe capability is not in the writ's permitted capability set (capability_in). Call one that is.
capability_set_invaliddeniedfinalThe writ's permitted capability set (capability_in) is malformed.
path_out_of_scopedeniedretry_with_changeThe resource path is outside the writ's path caveat.
credential_expireddeniedfinalThe credential's own expiry has passed.
unknown_caveatdeniedfinalThe credential carries a caveat this host does not recognize.
reserved_caveatdeniedfinalThe credential carries a reserved caveat (condition_hash, bond_id) that cannot be satisfied yet.
authority_check_errordeniedretry_laterThe authority check itself could not run on the host.
exceeds_total_capdeniedretry_with_changeThe call's price ceiling is larger than the writ's whole budget. Choose a cheaper capability.
exceeds_per_call_capdeniedretry_with_changeThe call's price ceiling is larger than the writ's per-call cap.
credential_unregistereddeniedfinalThis host never registered the credential.
credential_chain_brokendeniedfinalThe delegation chain does not reach a genuine root.
credential_revokeddeniedfinalThe writ, or an ancestor, was revoked.
credential_chain_expireddeniedfinalThe writ, or an ancestor, has expired according to the host's records.
negative_ceilingdeniedfinalThe host derived a negative price ceiling: a misconfigured capability.
approval_requiredapproval_requiredretry_laterThe spend needs a human. Retry the same call after the request in approvalRequestId is approved.
approval_expiredapproval_requiredretry_laterThe approval expired before it was used. A fresh request is pending; retry after it is approved.
budget_exhaustedbudget_exceededretry_with_changeSome capped link of the chain has less left than this call's ceiling. A cheaper call may still fit: check writ_budget.
reserve_per_call_capbudget_exceededretry_with_changeThe call's ceiling exceeds the tightest per-call cap the host records for the chain.
reserve_chain_revokedbudget_exceededfinalA writ on the chain was revoked between verification and the reserve.
reserve_chain_expiredbudget_exceededfinalA writ on the chain expired between verification and the reserve.
reserve_chain_brokenbudget_exceededfinalThe chain, or a capped link's budget account, could not be established at reserve time.
reserve_conflictbudget_exceededretry_laterA concurrent attempt moved the invocation first.
reserve_store_errorbudget_exceededretry_laterThe reserve hit a database error and rolled back.
executor_threwexecution_failedretry_laterThe executor failed unexpectedly. Nothing was paid.
destination_blockedexecution_failedfinalThe SSRF guard refused the capability's endpoint (a private, loopback, or metadata address).
destination_unresolvedexecution_failedretry_laterThe capability's endpoint host could not be resolved (DNS) at call time. Likely transient. Nothing was paid.
host_errorinternal_errorfinalThe host failed unexpectedly; the detail is logged host-side. You cannot know whether it paid: check writ_budget and writ_receipts, or re-send it with the SAME idempotency key to read its outcome. Never re-send it without a key.
capability_unroutableexecution_failedfinalThe capability has no usable endpoint or internal route on this host.
provider_unreachableexecution_failedretry_laterThe provider could not be reached. Nothing was paid.
provider_errorexecution_failedretry_laterThe provider answered with an error status or a redirect. Nothing was paid.
payment_challenge_invalidexecution_failedretry_with_changeThe provider answered 402 without a payment challenge Writ can read. Try another provider.
price_exceeds_ceilingexecution_failedretry_with_changeThe provider's invoice is above this call's ceiling (the lower of the capability's price and the writ's per-call cap). Refused before paying.
payment_refusedexecution_failedretry_with_changeThe payment was refused before anything was sent: an unreadable amount, no payment hash, or a wallet that cannot return a preimage.
model_call_failedexecution_failedretry_laterAn internal model step failed.
execution_failedexecution_failedretry_laterThe executor reported a failure it did not classify. Nothing was paid.
payment_outcome_unknownpending_reconciliationfinalThe wallet outcome is unknown and the hold is kept. Money may have moved: do not retry. The operator reconciles it.
paid_execution_failedexecution_failedfinalThe payment settled but the capability did not deliver. The spend is in the work record; do not retry blindly.
payment_replayedreplayedfinalAnother invocation already settled this payment reference. No second spend.
settlement_rejectedexecution_failedretry_laterThe ledger refused to settle a call that charged nothing; its hold was released.
idempotency_in_progressin_progressretry_laterThe call with this idempotency key is still in flight: executing, reserved, waiting for a human, or pending reconciliation. Retry the same call with the same key later.
invocation_abandonedexecution_failedfinalThe keyed call was abandoned before it reserved any budget (its process went away) and, after an hour, was resolved as not paid. A new key may attempt the work again.
reconciliation_requiredpending_reconciliationfinalThe keyed call holds budget for a payment whose outcome is unknown (an unknown wallet outcome, or a reservation stuck for 30 minutes). An operator must reconcile it; do not attempt the work again under any key until then.
reconciled_not_paidexecution_failedfinalA replayed call whose unknown payment an operator or wallet later reconciled as not paid; its hold was returned. retryWithNewKey is true.
operator_discardedexecuted or execution_failedfinalA replayed call whose work record the operator discarded (writ outbox discard). The call ran, and paid when paid says so; receiptEmitted is false: the chain holds a signed work_record_discarded record for it, not a work record. Do not retry it under any key.
outcome_unknownexecution_failedfinalA replayed call finished but its outcome was never recorded and no receipt says how it ended. paid and paidSats come from the ledger; when it paid, never attempt the work again.
idempotency_key_reusedidempotency_conflictretry_with_changeThis idempotency key was already used for a different request under this writ. Use a new key for a new request.

On the signed record​

A refusal recorded with recordDenials (a "denied" work-record receipt) also commits its reasonCode into the signed receipt. Such a receipt identifies itself as protocol version writ.execution-receipt/2 (signing domain tag writ.execution-receipt.v2): the version-1 format plus one trailing canonical field, reasonCode. Every other receipt is minted as writ.execution-receipt/1. Changing or stripping the code, or relabelling the version, breaks the signature.

Receipt result codes: completed, paid_execution_failed (paid, then the capability failed), denied (a recorded refusal, with its reasonCode), and work_record_discarded. A work_record_discarded receipt (reason code operator_discarded, protocol version 2) is not a work record: it is the host's signed statement that the operator discarded the work record of that invocation with writ outbox discard. It names the invocation, capability, principal and the payment hash the ledger recorded; its input, output and policy hashes are SHA-256 of the empty string and carry no information. writ_receipts lists it; an invoke replayed by its idempotency key answers with reasonCode operator_discarded and receiptEmitted false.

Verifier version. writ verify in Writ 0.1.0 checks both receipt versions.

Idempotent retries​

An agent that times out or loses a response cannot know whether its call ran. Without protection, retrying it pays a fresh invoice. Send an idempotency key and reuse it on every retry of the same call, and a retry never pays twice.

SurfaceHow you send it
IWritServiceInvokeRequest.IdempotencyKey
MCPthe idempotencyKey argument of writ_invoke
HTTPan Idempotency-Key request header on POST /v1/invocations (exactly one)

A key is 1 to 128 printable ASCII characters with no spaces; a UUID you generate per unit of work is ideal. It is scoped to the writ that presents it, so two writs can use the same key independently. Writ binds the key to a fingerprint of the request: the capability, resource path, query, body, purpose, and the derived price ceiling. A JSON body is compared in canonical form (member order, whitespace, and number spelling such as 1 versus 1.0 do not matter), so re-serializing the same request on a retry is safe; a body that is not JSON is compared byte for byte. Run id, approval threshold, and recordDenials are not part of it.

What a repeat with the same key returns:

The original callThe repeat returnsReserved, executed, or paid again?
Finished (succeeded, refused after authorization, failed, or replayed)The original outcome, reasonCode, invocationId, paidSats, and receipt id, with idempotentReplay: true. The output body is not stored, so output is null on a replay.No
Still in flight: executing or reservederrorCode: in_progress, reasonCode: idempotency_in_progress, the invocationId. Retry later with the same key.No
Its payment outcome is unknown (pending reconciliation), or it sat reserved for 30 minutes (the operator resolves it with writ_reconcile or writ reconcile --service-db; agents cannot)errorCode: pending_reconciliation, reasonCode: reconciliation_required. The hold is kept and an operator must reconcile; a stale reservation is moved to reconciliation, never released by age. Do not attempt the work under any key until then.No
Its process went away before it reserved anything, over an hour agoThe replay reasonCode: invocation_abandoned, paid: false, retryWithNewKey: true. Nothing can have been paid: a payment needs a reservation first.No
Waiting for a human approvalin_progress with the approvalRequestId to resolve. Once a human approves, the same call with the same key resumes that same invocation and runs once.No, until approved
Approval denied or expiredA fresh approval request bound to the same invocation (approval_required). Never a second invocation.No
The key was used for a different requesterrorCode: idempotency_conflict, reasonCode: idempotency_key_reused.No

A replay is the key's permanent answer, so on a non-success replay retry is always final, whatever the original reason, and a second field says what to do next:

  • retryWithNewKey: true: the ledger proves the original paid nothing (it ended without settling a payment). You may attempt the work again under a NEW key; read reasonCode first, because the same request may fail the same way.
  • retryWithNewKey: false: money moved or may have moved. Do not attempt the work again under any key. Read writ_receipts and writ_budget, or ask the operator.

paid and paidSats on a replay come from the ledger as well as the recorded outcome, so a call whose recording was lost (the process died after paying) still reads as paid, with reasonCode: outcome_unknown.

A payment proof always wins. When the paid capability returns a proof of payment (a preimage that opens the invoice's payment hash), Writ records the hash and the proven amount on the invocation and makes the ledger reflect exactly that amount as spent, whatever happened to the invocation meanwhile: still reserved, routed to reconciliation, reconciled by an operator as paid at the full hold (the excess is returned) or as not paid (a late settlement charges it again, audited and naming that reconciliation), or abandoned. From then on every answer for that invocation and its key says paid with that amount and retryWithNewKey: false. If the ledger cannot apply the proof at that moment, the call answers paid: true, paidSats, reasonCode: reconciliation_required, and the next re-send of the same key applies it. If the database refuses the proof itself, the host writes it to an authenticated, owner-only proof journal beside the database; only the operator can apply that journal (writ reconcile --apply-proof-journal --yes), after Writ verifies each line's MAC, checks that the line was written for this database, and checks it against the ledger. Agents cannot reach reconciliation or the journal: the reconcile tools and routes are the operator role's, and applying the journal is a CLI step. A call that ended payment_outcome_unknown replays that outcome even after the operator reconciles it, because money may have moved. Authority is still checked first, so a retry under a writ that has since been revoked or has expired is refused like any other call.

Concurrent calls with the same key are safe: the key is unique per writ in the database, so exactly one call creates the invocation and can pay; every other caller is answered in_progress or with the replay. Without a key, nothing changes: every call is a new invocation.

curl -s -X POST http://127.0.0.1:8787/v1/invocations \
-H "Authorization: Bearer $WRIT_API_AGENT_TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: <one-label-per-job>" \
-d '{"credential": "<the writ>", "capability": "demo.search", "query": {"q": "lightning"}}'