receiptd 1.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.
Files changed (48) hide show
  1. birkin/__init__.py +73 -0
  2. birkin/__main__.py +7 -0
  3. birkin/cli.py +9 -0
  4. birkin/hooks/__init__.py +4 -0
  5. birkin/hooks/claude_code_gate.py +9 -0
  6. birkin/hooks/claude_code_stop_gate.py +9 -0
  7. receiptd/__init__.py +76 -0
  8. receiptd/__main__.py +6 -0
  9. receiptd/adapter.py +164 -0
  10. receiptd/adapters/__init__.py +7 -0
  11. receiptd/adapters/grok_bot.py +74 -0
  12. receiptd/adapters/hermes.py +137 -0
  13. receiptd/adapters/infini_gateway.py +104 -0
  14. receiptd/adapters/null_agent.py +81 -0
  15. receiptd/audit.py +94 -0
  16. receiptd/card/__init__.py +5 -0
  17. receiptd/card/classifier.py +368 -0
  18. receiptd/card/demo/green.jsonl +8 -0
  19. receiptd/card/demo/red.jsonl +10 -0
  20. receiptd/card/demo/yellow.jsonl +7 -0
  21. receiptd/card/models.py +97 -0
  22. receiptd/card/parser.py +316 -0
  23. receiptd/card/pipeline.py +37 -0
  24. receiptd/card/redact.py +38 -0
  25. receiptd/card/render_card.py +274 -0
  26. receiptd/card/render_terminal.py +100 -0
  27. receiptd/card/rules.yaml +94 -0
  28. receiptd/card/signing.py +274 -0
  29. receiptd/card/verdict.py +77 -0
  30. receiptd/cli.py +1011 -0
  31. receiptd/crypto.py +413 -0
  32. receiptd/engine.py +515 -0
  33. receiptd/examples/invoice_review.py +259 -0
  34. receiptd/hooks/__init__.py +2 -0
  35. receiptd/hooks/claude_code_gate.py +513 -0
  36. receiptd/hooks/claude_code_stop_gate.py +419 -0
  37. receiptd/hooks/default_pretooluse.policy.json +26 -0
  38. receiptd/ledger.py +400 -0
  39. receiptd/models.py +437 -0
  40. receiptd/policy.py +300 -0
  41. receiptd/trifecta.py +8 -0
  42. receiptd/verify.py +377 -0
  43. receiptd-1.1.0.dist-info/METADATA +308 -0
  44. receiptd-1.1.0.dist-info/RECORD +48 -0
  45. receiptd-1.1.0.dist-info/WHEEL +5 -0
  46. receiptd-1.1.0.dist-info/entry_points.txt +3 -0
  47. receiptd-1.1.0.dist-info/licenses/LICENSE +21 -0
  48. receiptd-1.1.0.dist-info/top_level.txt +2 -0
birkin/__init__.py ADDED
@@ -0,0 +1,73 @@
1
+ """
2
+ birkin compatibility shim
3
+ =========================
4
+
5
+ Backward-compatibility shim re-exporting `receiptd` and mapping its
6
+ submodules (e.g. `birkin.crypto`, `birkin.verify`, `birkin.adapters`) via `sys.modules`.
7
+ """
8
+
9
+ import importlib
10
+ import sys
11
+
12
+ import receiptd
13
+ from receiptd import * # noqa: F401, F403
14
+
15
+ __all__ = getattr(receiptd, "__all__", [k for k in dir(receiptd) if not k.startswith("_")])
16
+ __version__ = getattr(receiptd, "__version__", "1.0.0")
17
+
18
+ _this_module = sys.modules[__name__]
19
+
20
+ # Submodule aliases mapped into sys.modules so legacy imports work.
21
+ _SUBMODULES = [
22
+ "adapter",
23
+ "adapters",
24
+ "adapters.grok_bot",
25
+ "adapters.hermes",
26
+ "adapters.infini_gateway",
27
+ "adapters.null_agent",
28
+ "audit",
29
+ "card",
30
+ "card.classifier",
31
+ "card.models",
32
+ "card.parser",
33
+ "card.pipeline",
34
+ "card.redact",
35
+ "card.render_card",
36
+ "card.render_terminal",
37
+ "card.signing",
38
+ "card.verdict",
39
+ "crypto",
40
+ "engine",
41
+ "ledger",
42
+ "models",
43
+ "policy",
44
+ "trifecta",
45
+ "verify",
46
+ ]
47
+
48
+ for _sub in _SUBMODULES:
49
+ _target = importlib.import_module(f"receiptd.{_sub}")
50
+ sys.modules[f"birkin.{_sub}"] = _target
51
+ _parts = _sub.split(".")
52
+ _curr = _this_module
53
+ for _part in _parts[:-1]:
54
+ _curr = getattr(_curr, _part, None)
55
+ if _curr is None:
56
+ break
57
+ if _curr is not None:
58
+ setattr(_curr, _parts[-1], _target)
59
+
60
+
61
+ def __getattr__(name: str):
62
+ """Fallback attribute lookup delegating to receiptd."""
63
+ if hasattr(receiptd, name):
64
+ val = getattr(receiptd, name)
65
+ setattr(_this_module, name, val)
66
+ return val
67
+ try:
68
+ mod = importlib.import_module(f"receiptd.{name}")
69
+ sys.modules[f"birkin.{name}"] = mod
70
+ setattr(_this_module, name, mod)
71
+ return mod
72
+ except ModuleNotFoundError:
73
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
birkin/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Thin shim for receiptd.__main__."""
2
+
3
+ from receiptd.cli import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
7
+
birkin/cli.py ADDED
@@ -0,0 +1,9 @@
1
+ """Thin shim for receiptd.cli."""
2
+
3
+ import sys
4
+ from receiptd.cli import * # noqa: F401, F403
5
+ from receiptd.cli import app, cli, main
6
+
7
+ if __name__ == "__main__":
8
+ main()
9
+
@@ -0,0 +1,4 @@
1
+ """Thin shim for receiptd.hooks."""
2
+
3
+ from receiptd.hooks import * # noqa: F401, F403
4
+
@@ -0,0 +1,9 @@
1
+ """Thin shim for receiptd.hooks.claude_code_gate."""
2
+
3
+ import sys
4
+ from receiptd.hooks.claude_code_gate import * # noqa: F401, F403
5
+ from receiptd.hooks.claude_code_gate import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
9
+
@@ -0,0 +1,9 @@
1
+ """Thin shim for receiptd.hooks.claude_code_stop_gate."""
2
+
3
+ import sys
4
+ from receiptd.hooks.claude_code_stop_gate import * # noqa: F401, F403
5
+ from receiptd.hooks.claude_code_stop_gate import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
9
+
receiptd/__init__.py ADDED
@@ -0,0 +1,76 @@
1
+ """
2
+ birkin
3
+ ======
4
+
5
+ Birkin — the open Agent Authorization & Evidence Layer.
6
+
7
+ Runtime-agnostic control plane for autonomous agents:
8
+ signed authorization receipts, a verifiable audit ledger with Merkle
9
+ checkpoints, and offline verification of exported run packages.
10
+ """
11
+
12
+ from .crypto import SigningKey, verify_signature, canonical_json, sha256_hex, merkle_root
13
+ from .models import (
14
+ AgentIdentity,
15
+ AuthorizationReceipt,
16
+ AuditEvent,
17
+ MerkleCheckpoint,
18
+ PolicyDecision,
19
+ RunPackage,
20
+ PACKAGE_MANIFEST,
21
+ VerificationReport,
22
+ CheckResult,
23
+ make_passport,
24
+ )
25
+ from .policy import PolicySpec, load_default_policy, DEFAULT_POLICY_PATH
26
+ from .adapter import AgentAdapter, BaseAdapter, Intent, ActionRequest, ActionResult
27
+ from .adapters.hermes import HermesAdapter
28
+ from .adapters.null_agent import NullAgentAdapter
29
+ from .adapters.grok_bot import GrokBotAdapter
30
+ from .audit import AuditLedger, GENESIS_HASH
31
+ from .engine import Engine
32
+ from .verify import (
33
+ verify_package,
34
+ verify_file,
35
+ load_run_package,
36
+ render_report,
37
+ )
38
+
39
+ __version__ = "1.1.0"
40
+
41
+ __all__ = [
42
+ "SigningKey",
43
+ "verify_signature",
44
+ "canonical_json",
45
+ "sha256_hex",
46
+ "merkle_root",
47
+ "AgentIdentity",
48
+ "AuthorizationReceipt",
49
+ "AuditEvent",
50
+ "MerkleCheckpoint",
51
+ "PolicyDecision",
52
+ "RunPackage",
53
+ "PACKAGE_MANIFEST",
54
+ "VerificationReport",
55
+ "CheckResult",
56
+ "make_passport",
57
+ "PolicySpec",
58
+ "load_default_policy",
59
+ "DEFAULT_POLICY_PATH",
60
+ "AgentAdapter",
61
+ "BaseAdapter",
62
+ "Intent",
63
+ "ActionRequest",
64
+ "ActionResult",
65
+ "HermesAdapter",
66
+ "NullAgentAdapter",
67
+ "GrokBotAdapter",
68
+ "AuditLedger",
69
+ "GENESIS_HASH",
70
+ "Engine",
71
+ "verify_package",
72
+ "verify_file",
73
+ "load_run_package",
74
+ "render_report",
75
+ "__version__",
76
+ ]
receiptd/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from receiptd.cli import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
receiptd/adapter.py ADDED
@@ -0,0 +1,164 @@
1
+ """
2
+ birkin.adapter
3
+ ==============
4
+
5
+ The ``AgentAdapter`` interface.
6
+
7
+ Birkin is runtime-agnostic. An adapter is the seam through which a
8
+ particular agent runtime (Hermes, an MCP server, a custom bot, …) is
9
+ brought under Birkin governance. The adapter is responsible for:
10
+
11
+ * constructing an :class:`AgentIdentity` (passport) for the run;
12
+ * declaring the agent's intent before any side-effect;
13
+ * producing an :class:`ActionRequest` that the Birkin engine can hand to
14
+ the policy engine;
15
+ * executing the action *only* after a signed receipt with
16
+ ``decision == "allow"`` has been issued.
17
+
18
+ Hermes is shipped as the first adapter. Adding a new runtime is a matter of
19
+ implementing this protocol; the rest of Birkin does not change.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass, field
25
+ from typing import Any, Protocol, runtime_checkable
26
+
27
+ from .crypto import SigningKey
28
+ from .models import AgentIdentity, make_passport
29
+
30
+
31
+ @dataclass
32
+ class Intent:
33
+ text: str
34
+ declared_at: str
35
+ extras: dict[str, Any] = field(default_factory=dict)
36
+
37
+
38
+ @dataclass
39
+ class ActionRequest:
40
+ """A request from an agent to attempt a side-effecting action."""
41
+
42
+ tool: str
43
+ args: dict[str, Any] = field(default_factory=dict)
44
+ justification: str = ""
45
+
46
+
47
+ @dataclass
48
+ class ActionResult:
49
+ ok: bool
50
+ output: Any = None
51
+ error: str = ""
52
+ side_effect_recorded: bool = False
53
+
54
+
55
+ @runtime_checkable
56
+ class AgentAdapter(Protocol):
57
+ """Stable interface that every runtime adapter must implement."""
58
+
59
+ name: str
60
+ version: str
61
+
62
+ # --- lifecycle ------------------------------------------------------
63
+ def make_identity(
64
+ self,
65
+ *,
66
+ agent_id: str,
67
+ policy_ref: str,
68
+ session_id: str | None = None,
69
+ ttl_seconds: int = 3600,
70
+ ) -> AgentIdentity:
71
+ """Mint a fresh signed passport for this run."""
72
+ ...
73
+
74
+ def declare_intent(
75
+ self, identity: AgentIdentity, text: str, extras: dict | None = None
76
+ ) -> Intent:
77
+ """Record the agent's declared intent *before* any action."""
78
+ ...
79
+
80
+ def build_action_request(
81
+ self,
82
+ *,
83
+ tool: str,
84
+ args: dict[str, Any] | None = None,
85
+ justification: str = "",
86
+ ) -> ActionRequest:
87
+ """Construct an :class:`ActionRequest` to be evaluated by Birkin."""
88
+ ...
89
+
90
+ def execute(
91
+ self,
92
+ identity: AgentIdentity,
93
+ request: ActionRequest,
94
+ receipt, # AuthorizationReceipt — avoiding import for runtime_checkable
95
+ ) -> ActionResult:
96
+ """Execute the action iff the receipt permits it."""
97
+ ...
98
+
99
+
100
+ # --------------------------------------------------------------------------- #
101
+ # A tiny base class providing identity minting shared by all adapters.
102
+ # --------------------------------------------------------------------------- #
103
+ class BaseAdapter:
104
+ """Common scaffolding for concrete adapters."""
105
+
106
+ name: str = "base"
107
+ version: str = "0.0.0"
108
+
109
+ def __init__(self, agent_signing_key: SigningKey | None = None) -> None:
110
+ self._agent_sk = agent_signing_key or SigningKey.generate()
111
+
112
+ @property
113
+ def agent_public_b64(self) -> str:
114
+ return self._agent_sk.public_b64
115
+
116
+ def make_identity(
117
+ self,
118
+ *,
119
+ agent_id: str,
120
+ policy_ref: str,
121
+ session_id: str | None = None,
122
+ ttl_seconds: int = 3600,
123
+ ) -> AgentIdentity:
124
+ return make_passport(
125
+ agent_id=agent_id,
126
+ runtime=f"{self.name}-{self.version}",
127
+ policy=policy_ref,
128
+ session_id=session_id,
129
+ ttl_seconds=ttl_seconds,
130
+ agent_signing_key=self._agent_sk,
131
+ )
132
+
133
+ def declare_intent(
134
+ self, identity: AgentIdentity, text: str, extras: dict | None = None
135
+ ) -> Intent:
136
+ from datetime import datetime, timezone
137
+
138
+ return Intent(
139
+ text=text,
140
+ declared_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
141
+ extras=extras or {},
142
+ )
143
+
144
+ def build_action_request(
145
+ self,
146
+ *,
147
+ tool: str,
148
+ args: dict[str, Any] | None = None,
149
+ justification: str = "",
150
+ ) -> ActionRequest:
151
+ return ActionRequest(tool=tool, args=args or {}, justification=justification)
152
+
153
+ # Concrete adapters override this.
154
+ def execute(self, identity, request, receipt) -> ActionResult: # pragma: no cover
155
+ raise NotImplementedError
156
+
157
+
158
+ __all__ = [
159
+ "AgentAdapter",
160
+ "BaseAdapter",
161
+ "Intent",
162
+ "ActionRequest",
163
+ "ActionResult",
164
+ ]
@@ -0,0 +1,7 @@
1
+ """Birkin adapter registry."""
2
+
3
+ from .hermes import HermesAdapter
4
+ from .null_agent import NullAgentAdapter
5
+ from .grok_bot import GrokBotAdapter
6
+
7
+ __all__ = ["HermesAdapter", "NullAgentAdapter", "GrokBotAdapter"]
@@ -0,0 +1,74 @@
1
+ """
2
+ birkin.adapters.grok_bot
3
+ ========================
4
+
5
+ Grok Bot adapter — implements AgentAdapter for agents running in the
6
+ Grok Bot environment (or any similar tool-using agent).
7
+
8
+ The adapter does not call the real tools itself. It only decides whether
9
+ a receipt permits the call. The actual tool execution is performed by the
10
+ host (the Grok Bot runtime or your own code) *after* it receives an
11
+ allow receipt.
12
+
13
+ This keeps Birkin as a pure authorization + evidence plane.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ from ..adapter import BaseAdapter, ActionResult
21
+ from ..models import AuthorizationReceipt
22
+
23
+
24
+ class GrokBotAdapter(BaseAdapter):
25
+ """Adapter for Grok Bots / similar tool-using agents."""
26
+
27
+ name: str = "grok-bot"
28
+ version: str = "0.1.0"
29
+
30
+ # Tools that a typical Grok Bot is expected to expose.
31
+ # The host is responsible for the real implementation.
32
+ KNOWN_TOOLS = [
33
+ "web_search",
34
+ "browse_page",
35
+ "bash",
36
+ "read_file",
37
+ "write_file",
38
+ "edit_file",
39
+ "places_search",
40
+ "weather_forecast",
41
+ "x_keyword_search",
42
+ "generate_image",
43
+ ]
44
+
45
+ def known_tools(self) -> list[str]:
46
+ return sorted(self.KNOWN_TOOLS)
47
+
48
+ def execute(
49
+ self,
50
+ identity,
51
+ request,
52
+ receipt: AuthorizationReceipt,
53
+ ) -> ActionResult:
54
+ """Refuse to execute unless the receipt says allow.
55
+
56
+ The real tool call happens outside this method. This method only
57
+ records that the host is allowed to proceed.
58
+ """
59
+ if receipt.decision != "allow":
60
+ return ActionResult(
61
+ ok=False,
62
+ error=f"refused by receipt {receipt.receipt_id}: decision={receipt.decision}",
63
+ side_effect_recorded=False,
64
+ )
65
+
66
+ # We do not execute the tool here. The host does, after seeing the allow.
67
+ return ActionResult(
68
+ ok=True,
69
+ output={"note": "receipt allows execution; host should perform the tool call"},
70
+ side_effect_recorded=False,
71
+ )
72
+
73
+
74
+ __all__ = ["GrokBotAdapter"]
@@ -0,0 +1,137 @@
1
+ """
2
+ birkin.adapters.hermes
3
+ ======================
4
+
5
+ Hermes adapter — the first concrete :class:`AgentAdapter`.
6
+
7
+ Hermes is treated here as a tool registry. The runtime surfaces a small set
8
+ of tools to the agent (``shell.exec``, ``fs.write``, ``http.get``,
9
+ ``http.post``, ``db.query``), and Birkin gates every invocation through the
10
+ policy engine + signed receipt flow.
11
+
12
+ This is deliberately minimal: it shows the seam. A production Hermes
13
+ adapter would plug into the real Hermes tool dispatch loop instead of this
14
+ in-process registry, but the contract with Birkin does not change.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Callable
20
+
21
+ from ..adapter import BaseAdapter, ActionResult
22
+ from ..models import AuthorizationReceipt
23
+
24
+
25
+ # Tool handlers: name -> callable(args) -> (ok, output_or_error)
26
+ ToolHandler = Callable[[dict[str, Any]], tuple[bool, Any]]
27
+
28
+
29
+ def _tool_fs_write(args: dict[str, Any]) -> tuple[bool, Any]:
30
+ path = args.get("path", "")
31
+ data = args.get("data", "")
32
+ try:
33
+ with open(path, "w", encoding="utf-8") as fh:
34
+ fh.write(str(data))
35
+ return True, f"wrote {len(str(data))} bytes to {path}"
36
+ except Exception as exc: # pragma: no cover - defensive
37
+ return False, str(exc)
38
+
39
+
40
+ def _tool_fs_read(args: dict[str, Any]) -> tuple[bool, Any]:
41
+ path = args.get("path", "")
42
+ try:
43
+ with open(path, "r", encoding="utf-8") as fh:
44
+ return True, fh.read()
45
+ except Exception as exc:
46
+ return False, str(exc)
47
+
48
+
49
+ def _tool_http_get(args: dict[str, Any]) -> tuple[bool, Any]:
50
+ url = args.get("url", "")
51
+ # Simulated HTTP GET — we do not actually network in this slice, but the
52
+ # call is real and the receipt is real.
53
+ return True, {"status": 200, "url": url, "body": "<simulated 200 OK>"}
54
+
55
+
56
+ def _tool_http_post(args: dict[str, Any]) -> tuple[bool, Any]:
57
+ url = args.get("url", "")
58
+ body = args.get("body", "")
59
+ return True, {"status": 201, "url": url, "echo": str(body)[:200]}
60
+
61
+
62
+ def _tool_db_query(args: dict[str, Any]) -> tuple[bool, Any]:
63
+ sql = args.get("sql", "")
64
+ # Simulated DB. The point is that the receipt is real and the policy
65
+ # decision is real.
66
+ if "DROP" in sql.upper():
67
+ return False, "refused: DROP statements are blocked"
68
+ return True, {"rows": [], "sql": sql}
69
+
70
+
71
+ def _tool_shell_exec(args: dict[str, Any]) -> tuple[bool, Any]:
72
+ cmd = args.get("cmd", "")
73
+ # Hermes registry always *can* run shell, but policy denies it by
74
+ # default. If a policy ever allowed it, we'd actually shell out here.
75
+ import subprocess
76
+
77
+ try:
78
+ out = subprocess.run(
79
+ cmd, shell=True, capture_output=True, text=True, timeout=5
80
+ )
81
+ return out.returncode == 0, out.stdout + out.stderr
82
+ except Exception as exc:
83
+ return False, str(exc)
84
+
85
+
86
+ class HermesAdapter(BaseAdapter):
87
+ """Hermes runtime adapter."""
88
+
89
+ name: str = "hermes"
90
+ version: str = "0.1.0"
91
+
92
+ def __init__(self, agent_signing_key=None) -> None:
93
+ super().__init__(agent_signing_key=agent_signing_key)
94
+ self._tools: dict[str, ToolHandler] = {
95
+ "fs.write": _tool_fs_write,
96
+ "fs.read": _tool_fs_read,
97
+ "http.get": _tool_http_get,
98
+ "http.post": _tool_http_post,
99
+ "db.query": _tool_db_query,
100
+ "shell.exec": _tool_shell_exec,
101
+ }
102
+
103
+ def known_tools(self) -> list[str]:
104
+ return sorted(self._tools.keys())
105
+
106
+ def execute(self, identity, request, receipt: AuthorizationReceipt) -> ActionResult:
107
+ """Execute the action iff the receipt permits it.
108
+
109
+ The receipt is the ground truth. The adapter MUST refuse to execute
110
+ if the receipt's decision is not ``"allow"``. This is the
111
+ invariant that makes the receipt meaningful as a primitive.
112
+ """
113
+ if receipt.decision != "allow":
114
+ return ActionResult(
115
+ ok=False,
116
+ error=f"refused by receipt {receipt.receipt_id}: decision={receipt.decision}",
117
+ side_effect_recorded=False,
118
+ )
119
+
120
+ handler = self._tools.get(request.tool)
121
+ if handler is None:
122
+ return ActionResult(
123
+ ok=False,
124
+ error=f"unknown tool: {request.tool}",
125
+ side_effect_recorded=False,
126
+ )
127
+
128
+ ok, out = handler(request.args)
129
+ return ActionResult(
130
+ ok=ok,
131
+ output=out if ok else None,
132
+ error="" if ok else str(out),
133
+ side_effect_recorded=ok,
134
+ )
135
+
136
+
137
+ __all__ = ["HermesAdapter"]
@@ -0,0 +1,104 @@
1
+ """
2
+ birkin.adapters.infini_gateway
3
+ ==============================
4
+
5
+ Decoupled action gateway for portable workflow runtimes (such as INFINI).
6
+
7
+ Contract:
8
+ 1. Workflow proposes an action: tool name + arguments.
9
+ 2. Gateway queries Birkin policy engine and issues a signed AuthorizationReceipt.
10
+ 3. If allowed, returns structured authorization granting permission to execute.
11
+ 4. If denied or require_approval, returns fail-closed refusal.
12
+ 5. Emits offline-verifiable Birkin evidence package upon workflow completion.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Optional
17
+ from pydantic import BaseModel, Field
18
+
19
+ from ..engine import Engine
20
+ from ..adapter import ActionRequest, BaseAdapter, ActionResult
21
+ from ..models import AgentIdentity, AuthorizationReceipt, RunPackage
22
+ from ..crypto import SigningKey
23
+ from ..policy import PolicySpec, load_default_policy
24
+
25
+
26
+ class GatewayDecision(BaseModel):
27
+ """Structured decision returned to an orchestrator."""
28
+ allowed: bool
29
+ decision: str
30
+ receipt_id: str
31
+ tool: str
32
+ rule: str
33
+ risk_score: int
34
+ reason: str
35
+ receipt: AuthorizationReceipt
36
+
37
+
38
+ class InfiniActionGateway:
39
+ """Independent gateway exposing Birkin authorization to external workflow engines."""
40
+
41
+ def __init__(
42
+ self,
43
+ policy: Optional[PolicySpec] = None,
44
+ signing_key: Optional[SigningKey] = None,
45
+ adapter: Optional[BaseAdapter] = None,
46
+ ) -> None:
47
+ self.signing_key = signing_key or SigningKey.generate()
48
+ self.policy = policy or load_default_policy()
49
+ from .null_agent import NullAgentAdapter
50
+ self.adapter = adapter or NullAgentAdapter()
51
+ self.engine = Engine(
52
+ birkin_signing_key=self.signing_key,
53
+ policy=self.policy,
54
+ adapter=self.adapter,
55
+ )
56
+ self.identity: Optional[AgentIdentity] = None
57
+
58
+ def initialize_workflow(self, workflow_name: str, agent_id: str = "infini-agent") -> AgentIdentity:
59
+ """Start a governance session for a named workflow."""
60
+ ident = self.adapter.make_identity(
61
+ agent_id=agent_id,
62
+ policy_ref=self.policy.ref,
63
+ )
64
+ self.identity = ident
65
+ self.engine.start_session(ident)
66
+ intent = self.adapter.declare_intent(ident, f"Execute workflow: {workflow_name}")
67
+ self.engine.declare_intent(ident, intent)
68
+ return ident
69
+
70
+ def evaluate_step(
71
+ self,
72
+ tool: str,
73
+ args: dict[str, Any],
74
+ justification: str = "",
75
+ ) -> GatewayDecision:
76
+ """Evaluate a proposed workflow step prior to execution."""
77
+ if not self.identity:
78
+ self.initialize_workflow("default-workflow")
79
+
80
+ request = self.adapter.build_action_request(
81
+ tool=tool,
82
+ args=args,
83
+ justification=justification,
84
+ )
85
+ receipt = self.engine.attempt_action(self.identity, request, justification=justification)
86
+
87
+ return GatewayDecision(
88
+ allowed=(receipt.decision == "allow"),
89
+ decision=receipt.decision,
90
+ receipt_id=receipt.receipt_id,
91
+ tool=receipt.tool,
92
+ rule=receipt.rule,
93
+ risk_score=receipt.risk_score,
94
+ reason=receipt.reason,
95
+ receipt=receipt,
96
+ )
97
+
98
+ def complete_workflow(self) -> RunPackage:
99
+ """Checkpoint, end session, and export offline-verifiable run package."""
100
+ if not self.identity:
101
+ raise RuntimeError("No active workflow session to complete")
102
+ self.engine.checkpoint()
103
+ self.engine.end_session(self.identity)
104
+ return self.engine.export(identity=self.identity)