Skip to content

Your first bundle

In this tutorial you will write a bundle that lets an agent order office supplies, under three rules:

  1. Agents may only buy from your approved vendor. They cannot choose another.
  2. An order may not exceed the department’s remaining budget.
  3. An order of EUR 500.00 or more needs a finance approver.

It takes about twenty minutes. You need the running sandbox from the quickstart. Run every command from the sefra-sandbox directory.

Create the bundle’s directories and its connector. The connector names a secret but never contains it. Sefra looks the value up in its own configuration when it makes the call.

mkdir -p my-bundle/intents my-bundle/policies
cat > my-bundle/connectors.yaml <<'EOF'
connectors:
  erp:
    type: http
    base_url: http://erp:9000
    auth:
      type: oauth_client_credentials
      token_url: http://idp:8080/sefra/token
      client_id: sefra-erp
      secret: erp_client_secret
    timeout_ms: 30000
    max_concurrency: 8
EOF

Grants decide which intents an agent can see. An intent nobody is granted does not appear in the agent’s tool list at all. Limits stop an agent that loops.

cat > my-bundle/grants.yaml <<'EOF'
grants:
  - role: procurement_agent
    intents: ["supplies.*"]
EOF
cat > my-bundle/limits.yaml <<'EOF'
limits:
  default: { per_minute: 60, burst: 20 }
  intents:
    supplies.place_order: { per_minute: 10, burst: 5 }
EOF

This file is the whole contract for the action. Read it from top to bottom:

  • input_schema is all the agent can send. There is no vendor field, so the agent cannot pick one.
  • facts reads the live budget before deciding.
  • execute is the real API call, with the vendor fixed to v_1001.
  • idempotency makes retries safe.
  • compensate says how to undo the order if a later step fails.
  • summary_template is what the approver reads.
cat > my-bundle/intents/supplies.place_order.yaml <<'EOF'
intent: supplies.place_order
version: 1
description: Order office supplies from the approved vendor, within the department's budget.
effect: write
tags: [supplies]
input_schema:
  type: object
  additionalProperties: false
  required: [sku, quantity, unit_price_minor, department]
  properties:
    sku:              { type: string, minLength: 1, maxLength: 64 }
    quantity:         { type: integer, minimum: 1, maximum: 1000 }
    unit_price_minor: { type: integer, minimum: 0, x-sefra-money: true }
    department:       { type: string, minLength: 1, maxLength: 64 }
output_schema:
  type: object
  required: [po_id, total_minor]
  properties:
    po_id:       { type: string }
    total_minor: { type: integer, x-sefra-money: true }
facts:
  budget:
    connector: erp
    method: GET
    path: "/budgets/${input.department}"
    timeout_ms: 2000
    response_schema:
      type: object
      additionalProperties: false
      required: [remaining_minor, currency]
      properties:
        department:      { type: string }
        remaining_minor: { type: integer, x-sefra-money: true }
        currency:        { type: string }
execute:
  connector: erp
  method: POST
  path: /purchase-orders
  body:
    vendor_id: v_1001
    sku: "${input.sku}"
    quantity: "${input.quantity}"
    unit_price_minor: "${input.unit_price_minor}"
    currency: EUR
    department: "${input.department}"
  idempotency: { mode: header, header: Idempotency-Key }
  success: [201]
  output: { po_id: "${response.body.id}", total_minor: "${response.body.total_minor}" }
compensate:
  connector: erp
  method: POST
  path: "/purchase-orders/${output.po_id}/cancel"
  idempotency: { mode: natural }
  success: [200]
  already_undone: [404, 409]
summary_template: "Order ${input.quantity} x ${input.sku} at ${input.unit_price_minor} EUR minor units for ${input.department}"
EOF

Each rule has a stable name and a message. The hint is addressed to the agent, so that it can correct its request.

cat > my-bundle/policies/supplies.rego <<'EOF'
package policies.supplies

approval_threshold_minor := 50000 # EUR 500.00

order_total := input.input.quantity * input.input.unit_price_minor

allow if {
	"procurement_agent" in input.principal.roles
	input.intent.type == "supplies.place_order"
}

deny contains {
	"rule": "supplies.no_budget",
	"message": "The department has no budget.",
	"path": "/department",
	"hint": "Use an existing department.",
} if {
	input.facts.budget == null
}

deny contains {
	"rule": "supplies.over_budget",
	"message": "Order total exceeds the remaining budget.",
	"path": "/quantity",
	"actual": order_total,
	"limit": input.facts.budget.remaining_minor,
	"hint": "Reduce the quantity.",
} if {
	order_total > input.facts.budget.remaining_minor
}

require_approval contains {
	"rule": "supplies.large_order",
	"message": sprintf("Order total %d is at least %d minor units.", [order_total, approval_threshold_minor]),
	"approver": {"role": "finance_approver"},
	"distinct_from_requester": true,
} if {
	order_total >= approval_threshold_minor
}
EOF

Policy tests run without a database or a network, so they fit in CI. Test each rule on both sides of its condition:

cat > my-bundle/policies/supplies_test.rego <<'EOF'
package policies.supplies_test

import data.policies.supplies

order(quantity, remaining) := {
	"principal": {"id": "agent:test", "type": "agent", "roles": ["procurement_agent"]},
	"intent": {"type": "supplies.place_order", "version": 1, "effect": "write", "irreversible": false},
	"input": {"sku": "PENS", "quantity": quantity, "unit_price_minor": 1000, "department": "it-ops"},
	"facts": {"budget": {"remaining_minor": remaining, "currency": "EUR"}},
}

rules(set) := {v.rule | some v in set}

test_agent_is_allowed if {
	supplies.allow with input as order(1, 100000)
}

test_other_role_is_not_allowed if {
	not supplies.allow with input as object.union(order(1, 100000), {"principal": {"roles": ["reporting_agent"]}})
}

test_over_budget if {
	"supplies.over_budget" in rules(supplies.deny) with input as order(11, 10000)
}

test_within_budget if {
	not "supplies.over_budget" in rules(supplies.deny) with input as order(10, 10000)
}

test_no_budget if {
	"supplies.no_budget" in rules(supplies.deny) with input as object.union(order(1, 0), {"facts": {"budget": null}})
}

test_large_order_at_threshold if {
	"supplies.large_order" in rules(supplies.require_approval) with input as order(50, 100000)
}

test_small_order_below_threshold if {
	count(supplies.require_approval) == 0 with input as order(49, 100000)
}
EOF
./sandbox sefra bundle test my-bundle

The output ends with the intents each role can see, and OK. If a test fails, the bundle cannot be activated.

Applying validates the bundle again, stores it under its digest and makes it active in one step. The change is recorded in the audit trail.

SEFRA_TOKEN=$(./sandbox token admin) ./sandbox sefra bundle apply my-bundle

Define a small helper that takes a product, a quantity and a unit price, then send a small order:

AGENT=$(./sandbox token agent)
order() {
  curl -sS -X POST http://127.0.0.1:18180/v1/executions \
    -H "Authorization: Bearer $AGENT" -H "Content-Type: application/json" \
    -H "Idempotency-Key: tutorial-order-$1-$2" \
    -d '{"intent": "supplies.place_order",
         "input": {"sku": "'"$1"'", "quantity": '"$2"', "unit_price_minor": '"$3"', "department": "it-ops"}}'
}
order PENS 5 1000 | jq '{status, output: .steps[0].output}'

Five items at EUR 10.00 is below the approval threshold, so the order goes straight through. Now ask for more than the budget holds:

order CHAIRS 1000 100000 | jq '.envelope.error.violations[0] | {rule, hint}'
{
  "rule": "supplies.over_budget",
  "hint": "Reduce the quantity."
}

Finally, send an order of EUR 600.00, which needs a person, and approve it:

RESPONSE=$(order TONER 60 1000)
echo "$RESPONSE" | jq '{status, required: .approval.required}'
SEFRA_OPERATOR_TOKEN=$(./sandbox token approver) ./sandbox sefra approvals approve "$(echo "$RESPONSE" | jq -r .approval.approval_id)" --comment "Approved"
./sandbox wait "$(echo "$RESPONSE" | jq -r .execution_id)" | jq '{status, output: .steps[0].output}'

The order waits as pending_approval, then ends as succeeded.

You now have a complete governed action: a typed contract, live facts, three rules with tests, an approval path and an undo. To adapt it to a real system, change the connector and the API paths. The structure stays the same.

To return the sandbox to the starter bundle that the other pages use:

SEFRA_TOKEN=$(./sandbox token admin) ./sandbox sefra bundle apply bundle

Connect a real agent to Sefra, or read the manifest guide and policy guide for everything a bundle can express.