pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.10

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 (144) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-notes.mjs +30 -7
  42. package/scripts/restore.mjs +22 -10
  43. package/scripts/sync-tui.mjs +3 -3
  44. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  45. package/scripts/versioning.mjs +41 -5
  46. package/src/agents/aphrodite.md +6 -1
  47. package/src/agents/apollo.md +1 -0
  48. package/src/agents/athena.md +1 -0
  49. package/src/agents/demeter.md +1 -1
  50. package/src/agents/gaia.md +1 -0
  51. package/src/agents/hephaestus.md +1 -1
  52. package/src/agents/hermes.md +8 -10
  53. package/src/agents/iris.md +1 -1
  54. package/src/agents/mnemosyne.md +1 -0
  55. package/src/agents/nyx.md +1 -1
  56. package/src/agents/prometheus.md +1 -1
  57. package/src/agents/talos.md +6 -1
  58. package/src/agents/themis.md +1 -1
  59. package/src/agents/zeus.md +52 -62
  60. package/src/mcp/eval_store.py +11 -4
  61. package/src/mcp/mcp_resources.py +11 -9
  62. package/src/mcp/memory_mcp.py +293 -150
  63. package/src/pantheon/cost-command.ts +30 -133
  64. package/src/pantheon/jev-decision-tool.ts +347 -0
  65. package/src/pantheon/jev-decisions.ts +625 -0
  66. package/src/pantheon/local-decision-agents.ts +170 -0
  67. package/src/pantheon/local-decision-budget.ts +1046 -0
  68. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  69. package/src/pantheon/local-decision-prompt.ts +256 -0
  70. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  71. package/src/pantheon/local-decision-router.ts +225 -0
  72. package/src/pantheon/local-decision-skills.ts +281 -0
  73. package/src/pantheon/local-decision-tool.ts +160 -0
  74. package/src/pantheon/local-decision-turn.ts +101 -0
  75. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  76. package/src/pantheon/local-orchestration.ts +322 -0
  77. package/src/pantheon/model-pricing.ts +1 -536
  78. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  79. package/src/pantheon/v2-decision-budget.ts +456 -0
  80. package/src/pantheon/v2-decision-contracts.ts +300 -0
  81. package/src/pantheon/v2-decision-egress.ts +203 -0
  82. package/src/pantheon/v2-decision-events.ts +180 -0
  83. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  84. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  85. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  86. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  87. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  88. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  89. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  90. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  91. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  92. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  93. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  94. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  95. package/src/pantheon/v2-decision-points.ts +242 -0
  96. package/src/pantheon/v2-decision-policy.ts +166 -0
  97. package/src/pantheon/v2-decision-premises.ts +146 -0
  98. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  99. package/src/pantheon/v2-decision-rank.ts +91 -0
  100. package/src/pantheon/v2-decision-registry.ts +391 -0
  101. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  102. package/src/pantheon/v2-decision-shadow.ts +123 -0
  103. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  104. package/src/pantheon/v2-decision-verify.ts +51 -0
  105. package/src/pantheon/v2-hook-engine.ts +307 -0
  106. package/src/pantheon/v2-native-decisions.ts +365 -0
  107. package/src/pantheon/v2-shell-hooks.ts +66 -2
  108. package/src/pantheon/v2-tools.ts +38 -15
  109. package/src/plugin-v2.ts +419 -26
  110. package/src/plugin.ts +4 -0
  111. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  112. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  113. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  114. package/src/plugins/tui/dist/server-v2.js +19 -666
  115. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  117. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  118. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  119. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  120. package/src/plugins/tui/dist/tui.js +1 -1
  121. package/src/plugins/tui/package-lock.json +17 -2
  122. package/src/plugins/tui/package.json +4 -2
  123. package/src/plugins/tui/src/cost-data.ts +607 -0
  124. package/src/plugins/tui/src/index-v2.tsx +213 -54
  125. package/src/plugins/tui/src/model-pricing.ts +536 -0
  126. package/src/plugins/tui/src/server-v2.ts +18 -838
  127. package/src/plugins/tui/tsdown.config.ts +28 -6
  128. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  129. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  130. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  131. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  132. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  133. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  134. package/src/plugins/tui/dist/quota-cli.js +0 -184
  135. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  136. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  138. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  139. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  140. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  141. package/src/plugins/tui/src/quota-cli.ts +0 -237
  142. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  143. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  144. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -0,0 +1,1046 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, type Stats } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
5
+ import { performance } from 'node:perf_hooks'
6
+ import { DatabaseSync } from 'node:sqlite'
7
+ import {
8
+ getVerifiedUsageEvidenceDetails,
9
+ type VerifiedUsageEvidence,
10
+ } from './local-decision-usage-evidence.internal.ts'
11
+
12
+ export type BudgetProvider = 'openai-decisions' | 'typesafe-jev' | 'opencode-console' | 'jev-free'
13
+
14
+ /** Model and OpenCode Console variant keys must be configured before admission. */
15
+ export type BudgetModel = string
16
+
17
+ export interface BudgetCaps {
18
+ /** Non-negative integer USD micros. Zero explicitly disables admission. */
19
+ monthlyCapMicros: number
20
+ /** Non-negative integer USD micros. Zero explicitly disables admission. */
21
+ perDecisionCapMicros: number
22
+ }
23
+
24
+ export type ReservationResult =
25
+ | {
26
+ status: 'reserved'
27
+ reservationId: string
28
+ period: string
29
+ reservedMicros: number
30
+ }
31
+ | {
32
+ status: 'denied'
33
+ reason:
34
+ | 'invalid-provider'
35
+ | 'invalid-model'
36
+ | 'no-cap'
37
+ | 'per-decision-cap'
38
+ | 'monthly-cap'
39
+ | 'frozen'
40
+ | 'duplicate-reservation-id'
41
+ | 'period-unconfirmed'
42
+ | 'period-mismatch'
43
+ | 'clock-untrusted'
44
+ }
45
+
46
+ export type ReservationDenialReason = Extract<ReservationResult, { status: 'denied' }>['reason']
47
+ export type AdmissionCheckResult =
48
+ | { status: 'eligible' }
49
+ | { status: 'denied'; reason: ReservationDenialReason }
50
+
51
+ export type PeriodConfirmationResult =
52
+ | { status: 'confirmed'; activePeriod: string }
53
+ | {
54
+ status: 'denied'
55
+ reason:
56
+ | 'invalid-period'
57
+ | 'stale-current'
58
+ | 'backwards'
59
+ | 'not-next-month'
60
+ | 'wall-clock-mismatch'
61
+ | 'clock-untrusted'
62
+ }
63
+
64
+ export type ReconciliationResult =
65
+ | { status: 'reconciled'; actualCostMicros: number; frozen: boolean }
66
+ | { status: 'unknown' | 'missing' | 'already-reconciled' | 'mismatch' }
67
+
68
+ export interface UncertainReservation {
69
+ reservationId: string
70
+ provider: BudgetProvider
71
+ model: BudgetModel
72
+ period: string
73
+ reservedMicros: number
74
+ state: 'pending' | 'uncertain'
75
+ createdAtMs: number
76
+ updatedAtMs: number
77
+ }
78
+
79
+ export interface LocalDecisionBudgetLedger {
80
+ /** Admin/configuration API: writes policy to the local user-level DB. */
81
+ configureUserCaps(caps: BudgetCaps): void
82
+ /** Shared cap applies to every model/variant registered for this provider. */
83
+ configureProviderCaps(provider: BudgetProvider, caps: BudgetCaps): void
84
+ /** Each model/variant has an independent monthly and per-decision cap. */
85
+ configureModelCaps(provider: BudgetProvider, model: BudgetModel, caps: BudgetCaps): void
86
+ /** Explicitly initialize or advance the persisted UTC budget month one month only. */
87
+ confirmBudgetPeriod(
88
+ expectedCurrentPeriod: string | null,
89
+ targetPeriod: string,
90
+ ): PeriodConfirmationResult
91
+ getActiveBudgetPeriod(): string | null
92
+ /** Read-only, transactionally consistent check used to count Auto candidates. */
93
+ canReserve(provider: BudgetProvider, model: BudgetModel): AdmissionCheckResult
94
+ /**
95
+ * Atomically reserves the model's configured per-decision maximum across the
96
+ * user, provider, and model buckets. No cost or cap comes from the caller.
97
+ */
98
+ reserve(provider: BudgetProvider, model: BudgetModel): ReservationResult
99
+ /** Accepts only an opaque capability minted by the internal usage verifier. */
100
+ reconcileVerified(reservationId: string, evidence: VerifiedUsageEvidence): ReconciliationResult
101
+ listUncertainReservations(): UncertainReservation[]
102
+ /** Recovery only moves pending rows to uncertain; it never releases budget. */
103
+ recoverPendingReservations(): number
104
+ /** Prune resolved reservations from past UTC periods with no unresolved holds. */
105
+ pruneCompletedPeriods(): number
106
+ close(): void
107
+ }
108
+
109
+ export interface OpenLocalDecisionBudgetOptions {
110
+ dbPath?: string
111
+ /** Test seams; monotonic time detects regressions but never selects a budget period. */
112
+ clock?: () => number
113
+ monotonicClock?: () => number
114
+ /** Test seam; duplicate generated IDs are denied without adding a reservation. */
115
+ reservationIdFactory?: () => string
116
+ /** SQLite lock wait; production defaults to five seconds, then errors fail closed. */
117
+ busyTimeoutMs?: number
118
+ }
119
+
120
+ const SCHEMA_VERSION = 3
121
+ const VERSION_TWO = 2
122
+ const APPLICATION_ID = 0x50424c31
123
+ const DB_FILENAME = 'decision-budget.sqlite'
124
+ /** Accounting provider IDs accepted by the ledger. */
125
+ export const LOCAL_DECISION_BUDGET_PROVIDERS: readonly BudgetProvider[] = Object.freeze([
126
+ 'openai-decisions',
127
+ 'typesafe-jev',
128
+ 'opencode-console',
129
+ 'jev-free',
130
+ ])
131
+ const ALLOWED_PROVIDERS = new Set<BudgetProvider>(LOCAL_DECISION_BUDGET_PROVIDERS)
132
+ const MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
133
+ const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
134
+ const CLOCK_ROLLBACK_TOLERANCE_MS = 60_000
135
+
136
+ /** Resolve an account-wide path, independent of project install state. */
137
+ export function resolveLocalDecisionBudgetDbPath(
138
+ env: Readonly<Record<string, string | undefined>> = process.env,
139
+ ): string {
140
+ const xdgStateHome = env.XDG_STATE_HOME
141
+ const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir()
142
+ const base =
143
+ xdgStateHome && isAbsolute(xdgStateHome) ? xdgStateHome : join(home, '.local', 'state')
144
+ return resolve(base, 'pantheon', DB_FILENAME)
145
+ }
146
+
147
+ /**
148
+ * Open Pantheon's separate user-scoped accounting DB. New DBs have no policy
149
+ * and deny reservations. Schema upgrades are forward-only and preserve holds.
150
+ */
151
+ export function openLocalDecisionBudgetLedger(
152
+ options: OpenLocalDecisionBudgetOptions = {},
153
+ ): LocalDecisionBudgetLedger {
154
+ const dbPath = resolve(options.dbPath ?? resolveLocalDecisionBudgetDbPath())
155
+ if (['opencode.db', 'install-state.json'].includes(basename(dbPath))) {
156
+ throw new Error('The budget ledger must use its own SQLite database file')
157
+ }
158
+ const busyTimeoutMs = options.busyTimeoutMs ?? 5_000
159
+ if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 30_000) {
160
+ throw new RangeError('Invalid SQLite busy timeout')
161
+ }
162
+ const wallClock = options.clock ?? Date.now
163
+ const monotonicClock = options.monotonicClock ?? performance.now.bind(performance)
164
+ const reservationIdFactory = options.reservationIdFactory ?? randomUUID
165
+
166
+ const directoryPath = dirname(dbPath)
167
+ ensureTrustedDirectoryChain(directoryPath)
168
+
169
+ try {
170
+ const file = openSync(dbPath, 'wx', 0o600)
171
+ closeSync(file)
172
+ } catch (error) {
173
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
174
+ }
175
+ const fileStat = lstatSync(dbPath)
176
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1) {
177
+ throw new Error('Budget ledger path is not a private regular file')
178
+ }
179
+ if (typeof process.getuid !== 'function' || fileStat.uid !== process.getuid()) {
180
+ throw new Error('Budget ledger file must be owned by the current user')
181
+ }
182
+ chmodSync(dbPath, 0o600)
183
+
184
+ const db = new DatabaseSync(dbPath)
185
+ try {
186
+ db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}; PRAGMA foreign_keys = ON;`)
187
+ ensureSchema(db)
188
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;')
189
+ validateSchema(db)
190
+ } catch (error) {
191
+ db.close()
192
+ throw error
193
+ }
194
+
195
+ let previousWallClock: number | undefined
196
+ let previousMonotonicClock: number | undefined
197
+ const now = (): number => {
198
+ const wall = wallClock()
199
+ const monotonic = monotonicClock()
200
+ if (!Number.isSafeInteger(wall) || wall < 0 || !Number.isFinite(new Date(wall).getTime())) {
201
+ throw new Error('Invalid ledger wall clock')
202
+ }
203
+ if (!Number.isFinite(monotonic) || monotonic < 0) {
204
+ throw new Error('Invalid ledger monotonic clock')
205
+ }
206
+ if (previousWallClock !== undefined && previousMonotonicClock !== undefined) {
207
+ const wallElapsed = wall - previousWallClock
208
+ const monotonicElapsed = monotonic - previousMonotonicClock
209
+ if (
210
+ monotonicElapsed < 0 ||
211
+ wallElapsed < -CLOCK_ROLLBACK_TOLERANCE_MS ||
212
+ wallElapsed + CLOCK_ROLLBACK_TOLERANCE_MS < monotonicElapsed
213
+ ) {
214
+ throw new Error('Untrusted wall-clock movement')
215
+ }
216
+ }
217
+ previousWallClock = wall
218
+ previousMonotonicClock = monotonic
219
+ return wall
220
+ }
221
+
222
+ function inImmediateTransaction<T>(operation: () => T): T {
223
+ db.exec('BEGIN IMMEDIATE')
224
+ try {
225
+ const result = operation()
226
+ db.exec('COMMIT')
227
+ return result
228
+ } catch (error) {
229
+ try {
230
+ db.exec('ROLLBACK')
231
+ } catch {
232
+ // Preserve the original database failure. A failed transaction cannot admit.
233
+ }
234
+ throw error
235
+ }
236
+ }
237
+
238
+ function configureUserCaps(capsInput: BudgetCaps): void {
239
+ const caps = validateConfiguredCaps(capsInput)
240
+ inImmediateTransaction(() => {
241
+ const timestamp = now()
242
+ db.prepare(
243
+ `INSERT INTO user_caps (id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
244
+ VALUES (1, ?, ?, ?)
245
+ ON CONFLICT(id) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
246
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
247
+ updated_at_ms = excluded.updated_at_ms`,
248
+ ).run(caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
249
+ })
250
+ }
251
+
252
+ function configureProviderCaps(provider: BudgetProvider, capsInput: BudgetCaps): void {
253
+ if (!isAllowedProvider(provider)) throw new TypeError('Invalid budget provider')
254
+ const caps = validateConfiguredCaps(capsInput)
255
+ inImmediateTransaction(() => {
256
+ const timestamp = now()
257
+ db.prepare(
258
+ `INSERT INTO provider_caps (provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
259
+ VALUES (?, ?, ?, ?)
260
+ ON CONFLICT(provider) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
261
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
262
+ updated_at_ms = excluded.updated_at_ms`,
263
+ ).run(provider, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
264
+ })
265
+ }
266
+
267
+ function configureModelCaps(
268
+ provider: BudgetProvider,
269
+ model: BudgetModel,
270
+ capsInput: BudgetCaps,
271
+ ): void {
272
+ if (!isAllowedProvider(provider)) throw new TypeError('Invalid budget provider')
273
+ if (!isAllowedModel(model)) throw new TypeError('Invalid budget model key')
274
+ const caps = validateConfiguredCaps(capsInput)
275
+ inImmediateTransaction(() => {
276
+ const timestamp = now()
277
+ db.prepare(
278
+ `INSERT INTO model_caps
279
+ (provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
280
+ VALUES (?, ?, ?, ?, ?)
281
+ ON CONFLICT(provider, model) DO UPDATE SET
282
+ monthly_cap_micros = excluded.monthly_cap_micros,
283
+ per_decision_cap_micros = excluded.per_decision_cap_micros,
284
+ updated_at_ms = excluded.updated_at_ms`,
285
+ ).run(provider, model, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp)
286
+ })
287
+ }
288
+
289
+ function getActiveBudgetPeriod(): string | null {
290
+ const row = db.prepare('SELECT active_period_utc FROM ledger_state WHERE id = 1').get() as
291
+ | { active_period_utc: string | null }
292
+ | undefined
293
+ if (!row || row.active_period_utc === null) return null
294
+ if (!isValidPeriod(row.active_period_utc))
295
+ throw new Error('Invalid active period in budget ledger')
296
+ return row.active_period_utc
297
+ }
298
+
299
+ function confirmBudgetPeriod(
300
+ expectedCurrentPeriod: string | null,
301
+ targetPeriod: string,
302
+ ): PeriodConfirmationResult {
303
+ if (
304
+ (expectedCurrentPeriod !== null && !isValidPeriod(expectedCurrentPeriod)) ||
305
+ !isValidPeriod(targetPeriod)
306
+ ) {
307
+ return { status: 'denied', reason: 'invalid-period' }
308
+ }
309
+ return inImmediateTransaction(() => {
310
+ let wallPeriod: string
311
+ try {
312
+ wallPeriod = periodFor(now())
313
+ } catch {
314
+ return { status: 'denied', reason: 'clock-untrusted' }
315
+ }
316
+ const activePeriod = getActiveBudgetPeriod()
317
+ if (activePeriod !== expectedCurrentPeriod) {
318
+ return { status: 'denied', reason: 'stale-current' }
319
+ }
320
+ if (activePeriod === null) {
321
+ if (targetPeriod !== wallPeriod) {
322
+ return { status: 'denied', reason: 'wall-clock-mismatch' }
323
+ }
324
+ db.prepare(
325
+ `INSERT INTO ledger_state (id, active_period_utc) VALUES (1, ?)
326
+ ON CONFLICT(id) DO UPDATE SET active_period_utc = excluded.active_period_utc`,
327
+ ).run(targetPeriod)
328
+ return { status: 'confirmed', activePeriod: targetPeriod }
329
+ }
330
+ if (targetPeriod < activePeriod) return { status: 'denied', reason: 'backwards' }
331
+ if (targetPeriod === activePeriod) return { status: 'denied', reason: 'not-next-month' }
332
+ if (nextPeriod(activePeriod) !== targetPeriod) {
333
+ return { status: 'denied', reason: 'not-next-month' }
334
+ }
335
+ if (wallPeriod !== targetPeriod) {
336
+ return { status: 'denied', reason: 'wall-clock-mismatch' }
337
+ }
338
+ db.prepare('UPDATE ledger_state SET active_period_utc = ? WHERE id = 1').run(targetPeriod)
339
+ return { status: 'confirmed', activePeriod: targetPeriod }
340
+ })
341
+ }
342
+
343
+ function reserve(provider: BudgetProvider, model: BudgetModel): ReservationResult {
344
+ if (!isAllowedProvider(provider)) return { status: 'denied', reason: 'invalid-provider' }
345
+ if (!isAllowedModel(model)) return { status: 'denied', reason: 'invalid-model' }
346
+ return inImmediateTransaction(() => {
347
+ const admission = checkAdmission(provider, model)
348
+ if (admission.status === 'denied') return admission
349
+
350
+ const reservationId = reservationIdFactory()
351
+ if (typeof reservationId !== 'string' || !RESERVATION_ID.test(reservationId)) {
352
+ throw new Error('Invalid generated reservation identifier')
353
+ }
354
+ const duplicate = db
355
+ .prepare('SELECT 1 AS found FROM reservations WHERE id = ?')
356
+ .get(reservationId)
357
+ if (duplicate) return { status: 'denied', reason: 'duplicate-reservation-id' }
358
+ db.prepare(
359
+ `INSERT INTO reservations
360
+ (id, provider, model, period_utc, reserved_micros, actual_micros, state,
361
+ created_at_ms, updated_at_ms)
362
+ VALUES (?, ?, ?, ?, ?, NULL, 'pending', ?, ?)`,
363
+ ).run(
364
+ reservationId,
365
+ provider,
366
+ model,
367
+ admission.period,
368
+ admission.reservedMicros,
369
+ admission.timestamp,
370
+ admission.timestamp,
371
+ )
372
+ return {
373
+ status: 'reserved',
374
+ reservationId,
375
+ period: admission.period,
376
+ reservedMicros: admission.reservedMicros,
377
+ }
378
+ })
379
+ }
380
+
381
+ function canReserve(provider: BudgetProvider, model: BudgetModel): AdmissionCheckResult {
382
+ if (!isAllowedProvider(provider)) return { status: 'denied', reason: 'invalid-provider' }
383
+ if (!isAllowedModel(model)) return { status: 'denied', reason: 'invalid-model' }
384
+ return inImmediateTransaction(() => {
385
+ const admission = checkAdmission(provider, model)
386
+ return admission.status === 'denied' ? admission : { status: 'eligible' }
387
+ })
388
+ }
389
+
390
+ function checkAdmission(
391
+ provider: BudgetProvider,
392
+ model: BudgetModel,
393
+ ):
394
+ | { status: 'eligible'; period: string; reservedMicros: number; timestamp: number }
395
+ | { status: 'denied'; reason: ReservationDenialReason } {
396
+ let timestamp: number
397
+ let wallPeriod: string
398
+ try {
399
+ timestamp = now()
400
+ wallPeriod = periodFor(timestamp)
401
+ } catch {
402
+ return { status: 'denied', reason: 'clock-untrusted' }
403
+ }
404
+ const userCaps = readUserCaps()
405
+ const providerCaps = readProviderCaps(provider)
406
+ const modelCaps = readModelCaps(provider, model)
407
+ if (
408
+ !hasPositiveCaps(userCaps) ||
409
+ !hasPositiveCaps(providerCaps) ||
410
+ !hasPositiveCaps(modelCaps)
411
+ ) {
412
+ return { status: 'denied', reason: 'no-cap' }
413
+ }
414
+
415
+ const period = getActiveBudgetPeriod()
416
+ if (period === null) return { status: 'denied', reason: 'period-unconfirmed' }
417
+ if (wallPeriod !== period) return { status: 'denied', reason: 'period-mismatch' }
418
+
419
+ const reservedMicros = modelCaps.per_decision_cap_micros
420
+ if (
421
+ reservedMicros > userCaps.per_decision_cap_micros ||
422
+ reservedMicros > providerCaps.per_decision_cap_micros
423
+ ) {
424
+ return { status: 'denied', reason: 'per-decision-cap' }
425
+ }
426
+ if (isFrozen(period, provider, model)) return { status: 'denied', reason: 'frozen' }
427
+
428
+ if (
429
+ wouldExceed(sumReservations(period), reservedMicros, userCaps.monthly_cap_micros) ||
430
+ wouldExceed(
431
+ sumReservations(period, provider),
432
+ reservedMicros,
433
+ providerCaps.monthly_cap_micros,
434
+ ) ||
435
+ wouldExceed(
436
+ sumReservations(period, provider, model),
437
+ reservedMicros,
438
+ modelCaps.monthly_cap_micros,
439
+ )
440
+ ) {
441
+ return { status: 'denied', reason: 'monthly-cap' }
442
+ }
443
+ return { status: 'eligible', period, reservedMicros, timestamp }
444
+ }
445
+
446
+ function reconcileVerified(
447
+ reservationId: string,
448
+ evidence: VerifiedUsageEvidence,
449
+ ): ReconciliationResult {
450
+ if (typeof reservationId !== 'string' || !RESERVATION_ID.test(reservationId)) {
451
+ return { status: 'unknown' }
452
+ }
453
+ const verified = getVerifiedUsageEvidenceDetails(evidence)
454
+ if (
455
+ !verified ||
456
+ !Number.isSafeInteger(verified.actualCostMicros) ||
457
+ // Zero is a legitimate host-reported cost on the native route (the free
458
+ // Console variant and hosts that do not price Decisions); reconciling at
459
+ // zero releases the hold instead of burning the period's budget.
460
+ verified.actualCostMicros < 0 ||
461
+ !isAllowedProvider(verified.provider) ||
462
+ !isAllowedModel(verified.model) ||
463
+ !isValidPeriod(verified.period)
464
+ ) {
465
+ return { status: 'unknown' }
466
+ }
467
+ return inImmediateTransaction(() => {
468
+ const row = db
469
+ .prepare(
470
+ `SELECT provider, model, period_utc, reserved_micros, state
471
+ FROM reservations WHERE id = ?`,
472
+ )
473
+ .get(reservationId) as
474
+ | {
475
+ provider: BudgetProvider
476
+ model: string
477
+ period_utc: string
478
+ reserved_micros: number
479
+ state: string
480
+ }
481
+ | undefined
482
+ if (!row) return { status: 'missing' }
483
+ if (row.state === 'reconciled') return { status: 'already-reconciled' }
484
+ if (row.state !== 'pending' && row.state !== 'uncertain') {
485
+ throw new Error('Invalid reservation state')
486
+ }
487
+ if (
488
+ verified.reservationId !== reservationId ||
489
+ verified.provider !== row.provider ||
490
+ verified.model !== row.model ||
491
+ verified.period !== row.period_utc
492
+ ) {
493
+ return { status: 'mismatch' }
494
+ }
495
+ const timestamp = now()
496
+ const update = db
497
+ .prepare(
498
+ `UPDATE reservations SET actual_micros = ?, state = 'reconciled', updated_at_ms = ?
499
+ WHERE id = ? AND state IN ('pending', 'uncertain')`,
500
+ )
501
+ .run(verified.actualCostMicros, timestamp, reservationId)
502
+ if (safeChangeCount(update.changes) !== 1) {
503
+ throw new Error('Reservation state changed unexpectedly')
504
+ }
505
+ const frozen = verified.actualCostMicros > row.reserved_micros
506
+ if (frozen) freezeBuckets(row.period_utc, row.provider, row.model, timestamp)
507
+ return { status: 'reconciled', actualCostMicros: verified.actualCostMicros, frozen }
508
+ })
509
+ }
510
+
511
+ function sumReservations(period: string, provider?: BudgetProvider, model?: string): number {
512
+ // Future-dated v2 holds may have resulted from an untrusted clock jump.
513
+ const where = ['period_utc >= ?']
514
+ const params: Array<string> = [period]
515
+ if (provider !== undefined) {
516
+ where.push('provider = ?')
517
+ params.push(provider)
518
+ }
519
+ if (model !== undefined) {
520
+ where.push('model = ?')
521
+ params.push(model)
522
+ }
523
+ const row = db
524
+ .prepare(
525
+ `SELECT COALESCE(SUM(CASE WHEN state = 'reconciled' THEN actual_micros ELSE reserved_micros END), 0) AS amount
526
+ FROM reservations WHERE ${where.join(' AND ')}`,
527
+ )
528
+ .get(...params) as { amount: number | bigint }
529
+ return safeMicrosTotal(row.amount)
530
+ }
531
+
532
+ function isFrozen(period: string, provider: BudgetProvider, model: string): boolean {
533
+ return Boolean(
534
+ db
535
+ .prepare(
536
+ `SELECT 1 AS found FROM budget_freezes
537
+ WHERE period_utc >= ? AND (
538
+ (scope = 'user' AND provider IS NULL AND model IS NULL) OR
539
+ (scope = 'provider' AND provider = ? AND model IS NULL) OR
540
+ (scope = 'model' AND provider = ? AND model = ?)
541
+ ) LIMIT 1`,
542
+ )
543
+ .get(period, provider, provider, model),
544
+ )
545
+ }
546
+
547
+ function freezeBuckets(
548
+ period: string,
549
+ provider: BudgetProvider,
550
+ model: string,
551
+ timestamp: number,
552
+ ): void {
553
+ const insertIfMissing = db.prepare(
554
+ `INSERT INTO budget_freezes (scope, provider, model, period_utc, reason, created_at_ms)
555
+ VALUES (?, ?, ?, ?, 'overrun', ?)
556
+ ON CONFLICT DO NOTHING`,
557
+ )
558
+ insertIfMissing.run('user', null, null, period, timestamp)
559
+ insertIfMissing.run('provider', provider, null, period, timestamp)
560
+ insertIfMissing.run('model', provider, model, period, timestamp)
561
+ }
562
+
563
+ function listUncertainReservations(): UncertainReservation[] {
564
+ const rows = db
565
+ .prepare(
566
+ `SELECT id, provider, model, period_utc, reserved_micros, state, created_at_ms, updated_at_ms
567
+ FROM reservations WHERE state IN ('pending', 'uncertain') ORDER BY created_at_ms, id`,
568
+ )
569
+ .all() as Array<{
570
+ id: string
571
+ provider: BudgetProvider
572
+ model: string
573
+ period_utc: string
574
+ reserved_micros: number
575
+ state: 'pending' | 'uncertain'
576
+ created_at_ms: number
577
+ updated_at_ms: number
578
+ }>
579
+ return rows.map((row) => ({
580
+ reservationId: row.id,
581
+ provider: row.provider,
582
+ model: row.model,
583
+ period: row.period_utc,
584
+ reservedMicros: row.reserved_micros,
585
+ state: row.state,
586
+ createdAtMs: row.created_at_ms,
587
+ updatedAtMs: row.updated_at_ms,
588
+ }))
589
+ }
590
+
591
+ function recoverPendingReservations(): number {
592
+ return inImmediateTransaction(() => {
593
+ const timestamp = now()
594
+ const result = db
595
+ .prepare(
596
+ `UPDATE reservations SET state = 'uncertain', updated_at_ms = ? WHERE state = 'pending'`,
597
+ )
598
+ .run(timestamp)
599
+ return safeChangeCount(result.changes)
600
+ })
601
+ }
602
+
603
+ function pruneCompletedPeriods(): number {
604
+ return inImmediateTransaction(() => {
605
+ let currentPeriod: string
606
+ try {
607
+ currentPeriod = periodFor(now())
608
+ } catch {
609
+ return 0
610
+ }
611
+ const activePeriod = getActiveBudgetPeriod()
612
+ if (activePeriod === null || currentPeriod !== activePeriod) return 0
613
+ const result = db
614
+ .prepare(
615
+ `DELETE FROM reservations AS completed
616
+ WHERE completed.period_utc < ? AND completed.state = 'reconciled'
617
+ AND NOT EXISTS (
618
+ SELECT 1 FROM reservations AS unresolved
619
+ WHERE unresolved.period_utc = completed.period_utc
620
+ AND unresolved.state IN ('pending', 'uncertain')
621
+ )`,
622
+ )
623
+ .run(activePeriod)
624
+ db.prepare(
625
+ `DELETE FROM budget_freezes
626
+ WHERE period_utc < ? AND NOT EXISTS (
627
+ SELECT 1 FROM reservations AS unresolved
628
+ WHERE unresolved.period_utc = budget_freezes.period_utc
629
+ AND unresolved.state IN ('pending', 'uncertain')
630
+ )`,
631
+ ).run(activePeriod)
632
+ return safeChangeCount(result.changes)
633
+ })
634
+ }
635
+
636
+ function readUserCaps(): StoredCaps | undefined {
637
+ return db
638
+ .prepare('SELECT monthly_cap_micros, per_decision_cap_micros FROM user_caps WHERE id = 1')
639
+ .get() as StoredCaps | undefined
640
+ }
641
+
642
+ function readProviderCaps(provider: BudgetProvider): StoredCaps | undefined {
643
+ return db
644
+ .prepare(
645
+ 'SELECT monthly_cap_micros, per_decision_cap_micros FROM provider_caps WHERE provider = ?',
646
+ )
647
+ .get(provider) as StoredCaps | undefined
648
+ }
649
+
650
+ function readModelCaps(provider: BudgetProvider, model: string): StoredCaps | undefined {
651
+ return db
652
+ .prepare(
653
+ `SELECT monthly_cap_micros, per_decision_cap_micros
654
+ FROM model_caps WHERE provider = ? AND model = ?`,
655
+ )
656
+ .get(provider, model) as StoredCaps | undefined
657
+ }
658
+
659
+ return {
660
+ configureUserCaps,
661
+ configureProviderCaps,
662
+ configureModelCaps,
663
+ confirmBudgetPeriod,
664
+ getActiveBudgetPeriod,
665
+ canReserve,
666
+ reserve,
667
+ reconcileVerified,
668
+ listUncertainReservations,
669
+ recoverPendingReservations,
670
+ pruneCompletedPeriods,
671
+ close: () => db.close(),
672
+ }
673
+ }
674
+
675
+ interface StoredCaps {
676
+ monthly_cap_micros: number
677
+ per_decision_cap_micros: number
678
+ }
679
+
680
+ function ensureSchema(db: DatabaseSync): void {
681
+ db.exec('BEGIN IMMEDIATE')
682
+ try {
683
+ const version = (db.prepare('PRAGMA user_version').get() as { user_version: number })
684
+ .user_version
685
+ const applicationId = (db.prepare('PRAGMA application_id').get() as { application_id: number })
686
+ .application_id
687
+ if (version === 0) {
688
+ const tables = db
689
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
690
+ .all()
691
+ if (applicationId !== 0 || tables.length !== 0) {
692
+ throw new Error('Refusing to initialize an unrecognized SQLite database')
693
+ }
694
+ createSchemaV3(db)
695
+ } else if (version === 1 && applicationId === APPLICATION_ID) {
696
+ migrateVersionOne(db)
697
+ migrateVersionTwoToThree(db)
698
+ } else if (version === VERSION_TWO && applicationId === APPLICATION_ID) {
699
+ migrateVersionTwoToThree(db)
700
+ } else if (version !== SCHEMA_VERSION || applicationId !== APPLICATION_ID) {
701
+ throw new Error('Unsupported or incompatible local decision budget database schema')
702
+ }
703
+ db.exec('COMMIT')
704
+ } catch (error) {
705
+ try {
706
+ db.exec('ROLLBACK')
707
+ } catch {
708
+ // Preserve schema/migration error.
709
+ }
710
+ throw error
711
+ }
712
+ }
713
+
714
+ function createSchemaV3(db: DatabaseSync): void {
715
+ db.exec(`
716
+ CREATE TABLE user_caps (
717
+ id INTEGER PRIMARY KEY CHECK (id = 1),
718
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
719
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
720
+ updated_at_ms INTEGER NOT NULL
721
+ ) STRICT;
722
+ CREATE TABLE provider_caps (
723
+ provider TEXT PRIMARY KEY NOT NULL,
724
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
725
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
726
+ updated_at_ms INTEGER NOT NULL
727
+ ) STRICT;
728
+ CREATE TABLE model_caps (
729
+ provider TEXT NOT NULL,
730
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
731
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
732
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
733
+ updated_at_ms INTEGER NOT NULL,
734
+ PRIMARY KEY (provider, model)
735
+ ) STRICT;
736
+ CREATE TABLE reservations (
737
+ id TEXT PRIMARY KEY NOT NULL,
738
+ provider TEXT NOT NULL,
739
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
740
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
741
+ reserved_micros INTEGER NOT NULL CHECK (reserved_micros > 0),
742
+ actual_micros INTEGER CHECK (actual_micros IS NULL OR actual_micros >= 0),
743
+ state TEXT NOT NULL CHECK (state IN ('pending', 'uncertain', 'reconciled')),
744
+ created_at_ms INTEGER NOT NULL,
745
+ updated_at_ms INTEGER NOT NULL,
746
+ CHECK ((state = 'reconciled' AND actual_micros IS NOT NULL) OR
747
+ (state IN ('pending', 'uncertain') AND actual_micros IS NULL))
748
+ ) STRICT;
749
+ CREATE INDEX reservations_provider_period_idx ON reservations (provider, period_utc, state);
750
+ CREATE INDEX reservations_model_period_idx
751
+ ON reservations (provider, model, period_utc, state);
752
+ CREATE INDEX reservations_period_state_idx ON reservations (period_utc, state);
753
+ CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
754
+ CREATE TABLE ledger_state (
755
+ id INTEGER PRIMARY KEY CHECK (id = 1),
756
+ active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
757
+ ) STRICT;
758
+ CREATE TABLE budget_freezes (
759
+ id INTEGER PRIMARY KEY,
760
+ scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
761
+ provider TEXT,
762
+ model TEXT,
763
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
764
+ reason TEXT NOT NULL CHECK (reason = 'overrun'),
765
+ created_at_ms INTEGER NOT NULL,
766
+ CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
767
+ (scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
768
+ (scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
769
+ ) STRICT;
770
+ CREATE UNIQUE INDEX budget_freezes_unique_idx
771
+ ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
772
+ CREATE INDEX budget_freezes_period_scope_idx
773
+ ON budget_freezes (period_utc, scope, provider, model);
774
+ PRAGMA application_id = ${APPLICATION_ID};
775
+ PRAGMA user_version = ${SCHEMA_VERSION};
776
+ `)
777
+ }
778
+
779
+ function migrateVersionTwoToThree(db: DatabaseSync): void {
780
+ validateVersionTwoSchema(db)
781
+ db.exec(`
782
+ UPDATE reservations SET
783
+ reserved_micros = CASE
784
+ WHEN actual_micros > reserved_micros THEN actual_micros
785
+ ELSE reserved_micros
786
+ END,
787
+ state = 'uncertain', actual_micros = NULL
788
+ WHERE state = 'reconciled';
789
+ ALTER TABLE ledger_state RENAME TO ledger_state_v2;
790
+ CREATE TABLE ledger_state (
791
+ id INTEGER PRIMARY KEY CHECK (id = 1),
792
+ active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
793
+ ) STRICT;
794
+ INSERT INTO ledger_state (id, active_period_utc)
795
+ SELECT id, NULL FROM ledger_state_v2;
796
+ DROP TABLE ledger_state_v2;
797
+ PRAGMA user_version = ${SCHEMA_VERSION};
798
+ `)
799
+ }
800
+
801
+ function migrateVersionOne(db: DatabaseSync): void {
802
+ validateVersionOneSchema(db)
803
+ const providers = db
804
+ .prepare('SELECT DISTINCT provider FROM reservations UNION SELECT provider FROM provider_caps')
805
+ .all() as Array<{ provider: string }>
806
+ if (providers.some(({ provider }) => provider !== 'openai-decisions' && provider !== 'jev')) {
807
+ throw new Error('Refusing to migrate an unsupported version-one provider')
808
+ }
809
+ db.exec(`
810
+ ALTER TABLE reservations
811
+ ADD COLUMN model TEXT NOT NULL DEFAULT 'legacy-unknown'
812
+ CHECK (length(model) BETWEEN 1 AND 128);
813
+ UPDATE reservations SET model = 'gpt-6-luna' WHERE provider = 'openai-decisions';
814
+ UPDATE reservations SET provider = 'typesafe-jev', model = 'jev-1.14.0' WHERE provider = 'jev';
815
+ UPDATE provider_caps SET provider = 'typesafe-jev' WHERE provider = 'jev';
816
+ CREATE TABLE user_caps (
817
+ id INTEGER PRIMARY KEY CHECK (id = 1),
818
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
819
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
820
+ updated_at_ms INTEGER NOT NULL
821
+ ) STRICT;
822
+ CREATE TABLE model_caps (
823
+ provider TEXT NOT NULL,
824
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
825
+ monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
826
+ per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
827
+ updated_at_ms INTEGER NOT NULL,
828
+ PRIMARY KEY (provider, model)
829
+ ) STRICT;
830
+ CREATE INDEX reservations_model_period_idx
831
+ ON reservations (provider, model, period_utc, state);
832
+ CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
833
+ CREATE TABLE budget_freezes (
834
+ id INTEGER PRIMARY KEY,
835
+ scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
836
+ provider TEXT,
837
+ model TEXT,
838
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
839
+ reason TEXT NOT NULL CHECK (reason = 'overrun'),
840
+ created_at_ms INTEGER NOT NULL,
841
+ CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
842
+ (scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
843
+ (scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
844
+ ) STRICT;
845
+ CREATE UNIQUE INDEX budget_freezes_unique_idx
846
+ ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
847
+ CREATE INDEX budget_freezes_period_scope_idx
848
+ ON budget_freezes (period_utc, scope, provider, model);
849
+ PRAGMA user_version = ${VERSION_TWO};
850
+ `)
851
+ }
852
+
853
+ function validateVersionOneSchema(db: DatabaseSync): void {
854
+ db.prepare(
855
+ `SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
856
+ FROM provider_caps LIMIT 0`,
857
+ )
858
+ db.prepare(
859
+ `SELECT id, provider, period_utc, reserved_micros, actual_micros, state,
860
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
861
+ )
862
+ db.prepare('SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0')
863
+ }
864
+
865
+ function validateVersionTwoSchema(db: DatabaseSync): void {
866
+ db.prepare(
867
+ 'SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0',
868
+ )
869
+ db.prepare(
870
+ 'SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM provider_caps LIMIT 0',
871
+ )
872
+ db.prepare(
873
+ 'SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM model_caps LIMIT 0',
874
+ )
875
+ db.prepare(
876
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
877
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
878
+ )
879
+ db.prepare('SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0')
880
+ db.prepare(
881
+ 'SELECT id, scope, provider, model, period_utc, reason, created_at_ms FROM budget_freezes LIMIT 0',
882
+ )
883
+ }
884
+
885
+ function validateSchema(db: DatabaseSync): void {
886
+ db.prepare(
887
+ `SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0`,
888
+ )
889
+ db.prepare(
890
+ `SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
891
+ FROM provider_caps LIMIT 0`,
892
+ )
893
+ db.prepare(
894
+ `SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
895
+ FROM model_caps LIMIT 0`,
896
+ )
897
+ db.prepare(
898
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
899
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`,
900
+ )
901
+ db.prepare('SELECT id, active_period_utc FROM ledger_state LIMIT 0')
902
+ db.prepare(
903
+ `SELECT id, scope, provider, model, period_utc, reason, created_at_ms
904
+ FROM budget_freezes LIMIT 0`,
905
+ )
906
+ }
907
+
908
+ function validateConfiguredCaps(value: unknown): BudgetCaps {
909
+ if (!isPlainRecord(value)) throw new TypeError('Caps must be an object')
910
+ const keys = Object.keys(value).sort()
911
+ if (keys.join(',') !== 'monthlyCapMicros,perDecisionCapMicros') {
912
+ throw new TypeError('Caps must contain only monthly and per-decision values')
913
+ }
914
+ if (!isValidCap(value.monthlyCapMicros) || !isValidCap(value.perDecisionCapMicros)) {
915
+ throw new TypeError('Caps must be non-negative safe integer USD micros')
916
+ }
917
+ return {
918
+ monthlyCapMicros: value.monthlyCapMicros,
919
+ perDecisionCapMicros: value.perDecisionCapMicros,
920
+ }
921
+ }
922
+
923
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
924
+ try {
925
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value))
926
+ } catch {
927
+ return false
928
+ }
929
+ }
930
+
931
+ function isAllowedProvider(provider: unknown): provider is BudgetProvider {
932
+ return typeof provider === 'string' && ALLOWED_PROVIDERS.has(provider as BudgetProvider)
933
+ }
934
+
935
+ function isAllowedModel(model: unknown): model is BudgetModel {
936
+ return typeof model === 'string' && MODEL_KEY.test(model)
937
+ }
938
+
939
+ function isValidCap(value: unknown): value is number {
940
+ return Number.isSafeInteger(value) && (value as number) >= 0
941
+ }
942
+
943
+ function hasPositiveCaps(value: StoredCaps | undefined): value is StoredCaps {
944
+ return Boolean(
945
+ value &&
946
+ isValidCap(value.monthly_cap_micros) &&
947
+ value.monthly_cap_micros > 0 &&
948
+ isValidCap(value.per_decision_cap_micros) &&
949
+ value.per_decision_cap_micros > 0,
950
+ )
951
+ }
952
+
953
+ function wouldExceed(current: number, additional: number, cap: number): boolean {
954
+ return current > cap || additional > cap - current
955
+ }
956
+
957
+ function safeMicrosTotal(value: number | bigint): number {
958
+ if (typeof value === 'bigint') {
959
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < 0n) {
960
+ throw new Error('Invalid spend total in budget ledger')
961
+ }
962
+ return Number(value)
963
+ }
964
+ if (!Number.isSafeInteger(value) || value < 0) {
965
+ throw new Error('Invalid spend total in budget ledger')
966
+ }
967
+ return value
968
+ }
969
+
970
+ function periodFor(timestamp: number): string {
971
+ const period = new Date(timestamp).toISOString().slice(0, 7)
972
+ if (!isValidPeriod(period)) throw new Error('Invalid UTC accounting period')
973
+ return period
974
+ }
975
+
976
+ function isValidPeriod(value: string): boolean {
977
+ return /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
978
+ }
979
+
980
+ function nextPeriod(period: string): string | null {
981
+ if (!isValidPeriod(period)) return null
982
+ let year = Number(period.slice(0, 4))
983
+ let month = Number(period.slice(5, 7)) + 1
984
+ if (month === 13) {
985
+ year += 1
986
+ month = 1
987
+ }
988
+ if (year > 9999) return null
989
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}`
990
+ }
991
+
992
+ function safeChangeCount(value: number | bigint): number {
993
+ const count = Number(value)
994
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid SQLite change count')
995
+ return count
996
+ }
997
+
998
+ function ensureTrustedDirectoryChain(directoryPath: string): void {
999
+ if (process.platform === 'win32' || typeof process.getuid !== 'function') {
1000
+ throw new Error('Secure budget-ledger path validation is unavailable on this platform')
1001
+ }
1002
+ const uid = process.getuid()
1003
+ const absolute = resolve(directoryPath)
1004
+ const root = parse(absolute).root
1005
+ let current = root
1006
+ validateDirectoryTrust(lstatSync(current), uid, current === absolute)
1007
+
1008
+ for (const component of absolute.slice(root.length).split(sep).filter(Boolean)) {
1009
+ current = join(current, component)
1010
+ try {
1011
+ lstatSync(current)
1012
+ } catch (error) {
1013
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
1014
+ try {
1015
+ mkdirSync(current, { mode: 0o700 })
1016
+ } catch (mkdirError) {
1017
+ if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST') throw mkdirError
1018
+ }
1019
+ }
1020
+ const stat = lstatSync(current)
1021
+ const isFinalDirectory = current === absolute
1022
+ validateDirectoryTrust(stat, uid, isFinalDirectory)
1023
+ if (isFinalDirectory) {
1024
+ chmodSync(current, 0o700)
1025
+ validateDirectoryTrust(lstatSync(current), uid, true)
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ function validateDirectoryTrust(stat: Stats, uid: number, isFinalDirectory: boolean): void {
1031
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
1032
+ throw new Error('Budget ledger path contains a non-directory or symlink ancestor')
1033
+ }
1034
+ if (stat.uid !== uid && stat.uid !== 0) {
1035
+ throw new Error('Budget ledger path contains an untrusted owner')
1036
+ }
1037
+ if (isFinalDirectory && stat.uid !== uid) {
1038
+ throw new Error('Budget ledger directory must be owned by the current user')
1039
+ }
1040
+ const mode = stat.mode & 0o7777
1041
+ const writableByOthers = (mode & 0o022) !== 0
1042
+ const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
1043
+ if (writableByOthers && !rootStickyDirectory) {
1044
+ throw new Error('Budget ledger path contains a group/other-writable directory')
1045
+ }
1046
+ }