Skip to content

The Python API

The names valgebra-planning promises a Python caller: each public module, the names its __all__ holds, and the two modules that need the mcp extra. The command line has a page of its own, and what each answer means is the method's.

Import a name from its module

from valgebra_planning.contracts import read_contract, read_task
from valgebra_planning.planner import plan
from valgebra_planning.program import render
from valgebra_planning.verify import verify

find = read_contract(
    {
        "name": "find_parcel",
        "inputSchema": {
            "type": "object",
            "properties": {"tracking": {"type": "string", "pattern": "^[A-Z]{2}[0-9]{9}[A-Z]{2}$"}},
            "required": ["tracking"],
        },
        "outputSchema": {
            "type": "object",
            "properties": {"parcel_id": {"type": "integer", "minimum": 1}},
            "required": ["parcel_id"],
        },
    }
)
contracts = {"find_parcel": find}
task = read_task(
    "find a parcel",
    {"tracking": {"type": "string", "pattern": "^[A-Z]{2}[0-9]{9}[A-Z]{2}$"}},
    {"type": "integer", "minimum": 1},
)
found = plan(contracts, task)
assert found.strong and found.program is not None
print(render(found.program))
checked = verify(found.program, contracts, task)
print(checked.count("proven"), "of", len(checked.links), "links proven")
c1 = find_parcel(tracking=tracking)
return c1.parcel_id
2 of 2 links proven

The tracking code lies inside find_parcel's argument, and the parcel identifier its output guarantees inside the goal.

The package itself exports nothing, and valgebra_planning.__all__ is empty. Three modules define a function of their own name, run, verify and proxy, so a function exported from the package would hide its module there; from valgebra_planning import * would bind plan, run and verify over a caller's own names; and an export of proxy or servers would import the mcp SDK on every import of the package, with or without the extra.

The public names

module names needs
valgebra_planning.contracts Contract, Slot, Task, read_contract, read_task
valgebra_planning.program Block, Branch, Call, Const, For, Next, Ref, Return, Stop, render, steps
valgebra_planning.planner DEPTH, Plan, Uncovered, plan, predicates
valgebra_planning.cells Abstraction, Cell, Predicate, Status, abstract, gather
valgebra_planning.verify Gap, Link, Verdict, Verification, verify
valgebra_planning.critic Critique, ProgramError, critique, read_program
valgebra_planning.codemode Repair, feedback, repair, stub, stubs
valgebra_planning.run Refusal, Run, ToolError, blame, run
valgebra_planning.policy Monitor, Policy, Reach, Transition, read_policy
valgebra_planning.flows Flow, read_flow
valgebra_planning.mining SlotKey, Types, infer_outputs, mine
valgebra_planning.library Library, Problem, read_library
valgebra_planning.privilege Change, Rule, Update, allowed, as_policy, describe, read_privileges, read_rules, updates
valgebra_planning.vacuity Certainty, Finding, vacuities
valgebra_planning.servers connect, read_server, run_on_server the mcp extra
valgebra_planning.proxy Gate, proxy, serve the mcp extra

A module's __all__ holds what a caller calls, the types those calls take and return, and the defaults a caller passes, DEPTH among them. Every other name a module defines serves the package's other modules and is not promised. valgebra_planning._valgebra, the one module importing valgebra and valgebra-jsonschema, and valgebra_planning.cli, the command line's, are not public.

What holds the table

tests/test_api.py holds the table to the package:

  • each public module's __all__ to its row, and the public modules to the rows;
  • each listed name to a definition in its own module, not one it imports;
  • each type a public function, class or method names in its signature to a public name, or to one valgebra, valgebra-jsonschema or the standard library defines;
  • the needs column to the modules that import mcp when they are imported.

The limit. Under 0.0.x a release may change any public name; the table says which names a release can break, not that it will not. The changelog records each change.

Reference

Each public module's names, read from their docstrings.

valgebra_planning.contracts

A tool's contract read as slots, and a task read as inputs and a goal.

An agent fills each argument of a call from a value it holds, so a tool is read as its argument slots, one per property of its input schema, and its result slots, one per field its output schema guarantees. Each slot is a set valgebra decides over, compiled by valgebra-jsonschema against the tool's own schema as root. To list the slots, the walk here reads five keywords itself, properties, required, items, prefixItems and a bare $ref, which it resolves from the document's root; what a keyword means is the companion's, so a slot a reading yields is kept only where valgebra proves the whole schema's set inside it.

Slot dataclass

One value a tool takes or returns: where it sits, and the set it lies in.

path is the argument's name for an argument, and the field names leading to it for a result, the empty path being the whole result. schema is the subschema as written, which a sampler draws members from against root, the document it sits in; values is the set it compiles to.

tool instance-attribute
tool: str
path instance-attribute
path: tuple[str, ...]
schema instance-attribute
schema: object
values instance-attribute
values: Validator[Any]
required instance-attribute
required: bool
root instance-attribute
root: object
name property
name: str

Return the slot as a program writes it: tool.path.

__init__
__init__(
    tool: str,
    path: tuple[str, ...],
    schema: object,
    values: Validator[Any],
    required: bool,
    root: object,
) -> None

Contract dataclass

A tool's slots, with its whole input set and whether its arguments are independent.

plain holds when the input schema constrains each argument on its own: each one proven inside its slot, with the required ones present, makes the record a member. Otherwise a call is accepted only once the record itself is proven inside accepts.

name instance-attribute
name: str
arguments instance-attribute
arguments: tuple[Slot, ...]
results instance-attribute
results: tuple[Slot, ...]
accepts instance-attribute
accepts: Validator[Any]
returns instance-attribute
returns: Validator[Any] | None
plain instance-attribute
plain: bool
idempotent class-attribute instance-attribute
idempotent: bool = False
hints class-attribute instance-attribute
hints: frozenset[str] = frozenset()
trusted class-attribute instance-attribute
trusted: bool = False
inferred class-attribute instance-attribute
inferred: bool = False
__init__
__init__(
    name: str,
    arguments: tuple[Slot, ...],
    results: tuple[Slot, ...],
    accepts: Validator[Any],
    returns: Validator[Any] | None,
    plain: bool,
    idempotent: bool = False,
    hints: frozenset[str] = frozenset(),
    trusted: bool = False,
    inferred: bool = False,
) -> None
argument
argument(name: str) -> Slot

Return the argument slot called name, or raise KeyError.

result
result(*path: str) -> Slot

Return the result slot at path, or raise KeyError.

Task dataclass

What an agent holds and what it must return.

held maps each variable the agent starts with to its slots, read as a result's are: the whole value and each field it guarantees. goal is the set the returned value must lie in, and goal_schema the schema it compiles from.

name instance-attribute
name: str
held instance-attribute
held: Mapping[str, tuple[Slot, ...]]
goal instance-attribute
goal: Validator[Any]
goal_schema instance-attribute
goal_schema: object
__init__
__init__(
    name: str,
    held: Mapping[str, tuple[Slot, ...]],
    goal: Validator[Any],
    goal_schema: object,
) -> None

read_contract

read_contract(spec: Mapping[str, Any]) -> Contract

Read one entry of a server's tool list into its contract.

Raises Unsupported for what valgebra-jsonschema refuses to read, and for an input schema whose properties it cannot list.

read_task

read_task(
    name: str, inputs: Mapping[str, object], goal: object
) -> Task

Read a task: the schema of each value the agent starts with, and of the goal.

valgebra_planning.program

A program of tool calls and type tests, and its text.

A program is a block: calls, each binding arguments to references or to constants and naming its result, then one ending. A return hands a reference back, a stop marks a value the program does not cover, and a test branches on whether a reference lies in a tool's argument, each branch a block of its own. A reference is a variable and a path of fields below it, c1.order.status; a constant is a JSON value, "delivered".

The text reads as Python, so a program written elsewhere in that form is read back by valgebra_planning.critic.

Ref dataclass

A variable, and the fields below it: c1.order.status is c1 at order.status.

variable instance-attribute
variable: str
path class-attribute instance-attribute
path: tuple[str, ...] = ()
__init__
__init__(variable: str, path: tuple[str, ...] = ()) -> None
__str__
__str__() -> str

Return the reference as a program writes it, a key no attribute names subscripted.

A key that is no Python identifier, or is a keyword, as a-b or class, reads back only as a subscript, x["a-b"], the form the critic reads it in.

Const dataclass

A JSON value written into a call, held as its JSON text so a program stays hashable.

text instance-attribute
text: str
value property
value: Any

Return the value the constant holds.

__init__
__init__(text: str) -> None
of staticmethod
of(value: Any) -> Const

Return the constant value, a JSON value.

__str__
__str__() -> str

Call dataclass

Call tool, each argument bound to a reference or a constant, the result result.

A tool may answer with an error. retry makes the call again until it succeeds, which only a tool that is read-only or idempotent allows; on_error is the block run instead of the rest, where the result is never bound.

tool instance-attribute
tool: str
bindings instance-attribute
bindings: tuple[tuple[str, Ref | Const], ...]
result instance-attribute
result: str
retry class-attribute instance-attribute
retry: bool = False
on_error class-attribute instance-attribute
on_error: Block | None = None
__init__
__init__(
    tool: str,
    bindings: tuple[tuple[str, Ref | Const], ...],
    result: str,
    retry: bool = False,
    on_error: Block | None = None,
) -> None

Return dataclass

Hand back the value of a reference: the task's goal must hold it.

ref instance-attribute
ref: Ref
__init__
__init__(ref: Ref) -> None

Stop dataclass

End a path the program does not cover; ref is the value left uncovered there.

ref instance-attribute
ref: Ref
__init__
__init__(ref: Ref) -> None

Branch dataclass

Branch on whether ref lies in a set: a tool's argument, JSON values listed, or a key.

With key set the set is every object holding that key, and the branch where it holds reads the fields the key opens. With tool empty the set is values, read as a JSON Schema enum: 1 and 1.0 are one value there. Otherwise it is the argument argument of tool.

ref instance-attribute
ref: Ref
tool instance-attribute
tool: str
argument instance-attribute
argument: str
then instance-attribute
then: Block
otherwise instance-attribute
otherwise: Block
values class-attribute instance-attribute
values: tuple[Any, ...] = ()
key class-attribute instance-attribute
key: str = ''
against property
against: str

Return the set as a program writes it.

__init__
__init__(
    ref: Ref,
    tool: str,
    argument: str,
    then: Block,
    otherwise: Block,
    values: tuple[Any, ...] = (),
    key: str = "",
) -> None

Next dataclass

End one iteration of a loop's body.

__init__
__init__() -> None

For dataclass

Run body once for each item of the array ref holds, named item; then after.

What the body calls is scoped to its iteration: after reads nothing of it.

ref instance-attribute
ref: Ref
item instance-attribute
item: str
body instance-attribute
body: Block
after instance-attribute
after: Block
__init__
__init__(
    ref: Ref, item: str, body: Block, after: Block
) -> None

Block dataclass

Calls in order, then one ending; a loop's body ends in Next.

calls instance-attribute
calls: tuple[Call, ...]
end instance-attribute
end: Return | Stop | Branch | For | Next
__init__
__init__(
    calls: tuple[Call, ...],
    end: Return | Stop | Branch | For | Next,
) -> None

render

render(block: Block, indent: str = '') -> str

Return the program as Python-like text, one step a line.

steps

steps(block: Block) -> int

Return the calls and tests on the longest path of a program, error paths included.

valgebra_planning.planner

Programs of calls and type tests, searched over the cells.

A state maps every reference the agent holds to the cells of the set it lies in. A call is enabled when each required argument can be bound to a reference whose cells all lie inside the argument's cells, and, where the input schema relates its arguments, valgebra proves the whole record inside it. A guarded call handles a reference that only overlaps an argument: it branches on the reference lying in the argument, calls the tool on the narrowed value, and goes on with the rest in the other branch. A program is strong when every path returns a reference whose cells lie inside the goal's: strong planning under nondeterministic outcomes (Cimatti et al. 2003, Def. 2.11), the outcomes partitioned by the cells rather than listed, and a branch on a runtime type test as an observation (Bertoli et al. 2006, Def. 2.8).

The search deepens on the calls and tests along a path, so the first strong program found is a shallowest one. Where none exists within the bound, one search at the full bound lets a branch stop once its sibling returns and no continuation exists within the depth its path has left, and each stop names the cells it leaves uncovered. Every program returned is checked again by valgebra_planning.verify.verify, which reads neither the cells nor the search.

DEPTH module-attribute

DEPTH = 6

Uncovered dataclass

A stop of a weak program: where, the reference, and the values it leaves uncovered.

examples holds a member of each uncovered cell that has one; undecided counts the uncovered cells that may be empty.

where instance-attribute
where: str
ref instance-attribute
ref: str
examples instance-attribute
examples: tuple[Any, ...]
undecided instance-attribute
undecided: int
__init__
__init__(
    where: str,
    ref: str,
    examples: tuple[Any, ...],
    undecided: int,
) -> None

Plan dataclass

A program for a task, whether it is strong, and what its stops leave uncovered.

assumed names each binding that rests on a mined semantic type or on an output schema inferred from observed calls, and each retry, which rests on its tool's errors being transient and, unless its server is trusted, on its annotations.

program instance-attribute
program: Block | None
strong instance-attribute
strong: bool
uncovered instance-attribute
uncovered: tuple[Uncovered, ...]
abstraction instance-attribute
abstraction: Abstraction
expanded instance-attribute
expanded: int
assumed class-attribute instance-attribute
assumed: tuple[str, ...] = ()
__init__
__init__(
    program: Block | None,
    strong: bool,
    uncovered: tuple[Uncovered, ...],
    abstraction: Abstraction,
    expanded: int,
    assumed: tuple[str, ...] = (),
) -> None

predicates

predicates(
    contracts: Mapping[str, Contract], task: Task
) -> list[Predicate]

Return every argument and the goal, and each result or input some of them may read.

A value no argument and no goal can hold is never passed on, so its cells cost the search and decide nothing; it is left out, with its reference. The sets are gathered in the order of their names, which fixes the cut: valgebra leaves some meets undecided, and which ones depends on the order the cut splits by and draws its members in, so a listing order of its own would make a library's count that order's.

plan

plan(
    contracts: Mapping[str, Contract],
    task: Task,
    *,
    depth: int = DEPTH,
    seed: int = 0,
    weak: bool = True,
    errors: bool = False,
    policies: Sequence[Policy] = (),
    flows: Sequence[Flow] = (),
    types: Types | None = None,
) -> Plan

Search a program for task over contracts: strong first, then weak if asked.

With errors, any tool may answer with an error, and every call is retried or given a block for it, as valgebra_planning.verify.verify holds with the same flag. A call is made only where valgebra proves it keeps every policy away from its bad states, and a call a policy reads is kept even where no result of it is read; a path ends, in a return or a stop, only where no policy holds a pending state. A value reaches a flow rule's sink only as valgebra_planning.verify.verify holds it with the same rules. With mined types, a value fills an argument only where their types agree, and the plan names every binding that rests on one. Raises ValueError for a task naming an input as a tool.

valgebra_planning.cells

The cells: the minterms of every set a plan reads, within each kind of JSON value.

Every slot, input and goal is a predicate on JSON values. Each predicate taken inside or outside cuts the values into cells, and each predicate is exactly a union of cells, so an inclusion between two predicates' cells implies the inclusion between the predicates: the canonical monomials of the predicates as abstract states (Graf and Saidi 1997, §2.2), the minterms of an effective Boolean algebra (D'Antoni and Veanes 2017, §2.1). The values split first into seven disjoint kinds, and a predicate cuts only the cells of the kinds it meets.

A part of a cell is dropped only where valgebra proves it empty. It is inhabited where a concrete value lies in it, or where valgebra refutes its emptiness. Every other part is kept as undecided, so it can cost a plan, never admit a wrong one. Most cuts are settled by relations between two predicates, each asked of valgebra once: a cell inside a predicate disjoint from the new one lies outside it, a cell inside a predicate below the new one lies inside it, and a cell outside a predicate above it lies outside it.

Status module-attribute

Status = Literal['inhabited', 'undecided']

Predicate dataclass

A set a plan reads, with the schema it compiles from and the names standing for it.

names instance-attribute
names: tuple[str, ...]
values instance-attribute
values: Validator[Any]
schema instance-attribute
schema: object
root instance-attribute
root: object
__init__
__init__(
    names: tuple[str, ...],
    values: Validator[Any],
    schema: object,
    root: object,
) -> None

Cell dataclass

One minterm: a kind, the predicates it lies inside, and whether it holds a value.

The cell lies outside every predicate of its kind not in inside. witness holds a member where one is known; an inhabited cell without one was proven non-empty.

kind instance-attribute
kind: str
inside instance-attribute
inside: frozenset[int]
values instance-attribute
values: Validator[Any]
status instance-attribute
status: Status
witness class-attribute instance-attribute
witness: tuple[Any, ...] = ()
__init__
__init__(
    kind: str,
    inside: frozenset[int],
    values: Validator[Any],
    status: Status,
    witness: tuple[Any, ...] = (),
) -> None

Abstraction dataclass

The predicates of a plan and the cells they cut the JSON values into.

predicates instance-attribute
predicates: tuple[Predicate, ...]
cells instance-attribute
cells: tuple[Cell, ...]
asked class-attribute instance-attribute
asked: int = 0
__init__
__init__(
    predicates: tuple[Predicate, ...],
    cells: tuple[Cell, ...],
    asked: int = 0,
    _members: dict[int, frozenset[int]] = dict(),
) -> None
index
index(name: str) -> int

Return the predicate a name stands for, or raise KeyError.

cells_of
cells_of(predicate: int) -> frozenset[int]

Return the cells lying inside a predicate.

members
members(cell: int) -> tuple[Any, ...]

Return the values a cell holds where a predicate it lies inside lists them all.

Elsewhere, the member found for it, if any.

undecided
undecided(cells: Iterable[int]) -> int

Return how many of cells may be empty.

gather

gather(
    entries: Iterable[
        tuple[str, Validator[Any], object, object]
    ],
) -> list[Predicate]

Merge named sets valgebra holds equal into one predicate each, keeping order.

Two schemas differing in a description, a title or a default compile to one set, and a predicate per spelling would only ask each relation again; the first spelling stays, to draw members from.

abstract

abstract(
    predicates: Sequence[Predicate], *, seed: int = 0
) -> Abstraction

Cut the JSON values into the cells of predicates.

valgebra_planning.verify

Every link of a program, asked of valgebra alone.

A link is an inclusion a program rests on: a reference inside the argument it fills, a call's whole argument record inside the tool's input set where the arguments are related, and the returned reference inside the goal. Each is asked of valgebra with the set the reference lies in at that point of the program, narrowed by every test on the way there, and nothing else, not the cells, not the search: the belief execution along a path (Bertoli et al. 2006, Def. 3.4), each reference's set read apart from the others'. A program whose every link is proven and on which no path stops is a strong solution, applicable at each call and inside the goal at the end of each path (Bertoli et al. 2006, Thm. 3.5). A refuted link carries a value outside the inclusion where one is found among the examples given and the values drawn from the reference's own schema. A value found that way refutes an undecided link too, since a concrete member is a proof.

Verdict module-attribute

Verdict = Literal['proven', 'refuted', 'undecided']

One inclusion a program rests on, where it sits, and what valgebra says of it.

where names the branches leading to it, then and else joined by dots, the empty string being the top. counterexample holds the value refuting it, when one is found.

where instance-attribute
where: str
claim instance-attribute
claim: str
verdict instance-attribute
verdict: Verdict
counterexample class-attribute instance-attribute
counterexample: tuple[Any, ...] = ()
assumed class-attribute instance-attribute
assumed: tuple[str, ...] = ()
__init__
__init__(
    where: str,
    claim: str,
    verdict: Verdict,
    counterexample: tuple[Any, ...] = (),
    assumed: tuple[str, ...] = (),
) -> None

Gap dataclass

A path the program stops on, and the reference it leaves uncovered there.

where instance-attribute
where: str
ref instance-attribute
ref: str
__init__
__init__(where: str, ref: str) -> None

Verification dataclass

The links of a program and the gaps it leaves.

links: tuple[Link, ...]
gaps instance-attribute
gaps: tuple[Gap, ...]
proven property
proven: bool

Return whether every link is proven and no path stops.

__init__
__init__(
    links: tuple[Link, ...], gaps: tuple[Gap, ...]
) -> None
count
count(verdict: Verdict) -> int

Return how many links read verdict.

verify

verify(
    program: Block,
    contracts: Mapping[str, Contract],
    task: Task,
    *,
    examples: Mapping[str, Sequence[Any]] | None = None,
    seed: int = 0,
    errors: bool = False,
    policies: Sequence[Policy] = (),
    flows: Sequence[Flow] = (),
) -> Verification

Ask every link of program of valgebra, for task over contracts.

examples maps a reference, written as the program writes it, to values it may hold, tried first in search of a counterexample. With errors, any tool may answer with an error, and a call neither retried nor given an error block leaves that path uncovered. A retry is accepted only for a tool that is read-only or idempotent, since calling twice must act as calling once; it ends under fairness, the strong cyclic reading (Cimatti et al. 2003, Def. 2.10). Each policy adds a link at the end of every path: proven where no bad state can be reached there, refuted where one surely is, undecided where one possibly is. Each flow rule adds a link for every value from one of its sources bound to its sink, and, where implicit flows are read, for every call to the sink under a test on such a value. Raises ValueError for a task naming an input as a tool, whose source no name could tell apart.

valgebra_planning.critic

A program written elsewhere, read from Python, verified, and answered with a critique.

A language model proposes, a sound critic checks (Kambhampati et al. 2024, §3.1): the program's every link is asked of valgebra by valgebra_planning.verify.verify, under the rules the task is held to, and the answer names each link that is not proven, the value that refutes it where one is found, and what the author can change: for an argument a value only overlaps, the test that makes the call safe; for a rule, the order, the source or the error block it needs.

The reader takes the Python an agent writes against typed tool APIs: a function or a bare block of statements; c1 = find_parcel(tracking=tracking) or tools.find_parcel(...), awaited or not; fields as attributes or as string subscripts; return; stop(ref); and an argument as a value the program holds or a JSON constant (state="delivered"); if/elif/else testing a value against a tool's argument (ref in tool.argument) or against listed constants (==, !=, in, not in), or a key of a record ("field" in ref); retry(tool(...)); and try: around one call with except ToolError:; for item in ref: over an array, whose body ends each iteration where its statements run out and never returns; and pass. Anything else is refused by line, never skipped.

ProgramError

Bases: ValueError

A program the reader does not read, with the line that stops it.

Critique dataclass

A proposed program, its verification, and the critique to hand back to its author.

program instance-attribute
program: Block
verification instance-attribute
verification: Verification
notes instance-attribute
notes: tuple[str, ...]
accepted property
accepted: bool

Return whether every link is proven and no path stops.

__init__
__init__(
    program: Block,
    verification: Verification,
    notes: tuple[str, ...],
) -> None

read_program

read_program(source: str) -> Block

Read a program from Python source: one function, or a block of statements.

Raises ProgramError naming the line of a construct it does not read.

critique

critique(
    source: str,
    contracts: Mapping[str, Contract],
    task: Task,
    *,
    examples: Mapping[str, Sequence[Any]] | None = None,
    errors: bool = False,
    policies: Sequence[Policy] = (),
    flows: Sequence[Flow] = (),
    types: Types | None = None,
) -> Critique

Read, verify and critique a program proposed for task under the rules it is held to.

errors, policies and flows are held as valgebra_planning.verify.verify holds them. Mined types decide nothing: a binding crossing two types the observed calls show is a note, and the program is accepted or not on its links alone. Raises ProgramError for a program the reader does not read.

valgebra_planning.codemode

Typed tool stubs for a model to write a program against, and the loop that repairs it.

In code mode a model writes a program against typed tool APIs rather than calling tools one by one. stubs gives those APIs as Python: one function a tool, every argument by name, its type hint the kind its schema names, and its docstring the tool's own input and output JSON Schemas, since a pattern or a bound has no Python type and the critic holds the program to the schemas. repair is the loop of a model that proposes and a sound critic that checks, the critique handed back as the next prompt (Kambhampati et al. 2024, §3.2): a program is critiqued, and its critique handed back for the next proposal, until it is accepted or the rounds run out. The model is any callable from the last critique to a program, so no model is part of this package.

Repair dataclass

The rounds a program took: each source proposed and its critique, or why it was not read.

rounds instance-attribute
rounds: tuple[tuple[str, Critique | str], ...]
accepted property
accepted: bool

Return whether the last program proposed was accepted.

__init__
__init__(
    rounds: tuple[tuple[str, Critique | str], ...],
) -> None

stub

stub(contract: Contract) -> str

Return a tool's stub: its signature, and its input and output schemas as its docstring.

stubs

stubs(contracts: Mapping[str, Contract]) -> str

Return the stubs of every tool, after the preamble stating the language a program uses.

feedback

feedback(checked: Critique | str) -> str

Return a critique as the text handed back to the model: each note, a line.

repair

repair(
    propose: Callable[[str | None], str],
    contracts: Mapping[str, Contract],
    task: Task,
    *,
    rounds: int = 3,
    **rules: Any,
) -> Repair

Propose, critique and hand the critique back, until a program is accepted or rounds end.

propose takes the last critique as text, None the first time, and returns a program's source. The rules are those valgebra_planning.critic.critique holds a program to.

valgebra_planning.run

A program run on concrete values, each argument and result checked against its contract.

The runner calls the tools a program names with the values the program binds, takes each branch by testing the value it reads, and checks every argument record against the tool's input set, every policy's step before the call, every result against its output set and the returned value against the goal. It fails closed: a broken check stops the run before the call is made, the result bound or the value returned, and the run names the check. A field the program reads and the value it holds lacks ends the run, named as a check too, since no value can be passed on in its place. A proof of the program rests on the contracts; a tool that answers outside its own is what a run must not pass on. With enforce=False a break is recorded and the run goes on, so one run reports every break it meets: a diagnosis, never a guard.

ToolError

Bases: Exception

A tool answered with an error: an MCP result with isError set.

Refusal dataclass

Which check ended a run: arguments, policy, result, goal, error or read.

tool is the tool the check was on, where it was on one.

check instance-attribute
check: str
tool class-attribute instance-attribute
tool: str | None = None
retried class-attribute instance-attribute
retried: bool = False
__init__
__init__(
    check: str,
    tool: str | None = None,
    retried: bool = False,
) -> None

Run dataclass

What a run returned or where it stopped, and every contract it broke on the way.

value instance-attribute
value: Any
stopped instance-attribute
stopped: str | None
broken instance-attribute
broken: tuple[str, ...]
refused class-attribute instance-attribute
refused: str | None = None
why class-attribute instance-attribute
why: Refusal | None = None
__init__
__init__(
    value: Any,
    stopped: str | None,
    broken: tuple[str, ...],
    refused: str | None = None,
    why: Refusal | None = None,
) -> None

run

run(
    program: Block,
    contracts: Mapping[str, Contract],
    task: Task,
    inputs: Mapping[str, Any],
    tools: Mapping[str, Callable[..., Any]],
    *,
    policies: Sequence[Policy] = (),
    enforce: bool = True,
) -> Run

Run program on inputs, calling tools by name, checking every contract.

Each policy is stepped on a call before it is made, and reaching a bad state is a broken check like a broken contract, as is a run ending, in a return or a stop, in a pending one. With enforce, the default, the first broken check ends the run, named in Run.refused; without it every break is recorded and the run goes on. Raises ValueError for a task naming an input as a tool.

blame

blame(
    result: Run,
    contracts: Mapping[str, Contract],
    *,
    proven: bool,
) -> str | None

Return why a run broke, given whether its program was proven; None if nothing broke.

A proven program breaks at run time only where something it rests on fails: a tool's result outside the output schema its server declared is the server's, one outside a schema shaped from observed calls is that assumption's, and an error a retry could not outlast is the fairness a retry assumes. An argument record, a policy or a returned value breaking in a proven program is a check the verification proved: a defect of this package or of valgebra. An unproven program's break is its own link's.

valgebra_planning.policy

Policies over the calls a program makes: automata whose guards are valgebra sets.

A policy is a symbolic automaton over call events (D'Antoni and Veanes 2017, Def. 1): a transition fires on a call to its tool whose argument record lies in its guard, a JSON Schema the companion reads into a set. Some states are bad: reaching one is a violation, and a bad state is never left. Some are pending: a path may pass through one and must not end in one, an obligation still open, as a notice owed after a booking. A call no guard of the current state matches keeps that state. It states what a domain policy says in prose (τ-bench, Yao et al. 2024, §3), and what a trace rule checks one prefix at a time (AgentLTL, Elkoussy and Perez 2026, §3.4), as a set a whole program is decided against before it runs.

Statically, a program's every path steps the automaton with the argument records it may pass: a guard is taken surely where valgebra proves the record inside it, never where it proves them disjoint, and possibly otherwise. A path ending in a bad or a pending state surely refutes the program, possibly leaves it undecided, and no path ending in one proves it; a bad state never left makes ending in one the same as reaching one. Every path of a program ends, a loop's after any number of items, so an obligation is decided over the whole program before it runs, where a monitor reading a run's prefix cannot decide it (Bauer et al. 2011, Def. 3.4). At run time the same automaton is a monitor stepping on concrete records, and reading the pending states when the run ends.

A policy reads one program's calls in order. It carries no value from one call to another, so a rule about the same parcel across two calls is read as a rule about any two calls: a program approving one parcel and booking another passes a rule that a booking follows its own parcel's approval. A rule that a call takes a value another returned is a flow rule with only (valgebra_planning.flows). A policy instance per value, a parametric property (Roşu and Chen 2012, Def. 12), is not read.

Reach module-attribute

Reach = Literal['never', 'possibly', 'surely']

Transition dataclass

From source to target on a call to tool whose arguments lie in guard.

With hint set and tool empty, the call is to any tool whose annotations set that hint, destructiveHint or another: a hint its server gives, untrusted unless the server is.

source instance-attribute
source: str
tool instance-attribute
tool: str
guard instance-attribute
guard: Validator[Any]
target instance-attribute
target: str
hint class-attribute instance-attribute
hint: str = ''
__init__
__init__(
    source: str,
    tool: str,
    guard: Validator[Any],
    target: str,
    hint: str = "",
) -> None
reads
reads(tool: str, hints: frozenset[str]) -> bool

Return whether a call to tool, whose annotations set hints, is one it reads.

Policy dataclass

An automaton over call events: where it starts, its bad states and its pending ones.

name instance-attribute
name: str
initial instance-attribute
initial: str
bad instance-attribute
bad: frozenset[str]
transitions instance-attribute
transitions: tuple[Transition, ...]
pending class-attribute instance-attribute
pending: frozenset[str] = frozenset()
__init__
__init__(
    name: str,
    initial: str,
    bad: frozenset[str],
    transitions: tuple[Transition, ...],
    pending: frozenset[str] = frozenset(),
) -> None
tools
tools() -> frozenset[str]

Return every tool a transition names.

hints
hints() -> frozenset[str]

Return every annotation hint a transition reads.

step
step(
    states: frozenset[str],
    tool: str,
    record: Validator[Any],
    hints: frozenset[str] = frozenset(),
) -> frozenset[str]

Return the states the automaton may be in after a call whose record lies in record.

A transition taken surely leaves its source; one taken possibly adds its target and keeps the source, as does a call no guard of the state surely matches. A bad state is never left.

reach
reach(
    states: frozenset[str], *, ended: bool = False
) -> Reach

Return whether a bad state is held, or a pending one where a path ends: surely if all.

A path that has not ended may pass through a pending state.

Monitor dataclass

A policy stepped on concrete calls, as a run makes them.

policy instance-attribute
policy: Policy
state class-attribute instance-attribute
state: str = ''
violations class-attribute instance-attribute
violations: list[str] = field(default_factory=list)
__init__
__init__(
    policy: Policy,
    state: str = "",
    violations: list[str] = list(),
) -> None
__post_init__
__post_init__() -> None
observe
observe(
    tool: str,
    arguments: Mapping[str, Any],
    hints: frozenset[str] = frozenset(),
) -> bool

Step on one call; return whether it reached a bad state, which it never leaves.

ended
ended() -> bool

Return whether the run ends in a pending state: an obligation it leaves open.

read_policy

read_policy(spec: Mapping[str, Any]) -> Policy

Read a policy: name, initial, bad states, transitions and pending.

Each transition names its from and to states and its tool, or the annotation hint a tool must set, and optionally the JSON Schema its arguments record must meet, every record where it names none.

valgebra_planning.flows

Where a value came from, and which arguments it may reach.

A program's control flow is fixed before any tool runs, so the origin of every value it passes on is known from the program alone: a task input, or the result of a named tool. A flow rule names untrusted sources and a sink argument. A value from a source reaches the sink only where valgebra proves it inside the rule's endorsed set, when the rule names one, the narrowing a test or a sanitizing tool performs; otherwise it does not reach it at all. This is the integrity half of information-flow control for agents, a value's provenance as its capability (CaMeL, Debenedetti et al. 2025, §5.3) and its integrity as its label (FIDES, Costa et al. 2025, §4.1), and a privilege rule over arguments (Progent, Shi et al. 2025, §4.1), decided over sets rather than checked per value.

With implicit, a sink call made under a test on a value from a source is refused too: which branch runs carries that value's influence, the dependency on a condition that CaMeL's STRICT mode adds (Debenedetti et al. 2025, §5.4).

With only, the rule holds every origin but its sources: a value from a tool it does not name, from a task input it does not name, or written into the program as a literal reaches the sink only inside the endorsed set. That is integrity as provenance: an identifier must come from the tool that retrieved it, on every path, which refutes the identifier a model makes up to pass an authentication step, the integrity leak (Sah et al. 2026, §4.3).

Flow dataclass

Values from the origins the rule holds reach tool.argument only inside endorsed.

It holds sources, or, with only, every origin but them.

name instance-attribute
name: str
sources instance-attribute
sources: frozenset[str]
tool instance-attribute
tool: str
argument instance-attribute
argument: str
endorsed instance-attribute
endorsed: Validator[Any] | None
implicit instance-attribute
implicit: bool
only class-attribute instance-attribute
only: bool = False
sink property
sink: str

Return the sink as a program writes it.

__init__
__init__(
    name: str,
    sources: frozenset[str],
    tool: str,
    argument: str,
    endorsed: Validator[Any] | None,
    implicit: bool,
    only: bool = False,
) -> None
holds
holds(origin: str | None) -> bool

Return whether a value from origin is held to the rule; None is a literal.

read_flow

read_flow(spec: Mapping[str, Any]) -> Flow

Read a flow rule from its JSON form.

It holds name, sources, sink as tool.argument, and optionally the endorsed JSON Schema, implicit and only. A source is a tool's name or a task input's.

valgebra_planning.mining

Semantic types mined from observed calls, stated as assumptions.

Two slots with the same schema are one set to valgebra, so the planner may pass a customer's name where a ticket's subject goes. Observed calls tell them apart: a value a tool returned that a later call took as an argument links the two slots, and slots linked by any shared value form one semantic type (APIphany, Guo et al. 2022, §4). A binding across two types is then refused, which narrows the planner's choices to what the observations show.

A mined type is an assumption, never a proof: the verifier reads none, every link of a program stays valgebra's, and a plan names each binding that relied on one. A slot never observed carries no type and is bound as its set alone allows.

SlotKey module-attribute

SlotKey = tuple[str, str]

Types dataclass

The semantic type of every slot seen in the observations.

of instance-attribute
of: Mapping[SlotKey, int]
__init__
__init__(of: Mapping[SlotKey, int]) -> None
agree
agree(one: SlotKey, other: SlotKey) -> bool

Return whether two slots may be bound together: one is untyped, or both share one.

typed
typed(one: SlotKey, other: SlotKey) -> bool

Return whether both slots carry a type, so binding them rests on the observations.

mine

mine(
    observed: Iterable[Mapping[str, Any]],
    contracts: Mapping[str, Contract],
) -> Types

Return the semantic types the observed calls show.

Each observation is {"tool": name, "arguments": {...}, "result": ...}. Every argument and every result field a contract names is a slot; two slots holding one value, under JSON equality, are one type.

infer_outputs

infer_outputs(
    observed: Iterable[Mapping[str, Any]],
    listing: Iterable[Mapping[str, Any]],
) -> dict[str, dict[str, Any]]

Return an output schema for each listed tool declaring none, shaped from its results.

An inferred schema is an assumption, as a mined type is: a contract carrying one is marked valgebra_planning.contracts.Contract.inferred, and every link and binding resting on it names it.

valgebra_planning.library

A library on disk: a server's tool list, the tasks over it and the rules each is held to.

A library is a directory. tools.json holds a server's tools/list result, {"tools": [...]}, and "trusted": true where the server's annotations are trusted. tasks.json holds {"tasks": [...]}, each task its name, the JSON Schema of each input in inputs and of the goal, and the rules it names: errors (any tool may fail), policies and flows by name, and types, the file of observed calls its types are mined from; a tool listed without an outputSchema gets one shaped from its results in those observed calls, an assumption (valgebra_planning.mining.infer_outputs). policies.json and flows.json hold the rules a task names, as valgebra_planning.policy.read_policy and valgebra_planning.flows.read_flow read them.

Problem dataclass

A task and the rules a program for it is held to.

task instance-attribute
task: Task
errors class-attribute instance-attribute
errors: bool = False
policies class-attribute instance-attribute
policies: tuple[Policy, ...] = ()
flows class-attribute instance-attribute
flows: tuple[Flow, ...] = ()
types class-attribute instance-attribute
types: Types | None = None
__init__
__init__(
    task: Task,
    errors: bool = False,
    policies: tuple[Policy, ...] = (),
    flows: tuple[Flow, ...] = (),
    types: Types | None = None,
) -> None

Library dataclass

The tools of a library, by name, and its problems, in the order the file lists them.

tools instance-attribute
tools: Mapping[str, Contract]
problems instance-attribute
problems: tuple[Problem, ...]
policies class-attribute instance-attribute
policies: Mapping[str, Policy] = field(default_factory=dict)
flows class-attribute instance-attribute
flows: Mapping[str, Flow] = field(default_factory=dict)
__init__
__init__(
    tools: Mapping[str, Contract],
    problems: tuple[Problem, ...],
    policies: Mapping[str, Policy] = dict(),
    flows: Mapping[str, Flow] = dict(),
) -> None
problem
problem(name: str) -> Problem

Return the problem whose task is name; raise KeyError naming it otherwise.

read_library

read_library(
    directory: Path,
    tools: Mapping[str, Contract] | None = None,
) -> Library

Read a library directory; a rule a task names and the directory lacks is a KeyError.

tools, read from a live server, replaces the directory's tools.json. A task naming an input as a tool is a ValueError.

valgebra_planning.privilege

Privilege policies in Progent's format, read as valgebra sets (Shi et al. 2025, §4.1).

A policy maps each tool to its rules, [priority, effect, condition, fallback]: effect 0 allows and 1 forbids, and the condition maps an argument to the JSON Schema its value must meet or to a regular expression a string value must match from its start. A condition checks only the arguments a call passes. Rules are tried by priority, a forbidding rule before an allowing one of the same priority, and the first whose condition holds decides; a call no rule matches, and a call to a tool the policy names no rule for, is denied. Within one priority that is the order Progent applies a policy in (Shi et al. 2025, §4.2, Alg. 2), which reads no priority. A rule asking the user (fallback 2) is read as denied, the reading that admits no call the user did not approve.

The calls a policy allows to a tool are then a set: each allowing rule's condition, minus the conditions of every rule tried before it, joined. Progent asks Z3 whether an update narrows a policy, one argument and one rule a tool at a time; here the question is an inclusion between two such sets, every rule and every argument at once, which valgebra decides, refutes with a call that one policy allows and the other does not, or leaves undecided.

Change module-attribute

Change = Literal['narrowing', 'expansion', 'undecided']

Rule dataclass

One rule of a tool: its priority, whether it allows, and the condition as a schema.

priority instance-attribute
priority: int
allows instance-attribute
allows: bool
condition instance-attribute
condition: dict[str, Any]
__init__
__init__(
    priority: int, allows: bool, condition: dict[str, Any]
) -> None

Update dataclass

Whether a new policy narrows an old one for a tool, and a call showing an expansion.

tool instance-attribute
tool: str
change instance-attribute
change: Change
witness class-attribute instance-attribute
witness: tuple[Any, ...] = ()
__init__
__init__(
    tool: str, change: Change, witness: tuple[Any, ...] = ()
) -> None

read_rules

read_rules(
    rules: Iterable[Sequence[Any]],
) -> tuple[Rule, ...]

Read a tool's rules in the order they are tried: by priority, forbidding first.

allowed

allowed(rules: Sequence[Rule]) -> Validator[Any]

Return the argument records the rules allow: each allowing one's, minus those tried first.

read_privileges

read_privileges(
    policy: Mapping[str, Iterable[Sequence[Any]]],
) -> dict[str, tuple[Rule, ...]]

Read a policy in Progent's format: each tool's rules, in the order they are tried.

updates

updates(
    old: Mapping[str, Sequence[Rule]],
    new: Mapping[str, Sequence[Rule]],
) -> list[Update]

Return, for each tool the new policy names, whether it narrows the old policy's calls.

A narrowing is applied without asking, and an expansion needs approval, as Progent has it (Shi et al. 2025, §4.3).

as_policy

as_policy(
    name: str,
    privileges: Mapping[str, Sequence[Rule]],
    tools: Iterable[str],
) -> Policy

Return the privilege policy as an automaton the verifier, planner and runner read.

A call outside a tool's allowed set reaches the bad state denied; a tool the policy names no rule for is denied every call.

describe

describe(update: Update) -> str

Return an update as a line: the tool, the change, and the call showing an expansion.

valgebra_planning.vacuity

Specifications that hold for a trivial reason, decided over a library's sets.

A goal no value meets makes every task over it unsolvable, and one every value meets makes any program a solution; a policy transition whose guard no argument record of its tool meets never fires, and a policy whose bad and pending states no transition that can fire reaches is never violated; a flow rule whose endorsed set misses the sink's argument lets nothing through, and one that holds it refuses nothing. Each is a specification satisfied vacuously (Kupferman and Vardi 1999, Def. 2), a check that passes without testing what its author meant, and each is a set question valgebra decides: emptiness, inclusion, a meet.

The cheap question is asked first: values drawn from a schema are tried for membership, and a member found is a proof the set is inhabited, so valgebra is asked only where none is. A question valgebra leaves undecided is reported as undecided, never as vacuous.

Certainty module-attribute

Certainty = Literal['proven', 'undecided']

Finding dataclass

A specification holding vacuously, where it is written, and whether valgebra proves it.

where instance-attribute
where: str
finding instance-attribute
finding: str
certainty instance-attribute
certainty: Certainty
__init__
__init__(
    where: str, finding: str, certainty: Certainty
) -> None

vacuities

vacuities(library: Library) -> list[Finding]

Return every specification of library that holds vacuously, or may.

valgebra_planning.servers

Tools read from a live MCP server, and a program run against it.

read_server pages through a server's tools/list and reads each tool into its contract, as valgebra_planning.contracts.read_contract reads a listing on disk. run_on_server runs a program with valgebra_planning.run.run, each call a tools/call through the client: the result's structuredContent is the value a call returns, an isError result is a valgebra_planning.run.ToolError, and a tool returning no structured content returns the text of its content blocks. A call the server answers with a protocol error is a tool error too, and so is one asking for input (MCP 2026-07-28's input_required: a sampling, an elicitation, the roots, or an interaction it waits on): the client gives none, so no value a program did not hold reaches a call.

Requires the mcp extra. The runner is synchronous and the client asynchronous, so the run goes on a worker thread and each call is sent to the client's event loop.

connect

connect(server: str) -> Client

Return a client for a server: a URL is Streamable HTTP, anything else a stdio command.

The command is split as a POSIX shell splits it (shlex.split), on Windows as well: a backslash escapes the character after it, so a Windows path is passed quoted, as shlex.quote quotes it, the way pre-commit quotes the interpreter in a hook's entry.

read_server async

read_server(client: Client) -> dict[str, Contract]

Return the contract of every tool the server lists, by name, every page read.

run_on_server async

run_on_server(
    program: Block,
    contracts: Mapping[str, Contract],
    task: Task,
    inputs: Mapping[str, Any],
    client: Client,
    *,
    policies: Sequence[Policy] = (),
    enforce: bool = True,
) -> Run

Run program against the server client is connected to, failing closed.

valgebra_planning.proxy

An MCP server in front of another, holding every call to the contracts, policies and flows.

The proxy lists the upstream server's tools as they are, and answers each tools/call only after checking it, as the fail-closed runner checks a call: the argument record against the tool's input set, each policy's step, and, the call forwarded, the result against its output set. A check that breaks answers the call with a tool error naming it, as Progent's proxy mode answers a denied call with its fallback message (Shi et al. 2025, §4.1, §7), so the agent can try another way; nothing breaking it reaches the upstream server or the agent.

A flow rule is held by provenance read from values: the proxy sees values, not a program's references, so an argument equal, as one JSON value, to a value an untrusted tool returned is taken as coming from it, and refused unless it lies in the rule's endorsed set. A rule with only refuses an argument equal to no value its sources returned: an identifier not retrieved earlier in the proxy's process, the strict grounding gate (Sah et al. 2026, §4.8). Both are assumptions: a value equal by chance to an untrusted one is refused with it, and one equal by chance to a retrieved one passes, and a value the agent transforms, upper-cased, encoded or cut, equals none it was returned and passes: a flow rule here holds against no attacker that adapts, where the contract and policy checks hold against any. A proxy sees no task, so a value from a task input is from elsewhere. The proxy serves one client over stdio for as long as its process runs, and MCP 2026-07-28 has no session a client ends, so a policy's pending states are not read there. A call the upstream answers with a protocol error, or with a request for input, is answered with a tool error: the proxy gives no input and forwards no request for one, since a value it never checked would reach the call. Requires the mcp extra.

Gate dataclass

The checks a proxy holds each call to, and the values each untrusted tool returned.

contracts instance-attribute
contracts: Mapping[str, Contract]
monitors instance-attribute
monitors: list[Monitor]
flows instance-attribute
flows: Sequence[Flow]
seen class-attribute instance-attribute
seen: dict[object, set[str]] = field(default_factory=dict)
__init__
__init__(
    contracts: Mapping[str, Contract],
    monitors: list[Monitor],
    flows: Sequence[Flow],
    seen: dict[object, set[str]] = dict(),
) -> None
before
before(tool: str, arguments: dict[str, Any]) -> str | None

Return why a call may not be made, or None.

after
after(tool: str, value: Any) -> str | None

Return why a result may not be passed on, or None; remember untrusted tools' values.

proxy

proxy(
    upstream: Client,
    listing: Sequence[Tool],
    contracts: Mapping[str, Contract],
    *,
    policies: Sequence[Policy] = (),
    flows: Sequence[Flow] = (),
) -> Server[Any]

Return an MCP server answering listing through upstream, every call checked.

serve async

serve(
    upstream: Client,
    *,
    policies: Sequence[Policy] = (),
    flows: Sequence[Flow] = (),
) -> None

Serve the proxy over stdio in front of the server upstream is connected to.