vogtcon 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vogtcon/__init__.py +47 -0
- vogtcon/contracts.py +84 -0
- vogtcon/core.py +77 -0
- vogtcon/execution.py +353 -0
- vogtcon/models.py +248 -0
- vogtcon/records.py +95 -0
- vogtcon/rules.py +216 -0
- vogtcon/telemetry.py +77 -0
- vogtcon-0.1.0.dist-info/METADATA +156 -0
- vogtcon-0.1.0.dist-info/RECORD +14 -0
- vogtcon-0.1.0.dist-info/WHEEL +5 -0
- vogtcon-0.1.0.dist-info/licenses/LICENSE +202 -0
- vogtcon-0.1.0.dist-info/licenses/NOTICE +4 -0
- vogtcon-0.1.0.dist-info/top_level.txt +1 -0
vogtcon/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Typed contracts and deterministic governance, independent of execution."""
|
|
5
|
+
|
|
6
|
+
from .contracts import load_contract
|
|
7
|
+
from .core import DeterministicEvaluator, Governor, GovernorEvaluator
|
|
8
|
+
from .execution import GovernedToolExecutor, ToolExecutionOutcome, WorkflowController
|
|
9
|
+
from .models import (
|
|
10
|
+
ActionProposal,
|
|
11
|
+
AgentContract,
|
|
12
|
+
ContractDocument,
|
|
13
|
+
ContractRulesV2,
|
|
14
|
+
EnforcementPolicy,
|
|
15
|
+
ExecutionContext,
|
|
16
|
+
GovernanceDecision,
|
|
17
|
+
GovernorInput,
|
|
18
|
+
Violation,
|
|
19
|
+
)
|
|
20
|
+
from .rules import DEFAULT_RULE_CATALOG, RuleCatalog
|
|
21
|
+
from .records import JsonlDecisionLog, RunEvent, RunRecorder
|
|
22
|
+
from .telemetry import TelemetryObserver
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"load_contract",
|
|
26
|
+
"DeterministicEvaluator",
|
|
27
|
+
"Governor",
|
|
28
|
+
"GovernorEvaluator",
|
|
29
|
+
"GovernedToolExecutor",
|
|
30
|
+
"ToolExecutionOutcome",
|
|
31
|
+
"WorkflowController",
|
|
32
|
+
"RuleCatalog",
|
|
33
|
+
"DEFAULT_RULE_CATALOG",
|
|
34
|
+
"JsonlDecisionLog",
|
|
35
|
+
"RunEvent",
|
|
36
|
+
"RunRecorder",
|
|
37
|
+
"TelemetryObserver",
|
|
38
|
+
"ActionProposal",
|
|
39
|
+
"AgentContract",
|
|
40
|
+
"ContractDocument",
|
|
41
|
+
"ContractRulesV2",
|
|
42
|
+
"EnforcementPolicy",
|
|
43
|
+
"ExecutionContext",
|
|
44
|
+
"GovernanceDecision",
|
|
45
|
+
"GovernorInput",
|
|
46
|
+
"Violation",
|
|
47
|
+
]
|
vogtcon/contracts.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Load contract data without changing its historical identity."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from .models import AgentContract, ContractDocument, ContractRulesV2
|
|
15
|
+
from .rules import DEFAULT_RULE_CATALOG, POSTCONDITIONS, RUNTIME_RULES, RuleCatalog
|
|
16
|
+
|
|
17
|
+
_PHASES = {"pre_execution", "runtime", "post_execution"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def validate_contract_rules(
|
|
21
|
+
contract: AgentContract | ContractRulesV2,
|
|
22
|
+
rule_catalog: RuleCatalog | None = None,
|
|
23
|
+
) -> None:
|
|
24
|
+
"""Resolve the supported vocabulary, including for direct evaluator calls.
|
|
25
|
+
|
|
26
|
+
Enforced contracts must enable all checkpoints. This is a configuration
|
|
27
|
+
requirement of this loader, not a change to the underlying data schema.
|
|
28
|
+
"""
|
|
29
|
+
catalog = rule_catalog if rule_catalog is not None else DEFAULT_RULE_CATALOG
|
|
30
|
+
for name, supported in (
|
|
31
|
+
("runtime_rules", catalog.runtime_rules),
|
|
32
|
+
("postconditions", catalog.postconditions),
|
|
33
|
+
):
|
|
34
|
+
unknown = set(getattr(contract, name)) - set(supported)
|
|
35
|
+
if unknown:
|
|
36
|
+
raise ValueError(f"Unsupported {name}: {', '.join(sorted(unknown))}")
|
|
37
|
+
if (isinstance(contract, ContractRulesV2) or contract.mode != "no_contract") and (
|
|
38
|
+
contract.validation_phases == "not_enforced"
|
|
39
|
+
or set(contract.validation_phases) != _PHASES
|
|
40
|
+
):
|
|
41
|
+
raise ValueError("Enforced contracts require all three validation phases")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _validate_v2_fingerprint(document: ContractDocument) -> None:
|
|
45
|
+
"""Check parsed v2 values using the historical JSON digest convention."""
|
|
46
|
+
contract = document.contract
|
|
47
|
+
if not isinstance(contract, ContractRulesV2):
|
|
48
|
+
return
|
|
49
|
+
payload = document.original
|
|
50
|
+
payload.pop("contract_fingerprint")
|
|
51
|
+
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
|
|
52
|
+
expected = f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}"
|
|
53
|
+
if contract.contract_fingerprint != expected:
|
|
54
|
+
raise ValueError("Contract fingerprint mismatch")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_contract(
|
|
58
|
+
path: str | Path,
|
|
59
|
+
rule_catalog: RuleCatalog | None = None,
|
|
60
|
+
) -> ContractDocument:
|
|
61
|
+
"""Read a JSON or safe YAML contract and return its original and typed views.
|
|
62
|
+
|
|
63
|
+
JSON is attempted first to retain JSON scalar semantics. YAML values must
|
|
64
|
+
satisfy the same JSON-compatible Pydantic schema. V2 fingerprints are
|
|
65
|
+
verified over parsed values; legacy fingerprints remain unchanged. File and
|
|
66
|
+
parsing errors propagate; an invalid contract never becomes an allow decision.
|
|
67
|
+
Pass the same ``rule_catalog`` to :class:`Governor` for custom rule IDs.
|
|
68
|
+
|
|
69
|
+
Example::
|
|
70
|
+
|
|
71
|
+
document = load_contract("agent_contract.yaml", rule_catalog=catalog)
|
|
72
|
+
contract = document.contract
|
|
73
|
+
"""
|
|
74
|
+
text = Path(path).read_text(encoding="utf-8")
|
|
75
|
+
try:
|
|
76
|
+
data = json.loads(text)
|
|
77
|
+
except json.JSONDecodeError:
|
|
78
|
+
data = yaml.safe_load(text)
|
|
79
|
+
if not isinstance(data, dict):
|
|
80
|
+
raise ValueError("Contract document must contain an object")
|
|
81
|
+
document = ContractDocument(data)
|
|
82
|
+
validate_contract_rules(document.contract, rule_catalog=rule_catalog)
|
|
83
|
+
_validate_v2_fingerprint(document)
|
|
84
|
+
return document
|
vogtcon/core.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Pure deterministic checks; execution and run-level effects belong to callers."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
from .contracts import validate_contract_rules
|
|
11
|
+
from .models import GovernanceDecision, GovernorInput, Violation
|
|
12
|
+
from .rules import DEFAULT_RULE_CATALOG, RuleCatalog
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GovernorEvaluator(Protocol):
|
|
16
|
+
def evaluate(self, request: GovernorInput) -> GovernanceDecision: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _pre_violations(request: GovernorInput) -> list[Violation]:
|
|
20
|
+
approved = [
|
|
21
|
+
item if isinstance(item, str) else item.fingerprint
|
|
22
|
+
for item in request.contract.approved_agent_configurations
|
|
23
|
+
]
|
|
24
|
+
checks = (
|
|
25
|
+
("agent.configuration_fingerprint_match", request.context.observed_agent_fingerprint not in approved),
|
|
26
|
+
("contract.fingerprint_match", request.context.observed_contract_fingerprint != request.contract.contract_fingerprint),
|
|
27
|
+
)
|
|
28
|
+
return [Violation(rule=rule, phase=request.phase) for rule, failed in checks if failed]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DeterministicEvaluator:
|
|
32
|
+
"""Evaluate configured rules without executing tools or mutating evidence."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, rule_catalog: RuleCatalog | None = None) -> None:
|
|
35
|
+
self._rule_catalog = rule_catalog if rule_catalog is not None else DEFAULT_RULE_CATALOG
|
|
36
|
+
|
|
37
|
+
def evaluate(self, request: GovernorInput) -> GovernanceDecision:
|
|
38
|
+
validate_contract_rules(request.contract, rule_catalog=self._rule_catalog)
|
|
39
|
+
mode = request.effective_mode
|
|
40
|
+
violations = []
|
|
41
|
+
if mode != "no_contract":
|
|
42
|
+
checks = {
|
|
43
|
+
"pre_execution": _pre_violations,
|
|
44
|
+
"runtime": self._rule_catalog.evaluate_runtime,
|
|
45
|
+
"post_execution": self._rule_catalog.evaluate_post,
|
|
46
|
+
}
|
|
47
|
+
violations = checks[request.phase](request)
|
|
48
|
+
decision = None
|
|
49
|
+
if request.phase == "runtime":
|
|
50
|
+
decision = "allow" if not violations else {
|
|
51
|
+
"advisory": "allow_with_warning", "guarded": "block", "strict": "abort",
|
|
52
|
+
}[mode]
|
|
53
|
+
return GovernanceDecision(phase=request.phase, violations=violations, decision=decision)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Governor:
|
|
57
|
+
"""Evaluate one checkpoint with the deterministic default or an injected evaluator.
|
|
58
|
+
|
|
59
|
+
``Governor(rule_catalog=catalog)`` enables custom rules from a contract.
|
|
60
|
+
The Governor returns a decision; :class:`WorkflowController` owns the
|
|
61
|
+
run state and invokes tools only after the runtime check.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
evaluator: GovernorEvaluator | None = None,
|
|
67
|
+
rule_catalog: RuleCatalog | None = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
if evaluator is not None and rule_catalog is not None:
|
|
70
|
+
raise ValueError("Cannot specify both evaluator and rule_catalog")
|
|
71
|
+
if evaluator is not None:
|
|
72
|
+
self._evaluator = evaluator
|
|
73
|
+
else:
|
|
74
|
+
self._evaluator = DeterministicEvaluator(rule_catalog=rule_catalog)
|
|
75
|
+
|
|
76
|
+
def evaluate(self, request: GovernorInput) -> GovernanceDecision:
|
|
77
|
+
return self._evaluator.evaluate(request)
|
vogtcon/execution.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
# Copyright (c) 2026 Jorge Carlos Urteaga Reyesvera
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Synchronous checkpoints and tool gating for one governed run.
|
|
5
|
+
|
|
6
|
+
The caller supplies trusted context and the tool implementation. This module
|
|
7
|
+
does not infer authorization from telemetry or undo effects after execution.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from contextlib import nullcontext
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Generic, Self, TypeVar
|
|
17
|
+
|
|
18
|
+
from .contracts import load_contract
|
|
19
|
+
from .core import Governor
|
|
20
|
+
from .models import (
|
|
21
|
+
ActionProposal,
|
|
22
|
+
AgentContract,
|
|
23
|
+
ContractRulesV2,
|
|
24
|
+
EnforcementPolicy,
|
|
25
|
+
ExecutionContext,
|
|
26
|
+
GovernanceDecision,
|
|
27
|
+
GovernorInput,
|
|
28
|
+
JsonObject,
|
|
29
|
+
)
|
|
30
|
+
from .records import RunEvent, RunRecorder
|
|
31
|
+
from .rules import RuleCatalog
|
|
32
|
+
from .telemetry import TelemetryObserver
|
|
33
|
+
|
|
34
|
+
T = TypeVar("T")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class ToolExecutionOutcome(Generic[T]):
|
|
39
|
+
decision: GovernanceDecision
|
|
40
|
+
executed: bool
|
|
41
|
+
result: T | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class GovernedToolExecutor:
|
|
45
|
+
"""Evaluate one runtime proposal immediately before invoking its tool.
|
|
46
|
+
|
|
47
|
+
Use ``execute(request, tool)`` for a host that already owns run state.
|
|
48
|
+
For a complete pre/runtime/post run, prefer :class:`WorkflowController`.
|
|
49
|
+
A blocked or aborted decision returns ``executed=False`` without calling
|
|
50
|
+
``tool``; tool exceptions propagate because their effects may be uncertain.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, governor: Governor, telemetry: TelemetryObserver | None = None) -> None:
|
|
54
|
+
self._governor = governor
|
|
55
|
+
self._telemetry = telemetry
|
|
56
|
+
|
|
57
|
+
def execute(
|
|
58
|
+
self,
|
|
59
|
+
request: GovernorInput,
|
|
60
|
+
tool: Callable[[ActionProposal], T],
|
|
61
|
+
*,
|
|
62
|
+
before_invoke: Callable[[GovernanceDecision], None] | None = None,
|
|
63
|
+
after_invoke: Callable[[], None] | None = None,
|
|
64
|
+
on_tool_error: Callable[[], None] | None = None,
|
|
65
|
+
action_index: int | None = None,
|
|
66
|
+
) -> ToolExecutionOutcome[T]:
|
|
67
|
+
if request.phase != "runtime" or request.action is None:
|
|
68
|
+
raise ValueError("Tool execution requires a runtime action")
|
|
69
|
+
# Keep the proposed action stable even if a custom evaluator mutates
|
|
70
|
+
# nested Pydantic values or the caller changes its original request.
|
|
71
|
+
snapshot = request.model_copy(deep=True)
|
|
72
|
+
evaluation_request = snapshot.model_copy(deep=True)
|
|
73
|
+
span_identity = {"action_index": action_index} if action_index is not None else {}
|
|
74
|
+
check_span = self._telemetry.span(
|
|
75
|
+
"governor.check", phase="runtime", mode=snapshot.effective_mode,
|
|
76
|
+
run_id=snapshot.run_id, contract_id=snapshot.contract.contract_id,
|
|
77
|
+
tool_name=snapshot.action.tool_name, **span_identity,
|
|
78
|
+
) if self._telemetry is not None else nullcontext(None)
|
|
79
|
+
with check_span as span:
|
|
80
|
+
decision = self._governor.evaluate(evaluation_request)
|
|
81
|
+
if evaluation_request != snapshot:
|
|
82
|
+
raise ValueError("Governor evaluator mutated the action or its context")
|
|
83
|
+
if not isinstance(decision, GovernanceDecision) or decision.phase != "runtime":
|
|
84
|
+
raise ValueError("Governor returned an invalid runtime decision")
|
|
85
|
+
if (
|
|
86
|
+
snapshot.effective_mode in ("guarded", "strict")
|
|
87
|
+
and decision.violations
|
|
88
|
+
and decision.decision in ("allow", "allow_with_warning")
|
|
89
|
+
):
|
|
90
|
+
raise ValueError("Governor allowed a violating action in an enforcement mode")
|
|
91
|
+
if self._telemetry is not None:
|
|
92
|
+
self._telemetry.record_decision(span, decision)
|
|
93
|
+
if before_invoke is not None:
|
|
94
|
+
before_invoke(decision)
|
|
95
|
+
if decision.decision not in ("allow", "allow_with_warning"):
|
|
96
|
+
return ToolExecutionOutcome(decision=decision, executed=False)
|
|
97
|
+
# A tool exception propagates: its external effects may be ambiguous.
|
|
98
|
+
assert snapshot.action is not None
|
|
99
|
+
tool_span = self._telemetry.span(
|
|
100
|
+
"governor.tool.execute", phase="runtime", run_id=snapshot.run_id,
|
|
101
|
+
contract_id=snapshot.contract.contract_id, tool_name=snapshot.action.tool_name,
|
|
102
|
+
**span_identity,
|
|
103
|
+
) if self._telemetry is not None else nullcontext(None)
|
|
104
|
+
with tool_span:
|
|
105
|
+
try:
|
|
106
|
+
result = tool(snapshot.action)
|
|
107
|
+
except Exception:
|
|
108
|
+
if on_tool_error is not None:
|
|
109
|
+
try:
|
|
110
|
+
on_tool_error()
|
|
111
|
+
except Exception:
|
|
112
|
+
# Preserve the tool failure when recording is also down.
|
|
113
|
+
pass
|
|
114
|
+
raise
|
|
115
|
+
if after_invoke is not None:
|
|
116
|
+
after_invoke()
|
|
117
|
+
return ToolExecutionOutcome(decision=decision, executed=True, result=result)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class WorkflowController:
|
|
121
|
+
"""Bind pre, runtime, and post checkpoints to one contract and run ID.
|
|
122
|
+
|
|
123
|
+
Guarded blocks leave the run active so a caller may propose another action.
|
|
124
|
+
Strict pre/runtime failures stop it. Post checks report violations after any
|
|
125
|
+
tool effects; they cannot roll those effects back.
|
|
126
|
+
|
|
127
|
+
Create one controller per run, call ``begin(context)``, route each proposed
|
|
128
|
+
tool call through ``execute(action, context, tool)``, then call
|
|
129
|
+
``finish(context, response)`` while the state is active. The host supplies
|
|
130
|
+
trusted ``ExecutionContext`` facts and the real tool callable. Pass
|
|
131
|
+
``policy=EnforcementPolicy(mode=...)`` when the contract uses v2 rules.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(
|
|
135
|
+
self,
|
|
136
|
+
governor: Governor,
|
|
137
|
+
run_id: str,
|
|
138
|
+
contract: AgentContract | ContractRulesV2,
|
|
139
|
+
recorder: RunRecorder | None = None,
|
|
140
|
+
telemetry: TelemetryObserver | None = None,
|
|
141
|
+
*,
|
|
142
|
+
policy: EnforcementPolicy | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
if not run_id:
|
|
145
|
+
raise ValueError("run_id must be nonempty")
|
|
146
|
+
if isinstance(contract, AgentContract) and "schema_version" in (contract.model_extra or {}):
|
|
147
|
+
raise ValueError("Unsupported contract schema_version")
|
|
148
|
+
if isinstance(contract, ContractRulesV2):
|
|
149
|
+
if policy is None:
|
|
150
|
+
raise ValueError("v2 contracts require an enforcement policy")
|
|
151
|
+
elif policy is not None and policy.mode != contract.mode:
|
|
152
|
+
raise ValueError("Enforcement policy conflicts with legacy contract mode")
|
|
153
|
+
self._governor = governor
|
|
154
|
+
self._executor = GovernedToolExecutor(governor, telemetry)
|
|
155
|
+
self._run_id = run_id
|
|
156
|
+
self._contract = contract.model_copy(deep=True)
|
|
157
|
+
self._policy = policy
|
|
158
|
+
self._mode = policy.mode if policy is not None else contract.mode
|
|
159
|
+
self._state = "new"
|
|
160
|
+
self._recorder = recorder
|
|
161
|
+
self._telemetry = telemetry
|
|
162
|
+
self._sequence = 0
|
|
163
|
+
self._action_index = 0
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def from_contract_path(
|
|
167
|
+
cls,
|
|
168
|
+
path: str | Path,
|
|
169
|
+
run_id: str,
|
|
170
|
+
*,
|
|
171
|
+
policy: EnforcementPolicy | None = None,
|
|
172
|
+
rule_catalog: RuleCatalog | None = None,
|
|
173
|
+
recorder: RunRecorder | None = None,
|
|
174
|
+
telemetry: TelemetryObserver | None = None,
|
|
175
|
+
) -> Self:
|
|
176
|
+
"""Load a contract and start one deterministic run.
|
|
177
|
+
|
|
178
|
+
The same rule catalog validates the document and evaluates its rules.
|
|
179
|
+
V2 still requires an explicit policy. Use the constructor directly to
|
|
180
|
+
supply a custom Governor evaluator.
|
|
181
|
+
"""
|
|
182
|
+
contract = load_contract(path, rule_catalog=rule_catalog).contract
|
|
183
|
+
return cls(
|
|
184
|
+
Governor(rule_catalog=rule_catalog), run_id, contract,
|
|
185
|
+
recorder, telemetry, policy=policy,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def _record(
|
|
189
|
+
self,
|
|
190
|
+
*,
|
|
191
|
+
phase: str,
|
|
192
|
+
event_type: str,
|
|
193
|
+
decision: GovernanceDecision | None = None,
|
|
194
|
+
action_index: int | None = None,
|
|
195
|
+
tool_name: str | None = None,
|
|
196
|
+
execution_status: str = "not_started",
|
|
197
|
+
) -> None:
|
|
198
|
+
if self._recorder is None:
|
|
199
|
+
return
|
|
200
|
+
self._sequence += 1
|
|
201
|
+
trace_id, span_id = (
|
|
202
|
+
self._telemetry.current_ids() if self._telemetry is not None else (None, None)
|
|
203
|
+
)
|
|
204
|
+
self._recorder.record(
|
|
205
|
+
RunEvent.model_validate({
|
|
206
|
+
"run_id": self._run_id,
|
|
207
|
+
"sequence": self._sequence,
|
|
208
|
+
"contract_id": self._contract.contract_id,
|
|
209
|
+
"mode": self._mode,
|
|
210
|
+
"phase": phase,
|
|
211
|
+
"event_type": event_type,
|
|
212
|
+
"action_index": action_index,
|
|
213
|
+
"tool_name": tool_name,
|
|
214
|
+
"decision": decision.decision if decision is not None else None,
|
|
215
|
+
"violation_rules": [v.rule for v in decision.violations] if decision is not None else [],
|
|
216
|
+
"execution_status": execution_status,
|
|
217
|
+
"trace_id": trace_id,
|
|
218
|
+
"span_id": span_id,
|
|
219
|
+
})
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def state(self) -> str:
|
|
224
|
+
return self._state
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def run_id(self) -> str:
|
|
228
|
+
return self._run_id
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def contract(self) -> AgentContract | ContractRulesV2:
|
|
232
|
+
return self._contract.model_copy(deep=True)
|
|
233
|
+
|
|
234
|
+
def _request(
|
|
235
|
+
self,
|
|
236
|
+
phase: str,
|
|
237
|
+
context: ExecutionContext,
|
|
238
|
+
*,
|
|
239
|
+
action: ActionProposal | None = None,
|
|
240
|
+
response: JsonObject | None = None,
|
|
241
|
+
run_ledger: JsonObject | None = None,
|
|
242
|
+
) -> GovernorInput:
|
|
243
|
+
return GovernorInput.model_validate(
|
|
244
|
+
{
|
|
245
|
+
"run_id": self._run_id,
|
|
246
|
+
"contract": self._contract.model_dump(),
|
|
247
|
+
"phase": phase,
|
|
248
|
+
"context": context.model_dump(),
|
|
249
|
+
"action": action.model_dump() if action is not None else None,
|
|
250
|
+
"response": response,
|
|
251
|
+
"run_ledger": run_ledger,
|
|
252
|
+
"policy": self._policy.model_dump() if self._policy is not None else None,
|
|
253
|
+
}
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def begin(self, context: ExecutionContext) -> GovernanceDecision:
|
|
257
|
+
if self._state != "new":
|
|
258
|
+
raise RuntimeError("Pre-execution check already completed")
|
|
259
|
+
check_span = self._telemetry.span(
|
|
260
|
+
"governor.check", phase="pre_execution", mode=self._mode,
|
|
261
|
+
run_id=self._run_id, contract_id=self._contract.contract_id,
|
|
262
|
+
) if self._telemetry is not None else nullcontext(None)
|
|
263
|
+
try:
|
|
264
|
+
with check_span as span:
|
|
265
|
+
decision = self._governor.evaluate(self._request("pre_execution", context))
|
|
266
|
+
if not isinstance(decision, GovernanceDecision) or decision.phase != "pre_execution":
|
|
267
|
+
raise ValueError("Governor returned an invalid pre-execution decision")
|
|
268
|
+
if self._telemetry is not None:
|
|
269
|
+
self._telemetry.record_decision(span, decision)
|
|
270
|
+
self._record(phase="pre_execution", event_type="decision", decision=decision)
|
|
271
|
+
except Exception:
|
|
272
|
+
self._state = "aborted"
|
|
273
|
+
raise
|
|
274
|
+
self._state = "aborted" if self._mode == "strict" and decision.violations else "active"
|
|
275
|
+
return decision
|
|
276
|
+
|
|
277
|
+
def execute(
|
|
278
|
+
self,
|
|
279
|
+
action: ActionProposal,
|
|
280
|
+
context: ExecutionContext,
|
|
281
|
+
tool: Callable[[ActionProposal], T],
|
|
282
|
+
) -> ToolExecutionOutcome[T]:
|
|
283
|
+
if self._state != "active":
|
|
284
|
+
raise RuntimeError("Run is not active")
|
|
285
|
+
self._action_index += 1
|
|
286
|
+
action_index = self._action_index
|
|
287
|
+
|
|
288
|
+
def record_before_tool(decision: GovernanceDecision) -> None:
|
|
289
|
+
self._record(
|
|
290
|
+
phase="runtime", event_type="decision", decision=decision,
|
|
291
|
+
action_index=action_index, tool_name=action.tool_name,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
def record_tool_completed() -> None:
|
|
295
|
+
self._record(
|
|
296
|
+
phase="runtime", event_type="tool_completed",
|
|
297
|
+
action_index=action_index, tool_name=action.tool_name,
|
|
298
|
+
execution_status="completed",
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
def record_tool_error() -> None:
|
|
302
|
+
self._record(
|
|
303
|
+
phase="runtime", event_type="tool_error",
|
|
304
|
+
action_index=action_index, tool_name=action.tool_name,
|
|
305
|
+
execution_status="unknown",
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
try:
|
|
309
|
+
outcome = self._executor.execute(
|
|
310
|
+
self._request("runtime", context, action=action), tool,
|
|
311
|
+
before_invoke=record_before_tool,
|
|
312
|
+
after_invoke=record_tool_completed,
|
|
313
|
+
on_tool_error=record_tool_error,
|
|
314
|
+
action_index=action_index,
|
|
315
|
+
)
|
|
316
|
+
except Exception:
|
|
317
|
+
self._state = "aborted"
|
|
318
|
+
raise
|
|
319
|
+
if outcome.decision.decision == "abort" or (
|
|
320
|
+
self._mode == "strict" and outcome.decision.violations
|
|
321
|
+
):
|
|
322
|
+
self._state = "aborted"
|
|
323
|
+
return outcome
|
|
324
|
+
|
|
325
|
+
def finish(
|
|
326
|
+
self,
|
|
327
|
+
context: ExecutionContext,
|
|
328
|
+
response: JsonObject,
|
|
329
|
+
run_ledger: JsonObject | None = None,
|
|
330
|
+
) -> GovernanceDecision:
|
|
331
|
+
if self._state != "active":
|
|
332
|
+
raise RuntimeError("Run is not active")
|
|
333
|
+
check_span = self._telemetry.span(
|
|
334
|
+
"governor.check", phase="post_execution", mode=self._mode,
|
|
335
|
+
run_id=self._run_id, contract_id=self._contract.contract_id,
|
|
336
|
+
) if self._telemetry is not None else nullcontext(None)
|
|
337
|
+
try:
|
|
338
|
+
with check_span as span:
|
|
339
|
+
decision = self._governor.evaluate(
|
|
340
|
+
self._request(
|
|
341
|
+
"post_execution", context, response=response, run_ledger=run_ledger
|
|
342
|
+
)
|
|
343
|
+
)
|
|
344
|
+
if not isinstance(decision, GovernanceDecision) or decision.phase != "post_execution":
|
|
345
|
+
raise ValueError("Governor returned an invalid post-execution decision")
|
|
346
|
+
if self._telemetry is not None:
|
|
347
|
+
self._telemetry.record_decision(span, decision)
|
|
348
|
+
self._record(phase="post_execution", event_type="decision", decision=decision)
|
|
349
|
+
except Exception:
|
|
350
|
+
self._state = "aborted"
|
|
351
|
+
raise
|
|
352
|
+
self._state = "failed_post" if self._mode == "strict" and decision.violations else "finished"
|
|
353
|
+
return decision
|