toolwrit 0.2.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,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: toolwrit
3
+ Version: 0.2.0
4
+ Summary: A written authority for AI agents. Allowlist the tools, cap the budget, prove what happened.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/emektor/toolwrit
7
+ Project-URL: Repository, https://github.com/emektor/toolwrit
8
+ Project-URL: Issues, https://github.com/emektor/toolwrit/issues
9
+ Keywords: ai,agent,guardrails,mcp,tool-calling,policy,audit,llm,security
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: pyyaml>=6
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest>=7; extra == "test"
19
+
20
+ # toolwrit
21
+
22
+ A written authority for AI agents. Allowlist the tools, cap the budget, prove
23
+ what happened.
24
+
25
+ This is the Python port of
26
+ [Toolwrit](https://github.com/emektor/toolwrit). **The full documentation lives
27
+ in the main project's docs** — the policy language, the threat model and the
28
+ design rationale are the same here, clause for clause:
29
+
30
+ - [the overview](https://github.com/emektor/toolwrit#readme) — run plans, the
31
+ bytes ceiling, receipts and anchoring.
32
+ - [`policy-reference.md`](https://github.com/emektor/toolwrit/blob/main/js/docs/policy-reference.md) — every
33
+ policy field with a worked example.
34
+ - [`threat-model.md`](https://github.com/emektor/toolwrit/blob/main/js/docs/threat-model.md) — what is and is
35
+ not defended against.
36
+ - [`python.md`](https://github.com/emektor/toolwrit/blob/main/js/docs/python.md) — the Python-specific
37
+ reference: the full API table, the sync/async split, and everything below in
38
+ more detail.
39
+
40
+ What follows is only what a Python user needs on top of that.
41
+
42
+ ```bash
43
+ pip install toolwrit
44
+ ```
45
+
46
+ Until the first release is published:
47
+ `pip install "git+https://github.com/emektor/toolwrit.git#subdirectory=python"`
48
+
49
+ ```python
50
+ from toolwrit import Toolwrit, ToolwritDenied, load_policy_file
51
+
52
+ toolwrit = Toolwrit(load_policy_file("policy.yaml"), audit_file="audit.jsonl")
53
+
54
+ try:
55
+ contents = toolwrit.guard("fs.read", {"path": "/tmp/notes"}, lambda: read_file())
56
+ except ToolwritDenied as denied:
57
+ print(denied.decision.reason, denied.audit_hash)
58
+
59
+ toolwrit.meter(1200, 350) # input tokens, output tokens
60
+ print(toolwrit.usage()) # BudgetUsage(calls=…, tokens=…, usd=…, bytes=…, started_at=…)
61
+ print(toolwrit.head()) # the head of this run's audit chain
62
+ ```
63
+
64
+ ```bash
65
+ toolwrit check --policy policy.yaml --tool fs.read --args '{"path":"/tmp/x"}'
66
+ toolwrit explain --policy policy.yaml
67
+ toolwrit verify audit.jsonl
68
+ ```
69
+
70
+ ## Run plans
71
+
72
+ A `plan:` block declares the envelope a run is approved for, and it works here
73
+ exactly as it does in TypeScript.
74
+
75
+ ```yaml
76
+ budget:
77
+ calls: 200
78
+ usd: 5.00
79
+ bytes: 20000000
80
+ seconds: 3600
81
+
82
+ plan:
83
+ purpose: nightly CRM export for the EU region
84
+ approvedBy: ergin
85
+ warnAt: [0.8, 0.95] # the default
86
+ ```
87
+
88
+ The argument for declaring an envelope rather than setting a global threshold:
89
+ a global threshold has to guess at every job at once, so it is either too loose
90
+ to catch anything or too tight to leave switched on — and an alert people mute
91
+ is the same as no alert. A declared envelope does not guess. Approve once at
92
+ the start, hear nothing until a threshold.
93
+
94
+ ```python
95
+ toolwrit = Toolwrit(
96
+ load_policy_file("export.yaml"),
97
+ run="nightly-2026-09-12",
98
+ audit_file="audit.jsonl",
99
+ on_warn=lambda w: print("on_warn ->", w.message),
100
+ )
101
+ ```
102
+
103
+ ```
104
+ on_warn -> run "nightly-2026-09-12" (nightly CRM export for the EU region) has used 16,000,000/20,000,000 bytes — 80% of the approved envelope
105
+ ```
106
+
107
+ Two properties worth knowing:
108
+
109
+ - **The plan is entry 1 of the audit chain**, written by the constructor before
110
+ anything can be guarded. What was *authorised* is in the tamper-evident record
111
+ alongside what happened.
112
+ - **Each threshold fires at most once per dimension**, across `calls`, `tokens`,
113
+ `usd`, `bytes` and `seconds`, and every warning is recorded in the chain as a
114
+ `toolwrit:warning` entry as well as delivered to `on_warn`. Keep `on_warn`
115
+ non-blocking; it runs inline with metering.
116
+
117
+ A `plan` requires a `budget` to measure against, `purpose` must be non-empty,
118
+ and `warnAt` entries must be greater than 0 and at most 1. All three are load
119
+ errors, with the same messages as the TypeScript implementation.
120
+
121
+ ## The bytes ceiling
122
+
123
+ `budget.bytes` caps the total size of what tools **return** over a run. Bulk
124
+ exfiltration is rarely a forbidden action — it is a permitted action repeated
125
+ until something is drained, so every individual call passes the allowlist and
126
+ only the running total gives it away. Unlike `usd` and `tokens`, this dimension
127
+ needs no cooperation from your integration: `guard` and `guard_async` feed it.
128
+
129
+ ```
130
+ call 5: ok, bytes now 20000000
131
+ call 6: toolwrit: crm.search denied — data budget exhausted: 20000000/20000000 bytes returned by tools
132
+ ```
133
+
134
+ **The limitation, stated up front.** A result's size is not knowable before the
135
+ tool runs, so the measurement happens afterwards: the call that blows the
136
+ ceiling **completes**, and the **next** one is refused. A bytes ceiling bounds a
137
+ run at the limit *plus one call*, never exactly the limit. If one call can
138
+ return everything, cap the response at the tool.
139
+
140
+ Sizes: `None` → 0; `str` → its UTF-8 byte length; `bytes`/`bytearray`/
141
+ `memoryview` → their length; anything else → the UTF-8 byte length of its
142
+ canonical JSON, which equals what TypeScript gets from `JSON.stringify`. A
143
+ result that cannot be serialised falls back to `str(result)` and is therefore
144
+ **under-counted** — documented rather than hidden, because under-counting a
145
+ volume ceiling fails open.
146
+
147
+ ## Receipts and anchoring: use the TypeScript CLI
148
+
149
+ Run receipts (`summarize`, `verifyAgainstReceipt`) and the `toolwrit receipt`,
150
+ `toolwrit anchor` and `toolwrit verify --against` subcommands are **not ported**.
151
+ Because the chains are compatible, that is not a blocker — point the TypeScript
152
+ CLI at a Python-written log:
153
+
154
+ ```bash
155
+ toolwrit receipt audit.jsonl # written by toolwrit for Python
156
+ toolwrit anchor audit.jsonl --to anchors.jsonl
157
+ toolwrit verify audit.jsonl --against anchors.jsonl
158
+ ```
159
+
160
+ This matters more than it sounds. Verifying a chain in isolation **cannot**
161
+ detect that its tail was cut off: a prefix of a valid chain is itself a valid
162
+ chain and verifies clean, so an agent that deletes its last twenty entries hands
163
+ you a log that passes. Comparing against a receipt anchored at the time closes
164
+ that hole — and only if the anchor lives where the agent cannot rewrite it,
165
+ which Toolwrit cannot enforce.
166
+
167
+ The Python `toolwrit verify` **refuses** `--against` rather than ignoring it:
168
+
169
+ ```
170
+ $ toolwrit verify truncated.jsonl --against anchors.jsonl
171
+ toolwrit: `verify --against <anchor>` is not implemented in the Python CLI; ...
172
+ $ echo $?
173
+ 1
174
+ ```
175
+
176
+ Accepting the flag and dropping it would print `ok` and exit 0 on precisely the
177
+ truncated log the flag exists to catch — a fail-open in the one command whose
178
+ job is detecting tampering. Every subcommand rejects flags it does not
179
+ implement for the same reason. Use the TypeScript CLI for anchoring; it reads
180
+ chains written here.
181
+
182
+ ## Chain compatibility
183
+
184
+ An audit chain written here verifies under the TypeScript `toolwrit verify`, and
185
+ one written there verifies here — same canonical string, same SHA-256, same
186
+ head hash. `tests/test_interop.py` proves it in both directions, and goes
187
+ further than "both say ok": it builds the same chain with both implementations
188
+ and asserts the entry hashes are equal, which no pair of mutually incompatible
189
+ serialisers could manage.
190
+
191
+ Getting there is mostly about numbers. JavaScript has one numeric type and
192
+ prints it with `Number::toString` — `1.0` is `"1"`, `1e21` is `"1e+21"`, `1e16`
193
+ is `"10000000000000000"` — where Python's `repr` keeps the `.0` and switches to
194
+ exponent notation at a different magnitude. `toolwrit._js` implements the
195
+ ECMAScript algorithm directly; `test_audit.py` pins the values one by one.
196
+
197
+ ## Differences from the TypeScript version
198
+
199
+ Behaviour is otherwise identical. These are the exceptions, and none of them
200
+ loosens a policy.
201
+
202
+ **`None` is `null`, not `undefined`.** JavaScript has two empty values and
203
+ `JSON.stringify` treats them differently: `null` is serialised, `undefined` is
204
+ dropped. Python has one. Since `decision.rule` is legitimately `null` on every
205
+ default-deny and the TypeScript chain commits to it, `canonicalize` **keeps**
206
+ `None` as `null` — dropping it would break the chain outright. The "drop me"
207
+ meaning is carried by an explicit `toolwrit._js.UNDEFINED` sentinel instead.
208
+
209
+ The visible consequence is in constraints: an argument key present but set to
210
+ `None` counts as **absent**, so it fails a non-`optional` constraint with a
211
+ `required` violation. TypeScript would call `{"path": null}` a present null and
212
+ report a `type` violation instead. Both refuse the call; only the violation
213
+ name differs.
214
+
215
+ **`guard` is split in two.** Python cannot await from a synchronous frame, so
216
+ `guard(tool, args, execute)` serves ordinary functions and
217
+ `await guard_async(tool, args, execute)` awaits whatever it is given — an async
218
+ tool, an async `on_ask` handler, or plain functions unchanged. Passing an async
219
+ `on_ask` to the synchronous `guard` raises `TypeError` rather than guessing.
220
+
221
+ **`toolwrit run` is not ported.** The MCP stdio proxy and the Anthropic/OpenAI SDK
222
+ adapters stay in the TypeScript package; `toolwrit run` here exits 1 and says so.
223
+ `check`, `explain` and `verify` behave identically, exit codes included.
224
+
225
+ **Run receipts and anchoring are not ported.** There is no `summarize` or
226
+ `verify_against_receipt`, and no `receipt`, `anchor` or working `verify
227
+ --against` in this CLI. Use the TypeScript CLI over the Python-written log; see
228
+ the section above.
229
+
230
+ **Regexes are Python regexes.** A `matches:` pattern is compiled with `re`, not
231
+ V8's `RegExp`. The common syntax is shared, but the dialects diverge on named
232
+ groups (`(?P<x>)` vs `(?<x>)`), lookbehind and the Unicode semantics of `\d`
233
+ and `\w`. A policy shared between the two implementations should stay inside
234
+ the common subset.
235
+
236
+ **URLs are parsed with `urllib.parse`,** with an explicit absolute-URL gate
237
+ (scheme required, declared authority must exist) standing in for the throw that
238
+ WHATWG `new URL()` performs. The tested behaviour matches, including the
239
+ `https://example.com@evil.com/` case. Two untested corners differ: an IPv6 host
240
+ comes back as `::1` rather than `[::1]`, and an internationalised domain is not
241
+ converted to punycode, so an IDN `urlHosts` entry must be written in the same
242
+ form the argument uses.
243
+
244
+ **YAML is YAML 1.1.** PyYAML implements 1.1, the TypeScript `yaml` package
245
+ implements 1.2. The difference a policy author can hit is bare `yes`/`no`/
246
+ `on`/`off`, which PyYAML reads as booleans and the TypeScript reads as strings.
247
+ Quote them. JSON parses identically under both.
248
+
249
+ **The JSONL byte layout differs cosmetically.** Within a violation object this
250
+ port writes `path` last where the TypeScript writes it second. The canonical
251
+ form sorts keys, so the hashes are unaffected and each implementation verifies
252
+ the other's file; only a byte-for-byte `diff` of the two logs shows it.
253
+
254
+ ## Development
255
+
256
+ ```bash
257
+ pip install -e '.[test]'
258
+ python -m pytest
259
+ ```
260
+
261
+ The cross-language tests need `node` and a built copy of the TypeScript
262
+ implementation; they look for it at `../js` or at `$TOOLWRIT_TS_ROOT`, and skip
263
+ when it is absent.
264
+
265
+ ## Licence
266
+
267
+ Apache-2.0.
@@ -0,0 +1,20 @@
1
+ toolwrit/__init__.py,sha256=eTo1WxcwP0WJpZ4zjIlJ61RlyCdsvECoSosr5WYIK64,2035
2
+ toolwrit/_js.py,sha256=yPyUqtcva6eJFPVgPey4l3bXZlZHVAuLsOdgUyzX-J0,9694
3
+ toolwrit/cli.py,sha256=S_kVN0RPc28fkEysmCAkVF9KbpI723Ei_I9Qcg8slrw,11092
4
+ toolwrit/toolwrit.py,sha256=XjNsE-ZIDSZfIKKJB6-PLnNLqF5RNT-4ROq8sQ3PKUI,16999
5
+ toolwrit/types.py,sha256=7YVrVbebvVon8UXknlJQ-zNgBK07DrAt32znKcw3LRg,9589
6
+ toolwrit/audit/__init__.py,sha256=FeapTmLVNzpm9g722jKM4NA1uztCs4QFJLb2WUbJ3ZU,55
7
+ toolwrit/audit/chain.py,sha256=Wx9NhRQT_TXvBs-mQszraoVFbbIFw1M_oHeDOjsacRM,8362
8
+ toolwrit/audit/verify.py,sha256=TYQ14siWhpYhr7wNkdDl8gfkEX72aG4vGcQYbzKaCWs,5317
9
+ toolwrit/budget/__init__.py,sha256=nJ7Z1xrOVYfbSZbu3Du5zxtybbAEfFFiae-CN3V9DRg,39
10
+ toolwrit/budget/ledger.py,sha256=Z0qunld4M4HFkO1GiIPCu1-zVH5x_8aY3BziQot4Q0s,5446
11
+ toolwrit/policy/__init__.py,sha256=F8zf3ns-qn3WWa-SvRz_TzPLndDQEJsIQmhZSnLIkyw,63
12
+ toolwrit/policy/constraints.py,sha256=X5vuACV_E71YFKE9b987pTzSMnKIELb0Vf1ZBZXvVwQ,17545
13
+ toolwrit/policy/engine.py,sha256=bfFKN7hLVfo0sC07NMgAMQXLHIt4-YZsgpDxB_4NexM,7153
14
+ toolwrit/policy/load.py,sha256=5FkU3-lg4U3akAF5ByuVECePYhuMRZLVAFZ-r2Wk2G8,15518
15
+ toolwrit/policy/match.py,sha256=X3jNiQqi9ZAaGPBP25sNb_J9Ek9jVn6B1x0hcoR2SVI,3199
16
+ toolwrit-0.2.0.dist-info/METADATA,sha256=NjgwIgMgrbJIjfQRPgXmc6wSroR8Bov4X6R2zbqPd1Q,11581
17
+ toolwrit-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
18
+ toolwrit-0.2.0.dist-info/entry_points.txt,sha256=zoXi3evI9lTmWm0NM4dEQHFNukGlHyzW9AK-SMdLftE,47
19
+ toolwrit-0.2.0.dist-info/top_level.txt,sha256=4eu7TJhdxIBzMd5sPeBopFUqK21Acob6sN9ty49AzlE,9
20
+ toolwrit-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ toolwrit = toolwrit.cli:main
@@ -0,0 +1 @@
1
+ toolwrit