@tokenzero/cli 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -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,903 @@
1
+ #!/usr/bin/env node
2
+ // TokenZero CLI (generated by cli/build.mjs; do not edit)
3
+
4
+ // cli/src/main.ts
5
+ import fs2 from "node:fs";
6
+ import path2 from "node:path";
7
+ import crypto2 from "node:crypto";
8
+ import readline from "node:readline/promises";
9
+
10
+ // src/audit-core.ts
11
+ import crypto from "node:crypto";
12
+
13
+ // src/pricing.ts
14
+ var P = (provider, tier, input, output, cachedInput, cacheWrite, extra = {}) => ({ provider, tier, input, output, cachedInput, cacheWrite, ...extra });
15
+ var PRICES = {
16
+ // ---- OpenAI (standard tier, ≤272K; cache write = 30m TTL rate) ----
17
+ "gpt-6-astra": P("openai", "frontier", 10, 50, 1, 12.5, { longCtxAt: 272e3, longCtx: { input: 20, output: 75, cachedInput: 2, cacheWrite: 25 }, minCacheTokens: 1024 }),
18
+ "gpt-6.1-sol": P("openai", "mid", 2, 10, 0.1, 2.5, { longCtxAt: 272e3, longCtx: { input: 4, output: 15, cachedInput: 0.2, cacheWrite: 5 }, minCacheTokens: 1024 }),
19
+ "gpt-6-sol": P("openai", "mid", 2, 10, 0.2, 2.5, { longCtxAt: 272e3, longCtx: { input: 4, output: 15, cachedInput: 0.4, cacheWrite: 5 }, minCacheTokens: 1024 }),
20
+ "gpt-6-luna": P("openai", "fast", 0.1, 0.5, 0.01, 0.125, { longCtxAt: 272e3, longCtx: { input: 0.2, output: 0.75, cachedInput: 0.02, cacheWrite: 0.25 }, minCacheTokens: 1024 }),
21
+ "gpt-5.6-sol": P("openai", "frontier", 4, 20, 0.4, 5, { longCtxAt: 272e3, longCtx: { input: 8, output: 30, cachedInput: 0.8, cacheWrite: 10 }, minCacheTokens: 1024 }),
22
+ "gpt-5.6-terra": P("openai", "mid", 2, 12, 0.2, 2.5, { longCtxAt: 272e3, longCtx: { input: 4, output: 18, cachedInput: 0.4, cacheWrite: 5 }, minCacheTokens: 1024 }),
23
+ "gpt-5.6-luna": P("openai", "fast", 0.2, 1.2, 0.02, 0.25, { longCtxAt: 272e3, longCtx: { input: 0.4, output: 1.8, cachedInput: 0.04, cacheWrite: 0.5 }, minCacheTokens: 1024 }),
24
+ "gpt-5.5": P("openai", "frontier", 5, 30, 0.5, void 0, { longCtxAt: 272e3, longCtx: { input: 10, output: 45, cachedInput: 1 }, minCacheTokens: 1024 }),
25
+ "gpt-5.5-pro": P("openai", "frontier", 30, 180),
26
+ "gpt-5.4": P("openai", "frontier", 2.5, 15, 0.25, void 0, { longCtxAt: 272e3, longCtx: { input: 5, output: 22.5, cachedInput: 0.5 }, minCacheTokens: 1024 }),
27
+ "gpt-5.4-pro": P("openai", "frontier", 30, 180),
28
+ "gpt-5.4-mini": P("openai", "fast", 0.75, 4.5, 0.075, void 0, { minCacheTokens: 1024 }),
29
+ "gpt-5.4-nano": P("openai", "fast", 0.2, 1.25, 0.02, void 0, { minCacheTokens: 1024 }),
30
+ "gpt-5.2": P("openai", "frontier", 1.75, 14, 0.175, void 0, { minCacheTokens: 1024 }),
31
+ "gpt-5.2-pro": P("openai", "frontier", 21, 168),
32
+ "gpt-5.1": P("openai", "mid", 1.25, 10, 0.125, void 0, { minCacheTokens: 1024 }),
33
+ "gpt-5": P("openai", "mid", 1.25, 10, 0.125, void 0, { minCacheTokens: 1024 }),
34
+ "gpt-5-mini": P("openai", "fast", 0.25, 2, 0.025, void 0, { minCacheTokens: 1024 }),
35
+ "gpt-5-nano": P("openai", "fast", 0.05, 0.4, 5e-3, void 0, { minCacheTokens: 1024 }),
36
+ "gpt-5-pro": P("openai", "frontier", 15, 120),
37
+ "o3": P("openai", "mid", 2, 8, 0.5, void 0, { minCacheTokens: 1024 }),
38
+ "o3-pro": P("openai", "frontier", 20, 80),
39
+ "o3-mini": P("openai", "fast", 1.1, 4.4, 0.55, void 0, { minCacheTokens: 1024 }),
40
+ "o4-mini": P("openai", "fast", 1.1, 4.4, 0.275, void 0, { minCacheTokens: 1024 }),
41
+ "o1": P("openai", "frontier", 15, 60, 7.5),
42
+ "gpt-4.1": P("openai", "mid", 2, 8, 0.5, void 0, { minCacheTokens: 1024 }),
43
+ "gpt-4.1-mini": P("openai", "fast", 0.4, 1.6, 0.1, void 0, { minCacheTokens: 1024 }),
44
+ "gpt-4.1-nano": P("openai", "fast", 0.1, 0.4, 0.025, void 0, { minCacheTokens: 1024 }),
45
+ "gpt-4o": P("openai", "mid", 2.5, 10, 1.25, void 0, { minCacheTokens: 1024 }),
46
+ "gpt-4o-mini": P("openai", "fast", 0.15, 0.6, 0.075, void 0, { minCacheTokens: 1024 }),
47
+ // ---- Anthropic (cache write = 5-minute TTL, 1.25x; 1h TTL is 2x) ----
48
+ "claude-fable-5-1": P("anthropic", "frontier", 10, 50, 0.25, 12.5, { minCacheTokens: 512 }),
49
+ "claude-fable-5": P("anthropic", "frontier", 10, 50, 1, 12.5, { minCacheTokens: 512 }),
50
+ "claude-opus-5-5": P("anthropic", "frontier", 4, 20, 0.2, 5, { minCacheTokens: 512 }),
51
+ "claude-opus-5": P("anthropic", "frontier", 5, 25, 0.5, 6.25, { minCacheTokens: 512 }),
52
+ "claude-opus-4-8": P("anthropic", "frontier", 5, 25, 0.5, 6.25, { minCacheTokens: 1024 }),
53
+ "claude-opus-4-7": P("anthropic", "frontier", 5, 25, 0.5, 6.25, { minCacheTokens: 2048 }),
54
+ "claude-opus-4-6": P("anthropic", "frontier", 5, 25, 0.5, 6.25, { minCacheTokens: 4096 }),
55
+ "claude-opus-4-5": P("anthropic", "frontier", 5, 25, 0.5, 6.25, { minCacheTokens: 4096 }),
56
+ "claude-sonnet-5-5": P("anthropic", "mid", 2, 10, 0.2, 2.5, { minCacheTokens: 512 }),
57
+ "claude-sonnet-5": P("anthropic", "mid", 2, 10, 0.2, 2.5, { minCacheTokens: 1024 }),
58
+ "claude-sonnet-4-6": P("anthropic", "mid", 3, 15, 0.3, 3.75, { minCacheTokens: 1024 }),
59
+ "claude-sonnet-4-5": P("anthropic", "mid", 3, 15, 0.3, 3.75, { minCacheTokens: 1024 }),
60
+ "claude-haiku-5-5": P("anthropic", "fast", 0.1, 0.5, 0.01, 0.125, { minCacheTokens: 512, longCtxAt: 1e5, longCtx: { input: 0.5, output: 2.5, cachedInput: 0.05, cacheWrite: 0.625 } }),
61
+ "claude-haiku-4-5": P("anthropic", "fast", 1, 5, 0.1, 1.25, { minCacheTokens: 4096 }),
62
+ // ---- Google Gemini (paid tier; prices scheduled to rise Dec 2026/Jan 2027 — re-verify) ----
63
+ "gemini-4-argon": P("gemini", "frontier", 2, 10, 0.1),
64
+ "gemini-3.8-flash": P("gemini", "fast", 0.75, 3.75, 0.075),
65
+ "gemini-3.6-flash": P("gemini", "fast", 0.75, 3.75, 0.075),
66
+ "gemini-3.5-flash-lite": P("gemini", "fast", 0.3, 2.5, 0.03),
67
+ "gemini-3.1-pro": P("gemini", "frontier", 2, 12, 0.2, void 0, { longCtxAt: 2e5, longCtx: { input: 4, output: 18, cachedInput: 0.4 } }),
68
+ "gemini-3.1-flash-lite": P("gemini", "fast", 0.25, 1.5, 0.025),
69
+ "gemini-3-flash": P("gemini", "fast", 0.5, 3, 0.05),
70
+ "gemini-2.5-pro": P("gemini", "frontier", 1.25, 10, 0.125, void 0, { longCtxAt: 2e5, longCtx: { input: 2.5, output: 15, cachedInput: 0.25 } }),
71
+ "gemini-2.5-flash": P("gemini", "fast", 0.3, 2.5, 0.03),
72
+ "gemini-2.5-flash-lite": P("gemini", "fast", 0.1, 0.4, 0.01)
73
+ };
74
+ var CASCADE_TARGET = {
75
+ "gpt-6-astra": "gpt-6.1-sol",
76
+ "gpt-6.1-sol": "gpt-6-luna",
77
+ "gpt-6-sol": "gpt-6-luna",
78
+ "gpt-5.6-sol": "gpt-5.6-terra",
79
+ "gpt-5.6-terra": "gpt-5.6-luna",
80
+ "gpt-5.5": "gpt-5.4-mini",
81
+ "gpt-5.4": "gpt-5.4-mini",
82
+ "gpt-5.2": "gpt-5-mini",
83
+ "gpt-5.1": "gpt-5-mini",
84
+ "gpt-5": "gpt-5-mini",
85
+ "gpt-4.1": "gpt-4.1-mini",
86
+ "gpt-4o": "gpt-4o-mini",
87
+ "o3": "o4-mini",
88
+ "claude-fable-5-1": "claude-opus-5-5",
89
+ "claude-fable-5": "claude-opus-5-5",
90
+ "claude-opus-5-5": "claude-sonnet-5-5",
91
+ "claude-opus-5": "claude-sonnet-5-5",
92
+ "claude-opus-4-8": "claude-sonnet-5-5",
93
+ "claude-opus-4-7": "claude-sonnet-5-5",
94
+ "claude-opus-4-6": "claude-sonnet-4-6",
95
+ "claude-sonnet-5-5": "claude-haiku-5-5",
96
+ "claude-sonnet-5": "claude-haiku-5-5",
97
+ "claude-sonnet-4-6": "claude-haiku-4-5",
98
+ "claude-sonnet-4-5": "claude-haiku-4-5",
99
+ "gemini-4-argon": "gemini-3.8-flash",
100
+ "gemini-3.1-pro": "gemini-3.8-flash",
101
+ "gemini-3.8-flash": "gemini-3.5-flash-lite",
102
+ "gemini-2.5-pro": "gemini-2.5-flash",
103
+ "gemini-2.5-flash": "gemini-2.5-flash-lite"
104
+ };
105
+ var KEYS_BY_LENGTH = Object.keys(PRICES).sort((a, b) => b.length - a.length);
106
+ function normalizeModel(model) {
107
+ if (typeof model !== "string" || !model) return null;
108
+ let m = model.toLowerCase().trim();
109
+ m = m.replace(/^(openai|anthropic|google|models|vertex_ai)\//, "");
110
+ m = m.replace(/@\d{8}$/, "");
111
+ m = m.replace(/-(\d{8}|\d{4}-\d{2}-\d{2})$/, "");
112
+ m = m.replace(/-(latest|preview|customtools|thinking)$/, "");
113
+ if (PRICES[m]) return m;
114
+ for (const k of KEYS_BY_LENGTH) if (m.startsWith(k + "-") || m === k) return k;
115
+ return null;
116
+ }
117
+ function priceFor(model) {
118
+ const key = normalizeModel(model);
119
+ return key ? { key, ...PRICES[key] } : null;
120
+ }
121
+ function costOf(model, u) {
122
+ const p = priceFor(model);
123
+ if (!p) return null;
124
+ const tier = p.longCtx && p.longCtxAt && u.input > p.longCtxAt ? { ...p, ...p.longCtx } : p;
125
+ const cached = u.cachedInput ?? 0;
126
+ const written = u.cacheWrite ?? 0;
127
+ const fresh = Math.max(0, u.input - cached - written);
128
+ const M = 1e6;
129
+ return fresh * tier.input / M + cached * (tier.cachedInput ?? tier.input) / M + written * (tier.cacheWrite ?? tier.input) / M + u.output * tier.output / M;
130
+ }
131
+
132
+ // cli/src/tokens-lite.ts
133
+ function countTokens(text, _provider = "openai") {
134
+ if (!text) return 0;
135
+ const symbols = (text.match(/[{}[\]<>=;:(),"'`]/g) ?? []).length;
136
+ const cpt = symbols / text.length > 0.04 ? 3.2 : 4;
137
+ return Math.ceil(text.length / cpt);
138
+ }
139
+
140
+ // src/audit-core.ts
141
+ var MODEL_RE = /["'`](?:openai\/|anthropic\/|google\/|models\/)?((?:gpt-[\w.-]+|o[134](?:-mini|-pro)?(?:-[\w-]+)?|claude-[\w.-]+|gemini-[\w.-]+))["'`]/g;
142
+ var CALL_RE = [
143
+ [/\.chat\.completions\.(create|parse)\s*\(/, "openai-chat"],
144
+ [/\.responses\.(create|parse|stream)\s*\(/, "openai-responses"],
145
+ [/\.messages\.(create|stream|parse)\s*\(/, "anthropic-messages"],
146
+ [/\b(generateText|streamText|generateObject|streamObject)\s*\(/, "vercel-ai"],
147
+ [/\b(ChatOpenAI|AzureChatOpenAI)\s*\(/, "langchain-openai"],
148
+ [/\bChatAnthropic\s*\(/, "langchain-anthropic"],
149
+ [/\bChatGoogleGenerativeAI\s*\(/, "langchain-gemini"],
150
+ [/\binit_chat_model\s*\(/, "langchain"],
151
+ [/\.generate_content\s*\(|\.generateContent\s*\(/, "gemini-sdk"],
152
+ [/\blitellm\.(a?completion)\s*\(/, "litellm"]
153
+ ];
154
+ var SOURCE_EXT = /\.(py|ts|tsx|js|jsx|mjs|cjs|rb|go|java|kt|rs|cs|php)$/i;
155
+ var SKIP_PATH = /(^|\/)(node_modules|dist|build|\.next|vendor|venv|\.venv|__pycache__|target|coverage|\.git)(\/|$)|\.min\.js$|\.lock$|\.d\.ts$|(^|\/)(test|tests|__tests__|spec)(\/|$)|[._-](test|spec)\.[a-z]+$|(^|\/)(public|static|assets)\/.*\.m?js$|(^|\/)(workbox|sw|service-worker)[\w.-]*\.js$|[.-][a-f0-9]{8,}\.m?js$|\.bundle\.m?js$/i;
156
+ var EXAMPLE_PATH = /(^|\/)(examples?|docs?|cookbooks?|samples?|demos?|notebooks?|benchmarks?|scripts)(\/|$)/i;
157
+ var MANIFEST_FILES = ["package.json", "pyproject.toml", "setup.py", "setup.cfg"];
158
+ var TRIPLE_DQ = '"'.repeat(3);
159
+ var TRIPLE_SQ = "'".repeat(3);
160
+ function lex(src, path3) {
161
+ const py = /\.py$/i.test(path3), hashComments = py || /\.(rb|php)$/i.test(path3);
162
+ const backtick = /\.(js|jsx|ts|tsx|mjs|cjs|go)$/i.test(path3);
163
+ const out2 = src.split("");
164
+ const literals = [];
165
+ let i = 0, line = 1;
166
+ const blank = (a, b) => {
167
+ for (let k = a; k < b; k++) if (out2[k] !== "\n") out2[k] = " ";
168
+ };
169
+ const advance = (a, b) => {
170
+ for (let k = a; k < b; k++) if (src[k] === "\n") line++;
171
+ };
172
+ while (i < src.length) {
173
+ const c2 = src[i], two = src.slice(i, i + 2), three = src.slice(i, i + 3);
174
+ if (hashComments && c2 === "#" || !py && two === "//") {
175
+ let j = src.indexOf("\n", i);
176
+ if (j < 0) j = src.length;
177
+ blank(i, j);
178
+ i = j;
179
+ continue;
180
+ }
181
+ if (!py && two === "/*") {
182
+ let j = src.indexOf("*/", i + 2);
183
+ j = j < 0 ? src.length : j + 2;
184
+ blank(i, j);
185
+ advance(i, j);
186
+ i = j;
187
+ continue;
188
+ }
189
+ if (py && (three === TRIPLE_DQ || three === TRIPLE_SQ)) {
190
+ let j = src.indexOf(three, i + 3);
191
+ j = j < 0 ? src.length : j + 3;
192
+ literals.push({ text: src.slice(i + 3, Math.max(i + 3, j - 3)), line });
193
+ blank(i + 3, Math.max(i + 3, j - 3));
194
+ advance(i, j);
195
+ i = j;
196
+ continue;
197
+ }
198
+ if (c2 === '"' || c2 === "'" || backtick && c2 === "`") {
199
+ let j = i + 1;
200
+ while (j < src.length && src[j] !== c2) {
201
+ if (src[j] === "\\") j++;
202
+ else if (src[j] === "\n" && c2 !== "`") break;
203
+ j++;
204
+ }
205
+ const end = Math.min(j, src.length);
206
+ literals.push({ text: src.slice(i + 1, end), line });
207
+ blank(i + 1, end);
208
+ advance(i, end + 1);
209
+ i = end + 1;
210
+ continue;
211
+ }
212
+ if (c2 === "\n") line++;
213
+ i++;
214
+ }
215
+ return { masked: out2.join("").split("\n"), literals };
216
+ }
217
+ function promptLike(t) {
218
+ if (t.length < 200) return false;
219
+ const tags = (t.match(/<\/?[a-z][\w-]*[^>]*>/gi) ?? []).length;
220
+ const cssRules = (t.match(/[{;]\s*[a-z-]+\s*:\s*[^;{}]+;/gi) ?? []).length;
221
+ const codeChars = (t.match(/[{}();=<>]/g) ?? []).length;
222
+ const words = (t.match(/[A-Za-z]{2,}/g) ?? []).length;
223
+ return tags < 4 && cssRules < 3 && codeChars / t.length < 0.03 && words / (t.length / 6) > 0.5;
224
+ }
225
+ var SIMPLE_TASK = /\b(classify|classification|categori[sz]e|sentiment|extract (the|all|every|any)|return (only |just )?(valid |a )?json|respond (only )?(with|in) (valid )?json|output (only )?(valid )?json|translate (this|the following|into)|summari[sz]e (this|the following|in \d+)|label (this|the|each)|is (this|it) spam|yes or no|true or false)\b/i;
226
+ var LLM_LIB_EXACT = /* @__PURE__ */ new Set(["openai", "anthropic", "@anthropic-ai/sdk", "ai", "litellm", "openai-agents", "@openai/agents", "instructor", "dspy", "dspy-ai", "guidance", "semantic-kernel", "haystack-ai", "autogen", "pyautogen", "autogen-agentchat", "crewai", "google-genai", "@google/genai", "mistralai", "@mistralai/mistralai", "cohere", "cohere-ai", "llama-index", "llama_index", "llamaindex", "langchain", "langgraph", "@langchain/core", "groq-sdk", "together-ai", "ollama"]);
227
+ var LLM_LIB_FAMILY = /^(@langchain\/[\w-]+|langchain[-_][\w-]+|langgraph[-_][\w-]+|llama[-_]index[-_][\w-]+|@ai-sdk\/[\w-]+|openai[-_]agents[-_][\w-]+)$/i;
228
+ var isLlmLib = (name) => LLM_LIB_EXACT.has(name.toLowerCase()) || LLM_LIB_FAMILY.test(name);
229
+ var APP_DEPS = ["next", "react-dom", "express", "fastify", "hono", "@remix-run/react", "nuxt", "svelte", "@sveltejs/kit", "electron"];
230
+ function detectRepoKind(manifests2, files) {
231
+ const get = (n) => manifests2.find((m) => m.path === n)?.content ?? "";
232
+ const pkgRaw = get("package.json");
233
+ if (pkgRaw) {
234
+ try {
235
+ const pkg = JSON.parse(pkgRaw);
236
+ if (pkg.name && isLlmLib(pkg.name)) return { kind: "library", reason: `package "${pkg.name}" is an LLM SDK/framework` };
237
+ const deps = { ...pkg.dependencies };
238
+ const appDep = APP_DEPS.some((d) => d in deps);
239
+ const publishable = !pkg.private && (pkg.exports || pkg.main || pkg.module || pkg.types) && (pkg.files || pkg.publishConfig);
240
+ if (publishable && !appDep) return { kind: "library", reason: "publishable npm package layout (exports/main + files, not private)" };
241
+ if (pkg.private || appDep) return { kind: "app", reason: "private package or app framework dependency" };
242
+ } catch {
243
+ }
244
+ }
245
+ const pyproject = get("pyproject.toml"), setup = get("setup.py") + get("setup.cfg");
246
+ const pyName = /^\s*name\s*=\s*["']([^"']+)["']/m.exec(pyproject)?.[1] ?? /name\s*=\s*["']([^"']+)["']/.exec(setup)?.[1];
247
+ if (pyName && isLlmLib(pyName)) return { kind: "library", reason: `Python package "${pyName}" is an LLM SDK/framework` };
248
+ const webApp = files.some((f) => /(^|\/)app\/(layout|page)\.[jt]sx?$|(^|\/)pages\/(_app|index)\.[jt]sx?$|(^|\/)src\/routes\/\+page\.svelte$/.test(f.path));
249
+ const hasAppEntry = files.some((f) => /^(app|main|server|manage|streamlit_app|bot)\.py$/i.test(f.path) || /^(app|api|server)\//i.test(f.path) && /\b(FastAPI|Flask|Django|streamlit|gradio)\b/.test(f.content));
250
+ const installable = pyproject.includes("[build-system]") && /^\s*\[project\]/m.test(pyproject) || /\bsetup\(/.test(setup);
251
+ if (webApp) return { kind: "app", reason: "web app routes found (Next.js / SvelteKit)" };
252
+ if (installable && files.some((f) => /^src\/[\w-]+\//.test(f.path)) && !hasAppEntry) return { kind: "library", reason: "installable Python package with src/ layout and no app entry point" };
253
+ if (hasAppEntry) return { kind: "app", reason: "app entry point found" };
254
+ return { kind: "unknown", reason: "no manifest signal" };
255
+ }
256
+ var DOWN = { high: "medium", medium: "low", low: "info", info: "info" };
257
+ function analyzeFiles(files, repo = null, manifests2 = []) {
258
+ const findings = [];
259
+ const callSites = [];
260
+ const siteFindings = [];
261
+ const models = {};
262
+ const unknownModels = /* @__PURE__ */ new Set();
263
+ const notes = [];
264
+ const sources = files.filter((f) => SOURCE_EXT.test(f.path) && !SKIP_PATH.test(f.path) && f.content.length <= 4e5);
265
+ const { kind, reason } = detectRepoKind(manifests2, sources);
266
+ if (kind === "library") notes.push(`Library/SDK layout detected (${reason}): call sites are most likely pass-through wrappers where the caller chooses the model and prompt, so findings are downgraded one level and the estimate is discounted.`);
267
+ const promptLibrary = [];
268
+ const repoCaches = sources.some((f) => /cache_control|cacheControl|prompt_cache_key|promptCacheKey|cachedContent|cached_content/.test(f.content));
269
+ const PROMPT_FILE = /(^|\/)[^/]*(prompt|instruction|template|persona)s?[^/]*\.[a-z]+$|(^|\/)prompts?\//i;
270
+ const PROMPT_NAME = /\b[\w.]*(prompt|system|instruction|template|persona)\w*\s*(:\s*[\w[\]|. ]+)?\s*[:=]\s*(f|r|rf|fr|b)?$/i;
271
+ for (const f of sources) {
272
+ const src = f.content, lines = src.split("\n");
273
+ const { masked, literals } = lex(src, f.path);
274
+ for (const l of literals) {
275
+ if (!promptLike(l.text)) continue;
276
+ const tokens = countTokens(l.text);
277
+ if (tokens < 300) continue;
278
+ const lead = (masked[l.line - 1] ?? "").slice(0, Math.max(0, (masked[l.line - 1] ?? "").search(/["'`]|$/))).trimEnd();
279
+ if (PROMPT_FILE.test(f.path) || PROMPT_NAME.test(lead) || PROMPT_NAME.test((masked[l.line - 2] ?? "").trimEnd())) promptLibrary.push({ file: f.path, line: l.line, tokens });
280
+ }
281
+ const hasCacheControl = /cache_control|cacheControl|prompt_cache_key|promptCacheKey|cachedContent|cached_content/.test(src);
282
+ const illustrative = EXAMPLE_PATH.test(f.path);
283
+ let repeatFlagged = false;
284
+ masked.forEach((code, i) => {
285
+ const sdk = CALL_RE.find(([re]) => re.test(code))?.[1];
286
+ if (!sdk) return;
287
+ const local = [];
288
+ const push = (fd) => {
289
+ let sev = fd.severity;
290
+ if (kind === "library") sev = DOWN[sev];
291
+ if (illustrative) sev = DOWN[sev];
292
+ local.push({ ...fd, severity: sev });
293
+ };
294
+ const window = lines.slice(i, Math.min(lines.length, i + 30)).join("\n");
295
+ const model = [...window.matchAll(MODEL_RE)].map((m) => m[1])[0] ?? null;
296
+ callSites.push({ file: f.path, line: i + 1, model, sdk });
297
+ if (model) models[model] = (models[model] ?? 0) + 1;
298
+ const key = normalizeModel(model);
299
+ const price = key ? priceFor(key) : null;
300
+ const near = literals.filter((l) => l.line >= i + 1 - 40 && l.line <= i + 1 + 40);
301
+ const prompts = near.filter((l) => promptLike(l.text));
302
+ const codeCtx = masked.slice(Math.max(0, i - 25), i + 25).join("\n");
303
+ const simpleTask = near.some((l) => SIMPLE_TASK.test(l.text));
304
+ const isAnthropic = sdk.includes("anthropic") || (model?.startsWith("claude") ?? false);
305
+ const bigTok = prompts.reduce((a, l) => a + countTokens(l.text), 0);
306
+ if (bigTok >= 300 && !hasCacheControl) {
307
+ const readRate = price?.cachedInput != null && price.input ? Math.round((1 - price.cachedInput / price.input) * 100) : 90;
308
+ const min = price?.minCacheTokens ?? 1024;
309
+ const cacheable = bigTok >= min || isAnthropic && bigTok >= 512;
310
+ push({
311
+ severity: isAnthropic ? bigTok >= 1500 ? "high" : cacheable ? "medium" : "low" : cacheable ? "medium" : "low",
312
+ file: f.path,
313
+ line: prompts[0].line,
314
+ title: `~${bigTok.toLocaleString()} static prompt tokens re-billed at full price on every call`,
315
+ detail: isAnthropic ? `This call sends a large fixed prompt but never marks a cache breakpoint, so Anthropic bills all ${bigTok} tokens at the full input rate each time instead of the cache-read rate (${readRate}% cheaper).` : `A fixed prefix of ~${bigTok} tokens is sent on every call. Prefix caching applies only to stable prefixes of at least ${min} tokens on this model; keep the static part first and nothing volatile (timestamps, ids) interpolated into it.`,
316
+ fix: isAnthropic ? 'Route through TokenZero (breakpoints are injected automatically) or add `cache_control: {type: "ephemeral"}` to the last system block and the last tool.' : "Route through TokenZero to get a stable `prompt_cache_key`, or move dynamic content below the static prefix and set `prompt_cache_key` yourself.",
317
+ // OpenAI/Gemini already cache stable prefixes automatically; the recoverable part
318
+ // is prefix hygiene and cache routing, not the whole cache discount.
319
+ est_savings_pct: !cacheable ? 0 : isAnthropic ? Math.min(85, Math.round(bigTok / (bigTok + 400) * readRate)) : 15
320
+ });
321
+ }
322
+ if (key && price?.tier === "frontier" && CASCADE_TARGET[key] && simpleTask) {
323
+ const to = CASCADE_TARGET[key];
324
+ const a = costOf(key, { input: 1500, output: 200 }), b = costOf(to, { input: 1500, output: 200 });
325
+ push({
326
+ severity: "high",
327
+ file: f.path,
328
+ line: i + 1,
329
+ title: `${key} used for a task whose prompt reads like extraction/classification`,
330
+ detail: `Frontier pricing ($${price.input}/M in, $${price.output}/M out) on a constrained task. ${to} costs ~${Math.round((1 - b / a) * 100)}% less per call at this shape.`,
331
+ fix: `Opt into TokenZero cascade routing (\`X-TokenZero-Cascade: auto\`) so this call is routed to ${to} only when the classifier is confident, with parity reported in the ledger, or switch the model here behind an eval.`,
332
+ est_savings_pct: Math.round((1 - b / a) * 100)
333
+ });
334
+ }
335
+ const above = masked.slice(Math.max(0, i - 6), i).join("\n");
336
+ if (/^\s*(for|while)\b|\.map\(|\.forEach\(|asyncio\.gather|Promise\.all/m.test(above) && !/batch/i.test(codeCtx)) {
337
+ push({
338
+ severity: "medium",
339
+ file: f.path,
340
+ line: i + 1,
341
+ title: "LLM call inside a loop",
342
+ detail: "Per-item calls repeat the full prompt prefix for every element. If items are independent and latency-tolerant, the provider Batch API is 50% cheaper; if the prefix is shared, caching pays off immediately.",
343
+ fix: "Batch where possible; otherwise keep the shared prefix cache-formatted (TokenZero does this automatically).",
344
+ est_savings_pct: 25
345
+ });
346
+ }
347
+ if (simpleTask && !repeatFlagged && !/seed\s*[:=]|temperature\s*[:=]\s*0\b/.test(codeCtx)) {
348
+ repeatFlagged = true;
349
+ push({
350
+ severity: "info",
351
+ file: f.path,
352
+ line: i + 1,
353
+ title: "Repeat-prone task with no response-cache opt-in",
354
+ detail: "Classification and extraction calls often see identical inputs. Without a determinism signal no proxy can safely serve repeats from cache.",
355
+ fix: "If identical inputs should get identical answers, send `X-TokenZero-Cache: always` on these calls (or `temperature: 0` / a `seed` on models that still accept them). Repeats are then served in <10 ms at $0.",
356
+ est_savings_pct: 10
357
+ });
358
+ }
359
+ if (isAnthropic && /\btools\s*[:=]/.test(masked.slice(i, i + 30).join("\n")) && !hasCacheControl) {
360
+ push({
361
+ severity: "low",
362
+ file: f.path,
363
+ line: i + 1,
364
+ title: "Tool definitions sent without a cache breakpoint",
365
+ detail: "Tool schemas render before the system prompt in the cached prefix. Without a breakpoint on the last tool they are billed in full on every call.",
366
+ fix: "TokenZero marks the last tool automatically; manually, add `cache_control` to the last tool definition.",
367
+ est_savings_pct: 8
368
+ });
369
+ }
370
+ if (model && !key && !unknownModels.has(model)) {
371
+ unknownModels.add(model);
372
+ push({ severity: "info", file: f.path, line: i + 1, title: `Unrecognised model id "${model}"`, detail: "Not in the current pricing table: it may be retired or renamed. Retired models return errors or are silently remapped by some providers.", fix: "Check the provider model list; TokenZero flags unpriced models in `X-TokenZero-Warning`.", est_savings_pct: 0 });
373
+ }
374
+ findings.push(...local);
375
+ siteFindings.push(local);
376
+ });
377
+ }
378
+ const libTokens = promptLibrary.reduce((a, p) => a + p.tokens, 0);
379
+ if (callSites.length && !repoCaches && libTokens >= 1024 && !findings.some((f) => /static prompt tokens/.test(f.title))) {
380
+ const anth = callSites.filter((c2) => c2.sdk.includes("anthropic") || c2.model?.startsWith("claude")).length;
381
+ const anthropicHeavy = anth * 2 >= callSites.length;
382
+ const top = promptLibrary.slice().sort((a, b) => b.tokens - a.tokens)[0];
383
+ const sev = anthropicHeavy ? libTokens >= 3e3 ? "high" : "medium" : "medium";
384
+ const fd = {
385
+ severity: kind === "library" ? DOWN[sev] : sev,
386
+ file: top.file,
387
+ line: top.line,
388
+ title: `${promptLibrary.length} static prompt template(s), ~${libTokens.toLocaleString()} tokens, and no caching directive anywhere in the repo`,
389
+ detail: anthropicHeavy ? "Most call sites use Anthropic, which only discounts cached input when the request marks a cache breakpoint. None of these prompts can be served from cache as written, so every call pays the full input rate for them." : "Most call sites use providers with automatic prefix caching, which only pays off when these templates are sent as a byte-identical prefix: static template first, nothing volatile (dates, ids, user data) interpolated into it.",
390
+ fix: anthropicHeavy ? 'Route through TokenZero (breakpoints are injected on tools and system automatically) or add `cache_control: {type: "ephemeral"}` after each static template.' : "Keep templates first and static; TokenZero adds a stable `prompt_cache_key` so related requests land on the same cache.",
391
+ est_savings_pct: anthropicHeavy ? Math.min(70, Math.round(libTokens / (libTokens + 2e3) * 85)) : 12
392
+ };
393
+ findings.push(fd);
394
+ for (const site of siteFindings) site.push(fd);
395
+ }
396
+ const weight = { high: 1, medium: 0.6, low: 0.3, info: 0 };
397
+ const perSite = siteFindings.map((fs3) => 1 - fs3.reduce((rem, f) => rem * (1 - f.est_savings_pct / 100 * weight[f.severity]), 1));
398
+ let waste = perSite.length ? perSite.reduce((a, b) => a + b, 0) / perSite.length : 0;
399
+ if (kind === "library") waste *= 0.3;
400
+ const wastePct = Math.round(Math.min(0.7, waste) * 100);
401
+ if (!callSites.length) notes.push("No recognised LLM call sites (OpenAI, Anthropic, Gemini, Vercel AI SDK, LangChain, LiteLLM). Calls behind custom wrappers are not detected.");
402
+ const topModel = Object.entries(models).sort((a, b) => b[1] - a[1]).map(([m]) => normalizeModel(m)).find(Boolean) ?? null;
403
+ let cost = null;
404
+ if (topModel && PRICES[topModel]) {
405
+ const assumed = 2e3;
406
+ const before = costOf(topModel, { input: assumed, output: 300 }) * 1e4;
407
+ cost = { model: topModel, assumed_prompt_tokens: assumed, before_usd: Math.round(before * 100) / 100, after_usd: Math.round(before * (1 - wastePct / 100) * 100) / 100 };
408
+ }
409
+ const order = { high: 0, medium: 1, low: 2, info: 3 };
410
+ findings.sort((a, b) => order[a.severity] - order[b.severity] || b.est_savings_pct - a.est_savings_pct);
411
+ const id = "aud_" + crypto.randomBytes(16).toString("base64url");
412
+ return { id, repo, method: "static heuristics", repo_kind: kind, notes, scanned_files: sources.length, call_sites: callSites, models, findings, estimated_waste_pct: wastePct, cost_per_10k_runs: cost, badge_url: null, generated_at: (/* @__PURE__ */ new Date()).toISOString() };
413
+ }
414
+ function filesFromDiff(diff) {
415
+ const files = [];
416
+ let cur = null;
417
+ for (const line of diff.split("\n")) {
418
+ const m = /^\+\+\+ b\/(.+)$/.exec(line);
419
+ if (m) {
420
+ cur = { path: m[1], content: "" };
421
+ files.push(cur);
422
+ continue;
423
+ }
424
+ if (!cur) continue;
425
+ if (line.startsWith("+") && !line.startsWith("+++")) cur.content += line.slice(1) + "\n";
426
+ else if (line.startsWith(" ")) cur.content += line.slice(1) + "\n";
427
+ else if (line.startsWith("@@")) cur.content += "\n";
428
+ }
429
+ return files;
430
+ }
431
+ function prComment(report, publicUrl) {
432
+ const c2 = report.cost_per_10k_runs;
433
+ const head = c2 ? `**TokenZero FinOps check** \u2014 estimated cost per 10k runs: \`$${c2.before_usd}\` \u2192 \`$${c2.after_usd}\` (${report.estimated_waste_pct}% recoverable) on \`${c2.model}\`` : `**TokenZero FinOps check** \u2014 ${report.findings.length} finding(s), ${report.call_sites.length} LLM call site(s)`;
434
+ const rows = report.findings.slice(0, 8).map((f) => `| ${f.severity} | \`${f.file}:${f.line}\` | ${f.title} | ${f.est_savings_pct}% |`).join("\n");
435
+ return [
436
+ head,
437
+ "",
438
+ report.findings.length ? "| severity | where | finding | est. savings |\n|---|---|---|---|\n" + rows : "_No token-waste patterns found in the changed lines._",
439
+ "",
440
+ report.findings.slice(0, 3).map((f) => `<details><summary>${f.title}</summary>
441
+
442
+ ${f.detail}
443
+
444
+ **Fix:** ${f.fix}
445
+ </details>`).join("\n"),
446
+ "",
447
+ `One-line fix for everything above: point your SDK at \`${publicUrl}/v1\` (BYOK; your keys pass straight through). [How it works](${publicUrl}) \xB7 [Full report](${publicUrl}/audit/${report.id})`,
448
+ ...report.notes.map((n) => `> ${n}`),
449
+ "",
450
+ "<sub>Estimates are static heuristics at list prices, not measurements. Verified numbers come from the signed ledger once traffic flows.</sub>"
451
+ ].join("\n");
452
+ }
453
+
454
+ // cli/src/scan.ts
455
+ import fs from "node:fs";
456
+ import path from "node:path";
457
+ function walk(root, limit = 5e3) {
458
+ const files = [];
459
+ const stack = [root];
460
+ while (stack.length && files.length < limit) {
461
+ const dir = stack.pop();
462
+ let entries;
463
+ try {
464
+ entries = fs.readdirSync(dir, { withFileTypes: true });
465
+ } catch {
466
+ continue;
467
+ }
468
+ for (const e of entries) {
469
+ const full = path.join(dir, e.name);
470
+ const rel = path.relative(root, full).split(path.sep).join("/");
471
+ if (e.name.startsWith(".") && e.name !== ".github") continue;
472
+ if (SKIP_PATH.test(rel + (e.isDirectory() ? "/" : ""))) continue;
473
+ if (e.isDirectory()) stack.push(full);
474
+ else if (e.isFile() && SOURCE_EXT.test(e.name)) {
475
+ try {
476
+ const st = fs.statSync(full);
477
+ if (st.size < 4e5) files.push({ path: rel, content: fs.readFileSync(full, "utf8") });
478
+ } catch {
479
+ }
480
+ }
481
+ }
482
+ }
483
+ return files;
484
+ }
485
+ function manifests(root) {
486
+ return MANIFEST_FILES.flatMap((n) => {
487
+ try {
488
+ return [{ path: n, content: fs.readFileSync(path.join(root, n), "utf8") }];
489
+ } catch {
490
+ return [];
491
+ }
492
+ });
493
+ }
494
+
495
+ // src/canonical.ts
496
+ function canonical(obj) {
497
+ if (obj === null || typeof obj !== "object") return JSON.stringify(obj);
498
+ if (Array.isArray(obj)) return "[" + obj.map(canonical).join(",") + "]";
499
+ const o = obj;
500
+ return "{" + Object.keys(o).sort().filter((k) => o[k] !== void 0).map((k) => JSON.stringify(k) + ":" + canonical(o[k])).join(",") + "}";
501
+ }
502
+
503
+ // cli/src/main.ts
504
+ var VERSION = "0.1.0";
505
+ var BAKED_URL = typeof __TOKENZERO_BAKED__ === "string" ? __TOKENZERO_BAKED__ : "__TOKENZERO_DEFAULT_URL__";
506
+ function parseArgs(argv) {
507
+ const a = { _: [], flags: {} };
508
+ for (let i = 0; i < argv.length; i++) {
509
+ const t = argv[i];
510
+ if (t === "--") {
511
+ a._.push(...argv.slice(i + 1));
512
+ break;
513
+ }
514
+ if (t.startsWith("--")) {
515
+ const [k, v] = t.slice(2).split("=", 2);
516
+ if (v !== void 0) a.flags[k] = v;
517
+ else if (argv[i + 1] && !argv[i + 1].startsWith("-") && VALUE_FLAGS.has(k)) a.flags[k] = argv[++i];
518
+ else a.flags[k] = true;
519
+ } else if (t === "-y") a.flags.yes = true;
520
+ else a._.push(t);
521
+ }
522
+ return a;
523
+ }
524
+ var VALUE_FLAGS = /* @__PURE__ */ new Set(["url", "name", "key", "format", "diff", "fail-over", "env-file"]);
525
+ var tty = process.stdout.isTTY && !process.env.NO_COLOR;
526
+ var c = (code) => (s) => tty ? `\x1B[${code}m${s}\x1B[0m` : s;
527
+ var bold = c("1");
528
+ var dim = c("2");
529
+ var green = c("32");
530
+ var yellow = c("33");
531
+ var red = c("31");
532
+ var cyan = c("36");
533
+ var out = (s = "") => process.stdout.write(s + "\n");
534
+ var err = (s) => process.stderr.write(s + "\n");
535
+ function baseUrl(a) {
536
+ const u = a.flags.url || process.env.TOKENZERO_URL || (BAKED_URL.startsWith("http") ? BAKED_URL : "");
537
+ return u ? u.replace(/\/+$/, "") : null;
538
+ }
539
+ async function confirm(q, a) {
540
+ if (a.flags.yes) return true;
541
+ if (!process.stdin.isTTY) return false;
542
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
543
+ const ans = (await rl.question(`${q} ${dim("[y/N]")} `)).trim().toLowerCase();
544
+ rl.close();
545
+ return ans === "y" || ans === "yes";
546
+ }
547
+ async function api(base, p, init = {}) {
548
+ let r;
549
+ try {
550
+ r = await fetch(base + p, { ...init, redirect: "manual", headers: { "content-type": "application/json", "user-agent": `tokenzero-cli/${VERSION}`, ...init.headers ?? {} } });
551
+ } catch (e) {
552
+ throw new Error(`cannot reach ${base}: ${e?.cause?.code ?? e?.message ?? e}`);
553
+ }
554
+ if (r.status >= 300 && r.status < 400) throw new Error(`${base} redirected (${r.status}) instead of answering; the gateway is not publicly reachable yet`);
555
+ const text = await r.text();
556
+ let body = text;
557
+ try {
558
+ body = JSON.parse(text);
559
+ } catch {
560
+ }
561
+ return { status: r.status, body };
562
+ }
563
+ function detectStack(root) {
564
+ const sdks = /* @__PURE__ */ new Set();
565
+ let lang = "unknown";
566
+ const read = (f) => {
567
+ try {
568
+ return fs2.readFileSync(path2.join(root, f), "utf8");
569
+ } catch {
570
+ return "";
571
+ }
572
+ };
573
+ const pkg = read("package.json");
574
+ if (pkg) {
575
+ lang = "node";
576
+ try {
577
+ const j = JSON.parse(pkg);
578
+ const deps = { ...j.dependencies, ...j.devDependencies };
579
+ if (deps.openai) sdks.add("openai");
580
+ if (deps["@anthropic-ai/sdk"]) sdks.add("anthropic");
581
+ if (deps.ai || Object.keys(deps).some((d) => d.startsWith("@ai-sdk/"))) sdks.add("vercel-ai");
582
+ if (Object.keys(deps).some((d) => d.startsWith("@langchain/") || d === "langchain")) sdks.add("langchain");
583
+ if (deps["@google/genai"]) sdks.add("gemini");
584
+ } catch {
585
+ }
586
+ }
587
+ const py = read("requirements.txt") + read("pyproject.toml") + read("Pipfile") + read("setup.py");
588
+ if (py) {
589
+ if (lang === "unknown") lang = "python";
590
+ if (/^\s*["']?openai\b/im.test(py)) sdks.add("openai");
591
+ if (/^\s*["']?anthropic\b/im.test(py)) sdks.add("anthropic");
592
+ if (/langchain/i.test(py)) sdks.add("langchain");
593
+ if (/litellm/i.test(py)) sdks.add("litellm");
594
+ if (/google-genai|google-generativeai/i.test(py)) sdks.add("gemini");
595
+ }
596
+ return { lang, sdks: [...sdks] };
597
+ }
598
+ var ENV_KEYS = ["OPENAI_BASE_URL", "ANTHROPIC_BASE_URL", "TOKENZERO_URL", "TOKENZERO_KEY"];
599
+ function planEnv(file, wanted) {
600
+ const existing = fs2.existsSync(file) ? fs2.readFileSync(file, "utf8") : "";
601
+ const current = {};
602
+ for (const line of existing.split("\n")) {
603
+ const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)$/.exec(line);
604
+ if (m) current[m[1]] = m[2].replace(/^["']|["']$/g, "");
605
+ }
606
+ const add = [], conflicts = [];
607
+ for (const [k, v] of Object.entries(wanted)) {
608
+ if (!(k in current)) add.push(`${k}=${v}`);
609
+ else if (current[k] !== v) conflicts.push(k);
610
+ }
611
+ return { existing, add, conflicts, exists: !!existing };
612
+ }
613
+ function gitignored(root, name) {
614
+ try {
615
+ return fs2.readFileSync(path2.join(root, ".gitignore"), "utf8").split("\n").some((l) => {
616
+ const t = l.trim();
617
+ return t === name || t === "/" + name || t === name + "*" || t === ".env*" || t === "*.env";
618
+ });
619
+ } catch {
620
+ return false;
621
+ }
622
+ }
623
+ function summarize(r, limit = 5) {
624
+ out(`${bold("Audit")} ${dim("(static heuristics, local only: no source left this machine)")}`);
625
+ out(` ${r.scanned_files} files \xB7 ${r.call_sites.length} LLM call site(s) \xB7 ${r.findings.length} finding(s) \xB7 repo looks like: ${r.repo_kind}`);
626
+ for (const n of r.notes) out(dim(` note: ${n}`));
627
+ if (r.cost_per_10k_runs) out(` est. cost per 10k runs on ${r.cost_per_10k_runs.model}: $${r.cost_per_10k_runs.before_usd} \u2192 ${green("$" + r.cost_per_10k_runs.after_usd)} (~${r.estimated_waste_pct}% recoverable)`);
628
+ for (const f of r.findings.slice(0, limit)) {
629
+ const sev = f.severity === "high" ? red(f.severity) : f.severity === "medium" ? yellow(f.severity) : dim(f.severity);
630
+ out(` ${sev.padEnd(tty ? 15 : 6)} ${cyan(f.file + ":" + f.line)} ${f.title}`);
631
+ }
632
+ if (r.findings.length > limit) out(dim(` \u2026 ${r.findings.length - limit} more (run the audit command for the full list)`));
633
+ }
634
+ function snippet(sdk, lang) {
635
+ const py = lang === "python";
636
+ switch (sdk) {
637
+ case "openai":
638
+ return py ? "OpenAI() # reads OPENAI_BASE_URL; no code change" : "new OpenAI() // reads OPENAI_BASE_URL; no code change";
639
+ case "anthropic":
640
+ return py ? "Anthropic() # reads ANTHROPIC_BASE_URL; no code change" : "new Anthropic() // reads ANTHROPIC_BASE_URL; no code change";
641
+ case "vercel-ai":
642
+ return 'createOpenAI({ baseURL: process.env.OPENAI_BASE_URL }) / createAnthropic({ baseURL: process.env.ANTHROPIC_BASE_URL + "/v1" })';
643
+ case "langchain":
644
+ return py ? 'ChatOpenAI(base_url=os.environ["OPENAI_BASE_URL"]) / ChatAnthropic(base_url=os.environ["ANTHROPIC_BASE_URL"])' : "new ChatOpenAI({ configuration: { baseURL: process.env.OPENAI_BASE_URL } })";
645
+ case "litellm":
646
+ return "litellm reads OPENAI_BASE_URL / ANTHROPIC_BASE_URL (api_base) per provider";
647
+ case "gemini":
648
+ return "use the OpenAI SDK against OPENAI_BASE_URL with your Gemini key (AIza\u2026)";
649
+ default:
650
+ return null;
651
+ }
652
+ }
653
+ async function cmdInit(a) {
654
+ const root = path2.resolve(a._[1] ?? ".");
655
+ const base = baseUrl(a);
656
+ out(`${bold("TokenZero")} init ${dim("v" + VERSION)} in ${root}
657
+ `);
658
+ const stack = detectStack(root);
659
+ out(`${bold("Project")} ${stack.lang}${stack.sdks.length ? " \xB7 " + stack.sdks.join(", ") : dim(" \xB7 no LLM SDK found in manifests")}`);
660
+ const report = analyzeFiles(walk(root), null, manifests(root));
661
+ out();
662
+ summarize(report, 5);
663
+ out();
664
+ if (!base) {
665
+ err(red("No gateway URL. Pass --url https://\u2026 or set TOKENZERO_URL."));
666
+ process.exitCode = 2;
667
+ return;
668
+ }
669
+ let key = a.flags.key || process.env.TOKENZERO_KEY || "";
670
+ let wsId = "";
671
+ if (!key) {
672
+ try {
673
+ const r = await api(base, "/v1/workspaces", { method: "POST", body: JSON.stringify({ name: a.flags.name ?? path2.basename(root) }) });
674
+ if (r.status !== 201) throw new Error(`workspace creation failed (${r.status}): ${JSON.stringify(r.body).slice(0, 200)}`);
675
+ key = r.body.key;
676
+ wsId = r.body.workspace.id;
677
+ out(`${bold("Workspace")} ${wsId} ${dim("created")}`);
678
+ } catch (e) {
679
+ err(yellow(`! ${e.message}`));
680
+ err(dim(" Continuing without a workspace key: requests will be grouped by an anonymous workspace derived from your provider key."));
681
+ }
682
+ }
683
+ const prefix = key ? `${base}/w/${key}` : base;
684
+ const wanted = { OPENAI_BASE_URL: `${prefix}/v1`, ANTHROPIC_BASE_URL: prefix, TOKENZERO_URL: base };
685
+ if (key) wanted.TOKENZERO_KEY = key;
686
+ const envFile = path2.join(root, a.flags["env-file"] ?? ".env");
687
+ const plan = planEnv(envFile, wanted);
688
+ out(`
689
+ ${bold("Environment")} ${dim("(your provider keys stay where they are; they pass through untouched)")}`);
690
+ for (const k of ENV_KEYS) if (wanted[k]) out(` ${k}=${k === "TOKENZERO_KEY" || k.endsWith("BASE_URL") && key ? redactKey(wanted[k], key) : wanted[k]}`);
691
+ if (plan.conflicts.length) out(yellow(` ! ${path2.basename(envFile)} already sets ${plan.conflicts.join(", ")} to other values; left unchanged`));
692
+ if (a.flags["no-env"]) out(dim(` --no-env: add the lines above to your environment yourself.`));
693
+ else if (plan.add.length && await confirm(`
694
+ Append ${plan.add.length} line(s) to ${path2.relative(root, envFile) || ".env"}?`, a)) {
695
+ const sep = plan.existing && !plan.existing.endsWith("\n") ? "\n" : "";
696
+ fs2.appendFileSync(envFile, `${sep}
697
+ # TokenZero (BYOK gateway): ${base}
698
+ ${plan.add.join("\n")}
699
+ `, { mode: 384 });
700
+ out(green(` \u2713 wrote ${path2.relative(root, envFile) || ".env"}`));
701
+ if (fs2.existsSync(path2.join(root, ".git")) && !gitignored(root, path2.basename(envFile))) out(yellow(` ! ${path2.basename(envFile)} is not in .gitignore; it now holds your TokenZero key`));
702
+ } else if (plan.add.length) out(dim(" not written; run with --yes to write, or copy the lines above."));
703
+ if (stack.sdks.length) {
704
+ out(`
705
+ ${bold("Your code")}`);
706
+ for (const s of stack.sdks) {
707
+ const sn = snippet(s, stack.lang);
708
+ if (sn) out(` ${s.padEnd(10)} ${sn}`);
709
+ }
710
+ }
711
+ if (a.flags.mcp) await setupMcp(root, base, a);
712
+ out(`
713
+ ${bold("Next")}`);
714
+ if (wsId) out(` dashboard ${base}/dashboard?workspace=${wsId}`);
715
+ out(` usage ${selfCmd(base)} usage`);
716
+ if (wsId) out(` badge turn on public stats in the dashboard, then: [![LLM spend verified by TokenZero](${base}/v1/badge/${wsId}.svg)](${base}/dashboard?workspace=${wsId})`);
717
+ if (!a.flags.mcp) out(` coding agents: ${selfCmd(base)} init --mcp`);
718
+ }
719
+ var selfCmd = (base) => `npx -y ${base}/cli/tokenzero.tgz`;
720
+ var redactKey = (s, key) => key ? s.replace(key, key.slice(0, 12) + "\u2026" + key.slice(-4)) : s;
721
+ async function setupMcp(root, base, a) {
722
+ out(`
723
+ ${bold("MCP")} ${dim("(audit_repo_token_waste, optimize_prompt_payload, calculate_model_arbitrage)")}`);
724
+ out(` Claude Code: claude mcp add --transport http tokenzero ${base}/mcp`);
725
+ const cursorDir = path2.join(root, ".cursor");
726
+ const file = path2.join(cursorDir, "mcp.json");
727
+ let cfg = {};
728
+ if (fs2.existsSync(file)) {
729
+ try {
730
+ cfg = JSON.parse(fs2.readFileSync(file, "utf8"));
731
+ } catch {
732
+ out(yellow(` ! ${file} is not valid JSON; not touching it`));
733
+ return;
734
+ }
735
+ }
736
+ if (cfg?.mcpServers?.tokenzero?.url === `${base}/mcp`) {
737
+ out(dim(" Cursor: already configured"));
738
+ return;
739
+ }
740
+ if (await confirm(` Add TokenZero to ${path2.relative(root, file)} for Cursor?`, a)) {
741
+ cfg.mcpServers = { ...cfg.mcpServers ?? {}, tokenzero: { url: `${base}/mcp` } };
742
+ fs2.mkdirSync(cursorDir, { recursive: true });
743
+ fs2.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
744
+ out(green(` \u2713 wrote ${path2.relative(root, file)}`));
745
+ }
746
+ }
747
+ async function cmdAudit(a) {
748
+ const root = path2.resolve(a._[1] ?? ".");
749
+ let report;
750
+ if (a.flags.diff) {
751
+ const src = a.flags.diff === "-" || a.flags.diff === true ? fs2.readFileSync(0, "utf8") : fs2.readFileSync(a.flags.diff, "utf8");
752
+ report = analyzeFiles(filesFromDiff(src), null);
753
+ } else report = analyzeFiles(walk(root), null, manifests(root));
754
+ const fmt = a.flags.format ?? (a.flags.json ? "json" : "text");
755
+ if (fmt === "json") out(JSON.stringify(report, null, 2));
756
+ else if (fmt === "markdown") out(prComment(report, baseUrl(a) ?? "https://tokenzero.sh"));
757
+ else {
758
+ summarize(report, 100);
759
+ for (const f of report.findings.slice(0, 3)) out(`
760
+ ${bold(f.title)}
761
+ ${f.detail}
762
+ ${green("fix:")} ${f.fix}`);
763
+ }
764
+ const gate = Number(a.flags["fail-over"]);
765
+ if (Number.isFinite(gate) && a.flags["fail-over"] !== void 0 && report.estimated_waste_pct > gate) {
766
+ err(red(`recoverable waste ${report.estimated_waste_pct}% exceeds --fail-over ${gate}%`));
767
+ process.exitCode = 1;
768
+ }
769
+ }
770
+ async function cmdUsage(a) {
771
+ const base = baseUrl(a);
772
+ const key = a.flags.key || process.env.TOKENZERO_KEY;
773
+ if (!base || !key) {
774
+ err(red("Need TOKENZERO_URL and TOKENZERO_KEY (run tokenzero init), or --url and --key."));
775
+ process.exitCode = 2;
776
+ return;
777
+ }
778
+ const [u, s] = await Promise.all([api(base, "/v1/usage", { headers: { "x-tokenzero-key": key } }), api(base, "/v1/ledger/stats", { headers: { "x-tokenzero-key": key } })]);
779
+ if (u.status !== 200) {
780
+ err(red(`usage: ${u.status} ${JSON.stringify(u.body).slice(0, 200)}`));
781
+ process.exitCode = 1;
782
+ return;
783
+ }
784
+ if (a.flags.json) {
785
+ out(JSON.stringify({ usage: u.body, stats: s.body }, null, 2));
786
+ return;
787
+ }
788
+ const d = u.body;
789
+ const barW = 30, filled = Math.round(d.free_tier_used_pct / 100 * barW);
790
+ out(`${bold(d.workspace)} \xB7 ${d.month} \xB7 plan ${d.plan}`);
791
+ out(` routed spend $${d.routed_usd.toFixed(2)} of $${d.free_tier_limit_usd} free [${(d.free_tier_used_pct >= 80 ? yellow : green)("\u2588".repeat(filled))}${dim("\u2591".repeat(barW - filled))}] ${d.free_tier_used_pct}%`);
792
+ out(` actual spend $${d.actual_usd.toFixed(2)} saved ${green("$" + d.savings_usd.toFixed(2))} requests ${d.requests}`);
793
+ if (s.status === 200 && s.body.savings_pct != null) out(` last 30 days ${s.body.savings_pct}% saved \xB7 ${s.body.cache_hits} cache hits \xB7 projected $${s.body.projected_monthly_savings_usd.toFixed(2)}/mo`);
794
+ if (d.engines_paused) out(yellow(` engines paused: free tier reached; traffic passes through unoptimised until ${d.resets_at}`));
795
+ out(dim(` fee preview: $${d.fee_preview.estimated_fee_usd.toFixed(2)} (${d.fee_preview.label})`));
796
+ }
797
+ async function cmdRotate(a) {
798
+ const base = baseUrl(a);
799
+ const key = a.flags.key || process.env.TOKENZERO_KEY;
800
+ if (!base || !key) {
801
+ err(red("Need TOKENZERO_URL and TOKENZERO_KEY (or --url and --key)."));
802
+ process.exitCode = 2;
803
+ return;
804
+ }
805
+ const root = path2.resolve(a._[1] ?? ".");
806
+ const envFile = path2.join(root, a.flags["env-file"] ?? ".env");
807
+ if (!await confirm(`Rotate the workspace key? The current key stops working immediately.`, a)) {
808
+ out(dim("cancelled"));
809
+ return;
810
+ }
811
+ const r = await api(base, "/v1/workspaces/me/rotate-key", { method: "POST", headers: { "x-tokenzero-key": key } });
812
+ if (r.status !== 200) {
813
+ err(red(`rotate: ${r.status} ${JSON.stringify(r.body).slice(0, 200)}`));
814
+ process.exitCode = 1;
815
+ return;
816
+ }
817
+ const fresh = r.body.key;
818
+ out(green(`\u2713 rotated; old key ${redactKey(key, key)} is now invalid`));
819
+ if (fs2.existsSync(envFile)) {
820
+ const before = fs2.readFileSync(envFile, "utf8");
821
+ const after = before.split(key).join(fresh);
822
+ if (after !== before) {
823
+ fs2.writeFileSync(envFile, after, { mode: 384 });
824
+ out(green(`\u2713 updated ${path2.relative(root, envFile) || ".env"} (TOKENZERO_KEY and /w/<key>/ base URLs)`));
825
+ return;
826
+ }
827
+ }
828
+ out(`New key (shown once): ${fresh}`);
829
+ out(dim("Update TOKENZERO_KEY and any /w/<key>/ base URLs wherever the old key was configured (CI secrets, hosting env)."));
830
+ }
831
+ async function cmdVerify(a) {
832
+ const base = baseUrl(a);
833
+ const id = a._[1];
834
+ if (!base || !id) {
835
+ err(red("usage: tokenzero verify <request_id> [--url \u2026]"));
836
+ process.exitCode = 2;
837
+ return;
838
+ }
839
+ const [r, k] = await Promise.all([api(base, `/v1/ledger/receipt/${encodeURIComponent(id)}`), api(base, "/.well-known/tokenzero.json")]);
840
+ if (r.status !== 200) {
841
+ err(red(`receipt: ${r.status}`));
842
+ process.exitCode = 1;
843
+ return;
844
+ }
845
+ const jwk = (k.body?.keys ?? []).find((x) => x.kid === r.body.receipt.key_id);
846
+ if (!jwk) {
847
+ err(red(`no public key with kid ${r.body.receipt.key_id} at ${base}/.well-known/tokenzero.json`));
848
+ process.exitCode = 1;
849
+ return;
850
+ }
851
+ const pub = crypto2.createPublicKey({ key: { kty: jwk.kty, crv: jwk.crv, x: jwk.x }, format: "jwk" });
852
+ const ok = crypto2.verify(null, Buffer.from(canonical(r.body.receipt)), pub, Buffer.from(r.body.signature, "base64url"));
853
+ const rc = r.body.receipt;
854
+ out(`${ok ? green("\u2713 valid") : red("\u2717 INVALID")} signature (Ed25519, key ${rc.key_id}, verified locally)`);
855
+ out(` ${rc.id} \xB7 ${new Date(rc.ts).toISOString()} \xB7 ${rc.provider} ${rc.requested_model}${rc.served_model && rc.served_model !== rc.requested_model ? " \u2192 " + rc.served_model : ""}`);
856
+ out(` baseline $${rc.baseline_usd} \xB7 actual $${rc.actual_usd} \xB7 saved $${rc.savings_usd} \xB7 engines ${rc.engines.join(",") || "none"} \xB7 pricing ${rc.pricing_version}`);
857
+ if (!ok) process.exitCode = 1;
858
+ }
859
+ function help() {
860
+ out(`${bold("tokenzero")} v${VERSION} \u2014 cut your LLM bill with a BYOK gateway
861
+
862
+ ${bold("tokenzero init")} [dir] [--url URL] [--name NAME] [--yes] [--no-env] [--mcp]
863
+ Audit locally, create a workspace, point OPENAI_BASE_URL / ANTHROPIC_BASE_URL at the gateway.
864
+ ${bold("tokenzero audit")} [dir] [--json | --format markdown] [--diff file|-] [--fail-over PCT]
865
+ Static token-waste audit. Runs locally; nothing is uploaded. --fail-over makes it a CI gate.
866
+ ${bold("tokenzero usage")} [--json] Routed spend vs the free tier, savings, fee preview.
867
+ ${bold("tokenzero verify")} <request_id> Verify a savings receipt's signature offline.
868
+ ${bold("tokenzero rotate-key")} [--yes] Issue a new workspace key; rewrites it in .env. Old key dies immediately.
869
+
870
+ Env: TOKENZERO_URL, TOKENZERO_KEY, NO_COLOR`);
871
+ }
872
+ async function main() {
873
+ process.stdout.on("error", (e) => {
874
+ if (e.code === "EPIPE") process.exit(0);
875
+ throw e;
876
+ });
877
+ const a = parseArgs(process.argv.slice(2));
878
+ const cmd = a._[0];
879
+ if (a.flags.version || cmd === "version") return out(VERSION);
880
+ switch (cmd) {
881
+ case "init":
882
+ return cmdInit(a);
883
+ case "audit":
884
+ return cmdAudit(a);
885
+ case "usage":
886
+ return cmdUsage(a);
887
+ case "verify":
888
+ return cmdVerify(a);
889
+ case "rotate-key":
890
+ return cmdRotate(a);
891
+ case void 0:
892
+ case "help":
893
+ return help();
894
+ default:
895
+ err(red(`unknown command: ${cmd}`));
896
+ help();
897
+ process.exitCode = 2;
898
+ }
899
+ }
900
+ main().catch((e) => {
901
+ err(red(`error: ${e?.message ?? e}`));
902
+ process.exitCode = 1;
903
+ });
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@tokenzero/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "TokenZero CLI: connect a project to the TokenZero BYOK gateway, audit LLM token waste locally, check usage and verify signed savings receipts.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "author": "TokenZero Contributors <support@tokenzero.sh>",
8
+ "homepage": "https://tokenzero.sh",
9
+ "bin": { "tokenzero": "bin/tokenzero.mjs" },
10
+ "files": ["bin/tokenzero.mjs"],
11
+ "engines": { "node": ">=18" },
12
+ "keywords": ["llm", "openai", "anthropic", "gemini", "cost", "finops", "prompt-caching", "mcp"]
13
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.