Write from code

Record decisions in process from Python, TypeScript or Rust: init(), decorated functions and agent() scopes, then streams you open yourself, and verify.

Your agent is a program and you want to record its decisions in process, without the CLI or a server. You will open the default stream with init(), record an issue_refund decision on each call of the function that issues refunds, pin the policy it relied on, record a refusal, run it as two different agents, and verify the stream against its pinned fingerprint. Then you check the same stream with the tenbri CLI.

The Python and Node packages wrap the same Rust writer as the CLI and tenbrid. init() opens one stream for the whole process, and decision writes the intent before your function runs and the outcome after. To hold several streams, or see every write, you open a stream yourself. In Rust, you call the writer directly.

Prerequisites: optionally the tenbri CLI (install) to check the result, and:

Python 3.10 or later:

pip install --pre tenbri

Record decisions

agent.py
import tenbri

# The default stream: creates it and its keys (in $TENBRI_KEYS) the first time, flushes at exit.
log = tenbri.init("audit/support")  # or set TENBRI_STREAM and call tenbri.init()
pin = log.fingerprint
print("pin this:", pin)

@tenbri.decision(
    "issue_refund",
    target="stripe:charge/{charge}",
    policy="policy:refund@14",
    # What the decision relied on, pinned by a keyed digest from the local key store.
    inputs=[("policy:refund", "14", "refunds under 50 EUR are automatic")],
)
def refund(charge: str, amount: int) -> str:
    if amount > 50:
        raise tenbri.Refused("over the 50 EUR limit")  # the outcome is "refused"
    return "re_123"  # call the payment API here

with tenbri.agent("agent:support-assistant"):
    print("refund", refund("ch_3PqX", 20))
    try:
        refund("ch_9ZzY", 900)
    except tenbri.Refused as e:
        print("refused:", e)

with tenbri.agent("agent:billing"):
    print("refund", refund("ch_7Kd2", 20))

report = log.verify(pin)
print("verified:", report.ok, report.entries, "entries")
export TENBRI_KEYS=$PWD/keys
python agent.py
pin this: sha256:be626433184d9fbefa38b2d3e237642968753db861c06d9cea6170a4e1877a27
refund re_123
refused: over the 50 EUR limit
refund re_123
verified: True 8 entries
  • The intent is durable before refund runs; if it cannot be written, refund does not run (fail closed) unless init(fail_open=True). Any other exception records the outcome error and propagates; a cancelled call records unknown.
  • target and subject are templates of the arguments ("{order.id}" reads an attribute or a key) or functions of them. inputs may be a function of the arguments too.
  • with tenbri.agent(...): sets who acts for the block, and the threads and tasks it starts with its context. principal= on the decorator wins over it; TENBRI_AGENT is the fallback.
  • async def functions are decorated the same way.
  • Input digests are keyed by the stream's local key store, one key per subject, so there is no secret in code. init(digest_key=...) keys them yourself instead.

Seq 1 and 2 are the key entries that creating the stream wrote: the genesis entry signed by the new stream key, and the certification of a 24-hour session key that signs everything after. Each intent and outcome returned only once its batch and HEAD were durable.

Check it with the CLI

The stream is a normal stream on disk. After the Python or TypeScript run:

tenbri verify audit/support --key sha256:be626433184d9fbefa38b2d3e237642968753db861c06d9cea6170a4e1877a27
tenbri tail audit/support -n 6 --no-follow | jq -c '{seq, phase, status, principal: .principal.id, target: .action.target, inputs: [.inputs[]?.ref]}'
verified 8 entries, stream tnb1:be626433184d9fbefa38b2d3e2376429, pinned to sha256:be626433184d9fbefa38b2d3e237642968753db861c06d9cea6170a4e1877a27
{"seq":3,"phase":"intent","status":null,"principal":"support-assistant","target":"stripe:charge/ch_3PqX","inputs":["policy:refund"]}
{"seq":4,"phase":"outcome","status":"ok","principal":"support-assistant","target":"stripe:charge/ch_3PqX","inputs":[]}
{"seq":5,"phase":"intent","status":null,"principal":"support-assistant","target":"stripe:charge/ch_9ZzY","inputs":["policy:refund"]}
{"seq":6,"phase":"outcome","status":"refused","principal":"support-assistant","target":"stripe:charge/ch_9ZzY","inputs":[]}
{"seq":7,"phase":"intent","status":null,"principal":"billing","target":"stripe:charge/ch_7Kd2","inputs":["policy:refund"]}
{"seq":8,"phase":"outcome","status":"ok","principal":"billing","target":"stripe:charge/ch_7Kd2","inputs":[]}

After the Rust run, the stream holds one decision:

tenbri verify audit/support --key sha256:2b16e61148c367e71361dbb382993c9aa931f29418d583868b7d631811592db5
tenbri tail audit/support -n 2 --no-follow | jq -c '{seq, kind, phase, status, action: .action.type}'
verified 4 entries, stream tnb1:2b16e61148c367e71361dbb382993c9a, pinned to sha256:2b16e61148c367e71361dbb382993c9aa931f29418d583868b7d631811592db5
{"seq":3,"kind":"decision","phase":"intent","status":null,"action":"issue_refund"}
{"seq":4,"kind":"decision","phase":"outcome","status":"ok","action":"issue_refund"}

Advanced: open a stream yourself

init() and decision are built on Tenbri.open. Open a stream yourself to hold several streams in one process, to give a digest key of your own, or to get each intent and outcome back. A run pins what the agent read to its next decision; a decision is a context manager, a callback or a decorator. The outputs below come from a fresh directory.

stream.py
from tenbri import Refused, Tenbri

# Creates the stream and its keys (in $TENBRI_KEYS) the first time; opens it after that.
# The digest key keys the hashes of what the agent reads: keep it in your secret store.
log = Tenbri.open("audit/support", create=True, digest_key=b"a 32-byte secret, kept apart....")
pin = log.fingerprint
print("pin this:", pin)

with log.run("agent:support-assistant") as run:
    # What the agent read is pinned to its next decision, by a keyed digest.
    run.read("policy:refund", "14", "refunds under 50 EUR are automatic")

    # The intent is durable before the block runs; the outcome follows when it exits.
    with run.decision("issue_refund", "stripe:charge/ch_3PqX") as d:
        pass  # call the payment API here
    print("intent ", d.intent["seq"], d.intent["id"], [i["ref"] for i in d.intent["inputs"]])
    print("outcome", d.outcome["seq"], d.outcome["status"])

    # Raise Refused when your policy says no: the outcome is "refused".
    try:
        with run.decision("issue_refund", "stripe:charge/ch_9ZzY") as big:
            raise Refused("over the 50 EUR limit")
    except Refused:
        pass
    print("outcome", big.outcome["seq"], big.outcome["status"])

# Or decorate a function: the target can come from its arguments.
@log.decision("issue_refund", target=lambda charge, amount: f"stripe:charge/{charge}", principal="agent:billing")
def refund(charge: str, amount: int) -> str:
    return "re_123"  # call the payment API here

refund("ch_7Kd2", 20)

report = log.verify(pin)
print("verified:", report.ok, report.entries, "entries")
log.close()
export TENBRI_KEYS=$PWD/keys
python stream.py
pin this: sha256:eb8bd94ee36f93baf21fcca4851f15623eaad289649b80c549089cfbd82900d2
intent  3 01M5D12HHCFMEZ566S06DWCAEJ ['policy:refund']
outcome 4 ok
outcome 6 refused
verified: True 8 entries
  • Any other exception inside a decision records the outcome error and propagates; an interruption (KeyboardInterrupt, cancellation) records unknown.
  • For asyncio, await AsyncTenbri.open(...) has the same methods as coroutines, async with decisions, and decorators of async def functions. Nothing blocks the event loop.
  • The low level: log.intent(draft), log.outcome(intent, status) and log.append(entry) take format v1 drafts and return entries as stored.

Pin out of band

These programs verify against log.fingerprint or the key they just made, which only shows the stream agrees with keys on this machine. An auditor pins the fingerprint printed at creation, kept where the operator of the stream cannot change it. See Integrity.

Other ways to write

  • Agents built on the Claude Agent SDK, the OpenAI Agents SDK or LangGraph record every tool call with one line after init(): see Adapters.
  • Agents in other languages, or on machines without the keys, write through tenbrid over REST or gRPC.
  • The same code writes to a bucket with an s3:// or r2:// location: see Streams on object storage.

Related: Keys · Streams and entries · Integrity · Entry format

Edit on GitHub

On this page