agent-spend-gate 0.7.2__tar.gz

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 (37) hide show
  1. agent_spend_gate-0.7.2/.gitignore +8 -0
  2. agent_spend_gate-0.7.2/CHANGELOG.md +101 -0
  3. agent_spend_gate-0.7.2/LICENSE +202 -0
  4. agent_spend_gate-0.7.2/PKG-INFO +195 -0
  5. agent_spend_gate-0.7.2/README.md +168 -0
  6. agent_spend_gate-0.7.2/SECURITY.md +30 -0
  7. agent_spend_gate-0.7.2/docs/CASE-STUDY.md +103 -0
  8. agent_spend_gate-0.7.2/docs/RELEASE-CHECKLIST.md +118 -0
  9. agent_spend_gate-0.7.2/examples/demo.py +12 -0
  10. agent_spend_gate-0.7.2/pyproject.toml +43 -0
  11. agent_spend_gate-0.7.2/skill/README.md +14 -0
  12. agent_spend_gate-0.7.2/skill/SKILL.md +115 -0
  13. agent_spend_gate-0.7.2/skill/scan_paid_calls.py +112 -0
  14. agent_spend_gate-0.7.2/src/spend_gate/__init__.py +17 -0
  15. agent_spend_gate-0.7.2/src/spend_gate/audit.py +38 -0
  16. agent_spend_gate-0.7.2/src/spend_gate/auth.py +105 -0
  17. agent_spend_gate-0.7.2/src/spend_gate/budget.py +348 -0
  18. agent_spend_gate-0.7.2/src/spend_gate/cli.py +205 -0
  19. agent_spend_gate-0.7.2/src/spend_gate/gate.py +226 -0
  20. agent_spend_gate-0.7.2/src/spend_gate/i18n.py +97 -0
  21. agent_spend_gate-0.7.2/src/spend_gate/keychain.py +77 -0
  22. agent_spend_gate-0.7.2/src/spend_gate/ledger.py +102 -0
  23. agent_spend_gate-0.7.2/src/spend_gate/locales/de.json +27 -0
  24. agent_spend_gate-0.7.2/src/spend_gate/locales/en.json +27 -0
  25. agent_spend_gate-0.7.2/src/spend_gate/locales/es.json +27 -0
  26. agent_spend_gate-0.7.2/src/spend_gate/locales/fr.json +27 -0
  27. agent_spend_gate-0.7.2/src/spend_gate/locales/ja.json +27 -0
  28. agent_spend_gate-0.7.2/src/spend_gate/locales/ko.json +27 -0
  29. agent_spend_gate-0.7.2/src/spend_gate/locales/zh-Hans.json +27 -0
  30. agent_spend_gate-0.7.2/src/spend_gate/locales/zh-Hant.json +27 -0
  31. agent_spend_gate-0.7.2/src/spend_gate/policy.py +269 -0
  32. agent_spend_gate-0.7.2/tests/test_budget.py +145 -0
  33. agent_spend_gate-0.7.2/tests/test_gate.py +107 -0
  34. agent_spend_gate-0.7.2/tests/test_i18n.py +50 -0
  35. agent_spend_gate-0.7.2/tests/test_limits.py +129 -0
  36. agent_spend_gate-0.7.2/tests/test_policy.py +115 -0
  37. agent_spend_gate-0.7.2/tests/test_vendors.py +83 -0
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ build/
5
+ dist/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .audit.jsonl
@@ -0,0 +1,101 @@
1
+ # Changelog
2
+
3
+ ## 0.7.2 — 2026-11-23
4
+
5
+ - Fix the period button reading "Allow for this daily" (and the Chinese
6
+ "本每日都放行"). Each period now has its own full phrase in all eight
7
+ locales. Caught in a real dialog, not by tests — key-parity checks do not
8
+ know that "daily" does not belong inside "Allow for this ___".
9
+
10
+ ## 0.7.1 — 2026-11-23
11
+
12
+ - **[Case study](docs/CASE-STUDY.md)**: a real adoption on a 40-file repository, from the incident that started it to the batch-approval problem that only showed up when imagining daily use. Includes the wrong numbers (215 call sites reported, 3 real) because that is the part worth reading.
13
+ - The setup skill is now linked from the top of the README, with its own `skill/README.md`. It stays in this repository rather than a separate one: it calls this CLI, so the two must version together.
14
+
15
+ ## 0.7.0 — 2026-11-22
16
+
17
+ - `spend-gate policy load policy.json` — apply a whole policy in one call, so a whitelist for five vendors costs one fingerprint instead of five.
18
+ - New skill in `skill/`: scans a repository for paid API calls, asks which vendors should stay behind a prompt, writes the policy, and wraps the call sites. Tested against a real 215-call repository.
19
+ - README rewritten around the three spending modes and the one thing that actually matters: an unwrapped call is unprotected and nothing tells you.
20
+
21
+ ## 0.6.0 — 2026-11-22
22
+
23
+ - **Korean, German, French and Spanish** locales, alongside the existing English, Simplified Chinese, Traditional Chinese and Japanese. Cantonese maps to Traditional Chinese.
24
+ - **No UI string is hardcoded any more.** The policy-change prompt, the envelope cap wording and the `day/week/month` labels inside the limit dialog all go through the locale files.
25
+ - Limit amounts in the dialog are formatted consistently (`18.00 + 5.00 = 23.00 > 20.00`) instead of mixing `0.9` and `0.90`.
26
+ - 69 tests, including key parity across all eight locales.
27
+
28
+ ## 0.5.0 — 2026-11-22
29
+
30
+ - **Per-vendor limits**: `--vendor dashscope --vendor-daily-limit 5`, prefix-matched with longest match winning.
31
+ - **Vendor whitelist**: `--vendor-trusted` skips the dialog for that vendor while it stays inside its own and the global ceilings. It removes the interruption, not the limit.
32
+ - **Period waiver**: the limit dialog gains "Allow for this day/week/month", so an approved long job keeps running instead of prompting at every charge. Waivers expire with the period.
33
+ - 64 tests.
34
+
35
+ ## 0.4.1 — 2026-11-22
36
+
37
+ Fixes from a second review.
38
+
39
+ - Auto-approved charges no longer skip the global ceilings: a stream of tiny auto-approved calls could previously spend past a hard limit.
40
+ - Manually approved charges are written to the ledger. Without this the ceilings were blind to the largest spends.
41
+ - `AuditWriteError` is wrapped in `SpendNotApproved`, so callers that only catch that exception do not crash on an unwritable audit log.
42
+ - Opening an envelope no longer double-counts its cap as a spend.
43
+ - 0.4.0
44
+
45
+ - **Daily, weekly and monthly ceilings** across all spending, independent of envelopes. Previously an agent could open any number of envelopes and never hit a total limit.
46
+ - Crossing a ceiling opens a distinct dialog that shows what was already spent, the pending charge, and the resulting total. Approving it is recorded with an `over_limit` field rather than silently allowed.
47
+ - `hard_limit` refuses instead of asking, for unattended services.
48
+ - `spend-gate policy set --daily-limit --weekly-limit --monthly-limit --hard-limit`.
49
+ - 56 tests.
50
+
51
+ ## 0.3.1 — 2026-11-22
52
+
53
+ Security and correctness fixes from an external review.
54
+
55
+ **The gate could be opened without a human.** `policy.save()` and
56
+ `spend-gate policy set` raised the auto-approve threshold with no
57
+ authentication, which defeats the entire point. Both now require Touch ID
58
+ or the account password.
59
+
60
+ - Auto-approved charges are written to the ledger. Without this the daily
61
+ cap was always computed from an empty ledger and never fired.
62
+ - `Ledger.append` holds a file lock across read-compute-write; two workers
63
+ appending concurrently used to produce the same `seq` and a chain that
64
+ failed verification during normal use.
65
+ - `Envelope` is a context manager, as the README always claimed.
66
+ - `settle()` refuses to run on an expired envelope; `_save` fsyncs before
67
+ the atomic replace.
68
+ - `verify` reconciles every envelope's `spent` against the ledger, so a
69
+ hand-edited envelope file shows up as a mismatch.
70
+ - Keychain reads distinguish "not found" from "denied"; a locked keychain
71
+ no longer causes the policy key to be silently regenerated.
72
+ - `canEvaluatePolicy` failures are converted to a denied result instead of
73
+ escaping as a raw PyObjC exception.
74
+ - Tests isolate `SPEND_GATE_HOME` and mock authentication; previously they
75
+ read the real `~/.spend-gate` and would have hung on a fingerprint prompt.
76
+
77
+ ## 0.3.0 — 2026-11-22
78
+
79
+ - **Keychain anchor**: the ledger head is written to the login Keychain whenever a human approves something. `spend-gate verify` now fails if the tail no longer matches the anchor, catching silent truncation and rollback that a pure hash chain cannot see.
80
+ - **Auto-approve policy** for tiny charges, off by default. `spend-gate policy set --auto-under 0.05 --daily-cap 1.00`. The policy file is HMAC-signed with a Keychain-held key; an invalid signature disables auto-approval rather than falling back to permissive behaviour.
81
+ - `spend-gate policy show|set`, `SPEND_GATE_NO_KEYCHAIN=1` to run without a Keychain (anchor checks reported as skipped).
82
+ - 46 tests, all without UI, network, or a real Keychain.
83
+
84
+ ## 0.2.0 — 2026-11-22
85
+
86
+ - **Budget envelopes** for spending where the total isn't known upfront: `open_envelope(max_amount=..., ttl_hours=...)` asks for one approval covering a cap, then charges inside it proceed without prompting.
87
+ - `Envelope.spend()` for known prices; `reserve()` / `settle()` / `release()` and a `reservation()` context manager for costs discovered after the call. Exceptions charge the held amount rather than silently freeing it.
88
+ - **Hash-chained ledger** at `~/.spend-gate/ledger.jsonl`; `spend-gate verify` detects edited or deleted rows. Truncation and rollback detection need the Keychain anchor planned for 0.3.
89
+ - `flock` serialises every read-modify-write, so concurrent workers cannot each believe they still have headroom.
90
+ - CLI: `spend-gate envelope open|status`, `spend-gate verify`.
91
+ - 36 tests, all without UI or network.
92
+
93
+ ## 0.1.0 — 2026-11-22
94
+
95
+ First public release.
96
+
97
+ - Two gates: an AppleScript confirmation dialog (default button is *Cancel*) followed by macOS `LocalAuthentication` (`deviceOwnerAuthentication`, Touch ID with password fallback).
98
+ - Fail-closed on every path: non-macOS, missing biometrics, timeout, user cancel, and audit-write failure all raise `SpendNotApproved`.
99
+ - Append-only audit log at `~/.spend-gate/audit.jsonl`, overridable with `SPEND_GATE_AUDIT_PATH`.
100
+ - Localized dialog and prompt text for English, Simplified Chinese, Traditional Chinese and Japanese, following the macOS UI language.
101
+ - CLI: `spend-gate doctor | approve | audit`.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-spend-gate
3
+ Version: 0.7.2
4
+ Summary: A human-in-the-loop spending gate for AI agents on macOS - no Touch ID or password approval, no paid API call.
5
+ Project-URL: Homepage, https://github.com/yuyauchuncn-dot/agent-spend-gate
6
+ Project-URL: Issues, https://github.com/yuyauchuncn-dot/agent-spend-gate/issues
7
+ Author: Derek Yu
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,human-in-the-loop,macos,safety,spending,touch-id
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: pyobjc-framework-localauthentication>=13; sys_platform == 'darwin'
22
+ Provides-Extra: dev
23
+ Requires-Dist: build; extra == 'dev'
24
+ Requires-Dist: pytest>=8; extra == 'dev'
25
+ Requires-Dist: twine; extra == 'dev'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # agent-spend-gate
29
+
30
+ **Your AI agent is about to spend money. This makes it ask you first.**
31
+
32
+ > **Adopting this in an existing repo?** [`skill/`](skill/) scans for paid API calls, asks once which vendors should stay behind a prompt, and wraps the call sites. One fingerprint for the whole policy. [Read the case study](docs/CASE-STUDY.md) — 215 apparent call sites turned out to be 3 real ones.
33
+
34
+ One line before the paid call. A dialog says who gets paid and how much. Then macOS asks for your fingerprint or password. If either step fails, the call never happens.
35
+
36
+ ```
37
+ ┌─ Spending approval ─────────────────────┐
38
+ │ openai/gpt-4o requests 2.00 CNY for: │
39
+ │ summarise 10 documents │
40
+ │ Quantity: 10 calls │
41
+ │ │
42
+ │ [ Cancel ] [ Approve ] │
43
+ └─────────────────────────────────────────┘
44
+ ↓ you click Approve
45
+ ┌─ macOS ─────────────────────────────────┐
46
+ │ 🔒 Touch ID │
47
+ │ Approve spending 2.00 CNY to openai │
48
+ └─────────────────────────────────────────┘
49
+ ↓ fingerprint accepted
50
+ the API call runs
51
+ ```
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install agent-spend-gate
57
+ ```
58
+
59
+ macOS only, Python 3.11+. On any other platform the gate **refuses** — it does not silently skip the check.
60
+
61
+ ## The one thing you have to do
62
+
63
+ Put `require_approval` in front of every billable call.
64
+
65
+ ```python
66
+ from spend_gate import require_approval
67
+
68
+ require_approval(amount=2.0, currency="CNY",
69
+ vendor="openai/gpt-4o",
70
+ purpose="summarise 10 documents",
71
+ quantity="10 calls")
72
+
73
+ # Only reached after a human approved. Now spend.
74
+ client.chat.completions.create(...)
75
+ ```
76
+
77
+ If you do not wrap a call, that call is not protected. The gate is opt-in per call site — there is no interception layer, and nothing fails loudly when you miss one. **That is the single most important thing to understand about this library.**
78
+
79
+ ## Three ways to spend, pick one
80
+
81
+ | Situation | Use | Prompts |
82
+ |---|---|---|
83
+ | You know the price | `require_approval(amount=...)` | one per call |
84
+ | A job whose total you don't know | `open_envelope(max_amount=...)` | one per job, then charges run inside it |
85
+ | Many calls, small amounts | auto-approve policy | none, until a ceiling is hit |
86
+
87
+ ### Envelope: when the total isn't known upfront
88
+
89
+ ```python
90
+ from spend_gate import open_envelope
91
+
92
+ with open_envelope(max_amount=10.0, vendor="openai",
93
+ purpose="nightly summarisation", ttl_hours=24) as env:
94
+ for doc in docs:
95
+ rid = env.reserve(0.50) # hold capacity first
96
+ cost = call_api(doc) # actual cost, known only afterwards
97
+ env.settle(rid, cost) # charge what it really cost
98
+ ```
99
+
100
+ One approval for "up to 10 CNY". Charges inside it do not prompt. It stops accepting charges when the cap or the 24 hours runs out. If you already know the price, `env.spend(0.05)` is the shortcut.
101
+
102
+ ### Ceilings: what a day, week or month may cost
103
+
104
+ ```bash
105
+ spend-gate policy set --daily-limit 20 --weekly-limit 80 --monthly-limit 200
106
+ ```
107
+
108
+ These apply to **all** spending, regardless of envelopes. Opening ten envelopes does not get around them.
109
+
110
+ When a charge would cross one, the dialog changes and tells you by how much:
111
+
112
+ ```
113
+ Budget limit reached
114
+ openai/gpt-4o requests 5.00 CNY for: batch job
115
+
116
+ This would exceed your daily limit:
117
+ daily: 18.00 + 5.00 = 23.00 > 20.00
118
+
119
+ [ Cancel ] [ Just this once ] [ Allow for this day ]
120
+ ```
121
+
122
+ "Allow for this day" writes a waiver until the period ends, so a long job keeps running instead of prompting at every file.
123
+
124
+ ### Per-vendor limits and whitelist
125
+
126
+ ```bash
127
+ spend-gate policy set --vendor dashscope --vendor-daily-limit 5 --vendor-trusted
128
+ ```
129
+
130
+ `--vendor` is a prefix; longest match wins, so `dashscope/wanx2.1-t2i` is covered by `dashscope`.
131
+
132
+ **Trusted** means: skip the dialog for this vendor *while it stays inside its own and the global ceilings*. It removes the interruption, not the limit. Exceed any ceiling and you are asked again.
133
+
134
+ ## What it does and does not protect
135
+
136
+ **Protects:** an agent or script running as you deciding to spend on its own. Both gates need a human action, and every attempt is recorded.
137
+
138
+ **Does not protect:** anyone who can edit this library (including an agent that can edit its own code), set `SPEND_GATE_BYPASS=1`, or obtain root. A call site you forgot to wrap is unprotected too.
139
+
140
+ This is a seatbelt, not a safe. Read [SECURITY.md](SECURITY.md) before trusting it with real money.
141
+
142
+ ## Every attempt is recorded
143
+
144
+ Two files under `~/.spend-gate/`:
145
+
146
+ - `audit.jsonl` — each approval decision: amount, vendor, purpose, method, result
147
+ - `ledger.jsonl` — each money movement, hash-chained. `spend-gate verify` detects edited or deleted rows and checks the head against a Keychain checkpoint.
148
+
149
+ ```bash
150
+ spend-gate verify # ledger chain + envelope reconciliation
151
+ spend-gate audit # recent decisions
152
+ ```
153
+
154
+ ## Commands
155
+
156
+ ```bash
157
+ spend-gate doctor # can this machine enforce approval?
158
+ spend-gate approve --amount 0.01 --vendor demo --purpose "smoke test"
159
+ spend-gate verify
160
+ spend-gate audit --tail 20
161
+ spend-gate policy show
162
+ spend-gate policy set --auto-under 0.05 --daily-limit 20
163
+ spend-gate policy set --vendor openai --vendor-daily-limit 20 --vendor-trusted
164
+ spend-gate policy load policy.json # batch, one fingerprint for all
165
+ ```
166
+
167
+ ## Environment variables
168
+
169
+ | Variable | Purpose |
170
+ |---|---|
171
+ | `SPEND_GATE_HOME` | Override `~/.spend-gate` |
172
+ | `SPEND_GATE_LEDGER_PATH` | Override the ledger path |
173
+ | `SPEND_GATE_AUDIT_PATH` | Override the audit path |
174
+ | `SPEND_GATE_NO_KEYCHAIN=1` | Run without a Keychain; anchor checks report as skipped |
175
+ | `SPEND_GATE_BYPASS=1` | **Skips both gates.** Tests only. Every use is logged as `bypassed`. |
176
+
177
+ ## Languages
178
+
179
+ Dialog, limit warning and Touch ID prompt follow the macOS UI language: English, Simplified Chinese, Traditional Chinese, Japanese, Korean, German, French, Spanish. Cantonese maps to Traditional Chinese; anything else falls back to English. Adding a language is a copy of `en.json` — a test fails if keys are missing.
180
+
181
+ ## Wrapping an existing codebase
182
+
183
+ The skill lives in [`skill/`](skill/) and ships with this repository — no separate install.
184
+
185
+ ```bash
186
+ python3 skill/scan_paid_calls.py /path/to/repo # what actually costs money
187
+ ```
188
+
189
+ Then point your agent at [`skill/SKILL.md`](skill/SKILL.md). It asks four questions, writes the policy, applies it in one authenticated call, and wraps the call sites. It also requires the agent to list what it did **not** wrap and why.
190
+
191
+ Why it is bundled rather than a separate repository: the skill depends on this CLI's flags, so the two must version together, and the files are small enough that a second repo would only add a way for them to drift.
192
+
193
+ ## License
194
+
195
+ Apache-2.0.
@@ -0,0 +1,168 @@
1
+ # agent-spend-gate
2
+
3
+ **Your AI agent is about to spend money. This makes it ask you first.**
4
+
5
+ > **Adopting this in an existing repo?** [`skill/`](skill/) scans for paid API calls, asks once which vendors should stay behind a prompt, and wraps the call sites. One fingerprint for the whole policy. [Read the case study](docs/CASE-STUDY.md) — 215 apparent call sites turned out to be 3 real ones.
6
+
7
+ One line before the paid call. A dialog says who gets paid and how much. Then macOS asks for your fingerprint or password. If either step fails, the call never happens.
8
+
9
+ ```
10
+ ┌─ Spending approval ─────────────────────┐
11
+ │ openai/gpt-4o requests 2.00 CNY for: │
12
+ │ summarise 10 documents │
13
+ │ Quantity: 10 calls │
14
+ │ │
15
+ │ [ Cancel ] [ Approve ] │
16
+ └─────────────────────────────────────────┘
17
+ ↓ you click Approve
18
+ ┌─ macOS ─────────────────────────────────┐
19
+ │ 🔒 Touch ID │
20
+ │ Approve spending 2.00 CNY to openai │
21
+ └─────────────────────────────────────────┘
22
+ ↓ fingerprint accepted
23
+ the API call runs
24
+ ```
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install agent-spend-gate
30
+ ```
31
+
32
+ macOS only, Python 3.11+. On any other platform the gate **refuses** — it does not silently skip the check.
33
+
34
+ ## The one thing you have to do
35
+
36
+ Put `require_approval` in front of every billable call.
37
+
38
+ ```python
39
+ from spend_gate import require_approval
40
+
41
+ require_approval(amount=2.0, currency="CNY",
42
+ vendor="openai/gpt-4o",
43
+ purpose="summarise 10 documents",
44
+ quantity="10 calls")
45
+
46
+ # Only reached after a human approved. Now spend.
47
+ client.chat.completions.create(...)
48
+ ```
49
+
50
+ If you do not wrap a call, that call is not protected. The gate is opt-in per call site — there is no interception layer, and nothing fails loudly when you miss one. **That is the single most important thing to understand about this library.**
51
+
52
+ ## Three ways to spend, pick one
53
+
54
+ | Situation | Use | Prompts |
55
+ |---|---|---|
56
+ | You know the price | `require_approval(amount=...)` | one per call |
57
+ | A job whose total you don't know | `open_envelope(max_amount=...)` | one per job, then charges run inside it |
58
+ | Many calls, small amounts | auto-approve policy | none, until a ceiling is hit |
59
+
60
+ ### Envelope: when the total isn't known upfront
61
+
62
+ ```python
63
+ from spend_gate import open_envelope
64
+
65
+ with open_envelope(max_amount=10.0, vendor="openai",
66
+ purpose="nightly summarisation", ttl_hours=24) as env:
67
+ for doc in docs:
68
+ rid = env.reserve(0.50) # hold capacity first
69
+ cost = call_api(doc) # actual cost, known only afterwards
70
+ env.settle(rid, cost) # charge what it really cost
71
+ ```
72
+
73
+ One approval for "up to 10 CNY". Charges inside it do not prompt. It stops accepting charges when the cap or the 24 hours runs out. If you already know the price, `env.spend(0.05)` is the shortcut.
74
+
75
+ ### Ceilings: what a day, week or month may cost
76
+
77
+ ```bash
78
+ spend-gate policy set --daily-limit 20 --weekly-limit 80 --monthly-limit 200
79
+ ```
80
+
81
+ These apply to **all** spending, regardless of envelopes. Opening ten envelopes does not get around them.
82
+
83
+ When a charge would cross one, the dialog changes and tells you by how much:
84
+
85
+ ```
86
+ Budget limit reached
87
+ openai/gpt-4o requests 5.00 CNY for: batch job
88
+
89
+ This would exceed your daily limit:
90
+ daily: 18.00 + 5.00 = 23.00 > 20.00
91
+
92
+ [ Cancel ] [ Just this once ] [ Allow for this day ]
93
+ ```
94
+
95
+ "Allow for this day" writes a waiver until the period ends, so a long job keeps running instead of prompting at every file.
96
+
97
+ ### Per-vendor limits and whitelist
98
+
99
+ ```bash
100
+ spend-gate policy set --vendor dashscope --vendor-daily-limit 5 --vendor-trusted
101
+ ```
102
+
103
+ `--vendor` is a prefix; longest match wins, so `dashscope/wanx2.1-t2i` is covered by `dashscope`.
104
+
105
+ **Trusted** means: skip the dialog for this vendor *while it stays inside its own and the global ceilings*. It removes the interruption, not the limit. Exceed any ceiling and you are asked again.
106
+
107
+ ## What it does and does not protect
108
+
109
+ **Protects:** an agent or script running as you deciding to spend on its own. Both gates need a human action, and every attempt is recorded.
110
+
111
+ **Does not protect:** anyone who can edit this library (including an agent that can edit its own code), set `SPEND_GATE_BYPASS=1`, or obtain root. A call site you forgot to wrap is unprotected too.
112
+
113
+ This is a seatbelt, not a safe. Read [SECURITY.md](SECURITY.md) before trusting it with real money.
114
+
115
+ ## Every attempt is recorded
116
+
117
+ Two files under `~/.spend-gate/`:
118
+
119
+ - `audit.jsonl` — each approval decision: amount, vendor, purpose, method, result
120
+ - `ledger.jsonl` — each money movement, hash-chained. `spend-gate verify` detects edited or deleted rows and checks the head against a Keychain checkpoint.
121
+
122
+ ```bash
123
+ spend-gate verify # ledger chain + envelope reconciliation
124
+ spend-gate audit # recent decisions
125
+ ```
126
+
127
+ ## Commands
128
+
129
+ ```bash
130
+ spend-gate doctor # can this machine enforce approval?
131
+ spend-gate approve --amount 0.01 --vendor demo --purpose "smoke test"
132
+ spend-gate verify
133
+ spend-gate audit --tail 20
134
+ spend-gate policy show
135
+ spend-gate policy set --auto-under 0.05 --daily-limit 20
136
+ spend-gate policy set --vendor openai --vendor-daily-limit 20 --vendor-trusted
137
+ spend-gate policy load policy.json # batch, one fingerprint for all
138
+ ```
139
+
140
+ ## Environment variables
141
+
142
+ | Variable | Purpose |
143
+ |---|---|
144
+ | `SPEND_GATE_HOME` | Override `~/.spend-gate` |
145
+ | `SPEND_GATE_LEDGER_PATH` | Override the ledger path |
146
+ | `SPEND_GATE_AUDIT_PATH` | Override the audit path |
147
+ | `SPEND_GATE_NO_KEYCHAIN=1` | Run without a Keychain; anchor checks report as skipped |
148
+ | `SPEND_GATE_BYPASS=1` | **Skips both gates.** Tests only. Every use is logged as `bypassed`. |
149
+
150
+ ## Languages
151
+
152
+ Dialog, limit warning and Touch ID prompt follow the macOS UI language: English, Simplified Chinese, Traditional Chinese, Japanese, Korean, German, French, Spanish. Cantonese maps to Traditional Chinese; anything else falls back to English. Adding a language is a copy of `en.json` — a test fails if keys are missing.
153
+
154
+ ## Wrapping an existing codebase
155
+
156
+ The skill lives in [`skill/`](skill/) and ships with this repository — no separate install.
157
+
158
+ ```bash
159
+ python3 skill/scan_paid_calls.py /path/to/repo # what actually costs money
160
+ ```
161
+
162
+ Then point your agent at [`skill/SKILL.md`](skill/SKILL.md). It asks four questions, writes the policy, applies it in one authenticated call, and wraps the call sites. It also requires the agent to list what it did **not** wrap and why.
163
+
164
+ Why it is bundled rather than a separate repository: the skill depends on this CLI's flags, so the two must version together, and the files are small enough that a second repo would only add a way for them to drift.
165
+
166
+ ## License
167
+
168
+ Apache-2.0.