@bytesbrains/cruise 0.0.0-stage → 0.12.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.
Files changed (41) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +59 -2
  3. package/dist/budget-FIRNSN67.mjs +132 -0
  4. package/dist/chunk-2FB2T3UI.mjs +122 -0
  5. package/dist/chunk-2NVDAK5J.mjs +76 -0
  6. package/dist/chunk-42ERHAJD.mjs +79 -0
  7. package/dist/chunk-4447IUTF.mjs +7 -0
  8. package/dist/chunk-5TVD3ZAI.mjs +69 -0
  9. package/dist/chunk-7NQHBXVZ.mjs +104 -0
  10. package/dist/chunk-BNP63KB2.mjs +42 -0
  11. package/dist/chunk-FGLMW5IY.mjs +575 -0
  12. package/dist/chunk-GUZNI3NS.mjs +267 -0
  13. package/dist/chunk-HQDQTXRX.mjs +57 -0
  14. package/dist/chunk-ICJVJSTC.mjs +42 -0
  15. package/dist/chunk-JZPUTXM7.mjs +236 -0
  16. package/dist/chunk-LALZUKEC.mjs +137 -0
  17. package/dist/chunk-N3YKWKOA.mjs +9 -0
  18. package/dist/chunk-O7TNRKSA.mjs +2 -0
  19. package/dist/chunk-RT4R2W6H.mjs +21 -0
  20. package/dist/chunk-SYTYOTO4.mjs +18 -0
  21. package/dist/chunk-T3ICD43U.mjs +15 -0
  22. package/dist/chunk-THEXUHQC.mjs +98 -0
  23. package/dist/chunk-UNXM6FSM.mjs +83 -0
  24. package/dist/chunk-WS6NFRIU.mjs +66 -0
  25. package/dist/chunk-XOH3XKM3.mjs +126 -0
  26. package/dist/compress-3DWG35BY.mjs +49 -0
  27. package/dist/conformance-NPFDYCQL.mjs +922 -0
  28. package/dist/cruise.mjs +693 -0
  29. package/dist/fallback-P5KK55M4.mjs +139 -0
  30. package/dist/keys-FWPQPMTW.mjs +127 -0
  31. package/dist/ledger-XBGWXY6C.mjs +97 -0
  32. package/dist/member-ZBV4YG2M.mjs +74 -0
  33. package/dist/report-VRYJ3W5L.mjs +414 -0
  34. package/dist/service-key-N2RZ7FMZ.mjs +59 -0
  35. package/dist/smoke-ZNYX6RO5.mjs +105 -0
  36. package/dist/sweep-SZX7OIDK.mjs +33 -0
  37. package/dist/tenant-4YDGI23Q.mjs +122 -0
  38. package/dist/tier-4L3SPLFP.mjs +116 -0
  39. package/package.json +38 -4
  40. package/templates/docker-compose.yml +66 -0
  41. package/templates/env.example +44 -0
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.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # cruise
2
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.
3
+ **One OpenAI-compatible endpoint in front of every model provider**, with per-project keys,
4
+ budgets that stop a runaway loop, a cost ledger every request lands in, and lanes that pick a
5
+ model per request. This package installs and runs [Cruise](https://gitlab.com/bytesbrains-oss/cruise),
6
+ in Docker on your machine or on your own Cloudflare account.
7
+
8
+ Node 22 or later.
9
+
10
+ ## In Docker
11
+
12
+ ```sh
13
+ npx @bytesbrains/cruise up
14
+ ```
15
+
16
+ On first run this asks for your provider keys (input hidden; skip any), writes
17
+ `~/.cruise/docker/`, starts the container, waits until it is healthy, and prints your first API
18
+ key, **once**. Then point any OpenAI SDK at `http://localhost:8787/v1`.
19
+
20
+ Before a model answers, Cruise has to have seen it serve. Measure every model you hold a key
21
+ for, and again weekly:
22
+
23
+ ```sh
24
+ npx @bytesbrains/cruise measure
25
+ ```
26
+
27
+ | | |
28
+ |---|---|
29
+ | `cruise init` | Write `~/.cruise/docker/` and ask for keys, without starting |
30
+ | `cruise up` | Start, or upgrade the running container to new settings |
31
+ | `cruise status`, `cruise logs [-f]` | What is running, and what it said |
32
+ | `cruise backup` | A consistent backup now, into the data volume |
33
+ | `cruise upgrade` | Back up, pull the newest image, restart. The image migrates before it serves |
34
+ | `cruise down` | Stop. The data volume is kept |
35
+ | `cruise measure` | Measure every model you hold a key for |
36
+ | `cruise key:issue`, `budget:set`, `ledger`, `report`, … | Admin, inside the container. `cruise help` lists them |
37
+
38
+ Keys go in `~/.cruise/docker/.env` (mode 0600). Run `cruise up` again after editing it.
39
+ `CRUISE_HOME` moves the whole directory.
40
+
41
+ ## On your own Cloudflare account
42
+
43
+ ```sh
44
+ export CLOUDFLARE_API_TOKEN=… # Workers Scripts, D1, Workers KV Storage and Workers R2 Storage edit; Account Settings read
45
+ npx @bytesbrains/cruise cloudflare deploy --env-file .env
46
+ npx @bytesbrains/cruise cloudflare measure
47
+ ```
48
+
49
+ `deploy` creates the database, cache and bucket, applies the migrations, deploys the Worker,
50
+ sets the secrets and the `PROVIDER_KEY_*` values from `--env-file`, and creates your first tenant
51
+ and key. Run it again to repair a deploy that stopped partway or to update to this package's
52
+ version; it never duplicates anything. `--name` deploys more than one.
53
+
54
+ Every provider is called at its own API, so Workers AI and AI Gateway are not used. Admin
55
+ commands work the same way: `cruise cloudflare ledger --by model`.
56
+
57
+ ## More
58
+
59
+ The manual is [`docs/self-hosting.md`](https://gitlab.com/bytesbrains-oss/cruise/-/blob/main/docs/self-hosting.md).
60
+ Apache-2.0.
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ // Built by packages/cli/build.ts.
3
+ import {
4
+ DEMO_ENVIRONMENT
5
+ } from "./chunk-N3YKWKOA.mjs";
6
+ import {
7
+ demoChargeStatements
8
+ } from "./chunk-RT4R2W6H.mjs";
9
+ import {
10
+ formatUsd,
11
+ readBudget,
12
+ setBudget,
13
+ usdToMicros
14
+ } from "./chunk-THEXUHQC.mjs";
15
+ import "./chunk-LALZUKEC.mjs";
16
+ import {
17
+ connect,
18
+ environmentOf,
19
+ optionalNumber,
20
+ parseArgs,
21
+ requireString,
22
+ run
23
+ } from "./chunk-7NQHBXVZ.mjs";
24
+ import "./chunk-JZPUTXM7.mjs";
25
+
26
+ // scripts/budget.ts
27
+ run(async () => {
28
+ const [command, ...rest] = process.argv.slice(2);
29
+ const args = parseArgs(rest);
30
+ const environment = environmentOf(args);
31
+ const db = connect(environment);
32
+ switch (command) {
33
+ case "set": {
34
+ const project = requireString(args, "project");
35
+ const period = typeof args.period === "string" ? args.period : "day";
36
+ const demoOnly = environment === DEMO_ENVIRONMENT;
37
+ if (period === "minute" && !demoOnly) throw new Error("--period minute is for --env demo only (#494)");
38
+ if (period !== "minute" && period !== "day" && period !== "month") {
39
+ throw new Error("--period must be day or month (or minute, on the demo)");
40
+ }
41
+ const charge = optionalNumber(args, "charge");
42
+ if (charge !== null && !demoOnly) throw new Error("--charge is for --env demo only (#494)");
43
+ const soft = optionalNumber(args, "soft");
44
+ const hard = optionalNumber(args, "hard");
45
+ const actor = requireString(args, "actor");
46
+ const sessionLimit = args["session-limit"] === "none" ? null : optionalNumber(args, "session-limit");
47
+ if (sessionLimit !== null && sessionLimit < 0) throw new Error("--session-limit must be a non-negative number, or none");
48
+ await setBudget(
49
+ db,
50
+ project,
51
+ {
52
+ period,
53
+ softMicros: soft === null ? null : usdToMicros(soft),
54
+ hardMicros: hard === null ? null : usdToMicros(hard),
55
+ // Absent leaves the per-run cap alone; `none` is the explicit clear.
56
+ ...args["session-limit"] === void 0 ? {} : { sessionHardMicros: sessionLimit === null ? null : usdToMicros(sessionLimit) }
57
+ },
58
+ actor,
59
+ charge === null ? [] : demoChargeStatements(db, project, usdToMicros(charge), actor)
60
+ );
61
+ const status = await readBudget(db, project);
62
+ const softLabel = status?.softMicros == null ? "\u2014" : formatUsd(status.softMicros);
63
+ const hardLabel = status?.hardMicros == null ? "UNCAPPED" : formatUsd(status.hardMicros);
64
+ const runLabel = status?.sessionHardMicros == null ? "\u2014" : formatUsd(status.sessionHardMicros);
65
+ console.log(`${project}: soft ${softLabel} hard ${hardLabel} per ${status?.period} per run ${runLabel}`);
66
+ if (charge !== null) console.log(` demo charge ${formatUsd(usdToMicros(charge), 4)} per served request; reservation floor 0`);
67
+ if (status?.hardMicros == null) {
68
+ console.log(" warning: no hard cap. This is the condition that keeps the pipelines switched off.");
69
+ }
70
+ break;
71
+ }
72
+ case "show": {
73
+ const { results } = await db.prepare(`SELECT id FROM projects ORDER BY id`).all();
74
+ console.log("project state spend soft hard at cap");
75
+ for (const { id } of results) {
76
+ const s = await readBudget(db, id);
77
+ if (!s) continue;
78
+ console.log(
79
+ `${id.padEnd(9)} ${s.state.padEnd(7)} ${formatUsd(s.spendMicros, 4).padStart(8)} ${(s.softMicros == null ? "\u2014" : formatUsd(s.softMicros)).padStart(6)} ${(s.hardMicros == null ? "NONE" : formatUsd(s.hardMicros)).padStart(6)} ${s.behaviour}`
80
+ );
81
+ }
82
+ break;
83
+ }
84
+ case "align": {
85
+ const project = requireString(args, "project");
86
+ const day = requireString(args, "day");
87
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error("--day must be YYYY-MM-DD");
88
+ const actor = requireString(args, "actor");
89
+ const apply = args.apply === true || args.apply === "true";
90
+ const counter = await db.prepare(
91
+ `SELECT spend_micros FROM spend
92
+ WHERE scope = 'project' AND subject = ?1 AND period = 'day' AND period_start = ?2`
93
+ ).bind(project, day).first();
94
+ const ledger = await db.prepare(
95
+ `SELECT COALESCE(sum(cost_micros), 0) AS charged FROM ledger
96
+ WHERE project_id = ?1 AND date(at) = ?2`
97
+ ).bind(project, day).first();
98
+ const before = counter?.spend_micros ?? 0;
99
+ const charged = ledger?.charged ?? 0;
100
+ const delta = charged - before;
101
+ console.log(
102
+ `${project} day ${day}: counter ${before} ledger ${charged} delta ${delta}` + (delta === 0 ? " (already aligned)" : "")
103
+ );
104
+ if (delta === 0 || !apply) {
105
+ if (delta !== 0 && !apply) console.log("dry-run; pass --apply to write");
106
+ break;
107
+ }
108
+ await db.batch([
109
+ db.prepare(
110
+ `INSERT INTO spend (scope, subject, period, period_start, spend_micros, request_count)
111
+ VALUES ('project', ?1, 'day', ?2, ?3, 0)
112
+ ON CONFLICT (scope, subject, period, period_start) DO UPDATE
113
+ SET spend_micros = ?3, updated_at = datetime('now')`
114
+ ).bind(project, day, charged),
115
+ db.prepare(
116
+ `INSERT INTO audit_events (id, actor, action, subject, detail, tenant_id)
117
+ SELECT ?1, ?2, 'budget.align', ?3, ?4, (SELECT tenant_id FROM projects WHERE id = ?3)`
118
+ ).bind(
119
+ crypto.randomUUID(),
120
+ actor,
121
+ project,
122
+ JSON.stringify({ day, before_micros: before, after_micros: charged, delta_micros: delta })
123
+ )
124
+ ]);
125
+ console.log(`aligned to ${charged}`);
126
+ break;
127
+ }
128
+ default:
129
+ console.error("usage: show | set | align (see scripts/budget.ts)");
130
+ process.exitCode = 1;
131
+ }
132
+ });
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ // Built by packages/cli/build.ts.
3
+ import {
4
+ DEFAULT_CACHE_POOL
5
+ } from "./chunk-T3ICD43U.mjs";
6
+ import {
7
+ generateKey,
8
+ keyRateLimitFor
9
+ } from "./chunk-5TVD3ZAI.mjs";
10
+
11
+ // src/admin.ts
12
+ function scopeProblem(entries, what) {
13
+ if (!Array.isArray(entries)) return `'${what}' must be an array of strings.`;
14
+ if (entries.some((entry) => typeof entry !== "string" || entry.trim() === "")) {
15
+ return `'${what}' has an empty entry. An unset variable reads exactly like this, and a blank is not a scope: omit the field for an unrestricted key.`;
16
+ }
17
+ return null;
18
+ }
19
+ function rateLimitProblem(value, what) {
20
+ if (value === void 0 || value === null) return null;
21
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
22
+ return `'${what}' must be a positive integer. Omit the field, or send null, for no limit on that axis.`;
23
+ }
24
+ return null;
25
+ }
26
+ async function platformPoolProblem(db, projectId) {
27
+ const row = await db.prepare(
28
+ `SELECT t.operator FROM projects p JOIN tenants t ON t.id = p.tenant_id WHERE p.id = ?`
29
+ ).bind(projectId).first();
30
+ if (row?.operator === 1) return null;
31
+ return `'${projectId}' does not belong to the tenant that operates Cruise, so a key for it cannot carry the 'platform' cache pool: that pool is read by every project we operate. Use 'tenant' to share within this tenant.`;
32
+ }
33
+ function canonicalScope(entries, what) {
34
+ const problem = scopeProblem(entries ?? [], what);
35
+ if (problem !== null) throw new Error(problem);
36
+ return [...new Set((entries ?? []).map((entry) => entry.trim()))];
37
+ }
38
+ async function issueKey(db, request) {
39
+ const allowedModels = canonicalScope(request.allowedModels, "models");
40
+ const allowedClasses = canonicalScope(request.allowedClasses, "classes");
41
+ const project = await db.prepare(`SELECT id FROM projects WHERE id = ? AND tenant_id = ?`).bind(request.projectId, request.tenantId).first();
42
+ if (project === null) throw new Error(`No such project: ${request.projectId}`);
43
+ const cachePool = request.cachePool ?? DEFAULT_CACHE_POOL;
44
+ if (cachePool === "platform") {
45
+ const problem = await platformPoolProblem(db, project.id);
46
+ if (problem !== null) throw new Error(problem);
47
+ }
48
+ const generated = await generateKey(request.environment);
49
+ const keyId = crypto.randomUUID();
50
+ const rateLimitPerMin = keyRateLimitFor(request.environment, request.rateLimitPerMin);
51
+ const accountRateLimitPerMin = request.accountRateLimitPerMin ?? null;
52
+ const statements = [
53
+ db.prepare(
54
+ `INSERT INTO virtual_keys
55
+ (id, project_id, name, prefix, key_hash, created_by,
56
+ rate_limit_per_min, account_rate_limit_per_min,
57
+ conformance, cache_pool, revoked_at, revoked_reason)
58
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), 'provisioning')`
59
+ ).bind(
60
+ keyId,
61
+ project.id,
62
+ request.name ?? null,
63
+ generated.prefix,
64
+ generated.hash,
65
+ request.actor,
66
+ rateLimitPerMin,
67
+ accountRateLimitPerMin,
68
+ request.conformance ? 1 : 0,
69
+ cachePool
70
+ )
71
+ ];
72
+ for (const model of allowedModels) {
73
+ statements.push(
74
+ db.prepare(`INSERT INTO key_allowed_models (key_id, model) VALUES (?, ?)`).bind(keyId, model)
75
+ );
76
+ }
77
+ for (const trafficClass of allowedClasses) {
78
+ statements.push(
79
+ db.prepare(`INSERT INTO key_allowed_classes (key_id, class) VALUES (?, ?)`).bind(keyId, trafficClass)
80
+ );
81
+ }
82
+ statements.push(
83
+ db.prepare(
84
+ `INSERT INTO audit_events (id, actor, action, subject, detail, tenant_id)
85
+ SELECT ?1, ?2, 'key.issue', ?3, ?4, (SELECT tenant_id FROM projects WHERE id = ?5)`
86
+ ).bind(
87
+ crypto.randomUUID(),
88
+ request.actor,
89
+ generated.prefix,
90
+ JSON.stringify({ project: project.id, cache_pool: cachePool }),
91
+ project.id
92
+ )
93
+ );
94
+ statements.push(
95
+ db.prepare(`UPDATE virtual_keys SET revoked_at = NULL, revoked_reason = NULL WHERE id = ?`).bind(keyId)
96
+ );
97
+ await db.batch(statements);
98
+ return { keyId, prefix: generated.prefix, key: generated.key, rateLimitPerMin, accountRateLimitPerMin };
99
+ }
100
+ async function revokeKey(db, request) {
101
+ const { tenantId, prefix, actor, reason } = request;
102
+ const result = await db.prepare(
103
+ `UPDATE virtual_keys
104
+ SET revoked_at = datetime('now'), revoked_by = ?, revoked_reason = ?
105
+ WHERE prefix = ? AND revoked_at IS NULL
106
+ AND project_id IN (SELECT id FROM projects WHERE tenant_id = ?)`
107
+ ).bind(actor, reason, prefix, tenantId).run();
108
+ const changed = (result.meta.changes ?? 0) > 0;
109
+ if (changed) {
110
+ await db.prepare(
111
+ `INSERT INTO audit_events (id, actor, action, subject, reason, tenant_id)
112
+ VALUES (?, ?, 'key.revoke', ?, ?, ?)`
113
+ ).bind(crypto.randomUUID(), actor, prefix, reason, tenantId).run();
114
+ }
115
+ return changed;
116
+ }
117
+
118
+ export {
119
+ rateLimitProblem,
120
+ issueKey,
121
+ revokeKey
122
+ };
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ // Built by packages/cli/build.ts.
3
+
4
+ // src/membership.ts
5
+ var ROLES = ["owner", "admin", "viewer"];
6
+ var MAX_UID_LENGTH = 128;
7
+ function assertUid(uid) {
8
+ const trimmed = uid.trim();
9
+ if (trimmed === "") throw new Error("uid cannot be empty");
10
+ if (trimmed.length > MAX_UID_LENGTH) {
11
+ throw new Error(`uid cannot exceed ${MAX_UID_LENGTH} characters`);
12
+ }
13
+ return trimmed;
14
+ }
15
+ async function grantMembership(db, rawUid, tenantId, role, actor) {
16
+ const uid = assertUid(rawUid);
17
+ if (!ROLES.includes(role)) throw new Error(`Unknown role: ${role}`);
18
+ const tenant = await db.prepare(`SELECT id FROM tenants WHERE id = ?`).bind(tenantId).first();
19
+ if (tenant === null) throw new Error(`No such tenant: ${tenantId}`);
20
+ await db.batch([
21
+ // Re-granting changes the role rather than failing, because "make Alice an
22
+ // admin" and "Alice is already a viewer" should not be two different
23
+ // operations for whoever is doing it.
24
+ db.prepare(
25
+ `INSERT INTO memberships (uid, tenant_id, role, created_by) VALUES (?1, ?2, ?3, ?4)
26
+ ON CONFLICT (uid, tenant_id) DO UPDATE SET role = ?3, created_by = ?4`
27
+ ).bind(uid, tenantId, role, actor),
28
+ db.prepare(
29
+ `INSERT INTO audit_events (id, actor, action, subject, detail, tenant_id)
30
+ VALUES (?, ?, 'membership.grant', ?, ?, ?)`
31
+ ).bind(crypto.randomUUID(), actor, uid, JSON.stringify({ tenant: tenantId, role }), tenantId)
32
+ ]);
33
+ }
34
+ async function revokeMembership(db, uid, tenantId, actor, reason) {
35
+ const result = await db.prepare(
36
+ `DELETE FROM memberships
37
+ WHERE uid = ?1 AND tenant_id = ?2
38
+ AND NOT (
39
+ role = 'owner'
40
+ AND (SELECT count(*) FROM memberships WHERE tenant_id = ?2 AND role = 'owner') <= 1
41
+ )`
42
+ ).bind(uid, tenantId).run();
43
+ if ((result.meta.changes ?? 0) > 0) {
44
+ await db.prepare(
45
+ `INSERT INTO audit_events (id, actor, action, subject, reason, tenant_id)
46
+ VALUES (?, ?, 'membership.revoke', ?, ?, ?)`
47
+ ).bind(crypto.randomUUID(), actor, uid, reason, tenantId).run();
48
+ return "revoked";
49
+ }
50
+ const still = await db.prepare(`SELECT 1 AS ok FROM memberships WHERE uid = ? AND tenant_id = ?`).bind(uid, tenantId).first();
51
+ return still === null ? "not_found" : "last_owner";
52
+ }
53
+ async function listMemberships(db, tenantId) {
54
+ const statement = tenantId ? db.prepare(
55
+ `SELECT uid, tenant_id, role, created_at, created_by FROM memberships
56
+ WHERE tenant_id = ? ORDER BY created_at`
57
+ ).bind(tenantId) : db.prepare(
58
+ `SELECT uid, tenant_id, role, created_at, created_by FROM memberships ORDER BY tenant_id, created_at`
59
+ );
60
+ const { results } = await statement.all();
61
+ return results.map((row) => ({
62
+ uid: row.uid,
63
+ tenantId: row.tenant_id,
64
+ role: row.role,
65
+ createdAt: row.created_at,
66
+ createdBy: row.created_by
67
+ }));
68
+ }
69
+
70
+ export {
71
+ ROLES,
72
+ assertUid,
73
+ grantMembership,
74
+ revokeMembership,
75
+ listMemberships
76
+ };
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ // Built by packages/cli/build.ts.
3
+
4
+ // src/ledger-lanes.ts
5
+ async function laneSavings(db, month, tenantId, laneId) {
6
+ const scope = "AND (?2 IS NULL OR l.tenant_id = ?2) AND (?3 IS NULL OR l.lane = ?3)";
7
+ const statement = db.prepare(
8
+ `WITH lane_requests AS (
9
+ SELECT l.id, l.lane, l.model, l.cost_micros, l.list_micros, l.cache_status
10
+ FROM ledger l
11
+ WHERE (?1 IS NULL OR strftime('%Y-%m', l.at) = ?1) AND l.priced = 1
12
+ AND l.requested_model = l.lane
13
+ -- A lane request is one whose requested model IS a lane, checked
14
+ -- against the table rather than by prefix. This read
15
+ -- 'l.lane LIKE bb/%', written when every lane was ours and left there
16
+ -- when 0028 gave tenants their own -- so a tenant lane's savings, the
17
+ -- receipt that is the entire reason to put config in a lane, came
18
+ -- back empty. The lane column is caller-influenced (x-cruise-lane),
19
+ -- so the existence check also keeps a spoofed header out.
20
+ AND EXISTS (SELECT 1 FROM lanes ln WHERE ln.id = l.lane) ${scope}
21
+ ),
22
+ dearest AS (
23
+ SELECT a.ledger_id, max(a.cost_micros) AS cost
24
+ FROM lane_alternatives a WHERE a.priced = 1 GROUP BY a.ledger_id
25
+ ),
26
+ reference AS (
27
+ SELECT a.ledger_id, a.cost_micros AS cost
28
+ FROM lane_alternatives a
29
+ JOIN lane_requests r ON r.id = a.ledger_id
30
+ JOIN lane_members m ON m.lane_id = r.lane AND m.model_id = a.model AND m.position = 1
31
+ WHERE a.priced = 1
32
+ ),
33
+ selection AS (
34
+ SELECT r.lane AS lane,
35
+ count(*) AS requests,
36
+ sum(r.cost_micros) AS spentMicros,
37
+ sum(d.cost) AS dearestMicros,
38
+ sum(coalesce(ref.cost, 0)) AS referenceMicros,
39
+ count(ref.cost) AS referenceRequests,
40
+ -- From the same scoped set as every other column. A separate
41
+ -- subquery here once read the whole ledger, which for a tenant-scoped
42
+ -- caller counted other tenants' members. Raised in review of PR #63.
43
+ count(DISTINCT r.model) AS membersUsed
44
+ FROM lane_requests r
45
+ -- Only requests whose alternatives were recorded. A lane request from
46
+ -- before 0027 has none, and counting it as "saved nothing" would drag
47
+ -- every percentage toward zero while looking like a measurement.
48
+ JOIN dearest d ON d.ledger_id = r.id
49
+ LEFT JOIN reference ref ON ref.ledger_id = r.id
50
+ GROUP BY r.lane
51
+ ),
52
+ -- The cache's own term (#281): a hit reaches no provider and records no
53
+ -- alternatives, so it is outside the selection comparison above and
54
+ -- counted here from the same scoped set, against list.
55
+ cache AS (
56
+ SELECT r.lane AS lane, count(*) AS cacheHits, sum(r.list_micros - r.cost_micros) AS cacheMicros
57
+ FROM lane_requests r WHERE r.cache_status = 'HIT' GROUP BY r.lane
58
+ )
59
+ SELECT lanes.lane AS lane,
60
+ coalesce(s.requests, 0) AS requests,
61
+ coalesce(s.spentMicros, 0) AS spentMicros,
62
+ coalesce(s.dearestMicros, 0) AS dearestMicros,
63
+ coalesce(s.referenceMicros, 0) AS referenceMicros,
64
+ coalesce(s.referenceRequests, 0) AS referenceRequests,
65
+ coalesce(s.membersUsed, 0) AS membersUsed,
66
+ coalesce(c.cacheHits, 0) AS cacheHits,
67
+ coalesce(c.cacheMicros, 0) AS cacheMicros
68
+ FROM (SELECT lane FROM selection UNION SELECT lane FROM cache) lanes
69
+ LEFT JOIN selection s ON s.lane = lanes.lane
70
+ LEFT JOIN cache c ON c.lane = lanes.lane
71
+ ORDER BY lanes.lane`
72
+ );
73
+ const { results } = await statement.bind(month, tenantId ?? null, laneId ?? null).all();
74
+ return results;
75
+ }
76
+
77
+ export {
78
+ laneSavings
79
+ };