Skip to content

Python kit

The aidy package lets a Python host join an aidy catalog: annotate operations with x-aidy, verify the Aidy-Assertion aidy sends with every call it makes as the user, and answer the identity and search contracts. It needs Python 3.12 or later.

Terminal window
pip install "aidy[fastapi]"

For a walkthrough, see the FastAPI guide. Everything below is importable from aidy except the FastAPI integration, which lives in aidy.fastapi.

def op(
name: str,
*,
title: str | None = None,
description: str | None = None,
effect: Effect | None = None,
approval: Approval | None = None,
role: Role | None = None,
surfaces: list[Surface] | None = None,
confirmation: Confirmation | None = None,
form: str | None = None,
resolve: dict[str, Reference] | None = None,
next: Next | None = None,
open: str | None = None,
redact: list[str] | None = None,
repeatable: bool | None = None,
timeout_seconds: float | None = None,
cli: Cli | None = None,
) -> dict[str, Any]

Answers {"x-aidy": {...}} for FastAPI’s openapi_extra. The keyword arguments are the keys of x-aidy in snake case: timeout_seconds becomes timeoutSeconds. Nested objects keep the wire’s camelCase. Arguments left as None are omitted, so the catalog defaults apply. The result is validated against the bundled x-aidy schema; any problem raises ValueError listing every one.

@app.post(
"/api/vm/{vm_id}/stop",
openapi_extra=op(
"stop_vm",
title="Stop server",
open="/console/instance/{vm_id}",
confirmation={
"title": "Stop server {resource_name}?",
"lookup": {"path": "/api/vm/{vm_id}", "labelPath": "name"},
},
),
)
Literal type Values
Effect "read", "create", "update", "delete", "external"
Approval "never", "always"
Role "identity", "search", "form"
Surface "agent", "mcp", "cli"
Risk "low", "medium", "high"

These literal types live in aidy.openapi.

TypedDicts for the nested objects of op():

Type Keys
Confirmation title (required), target, fields: list[ConfirmationField], lookup: Lookup, risk: Risk, costHint
ConfirmationField key, label, values: dict[str, str] (optional)
Lookup path, labelPath
Next op (required), arguments: dict[str, str], argumentsFrom: str, when: dict[str, Any]
Reference op, key (optional)
Cli command (required), args: list[str]

See Confirmation, Chains and Resolve.

from aidy.fastapi import AidyHost
AidyHost(
app: FastAPI,
*,
keys: Mapping[str, Ed25519PublicKey],
audience: str,
identity: IdentityResolver,
public_url: str | None = None,
replay_cache: ReplayCache | None = None,
)

Installs the assertion check on app as an ASGI middleware. A request without Aidy-Assertion passes untouched.

Parameter Meaning
keys Pinned aidy public keys by kid, from load_public_keys.
audience The host’s origin (https://console.example.com); the assertion’s aud.
identity (request) -> (subject, tenant | None) | None, sync or async, resolved from the request’s own credential exactly as the UI authenticates it. None means the request names nobody. An HTTPException it raises is answered as is.
public_url The base the client addressed, joined with the raw path and query to rebuild the URL the assertion binds. Defaults to audience. Set it when a proxy strips a path prefix (https://console.example.com/gw).
replay_cache Where seen jti values are kept. Default MemoryReplayCache(), which is per process.

With an assertion, the middleware buffers the body and checks, in order:

  1. the EdDSA signature against a pinned key (kid), and the claims’ shape;
  2. lifetime ≤ 60 s, exp/iat within 60 s of skew, aud == audience;
  3. htm, htu (the full URL as sent, query included) and bsh (SHA-256 of the exact body);
  4. that jti is new;
  5. sub/ten against identity(request), op against the x-aidy.name of the route the router dispatches to (from app.openapi()), and apr when the operation needs approval (its approval, else never for reads and always otherwise).

A failure answers:

{ "detail": "aidy_assertion_invalid", "code": "approval_missing" }

with status 401 and the failure code. On success the claims are on request.state.aidy.

from aidy.fastapi import AidyCall
async def stop_vm(vm_id: str, aidy: AidyCall) -> dict[str, str]:
if aidy is not None:
audit(actor="aidy", run=aidy.rid, approval=aidy.apr)

AidyCall is Annotated[AssertionClaims | None, Depends(...)]: the verified claims of a delegated call, or None for a direct user call.

A frozen pydantic model of the assertion’s claims (Delegation):

Field Type
iss, aud, htu str (URLs)
sub, sid, rid, cid str
ten, apr str | None
op str
htm "GET", "HEAD", "POST", "PUT", "PATCH" or "DELETE"
bsh, jti str
iat, exp int

claims.audit() answers the claims as a plain dict without absent ones, for an audit record. Hosts should record actor = aidy, rid and apr.

ReplayCache is a protocol with redis-py’s set signature:

def set(self, key: str, value: str, *, nx: bool, ex: int) -> object: ...

With nx=True it stores the key for ex seconds only when it is new, and answers a truthy value then. It may be sync or async, so redis.Redis and redis.asyncio.Redis both fit. Keys are aidy:jti:<jti> and live until the assertion can no longer be accepted.

MemoryReplayCache() is a per-process implementation. With several workers, pass a shared store:

from redis.asyncio import Redis
AidyHost(app, ..., replay_cache=Redis.from_url("redis://cache:6379/0"))
def verify_assertion(
token: str,
*,
keys: Mapping[str, Ed25519PublicKey],
audience: str,
method: str,
url: str,
body: bytes | str,
remember: Callable[[str, int], bool],
now: int | None = None,
) -> AssertionClaims

Verifies the signature, lifetime, audience, request binding and replay (checks 1 to 3 of host verification). url is the full URL as the client sent it, query string included; body the exact body bytes (empty for none). remember(jti, until) records jti until the epoch second until and answers False when it was already seen. Raises AidyAssertionError.

verify_signed(...) takes the same arguments without remember and skips the replay check, for callers whose replay store is asynchronous.

def check_call(
claims: AssertionClaims,
*,
subject: str,
tenant: str | None,
op: str,
approval: Literal["never", "always"],
) -> None

Checks 4 to 6: the assertion names the user the host resolved and the operation it serves, and carries apr when approval is "always". Raises AidyAssertionError.

from aidy import check_call, verify_assertion
claims = verify_assertion(
token,
keys=keys,
audience="https://console.example.com",
method="POST",
url=full_url_as_sent,
body=raw_body,
remember=lambda jti, until: cache.add(jti, until), # False when seen before
)
check_call(claims, subject=user.id, tenant=user.tenant_id, op="stop_vm", approval="always")
def load_public_keys(jwks: Iterable[Mapping[str, str]]) -> dict[str, Ed25519PublicKey]

Public keys by kid from Ed25519 JWKs ({"kty": "OKP", "crv": "Ed25519", "x": …, "kid": …}), as aidy keys generate prints them. Raises ValueError for a JWK without kid, of another key type, or of the wrong length.

def canonical_json(value: object) -> str
def args_hash(args: Mapping[str, object]) -> str

canonical_json is the JSON Canonicalization Scheme (RFC 8785): sorted keys, ECMAScript number and string forms. args_hash is the base64url SHA-256 of the canonical JSON of the frozen arguments, the hash an approval binds to. Both produce the same output as @aidy-dev/spec.

An Exception with code: AssertionErrorCode, the name of the failed check.

Code Check
malformed Not a compact JWS, wrong header, or invalid claims.
unknown_key No pinned key for kid.
bad_signature The signature does not verify.
expired exp passed, beyond 60 s of skew.
not_yet_valid iat is more than 60 s in the future.
too_long exp - iat exceeds 60 s.
audience aud is not the host’s origin.
method htm does not match.
url htu does not match.
body bsh does not match.
replay jti was seen before.
subject sub is not the resolved user, or the request names nobody.
tenant ten is not the resolved tenant.
operation op is not the operation serving this request, or no catalog operation serves it.
approval_missing The operation needs approval and apr is absent.
class Identity(BaseModel):
subject: str
tenant: str | None = None
name: str | None = None
locale: str | None = None
scopes: list[str] | None = None

The answer of the role: identity operation. Absent fields are omitted when serialized. ADMIN_SCOPE is "aidy:admin". See Identity.

@app.get("/api/me", openapi_extra=op("whoami", role="identity"))
async def whoami(request: Request) -> Identity:
user = current_user(request)
return Identity(subject=user.id, tenant=user.tenant_id, locale="zh-CN")
class SearchHit(BaseModel):
type: str # ^[a-z][a-z0-9_.-]{0,31}$
id: str
title: str
excerpt: str | None = None # at most 300 characters
url: str # a path starting with one "/", or http(s)://
updated_at: AwareDatetime | None = None
content: str | None = None # at most 4000 characters, for the model only
class SearchResponse(BaseModel):
hits: list[SearchHit] # at most 50

SearchHit serializes in the wire’s camelCase (updatedAt) and accepts either spelling. Unknown fields are rejected. content is the passage text the model reads: aidy’s search tool gives it to the model and strips it from its /aidy/v0/search response and from citations, so people see title, excerpt and url.

Form, SearchHit, SearchResponse and Identity serialize in camelCase and leave absent fields out (the aidy runtime rejects null) in model_dump, model_dump_json and FastAPI responses alike, without response_model_exclude_none. FastAPI’s OpenAPI document shows their real camelCase schemas. DEFAULT_SEARCH_LIMIT is 10 and MAX_SEARCH_LIMIT is 50. See Search.

@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))
async def search_vms(q: str, limit: int = 10) -> SearchResponse:
return SearchResponse(
hits=[
SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}")
for vm in find_vms(q, limit)
]
)
Name Value
ASSERTION_HEADER "aidy-assertion"
ADMIN_SCOPE "aidy:admin"
DEFAULT_SEARCH_LIMIT 10
MAX_SEARCH_LIMIT 50
aidy.fastapi.INVALID "aidy_assertion_invalid"