Your first governed agent
Take a Payment Controls Policy from PDF to contracts, run an agent under it, and approve its payments.
Take a real policy from PDF to live contracts, run an agent under it, and approve its payments.
In this tutorial, you build a payments agent bound by a two-page Payment Controls Policy. Everything runs on your machine, so the project needs no API key. It takes about 30 minutes. To work through the hosted gate instead, see Connect to the gate.
Prerequisites:
- The SDK and coco-framework, installed as in the Quickstart. The page shows
trustcoco-sdk0.1.3; on 0.1.2, one step copies the sample policy from your checkout. - A checkout of coco-sdk, for the sample agent and the saved extraction. The repository is private until launch, so contact us at trustcoco.ai for access.
- A model with tool calling, for the sections that run the agent. Any OpenAI-compatible endpoint works. The page reads
COCO_MODEL,COCO_MODEL_API_KEYand, for a provider other than OpenAI,COCO_MODEL_BASE_URL. - For the optional live extraction only, the pipeline's checkout, read from
COCO_PIPELINE, and a Model Studio key, read fromDASHSCOPE_API_KEY.
Point at the sample files
From the folder that holds your coco-sdk checkout, set the checkout and your model:
export COCO_SDK=$PWD/coco-sdk
export COCO_MODEL=gpt-6-luna # any model with tool calling
export COCO_MODEL_API_KEY=sk-... # the model provider's key
export COCO_MODEL_BASE_URL= # empty for OpenAI, or an OpenAI-compatible endpointEvery later block reads these values, so keep this terminal open.
See the four verdicts
Run the sample agent. Its calls are scripted, so no model is needed:
python $COCO_SDK/python/examples/payments_agent.pyYou'll see one verdict per call:
clean AUTO_EXECUTE Sent $8,200 to Sunrise Capital Ltd
no memo OBSERVE Sent $3,100 to Sunrise Capital Ltd
unapproved payee DENY Coco denied this action. The payee is not on the approved list
over the limit ESCALATE paused on ESC-001: The amount exceeds the auto-release limit, so an authorised officer decides
after approval ESCALATE Sent $128,400 to Sunrise Capital Ltd
chain: {'ok': True, 'rows': 5, 'broken_at': None, 'why': None}AUTO_EXECUTE runs the call. OBSERVE runs it with a note on the record. DENY stops it. ESCALATE waits for a person.
Create a project
Keep your projects in a folder of their own, then create one:
mkdir coco-projects && cd coco-projects
coco init payments-agent
cd payments-agent| File | Contents |
|---|---|
coco.yaml | The settings: mode, limits, classifier, and gate. |
agent.py | An agent on coco-framework, with Coco on every tool call. |
tools/payments.py | One tool, send_payment, which performs the action payments.send. |
contracts/ | The rules, compiled from your policies or written by hand. |
policies/ | Your policy documents. From 0.1.3, it starts with sample_policy.pdf, the policy this tutorial uses. |
.env.example | The agent's model and keys. |
New projects start in Monitor. Every call runs, and the record says what Enforce would have done.
Turn the policy into rules
From trustcoco-sdk 0.1.3, coco init writes the sample to policies/sample_policy.pdf. Version 0.1.2 doesn't, so copy it from your checkout when it's missing:
[ -f policies/sample_policy.pdf ] || cp "$COCO_SDK/python/coco_sdk/samples/sample_policy.pdf" policies/
ls policiesls lists README.md and sample_policy.pdf. The policy has an approval matrix by amount and several controls written in prose. Use one of the options below.
Extract it with the pipeline
This option needs the pipeline's checkout and a Model Studio key. Run:
export COCO_PIPELINE=/path/to/coco-policy-generation-pipeline
export DASHSCOPE_API_KEY=sk-...
coco policy extractRead policies/sample_policy.pdf while this runs, because you'll check the result against it. The pipeline reads the PDF, builds a search index with offline embeddings, and extracts each rule with its clause. It takes about 15 seconds and ends like this:
sample_policy.pdf | sections 5 (failed 0) | llm calls 5 | candidates 9 | verified 8 | issues AMBIGUITY 1 | REVIEW_REQUIRED | 13.9s | ...
sample_policy-e3851671: 8 rules, issues AMBIGUITY 1, REVIEW_REQUIRED
Next: coco contracts compileA model reads the document, so the rule count varies between runs. REVIEW_REQUIRED means a person reads the result before anything goes live. The output lands in .coco/policy/. With a wrong key, every section fails and the command stops with no rules extracted.
Import the saved extraction
Without the pipeline or a key, import the extraction saved with the SDK's tests:
coco policy extract --from-output $COCO_SDK/python/tests/fixtures/sample_policyYou'll see sample_policy: 10 rules, issues AMBIGUITY 2, REVIEW_REQUIRED. The outputs in the rest of this tutorial come from this extraction, because it repeats exactly.
Review the draft contracts
Compile the rules and print the drafts:
coco contracts compile
coco contracts reviewThe compiler groups the rules into contracts, one per action, and reports 5 draft contracts, 9 checks (3 judge), 6 review issues, 24 cases. Two note: lines say the payroll and internal transfer exemptions are permissions, not controls, so no contract holds them. To use them, add them by hand as applies_when on the contracts they exempt.
Each contract starts as a draft and cites its clause:
payment.transfer v1 [draft] action payment.transfer (sample_policy.yaml)
source sample_policy.pdf, p.1, Payment Controls Policy > 2. Approval Matrix
says "| 10,001 - 50,000 | Level 2 manager | Yes | | Above 50,000 | Level 3 manager | Yes |"
r004_require_approval rule not (args.amount > 10000 and args.amount <= 50000) -> ESCALATE
obligations {"approver_role": "Level 2 manager", "requires": "approval"}
r005_require_approval rule args.amount <= 50000 -> ESCALATE
obligations {"approver_role": "Level 3 manager", "requires": "approval"}
r006_require_mfa rule not (args.amount > 10000 and args.amount <= 50000) -> ESCALATE
obligations {"requires": "mfa"}
r007_require_mfa rule args.amount <= 50000 -> ESCALATE
obligations {"requires": "mfa"}
review GUESSED_BINDING: transaction.amount -> args.amount was guessedsourceandsays: The page, section, and words the rule came from.- Rule lines: A condition the call must meet, with the verdict when it fails.
obligations: Travel with the escalation, so the approver sees who has to sign.review: The compiler's own doubts. Here it guessed that the policy's amount is the tool'samountargument.
Read each draft against the PDF. A rule the policy gives only in prose becomes a judge check. To see one line per contract, run coco contracts list.
Good to know: A live extraction groups rules its own way. One run gave two drafts and another three, and each reading was faithful to the policy.
Confirm the bindings and go live
contracts/bindings.yaml maps the policy's words to what the tool receives. The compiler listed every entry it guessed under guessed:. This agent needs one field and one action:
cat > contracts/bindings.yaml <<'EOF'
fields:
transaction.amount: args.amount # the policy's amount is the tool's amount
actions:
payment.transfer: payments.send # a payment transfer is what send_payment does
guessed: [] # a person has checked these
EOF
coco contracts compile
coco eval casescoco eval cases replays the boundary cases the compiler wrote from the policy, such as 10,000, 10,001, and 50,000. It ends 24 of 24 cases got exactly the expected verdict with rules only. A miss names the case and the reason. Settle each miss before the contract goes live.
Activate the contract:
coco contracts activate payment.transfer --live
coco contracts listpayment.transfer now reads live and governs payments.send.
Keep in mind: A contract with open review issues can't go live. If activate answers 1 review issues open, open contracts/sample_policy.yaml, find the issue under review:, add resolved: true with a note, and activate again. A later coco contracts compile asks again. --force skips the check.
Write a rule by hand
The policy has no rule to stop a payment outright. Add one:
cat > contracts/blocked_payees.yaml <<'EOF'
id: payments.blocked_payee
version: 1
status: live
action: payments.send
governs: Never pay a payee on the blocked list.
checks:
- id: payee_not_blocked
check: 'lower(args.payee) not in ["apex corp", "shadow ltd"]'
on_fail: DENY
reason: The payee is on the blocked list
EOF
coco contracts listcoco contracts list now has a line starting payments.blocked_payee, which reads live and governs payments.send.
For the full language, see Contracts and rules.
Decide calls and act as the approver
Ask Coco for verdicts directly, before any model is involved:
python - <<'EOF'
from coco_sdk.project import load
engine = load().engine(mode="enforce")
for amount, payee in ((900, "Sunrise Capital"), (25000, "Sunrise Capital"),
(90000, "Sunrise Capital"), (500, "Apex Corp")):
d = engine.check("payments.send", {"amount": amount, "payee": payee}, call_id=f"c{amount}{payee}")
print(f"{amount:>6} {payee:16} {d.verdict:13} {d.reason}")
EOFYou'll see:
900 Sunrise Capital AUTO_EXECUTE Every check passed
25000 Sunrise Capital ESCALATE Needs approval by Level 2 manager, under the policy: "| 10,001 - 50,000 | Level 2 manager | Yes |"
90000 Sunrise Capital ESCALATE Needs approval by Level 3 manager, under the policy: "| Above 50,000 | Level 3 manager | Yes |"
500 Apex Corp DENY The payee is on the blocked listTwo calls now wait on a person. Decide them:
coco escalations
coco escalations approve ESC-001 --by you@example.com
coco escalations reject ESC-002 --by you@example.com --reason "No Level 3 manager available"
coco ledger
coco verifycoco ledger shows each verdict with its rule and clause, then your two decisions. coco verify walks the hash chain and prints Chain intact: 6 receipts.
Run the agent in Monitor
Write your model to .env, then run the agent:
cat > .env <<EOF
COCO_MODEL=$COCO_MODEL
COCO_MODEL_BASE_URL=$COCO_MODEL_BASE_URL
COCO_MODEL_API_KEY=$COCO_MODEL_API_KEY
EOF
coco run "Pay Sunrise Capital 900 for invoice 88"
coco run "Pay Sunrise Capital 25,000 for invoice 89"
coco run "Pay Apex Corp 500 for invoice 91"
coco ledger --limit 3The agent reports every payment as sent, because Monitor stops nothing. The ledger reads AUTO_EXECUTE run, ESCALATE run, and DENY run: what Enforce would have decided, and the fact the call ran.
To tell the agent what Enforce would have done, set tell_agent: true in coco.yaml.
Switch to Enforce
Move the project to Enforce, then run the agent:
sed -i.bak 's/^mode: monitor/mode: enforce/' coco.yaml
coco run "Pay Apex Corp 500 for invoice 91"
coco run "Pay Sunrise Capital 25,000 for invoice 90"The agent says it couldn't pay Apex Corp and gives Coco's reason. The Sunrise payment pauses:
waiting on a person: ESC-003 Needs approval by Level 2 manager, under the policy: ...
coco escalations approve ESC-003 --by <name>, then run againKeep in mind: Approving and running the prompt again doesn't finish this payment. coco run keeps no thread between runs, so the second run opens a new escalation. Close this one and use the next section:
coco escalations reject ESC-003 --by you@example.com --reason "Approving inside the run instead"Wait for a person inside the run
Your application keeps the run open while a person decides, then resumes the same thread. This script does that at the terminal:
cat > wait_for_person.py <<'EOF'
"""One agent run that pauses on an escalation, asks you, and resumes."""
import sys
from coco_graph.types import Command
import agent
from coco_sdk.project import load, load_env
load_env(agent.ROOT)
bot = agent.build()
config = {"configurable": {"thread_id": "wait-for-person"}}
prompt = " ".join(sys.argv[1:]) or "Pay Sunrise Capital 25,000 for invoice 90"
result = bot.invoke({"messages": [("user", prompt)]}, config)
for paused in result.get("__interrupt__", []):
esc = paused.value
print(f"\nPAUSED {esc['escalation_id']} {esc['action']} {esc['args']}")
print(f" {esc['reason']}")
approve = input("Approve? [y/N] ").strip().lower() == "y"
reason = "" if approve else (input("Reason: ").strip() or "Rejected")
load(agent.ROOT).engine().resolve_escalation(esc["escalation_id"], approve=approve, by="you", reason=reason)
result = bot.invoke(Command(resume={"escalation_id": esc["escalation_id"]}), config)
print("\nAGENT ", result["messages"][-1].text)
EOF
python wait_for_person.py # answer y
python wait_for_person.py "Pay Sunrise Capital 30,000 for invoice 92" # answer n, give a reasonEach run prints PAUSED ESC-004 payments.send ... (then ESC-005) with the policy's reason, and asks Approve? [y/N]. Approve the first and the agent reports the 25,000 sent. Reject the second and the agent gives your reason. The pause lasts only while the thread exists: InMemorySaver keeps it for one process, and a SQLite checkpointer keeps it across restarts.
Read the record
Check the project and its chain:
coco status
coco ledger
coco verifycoco status shows the mode, contracts by status, classifier, gate, decision counts, and open escalations: here the mode is enforce, contracts 6 (4 draft, 2 live) and decisions 11. Every call you made is in the ledger, and coco verify prints Chain intact: 16 receipts. when each agent run made one tool call.
Congratulations! You've taken a policy from PDF to a governed agent, approved its payments, and verified the record.
Related Resources
Turn policies into contracts
Start again with your own documents.
Python agents
Add your own tools and supply facts from your systems.
Connect to the gate
Move decisions and the record to the hosted gate.
Monitor to Enforce
Plan a safe rollout.
Need Help?
We want your first agent to go smoothly. If you get stuck, contact us at trustcoco.ai.