@sakk-dev/sakk 0.0.0 → 0.4.0

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,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,82 @@
1
+ Sakk
2
+ Copyright 2026 The Sakk authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see
5
+ LICENSE).
6
+
7
+ Third-party material
8
+ ====================
9
+
10
+ The package also ships material derived from the following MIT-licensed
11
+ projects. The MIT license
12
+ requires that its copyright and permission notice be included in all copies
13
+ or substantial portions of the material; this file carries those notices.
14
+
15
+ 1. gitleaks — secret-detection rules
16
+ ------------------------------------
17
+
18
+ src/secret-rules.generated.mjs is generated from the gitleaks rule set
19
+ (config/gitleaks.toml), tag v8.21.2, commit
20
+ a9e1950fe247fbb08817393121691474c55a6cfa: 194 of 195 rules ported, 192
21
+ enabled. Source: https://github.com/gitleaks/gitleaks
22
+
23
+ MIT License
24
+
25
+ Copyright (c) 2019 Zachary Rice
26
+
27
+ Permission is hereby granted, free of charge, to any person obtaining a
28
+ copy of this software and associated documentation files (the
29
+ "Software"), to deal in the Software without restriction, including
30
+ without limitation the rights to use, copy, modify, merge, publish,
31
+ distribute, sublicense, and/or sell copies of the Software, and to
32
+ permit persons to whom the Software is furnished to do so, subject to
33
+ the following conditions:
34
+
35
+ The above copyright notice and this permission notice shall be included
36
+ in all copies or substantial portions of the Software.
37
+
38
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
39
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
40
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
41
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
42
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
43
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
44
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
45
+
46
+ 2. LiteLLM — model price table
47
+ ------------------------------
48
+
49
+ prices/snapshot.json is a trimmed snapshot of LiteLLM's
50
+ model_prices_and_context_window.json (the snapshot records the exact source
51
+ URL, fetch time and upstream sha-256).
52
+ Source: https://github.com/BerriAI/litellm
53
+
54
+ MIT License
55
+
56
+ Copyright (c) 2023 Berri AI
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a
59
+ copy of this software and associated documentation files (the
60
+ "Software"), to deal in the Software without restriction, including
61
+ without limitation the rights to use, copy, modify, merge, publish,
62
+ distribute, sublicense, and/or sell copies of the Software, and to
63
+ permit persons to whom the Software is furnished to do so, subject to
64
+ the following conditions:
65
+
66
+ The above copyright notice and this permission notice shall be included
67
+ in all copies or substantial portions of the Software.
68
+
69
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
70
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
71
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
72
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
73
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
74
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
75
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
76
+
77
+ 3. cc-safety-net — acknowledgment
78
+ ---------------------------------
79
+
80
+ The guard's shell tokenizer and wrapper-unwrapping approach was studied
81
+ from cc-safety-net (MIT). No code was copied (specs/guard/decide.md); this
82
+ acknowledgment records the influence.
@@ -0,0 +1,366 @@
1
+ # Sakk spend gate for the LiteLLM proxy
2
+
3
+ Put the [LiteLLM proxy](https://docs.litellm.ai/docs/simple_proxy) between
4
+ your application and the model providers, load `sakk_gateway.py` as a
5
+ callback, and every chat call reserves its worst-case cost with Sakk before
6
+ the provider is called and settles the real cost afterwards. When the
7
+ reservation would pass the cap, the provider is never called and the client
8
+ gets HTTP 402.
9
+
10
+ If Sakk itself cannot answer, the gateway lets calls through by default,
11
+ unmetered and loudly, so a Sakk outage does not take your service down. See
12
+ [When Sakk cannot answer](#when-sakk-cannot-answer).
13
+
14
+ The proxy speaks the OpenAI chat completions API, so any language that can
15
+ send an HTTP request works: Python, Node, Java, PHP, Go, curl. The client
16
+ changes two things, the base URL and the key.
17
+
18
+ ## Why LiteLLM
19
+
20
+ We picked an existing gateway and wrote only the hook:
21
+
22
+ - **LiteLLM proxy** (MIT licence). It is OpenAI compatible,
23
+ it reaches every provider a production content app uses, and its
24
+ [custom callback](https://docs.litellm.ai/docs/proxy/call_hooks) can
25
+ refuse a call before the provider sees it. This is the one we use.
26
+ - **Portkey gateway**, open source. Budgets and guardrail hooks are in the
27
+ hosted or paid tiers, so we did not use it.
28
+ - **Bifrost**. Custom logic needs Go plugins built against the gateway, so we
29
+ did not use it.
30
+
31
+ ## Install (pinned)
32
+
33
+ LiteLLM's PyPI releases have been compromised twice: 1.82.7 and 1.82.8 in
34
+ March 2026 ([LiteLLM's security update](https://docs.litellm.ai/blog/security-update-march-2026)),
35
+ and 1.107.0 on 2026-10-21
36
+ ([StepSecurity](https://www.stepsecurity.io/blog/litellm-1-107-0-compromised-pypi-backdoored-wheels-credential-stealer),
37
+ [Cloudsmith](https://cloudsmith.com/blog/litellm-1-107-0-compromised-on-pypi)).
38
+ Install only the pinned version, from the hash lock committed next to this
39
+ file, the same way CI does:
40
+
41
+ ```bash
42
+ uv venv --python 3.12 .venv
43
+ uv pip install --python .venv/bin/python --require-hashes --no-build -r integrations/litellm/requirements.lock
44
+ ```
45
+
46
+ The lock's input is `integrations/litellm/requirements.in`, one line,
47
+ `litellm[proxy]==1.106.2`, with the command that regenerates the lock in its
48
+ comments. Version 1.106.2 was published before the October release. The lock
49
+ comes to 117 packages, about 472 MB. Do not move to a newer version until
50
+ LiteLLM's advisory names it safe.
51
+
52
+ Installed Sakk from npm? The lock is not in the npm package, so make the
53
+ same kind of lock from the same one-line input. These are the steps
54
+ `sakk gateway init` prints when it finds no `litellm`; the cut-off date
55
+ keeps out every release published after 2026-10-21 11:00 UTC, 1.107.0
56
+ included:
57
+
58
+ ```bash
59
+ printf 'litellm[proxy]==1.106.2\n' > req.in
60
+ uv venv --python 3.12 .venv
61
+ uv pip compile req.in --generate-hashes --exclude-newer 2026-10-21T11:00:00Z -o req.lock
62
+ uv pip install --require-hashes -r req.lock
63
+ ```
64
+
65
+ ## Run
66
+
67
+ ```bash
68
+ cp config.example.yaml config.yaml # next to sakk_gateway.py
69
+ sakk init --cap 5 --ledger /abs/path/ledger.json --by you
70
+ export SAKK_BIN=/abs/path/to/sakk/bin/sakk.mjs
71
+ export SAKK_LEDGER=/abs/path/ledger.json
72
+ export SAKK_GATEWAY_CONFIG=$PWD/config.yaml
73
+ export LITELLM_MASTER_KEY=sk-choose-a-long-random-key
74
+ export LITELLM_LOCAL_MODEL_COST_MAP=True # no cost-map fetch at start
75
+ export DEEPSEEK_API_KEY=... # provider keys live here only
76
+ .venv/bin/litellm --config config.yaml --host 127.0.0.1 --port 4000
77
+ ```
78
+
79
+ The gateway does not start without `SAKK_BIN`, `SAKK_LEDGER` and
80
+ `SAKK_GATEWAY_CONFIG`, or with a `SAKK_ON_UNAVAILABLE` other than `allow` or
81
+ `deny`, or a `SAKK_TIMEOUT_S` or `SAKK_RESERVATION_TTL_S` that is not a
82
+ positive number, or a `SAKK_BREAKER_S` that is negative or not a number.
83
+ Optional settings:
84
+
85
+ | Variable | Default | Meaning |
86
+ | ------------------------- | ---------------------------- | ----------------------------------------------------------------------------------- |
87
+ | `SAKK_NODE` | `node` | Node executable that runs Sakk |
88
+ | `SAKK_DEFAULT_MAX_TOKENS` | 2048 | `max_tokens` added when a request has none |
89
+ | `SAKK_TIMEOUT_S` | 5 | How long one ledger call may take, reserve or settle |
90
+ | `SAKK_BREAKER_S` | 10 | After a reserve outage, how long reserves skip the ledger; 0 turns it off |
91
+ | `SAKK_RESERVATION_TTL_S` | 3600 | Age at which the gateway settles its own unsettled reservations at their worst case |
92
+ | `SAKK_LATE_SETTLE_S` | 2 | Wait before charging the worst case on errors |
93
+ | `SAKK_ON_UNAVAILABLE` | `allow` | `allow` or `deny` a call when Sakk cannot answer |
94
+ | `SAKK_GATEWAY_STATUS` | `<SAKK_LEDGER>.gateway.json` | Where the gateway records outages |
95
+ | `SAKK_GATEWAY_URL` | `http://127.0.0.1:4000` | Read by the console, which checks the gateway is up |
96
+
97
+ ### Prices
98
+
99
+ Prices are USD per token in `config.yaml`, under each model's
100
+ `litellm_params`, as `input_cost_per_token` and `output_cost_per_token`.
101
+ **Write them as decimals** (`0.00000028`). PyYAML reads `1e-06` as a string,
102
+ so a price written that way counts as missing and the model is refused. The
103
+ gateway logs the priced models when it starts; check that list.
104
+
105
+ ## Clients
106
+
107
+ Point the client at `http://127.0.0.1:4000/v1` and send the gateway key.
108
+ Keep the provider keys out of the application.
109
+
110
+ Python (OpenAI SDK):
111
+
112
+ ```python
113
+ from openai import OpenAI
114
+ client = OpenAI(base_url="http://127.0.0.1:4000/v1", api_key=GATEWAY_KEY)
115
+ r = client.chat.completions.create(model="deepseek-chat", max_tokens=512,
116
+ messages=[{"role": "user", "content": "hi"}])
117
+ ```
118
+
119
+ curl:
120
+
121
+ ```bash
122
+ curl -s http://127.0.0.1:4000/v1/chat/completions \
123
+ -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" \
124
+ -d '{"model":"deepseek-chat","max_tokens":512,"messages":[{"role":"user","content":"hi"}]}'
125
+ ```
126
+
127
+ Java (JDK 11+, no SDK):
128
+
129
+ ```java
130
+ var body = """
131
+ {"model":"deepseek-chat","max_tokens":512,
132
+ "messages":[{"role":"user","content":"hi"}]}""";
133
+ var req = java.net.http.HttpRequest.newBuilder(
134
+ java.net.URI.create("http://127.0.0.1:4000/v1/chat/completions"))
135
+ .header("Authorization", "Bearer " + gatewayKey)
136
+ .header("Content-Type", "application/json")
137
+ .POST(java.net.http.HttpRequest.BodyPublishers.ofString(body)).build();
138
+ var res = java.net.http.HttpClient.newHttpClient()
139
+ .send(req, java.net.http.HttpResponse.BodyHandlers.ofString());
140
+ if (res.statusCode() == 402) { /* over the cap: no call was made */ }
141
+ ```
142
+
143
+ PHP (curl extension):
144
+
145
+ ```php
146
+ $ch = curl_init('http://127.0.0.1:4000/v1/chat/completions');
147
+ curl_setopt_array($ch, [
148
+ CURLOPT_POST => true,
149
+ CURLOPT_RETURNTRANSFER => true,
150
+ CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $gatewayKey, 'Content-Type: application/json'],
151
+ CURLOPT_POSTFIELDS => json_encode(['model' => 'deepseek-chat', 'max_tokens' => 512,
152
+ 'messages' => [['role' => 'user', 'content' => 'hi']]]),
153
+ ]);
154
+ $body = curl_exec($ch);
155
+ $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 402: over the cap
156
+ ```
157
+
158
+ The tests run the Python SDK and a plain HTTP client with no SDK. The Java
159
+ and PHP snippets send the same request but were not run here, because
160
+ neither runtime is installed on the test machine.
161
+
162
+ Provider fields outside the OpenAI spec pass through. For example, MiniMax's
163
+ `reasoning_split` sent in `extra_body` reaches MiniMax.
164
+
165
+ ## How a call is charged
166
+
167
+ 1. **Before the call**, the gateway takes the request's prompt fields and
168
+ `max_tokens` and works out the most the call can cost:
169
+ `(prompt bytes + 512) × input price + (max_tokens + 64) × n × output price`.
170
+ Prompt bytes are an upper bound on tokens. If the request has no
171
+ `max_tokens`, the gateway adds one. It reserves that amount with Sakk. A
172
+ refusal means the provider is not called.
173
+ 2. **After a success**, it settles the provider's reported usage at the
174
+ configured prices. A stream is made to report usage in its last chunk.
175
+ If no usage comes back, it settles the worst case.
176
+ 3. **After a provider error** (4xx or 5xx, not a timeout) on a request that
177
+ was not streaming, it settles zero, because the provider answered without
178
+ generating. On a timeout, a dropped connection or a failed stream, it
179
+ settles the worst case, because the provider may have run the call.
180
+ 4. If the reported cost is above the reservation, Sakk halts the ledger and
181
+ refuses every later call until a person runs `sakk reconcile`.
182
+
183
+ Retries are off in the example config, so one reservation covers one
184
+ provider request.
185
+
186
+ ## When Sakk cannot answer
187
+
188
+ Sakk cannot answer when its process will not start, crashes, closes its
189
+ pipe, takes longer than `SAKK_TIMEOUT_S` (5 seconds by default), or replies
190
+ with something that is not a valid answer. A process that died since the last
191
+ call is started again within the next call, and the request goes to the new
192
+ one only if it never reached the old one (the pipe was already closed). If
193
+ the new one answers, that call is metered as usual. A request that was
194
+ written and then got no reply is not sent again: the first reservation may
195
+ have landed, and Sakk would refuse the same call id twice. That call counts
196
+ as an outage, and the reservation, if it landed, is held until it expires
197
+ (below).
198
+
199
+ After a reserve that Sakk did not answer, the gateway stops asking for
200
+ `SAKK_BREAKER_S` (10 seconds by default): reserves in that window, including
201
+ calls already queued behind the failing one, take the outage path at once
202
+ instead of each waiting out its own timeout. They are still counted, logged
203
+ and shown like any other outage call, with a reason that starts with
204
+ `breaker open`. Settles are never held back by it. Set `SAKK_BREAKER_S=0` to
205
+ ask Sakk on every call.
206
+
207
+ With the default, `SAKK_ON_UNAVAILABLE=allow`, the gateway then sends the
208
+ call to the provider anyway, and says so:
209
+
210
+ - one WARNING log line per call, in JSON, with `"event": "sakk_unavailable_allowed"`,
211
+ the model, the call's worst-case price (`est_max_usd`), the reason, when the
212
+ outage began (`outage_since`) and how many calls it has let through
213
+ (`allowed_calls`);
214
+ - the response header `x-sakk-status: unmetered`, on plain and streamed
215
+ responses;
216
+ - an outage record in the status file (below). `sakk status` prints it,
217
+ `sakk status --json` returns it under `gateway`, and the console shows a red
218
+ banner on every page while the outage lasts.
219
+
220
+ The first reservation Sakk answers again ends the outage. The record moves to
221
+ `last_outage`, the gateway logs a `sakk_outage_ended` line, and the console
222
+ shows a yellow note instead of the red banner.
223
+
224
+ **Calls let through during an outage are not recorded in the ledger and are
225
+ not capped.** `est_max_unrecorded_usd` is the sum of their worst-case prices:
226
+ an upper bound, not a spend. Check the provider's bill for that window. If no
227
+ call may ever go out unmetered, set `SAKK_ON_UNAVAILABLE=deny`. Those calls
228
+ then get 503 `SAKK_UNAVAILABLE` and the provider is not called; the outage is
229
+ still recorded, with `allowed_calls` at 0.
230
+
231
+ A refusal from Sakk is an answer, not an outage, and stays a refusal in both
232
+ modes: 402 over the cap, halted, or reconciliation required, and any other
233
+ code Sakk returns within `SAKK_TIMEOUT_S`. A refusal also ends an open outage,
234
+ the same as a reservation.
235
+
236
+ A ledger file lock that another process holds is the one case that depends
237
+ on timing. Sakk waits about 2 seconds for the lock, then answers
238
+ `LEDGER_LOCK_UNAVAILABLE`. If that answer arrives within `SAKK_TIMEOUT_S`, it
239
+ is a 402 like any other refusal. A lock held longer than the timeout means
240
+ Sakk has not answered in time, and that counts as Sakk cannot answer, the way
241
+ Envoy's `ext_authz` filter treats an authorization service that is too slow:
242
+ the call is let through, recorded and shown red, or gets 503 in deny mode.
243
+ The default 5-second timeout leaves room for Sakk's own 2-second wait, so a
244
+ busy but healthy ledger shows up as a 402 `LEDGER_LOCK_UNAVAILABLE`, not as
245
+ an outage (F-243; with the earlier 2-second default the gateway usually
246
+ stopped waiting first).
247
+
248
+ ## Reservations nobody settled
249
+
250
+ A reservation whose settle never arrives (the proxy restarted mid-call, the
251
+ ledger refused or missed the settle twice) would stay outstanding for good.
252
+ Its worst case counts against the cap either way, but it also holds one of
253
+ the ledger's 10,000 outstanding slots (`LEDGER_FULL`) and keeps the books
254
+ from sealing. Once one of the gateway's own reservations (agent
255
+ `litellm-gateway`) is older than `SAKK_RESERVATION_TTL_S` (an hour by
256
+ default), a sweep in the background settles it at the worst case it
257
+ reserved and logs a WARNING JSON line with `"event": "sakk_reservation_expired"`,
258
+ the `callId`, `settled_usd`, `created_at` and `ttl_s` (F-242). The next call
259
+ starts the sweep, at most once a minute and 50 settles per run. Set the TTL
260
+ longer than your slowest call: a call still running when it expires is
261
+ booked at its worst case and its own settle is dropped. With several gateways
262
+ on one ledger, one may expire another's long call; that call's settle then
263
+ gets `SETTLE_MISMATCH` and an alert.
264
+
265
+ To release one reservation sooner, a person runs
266
+
267
+ ```bash
268
+ sakk settle <callId> --by <name> --ledger <path>
269
+ ```
270
+
271
+ at a terminal and types `settle` to confirm. It books the reserved amount and
272
+ writes a `SETTLED_AT_RESERVED` line to the alerts file naming who did it. An
273
+ agent cannot run it: without a terminal it exits 2 with
274
+ `HUMAN_CONFIRMATION_REQUIRED`, and the guard hook denies it.
275
+
276
+ The gateway's own 403 and 400 refusals do not depend on Sakk at all.
277
+
278
+ ### Status file
279
+
280
+ The path is `SAKK_GATEWAY_STATUS`, or the ledger path with `.gateway.json`
281
+ added, after the ledger's folder is resolved to its real path (a relative
282
+ path or a linked folder names the same file). `sakk status` and the console
283
+ use the same rule, so if you set
284
+ `SAKK_GATEWAY_STATUS` for the gateway, set it for them too. The file is
285
+ written whole each time (temporary file, fsync, rename) with mode 0600. A
286
+ write that fails is logged at ERROR and the call goes on.
287
+
288
+ ```json
289
+ {
290
+ "version": 1,
291
+ "updatedAt": "2026-11-02T06:10:00.000Z",
292
+ "mode": "allow",
293
+ "outage": {
294
+ "since": "2026-11-02T06:02:11.408Z",
295
+ "allowed_calls": 3,
296
+ "est_max_unrecorded_usd": 0.004213,
297
+ "last_reason": "sakk_reserve: TimeoutError: ",
298
+ "last_at": "2026-11-02T06:09:58.120Z"
299
+ },
300
+ "last_outage": null
301
+ }
302
+ ```
303
+
304
+ `outage` is null while Sakk answers. `last_outage` is the most recent outage
305
+ that ended, with the same fields plus `ended_at`. An outage still open when
306
+ the gateway restarts keeps counting.
307
+
308
+ When the status file exists, the console also checks the gateway: it asks
309
+ `SAKK_GATEWAY_URL` for `/health/liveliness`, waits at most 500 ms, reuses the
310
+ answer for 5 seconds, and shows a red "Gateway not answering at <url>"
311
+ banner when the check fails.
312
+
313
+ ## Refusals
314
+
315
+ | HTTP | Code | Meaning |
316
+ | ---- | ------------------------- | ----------------------------------------------------------------- |
317
+ | 402 | `BUDGET_EXCEEDED` | The worst case would pass the cap; the provider was not called |
318
+ | 402 | `RECONCILIATION_REQUIRED` | An earlier call cost more than its reservation; a person must act |
319
+ | 402 | other Sakk codes | The ledger refused, for example while halted |
320
+ | 403 | `SAKK_NO_PRICE` | The model has no price in the config, or is a wildcard |
321
+ | 403 | `SAKK_UNMETERED` | A route other than chat, or a non-text message part (image/audio) |
322
+ | 400 | `SAKK_BAD_REQUEST` | `max_tokens` or `n` is not a positive integer |
323
+ | 503 | `SAKK_UNAVAILABLE` | Deny mode only: Sakk cannot answer; no call was made |
324
+
325
+ The Sakk code is in the error body, at
326
+ `error.provider_specific_fields.error.code`.
327
+
328
+ ## Limits
329
+
330
+ - **An outage lets calls through unmetered by default.** They are not in the
331
+ ledger and not capped; only the status file and the log count them. Use
332
+ `SAKK_ON_UNAVAILABLE=deny` if that is not acceptable.
333
+ - **One gateway process per ledger.** The status file is guarded by a lock
334
+ inside the process, so several LiteLLM workers would overwrite each other's
335
+ outage counts.
336
+ - **Outage records are written on the event loop.** Each call that opens,
337
+ counts or ends an outage takes that lock and fsyncs the status file on the
338
+ event-loop thread, so a slow disk delays every call in the worker meanwhile.
339
+ A metered call with no outage open writes nothing.
340
+ - **Waiting calls queue.** Calls to Sakk go one at a time. The first reserve
341
+ that hangs waits out `SAKK_TIMEOUT_S`; the breaker then sends the ones
342
+ queued behind it on at once. Settles queue behind a hung call too.
343
+ - **A reservation that timed out may still land.** If Sakk wrote it after the
344
+ gateway gave up, it stays reserved and counts against the cap until it
345
+ expires after `SAKK_RESERVATION_TTL_S` or a person runs `sakk settle`, and
346
+ is then booked at its worst case. That over-counts; it never under-counts.
347
+ - **Calls let through in an outage are not booked afterwards.** The status
348
+ file's `allowed_calls` and `est_max_unrecorded_usd` are their only record;
349
+ writing them to a side file and booking them once Sakk answers is planned.
350
+ - **A direct call bypasses the gateway.** An application holding a real
351
+ provider key can call the provider directly, and Sakk never sees it. Give
352
+ applications only the gateway key.
353
+ - **Only chat completions are metered.** Embeddings, images, audio, the
354
+ responses API, Anthropic's `/v1/messages` route and pass-through routes are
355
+ refused, not let through. An Anthropic-SDK client must switch to the
356
+ OpenAI-format route.
357
+ - **Paid calls that do not go through LiteLLM are not covered**, for example
358
+ a search API the application calls itself.
359
+ - **Cached-input discounts are not applied.** Input is charged at the full
360
+ price, so the ledger can read slightly higher than the provider's bill.
361
+ - **The Python tests run in CI but are not a required check.** The `gateway`
362
+ job runs them on every pull request; adding it to main's required checks is
363
+ the owner's call, so read its result before merging. Run them locally:
364
+ `.venv/bin/python -m unittest integrations/litellm/test_sakk_gateway.py -v`.
365
+ They use a local mock provider and a temporary ledger, so they cost
366
+ nothing and do not touch `~/.sakk`.