Skip to content

Policy reference

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