Guide · @toip-tools/mandates, @toip-tools/trust-core
Delegate bounded authority to an AI agent with mandates
Give an AI agent a signed mandate with allowed actions, spending limits, one-time approvals and revocation, and decide each action against it.
An agent that can act for you needs limits it can't talk its way past: which actions, with whom, how much each time and per week. A mandate is a signed credential that says exactly that. Anyone can check an action against it, on their own, and get a decision with reasons.
This program gives a shopping agent a mandate, then decides five purchases and a revoked one: an allowed purchase, a merchant outside the list, one over the per-purchase limit that the owner approves, one that would break the weekly budget, and one after revocation.
Before you start
You need Node 22.13 or later. In a new folder, install the packages and tsx, a TypeScript runner:
mkdir delegate-to-ai-agent && cd delegate-to-ai-agent
npm init -y && npm pkg set type=module
npm install @toip-tools/mandates @toip-tools/trust-core tsx
The code
Save this as delegate-to-ai-agent.ts. It is the complete program; the site's checks run it on every build.
// Delegate bounded authority to an AI agent with a mandate: which actions, which merchants, how much per
// purchase and per week. Every action gets a decision (allow, escalate or deny) with reasons in plain words.
import {
MandateEngine, SpendLedger, StatusRegistry, approve, explain, issueMandate, registerProfile, staticStatusResolver, type Action,
} from "@toip-tools/mandates";
import { SystemClock, identityFromSeed } from "@toip-tools/trust-core";
const clock = new SystemClock();
const random = () => crypto.getRandomValues(new Uint8Array(32));
const owner = identityFromSeed(random());
const agent = identityFromSeed(random());
// A profile is the action vocabulary: what an action of each type must say. Roots must constrain type and spend.
registerProfile({ id: "shopping/1", actions: { "shopping/buy": { required: ["merchant", "item"] } }, rootRequires: ["type", "spend:budget"] });
// The owner signs a mandate for the agent. Amounts are integer units: here, cents.
const status = new StatusRegistry(owner, clock); // the owner's revocation list
const mandate = issueMandate(owner, clock, {
subject: agent.did,
validUntil: new Date(clock.now() + 30 * 86_400_000).toISOString(),
status: status.allocate(),
profile: "shopping/1",
constraints: {
actions: { attr: "type", anyOf: ["shopping/buy"] },
merchants: { attr: "merchant", anyOf: ["grocer.example", "pharmacy.example"] },
perPurchase: { attr: "spend", max: "5000" },
perWeek: { attr: "spend", budget: "15000", period: "P7D" },
},
delegation: { maxDepth: 0 }, // the agent may not delegate further
escalation: { approvable: ["perPurchase"], approvalTtlSeconds: 600 }, // the owner may approve a bigger purchase
revocation: { maxAgeSeconds: 3600 }, // verifiers need a status list less than an hour old
});
const engine = await MandateEngine.load();
const ledger = new SpendLedger(); // what the agent has spent, per mandate
const words = {
name: (did: string) => (did === owner.did ? "Sam" : "the shopping agent"),
units: (cents: string, attr: string) => (attr === "spend" ? `$${(Number(cents) / 100).toFixed(2)}` : cents),
label: (dimension: string) => ({ perPurchase: "per purchase", perWeek: "per week" })[dimension],
noun: "this purchase",
};
async function attempt(merchant: string, item: string, cents: number, approvals = [] as ReturnType<typeof approve>[]) {
const action: Action = {
type: "shopping/buy", profile: "shopping/1", id: crypto.randomUUID(), actor: agent.did, at: clock.iso(),
attrs: { merchant, item, spend: String(cents) },
};
const decision = await engine.decide({
chain: [mandate], presenter: agent.did, action, approvals,
state: { mandate: mandate.id, spent: ledger.spent(mandate.id, clock.now()) },
status: staticStatusResolver([status.sign()]), clock,
});
console.log(`${item} at ${merchant}, $${(cents / 100).toFixed(2)}: ${decision.outcome}`);
console.log(` ${explain(decision, words).join(" ")}`);
// Allowed: reserve the spend before paying, so two purchases can't both take the last of the budget.
if (decision.outcome === "allow") ledger.tryReserve(mandate, action.id, action.attrs.spend, clock.now(), action.type);
return { action, decision };
}
await attempt("grocer.example", "groceries", 4200);
await attempt("casino.example", "chips", 2000);
const { action } = await attempt("pharmacy.example", "allergy medicine", 6500);
// The owner approves that one purchase, and only that one.
const approval = approve(owner, clock, { chain: [mandate], action, ttlSeconds: 600 });
const retry = await engine.decide({
chain: [mandate], presenter: agent.did, action, approvals: [approval], usedApprovals: (id) => ledger.approvalUsed(id),
state: { mandate: mandate.id, spent: ledger.spent(mandate.id, clock.now()) },
status: staticStatusResolver([status.sign()]), clock,
});
console.log(`With Sam's approval: ${retry.outcome}`);
ledger.tryReserve(mandate, action.id, action.attrs.spend, clock.now(), action.type);
ledger.markApprovalUsed(approval.id);
await attempt("grocer.example", "more groceries", 4900); // the weekly budget has $43.00 left
// Revoke the mandate: the agent is stopped as soon as verifiers see the new list.
status.revoke(mandate.credentialStatus);
await attempt("grocer.example", "milk", 300);
Run it:
npx tsx delegate-to-ai-agent.ts
groceries at grocer.example, $42.00: allow
This purchase is within every limit of the chain from Sam to the shopping agent.
chips at casino.example, $20.00: deny
The merchant “casino.example” isn't one Sam allowed the shopping agent (merchants). This purchase can't go ahead.
allergy medicine at pharmacy.example, $65.00: escalate
$65.00 is more than the $50.00 per purchase that Sam allowed the shopping agent. Sam can approve this purchase.
With Sam's approval: allow
more groceries at grocer.example, $49.00: deny
Spending $49.00 would bring the spending in the last 7 days to $156.00, over the $150.00 budget that Sam allowed the shopping agent (per week). This purchase can't go ahead.
milk at grocer.example, $3.00: deny
Sam has revoked the mandate to the shopping agent. This purchase can't go ahead.
Keys are random, so identifiers and sizes differ on each run. From a clone of the repository, run npx tsx --tsconfig site/tsconfig.json site/examples/guides/delegate-to-ai-agent.ts, or read it in site/examples/guides/delegate-to-ai-agent.ts.
How it works
- A profile (
registerProfile) is the action vocabulary: here one action type,shopping/buy, which must name a merchant and an item. Every action also carriesspend, in integer units. issueMandatesigns the constraints:anyOfsets for the action type and merchant,maxper purchase, and a rollingbudgetover seven days (P7D). It also says how many more links may follow, which failures the owner may approve, and how fresh the revocation list must be.MandateEngine.decidechecks the signature, validity window and revocation status, then evaluates the constraints with a Rego policy compiled to WebAssembly. It returnsallow,escalateordenywith reasons, and every decision carries the policy's hash.escalatemeans only approvable limits failed. The owner signs anapprovefor that exact action (it is bound to the action's hash), and the engine allows it once. Record used approvals so they can't be replayed.SpendLedger.tryReservechecks the budget and reserves in one step before you pay, so two purchases can't both take the last of it.explainturns reasons into sentences.
Limits and production notes
- The engine decides; your code enforces. Check for
allowand reserve the spend before the agent acts. - A delegate can pass on a narrower mandate with
delegate(): every link can only narrow its parent, and a widening is refused without signing anything. - Spending totals come from your ledger, not from the engine. Persist the ledger and the status registry (
save()), and publish the signed status list where verifiers fetch it.