Agents bound to trees #

What is new: an agent gets a grant, a signed record that binds it to:

Every instruction is checked against the grant before anything is touched, and paid for from the budget. A refused one costs nothing and changes nothing. Every action that runs becomes a signed receipt on the agent bus, so the whole run can be handed over as one proof file. The receipts that were licensed for training, and still check out, export as training records, each citing its receipt.

Why it matters: you can let an agent work on real files and know exactly what it may do, what it did, what it cost, and which of its work may be learned from. A model trained on that record is trained only on verified actions that someone agreed to share.

Grant an agent one directory and three tools #

import json, os, time
from pathlib import Path
from tensorchain import agents, bundle, issuers, scope
from tensorchain.workspace import Workspace

tree = Path("repo")
(tree / "src").mkdir(parents=True)
(tree / "secrets").mkdir()
(tree / "src" / "app.py").write_text("print('hi')\n")
(tree / "secrets" / "key.txt").write_text("hunter2\n")

reg = issuers.Registry("keys")
ws = Workspace("run.sqlite", actor="docs").__enter__()
bus = agents.Bus(ws, reg)
token = bus.enrol("worker", "admin:acme")
s = scope.Scope(ws, reg, bus, "admin:acme")
END_OF_2099 = 4_102_444_800_000                       # the expiry, in ms (a fixed date keeps this page reproducible)
g = s.grant("worker", tree, paths=["src/"], tools=["list", "read", "write"], units=4, expires_ms=END_OF_2099,
            training="yes")
body = s.grant_body(g)
print("tree", body["tree_root"][:16], "paths", body["paths"], "tools", body["tools"], "units", body["units"],
      "training", body["training"])
assert body["paths"] == ["src/"] and body["units"] == 4
Output (captured at build)
tree d5212b2217b7b1b0 paths ['src/'] tools ['list', 'read', 'write'] units 4 training yes

Instructions cost units #

Each instruction names its price. A run is a series of exchanges: units for instructions, each one receipted.

_, files = s.instruct("worker", token, g, "list", "src")
_, code = s.instruct("worker", token, g, "read", "src/app.py")
s.instruct("worker", token, g, "write", "src/notes.txt", b"reviewed app.py\n")
print("listed:", json.loads(files), "| read:", code, "| units spent:", s.spent(g), "of", body["units"])
assert json.loads(files) == ["app.py"] and s.spent(g) == 3
assert (tree / "src" / "notes.txt").read_bytes() == b"reviewed app.py\n"
Output (captured at build)
listed: ['app.py'] | read: b"print('hi')\n" | units spent: 3 of 4

What the grant refuses #

Each refusal happens before anything is touched: no file changes, and no unit is spent.

def attempt(tool, path, data=None, price=1, agent="worker"):
    try:
        s.instruct(agent, token, g, tool, path, data, price)
        return "ran"
    except scope.ScopeRefused as e:
        return e.code

before = {p: p.read_bytes() for p in tree.rglob("*") if p.is_file()}
tries = {
    "read a secret outside src/": attempt("read", "secrets/key.txt"),
    "climb out with ..": attempt("read", "src/../secrets/key.txt"),
    "an absolute path": attempt("read", "/etc/passwd"),
    "a tool it was not given": attempt("shell", "src/app.py"),
    "more than the budget left": attempt("write", "src/big.txt", b"x", price=2),
}
for k, v in tries.items():
    print(f"{k}: {v}")
assert list(tries.values()) == ["path_out_of_scope"] * 3 + ["tool_not_granted", "budget_exceeded"]
assert s.spent(g) == 3 and {p: p.read_bytes() for p in tree.rglob("*") if p.is_file()} == before
Output (captured at build)
read a secret outside src/: path_out_of_scope
climb out with ..: path_out_of_scope
an absolute path: path_out_of_scope
a tool it was not given: tool_not_granted
more than the budget left: budget_exceeded

If someone changes the tree outside the grant, the agent is stopped until the admin looks: the tree no longer has the fingerprint the grant last saw.

(tree / "src" / "app.py").write_text("print('changed by someone else')\n")
print("after an outside change:", attempt("read", "src/app.py"))
assert attempt("read", "src/app.py") == "tree_changed"
s._set_head(g, scope.tree_root(tree))        # the admin reviews the change and accepts the tree as it now is
Output (captured at build)
after an outside change: tree_changed

Every action is a receipt #

s.instruct("worker", token, g, "read", "src/app.py")                     # the last unit
for root, r in s.receipts(g):
    print(r["tool"], r["path"], "out", r["output_sha256"][:12], "spent", r["spent"], "/", r["units"])
assert [r["tool"] for _, r in s.receipts(g)] == ["list", "read", "write", "read"]
assert attempt("read", "src/app.py") == "budget_exceeded"                  # the budget is used up

bus.close("admin:acme")
proof = bundle.export(bus, "admin:acme")
key = reg.card("admin:acme")["keys"][reg.active_key("admin:acme")]["public_key"]
report = bundle.verify(proof, [key])
print("the run as one file: trusted", report["trusted"], "intact", report["intact"], "messages", len(proof["messages"]))
assert report["trusted"] and report["intact"] and len(proof["messages"]) == 4
Output (captured at build)
list src out 5a473f0b9507 spent 1 / 4
read src/app.py out caf026f25d71 spent 2 / 4
write src/notes.txt out f69beeb910f2 spent 3 / 4
read src/app.py out 80fb24c293ba spent 4 / 4
the run as one file: trusted True intact True messages 4

Ready for training: licensed and verified only #

The grant said training: yes, so its actions may be learned from, but only those that still check out. Here, someone edits the written file afterwards, and that action drops out of the export with its reason. So do the first listing and the first read: the directory and app.py have both changed since they were receipted. Only the last read still matches what is on disk.

(tree / "src" / "notes.txt").write_text("edited after the receipt\n")
t = s.training_records(g)
print("records:", [(r["tool"], r["path"]) for r in t["records"]])
print("excluded:", [x["reason"] for x in t["excluded"]])
on_bus = {root for root, _ in s.receipts(g)}
assert all(r["receipt"] in on_bus and r["licence"] == "yes" for r in t["records"])
assert [(r["tool"], r["path"]) for r in t["records"]] == [("read", "src/app.py")]
assert [x["reason"] for x in t["excluded"]] == ["no_longer_verifies"] * 3
ws.__exit__(None, None, None)
Output (captured at build)
records: [('read', 'src/app.py')]
excluded: ['no_longer_verifies', 'no_longer_verifies', 'no_longer_verifies']

A grant with training: no contributes nothing, whatever its agent does.

What it does not do #

Next: on Sui, where the same kind of permission is enforced by a contract.