trooth-verify 0.4.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.
@@ -0,0 +1,157 @@
1
+ """The Trooth guard for the OpenAI Agents SDK for Python (openai-agents).
2
+
3
+ Followed, read on October 7, 2026:
4
+ https://openai.github.io/openai-agents-python/guardrails/ (tool guardrails:
5
+ @tool_input_guardrail functions get ToolInputGuardrailData whose context is a ToolContext
6
+ with tool_name, tool_call_id and tool_arguments (a JSON string); they return
7
+ ToolGuardrailFunctionOutput.allow(), .reject_content(message) or .raise_exception();
8
+ attached with @function_tool(tool_input_guardrails=[...]))
9
+ https://openai.github.io/openai-agents-python/human_in_the_loop/ (needs_approval: True or
10
+ an async function (run_context, params, call_id) -> bool; result.interruptions,
11
+ state.approve / state.reject)
12
+ and src/agents/tool_guardrails.py, tool.py and run_context.py
13
+ (RunContextWrapper.is_tool_approved(tool_name, call_id)) on github.com/openai/openai-agents-python main.
14
+
15
+ from agents import function_tool
16
+ from trooth_guard.openai_agents import needs_approval, tool_input_guardrail
17
+
18
+ @function_tool(needs_approval=needs_approval("policy.yaml", "create_payout"),
19
+ tool_input_guardrails=[tool_input_guardrail("policy.yaml")])
20
+ def create_payout(url: str, amount: int) -> str: ...
21
+
22
+ allow runs the tool. hold: needs_approval pauses the run for a person; the
23
+ guardrail then allows a call a person approved and otherwise rejects it with
24
+ a message to the model. deny: the guardrail raises the tripwire
25
+ (ToolInputGuardrailTripwireTriggered), which stops the run.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import asyncio
31
+ import json
32
+ from typing import Any, Callable, Dict, Optional, Sequence
33
+
34
+ from .core import covered, decide, describe
35
+
36
+
37
+ class _Output:
38
+ """The shape of agents.ToolGuardrailFunctionOutput, for use without the SDK installed."""
39
+
40
+ def __init__(self, behavior: Dict[str, Any], output_info: Any = None):
41
+ self.behavior = behavior
42
+ self.output_info = output_info
43
+
44
+ @classmethod
45
+ def allow(cls, output_info: Any = None) -> "_Output":
46
+ return cls({"type": "allow"}, output_info)
47
+
48
+ @classmethod
49
+ def reject_content(cls, message: str, output_info: Any = None) -> "_Output":
50
+ return cls({"type": "reject_content", "message": message}, output_info)
51
+
52
+ @classmethod
53
+ def raise_exception(cls, output_info: Any = None) -> "_Output":
54
+ return cls({"type": "raise_exception"}, output_info)
55
+
56
+
57
+ def _factory(output_factory: Any) -> Any:
58
+ if output_factory is not None:
59
+ return output_factory
60
+ try:
61
+ from agents import ToolGuardrailFunctionOutput # optional
62
+
63
+ return ToolGuardrailFunctionOutput
64
+ except Exception: # noqa: BLE001 - the SDK is optional
65
+ return _Output
66
+
67
+
68
+ def _parse(args: Any) -> Any:
69
+ if not isinstance(args, str):
70
+ return args if args is not None else {}
71
+ try:
72
+ return json.loads(args or "{}")
73
+ except ValueError:
74
+ return args
75
+
76
+
77
+ def _approved(ctx: Any, name: Any, call_id: Any) -> bool:
78
+ fn = getattr(ctx, "is_tool_approved", None)
79
+ if not callable(fn) or name is None or call_id is None:
80
+ return False
81
+ try:
82
+ return fn(name, call_id) is True
83
+ except Exception: # noqa: BLE001
84
+ return False
85
+
86
+
87
+ def tool_input_guardrail_function(
88
+ policy_path: str,
89
+ *,
90
+ on_hold: str = "reject",
91
+ tools: Optional[Sequence[str]] = None,
92
+ output_factory: Any = None,
93
+ on_decision: Optional[Callable[[dict], None]] = None,
94
+ **decide_kw: Any,
95
+ ) -> Callable[[Any], Any]:
96
+ """The guardrail function: async (ToolInputGuardrailData) -> ToolGuardrailFunctionOutput.
97
+
98
+ on_hold "reject" (default) rejects a held call no person approved with a
99
+ message to the model; "raise" raises the tripwire instead. tools: the
100
+ policy's applies_to.tools globs; other tools are allowed without asking.
101
+ """
102
+ if on_hold not in ("reject", "raise"):
103
+ raise ValueError('on_hold is "reject" or "raise"')
104
+ F = _factory(output_factory)
105
+
106
+ async def trooth_guard(data: Any) -> Any:
107
+ ctx = getattr(data, "context", None)
108
+ name = getattr(ctx, "tool_name", None)
109
+ if not covered(name, tools):
110
+ return F.allow({"covered": False})
111
+ args = _parse(getattr(ctx, "tool_arguments", None))
112
+ d = await asyncio.to_thread(decide, policy_path, str(name), None, args, **decide_kw)
113
+ if d is None:
114
+ return F.allow({"covered": False})
115
+ if on_decision:
116
+ on_decision(d)
117
+ info = {"covered": True, "decision": d}
118
+ if d["decision"] == "allow":
119
+ return F.allow(info)
120
+ if d["decision"] == "deny":
121
+ return F.raise_exception(info)
122
+ if _approved(ctx, name, getattr(ctx, "tool_call_id", None)):
123
+ return F.allow({**info, "approved_by_person": True})
124
+ return F.raise_exception(info) if on_hold == "raise" else F.reject_content(describe(d), info)
125
+
126
+ trooth_guard.__name__ = "trooth_guard"
127
+ return trooth_guard
128
+
129
+
130
+ def tool_input_guardrail(policy_path: str, *, name: str = "trooth_guard", **kw: Any) -> Any:
131
+ """An agents.ToolInputGuardrail. Imports the SDK."""
132
+ from agents import ToolInputGuardrail # optional; only here
133
+
134
+ return ToolInputGuardrail(guardrail_function=tool_input_guardrail_function(policy_path, **kw), name=name)
135
+
136
+
137
+ def needs_approval(
138
+ policy_path: str,
139
+ tool_name: str,
140
+ *,
141
+ on_decision: Optional[Callable[[dict], None]] = None,
142
+ **decide_kw: Any,
143
+ ) -> Callable[[Any, Dict[str, Any], str], Any]:
144
+ """An approval policy for function_tool(needs_approval=...): True when the guard holds the call.
145
+
146
+ Deny answers False: the guardrail stops a denied call; a person cannot approve it.
147
+ """
148
+
149
+ async def policy(run_context: Any, params: Dict[str, Any], call_id: str) -> bool:
150
+ d = await asyncio.to_thread(decide, policy_path, tool_name, None, params, **decide_kw)
151
+ if d is None:
152
+ return False # the policy does not cover this tool; nothing was decided
153
+ if on_decision:
154
+ on_decision(d)
155
+ return d["decision"] == "hold"
156
+
157
+ return policy
@@ -0,0 +1,39 @@
1
+ """trooth-verify: check a Trooth witness statement yourself.
2
+
3
+ from trooth_verify import verify_statement, verify_bundle
4
+
5
+ The rules are docs/VERIFY.md in github.com/troothllc/trooth-cli; this package
6
+ runs that repository's test vectors. Licensed under the Apache License 2.0.
7
+ """
8
+
9
+ from .jcs import CanonicalizationError, canonicalize, is_canonical
10
+ from .tlog import LOG_ORIGIN, check_receipt, open_checkpoint, verify_consistency, verify_inclusion
11
+ from .verify import (
12
+ ASSURANCE,
13
+ JCS_LABEL,
14
+ REASONS,
15
+ VERIFICATION_BUNDLE_V1,
16
+ WITNESS_STATEMENT_V1,
17
+ WITNESS_STATEMENT_V2,
18
+ WITNESS_STATEMENT_V3,
19
+ BundleError,
20
+ canonical_manifest,
21
+ count_problems,
22
+ key_state,
23
+ key_trust,
24
+ sha256_digest,
25
+ statement_id,
26
+ verify_bundle,
27
+ verify_correction,
28
+ verify_statement,
29
+ )
30
+
31
+ __version__ = "0.2.0"
32
+
33
+ __all__ = [
34
+ "ASSURANCE", "JCS_LABEL", "REASONS", "VERIFICATION_BUNDLE_V1", "WITNESS_STATEMENT_V1",
35
+ "WITNESS_STATEMENT_V2", "WITNESS_STATEMENT_V3", "BundleError", "CanonicalizationError",
36
+ "canonical_manifest", "canonicalize", "count_problems", "is_canonical", "key_state", "key_trust",
37
+ "sha256_digest", "statement_id", "verify_bundle", "verify_statement", "__version__",
38
+ "LOG_ORIGIN", "check_receipt", "open_checkpoint", "verify_consistency", "verify_inclusion", "verify_correction",
39
+ ]
trooth_verify/jcs.py ADDED
@@ -0,0 +1,88 @@
1
+ """RFC 8785 (JCS) under the trooth.witness-statement.v3 profile: integers only.
2
+
3
+ The same rules as bin/lib/jcs.mjs and sdk/go/trooth/jcs.go, so all three
4
+ produce the same bytes or the same refusal.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+ MAX_SAFE = 2**53 - 1
13
+
14
+
15
+ class CanonicalizationError(ValueError):
16
+ """The value has no canonical form under the v3 profile."""
17
+
18
+
19
+ def _str(s: str) -> str:
20
+ out = ['"']
21
+ for ch in s:
22
+ o = ord(ch)
23
+ if 0xD800 <= o <= 0xDFFF:
24
+ raise CanonicalizationError("a string holds a lone surrogate")
25
+ if ch == '"':
26
+ out.append('\\"')
27
+ elif ch == "\\":
28
+ out.append("\\\\")
29
+ elif ch == "\b":
30
+ out.append("\\b")
31
+ elif ch == "\f":
32
+ out.append("\\f")
33
+ elif ch == "\n":
34
+ out.append("\\n")
35
+ elif ch == "\r":
36
+ out.append("\\r")
37
+ elif ch == "\t":
38
+ out.append("\\t")
39
+ elif o < 0x20:
40
+ out.append("\\u%04x" % o)
41
+ else:
42
+ out.append(ch)
43
+ out.append('"')
44
+ return "".join(out)
45
+
46
+
47
+ def _utf16_key(k: str) -> bytes:
48
+ return k.encode("utf-16-be", "surrogatepass")
49
+
50
+
51
+ def canonicalize(value: Any) -> str:
52
+ """The canonical JSON text of a parsed JSON value."""
53
+ if value is None:
54
+ return "null"
55
+ if value is True:
56
+ return "true"
57
+ if value is False:
58
+ return "false"
59
+ if isinstance(value, str):
60
+ return _str(value)
61
+ if isinstance(value, int):
62
+ if not -MAX_SAFE <= value <= MAX_SAFE:
63
+ raise CanonicalizationError(f"the number {value} is outside -(2^53 - 1) to 2^53 - 1")
64
+ return str(value)
65
+ if isinstance(value, float):
66
+ if value != value or value in (float("inf"), float("-inf")) or not value.is_integer():
67
+ raise CanonicalizationError(f"the number {value} is not an integer")
68
+ return canonicalize(int(value))
69
+ if isinstance(value, list):
70
+ return "[" + ",".join(canonicalize(v) for v in value) + "]"
71
+ if isinstance(value, dict):
72
+ keys = sorted(value.keys(), key=_utf16_key)
73
+ return "{" + ",".join(_str(k) + ":" + canonicalize(value[k]) for k in keys) + "}"
74
+ raise CanonicalizationError(f"a {type(value).__name__} has no JSON form")
75
+
76
+
77
+ def is_canonical(text: str) -> bool:
78
+ """Whether text is already the canonical form of the JSON it holds."""
79
+ if not isinstance(text, str):
80
+ return False
81
+ try:
82
+ parsed = json.loads(text)
83
+ except ValueError:
84
+ return False
85
+ try:
86
+ return canonicalize(parsed) == text
87
+ except CanonicalizationError:
88
+ return False