Skip to content

SDK reference

agent_tessera

Agent Tessera SDK: identity, permissions, and governance for AI agents.

The SDK gives an agent a verifiable identity, enforces its YAML policy on model and tool calls, and records an audit trail, regardless of which LLM provider it uses.

Public names are imported the first time they are used, so importing this package does not load the client, the policy schema, or the HTTP stack.

Tessera

Tessera(
    agent: str,
    *,
    policy: str | Path | AgentPolicy | None = None,
    baselines: Sequence[str | Path | BaselinePolicy]
    | None = None,
    audit_path: str | Path | None = None,
    suspended: bool | None = None,
    approval_handler: ApprovalHandler | None = None,
    approval_mode: _ApprovalMode | None = None,
    approval_wait: bool = True,
    server_url: str | None = None,
    agent_token: str | None = None,
    fail_mode: Literal["closed", "open"] | None = None,
    price_table: str | Path | None = None,
    detect_bypass: bool = False,
)

Govern one agent from a local policy and an append-only audit log.

The client evaluates actions in process. check reports a decision. enforce raises when the action is denied or still needs approval.

Parameters:

Name Type Description Default
agent str

Agent name. It must match the loaded policy.

required
policy str | Path | AgentPolicy | None

Agent policy object or file. Falls back to TESSERA_POLICY.

None
baselines Sequence[str | Path | BaselinePolicy] | None

Baseline policies or files. Falls back to TESSERA_BASELINES.

None
audit_path str | Path | None

Audit log file. Falls back to TESSERA_AUDIT_PATH, then .tessera/audit.jsonl in the current directory.

None
suspended bool | None

Start suspended when True. Falls back to TESSERA_SUSPENDED being 1.

None
approval_handler ApprovalHandler | None

Called with the decision when approval is required. True allows the action. None leaves approval unresolved.

None
approval_mode _ApprovalMode | None

handler calls approval_handler, server asks the control plane, and raise raises ApprovalRequired. The default is server in server mode, otherwise handler when a handler is set, otherwise raise.

None
approval_wait bool

When True in server mode, block until the approval is decided or the policy timeout passes. When False, raise ApprovalRequired with approval_id.

True
server_url str | None

Control-plane URL. Falls back to TESSERA_URL. Unset keeps the client in offline mode.

None
agent_token str | None

Registration token. Falls back to TESSERA_AGENT_TOKEN.

None
fail_mode Literal['closed', 'open'] | None

open or closed when the server is unreachable. Falls back to TESSERA_FAIL_MODE, then open when TESSERA_ENV is dev.

None
detect_bypass bool

When True, or when TESSERA_DETECT_BYPASS is 1, record provider HTTP calls that did not pass through an adapter. The call is not blocked.

False
Example
from agent_tessera import AgentPolicy, Tessera
from agent_tessera.types import Action

policy = AgentPolicy.model_validate(
    {
        "apiVersion": "tessera/v1",
        "kind": "AgentPolicy",
        "metadata": {"agent": "bot"},
        "spec": {"tools": {"allow": ["files.read"]}},
    }
)
with Tessera("bot", policy=policy, audit_path="audit.jsonl") as client:
    client.enforce(Action.tool("files.read"))

Load policy, open the audit log, and record a start event.

Parameters:

Name Type Description Default
agent str

Agent name. It must match the loaded policy.

required
policy str | Path | AgentPolicy | None

Agent policy object or file. Falls back to TESSERA_POLICY.

None
baselines Sequence[str | Path | BaselinePolicy] | None

Baseline policies or files. Falls back to TESSERA_BASELINES.

None
audit_path str | Path | None

Audit log file. Falls back to TESSERA_AUDIT_PATH, then .tessera/audit.jsonl.

None
suspended bool | None

Start suspended when True. Falls back to TESSERA_SUSPENDED being 1.

None
approval_handler ApprovalHandler | None

Called when an action requires approval.

None
approval_mode _ApprovalMode | None

handler, server, or raise. None selects server in server mode, handler when a handler is set, and raise otherwise.

None
approval_wait bool

Block for a server approval when True. When False, raise ApprovalRequired carrying approval_id.

True
server_url str | None

Control-plane URL. Falls back to TESSERA_URL.

None
agent_token str | None

Registration token. Falls back to TESSERA_AGENT_TOKEN.

None
fail_mode Literal['closed', 'open'] | None

open or closed. Falls back to TESSERA_FAIL_MODE.

None
price_table str | Path | None

JSON price table. Falls back to TESSERA_PRICE_TABLE, then the built-in table.

None
detect_bypass bool

Record ungoverned provider HTTP calls. Also enabled when TESSERA_DETECT_BYPASS is 1. The call is not blocked.

False

Raises:

Type Description
ConfigError

If no policy is configured, the agent name does not match, server mode is combined with a local policy, the price table cannot be read, or approval_mode is server without a control plane.

ServerError

If server mode cannot obtain a policy and fail mode is closed.

agent property

agent: str

Return the agent name.

Returns:

Type Description
str

The agent name passed to the constructor.

instance_id property

instance_id: str

Return this client's id.

Returns:

Type Description
str

A random 32-character hex id, stable for the life of the client.

policy property

policy: EffectivePolicy | None

Return the effective policy.

Returns:

Type Description
EffectivePolicy | None

The agent policy after applicable baselines were merged. None

EffectivePolicy | None

only while server mode is fail-open and no bundle is available.

mode property

mode: Literal['offline', 'server']

Return whether decisions use a local policy or the control plane.

Returns:

Type Description
Literal['offline', 'server']

offline or server.

suspended property

suspended: bool

Return whether the client is suspended.

Returns:

Type Description
bool

True when the local flag, the registry, the bundle, the

bool

revocation stream, or a rejected refresh says so. resume clears

bool

only the local flag.

flush

flush(timeout: float = 5.0) -> bool

Upload events buffered for the control plane.

Parameters:

Name Type Description Default
timeout float

How long to wait, in seconds.

5.0

Returns:

Type Description
bool

True when nothing remains buffered. Offline mode has no buffer.

check

check(action: Action) -> Decision

Evaluate an action without changing counters.

Parameters:

Name Type Description Default
action Action

Action to evaluate. The active principal is attached when the action does not already name one.

required

Returns:

Type Description
Decision

The decision. A denial is returned, not raised.

Example
decision = client.check(Action.tool("files.read"))
assert decision.effect in {"allow", "deny", "require_approval"}

enforce

enforce(action: Action) -> Decision

Evaluate an action and commit it when it is allowed.

Parameters:

Name Type Description Default
action Action

Action to evaluate and, when allowed, count.

required

Returns:

Type Description
Decision

The allowing decision. Approval that is granted is returned as

Decision

allow with reason approval_granted.

Raises:

Type Description
Denied

If the action is denied, an approval handler rejects it, or a server approval is denied or times out.

ApprovalRequired

If approval is required and the client is not waiting on the server. In server mode with approval_wait false, approval_id is set.

Example
client.enforce(Action.tool("files.read"))

suspend

suspend() -> None

Suspend the client so every later action is denied.

Example
client.suspend()
client.resume()

resume

resume() -> None

Clear the suspended flag.

Example
client.resume()

task

task(
    task_id: str | None = None,
    *,
    supervisor: str | None = None,
) -> AbstractContextManager[Task]

Activate a task for this client until the block exits.

Parameters:

Name Type Description Default
task_id str | None

Id to store on the task. A random id is used when omitted.

None
supervisor str | None

Supervisor for this run. The first value is the run binding. A nested task can name its own.

None

Returns:

Type Description
AbstractContextManager[Task]

A context manager that yields the task. Nested tasks are allowed.

Example
with client.task() as task:
    client.enforce(Action.tool("files.read"))
    assert task.steps == 1

http_client

http_client() -> httpx.Client

Return an HTTP client that attaches this agent's chain headers.

Each request gets Authorization: Bearer <runtime JWT> when this client is in server mode, Tessera-Run when a task is active, and X-Tessera-Parent-Span when a governed call is on the stack.

Returns:

Type Description
Client

A sync httpx.Client. Callers own it and must close it.

Example
with client.task("run-1"):
    with client.http_client() as http:
        http.get("https://worker.internal/work")

handle_call

handle_call(headers: Mapping[str, str]) -> Iterator[None]

Bind an inbound parent span from request headers.

Parameters:

Name Type Description Default
headers Mapping[str, str]

Incoming HTTP headers. A malformed X-Tessera-Parent-Span is ignored.

required

Yields:

Type Description
None

Nothing. Decisions inside the block parent to the inbound span

None

when no local call is already on the stack.

Example
with worker.handle_call(request.headers):
    worker.enforce(Action.tool("files.read"))

receive_handoff

receive_handoff(
    caller: Tessera,
) -> AbstractContextManager[Task | None]

Join the caller's run and principal for an in-process hop.

The process-wide principal stays active. When the caller has a task, this client opens a task with the same id so both agents share the run for the duration of the block. The caller's active span becomes the inbound parent for decisions in this block when the call stack does not already supply one.

Parameters:

Name Type Description Default
caller Tessera

Client that is handing work to this one.

required

Returns:

Type Description
AbstractContextManager[Task | None]

A context manager that yields the joined task, or None when the

AbstractContextManager[Task | None]

caller has no active task.

Example
with orchestrator.task("run-1"):
    with worker.receive_handoff(orchestrator) as run:
        assert run is not None and run.id == "run-1"

record_effect

record_effect(
    ref: str,
    *,
    reversible: bool = False,
    undo: str | None = None,
) -> None

Remember an opaque change made by the current run.

Parameters:

Name Type Description Default
ref str

Caller-supplied id, such as zendesk:ticket/123. Content does not belong here.

required
reversible bool

Whether the caller says the change can be undone.

False
undo str | None

Name of a tool that would undo the change. Tessera stores the name and does not call it.

None

Raises:

Type Description
ConfigError

If ref or undo is not usable.

Example
with client.task("run-1"):
    client.record_effect("zendesk:ticket/123", reversible=True, undo="zendesk.reopen")

on_behalf_of

on_behalf_of(
    user: str,
    groups: Iterable[str] = (),
    *,
    user_token: str | None = None,
) -> AbstractContextManager[Principal]

Act for a user until the block exits.

Offline, and in server mode without user_token, user is trusted. In server mode, user_token is exchanged for a delegated runtime JWT that is used until the block exits.

Parameters:

Name Type Description Default
user str

User identifier.

required
groups Iterable[str]

Groups the user belongs to.

()
user_token str | None

User access or ID token. Keyword-only. Server mode exchanges it. Offline mode ignores it.

None

Returns:

Type Description
AbstractContextManager[Principal]

A context manager that yields the principal. The principal is

AbstractContextManager[Principal]

shared by every client in the process.

Raises:

Type Description
ServerError

In server mode, if the exchange is rejected or there is no runtime JWT.

Example
with client.on_behalf_of("ada", ["support"]):
    client.check(Action.tool("files.read"))

tool

tool(name: str) -> Callable[[F], F]

Wrap a function so each call is enforced as a tool action.

Parameters:

Name Type Description Default
name str

Tool name recorded in the decision and the call event.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. self and cls are

Callable[[F], F]

omitted from the audited arguments.

Example
@client.tool("files.read")
def read(path: str) -> str:
    return path

guardrail

guardrail(name: str) -> Callable[[F], F]

Mark a guardrail as ran when the wrapped function returns.

Parameters:

Name Type Description Default
name str

Guardrail name, such as input.prompt_injection.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. An exception leaves the

Callable[[F], F]

guardrail unmarked.

Example
@client.guardrail("input.prompt_injection")
def scan(prompt: str) -> None:
    return None

model_call

model_call(name: str) -> Callable[[F], F]

Wrap a function as a governed model call.

Parameters:

Name Type Description Default
name str

Model resource, such as ollama/llama3.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. Missing warn and

Callable[[F], F]

flag input guardrails are recorded, then the call is enforced.

Callable[[F], F]

Guardrails are cleared after the function returns.

Example
@client.model_call("local/echo")
def complete(prompt: str) -> str:
    return prompt

record_usage

record_usage(
    model: str, input_tokens: int, output_tokens: int
) -> None

Add token usage and estimated cost to today's total and the audit log.

An unknown model is priced at zero and emits one cost.unknown_model event for this process.

Parameters:

Name Type Description Default
model str

Model name the tokens belong to.

required
input_tokens int

Prompt tokens.

required
output_tokens int

Completion tokens.

required
Example
client.record_usage("local/echo", 3, 4)

wrap

wrap(client: T) -> T

Return a governed view of a provider client.

Parameters:

Name Type Description Default
client T

OpenAI, Azure OpenAI, or Anthropic client.

required

Returns:

Type Description
T

A proxy with the same interface. Model calls are enforced.

Raises:

Type Description
ConfigError

If the client type is not supported.

Example
governed = client.wrap(openai_client)
governed.chat.completions.create(model="gpt-4.1-mini")

close

close() -> None

Stop background work, record a stop event, and upload it.

A second call does nothing. Offline mode only closes the local audit log.

Example
client.close()
client.close()

__enter__

__enter__() -> Self

Return this client.

Returns:

Type Description
Self

The same client.

__exit__

__exit__(*exc_info: object) -> None

Close the client when the block exits.

Parameters:

Name Type Description Default
exc_info object

Exception information supplied by the with statement.

()

Task dataclass

Task(
    id: str,
    client_id: str,
    steps: int = 0,
    guardrails_ran: set[str] = set(),
    started_at: datetime = (lambda: datetime.now(UTC))(),
    cost_usd: float = 0.0,
    supervisor: str | None = None,
)

One unit of work whose steps and guardrails are tracked.

Attributes:

Name Type Description
id str

Task identifier. Callers pass uuid4().hex when they have no id.

client_id str

Instance id of the client that created the task.

steps int

Governed model and tool calls already allowed in this task.

guardrails_ran set[str]

Guardrail names that have run while this task is active.

started_at datetime

When the task began. Run duration is measured from here.

cost_usd float

Estimated model spend recorded while this task is active.

supervisor str | None

Supervisor bound to this run, or None.

ApprovalRequired

ApprovalRequired(
    decision: Decision, approval_id: str | None = None
)

Bases: GovernanceError

Raise when an action needs approval before it can proceed.

Attributes:

Name Type Description
approval_id str | None

Server approval id when the client did not wait. None when no request was stored.

Example
err = ApprovalRequired(decision, approval_id="01H")
assert err.approval_id == "01H"

Store the decision and, when present, the server approval id.

Parameters:

Name Type Description Default
decision Decision

Decision that still needs approval.

required
approval_id str | None

Id from POST /v1/approvals. Omit it offline.

None

ConfigError

Bases: TesseraError

Raise when SDK configuration is invalid.

The policy path is missing, the agent name does not match the loaded policy, or the wrapped client is unsupported.

Denied

Denied(decision: Decision)

Bases: GovernanceError

Raise when policy denies an action.

GovernanceError

GovernanceError(decision: Decision)

Bases: TesseraError

Raise when an action is not allowed to proceed.

The string form is <effect> <kind> '<resource>': <reason>. When rule is set, (rule <rule>) is appended.

Parameters:

Name Type Description Default
decision Decision

Decision that blocked the action.

required
Example
from agent_tessera import Action, Decision, Denied, Effect, Reason

decision = Decision(
    Effect.DENY,
    Reason.DENY_RULE,
    Action.tool("shell.exec"),
    "v1",
    "agent:tools.deny[0]",
)
assert str(Denied(decision)) == (
    "deny tool 'shell.exec': deny_rule (rule agent:tools.deny[0])"
)

Store the decision that blocked the action.

Parameters:

Name Type Description Default
decision Decision

Decision that blocked the action.

required

PolicyError

PolicyError(message: str, *, path: Path | None = None)

Bases: TesseraError

Raise when a policy cannot be read or validated.

The string form is message alone, or <path>: <message> when path is set.

Parameters:

Name Type Description Default
message str

What is wrong with the policy.

required
path Path | None

File the error refers to. Omit it when the policy did not come from a file.

None
Example
from pathlib import Path

err = PolicyError("unknown field", path=Path("policy.yaml"))
assert err.path == Path("policy.yaml")
assert str(err) == "policy.yaml: unknown field"

Store the policy failure and an optional source path.

Parameters:

Name Type Description Default
message str

What is wrong with the policy.

required
path Path | None

File the error refers to. Omit it when the policy did not come from a file.

None

RegistryError

Bases: TesseraError

Raise when a local agent registry cannot be read or changed.

Example
from agent_tessera import RegistryError

err = RegistryError("registry is locked")
assert str(err) == "registry is locked"

ServerError

Bases: TesseraError

Raise when the control plane cannot be used.

The server is unreachable, the credentials are rejected, or the response does not match the protocol.

TesseraError

Bases: Exception

Raise as the base class for every Agent Tessera error.

AgentPolicy

Bases: BaseModel

Grant an agent's permissions in one environment.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Policy schema version. Always tessera/v1. Accepts the alias apiVersion.

kind Literal['AgentPolicy']

Document kind. Always AgentPolicy.

metadata AgentPolicyMetadata

Agent identity.

spec AgentPolicySpec

Permissions, limits, and guardrails.

Example
policy = AgentPolicy(
    api_version="tessera/v1",
    kind="AgentPolicy",
    metadata=AgentPolicyMetadata(agent="support-triage", environment="prod"),
)
assert policy.spec.guardrails.on_missing == "flag"

BaselinePolicy

Bases: BaseModel

Restrict agents across an organization.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Policy schema version. Always tessera/v1. Accepts the alias apiVersion.

kind Literal['BaselinePolicy']

Document kind. Always BaselinePolicy.

metadata BaselinePolicyMetadata

Baseline name.

spec BaselinePolicySpec

Restrictions and the selector that chooses agents.

AgentRegistry

Bases: BaseModel

A file that lists agents and the baselines that apply to them.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Always tessera/v1.

kind Literal['AgentRegistry']

Always AgentRegistry.

baselines tuple[str, ...]

Baseline paths relative to the registry file.

agents tuple[RegistryEntry, ...]

Registered agents. Each name and environment pair is unique.

Example
registry = AgentRegistry.model_validate(
    {"apiVersion": "tessera/v1", "kind": "AgentRegistry"}
)
assert registry.agents == ()

LocalRegistry

LocalRegistry(
    path: str | Path,
    *,
    now: Callable[[], datetime] = _utc_now,
)

Read and update one registry file.

Writes take an exclusive lock, re-read the file, and replace it atomically. Every change is appended to registry-audit.jsonl beside the file.

Parameters:

Name Type Description Default
path str | Path

Registry file. A missing file is read as an empty registry.

required
now Callable[[], datetime]

Clock stored on registered_at and updated_at.

_utc_now
Example
from agent_tessera.registry import LocalRegistry, RegistryEntry

registry = LocalRegistry(".tessera/registry.yaml")
registry.register(RegistryEntry(name="helper", owner="dev@localhost"))
assert registry.find("helper", "dev") is not None

Store the path and the clock.

Parameters:

Name Type Description Default
path str | Path

Registry file.

required
now Callable[[], datetime]

Clock stored on registered_at and updated_at.

_utc_now

path property

path: Path

Return the registry file path.

Returns:

Type Description
Path

The path passed to the constructor.

load

load() -> AgentRegistry

Read the registry.

Returns:

Type Description
AgentRegistry

The file's contents. A missing file is an empty registry.

Raises:

Type Description
PolicyError

If the file exists and is not a registry document.

find

find(name: str, environment: str) -> RegistryEntry | None

Return the entry for one agent, if it is registered.

Parameters:

Name Type Description Default
name str

Agent name.

required
environment str

Environment name.

required

Returns:

Type Description
RegistryEntry | None

The entry, or None.

register

register(entry: RegistryEntry) -> RegistryEntry

Add an agent.

Parameters:

Name Type Description Default
entry RegistryEntry

Agent to add. Timestamps are filled by this store.

required

Returns:

Type Description
RegistryEntry

The stored entry.

Raises:

Type Description
RegistryError

If the agent is already registered, the policy does not match, or an active entry has no policy.

update

update(
    name: str, environment: str, **changes: object
) -> RegistryEntry

Replace metadata fields on one agent.

Parameters:

Name Type Description Default
name str

Agent name.

required
environment str

Environment name.

required
**changes object

Fields to replace. status is changed with set_status. Timestamps are not accepted.

{}

Returns:

Type Description
RegistryEntry

The stored entry.

Raises:

Type Description
RegistryError

If the agent is missing, a field is unknown, or the new policy does not match the agent.

set_status

set_status(
    name: str, environment: str, status: AgentStatus
) -> RegistryEntry

Move an agent to another lifecycle status.

Parameters:

Name Type Description Default
name str

Agent name.

required
environment str

Environment name.

required
status AgentStatus

Status to store.

required

Returns:

Type Description
RegistryEntry

The stored entry.

Raises:

Type Description
RegistryError

If the agent is missing, the transition is not allowed, or activation has no policy.

resolve_policy

resolve_policy(entry: RegistryEntry) -> Path | None

Return the policy file for an entry.

Parameters:

Name Type Description Default
entry RegistryEntry

Registry entry.

required

Returns:

Type Description
Path | None

The path relative to the registry file, or None when the entry

Path | None

has no policy.

resolve_baselines

resolve_baselines() -> tuple[Path, ...]

Return the baseline files listed by the registry.

Returns:

Type Description
tuple[Path, ...]

Paths relative to the registry file.

Action dataclass

Action(
    kind: ActionKind,
    resource: str,
    args: Mapping[str, object] = dict(),
    principal: Principal | None = None,
)

Describe one model, tool, data, or agent call.

Instances compare by identity. args is copied so later changes to the mapping passed in do not change the action.

Parameters:

Name Type Description Default
kind ActionKind

Kind of call.

required
resource str

Model name, tool name, data scope, or agent name.

required
args Mapping[str, object]

Arguments supplied with the call. Empty when the call has none.

dict()
principal Principal | None

User this call is made for, when acting on behalf of someone.

None
Example
action = Action.tool("files.read")
assert action.kind is ActionKind.TOOL
assert action.resource == "files.read"
assert action.args == {}

__post_init__

__post_init__() -> None

Copy call arguments so the action keeps its own mapping.

model classmethod

model(name: str) -> Action

Build a model-call action.

Parameters:

Name Type Description Default
name str

Provider-qualified model name, such as openai/gpt-4.1.

required

Returns:

Type Description
Action

An action of kind model.

tool classmethod

tool(
    name: str, args: Mapping[str, object] | None = None
) -> Action

Build a tool-call action.

Parameters:

Name Type Description Default
name str

Tool name, which may include dots such as files.read.

required
args Mapping[str, object] | None

Arguments the tool was called with. None means no arguments.

None

Returns:

Type Description
Action

An action of kind tool.

data classmethod

data(scope: str) -> Action

Build a data-access action.

Parameters:

Name Type Description Default
scope str

Data scope, such as crm.customers:read.

required

Returns:

Type Description
Action

An action of kind data.

agent classmethod

agent(name: str) -> Action

Build an outbound call to another agent.

Parameters:

Name Type Description Default
name str

Name of the agent being called.

required

Returns:

Type Description
Action

An action of kind agent.

ActionKind

Bases: StrEnum

Name the kind of call a policy evaluates.

Attributes:

Name Type Description
MODEL

A model invocation, such as openai/gpt-4.1.

TOOL

A tool call.

DATA

A data-scope access, such as crm.customers:read.

AGENT

An outbound call to another agent.

Decision dataclass

Decision(
    effect: Effect,
    reason: Reason,
    action: Action,
    policy_version: str,
    rule: str | None = None,
)

Record the result of evaluating one action.

Instances compare by identity. rule is an identifier such as agent:tools.allow[0] or agent:limits.max_steps_per_task, and is None when the reason is suspended or not_granted.

Parameters:

Name Type Description Default
effect Effect

Whether the action is allowed, denied, or needs approval.

required
reason Reason

Why the effect was chosen.

required
action Action

Action that was evaluated.

required
policy_version str

Identifier of the policy that produced this decision.

required
rule str | None

Identifier of the rule that decided the effect, if one applied.

None
Example
decision = Decision(
    Effect.DENY,
    Reason.NOT_GRANTED,
    Action.tool("shell.exec"),
    "v1",
)
assert decision.allowed is False
assert decision.rule is None

allowed property

allowed: bool

Return whether the effect is allow.

Returns:

Type Description
bool

True when effect is allow.

Effect

Bases: StrEnum

Name the outcome of evaluating an action.

Attributes:

Name Type Description
ALLOW

The action may proceed.

DENY

The action is refused.

REQUIRE_APPROVAL

The action needs approval before it may proceed.

Principal dataclass

Principal(user: str, groups: frozenset[str] = frozenset())

Identify the person an action is performed for.

Parameters:

Name Type Description Default
user str

Stable user identifier.

required
groups frozenset[str]

Group names used by delegation checks. Empty when the user belongs to none.

frozenset()
Example
principal = Principal("ada", frozenset({"support"}))
assert principal.user == "ada"
assert "support" in principal.groups

Reason

Bases: StrEnum

Name why a decision has its effect.

These values are stable strings recorded with each decision.

Attributes:

Name Type Description
SUSPENDED

The agent is suspended.

DENY_RULE

A deny list matched the action.

DELEGATION

The caller may not act for the principal.

GUARDRAIL_MISSING

A required input guardrail has not run.

NOT_GRANTED

No allow rule or granting approval rule matched.

LIMIT

A usage limit was reached.

APPROVAL_RULE

An approval rule matched.

ALLOW_RULE

An allow list matched.

APPROVAL_GRANTED

An approval handler allowed the action.

APPROVAL_REJECTED

An approval handler refused the action.

RUN_REVOKED

The active run was revoked.

POLICY_UNAVAILABLE

No current policy bundle is available.

FAIL_OPEN

The client allowed the action because the server was unreachable.

OUTSIDE_WINDOW

The action is outside the agent's operating window.

EFFECT_DENIED

An effect tag on the resource is denied.

ASSISTIVE_EFFECT

An assistive agent tried a side-effecting action.

EFFECT_APPROVAL

An effect tag on the resource requires approval.

APPROVAL_UNAVAILABLE

An unattended agent has nobody to ask.

APPROVAL_TIMEOUT

The approval route ended without a decision.

QUOTA_UNAVAILABLE

A shared quota cannot be charged.

CIRCUIT_OPEN

Too many recent denials opened the circuit breaker.

CHAIN_TOO_DEEP

The call chain is longer than agents.max_chain_depth.

CHAIN_REENTRY

This agent already appears in the chain.

PRINCIPAL_REQUIRED

A chain hop has no principal.

PRINCIPAL_FORBIDDEN

The agent must not act for a principal.

CHAIN_POLICY_UNAVAILABLE

A chain member's grants are not in the bundle.

SUPERVISOR_GRANTS_MISSING

cap_to_supervisor is set and that supervisor has no grant document.

UNSUPERVISED

A supervisor is required and none is resolved.

DEAD_MAN

The supervisor acknowledgement is overdue.

load_policy

load_policy(
    path: str | Path,
) -> AgentPolicy | BaselinePolicy | SupervisorGrants

Read one YAML policy document from disk.

Parameters:

Name Type Description Default
path str | Path

Path of the policy file.

required

Returns:

Type Description
AgentPolicy | BaselinePolicy | SupervisorGrants

The agent policy, baseline, or supervisor grant document.

Raises:

Type Description
PolicyError

If the file cannot be read, the YAML is invalid, or the document is not a single policy. The error's path is this file.

__getattr__

__getattr__(name: str) -> object

Import a public name the first time it is used.

Parameters:

Name Type Description Default
name str

Attribute requested on this package.

required

Returns:

Type Description
object

The exported object.

Raises:

Type Description
AttributeError

If name is not a public export.

__dir__

__dir__() -> list[str]

List the public names, including those not imported yet.

Returns:

Type Description
list[str]

Sorted attribute names.

agent_tessera.client

In-process client that evaluates policy and writes the audit log.

Tessera

Tessera(
    agent: str,
    *,
    policy: str | Path | AgentPolicy | None = None,
    baselines: Sequence[str | Path | BaselinePolicy]
    | None = None,
    audit_path: str | Path | None = None,
    suspended: bool | None = None,
    approval_handler: ApprovalHandler | None = None,
    approval_mode: _ApprovalMode | None = None,
    approval_wait: bool = True,
    server_url: str | None = None,
    agent_token: str | None = None,
    fail_mode: Literal["closed", "open"] | None = None,
    price_table: str | Path | None = None,
    detect_bypass: bool = False,
)

Govern one agent from a local policy and an append-only audit log.

The client evaluates actions in process. check reports a decision. enforce raises when the action is denied or still needs approval.

Parameters:

Name Type Description Default
agent str

Agent name. It must match the loaded policy.

required
policy str | Path | AgentPolicy | None

Agent policy object or file. Falls back to TESSERA_POLICY.

None
baselines Sequence[str | Path | BaselinePolicy] | None

Baseline policies or files. Falls back to TESSERA_BASELINES.

None
audit_path str | Path | None

Audit log file. Falls back to TESSERA_AUDIT_PATH, then .tessera/audit.jsonl in the current directory.

None
suspended bool | None

Start suspended when True. Falls back to TESSERA_SUSPENDED being 1.

None
approval_handler ApprovalHandler | None

Called with the decision when approval is required. True allows the action. None leaves approval unresolved.

None
approval_mode _ApprovalMode | None

handler calls approval_handler, server asks the control plane, and raise raises ApprovalRequired. The default is server in server mode, otherwise handler when a handler is set, otherwise raise.

None
approval_wait bool

When True in server mode, block until the approval is decided or the policy timeout passes. When False, raise ApprovalRequired with approval_id.

True
server_url str | None

Control-plane URL. Falls back to TESSERA_URL. Unset keeps the client in offline mode.

None
agent_token str | None

Registration token. Falls back to TESSERA_AGENT_TOKEN.

None
fail_mode Literal['closed', 'open'] | None

open or closed when the server is unreachable. Falls back to TESSERA_FAIL_MODE, then open when TESSERA_ENV is dev.

None
detect_bypass bool

When True, or when TESSERA_DETECT_BYPASS is 1, record provider HTTP calls that did not pass through an adapter. The call is not blocked.

False
Example
from agent_tessera import AgentPolicy, Tessera
from agent_tessera.types import Action

policy = AgentPolicy.model_validate(
    {
        "apiVersion": "tessera/v1",
        "kind": "AgentPolicy",
        "metadata": {"agent": "bot"},
        "spec": {"tools": {"allow": ["files.read"]}},
    }
)
with Tessera("bot", policy=policy, audit_path="audit.jsonl") as client:
    client.enforce(Action.tool("files.read"))

Load policy, open the audit log, and record a start event.

Parameters:

Name Type Description Default
agent str

Agent name. It must match the loaded policy.

required
policy str | Path | AgentPolicy | None

Agent policy object or file. Falls back to TESSERA_POLICY.

None
baselines Sequence[str | Path | BaselinePolicy] | None

Baseline policies or files. Falls back to TESSERA_BASELINES.

None
audit_path str | Path | None

Audit log file. Falls back to TESSERA_AUDIT_PATH, then .tessera/audit.jsonl.

None
suspended bool | None

Start suspended when True. Falls back to TESSERA_SUSPENDED being 1.

None
approval_handler ApprovalHandler | None

Called when an action requires approval.

None
approval_mode _ApprovalMode | None

handler, server, or raise. None selects server in server mode, handler when a handler is set, and raise otherwise.

None
approval_wait bool

Block for a server approval when True. When False, raise ApprovalRequired carrying approval_id.

True
server_url str | None

Control-plane URL. Falls back to TESSERA_URL.

None
agent_token str | None

Registration token. Falls back to TESSERA_AGENT_TOKEN.

None
fail_mode Literal['closed', 'open'] | None

open or closed. Falls back to TESSERA_FAIL_MODE.

None
price_table str | Path | None

JSON price table. Falls back to TESSERA_PRICE_TABLE, then the built-in table.

None
detect_bypass bool

Record ungoverned provider HTTP calls. Also enabled when TESSERA_DETECT_BYPASS is 1. The call is not blocked.

False

Raises:

Type Description
ConfigError

If no policy is configured, the agent name does not match, server mode is combined with a local policy, the price table cannot be read, or approval_mode is server without a control plane.

ServerError

If server mode cannot obtain a policy and fail mode is closed.

agent property

agent: str

Return the agent name.

Returns:

Type Description
str

The agent name passed to the constructor.

instance_id property

instance_id: str

Return this client's id.

Returns:

Type Description
str

A random 32-character hex id, stable for the life of the client.

policy property

policy: EffectivePolicy | None

Return the effective policy.

Returns:

Type Description
EffectivePolicy | None

The agent policy after applicable baselines were merged. None

EffectivePolicy | None

only while server mode is fail-open and no bundle is available.

mode property

mode: Literal['offline', 'server']

Return whether decisions use a local policy or the control plane.

Returns:

Type Description
Literal['offline', 'server']

offline or server.

suspended property

suspended: bool

Return whether the client is suspended.

Returns:

Type Description
bool

True when the local flag, the registry, the bundle, the

bool

revocation stream, or a rejected refresh says so. resume clears

bool

only the local flag.

flush

flush(timeout: float = 5.0) -> bool

Upload events buffered for the control plane.

Parameters:

Name Type Description Default
timeout float

How long to wait, in seconds.

5.0

Returns:

Type Description
bool

True when nothing remains buffered. Offline mode has no buffer.

check

check(action: Action) -> Decision

Evaluate an action without changing counters.

Parameters:

Name Type Description Default
action Action

Action to evaluate. The active principal is attached when the action does not already name one.

required

Returns:

Type Description
Decision

The decision. A denial is returned, not raised.

Example
decision = client.check(Action.tool("files.read"))
assert decision.effect in {"allow", "deny", "require_approval"}

enforce

enforce(action: Action) -> Decision

Evaluate an action and commit it when it is allowed.

Parameters:

Name Type Description Default
action Action

Action to evaluate and, when allowed, count.

required

Returns:

Type Description
Decision

The allowing decision. Approval that is granted is returned as

Decision

allow with reason approval_granted.

Raises:

Type Description
Denied

If the action is denied, an approval handler rejects it, or a server approval is denied or times out.

ApprovalRequired

If approval is required and the client is not waiting on the server. In server mode with approval_wait false, approval_id is set.

Example
client.enforce(Action.tool("files.read"))

suspend

suspend() -> None

Suspend the client so every later action is denied.

Example
client.suspend()
client.resume()

resume

resume() -> None

Clear the suspended flag.

Example
client.resume()

task

task(
    task_id: str | None = None,
    *,
    supervisor: str | None = None,
) -> AbstractContextManager[Task]

Activate a task for this client until the block exits.

Parameters:

Name Type Description Default
task_id str | None

Id to store on the task. A random id is used when omitted.

None
supervisor str | None

Supervisor for this run. The first value is the run binding. A nested task can name its own.

None

Returns:

Type Description
AbstractContextManager[Task]

A context manager that yields the task. Nested tasks are allowed.

Example
with client.task() as task:
    client.enforce(Action.tool("files.read"))
    assert task.steps == 1

http_client

http_client() -> httpx.Client

Return an HTTP client that attaches this agent's chain headers.

Each request gets Authorization: Bearer <runtime JWT> when this client is in server mode, Tessera-Run when a task is active, and X-Tessera-Parent-Span when a governed call is on the stack.

Returns:

Type Description
Client

A sync httpx.Client. Callers own it and must close it.

Example
with client.task("run-1"):
    with client.http_client() as http:
        http.get("https://worker.internal/work")

handle_call

handle_call(headers: Mapping[str, str]) -> Iterator[None]

Bind an inbound parent span from request headers.

Parameters:

Name Type Description Default
headers Mapping[str, str]

Incoming HTTP headers. A malformed X-Tessera-Parent-Span is ignored.

required

Yields:

Type Description
None

Nothing. Decisions inside the block parent to the inbound span

None

when no local call is already on the stack.

Example
with worker.handle_call(request.headers):
    worker.enforce(Action.tool("files.read"))

receive_handoff

receive_handoff(
    caller: Tessera,
) -> AbstractContextManager[Task | None]

Join the caller's run and principal for an in-process hop.

The process-wide principal stays active. When the caller has a task, this client opens a task with the same id so both agents share the run for the duration of the block. The caller's active span becomes the inbound parent for decisions in this block when the call stack does not already supply one.

Parameters:

Name Type Description Default
caller Tessera

Client that is handing work to this one.

required

Returns:

Type Description
AbstractContextManager[Task | None]

A context manager that yields the joined task, or None when the

AbstractContextManager[Task | None]

caller has no active task.

Example
with orchestrator.task("run-1"):
    with worker.receive_handoff(orchestrator) as run:
        assert run is not None and run.id == "run-1"

record_effect

record_effect(
    ref: str,
    *,
    reversible: bool = False,
    undo: str | None = None,
) -> None

Remember an opaque change made by the current run.

Parameters:

Name Type Description Default
ref str

Caller-supplied id, such as zendesk:ticket/123. Content does not belong here.

required
reversible bool

Whether the caller says the change can be undone.

False
undo str | None

Name of a tool that would undo the change. Tessera stores the name and does not call it.

None

Raises:

Type Description
ConfigError

If ref or undo is not usable.

Example
with client.task("run-1"):
    client.record_effect("zendesk:ticket/123", reversible=True, undo="zendesk.reopen")

on_behalf_of

on_behalf_of(
    user: str,
    groups: Iterable[str] = (),
    *,
    user_token: str | None = None,
) -> AbstractContextManager[Principal]

Act for a user until the block exits.

Offline, and in server mode without user_token, user is trusted. In server mode, user_token is exchanged for a delegated runtime JWT that is used until the block exits.

Parameters:

Name Type Description Default
user str

User identifier.

required
groups Iterable[str]

Groups the user belongs to.

()
user_token str | None

User access or ID token. Keyword-only. Server mode exchanges it. Offline mode ignores it.

None

Returns:

Type Description
AbstractContextManager[Principal]

A context manager that yields the principal. The principal is

AbstractContextManager[Principal]

shared by every client in the process.

Raises:

Type Description
ServerError

In server mode, if the exchange is rejected or there is no runtime JWT.

Example
with client.on_behalf_of("ada", ["support"]):
    client.check(Action.tool("files.read"))

tool

tool(name: str) -> Callable[[F], F]

Wrap a function so each call is enforced as a tool action.

Parameters:

Name Type Description Default
name str

Tool name recorded in the decision and the call event.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. self and cls are

Callable[[F], F]

omitted from the audited arguments.

Example
@client.tool("files.read")
def read(path: str) -> str:
    return path

guardrail

guardrail(name: str) -> Callable[[F], F]

Mark a guardrail as ran when the wrapped function returns.

Parameters:

Name Type Description Default
name str

Guardrail name, such as input.prompt_injection.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. An exception leaves the

Callable[[F], F]

guardrail unmarked.

Example
@client.guardrail("input.prompt_injection")
def scan(prompt: str) -> None:
    return None

model_call

model_call(name: str) -> Callable[[F], F]

Wrap a function as a governed model call.

Parameters:

Name Type Description Default
name str

Model resource, such as ollama/llama3.

required

Returns:

Type Description
Callable[[F], F]

A decorator for a sync or async function. Missing warn and

Callable[[F], F]

flag input guardrails are recorded, then the call is enforced.

Callable[[F], F]

Guardrails are cleared after the function returns.

Example
@client.model_call("local/echo")
def complete(prompt: str) -> str:
    return prompt

record_usage

record_usage(
    model: str, input_tokens: int, output_tokens: int
) -> None

Add token usage and estimated cost to today's total and the audit log.

An unknown model is priced at zero and emits one cost.unknown_model event for this process.

Parameters:

Name Type Description Default
model str

Model name the tokens belong to.

required
input_tokens int

Prompt tokens.

required
output_tokens int

Completion tokens.

required
Example
client.record_usage("local/echo", 3, 4)

wrap

wrap(client: T) -> T

Return a governed view of a provider client.

Parameters:

Name Type Description Default
client T

OpenAI, Azure OpenAI, or Anthropic client.

required

Returns:

Type Description
T

A proxy with the same interface. Model calls are enforced.

Raises:

Type Description
ConfigError

If the client type is not supported.

Example
governed = client.wrap(openai_client)
governed.chat.completions.create(model="gpt-4.1-mini")

close

close() -> None

Stop background work, record a stop event, and upload it.

A second call does nothing. Offline mode only closes the local audit log.

Example
client.close()
client.close()

__enter__

__enter__() -> Self

Return this client.

Returns:

Type Description
Self

The same client.

__exit__

__exit__(*exc_info: object) -> None

Close the client when the block exits.

Parameters:

Name Type Description Default
exc_info object

Exception information supplied by the with statement.

()

agent_tessera.context

Per-client task and guardrail state, with a shared principal.

Task dataclass

Task(
    id: str,
    client_id: str,
    steps: int = 0,
    guardrails_ran: set[str] = set(),
    started_at: datetime = (lambda: datetime.now(UTC))(),
    cost_usd: float = 0.0,
    supervisor: str | None = None,
)

One unit of work whose steps and guardrails are tracked.

Attributes:

Name Type Description
id str

Task identifier. Callers pass uuid4().hex when they have no id.

client_id str

Instance id of the client that created the task.

steps int

Governed model and tool calls already allowed in this task.

guardrails_ran set[str]

Guardrail names that have run while this task is active.

started_at datetime

When the task began. Run duration is measured from here.

cost_usd float

Estimated model spend recorded while this task is active.

supervisor str | None

Supervisor bound to this run, or None.

current_task

current_task(client_id: str) -> Task | None

Return the innermost active task for a client.

Parameters:

Name Type Description Default
client_id str

Client whose task to find. Other clients' tasks are ignored.

required

Returns:

Type Description
Task | None

The matching task, or None when that client has none active.

active_tasks

active_tasks(client_id: str) -> tuple[Task, ...]

Return every active task for a client, outermost first.

Parameters:

Name Type Description Default
client_id str

Client whose tasks to collect. Other clients' tasks are ignored.

required

Returns:

Type Description
Task

The tasks currently on the stack for that client. Empty when none

...

are active.

Example
from agent_tessera.context import Task, active_tasks, use_task

with use_task(Task("outer", "client-a")):
    with use_task(Task("inner", "client-a")):
        assert [task.id for task in active_tasks("client-a")] == ["outer", "inner"]

current_principal

current_principal() -> Principal | None

Return the principal shared by every client in this context.

Returns:

Type Description
Principal | None

The active principal, or None.

guardrails_ran

guardrails_ran(client_id: str) -> frozenset[str]

Return guardrails that have run for a client.

Parameters:

Name Type Description Default
client_id str

Client to read. When that client has an active task, the task's set is returned. Otherwise the set recorded outside a task is returned.

required

Returns:

Type Description
frozenset[str]

Guardrail names. Empty when none have run.

mark_guardrail_ran

mark_guardrail_ran(client_id: str, name: str) -> None

Record that a guardrail ran for a client.

Parameters:

Name Type Description Default
client_id str

Client the guardrail belongs to.

required
name str

Guardrail name, such as input.prompt_injection.

required

clear_guardrails

clear_guardrails(client_id: str) -> None

Forget guardrails that have run for a client.

Parameters:

Name Type Description Default
client_id str

Client whose set to clear. The active task is cleared when that client has one; otherwise the outside-task set is cleared.

required

use_task

use_task(task: Task) -> Iterator[Task]

Push a task and pop it when the block exits.

Parameters:

Name Type Description Default
task Task

Task to make active. Nested blocks keep the outer tasks.

required

Yields:

Type Description
Task

The same task.

Example
from agent_tessera.context import Task, current_task, use_task

task = Task("task-1", "client-a")
with use_task(task):
    assert current_task("client-a") is task
assert current_task("client-a") is None

use_principal

use_principal(principal: Principal) -> Iterator[Principal]

Set the shared principal and restore the previous one on exit.

Parameters:

Name Type Description Default
principal Principal

Person the enclosed calls are for.

required

Yields:

Type Description
Principal

The same principal.

Example
from agent_tessera.context import current_principal, use_principal
from agent_tessera.types import Principal

person = Principal("ada")
with use_principal(person):
    assert current_principal() is person

agent_tessera.errors

Errors raised by the Agent Tessera SDK.

TesseraError

Bases: Exception

Raise as the base class for every Agent Tessera error.

ServerError

Bases: TesseraError

Raise when the control plane cannot be used.

The server is unreachable, the credentials are rejected, or the response does not match the protocol.

ConfigError

Bases: TesseraError

Raise when SDK configuration is invalid.

The policy path is missing, the agent name does not match the loaded policy, or the wrapped client is unsupported.

PolicyError

PolicyError(message: str, *, path: Path | None = None)

Bases: TesseraError

Raise when a policy cannot be read or validated.

The string form is message alone, or <path>: <message> when path is set.

Parameters:

Name Type Description Default
message str

What is wrong with the policy.

required
path Path | None

File the error refers to. Omit it when the policy did not come from a file.

None
Example
from pathlib import Path

err = PolicyError("unknown field", path=Path("policy.yaml"))
assert err.path == Path("policy.yaml")
assert str(err) == "policy.yaml: unknown field"

Store the policy failure and an optional source path.

Parameters:

Name Type Description Default
message str

What is wrong with the policy.

required
path Path | None

File the error refers to. Omit it when the policy did not come from a file.

None

GovernanceError

GovernanceError(decision: Decision)

Bases: TesseraError

Raise when an action is not allowed to proceed.

The string form is <effect> <kind> '<resource>': <reason>. When rule is set, (rule <rule>) is appended.

Parameters:

Name Type Description Default
decision Decision

Decision that blocked the action.

required
Example
from agent_tessera import Action, Decision, Denied, Effect, Reason

decision = Decision(
    Effect.DENY,
    Reason.DENY_RULE,
    Action.tool("shell.exec"),
    "v1",
    "agent:tools.deny[0]",
)
assert str(Denied(decision)) == (
    "deny tool 'shell.exec': deny_rule (rule agent:tools.deny[0])"
)

Store the decision that blocked the action.

Parameters:

Name Type Description Default
decision Decision

Decision that blocked the action.

required

Denied

Denied(decision: Decision)

Bases: GovernanceError

Raise when policy denies an action.

ApprovalRequired

ApprovalRequired(
    decision: Decision, approval_id: str | None = None
)

Bases: GovernanceError

Raise when an action needs approval before it can proceed.

Attributes:

Name Type Description
approval_id str | None

Server approval id when the client did not wait. None when no request was stored.

Example
err = ApprovalRequired(decision, approval_id="01H")
assert err.approval_id == "01H"

Store the decision and, when present, the server approval id.

Parameters:

Name Type Description Default
decision Decision

Decision that still needs approval.

required
approval_id str | None

Id from POST /v1/approvals. Omit it offline.

None

RegistryError

Bases: TesseraError

Raise when a local agent registry cannot be read or changed.

Example
from agent_tessera import RegistryError

err = RegistryError("registry is locked")
assert str(err) == "registry is locked"

agent_tessera.types

Core value types for actions, principals, and policy decisions.

ActionKind

Bases: StrEnum

Name the kind of call a policy evaluates.

Attributes:

Name Type Description
MODEL

A model invocation, such as openai/gpt-4.1.

TOOL

A tool call.

DATA

A data-scope access, such as crm.customers:read.

AGENT

An outbound call to another agent.

Effect

Bases: StrEnum

Name the outcome of evaluating an action.

Attributes:

Name Type Description
ALLOW

The action may proceed.

DENY

The action is refused.

REQUIRE_APPROVAL

The action needs approval before it may proceed.

Reason

Bases: StrEnum

Name why a decision has its effect.

These values are stable strings recorded with each decision.

Attributes:

Name Type Description
SUSPENDED

The agent is suspended.

DENY_RULE

A deny list matched the action.

DELEGATION

The caller may not act for the principal.

GUARDRAIL_MISSING

A required input guardrail has not run.

NOT_GRANTED

No allow rule or granting approval rule matched.

LIMIT

A usage limit was reached.

APPROVAL_RULE

An approval rule matched.

ALLOW_RULE

An allow list matched.

APPROVAL_GRANTED

An approval handler allowed the action.

APPROVAL_REJECTED

An approval handler refused the action.

RUN_REVOKED

The active run was revoked.

POLICY_UNAVAILABLE

No current policy bundle is available.

FAIL_OPEN

The client allowed the action because the server was unreachable.

OUTSIDE_WINDOW

The action is outside the agent's operating window.

EFFECT_DENIED

An effect tag on the resource is denied.

ASSISTIVE_EFFECT

An assistive agent tried a side-effecting action.

EFFECT_APPROVAL

An effect tag on the resource requires approval.

APPROVAL_UNAVAILABLE

An unattended agent has nobody to ask.

APPROVAL_TIMEOUT

The approval route ended without a decision.

QUOTA_UNAVAILABLE

A shared quota cannot be charged.

CIRCUIT_OPEN

Too many recent denials opened the circuit breaker.

CHAIN_TOO_DEEP

The call chain is longer than agents.max_chain_depth.

CHAIN_REENTRY

This agent already appears in the chain.

PRINCIPAL_REQUIRED

A chain hop has no principal.

PRINCIPAL_FORBIDDEN

The agent must not act for a principal.

CHAIN_POLICY_UNAVAILABLE

A chain member's grants are not in the bundle.

SUPERVISOR_GRANTS_MISSING

cap_to_supervisor is set and that supervisor has no grant document.

UNSUPERVISED

A supervisor is required and none is resolved.

DEAD_MAN

The supervisor acknowledgement is overdue.

Principal dataclass

Principal(user: str, groups: frozenset[str] = frozenset())

Identify the person an action is performed for.

Parameters:

Name Type Description Default
user str

Stable user identifier.

required
groups frozenset[str]

Group names used by delegation checks. Empty when the user belongs to none.

frozenset()
Example
principal = Principal("ada", frozenset({"support"}))
assert principal.user == "ada"
assert "support" in principal.groups

Action dataclass

Action(
    kind: ActionKind,
    resource: str,
    args: Mapping[str, object] = dict(),
    principal: Principal | None = None,
)

Describe one model, tool, data, or agent call.

Instances compare by identity. args is copied so later changes to the mapping passed in do not change the action.

Parameters:

Name Type Description Default
kind ActionKind

Kind of call.

required
resource str

Model name, tool name, data scope, or agent name.

required
args Mapping[str, object]

Arguments supplied with the call. Empty when the call has none.

dict()
principal Principal | None

User this call is made for, when acting on behalf of someone.

None
Example
action = Action.tool("files.read")
assert action.kind is ActionKind.TOOL
assert action.resource == "files.read"
assert action.args == {}

__post_init__

__post_init__() -> None

Copy call arguments so the action keeps its own mapping.

model classmethod

model(name: str) -> Action

Build a model-call action.

Parameters:

Name Type Description Default
name str

Provider-qualified model name, such as openai/gpt-4.1.

required

Returns:

Type Description
Action

An action of kind model.

tool classmethod

tool(
    name: str, args: Mapping[str, object] | None = None
) -> Action

Build a tool-call action.

Parameters:

Name Type Description Default
name str

Tool name, which may include dots such as files.read.

required
args Mapping[str, object] | None

Arguments the tool was called with. None means no arguments.

None

Returns:

Type Description
Action

An action of kind tool.

data classmethod

data(scope: str) -> Action

Build a data-access action.

Parameters:

Name Type Description Default
scope str

Data scope, such as crm.customers:read.

required

Returns:

Type Description
Action

An action of kind data.

agent classmethod

agent(name: str) -> Action

Build an outbound call to another agent.

Parameters:

Name Type Description Default
name str

Name of the agent being called.

required

Returns:

Type Description
Action

An action of kind agent.

Decision dataclass

Decision(
    effect: Effect,
    reason: Reason,
    action: Action,
    policy_version: str,
    rule: str | None = None,
)

Record the result of evaluating one action.

Instances compare by identity. rule is an identifier such as agent:tools.allow[0] or agent:limits.max_steps_per_task, and is None when the reason is suspended or not_granted.

Parameters:

Name Type Description Default
effect Effect

Whether the action is allowed, denied, or needs approval.

required
reason Reason

Why the effect was chosen.

required
action Action

Action that was evaluated.

required
policy_version str

Identifier of the policy that produced this decision.

required
rule str | None

Identifier of the rule that decided the effect, if one applied.

None
Example
decision = Decision(
    Effect.DENY,
    Reason.NOT_GRANTED,
    Action.tool("shell.exec"),
    "v1",
)
assert decision.allowed is False
assert decision.rule is None

allowed property

allowed: bool

Return whether the effect is allow.

Returns:

Type Description
bool

True when effect is allow.

agent_tessera.policy

Policy schema, loading, and evaluation.

Import the schema types, YAML loaders, and evaluator from this package.

EffectivePolicy dataclass

EffectivePolicy(
    agent: str,
    environment: str,
    owner: str | None,
    version: str,
    applied_baselines: tuple[str, ...],
    allow: Mapping[ActionKind, tuple[PatternRule, ...]],
    deny: Mapping[ActionKind, tuple[PatternRule, ...]],
    approvals: Mapping[
        ActionKind, tuple[ApprovalPatternRule, ...]
    ],
    may_be_invoked_by: tuple[PatternRule, ...],
    delegation: Delegation,
    max_steps_per_task: LimitValue | None,
    tokens_per_day: LimitValue | None,
    cost_usd_per_day: LimitValue | None,
    calls_per_minute: tuple[tuple[str, LimitValue], ...],
    required_guardrails: tuple[RequiredGuardrail, ...],
    capture_content: bool,
    controls: EffectiveControls,
    max_chain_depth: int | None,
    allow_reentry: bool,
    caller_constraint: CallerConstraint
    | tuple[CallerConstraintRule, ...],
    peer_allows: Mapping[
        str, Mapping[ActionKind, tuple[str, ...]]
    ] = dict(),
    cap_to_supervisor: bool = False,
    supervisor_grants: Mapping[
        str, Mapping[ActionKind, tuple[str, ...]]
    ] = dict(),
    supervision_required: bool = False,
    max_unacknowledged_seconds: int | None = None,
)

The agent policy after applicable baselines have constrained it.

Attributes:

Name Type Description
agent str

Agent name.

environment str

Environment name.

owner str | None

Accountable owner, or None.

version str

sha256: plus the hex digest of the canonical merged input.

applied_baselines tuple[str, ...]

Names of baselines that matched, sorted.

allow Mapping[ActionKind, tuple[PatternRule, ...]]

Grant patterns for every action kind.

deny Mapping[ActionKind, tuple[PatternRule, ...]]

Deny patterns for every action kind. Agent entries come first.

approvals Mapping[ActionKind, tuple[ApprovalPatternRule, ...]]

Approval patterns for every action kind.

may_be_invoked_by tuple[PatternRule, ...]

Patterns for agents that may call this one.

delegation Delegation

On-behalf-of settings from the agent policy.

max_steps_per_task LimitValue | None

Smallest step limit that any source set.

tokens_per_day LimitValue | None

Smallest daily token limit that any source set.

cost_usd_per_day LimitValue | None

Smallest daily spend limit that any source set.

calls_per_minute tuple[tuple[str, LimitValue], ...]

Per-pattern call caps, sorted by pattern.

required_guardrails tuple[RequiredGuardrail, ...]

Required guardrails, sorted by name.

capture_content bool

Whether audit events may store prompts and responses.

controls EffectiveControls

Merged quotas, caps, effect tags, and autonomy.

max_chain_depth int | None

Most agents in a chain that reaches this one, including this agent. None sets no limit.

allow_reentry bool

Whether this agent may appear twice in one chain.

caller_constraint CallerConstraint | tuple[CallerConstraintRule, ...]

own, intersect, or per-caller rules.

peer_allows Mapping[str, Mapping[ActionKind, tuple[str, ...]]]

Allow globs for other agents, keyed by agent name and action kind. Empty in offline mode. The bundle supplies these when caller_constraint is intersect.

cap_to_supervisor bool

Whether model and tool calls must also match the resolved supervisor's grants.

supervisor_grants Mapping[str, Mapping[ActionKind, tuple[str, ...]]]

Allow globs keyed by supervisor id and action kind. Empty until a bundle supplies them.

supervision_required bool

Whether a missing supervisor denies every action.

max_unacknowledged_seconds int | None

Shortest dead-man duration, in seconds. None disables it.

RuntimeState dataclass

RuntimeState(
    suspended: bool = False,
    run_revoked: bool = False,
    guardrails_ran: frozenset[str] = frozenset(),
    steps_in_task: int | None = None,
    tokens_today: int = 0,
    calls_last_minute: Mapping[str, int] = dict(),
    now: datetime | None = None,
    approvals_available: bool = True,
    input_tokens: int | None = None,
    output_tokens: int | None = None,
    tool_arg_bytes: int | None = None,
    cost_usd: float | None = None,
    in_flight_model_calls: int = 0,
    in_flight_tool_calls: int = 0,
    concurrent_runs: int = 0,
    run_steps: int = 0,
    run_cost_usd: float = 0.0,
    run_elapsed_seconds: float | None = None,
    run_id: str | None = None,
    supervisor: str | None = None,
    quota_usage: Mapping[str, float] = dict(),
    recent_denials: int = 0,
    chain: tuple[str, ...] = (),
    dead_man: bool = False,
)

Snapshot of the counters and flags an evaluation may consult.

Attributes:

Name Type Description
suspended bool

When True, every action is denied.

run_revoked bool

When True, and the client is not suspended, every action is denied because the active run was revoked.

guardrails_ran frozenset[str]

Guardrail names that have already run.

steps_in_task int | None

Steps already taken in the active task. None means no task is active, so the step limit does not apply.

tokens_today int

Tokens recorded for the current day.

calls_last_minute Mapping[str, int]

Calls in the last minute, keyed by the calls_per_minute pattern.

now datetime | None

Clock used for the operating window. None uses the current time in the window's time zone.

approvals_available bool

Whether an approval handler or server route can answer. supervised and autonomous agents are denied when this is False.

input_tokens int | None

Estimated input tokens for this call, when known.

output_tokens int | None

Requested output tokens for this call, when known.

tool_arg_bytes int | None

Size of the tool arguments, when known.

cost_usd float | None

Estimated cost of this call, when known.

in_flight_model_calls int

Model calls already open on this instance.

in_flight_tool_calls int

Tool calls already open on this instance.

concurrent_runs int

Runs already open for this agent.

run_steps int

Steps already taken in the active run.

run_cost_usd float

Estimated spend already recorded for the active run.

run_elapsed_seconds float | None

Seconds since the active run started, when known.

run_id str | None

Active run id. Required by a run-scoped quota.

supervisor str | None

Bound supervisor. Required by a supervisor-scoped quota.

quota_usage Mapping[str, float]

Amount already consumed, keyed by quota name.

recent_denials int

Denials already recorded inside the circuit-breaker window.

chain tuple[str, ...]

Agents the request has already passed through, root first. This agent is not included. Empty when the call did not arrive from another agent.

dead_man bool

When True, and the policy sets max_unacknowledged, every action is denied.

ActiveHoursSpec

Bases: BaseModel

Name the clock window when governed actions are allowed.

Attributes:

Name Type Description
tz str

IANA time zone, such as Europe/Madrid.

days tuple[str, ...]

Weekdays or ranges. Each entry is mon through sun, or a range such as mon-fri.

from_ str

Local start time, HH:MM. Accepts the alias from.

to str

Local end time, HH:MM.

Example
hours = ActiveHoursSpec.model_validate(
    {"tz": "Europe/Madrid", "days": ["mon-fri"], "from": "08:00", "to": "20:00"}
)
assert hours.from_ == "08:00"

AgentPolicy

Bases: BaseModel

Grant an agent's permissions in one environment.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Policy schema version. Always tessera/v1. Accepts the alias apiVersion.

kind Literal['AgentPolicy']

Document kind. Always AgentPolicy.

metadata AgentPolicyMetadata

Agent identity.

spec AgentPolicySpec

Permissions, limits, and guardrails.

Example
policy = AgentPolicy(
    api_version="tessera/v1",
    kind="AgentPolicy",
    metadata=AgentPolicyMetadata(agent="support-triage", environment="prod"),
)
assert policy.spec.guardrails.on_missing == "flag"

AgentPolicyMetadata

Bases: BaseModel

Identify an agent and the selectors that apply to it.

Attributes:

Name Type Description
agent str

Agent name. Lowercase letters, digits, and hyphens, up to 63 characters, and it cannot start or end with a hyphen.

environment str

Environment name, using the same shape as agent.

owner str | None

Accountable owner. None when the policy names nobody.

risk_tier RiskTier

low, medium, or high.

labels dict[str, str]

Free-form labels used by baseline selectors.

autonomy AutonomySettings

How independently the agent acts, and its operating window.

AgentPolicySpec

Bases: BaseModel

Describe the permissions and limits of one agent.

Attributes:

Name Type Description
models ResourceRules

Rules for model calls.

tools ResourceRules

Rules for tool calls.

data ResourceRules

Rules for data scopes.

agents AgentRules

Rules for agent-to-agent calls.

delegation Delegation

On-behalf-of settings.

limits Limits

Usage bounds.

guardrails Guardrails

Required guardrails.

audit AuditSettings

Audit capture settings.

circuit_breaker CircuitBreakerSpec | None

Denial breaker. None disables it.

approvals ApprovalsSpec

How an approval is routed. The default offers it to the principal for 15 minutes.

effects EffectsSpec

Tool effect tags. Empty classification leaves every tool unclassified.

supervision SupervisionSpec

Whether model and tool calls are capped to the supervisor's grants.

AgentRules

Bases: BaseModel

Control which agents this agent may call and be called by.

Attributes:

Name Type Description
may_invoke tuple[str, ...]

Globs for agents this agent may call.

may_be_invoked_by tuple[str, ...]

Globs for agents that may call this agent.

max_chain_depth PositiveInt | None

Most agents allowed in a chain that reaches this one, including this agent. None sets no limit.

allow_reentry bool

Whether this agent may appear twice in one chain.

caller_constraint CallerConstraint | tuple[CallerConstraintRule, ...]

own, intersect, or a list of per-caller rules. own is the default.

Example
rules = AgentRules(caller_constraint="intersect", max_chain_depth=3)
assert rules.allow_reentry is False

ApprovalRule

Bases: BaseModel

Require approval for resources that match a glob.

Attributes:

Name Type Description
name str

Glob pattern matched against the resource name.

when tuple[Condition, ...]

Conditions that must all hold before approval is required. Empty means the pattern alone is enough.

ApprovalsSpec

Bases: BaseModel

Route an approval through one or more parties.

Attributes:

Name Type Description
route_to tuple[str, ...]

Escalation order. Each entry is principal, supervisor, owner, user:..., group:..., or agent:....

timeout str

How long each entry is offered the approval.

forbid_self_approval bool

Whether the principal who triggered the action may approve it.

Example
approvals = ApprovalsSpec.model_validate({"route_to": ["supervisor", "owner"]})
assert approvals.timeout == "15m"
assert approvals.forbid_self_approval is True

AuditSettings

Bases: BaseModel

Choose what an audit event may store.

Attributes:

Name Type Description
capture_content bool

Whether prompts and responses may be stored.

AutonomySettings

Bases: BaseModel

Choose how independently an agent acts, and when it may act.

A bare string such as interactive is the level, with no operating window.

Attributes:

Name Type Description
level AutonomyLevel

assistive, interactive, supervised, or autonomous.

active_hours ActiveHoursSpec | None

Operating window. None means the agent may act at any time.

Example
settings = AutonomySettings.model_validate("supervised")
assert settings.level == "supervised"
assert settings.active_hours is None

BaselinePolicy

Bases: BaseModel

Restrict agents across an organization.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Policy schema version. Always tessera/v1. Accepts the alias apiVersion.

kind Literal['BaselinePolicy']

Document kind. Always BaselinePolicy.

metadata BaselinePolicyMetadata

Baseline name.

spec BaselinePolicySpec

Restrictions and the selector that chooses agents.

BaselinePolicyMetadata

Bases: BaseModel

Name a baseline policy.

Attributes:

Name Type Description
name str

Baseline name, using the same shape as an agent name.

BaselinePolicySpec

Bases: BaseModel

Restrict agents that match a selector.

Attributes:

Name Type Description
selector Selector

Agents this baseline applies to.

models BaselineResourceRules

Extra model denials and approvals.

tools BaselineResourceRules

Extra tool denials and approvals.

data BaselineResourceRules

Extra data denials and approvals.

limits Limits

Upper bounds combined with the agent policy.

guardrails Guardrails

Guardrails every matching agent must run.

require_owner bool

Whether a matching agent policy must name an owner.

circuit_breaker CircuitBreakerSpec | None

Denial breaker. None disables it.

approvals ApprovalsSpec

Extra approval routing. A baseline may name an agent: reviewer; the agent's risk tier is checked on the agent policy.

effects EffectsSpec

Effect tags added to matching agents.

supervision SupervisionSpec

Extra supervisor requirements. required and max_unacknowledged merge with the agent. cap_to_supervisor on a baseline is ignored.

BaselineResourceRules

Bases: BaseModel

Deny or gate resources without granting new ones.

A string in require_approval is read as a rule with that name and no conditions. Baselines have no allow list.

Attributes:

Name Type Description
deny tuple[str, ...]

Glob patterns that refuse a resource.

require_approval tuple[ApprovalRule, ...]

Patterns that add an approval requirement.

CallerConstraintRule

Bases: BaseModel

Apply one chain constraint to a set of callers.

The first matching rule wins. callers entries are globs.

Attributes:

Name Type Description
callers tuple[str, ...]

Globs for the agents this rule covers. At least one.

constraint CallerConstraint

own limits the callee by its own policy. intersect also requires every agent in the chain to grant the action.

Example
rule = CallerConstraintRule(callers=("orchestrator",), constraint="intersect")
assert rule.constraint == "intersect"

CircuitBreakerSpec

Bases: BaseModel

Stop an agent after too many denials.

Attributes:

Name Type Description
denials PositiveInt

How many denials open the breaker.

window str

Sliding window, as seconds or Nh, Nm, or Ns.

action Literal['suspend', 'revoke_run']

suspend the agent or revoke_run.

Example
breaker = CircuitBreakerSpec(denials=5, window="10m", action="suspend")
assert breaker.denials == 5

ConcurrencyLimits

Bases: BaseModel

Cap how many calls or runs may be in progress together.

Attributes:

Name Type Description
max_in_flight_model_calls PositiveInt | None

Model calls one instance may have open.

max_in_flight_tool_calls PositiveInt | None

Tool calls one instance may have open.

max_concurrent_runs PositiveInt | None

Runs one agent may have open.

Example
limits = ConcurrencyLimits(max_in_flight_model_calls=4)
assert limits.max_concurrent_runs is None

Condition

Bases: BaseModel

Compare one call argument with an expected value.

in and not_in store value as a tuple. Ordering operators accept only an int or float, and reject bool. matches requires a regular expression.

Attributes:

Name Type Description
arg str

Name of the top-level call argument to read.

op Operator

Comparison operator.

value Any

Expected value. Its shape depends on op.

Example
condition = Condition(arg="status", op="in", value=["open", "closed"])
assert condition.value == ("open", "closed")

Delegation

Bases: BaseModel

Say whether the agent may act for a user.

Attributes:

Name Type Description
allow_on_behalf_of bool

Whether calls may carry a user principal.

user_groups tuple[str, ...]

Groups a principal must intersect when delegation is limited. Empty means any principal is allowed once delegation itself is allowed.

principal PrincipalMode

Whether a chain must, may, or must not carry a principal. optional is the default.

Example
delegation = Delegation(allow_on_behalf_of=True, principal="required")
assert delegation.principal == "required"

EffectsSpec

Bases: BaseModel

Classify tools and name the effects to deny or approve.

Attributes:

Name Type Description
classify dict[str, tuple[EffectTag, ...]]

Glob pattern to effect tags. Tags are read, write, delete, send, financial, credential, spawn, and irreversible.

deny tuple[EffectTag, ...]

Effect tags that are denied.

require_approval tuple[EffectTag, ...]

Effect tags that require approval.

Example
effects = EffectsSpec.model_validate(
    {"classify": {"zendesk.read_*": ["read"]}, "deny": ["delete"]}
)
assert effects.classify["zendesk.read_*"] == ("read",)

Guardrails

Bases: BaseModel

Name the guardrails an agent must run.

Attributes:

Name Type Description
required tuple[Annotated[str, StringConstraints(pattern=GUARDRAIL_NAME)], ...]

Guardrail names, each with at least one dot, such as input.prompt_injection.

on_missing OnMissing

What to do when a required guardrail has not run. One of block, warn, or flag.

Limits

Bases: BaseModel

Bound how much work an agent may do.

The v0.1 fields stay valid on their own. per_call, concurrency, run, and quotas add the v0.3 ceilings. A token or cost quota that applies to models still requires per_call.max_output_tokens; that check lives on the policy document.

Attributes:

Name Type Description
cost_usd_per_day PositiveFloat | None

Maximum model spend per day, in US dollars. This shorthand does not by itself require a per-call output cap.

tokens_per_day PositiveInt | None

Maximum total tokens per day.

calls_per_minute dict[str, PositiveInt]

Glob pattern to the maximum matching tool calls in a minute.

max_steps_per_task PositiveInt | None

Maximum model and tool steps in one task.

per_call PerCallLimits

Caps for one call.

concurrency ConcurrencyLimits

Caps for in-flight work.

run RunLimits

Caps for one run.

quotas tuple[QuotaSpec, ...]

General quotas. An empty tuple adds none.

Example
limits = Limits(tokens_per_day=1000)
assert limits.quotas == ()

PerCallLimits

Bases: BaseModel

Cap a single model or tool call.

Attributes:

Name Type Description
max_output_tokens PositiveInt | None

Most tokens a model response may request.

max_input_tokens PositiveInt | None

Most tokens a model prompt may contain.

max_tool_arg_bytes PositiveInt | None

Most bytes of tool arguments a call may send.

Example
cap = PerCallLimits(max_output_tokens=4096)
assert cap.max_input_tokens is None

QuotaSpec

Bases: BaseModel

One hard ceiling for a metric, window, and scope.

Attributes:

Name Type Description
name str

Quota name. Lowercase letters, digits, and hyphens.

metric QuotaMetric

What the counter measures.

window QuotaWindow

How long the counter covers.

scope QuotaScope

Who shares the counter.

max float

Hard ceiling. A float, so a cost ceiling can be fractional.

kinds tuple[ActionKind, ...] | None

Action kinds that count. None counts every kind.

resources tuple[str, ...] | None

Resource globs that count. None counts every resource.

warn_at float | None

Fraction of max that only warns. Greater than 0 and at most 1.

on_exhausted Literal['deny', 'suspend']

deny or suspend.

Example
quota = QuotaSpec(
    name="refunds-per-hour",
    metric="tool_calls",
    window="hour",
    scope="agent",
    max=20,
)
assert quota.on_exhausted == "deny"

ResourceRules

Bases: BaseModel

Grant, deny, or gate one class of resources.

A string in require_approval is read as a rule with that name and no conditions.

Attributes:

Name Type Description
allow tuple[str, ...]

Glob patterns that grant a resource.

deny tuple[str, ...]

Glob patterns that refuse a resource.

require_approval tuple[ApprovalRule, ...]

Patterns that grant a resource and may require approval.

Example
rules = ResourceRules.model_validate({"require_approval": ["files.delete"]})
assert rules.require_approval[0].name == "files.delete"

RunLimits

Bases: BaseModel

Cap one run.

Attributes:

Name Type Description
max_duration str | None

Longest run, as seconds or Nh, Nm, or Ns.

max_steps PositiveInt | None

Most steps in the run.

max_cost_usd PositiveFloat | None

Most estimated spend in the run, in US dollars.

Example
limits = RunLimits.model_validate({"max_duration": "2h", "max_steps": 50})
assert limits.max_duration == "2h"

Selector

Bases: BaseModel

Choose which agents a baseline applies to.

Attributes:

Name Type Description
environment str | None

Environment that must match. None does not filter.

risk_tier tuple[RiskTier, ...]

Risk tiers that match. Empty does not filter.

labels dict[str, str]

Label keys and values that must all be present on the agent.

autonomy tuple[AutonomyLevel, ...]

Autonomy levels that match. Empty does not filter.

matches

matches(metadata: AgentPolicyMetadata) -> bool

Return whether every set criterion applies to an agent.

An empty selector matches every agent. Environment is compared only when set, risk tier only when the list is non-empty, and each label only when present. Extra labels on the agent are ignored.

Parameters:

Name Type Description Default
metadata AgentPolicyMetadata

Agent identity to test.

required

Returns:

Type Description
bool

True when the agent satisfies every criterion this selector sets.

Example
selector = Selector(environment="prod")
agent = AgentPolicyMetadata(
    agent="support-triage",
    environment="prod",
    risk_tier="medium",
)
assert selector.matches(agent) is True

SupervisionSpec

Bases: BaseModel

Choose how a supervisor limits an agent.

Attributes:

Name Type Description
cap_to_supervisor bool

When True, a model or tool call must also match the resolved supervisor's grant document. A missing document denies the action.

required bool

When True, an action with no resolved supervisor is denied.

max_unacknowledged str | None

How long a supervisor may go without acknowledging the agent. None disables the dead-man switch. A baseline may set a shorter duration.

SupervisorAllowLists

Bases: BaseModel

Allow globs for one kind of action in a supervisor grant.

Attributes:

Name Type Description
allow tuple[Annotated[str, StringConstraints(min_length=1)], ...]

Glob patterns. Empty grants nothing of this kind.

SupervisorGrants

Bases: BaseModel

Allow lists for one supervisor.

Attributes:

Name Type Description
api_version Literal['tessera/v1']

Always tessera/v1.

kind Literal['SupervisorGrants']

Always SupervisorGrants.

metadata SupervisorGrantsMetadata

The supervisor id.

spec SupervisorGrantsSpec

Model and tool allow lists.

Example
grants = SupervisorGrants.model_validate(
    {
        "apiVersion": "tessera/v1",
        "kind": "SupervisorGrants",
        "metadata": {"supervisor": "user:ada"},
        "spec": {"tools": {"allow": ["files.read"]}},
    }
)
assert grants.spec.tools.allow == ("files.read",)

SupervisorGrantsMetadata

Bases: BaseModel

Name the supervisor a grant document belongs to.

Attributes:

Name Type Description
supervisor str

user: or group: id, at most 200 characters.

SupervisorGrantsSpec

Bases: BaseModel

Model and tool allows a supervisor grants.

Attributes:

Name Type Description
models SupervisorAllowLists

Model globs.

tools SupervisorAllowLists

Tool globs.

build_effective_policy

build_effective_policy(
    agent: AgentPolicy,
    baselines: Sequence[BaselinePolicy] = (),
) -> EffectivePolicy

Merge an agent policy with every baseline that selects it.

Parameters:

Name Type Description Default
agent AgentPolicy

Agent policy that grants permissions.

required
baselines Sequence[BaselinePolicy]

Candidate baselines. Only those whose selector matches are applied, in name order.

()

Returns:

Type Description
EffectivePolicy

The effective policy used for evaluation.

Raises:

Type Description
PolicyError

If two baselines share a name, or an applied baseline requires an owner and the agent names none.

Example
from agent_tessera.policy.effective import build_effective_policy
from agent_tessera.policy.models import AgentPolicy

policy = AgentPolicy.model_validate(
    {
        "apiVersion": "tessera/v1",
        "kind": "AgentPolicy",
        "metadata": {"agent": "bot"},
    }
)
effective = build_effective_policy(policy)
assert effective.agent == "bot"
assert effective.version.startswith("sha256:")

evaluate

evaluate(
    policy: EffectivePolicy,
    action: Action,
    state: RuntimeState | None = None,
) -> Decision

Decide whether one action is allowed.

The checks run in a fixed order and the first one that applies wins. Nothing is logged and no counters change.

Parameters:

Name Type Description Default
policy EffectivePolicy

Effective policy for the agent.

required
action Action

Action to evaluate.

required
state RuntimeState | None

Runtime flags and counters. Defaults to an empty state.

None

Returns:

Type Description
Decision

The decision, including the policy version.

Example
from agent_tessera.policy.effective import build_effective_policy
from agent_tessera.policy.evaluator import evaluate
from agent_tessera.policy.models import AgentPolicy
from agent_tessera.types import Action, Effect

agent = AgentPolicy.model_validate(
    {
        "apiVersion": "tessera/v1",
        "kind": "AgentPolicy",
        "metadata": {"agent": "bot"},
        "spec": {"tools": {"allow": ["files.read"]}},
    }
)
decision = evaluate(build_effective_policy(agent), Action.tool("files.read"))
assert decision.effect is Effect.ALLOW

load_agent_policy

load_agent_policy(path: str | Path) -> AgentPolicy

Read an agent policy from disk.

Parameters:

Name Type Description Default
path str | Path

Path of the policy file.

required

Returns:

Type Description
AgentPolicy

The agent policy.

Raises:

Type Description
PolicyError

If the file is not a readable AgentPolicy document.

load_baseline_policy

load_baseline_policy(path: str | Path) -> BaselinePolicy

Read a baseline policy from disk.

Parameters:

Name Type Description Default
path str | Path

Path of the policy file.

required

Returns:

Type Description
BaselinePolicy

The baseline policy.

Raises:

Type Description
PolicyError

If the file is not a readable BaselinePolicy document.

load_policy

load_policy(
    path: str | Path,
) -> AgentPolicy | BaselinePolicy | SupervisorGrants

Read one YAML policy document from disk.

Parameters:

Name Type Description Default
path str | Path

Path of the policy file.

required

Returns:

Type Description
AgentPolicy | BaselinePolicy | SupervisorGrants

The agent policy, baseline, or supervisor grant document.

Raises:

Type Description
PolicyError

If the file cannot be read, the YAML is invalid, or the document is not a single policy. The error's path is this file.

parse_policy

parse_policy(
    data: object, *, path: Path | None = None
) -> AgentPolicy | BaselinePolicy | SupervisorGrants

Validate one already parsed policy document.

Parameters:

Name Type Description Default
data object

A mapping with kind of AgentPolicy, BaselinePolicy, or SupervisorGrants.

required
path Path | None

File the document came from. Included in errors when set.

None

Returns:

Type Description
AgentPolicy | BaselinePolicy | SupervisorGrants

The agent policy, baseline, or supervisor grant document.

Raises:

Type Description
PolicyError

If data is not a policy document. Validation failures list each problem as <dotted.location>: <message>.

Example
from agent_tessera.policy import parse_policy

policy = parse_policy(
    {
        "apiVersion": "tessera/v1",
        "kind": "AgentPolicy",
        "metadata": {"agent": "bot"},
    }
)
assert policy.metadata.agent == "bot"

parse_duration

parse_duration(value: str) -> int

Parse a limit duration into seconds.

A bare number is seconds. h, m, and s suffixes select hours, minutes, and seconds. 2h, 30m, and 90 are valid. Combined values such as 2h30m are not.

Parameters:

Name Type Description Default
value str

Duration text, already stripped.

required

Returns:

Type Description
int

The duration in seconds.

Raises:

Type Description
ValueError

If the text is not a positive duration of that shape.

Example
from agent_tessera.policy.models import parse_duration

assert parse_duration("2h") == 7200
assert parse_duration("90") == 90

agent_tessera.otel

Optional OpenTelemetry spans for evaluation, enforcement, and calls.

Importing agent_tessera does not import OpenTelemetry. Spans are no-ops when the otel extra is not installed.

CallSpan

CallSpan(span: _Span, span_id: str, trace_id: str)

An OpenTelemetry call span held from decision until the call ends.

Attributes:

Name Type Description
span_id

16 lowercase hex characters.

trace_id

32 lowercase hex characters.

Store the live span and its formatted ids.

Parameters:

Name Type Description Default
span _Span

OpenTelemetry span started for this call.

required
span_id str

Formatted span id.

required
trace_id str

Formatted trace id.

required

activate

activate() -> None

Make this span the current OpenTelemetry span.

deactivate

deactivate() -> None

Restore the previous OpenTelemetry context.

end

end() -> None

Deactivate and finish the span.

trace_span

trace_span(
    name: str, attributes: Mapping[str, str] | None = None
) -> Iterator[_Span | None]

Start a span, or yield None when OpenTelemetry is not installed.

Parameters:

Name Type Description Default
name str

Span name, such as tessera.evaluate.

required
attributes Mapping[str, str] | None

Initial string attributes.

None

Yields:

Type Description
_Span | None

The span, or None.

Example
with trace_span("tessera.evaluate", {"tessera.agent": "bot"}):
    pass

start_call_span

start_call_span(
    attributes: Mapping[str, str] | None = None,
) -> CallSpan | None

Start a tessera.call span and return its ids, or None when OTel is off.

The span is not ended here. Callers must activate it while the governed call runs and end it afterwards.

Parameters:

Name Type Description Default
attributes Mapping[str, str] | None

Initial string attributes.

None

Returns:

Type Description
CallSpan | None

A live call span, or None when the tracer is unavailable.

set_attributes

set_attributes(
    span: _Span | None, attributes: Mapping[str, str]
) -> None

Add attributes to a span opened by trace_span.

Parameters:

Name Type Description Default
span _Span | None

Current span, or None when tracing is off.

required
attributes Mapping[str, str]

Names and values.

required

configure

configure(endpoint: str | None = None) -> bool

Export spans to an OTLP HTTP endpoint.

Parameters:

Name Type Description Default
endpoint str | None

Collector URL. None reads TESSERA_OTEL_ENDPOINT.

None

Returns:

Type Description
bool

True when a provider was installed. False when no endpoint is

bool

configured, the extra is missing, or a provider is already installed.

Example
assert configure() is False

agent_tessera.pricing

Estimate model cost from a built-in or caller-supplied price table.

Prices are USD per one million tokens. The built-in table is a small estimate for common OpenAI and Anthropic model names. Load another file with load_price_table when those rates are wrong. The first matching glob wins, so a specific pattern has to be listed before a broader one.

ModelPrice dataclass

ModelPrice(
    pattern: str,
    input_per_million: Decimal,
    output_per_million: Decimal,
)

USD rates for one model glob.

Attributes:

Name Type Description
pattern str

<provider>/<model> glob. * and ? are shell wildcards.

input_per_million Decimal

USD for one million input tokens.

output_per_million Decimal

USD for one million output tokens.

Example
price = ModelPrice("openai/gpt-4.1", Decimal("2"), Decimal("8"))
assert price.input_per_million == Decimal("2")

PriceTable dataclass

PriceTable(models: tuple[ModelPrice, ...])

Ordered model rates. The first matching pattern wins.

Attributes:

Name Type Description
models tuple[ModelPrice, ...]

Rates in match order.

Example
table = PriceTable((ModelPrice("local/*", Decimal("0"), Decimal("0")),))
assert table.models[0].pattern == "local/*"

load_price_table

load_price_table(path: Path | None = None) -> PriceTable

Load a price table from JSON, or the built-in table.

Parameters:

Name Type Description Default
path Path | None

JSON file to read. None reads the built-in table.

None

Returns:

Type Description
PriceTable

The parsed table. An empty models list prices every model at zero.

Raises:

Type Description
ConfigError

If the file cannot be read or is not a price table.

Example
from agent_tessera.pricing import load_price_table

table = load_price_table()
assert table.models

estimate_cost

estimate_cost(
    model: str,
    input_tokens: int,
    output_tokens: int,
    table: PriceTable,
) -> Decimal

Estimate the USD cost of one model call.

Parameters:

Name Type Description Default
model str

<provider>/<model> name.

required
input_tokens int

Prompt tokens. Must be zero or greater.

required
output_tokens int

Completion tokens. Must be zero or greater.

required
table PriceTable

Rates to use. The first matching pattern wins.

required

Returns:

Type Description
Decimal

The estimated cost. Zero when no pattern matches.

Raises:

Type Description
ValueError

If a token count is negative.

Example
from decimal import Decimal

from agent_tessera.pricing import PriceTable, ModelPrice, estimate_cost

table = PriceTable((ModelPrice("openai/gpt-4.1", Decimal("2"), Decimal("8")),))
assert estimate_cost("openai/gpt-4.1", 1_000_000, 0, table) == Decimal("2")
assert estimate_cost("local/echo", 10, 10, table) == Decimal("0")

model_price

model_price(
    model: str, table: PriceTable
) -> ModelPrice | None

Return the first rate whose pattern matches a model.

Parameters:

Name Type Description Default
model str

<provider>/<model> name.

required
table PriceTable

Rates in match order.

required

Returns:

Type Description
ModelPrice | None

The matching rate, or None when every pattern misses.

Example
from decimal import Decimal

from agent_tessera.pricing import PriceTable, ModelPrice, model_price

table = PriceTable((ModelPrice("openai/*", Decimal("1"), Decimal("1")),))
assert model_price("openai/gpt-4.1", table) is not None

claim_unknown_model

claim_unknown_model(model: str) -> bool

Remember an unknown model for this process.

Parameters:

Name Type Description Default
model str

Model name that had no price.

required

Returns:

Type Description
bool

True the first time this process sees model, otherwise False.

Example
from agent_tessera.pricing import claim_unknown_model

assert claim_unknown_model("vendor/example-once") is True
assert claim_unknown_model("vendor/example-once") is False

agent_tessera.quotas

Local quota counters and the model-call reservation estimate.

Instance-scoped quotas, and every quota while the SDK is offline, are counted here. A server lease is used for the other scopes. The reservation for a model call is ceil(estimate_input * 1.1) + max_output_tokens, where estimate_input is max(1, ceil(text_chars / 4)).

LocalQuotas

LocalQuotas()

Count quota usage inside one process.

Holds are included in try_reserve but not in used, so the call that placed a hold is not denied by its own reservation.

Example
from datetime import UTC, datetime

from agent_tessera.quotas import LocalQuotas

book = LocalQuotas()
moment = datetime(2026, 11, 6, tzinfo=UTC)
held = book.try_reserve("calls", "day", None, amount=1, maximum=2, moment=moment)
assert held is True
book.reconcile("calls", "day", None, reserved=1, actual=1, moment=moment)
assert book.used("calls", "day", None, moment) == 1

Start with empty counters.

used

used(
    name: str,
    window: str,
    run_id: str | None,
    moment: datetime,
) -> float

Return permanent usage for one quota bucket.

Parameters:

Name Type Description Default
name str

Quota name.

required
window str

Quota window.

required
run_id str | None

Active run, used when the window is run.

required
moment datetime

Time that selects a calendar bucket.

required

Returns:

Type Description
float

Usage already reconciled. A call window returns 0.

try_reserve

try_reserve(
    name: str,
    window: str,
    run_id: str | None,
    *,
    amount: float,
    maximum: float,
    moment: datetime,
) -> bool

Hold units when they still fit under the ceiling.

Parameters:

Name Type Description Default
name str

Quota name.

required
window str

Quota window.

required
run_id str | None

Active run, used when the window is run.

required
amount float

Units to hold.

required
maximum float

Quota ceiling in the same units.

required
moment datetime

Time that selects a calendar bucket.

required

Returns:

Type Description
bool

True when the hold was taken. A call window is not held here.

release

release(
    name: str,
    window: str,
    run_id: str | None,
    amount: float,
    moment: datetime,
) -> None

Give back a hold.

Parameters:

Name Type Description Default
name str

Quota name.

required
window str

Quota window.

required
run_id str | None

Active run, used when the window is run.

required
amount float

Units to release.

required
moment datetime

Time that selects a calendar bucket.

required

consume

consume(
    name: str,
    window: str,
    run_id: str | None,
    amount: float,
    moment: datetime,
) -> None

Add permanent usage.

Parameters:

Name Type Description Default
name str

Quota name.

required
window str

Quota window.

required
run_id str | None

Active run, used when the window is run.

required
amount float

Units to add.

required
moment datetime

Time that selects a calendar bucket.

required

reconcile

reconcile(
    name: str,
    window: str,
    run_id: str | None,
    *,
    reserved: float,
    actual: float,
    moment: datetime,
) -> None

Replace a hold with the measured usage.

Parameters:

Name Type Description Default
name str

Quota name.

required
window str

Quota window.

required
run_id str | None

Active run, used when the window is run.

required
reserved float

Units previously held.

required
actual float

Units to keep.

required
moment datetime

Time that selects a calendar bucket.

required

estimate_input_tokens

estimate_input_tokens(text_chars: int) -> int

Estimate input tokens from a character count.

Parameters:

Name Type Description Default
text_chars int

Characters of prompt text. Zero still estimates one token.

required

Returns:

Type Description
int

max(1, ceil(text_chars / 4)).

Example
from agent_tessera.quotas import estimate_input_tokens

assert estimate_input_tokens(8) == 2
assert estimate_input_tokens(0) == 1

reserved_input_tokens

reserved_input_tokens(text_chars: int) -> int

Return the input side of a model reservation.

Parameters:

Name Type Description Default
text_chars int

Characters of prompt text.

required

Returns:

Type Description
int

ceil(estimate_input_tokens(text_chars) * 1.1).

model_reservation

model_reservation(
    text_chars: int, max_output_tokens: int
) -> int

Return the tokens held before a model call.

Parameters:

Name Type Description Default
text_chars int

Characters of prompt text.

required
max_output_tokens int

Policy output cap. Zero when the policy sets none.

required

Returns:

Type Description
int

The input reservation plus the output cap.

Example
from agent_tessera.quotas import model_reservation

assert model_reservation(0, 100) == 102

text_chars

text_chars(value: object) -> int

Count characters in strings nested inside a call's arguments.

Parameters:

Name Type Description Default
value object

Arguments or keyword arguments. Mappings and sequences are walked. Other objects contribute nothing.

required

Returns:

Type Description
int

The total character count, stopping after six levels of nesting.

quota_applies

quota_applies(quota: QuotaLimit, action: Action) -> bool

Return whether a quota counts an action.

Parameters:

Name Type Description Default
quota QuotaLimit

Quota from the effective policy.

required
action Action

Action being governed.

required

Returns:

Type Description
bool

True when the kind and resource filters match.

server_leased

server_leased(quota: QuotaLimit) -> bool

Return whether the server, not this process, holds the counter.

Parameters:

Name Type Description Default
quota QuotaLimit

Quota from the effective policy.

required

Returns:

Type Description
bool

True for an agent, org, principal, supervisor, or run quota whose

bool

window is not call.

count_amount

count_amount(metric: str, kind: ActionKind) -> float

Return how many units one allowed call adds to a count metric.

Parameters:

Name Type Description Default
metric str

Quota metric.

required
kind ActionKind

Kind of the allowed action.

required

Returns:

Type Description
float

1 when the metric counts this kind, otherwise 0.

usage_amount

usage_amount(
    metric: str,
    *,
    input_tokens: int,
    output_tokens: int,
    cost_usd: float,
) -> float

Return the recorded size of one model call for a metric.

Parameters:

Name Type Description Default
metric str

Quota metric.

required
input_tokens int

Prompt tokens.

required
output_tokens int

Completion tokens.

required
cost_usd float

Estimated cost in dollars.

required

Returns:

Type Description
float

The amount to add. Count metrics return 0 here; they are counted

float

when the call is allowed.

agent_tessera.cli

Command-line interface for Agent Tessera (the tessera command).

build_parser

build_parser() -> argparse.ArgumentParser

Build the argument parser for the tessera command.

Returns:

Type Description
ArgumentParser

The configured top-level parser.

main

main(argv: Sequence[str] | None = None) -> int

Run the tessera command.

Parameters:

Name Type Description Default
argv Sequence[str] | None

Command-line arguments, excluding the program name. Defaults to sys.argv[1:].

None

Returns:

Type Description
int

The process exit code.

Example
from agent_tessera.cli import main

raise SystemExit(main(["--version"]))