Skip to content

crp.agent

Auto-generated reference for the crp.agent subpackage.

agent

crp.agent

CRP multi-agent safety (CRP-SPEC-012).

Session-scoped Safety Budget + circuit breaker, cross-agent header propagation and delegation limits, cross-agent provenance linking, and the human-oversight token flow.

PRIVATE REFERENCE IMPLEMENTATION - SPEC-012 internals are NOT published. This package is part of the closed-source crp reference engine only.

Public API

AgentSafetyBudget / BudgetDecision / classify_budget - budget + circuit breaker DelegationLimits / check_delegation - chain-bounding guards build_downstream_headers / filter_upstream_headers - header propagation link_sub_agent_hmac / fan_in_hmac / SubAgentResult - cross-agent provenance issue_oversight_token / verify_oversight_token - oversight token flow

AgentSafetyBudget dataclass

Session-scoped safety budget (CRP-SPEC-012 §2).

The authoritative budget value lives in the signed session token; this object is the gateway-side accountant. Decrements are computed server-side only (anti-inflation, §10.1) and the budget never recovers within a session (§2.4).

Attributes:

Name Type Description
budget float

Current remaining safety budget, initialised to INITIAL_BUDGET.

decrements dict[RiskLevel, float]

Mapping from RiskLevel to the amount subtracted when a response at that risk level is delivered. Values are clamped to the interoperability ranges in DECREMENT_RANGES.

health property

Return the current BudgetHealth band.

circuit_state property

Return the current CircuitState.

peek()

Return the current decision without applying any decrement.

Returns:

Type Description
BudgetDecision

A BudgetDecision reflecting the present budget state.

account(risk_level, *, is_redispatch=False)

Decrement the budget for a delivered response's risk level (§2.2).

Re-dispatches do not decrement (§2.5) - only the final delivered response counts.

Parameters:

Name Type Description Default
risk_level RiskLevel | None

DPE risk level of the delivered response, or None if the response carries no risk classification.

required
is_redispatch bool

When True, the event is a re-dispatch and must not decrement the budget.

False

Returns:

Type Description
BudgetDecision

The resulting BudgetDecision after accounting for the event.

merge_downstream(sub_agent_budget)

Fan-in merge: orchestrator budget = min of self and sub-agent (§5.3).

Parameters:

Name Type Description Default
sub_agent_budget float

Remaining safety budget reported by a sub-agent.

required

Returns:

Type Description
BudgetDecision

The resulting BudgetDecision after merging budgets.

BudgetDecision dataclass

Outcome of accounting a risk event against the budget.

Attributes:

Name Type Description
budget float

Remaining safety budget after the event.

health BudgetHealth

Human-readable health band for the remaining budget.

circuit_state CircuitState

Current circuit-breaker state.

http_status int | None

HTTP status to return when the session is halted, or None.

force_oversight bool

Whether the gateway should force human review.

warning str | None

Short warning label for CRP-Safety-Budget-Warning header.

retry_after str | None

Retry guidance for halted sessions, or None.

halted property

Return True if the session has been halted (HTTP 451).

headers property

CRP headers describing the current budget state.

Returns:

Type Description
dict[str, str]

Mapping of CRP header names to header values, including the

dict[str, str]

remaining budget and any warning/oversight/retry directives.

BudgetHealth

Bases: str, Enum

Budget health band (CRP-SPEC-012 §2.3).

Attributes:

Name Type Description
HEALTHY

Budget above 0.50.

CAUTION

Budget between 0.25 and 0.50 inclusive.

LOW

Budget between 0.10 and 0.24.

DEPLETED

Budget at or below 0.10 but still positive.

EXHAUSTED

Budget at or below 0.00.

CircuitState

Bases: str, Enum

Circuit-breaker state (CRP-SPEC-012 §5.1).

Attributes:

Name Type Description
CLOSED

Normal operation; budget is above the half-open threshold.

HALF_OPEN

Cautious operation; human review may be required.

OPEN

Session halted; the gateway responds with HTTP 451.

FanInQualityResult dataclass

Aggregate coherence/completeness over fan-in sub-agent responses (§8.3).

When an orchestrator merges several sub-agent results it must check that the combined answer is internally consistent (no cross-agent contradictions) and that, together, the sub-agents covered the parent query. This reuses RQA Stage 6 (cross-window coherence) and Stage 8 (completeness).

Attributes:

Name Type Description
coherence object | None

Result of cross-agent coherence checking, or None if not run.

completeness object | None

Completeness result versus the parent query, or None.

contradiction_count int

Total number of contradictions detected across all pairwise comparisons.

is_coherent property

Return True when no contradictions were detected.

has_critical property

Return True if the coherence result reports a critical contradiction.

headers property

Collect CRP headers from nested coherence/completeness results.

Returns:

Type Description
dict[str, str]

Merged header dictionary produced by nested result objects, if any.

SubAgentResult dataclass

A SUB_AGENT_RESULT audit event linking a sub-agent's chain (§8.1).

Attributes:

Name Type Description
sub_agent_session_id str

Session identifier of the sub-agent that produced the result.

sub_agent_chain_tip str

Independently-verified HMAC chain tip of the sub-agent session.

timestamp str

ISO-8601 UTC timestamp when the linkage event was created.

event_type str

Audit event type, always SUB_AGENT_RESULT.

to_dict()

Serialize the event to a JSON-friendly dictionary.

Returns:

Type Description
dict[str, str]

Dictionary with event type, sub-agent session id, chain tip, and

dict[str, str]

timestamp.

OversightApproval dataclass

A human reviewer's approval of an oversighted response (§6.2).

Attributes:

Name Type Description
session_id str

Session that produced the halted response.

window_id str

Window identifier of the halted response.

reviewer_id str

Identifier of the human reviewer granting approval.

approval_timestamp str

ISO-8601 UTC timestamp of the approval.

signing_payload()

Build the HMAC signing payload bound to this approval.

The payload binds the token to session_id + window_id so a token issued for one window cannot release another.

Returns:

Type Description
bytes

UTF-8 encoded string of the joined approval fields.

DelegationCheck dataclass

Result of validating a delegation attempt against the limits.

http_status property

Return the HTTP status.

headers property

Return the headers.

DelegationLimits dataclass

Per-agent delegation controls (CRP-SPEC-012 §7.2).

classify_budget(budget)

Map a budget value to its health band and circuit state (§2.3, §5.1).

Parameters:

Name Type Description Default
budget float

Remaining safety budget, typically in the range [0.0, 1.0].

required

Returns:

Type Description
BudgetHealth

A tuple of (BudgetHealth, CircuitState) matching the budget

CircuitState

threshold rules defined in CRP-SPEC-012.

aggregate_sub_agent_quality(parent_query, sub_agent_responses, *, embedder=None, nli=None)

Run cross-agent coherence + completeness over fan-in responses (§8.3).

Detects contradictions between sub-agent responses (each response is checked against the ones merged before it) and verifies that the union of responses answers parent_query. Imported lazily so :mod:crp.agent stays independent of the provenance package at import time.

Parameters:

Name Type Description Default
parent_query str

Original query the sub-agents were asked to address.

required
sub_agent_responses list[str]

Individual response strings from each sub-agent.

required
embedder object | None

Optional embedding function for completeness verification.

None
nli object | None

Optional natural-language inference helper for contradiction detection.

None

Returns:

Type Description
FanInQualityResult

A FanInQualityResult summarising coherence, completeness, and

FanInQualityResult

contradiction counts.

fan_in_hmac(parent_hmacs, key)

Merge multiple parent window HMACs into one fan-in HMAC (sorted, §3 / SPEC-004).

Sorting makes the merge order-independent so the same set of parents always produces the same fan-in tip.

Parameters:

Name Type Description Default
parent_hmacs list[str]

List of parent window HMACs to merge.

required
key bytes

HMAC signing key.

required

Returns:

Type Description
str

Hexadecimal HMAC-SHA256 digest of the sorted parent tips.

Compute the orchestrator window HMAC incorporating a sub-agent tip (§8.1).

HMAC-SHA256(session_id ‖ window ‖ response_hash ‖ prev_hmac ‖ sub_tip, key) creates a cryptographic link between the two chains without merging them.

Parameters:

Name Type Description Default
orchestrator_session_id str

Identifier of the orchestrator session.

required
window_number int

Window index being sealed.

required
response_hash str

Hash of the response content for this window.

required
prev_window_hmac str

HMAC of the previous orchestrator window.

required
sub_agent_chain_tip str

HMAC chain tip from the sub-agent session.

required
key bytes

HMAC signing key.

required

Returns:

Type Description
str

Hexadecimal HMAC-SHA256 digest linking the orchestrator window to the

str

sub-agent chain.

Confirm a sub-agent's independently-verified tip matches the record (§8.2).

Parameters:

Name Type Description Default
event SubAgentResult

Audit event containing the recorded sub-agent chain tip.

required
verified_chain_tip str

Tip obtained by independently verifying the sub-agent's chain.

required

Returns:

Type Description
bool

True when the recorded tip equals the verified tip in constant time.

issue_oversight_token(approval, secret)

Issue a CRP-Oversight-Token value for an approved response.

Parameters:

Name Type Description Default
approval OversightApproval

Approval record identifying the session, window, reviewer, and timestamp.

required
secret bytes

HMAC secret shared by the oversight issuer and verifier.

required

Returns:

Type Description
str

The full token string, including the approved:sha256: prefix.

now_iso()

Current UTC timestamp in ISO-8601 (helper for building approvals).

Returns:

Type Description
str

ISO-8601 formatted UTC timestamp string.

verify_oversight_token(token, approval, secret)

Constant-time validation that token approves approval (§6.2).

The token's scope is bound to session_id + window_id via the signing payload, so a token issued for one window cannot release another.

Parameters:

Name Type Description Default
token str

Token presented by the client in CRP-Oversight-Token.

required
approval OversightApproval

Expected approval record against which to validate.

required
secret bytes

HMAC secret used to issue the token.

required

Returns:

Type Description
bool

True if the token is well-formed and its signature matches the expected

bool

value in constant time.

build_downstream_headers(parent_headers, *, parent_session_id, loop_depth)

Construct the header set an orchestrator forwards to a sub-agent (§3.1).

Copies the propagating headers from the parent context, sets CRP-Agent-Session-Parent to the orchestrator session, and increments CRP-Agent-Loop-Depth.

check_delegation(limits, *, loop_depth, delegations_made, dag_nodes, strategy=None)

Validate a delegation against loop-depth / fan-out / DAG / strategy limits.

filter_upstream_headers(sub_agent_headers)

Select the headers a sub-agent surfaces back to the orchestrator (§3.2).

agent.budget

crp.agent.budget

Safety Budget + circuit breaker (CRP-SPEC-012 §2, §5; CRP-SPEC-015).

The Safety Budget is a session-scoped, header-observable risk-accumulation signal. Every session starts at 1.0; each delivered response decrements it by an amount keyed to the DPE risk level. When the budget crosses thresholds, the gateway escalates oversight and ultimately halts the session - the AI equivalent of a distributed-systems circuit breaker.

Relevant specifications
  • CRP-SPEC-012: Multi-Agent Safety
  • CRP-SPEC-015: Security & Privacy

PRIVATE REFERENCE IMPLEMENTATION - SPEC-012 internals are not published. This module lives in the closed-source crp package only.

CircuitState

Bases: str, Enum

Circuit-breaker state (CRP-SPEC-012 §5.1).

Attributes:

Name Type Description
CLOSED

Normal operation; budget is above the half-open threshold.

HALF_OPEN

Cautious operation; human review may be required.

OPEN

Session halted; the gateway responds with HTTP 451.

BudgetHealth

Bases: str, Enum

Budget health band (CRP-SPEC-012 §2.3).

Attributes:

Name Type Description
HEALTHY

Budget above 0.50.

CAUTION

Budget between 0.25 and 0.50 inclusive.

LOW

Budget between 0.10 and 0.24.

DEPLETED

Budget at or below 0.10 but still positive.

EXHAUSTED

Budget at or below 0.00.

BudgetDecision dataclass

Outcome of accounting a risk event against the budget.

Attributes:

Name Type Description
budget float

Remaining safety budget after the event.

health BudgetHealth

Human-readable health band for the remaining budget.

circuit_state CircuitState

Current circuit-breaker state.

http_status int | None

HTTP status to return when the session is halted, or None.

force_oversight bool

Whether the gateway should force human review.

warning str | None

Short warning label for CRP-Safety-Budget-Warning header.

retry_after str | None

Retry guidance for halted sessions, or None.

halted property

Return True if the session has been halted (HTTP 451).

headers property

CRP headers describing the current budget state.

Returns:

Type Description
dict[str, str]

Mapping of CRP header names to header values, including the

dict[str, str]

remaining budget and any warning/oversight/retry directives.

AgentSafetyBudget dataclass

Session-scoped safety budget (CRP-SPEC-012 §2).

The authoritative budget value lives in the signed session token; this object is the gateway-side accountant. Decrements are computed server-side only (anti-inflation, §10.1) and the budget never recovers within a session (§2.4).

Attributes:

Name Type Description
budget float

Current remaining safety budget, initialised to INITIAL_BUDGET.

decrements dict[RiskLevel, float]

Mapping from RiskLevel to the amount subtracted when a response at that risk level is delivered. Values are clamped to the interoperability ranges in DECREMENT_RANGES.

health property

Return the current BudgetHealth band.

circuit_state property

Return the current CircuitState.

peek()

Return the current decision without applying any decrement.

Returns:

Type Description
BudgetDecision

A BudgetDecision reflecting the present budget state.

account(risk_level, *, is_redispatch=False)

Decrement the budget for a delivered response's risk level (§2.2).

Re-dispatches do not decrement (§2.5) - only the final delivered response counts.

Parameters:

Name Type Description Default
risk_level RiskLevel | None

DPE risk level of the delivered response, or None if the response carries no risk classification.

required
is_redispatch bool

When True, the event is a re-dispatch and must not decrement the budget.

False

Returns:

Type Description
BudgetDecision

The resulting BudgetDecision after accounting for the event.

merge_downstream(sub_agent_budget)

Fan-in merge: orchestrator budget = min of self and sub-agent (§5.3).

Parameters:

Name Type Description Default
sub_agent_budget float

Remaining safety budget reported by a sub-agent.

required

Returns:

Type Description
BudgetDecision

The resulting BudgetDecision after merging budgets.

classify_budget(budget)

Map a budget value to its health band and circuit state (§2.3, §5.1).

Parameters:

Name Type Description Default
budget float

Remaining safety budget, typically in the range [0.0, 1.0].

required

Returns:

Type Description
BudgetHealth

A tuple of (BudgetHealth, CircuitState) matching the budget

CircuitState

threshold rules defined in CRP-SPEC-012.

agent.chain

crp.agent.chain

Cross-agent provenance linking (CRP-SPEC-012 §8; CRP-SPEC-011).

Links two sessions' HMAC provenance chains without merging them: when a sub-agent result is consumed, its chain tip is folded into the orchestrator's next window HMAC, and a SUB_AGENT_RESULT event records the linkage for auditor traversal.

Relevant specifications
  • CRP-SPEC-011: Audit Trail
  • CRP-SPEC-012: Multi-Agent Safety

PRIVATE REFERENCE IMPLEMENTATION - SPEC-012 internals are not published.

SubAgentResult dataclass

A SUB_AGENT_RESULT audit event linking a sub-agent's chain (§8.1).

Attributes:

Name Type Description
sub_agent_session_id str

Session identifier of the sub-agent that produced the result.

sub_agent_chain_tip str

Independently-verified HMAC chain tip of the sub-agent session.

timestamp str

ISO-8601 UTC timestamp when the linkage event was created.

event_type str

Audit event type, always SUB_AGENT_RESULT.

to_dict()

Serialize the event to a JSON-friendly dictionary.

Returns:

Type Description
dict[str, str]

Dictionary with event type, sub-agent session id, chain tip, and

dict[str, str]

timestamp.

FanInQualityResult dataclass

Aggregate coherence/completeness over fan-in sub-agent responses (§8.3).

When an orchestrator merges several sub-agent results it must check that the combined answer is internally consistent (no cross-agent contradictions) and that, together, the sub-agents covered the parent query. This reuses RQA Stage 6 (cross-window coherence) and Stage 8 (completeness).

Attributes:

Name Type Description
coherence object | None

Result of cross-agent coherence checking, or None if not run.

completeness object | None

Completeness result versus the parent query, or None.

contradiction_count int

Total number of contradictions detected across all pairwise comparisons.

is_coherent property

Return True when no contradictions were detected.

has_critical property

Return True if the coherence result reports a critical contradiction.

headers property

Collect CRP headers from nested coherence/completeness results.

Returns:

Type Description
dict[str, str]

Merged header dictionary produced by nested result objects, if any.

Compute the orchestrator window HMAC incorporating a sub-agent tip (§8.1).

HMAC-SHA256(session_id ‖ window ‖ response_hash ‖ prev_hmac ‖ sub_tip, key) creates a cryptographic link between the two chains without merging them.

Parameters:

Name Type Description Default
orchestrator_session_id str

Identifier of the orchestrator session.

required
window_number int

Window index being sealed.

required
response_hash str

Hash of the response content for this window.

required
prev_window_hmac str

HMAC of the previous orchestrator window.

required
sub_agent_chain_tip str

HMAC chain tip from the sub-agent session.

required
key bytes

HMAC signing key.

required

Returns:

Type Description
str

Hexadecimal HMAC-SHA256 digest linking the orchestrator window to the

str

sub-agent chain.

Confirm a sub-agent's independently-verified tip matches the record (§8.2).

Parameters:

Name Type Description Default
event SubAgentResult

Audit event containing the recorded sub-agent chain tip.

required
verified_chain_tip str

Tip obtained by independently verifying the sub-agent's chain.

required

Returns:

Type Description
bool

True when the recorded tip equals the verified tip in constant time.

fan_in_hmac(parent_hmacs, key)

Merge multiple parent window HMACs into one fan-in HMAC (sorted, §3 / SPEC-004).

Sorting makes the merge order-independent so the same set of parents always produces the same fan-in tip.

Parameters:

Name Type Description Default
parent_hmacs list[str]

List of parent window HMACs to merge.

required
key bytes

HMAC signing key.

required

Returns:

Type Description
str

Hexadecimal HMAC-SHA256 digest of the sorted parent tips.

aggregate_sub_agent_quality(parent_query, sub_agent_responses, *, embedder=None, nli=None)

Run cross-agent coherence + completeness over fan-in responses (§8.3).

Detects contradictions between sub-agent responses (each response is checked against the ones merged before it) and verifies that the union of responses answers parent_query. Imported lazily so :mod:crp.agent stays independent of the provenance package at import time.

Parameters:

Name Type Description Default
parent_query str

Original query the sub-agents were asked to address.

required
sub_agent_responses list[str]

Individual response strings from each sub-agent.

required
embedder object | None

Optional embedding function for completeness verification.

None
nli object | None

Optional natural-language inference helper for contradiction detection.

None

Returns:

Type Description
FanInQualityResult

A FanInQualityResult summarising coherence, completeness, and

FanInQualityResult

contradiction counts.

agent.oversight

crp.agent.oversight

Human-oversight token flow (CRP-SPEC-012 §6.2; CRP-SPEC-011).

When a response is halted (HTTP 451) and a human reviewer approves it, an oversight token is issued. The client retries with CRP-Oversight-Token: approved:sha256:<sig>; the gateway validates it and releases the halted response. The safety budget is NOT replenished - the human has merely accepted the logged risk.

Relevant specifications
  • CRP-SPEC-011: Audit Trail
  • CRP-SPEC-012: Multi-Agent Safety

PRIVATE REFERENCE IMPLEMENTATION - SPEC-012 internals are not published.

OversightApproval dataclass

A human reviewer's approval of an oversighted response (§6.2).

Attributes:

Name Type Description
session_id str

Session that produced the halted response.

window_id str

Window identifier of the halted response.

reviewer_id str

Identifier of the human reviewer granting approval.

approval_timestamp str

ISO-8601 UTC timestamp of the approval.

signing_payload()

Build the HMAC signing payload bound to this approval.

The payload binds the token to session_id + window_id so a token issued for one window cannot release another.

Returns:

Type Description
bytes

UTF-8 encoded string of the joined approval fields.

issue_oversight_token(approval, secret)

Issue a CRP-Oversight-Token value for an approved response.

Parameters:

Name Type Description Default
approval OversightApproval

Approval record identifying the session, window, reviewer, and timestamp.

required
secret bytes

HMAC secret shared by the oversight issuer and verifier.

required

Returns:

Type Description
str

The full token string, including the approved:sha256: prefix.

verify_oversight_token(token, approval, secret)

Constant-time validation that token approves approval (§6.2).

The token's scope is bound to session_id + window_id via the signing payload, so a token issued for one window cannot release another.

Parameters:

Name Type Description Default
token str

Token presented by the client in CRP-Oversight-Token.

required
approval OversightApproval

Expected approval record against which to validate.

required
secret bytes

HMAC secret used to issue the token.

required

Returns:

Type Description
bool

True if the token is well-formed and its signature matches the expected

bool

value in constant time.

now_iso()

Current UTC timestamp in ISO-8601 (helper for building approvals).

Returns:

Type Description
str

ISO-8601 formatted UTC timestamp string.

agent.propagation

crp.agent.propagation

Multi-agent header propagation + delegation limits (CRP-SPEC-012 §3, §10.3).

Defines which CRP headers flow downstream (orchestrator → sub-agent) and upstream (sub-agent → orchestrator), the fan-in budget merge, and the loop-depth / delegation / DAG-node guards that prevent unbounded chains.

PRIVATE REFERENCE IMPLEMENTATION - SPEC-012 internals are not published.

DelegationLimits dataclass

Per-agent delegation controls (CRP-SPEC-012 §7.2).

DelegationCheck dataclass

Result of validating a delegation attempt against the limits.

http_status property

Return the HTTP status.

headers property

Return the headers.

build_downstream_headers(parent_headers, *, parent_session_id, loop_depth)

Construct the header set an orchestrator forwards to a sub-agent (§3.1).

Copies the propagating headers from the parent context, sets CRP-Agent-Session-Parent to the orchestrator session, and increments CRP-Agent-Loop-Depth.

filter_upstream_headers(sub_agent_headers)

Select the headers a sub-agent surfaces back to the orchestrator (§3.2).

check_delegation(limits, *, loop_depth, delegations_made, dag_nodes, strategy=None)

Validate a delegation against loop-depth / fan-out / DAG / strategy limits.