@bytesbrains/cruise-worker 0.0.0-stage → 0.12.1

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 (137) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +37 -2
  3. package/index.d.ts +14 -0
  4. package/index.mjs +41 -0
  5. package/migrations/0001_virtual_keys.sql +102 -0
  6. package/migrations/0002_seed_projects.sql +16 -0
  7. package/migrations/0003_budgets.sql +43 -0
  8. package/migrations/0004_tenant_isolation_and_integer_money.sql +49 -0
  9. package/migrations/0005_model_prices.sql +42 -0
  10. package/migrations/0006_budget_reservation.sql +38 -0
  11. package/migrations/0007_routing_table.sql +93 -0
  12. package/migrations/0008_measurement_provenance.sql +24 -0
  13. package/migrations/0009_conformance.sql +37 -0
  14. package/migrations/0010_conformance_key.sql +20 -0
  15. package/migrations/0011_correct_workers_ai_price.sql +30 -0
  16. package/migrations/0012_rate_limits.sql +28 -0
  17. package/migrations/0013_deepseek_and_mistral.sql +42 -0
  18. package/migrations/0014_cost_ledger.sql +104 -0
  19. package/migrations/0015_memberships.sql +33 -0
  20. package/migrations/0016_latency.sql +23 -0
  21. package/migrations/0017_ledger_provider_index.sql +8 -0
  22. package/migrations/0018_fallback_chains.sql +34 -0
  23. package/migrations/0019_rate_buckets.sql +27 -0
  24. package/migrations/0020_mistral_price_and_pin.sql +62 -0
  25. package/migrations/0021_mistral_price_date_is_utc.sql +35 -0
  26. package/migrations/0022_drop_unenforced_key_budget.sql +32 -0
  27. package/migrations/0023_model_limits.sql +48 -0
  28. package/migrations/0024_conditional_prices.sql +84 -0
  29. package/migrations/0025_catalogue_from_keyed_hosts.sql +172 -0
  30. package/migrations/0026_lanes.sql +83 -0
  31. package/migrations/0027_lane_alternatives.sql +36 -0
  32. package/migrations/0028_lanes_tenant_scope.sql +66 -0
  33. package/migrations/0029_lane_jobs.sql +146 -0
  34. package/migrations/0030_lane_requires.sql +38 -0
  35. package/migrations/0031_tenant_billable.sql +15 -0
  36. package/migrations/0032_cache_hit_billing.sql +35 -0
  37. package/migrations/0033_sell_markup.sql +37 -0
  38. package/migrations/0034_tiers_and_lane_quotas.sql +38 -0
  39. package/migrations/0035_wallet_scope.sql +68 -0
  40. package/migrations/0036_credit_grants.sql +53 -0
  41. package/migrations/0037_reconciliation.sql +45 -0
  42. package/migrations/0038_balance_service_keys.sql +35 -0
  43. package/migrations/0039_deepseek_peak_is_weekdays.sql +77 -0
  44. package/migrations/0040_glm_5_3_on_workers_ai.sql +63 -0
  45. package/migrations/0041_mistral_sweep_2026_08_29.sql +89 -0
  46. package/migrations/0042_provision_service_keys.sql +50 -0
  47. package/migrations/0043_tier_project_quota.sql +32 -0
  48. package/migrations/0044_audit_tenant_scope.sql +49 -0
  49. package/migrations/0045_audit_backfill_derivable.sql +42 -0
  50. package/migrations/0046_measurement_note.sql +24 -0
  51. package/migrations/0047_ledger_max_tokens.sql +21 -0
  52. package/migrations/0048_price_observations.sql +140 -0
  53. package/migrations/0049_openai_and_gemini.sql +239 -0
  54. package/migrations/0050_meta_direct_upstream.sql +127 -0
  55. package/migrations/0051_upstream_credential_and_operator.sql +74 -0
  56. package/migrations/0052_muse_spark_1_3.sql +71 -0
  57. package/migrations/0053_anthropic_groq_and_xai.sql +172 -0
  58. package/migrations/0054_tier_service_keys.sql +60 -0
  59. package/migrations/0055_output_defaults.sql +79 -0
  60. package/migrations/0056_model_modality.sql +37 -0
  61. package/migrations/0057_openai_image_models.sql +177 -0
  62. package/migrations/0058_price_components.sql +230 -0
  63. package/migrations/0059_speech.sql +151 -0
  64. package/migrations/0060_embeddings.sql +131 -0
  65. package/migrations/0061_data_retention_backfill.sql +121 -0
  66. package/migrations/0062_gemini_embedding_disabled.sql +125 -0
  67. package/migrations/0063_google_provider_path_prefix.sql +59 -0
  68. package/migrations/0064_economics_service_keys.sql +51 -0
  69. package/migrations/0065_lane_selection.sql +66 -0
  70. package/migrations/0066_tenant_default_selection.sql +42 -0
  71. package/migrations/0067_graduated_selection.sql +103 -0
  72. package/migrations/0068_cache_scope.sql +73 -0
  73. package/migrations/0069_lane_cache_settings.sql +50 -0
  74. package/migrations/0070_lane_member_quality_rank.sql +98 -0
  75. package/migrations/0071_key_cache_pool.sql +60 -0
  76. package/migrations/0072_cache_digest.sql +51 -0
  77. package/migrations/0073_lane_max_chain.sql +51 -0
  78. package/migrations/0074_hunter_builder_lanes.sql +149 -0
  79. package/migrations/0075_hunter_builder_frontline.sql +36 -0
  80. package/migrations/0076_deepseek_flash.sql +86 -0
  81. package/migrations/0077_gpt_6_astra.sql +35 -0
  82. package/migrations/0078_astra_deep_reasoning.sql +20 -0
  83. package/migrations/0079_gemini_flash_lite_extraction.sql +15 -0
  84. package/migrations/0080_priced_by.sql +24 -0
  85. package/migrations/0081_grok_imagine.sql +81 -0
  86. package/migrations/0082_markup_three_percent.sql +32 -0
  87. package/migrations/0083_markup_per_tenant_and_tier.sql +57 -0
  88. package/migrations/0084_coding_lanes_frontier.sql +93 -0
  89. package/migrations/0085_minute_period_and_demo_charge.sql +77 -0
  90. package/migrations/0086_project_sentry.sql +41 -0
  91. package/migrations/0087_lane_router.sql +71 -0
  92. package/migrations/0088_openai_frontier_coding_lanes.sql +54 -0
  93. package/migrations/0089_agentic_coding_drops_codestral.sql +44 -0
  94. package/migrations/0090_board_followups_2026_10.sql +196 -0
  95. package/migrations/0091_opus_5_5_coding_lanes.sql +43 -0
  96. package/migrations/0092_deepseek_peak_holidays.sql +83 -0
  97. package/migrations/0093_tool_choice_forced.sql +26 -0
  98. package/migrations/0094_board_followups_2026_10_08.sql +115 -0
  99. package/migrations/0095_request_compression.sql +43 -0
  100. package/migrations/0096_lane_compress.sql +36 -0
  101. package/migrations/0097_tenant_default_compress.sql +34 -0
  102. package/migrations/0098_ledger_session.sql +47 -0
  103. package/migrations/0099_wallet_low_water_backfill.sql +47 -0
  104. package/migrations/0100_rag_grounded_answers_lane.sql +92 -0
  105. package/migrations/0101_perplexity_agent_api.sql +125 -0
  106. package/migrations/0102_web_search_job_and_flag.sql +137 -0
  107. package/migrations/0103_openai_web_search_price.sql +44 -0
  108. package/migrations/0104_web_search_lane.sql +82 -0
  109. package/migrations/0105_web_search_lane_billed.sql +22 -0
  110. package/migrations/0106_reservations_journal.sql +64 -0
  111. package/migrations/0107_session_cap.sql +65 -0
  112. package/migrations/0108_ledger_attempts.sql +41 -0
  113. package/migrations/0109_gemini_retention.sql +39 -0
  114. package/migrations/0110_gemini_4_argon.sql +110 -0
  115. package/migrations/0111_gemini_4_argon_lanes.sql +80 -0
  116. package/migrations/0112_ledger_affinity.sql +42 -0
  117. package/migrations/0113_contributor_lane_namespace.sql +125 -0
  118. package/migrations/0114_meta_contributor_models.sql +55 -0
  119. package/migrations/0115_oss_chat_assistant_lane.sql +41 -0
  120. package/migrations/0116_promo_credits.sql +63 -0
  121. package/migrations/0117_oss_mirror_lanes.sql +85 -0
  122. package/migrations/0118_project_management_job.sql +112 -0
  123. package/migrations/0119_oss_project_management_lane.sql +29 -0
  124. package/migrations/0120_moonshot_k3_1_pro.sql +107 -0
  125. package/migrations/0121_jobs.sql +100 -0
  126. package/migrations/0122_batch_prices.sql +188 -0
  127. package/migrations/0123_batch_files.sql +50 -0
  128. package/migrations/0124_batch_run.sql +21 -0
  129. package/migrations/0125_anthropic_path_prefix.sql +22 -0
  130. package/package.json +37 -4
  131. package/worker/284906b51fc0a3173ea7d301234907f30e834f54-cruise-mark-64.png +0 -0
  132. package/worker/2c39de526314484775fdfc503fac50c437d21e4e-cruise-logo-240.png +0 -0
  133. package/worker/63fb63e2d8ae6d8b68228768ef6c91ab8f0c0100-cruise-logo-480.png +0 -0
  134. package/worker/VERSION +1 -0
  135. package/worker/b23bfbc792e8710d3b74284a0a1b8ab044c18897-logo-dark.png +0 -0
  136. package/worker/index.js +31451 -0
  137. package/wrangler.template.jsonc +48 -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,38 @@
1
- # Temporary Holding Version
1
+ # @bytesbrains/cruise-worker
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
+ The [Cruise](https://gitlab.com/bytesbrains-oss/cruise) Worker, built and ready to deploy to
4
+ your own Cloudflare account: one OpenAI-compatible endpoint in front of every model provider,
5
+ with per-project keys, budgets that stop, and a cost ledger for every request.
6
+
7
+ This is the deployable artifact, not a library. It holds:
8
+
9
+ | | |
10
+ |---|---|
11
+ | `worker/` | The bundle `wrangler deploy` produces, for `no_bundle` deploys |
12
+ | `migrations/` | Every migration as SQL, in order |
13
+ | `wrangler.template.jsonc` | A complete config for this version: bindings, compatibility date, vars |
14
+ | `index.mjs` | The same paths and settings, for scripts that write their own config |
15
+
16
+ ## Deploy
17
+
18
+ ```sh
19
+ npm install @bytesbrains/cruise-worker@<version>
20
+ cp node_modules/@bytesbrains/cruise-worker/wrangler.template.jsonc wrangler.jsonc # fill in every <…>
21
+ npx wrangler d1 migrations apply <database> --remote # always before the Worker
22
+ npx wrangler deploy
23
+ ```
24
+
25
+ **Pin an exact version.** A release can carry migrations, and its Worker reads their columns, so
26
+ the order is always: apply that version's migrations, then deploy that version's Worker.
27
+
28
+ For a deploy that creates everything for you, see the `cruise` CLI
29
+ (`npx @bytesbrains/cruise cloudflare deploy`). To run Cruise without Cloudflare, see the
30
+ Docker image. Both run this same bundle.
31
+
32
+ ## In a script
33
+
34
+ ```js
35
+ import { mainModule, workerDir, migrationsDir, compatibilityDate, bindings } from "@bytesbrains/cruise-worker";
36
+ ```
37
+
38
+ Apache-2.0.
package/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export declare const packageDir: string;
2
+ export declare const workerDir: string;
3
+ export declare const mainModule: string;
4
+ export declare const migrationsDir: string;
5
+ export declare const compatibilityDate: string;
6
+ export declare const compatibilityFlags: readonly string[];
7
+ export declare const bindings: {
8
+ readonly d1: readonly string[];
9
+ readonly kv: readonly string[];
10
+ readonly r2: readonly string[];
11
+ readonly workflows: readonly { binding: string; className: string }[];
12
+ readonly analyticsEngine: readonly string[];
13
+ readonly versionMetadata: "CF_VERSION_METADATA";
14
+ };
package/index.mjs ADDED
@@ -0,0 +1,41 @@
1
+ // packages/worker/src/index.ts
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ // selfhost/worker-config.ts
6
+ var COMPATIBILITY_DATE = "2026-08-13";
7
+ var COMPATIBILITY_FLAGS = ["nodejs_compat"];
8
+ var STORAGE = {
9
+ d1: { DB: "cruise" },
10
+ kv: { CACHE: "cruise-cache" },
11
+ r2: { BATCH_FILES: "cruise-batch-files" },
12
+ workflows: { BATCH_WORKFLOW: { name: "cruise-batch", className: "BatchWorkflow" } },
13
+ analytics: { METRICS: { dataset: "cruise_requests" } }
14
+ };
15
+
16
+ // packages/worker/src/index.ts
17
+ var here = import.meta.dirname;
18
+ var root = existsSync(path.join(here, "package.json")) ? here : path.join(here, "..");
19
+ var packageDir = root;
20
+ var workerDir = path.join(root, "worker");
21
+ var mainModule = path.join(root, "worker", "index.js");
22
+ var migrationsDir = path.join(root, "migrations");
23
+ var compatibilityDate = COMPATIBILITY_DATE;
24
+ var compatibilityFlags = COMPATIBILITY_FLAGS;
25
+ var bindings = {
26
+ d1: Object.keys(STORAGE.d1),
27
+ kv: Object.keys(STORAGE.kv),
28
+ r2: Object.keys(STORAGE.r2),
29
+ workflows: Object.entries(STORAGE.workflows).map(([binding, w]) => ({ binding, className: w.className })),
30
+ analyticsEngine: Object.keys(STORAGE.analytics),
31
+ versionMetadata: "CF_VERSION_METADATA"
32
+ };
33
+ export {
34
+ bindings,
35
+ compatibilityDate,
36
+ compatibilityFlags,
37
+ mainModule,
38
+ migrationsDir,
39
+ packageDir,
40
+ workerDir
41
+ };
@@ -0,0 +1,102 @@
1
+ -- Virtual per-project API keys (#4). Spec: docs/v0.md §3 component 2, §4.
2
+ --
3
+ -- D1 rather than KV, deliberately: revocation needs read-after-write consistency,
4
+ -- and a revoked key that keeps working for a propagation window is a security
5
+ -- control that does not work.
6
+
7
+ -- Tenants exist from the first migration even while there is exactly one value,
8
+ -- per v0.md §2 — a product that happens to have one tenant is not allowed to defer this.
9
+ CREATE TABLE tenants (
10
+ id TEXT PRIMARY KEY,
11
+ name TEXT NOT NULL,
12
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
13
+ );
14
+
15
+ CREATE TABLE projects (
16
+ id TEXT PRIMARY KEY,
17
+ tenant_id TEXT NOT NULL REFERENCES tenants(id),
18
+ slug TEXT NOT NULL,
19
+ name TEXT NOT NULL,
20
+
21
+ -- Which gateway this project's traffic goes to. A property of who is calling,
22
+ -- never a per-request flag anyone can get wrong (v0.md §4). Retention-off is the
23
+ -- default, and logging is what a project opts into.
24
+ gateway TEXT NOT NULL DEFAULT 'gw-sensitive'
25
+ CHECK (gateway IN ('gw-sensitive', 'gw-internal')),
26
+
27
+ -- Behaviour at the budget ceiling (v0.md §1). User-facing projects degrade and keep
28
+ -- serving; internal pipelines refuse loudly because nobody is waiting.
29
+ -- v0 ships only the refusal path — full degradation needs auto mode — so this
30
+ -- records intent that phase 1b will honour.
31
+ budget_behaviour TEXT NOT NULL DEFAULT 'refuse'
32
+ CHECK (budget_behaviour IN ('degrade', 'refuse')),
33
+
34
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
35
+ UNIQUE (tenant_id, slug)
36
+ );
37
+
38
+ CREATE TABLE virtual_keys (
39
+ id TEXT PRIMARY KEY,
40
+ tenant_id TEXT NOT NULL REFERENCES tenants(id),
41
+ project_id TEXT NOT NULL REFERENCES projects(id),
42
+ name TEXT,
43
+
44
+ -- Non-secret. Identifies a key in logs and error messages without the log
45
+ -- becoming a place credentials live.
46
+ prefix TEXT NOT NULL UNIQUE,
47
+
48
+ -- SHA-256 of the whole key. A fast hash is the correct choice here precisely
49
+ -- because these are not passwords: the secret is 192 bits of CSPRNG output, so
50
+ -- there is no low-entropy guessing attack for a KDF to slow down.
51
+ key_hash TEXT NOT NULL,
52
+
53
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
54
+ created_by TEXT,
55
+ last_used_at TEXT,
56
+ revoked_at TEXT,
57
+ revoked_by TEXT,
58
+ revoked_reason TEXT,
59
+
60
+ -- Enforced per project in phase 1 (#7).
61
+ rate_limit_per_min INTEGER,
62
+ budget_usd_month REAL,
63
+
64
+ -- Carried from the first migration, enforced later. Decided 2026-08-13: adding
65
+ -- this to a live ledger at the moment an open-signup product needs it is the
66
+ -- expensive version of the same change.
67
+ account_rate_limit_per_min INTEGER
68
+ );
69
+
70
+ CREATE INDEX idx_virtual_keys_project ON virtual_keys (project_id);
71
+ CREATE INDEX idx_virtual_keys_tenant ON virtual_keys (tenant_id);
72
+
73
+ -- Allowed models. No rows means unrestricted; a row set means exactly that set.
74
+ -- Capabilities are recorded per model rather than per upstream (v0.md §3), so a key
75
+ -- that needs tools must never be routed to a model that silently lacks them.
76
+ CREATE TABLE key_allowed_models (
77
+ key_id TEXT NOT NULL REFERENCES virtual_keys(id) ON DELETE CASCADE,
78
+ model TEXT NOT NULL,
79
+ PRIMARY KEY (key_id, model)
80
+ );
81
+
82
+ -- Traffic classes this key may declare (#6). A key cannot label its own traffic
83
+ -- as something it was not scoped for, or the segmented report in v0.md §7 is fiction.
84
+ CREATE TABLE key_allowed_classes (
85
+ key_id TEXT NOT NULL REFERENCES virtual_keys(id) ON DELETE CASCADE,
86
+ class TEXT NOT NULL,
87
+ PRIMARY KEY (key_id, class)
88
+ );
89
+
90
+ -- Audit. #13 requires that opting a project into logging records who did it and
91
+ -- why; key issue and revocation belong in the same place for the same reason.
92
+ CREATE TABLE audit_events (
93
+ id TEXT PRIMARY KEY,
94
+ at TEXT NOT NULL DEFAULT (datetime('now')),
95
+ actor TEXT NOT NULL,
96
+ action TEXT NOT NULL,
97
+ subject TEXT NOT NULL,
98
+ reason TEXT,
99
+ detail TEXT
100
+ );
101
+
102
+ CREATE INDEX idx_audit_subject ON audit_events (subject);
@@ -0,0 +1,16 @@
1
+ -- Originally the first deployment's tenant and its projects, seeded here so the
2
+ -- schema could be exercised from day one with one tenant modelled as one of many
3
+ -- (v0.md §2).
4
+ --
5
+ -- The open-source release seeds nothing: a deployment starts with no tenants and
6
+ -- creates its own with `npm run tenant:provision`, which writes the project and its
7
+ -- budget in one batch. The file stays so migration numbering matches every
8
+ -- database that has already applied it. Tests load equivalent rows from
9
+ -- test/fixtures/seed.ts instead.
10
+ --
11
+ -- Gateway and budget behaviour per v0.md §1 and §4 still describe what a project
12
+ -- should be given: retention-off (`gw-sensitive`) is the default and logging is the
13
+ -- exception a project opts into; user-facing projects degrade at the ceiling while
14
+ -- internal pipelines refuse loudly.
15
+
16
+ SELECT 1;
@@ -0,0 +1,43 @@
1
+ -- Budgets and spend accounting (#7). Spec: docs/v0.md §1, §3 component 6, §4.
2
+ --
3
+ -- This is the feature the agentic pipelines are switched off waiting for, so the
4
+ -- bar is a correctness property rather than a dashboard setting.
5
+ --
6
+ -- Two halves, deliberately. The gateway's cost node is the authoritative stop
7
+ -- because it sees real upstream cost; these tables are what makes the soft threshold
8
+ -- *readable by the Worker*, which #7 requires and a dashboard-only budget cannot
9
+ -- provide. They also carry the per-project degrade-or-refuse decision.
10
+
11
+ CREATE TABLE project_budgets (
12
+ project_id TEXT PRIMARY KEY REFERENCES projects(id),
13
+
14
+ period TEXT NOT NULL DEFAULT 'day' CHECK (period IN ('day', 'month')),
15
+
16
+ -- Warn here; keep serving. Null means no soft threshold.
17
+ soft_usd REAL,
18
+ -- Stop here. Null means uncapped, which is the state that made the pipelines
19
+ -- unsafe to switch on in the first place.
20
+ hard_usd REAL,
21
+
22
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
23
+ updated_by TEXT
24
+ );
25
+
26
+ -- Running spend per project per period. Written from response usage rather than
27
+ -- from what the client submitted: v0.md §7 found devstral reporting 1,230 prompt tokens
28
+ -- for a ~10-token message, so the ledger must attribute what the upstream bills.
29
+ CREATE TABLE project_spend (
30
+ project_id TEXT NOT NULL REFERENCES projects(id),
31
+ period TEXT NOT NULL CHECK (period IN ('day', 'month')),
32
+ period_start TEXT NOT NULL,
33
+ spend_usd REAL NOT NULL DEFAULT 0,
34
+ request_count INTEGER NOT NULL DEFAULT 0,
35
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
36
+ PRIMARY KEY (project_id, period, period_start)
37
+ );
38
+
39
+ -- Starting limits were seeded here for the first deployment's projects. The
40
+ -- open-source release seeds none (see 0002): `tenant:provision` writes a budget in
41
+ -- the same batch as the project, because a project with no budget row is uncapped
42
+ -- and serving. Keep a new project's first cap deliberately low: a cap that is wrong
43
+ -- stops a job, while an absent cap is the unbounded liability v0.md §1 describes.
@@ -0,0 +1,49 @@
1
+ -- Two corrections from review of PR #23.
2
+ --
3
+ -- 1. Tenant isolation was not enforced by the schema.
4
+ --
5
+ -- `virtual_keys` carried its own `tenant_id` alongside `project_id`, with a
6
+ -- foreign key on each and nothing tying them together. A row could name tenant A
7
+ -- and a project belonging to tenant B, and every later authorization decision
8
+ -- trusts that column. v0.md §2 calls tenant isolation a day-one constraint rather than
9
+ -- phase-4 work, and a constraint the database does not enforce is a convention.
10
+ --
11
+ -- Fixed by deleting the redundancy rather than constraining it. A key belongs to
12
+ -- a project, and a project belongs to a tenant; there is now exactly one path to
13
+ -- that fact, so the two cannot disagree. A composite foreign key would also have
14
+ -- worked, but it keeps a denormalisation whose only purpose was to save a join
15
+ -- that `resolveVirtualKey` already performs.
16
+ DROP INDEX idx_virtual_keys_tenant;
17
+ ALTER TABLE virtual_keys DROP COLUMN tenant_id;
18
+
19
+ -- 2. Money was stored as REAL.
20
+ --
21
+ -- The hard cap is the correctness property of #7 — it is the single feature the
22
+ -- agentic pipelines are switched off waiting for — and binary floating point
23
+ -- cannot represent most decimal money exactly. Accumulating thousands of small
24
+ -- per-request costs into a REAL lets the total drift from the sum of what the
25
+ -- providers actually billed, in either direction, which is both a cap that can be
26
+ -- crossed and a ledger that cannot be reconciled against an invoice (#5).
27
+ --
28
+ -- Everything monetary is now an integer count of **micros**: 1 USD = 1,000,000.
29
+ -- Cents would be too coarse, since a single cheap request can cost a small
30
+ -- fraction of one. Conversion happens at the boundaries and nowhere else.
31
+ --
32
+ -- Done now because there is no production data. Doing it later means migrating a
33
+ -- live ledger, which is the same argument this repo has already made twice.
34
+
35
+ ALTER TABLE project_budgets ADD COLUMN soft_micros INTEGER;
36
+ ALTER TABLE project_budgets ADD COLUMN hard_micros INTEGER;
37
+ UPDATE project_budgets
38
+ SET soft_micros = CAST(ROUND(soft_usd * 1000000) AS INTEGER),
39
+ hard_micros = CAST(ROUND(hard_usd * 1000000) AS INTEGER);
40
+ ALTER TABLE project_budgets DROP COLUMN soft_usd;
41
+ ALTER TABLE project_budgets DROP COLUMN hard_usd;
42
+
43
+ ALTER TABLE project_spend ADD COLUMN spend_micros INTEGER NOT NULL DEFAULT 0;
44
+ UPDATE project_spend SET spend_micros = CAST(ROUND(spend_usd * 1000000) AS INTEGER);
45
+ ALTER TABLE project_spend DROP COLUMN spend_usd;
46
+
47
+ ALTER TABLE virtual_keys ADD COLUMN budget_micros_month INTEGER;
48
+ UPDATE virtual_keys SET budget_micros_month = CAST(ROUND(budget_usd_month * 1000000) AS INTEGER);
49
+ ALTER TABLE virtual_keys DROP COLUMN budget_usd_month;
@@ -0,0 +1,42 @@
1
+ -- Prices, so the Worker can turn a response's token usage into spend (#1, #7).
2
+ --
3
+ -- The Worker has to compute cost itself rather than read it from gateway logs,
4
+ -- because `gw-sensitive` has logging off (v0.md §4) — which is the default and covers
5
+ -- every project carrying end-user content. A budget that only works on the
6
+ -- logging gateway would not restrain the traffic it exists to restrain.
7
+ --
8
+ -- This is a stopgap sized to #7's needs, not the cost ledger. #5 owns
9
+ -- reconciliation against Custom Costs and provider invoices, and v0.md §8 warns that a
10
+ -- stale table produces attribution that looks authoritative and is wrong — so
11
+ -- `source` and `as_of` are recorded from the start, and unknown models are
12
+ -- counted rather than guessed at.
13
+ --
14
+ -- Micros per million tokens, integer. See migration 0004 for why nothing
15
+ -- monetary is a float.
16
+
17
+ CREATE TABLE model_prices (
18
+ model TEXT PRIMARY KEY,
19
+ input_micros_per_mtok INTEGER NOT NULL,
20
+ output_micros_per_mtok INTEGER NOT NULL,
21
+ source TEXT NOT NULL,
22
+ as_of TEXT NOT NULL,
23
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
24
+ );
25
+
26
+ -- Requests whose model has no price. Counted rather than silently costed at
27
+ -- zero, because a budget that under-counts is the failure mode that matters:
28
+ -- it lets spend past a cap while reporting the cap as unbreached.
29
+ CREATE TABLE unpriced_usage (
30
+ model TEXT NOT NULL,
31
+ period_start TEXT NOT NULL,
32
+ request_count INTEGER NOT NULL DEFAULT 0,
33
+ input_tokens INTEGER NOT NULL DEFAULT 0,
34
+ output_tokens INTEGER NOT NULL DEFAULT 0,
35
+ PRIMARY KEY (model, period_start)
36
+ );
37
+
38
+ -- Workers AI, the only upstream reachable today without a BYOK provider key, and
39
+ -- what step 0 was measured against. Everything else lands here as projects
40
+ -- migrate and #5 takes over.
41
+ INSERT INTO model_prices (model, input_micros_per_mtok, output_micros_per_mtok, source, as_of) VALUES
42
+ ('workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast', 290000, 2250000, 'cloudflare-published', '2026-08-13');
@@ -0,0 +1,38 @@
1
+ -- Atomic budget reservation (#7), from review of PR #24.
2
+ --
3
+ -- The previous shape read spend, decided, called the upstream, and recorded cost
4
+ -- afterwards. Two problems followed from the gap between the read and the write.
5
+ --
6
+ -- Concurrent requests could all pass the check before any of them recorded, so
7
+ -- the cap could be exceeded by `concurrency × cost-per-request`. That was
8
+ -- measured and documented rather than fixed, on the argument that an agentic
9
+ -- loop is sequential and therefore already tightly bounded — which is true, and
10
+ -- was the wrong place to stop, because product traffic is the concurrent case
11
+ -- and v0.md §1 is explicit that spend now rises with marketing rather than engineering.
12
+ --
13
+ -- And because spend was only recorded after the response, a failure in that path
14
+ -- meant spend was never counted at all — so the cap drifted upward silently and
15
+ -- every later request was served against a stale total.
16
+ --
17
+ -- Reserving first fixes both. A request takes its reservation atomically before
18
+ -- the upstream call and reconciles to actual cost afterwards; if reconciliation
19
+ -- never happens, the reservation stands and the system fails closed rather than
20
+ -- open.
21
+
22
+ ALTER TABLE project_budgets
23
+ ADD COLUMN reserve_micros INTEGER NOT NULL DEFAULT 50000; -- $0.05
24
+
25
+ -- Reservations that were never reconciled, so the gap between what was held and
26
+ -- what was actually billed is visible rather than inferred. A reservation that
27
+ -- is never released is a small permanent overcharge against the cap; one that is
28
+ -- released twice is a hole in it. Both need to be countable.
29
+ CREATE TABLE reservation_failures (
30
+ id TEXT PRIMARY KEY,
31
+ at TEXT NOT NULL DEFAULT (datetime('now')),
32
+ project_id TEXT NOT NULL,
33
+ reserved INTEGER NOT NULL,
34
+ stage TEXT NOT NULL,
35
+ detail TEXT
36
+ );
37
+
38
+ CREATE INDEX idx_reservation_failures_project ON reservation_failures (project_id, at);