pantheon-opencode 1.6.2-beta.3 → 1.6.2-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +38 -1
- package/bin/pantheon-init.mjs +17 -0
- package/package.json +9 -3
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +781 -0
- package/scripts/decision-router.mjs +297 -0
- package/scripts/install/decision-router-config.mjs +432 -0
- package/scripts/install/interactive.mjs +76 -5
- package/scripts/install/opencode.mjs +12 -0
- package/scripts/install/state.mjs +5 -0
- package/scripts/install/strings.mjs +4 -0
- package/src/agents/zeus.md +12 -0
- package/src/pantheon/local-decision-agents.ts +170 -0
- package/src/pantheon/local-decision-budget.ts +1043 -0
- package/src/pantheon/local-decision-egress-gate.ts +264 -0
- package/src/pantheon/local-decision-prompt.ts +123 -0
- package/src/pantheon/local-decision-provider-matrix.ts +92 -0
- package/src/pantheon/local-decision-provider-protocol.ts +335 -0
- package/src/pantheon/local-decision-provider.internal.ts +260 -0
- package/src/pantheon/local-decision-router.ts +225 -0
- package/src/pantheon/local-decision-skills.ts +171 -0
- package/src/pantheon/local-decision-tool.ts +126 -0
- package/src/pantheon/local-decision-turn.ts +338 -0
- package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
- package/src/pantheon/local-orchestration.ts +322 -0
- package/src/pantheon/pantheon-decision-catalog.ts +101 -0
- package/src/pantheon/v2-tools.ts +15 -14
- package/src/plugin-v2.ts +52 -19
- package/src/plugin.ts +4 -0
- package/src/plugins/tui/dist/tui-v2.js +3 -3
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
|
@@ -0,0 +1,781 @@
|
|
|
1
|
+
// Generated by scripts/build-decision-router.mjs from src/pantheon/local-decision-budget.ts.
|
|
2
|
+
// The published CLI cannot import TypeScript from node_modules, so it imports
|
|
3
|
+
// this prebuilt ESM bundle instead. Do not edit: run `npm run build:decision-router`.
|
|
4
|
+
|
|
5
|
+
// src/pantheon/local-decision-budget.ts
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { chmodSync, closeSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
|
|
10
|
+
import { performance } from "node:perf_hooks";
|
|
11
|
+
import { DatabaseSync } from "node:sqlite";
|
|
12
|
+
|
|
13
|
+
// src/pantheon/local-decision-usage-evidence.internal.ts
|
|
14
|
+
var MODEL_IDS = Object.freeze({
|
|
15
|
+
"openai-decisions": "gpt-6-luna",
|
|
16
|
+
"typesafe-jev": "jev-1.14.0"
|
|
17
|
+
});
|
|
18
|
+
var evidenceDetails = /* @__PURE__ */ new WeakMap();
|
|
19
|
+
function getVerifiedUsageEvidenceDetails(value) {
|
|
20
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) return null;
|
|
21
|
+
return evidenceDetails.get(value) ?? null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/pantheon/local-decision-budget.ts
|
|
25
|
+
var SCHEMA_VERSION = 3;
|
|
26
|
+
var VERSION_TWO = 2;
|
|
27
|
+
var APPLICATION_ID = 1346522161;
|
|
28
|
+
var DB_FILENAME = "decision-budget.sqlite";
|
|
29
|
+
var LOCAL_DECISION_BUDGET_PROVIDERS = Object.freeze([
|
|
30
|
+
"openai-decisions",
|
|
31
|
+
"typesafe-jev",
|
|
32
|
+
"opencode-console",
|
|
33
|
+
"jev-free"
|
|
34
|
+
]);
|
|
35
|
+
var ALLOWED_PROVIDERS = new Set(LOCAL_DECISION_BUDGET_PROVIDERS);
|
|
36
|
+
var MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
37
|
+
var RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
38
|
+
var CLOCK_ROLLBACK_TOLERANCE_MS = 6e4;
|
|
39
|
+
function resolveLocalDecisionBudgetDbPath(env = process.env) {
|
|
40
|
+
const xdgStateHome = env.XDG_STATE_HOME;
|
|
41
|
+
const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir();
|
|
42
|
+
const base = xdgStateHome && isAbsolute(xdgStateHome) ? xdgStateHome : join(home, ".local", "state");
|
|
43
|
+
return resolve(base, "pantheon", DB_FILENAME);
|
|
44
|
+
}
|
|
45
|
+
function openLocalDecisionBudgetLedger(options = {}) {
|
|
46
|
+
const dbPath = resolve(options.dbPath ?? resolveLocalDecisionBudgetDbPath());
|
|
47
|
+
if (["opencode.db", "install-state.json"].includes(basename(dbPath))) {
|
|
48
|
+
throw new Error("The budget ledger must use its own SQLite database file");
|
|
49
|
+
}
|
|
50
|
+
const busyTimeoutMs = options.busyTimeoutMs ?? 5e3;
|
|
51
|
+
if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 3e4) {
|
|
52
|
+
throw new RangeError("Invalid SQLite busy timeout");
|
|
53
|
+
}
|
|
54
|
+
const wallClock = options.clock ?? Date.now;
|
|
55
|
+
const monotonicClock = options.monotonicClock ?? performance.now.bind(performance);
|
|
56
|
+
const reservationIdFactory = options.reservationIdFactory ?? randomUUID;
|
|
57
|
+
const directoryPath = dirname(dbPath);
|
|
58
|
+
ensureTrustedDirectoryChain(directoryPath);
|
|
59
|
+
try {
|
|
60
|
+
const file = openSync(dbPath, "wx", 384);
|
|
61
|
+
closeSync(file);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error.code !== "EEXIST") throw error;
|
|
64
|
+
}
|
|
65
|
+
const fileStat = lstatSync(dbPath);
|
|
66
|
+
if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1) {
|
|
67
|
+
throw new Error("Budget ledger path is not a private regular file");
|
|
68
|
+
}
|
|
69
|
+
if (typeof process.getuid !== "function" || fileStat.uid !== process.getuid()) {
|
|
70
|
+
throw new Error("Budget ledger file must be owned by the current user");
|
|
71
|
+
}
|
|
72
|
+
chmodSync(dbPath, 384);
|
|
73
|
+
const db = new DatabaseSync(dbPath);
|
|
74
|
+
try {
|
|
75
|
+
db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}; PRAGMA foreign_keys = ON;`);
|
|
76
|
+
ensureSchema(db);
|
|
77
|
+
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
|
|
78
|
+
validateSchema(db);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
db.close();
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
let previousWallClock;
|
|
84
|
+
let previousMonotonicClock;
|
|
85
|
+
const now = () => {
|
|
86
|
+
const wall = wallClock();
|
|
87
|
+
const monotonic = monotonicClock();
|
|
88
|
+
if (!Number.isSafeInteger(wall) || wall < 0 || !Number.isFinite(new Date(wall).getTime())) {
|
|
89
|
+
throw new Error("Invalid ledger wall clock");
|
|
90
|
+
}
|
|
91
|
+
if (!Number.isFinite(monotonic) || monotonic < 0) {
|
|
92
|
+
throw new Error("Invalid ledger monotonic clock");
|
|
93
|
+
}
|
|
94
|
+
if (previousWallClock !== void 0 && previousMonotonicClock !== void 0) {
|
|
95
|
+
const wallElapsed = wall - previousWallClock;
|
|
96
|
+
const monotonicElapsed = monotonic - previousMonotonicClock;
|
|
97
|
+
if (monotonicElapsed < 0 || wallElapsed < -CLOCK_ROLLBACK_TOLERANCE_MS || wallElapsed + CLOCK_ROLLBACK_TOLERANCE_MS < monotonicElapsed) {
|
|
98
|
+
throw new Error("Untrusted wall-clock movement");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
previousWallClock = wall;
|
|
102
|
+
previousMonotonicClock = monotonic;
|
|
103
|
+
return wall;
|
|
104
|
+
};
|
|
105
|
+
function inImmediateTransaction(operation) {
|
|
106
|
+
db.exec("BEGIN IMMEDIATE");
|
|
107
|
+
try {
|
|
108
|
+
const result = operation();
|
|
109
|
+
db.exec("COMMIT");
|
|
110
|
+
return result;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
try {
|
|
113
|
+
db.exec("ROLLBACK");
|
|
114
|
+
} catch {
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function configureUserCaps(capsInput) {
|
|
120
|
+
const caps = validateConfiguredCaps(capsInput);
|
|
121
|
+
inImmediateTransaction(() => {
|
|
122
|
+
const timestamp = now();
|
|
123
|
+
db.prepare(
|
|
124
|
+
`INSERT INTO user_caps (id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
|
|
125
|
+
VALUES (1, ?, ?, ?)
|
|
126
|
+
ON CONFLICT(id) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
|
|
127
|
+
per_decision_cap_micros = excluded.per_decision_cap_micros,
|
|
128
|
+
updated_at_ms = excluded.updated_at_ms`
|
|
129
|
+
).run(caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function configureProviderCaps(provider, capsInput) {
|
|
133
|
+
if (!isAllowedProvider(provider)) throw new TypeError("Invalid budget provider");
|
|
134
|
+
const caps = validateConfiguredCaps(capsInput);
|
|
135
|
+
inImmediateTransaction(() => {
|
|
136
|
+
const timestamp = now();
|
|
137
|
+
db.prepare(
|
|
138
|
+
`INSERT INTO provider_caps (provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
|
|
139
|
+
VALUES (?, ?, ?, ?)
|
|
140
|
+
ON CONFLICT(provider) DO UPDATE SET monthly_cap_micros = excluded.monthly_cap_micros,
|
|
141
|
+
per_decision_cap_micros = excluded.per_decision_cap_micros,
|
|
142
|
+
updated_at_ms = excluded.updated_at_ms`
|
|
143
|
+
).run(provider, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function configureModelCaps(provider, model, capsInput) {
|
|
147
|
+
if (!isAllowedProvider(provider)) throw new TypeError("Invalid budget provider");
|
|
148
|
+
if (!isAllowedModel(model)) throw new TypeError("Invalid budget model key");
|
|
149
|
+
const caps = validateConfiguredCaps(capsInput);
|
|
150
|
+
inImmediateTransaction(() => {
|
|
151
|
+
const timestamp = now();
|
|
152
|
+
db.prepare(
|
|
153
|
+
`INSERT INTO model_caps
|
|
154
|
+
(provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms)
|
|
155
|
+
VALUES (?, ?, ?, ?, ?)
|
|
156
|
+
ON CONFLICT(provider, model) DO UPDATE SET
|
|
157
|
+
monthly_cap_micros = excluded.monthly_cap_micros,
|
|
158
|
+
per_decision_cap_micros = excluded.per_decision_cap_micros,
|
|
159
|
+
updated_at_ms = excluded.updated_at_ms`
|
|
160
|
+
).run(provider, model, caps.monthlyCapMicros, caps.perDecisionCapMicros, timestamp);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
function getActiveBudgetPeriod() {
|
|
164
|
+
const row = db.prepare("SELECT active_period_utc FROM ledger_state WHERE id = 1").get();
|
|
165
|
+
if (!row || row.active_period_utc === null) return null;
|
|
166
|
+
if (!isValidPeriod(row.active_period_utc))
|
|
167
|
+
throw new Error("Invalid active period in budget ledger");
|
|
168
|
+
return row.active_period_utc;
|
|
169
|
+
}
|
|
170
|
+
function confirmBudgetPeriod(expectedCurrentPeriod, targetPeriod) {
|
|
171
|
+
if (expectedCurrentPeriod !== null && !isValidPeriod(expectedCurrentPeriod) || !isValidPeriod(targetPeriod)) {
|
|
172
|
+
return { status: "denied", reason: "invalid-period" };
|
|
173
|
+
}
|
|
174
|
+
return inImmediateTransaction(() => {
|
|
175
|
+
let wallPeriod;
|
|
176
|
+
try {
|
|
177
|
+
wallPeriod = periodFor(now());
|
|
178
|
+
} catch {
|
|
179
|
+
return { status: "denied", reason: "clock-untrusted" };
|
|
180
|
+
}
|
|
181
|
+
const activePeriod = getActiveBudgetPeriod();
|
|
182
|
+
if (activePeriod !== expectedCurrentPeriod) {
|
|
183
|
+
return { status: "denied", reason: "stale-current" };
|
|
184
|
+
}
|
|
185
|
+
if (activePeriod === null) {
|
|
186
|
+
if (targetPeriod !== wallPeriod) {
|
|
187
|
+
return { status: "denied", reason: "wall-clock-mismatch" };
|
|
188
|
+
}
|
|
189
|
+
db.prepare(
|
|
190
|
+
`INSERT INTO ledger_state (id, active_period_utc) VALUES (1, ?)
|
|
191
|
+
ON CONFLICT(id) DO UPDATE SET active_period_utc = excluded.active_period_utc`
|
|
192
|
+
).run(targetPeriod);
|
|
193
|
+
return { status: "confirmed", activePeriod: targetPeriod };
|
|
194
|
+
}
|
|
195
|
+
if (targetPeriod < activePeriod) return { status: "denied", reason: "backwards" };
|
|
196
|
+
if (targetPeriod === activePeriod) return { status: "denied", reason: "not-next-month" };
|
|
197
|
+
if (nextPeriod(activePeriod) !== targetPeriod) {
|
|
198
|
+
return { status: "denied", reason: "not-next-month" };
|
|
199
|
+
}
|
|
200
|
+
if (wallPeriod !== targetPeriod) {
|
|
201
|
+
return { status: "denied", reason: "wall-clock-mismatch" };
|
|
202
|
+
}
|
|
203
|
+
db.prepare("UPDATE ledger_state SET active_period_utc = ? WHERE id = 1").run(targetPeriod);
|
|
204
|
+
return { status: "confirmed", activePeriod: targetPeriod };
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
function reserve(provider, model) {
|
|
208
|
+
if (!isAllowedProvider(provider)) return { status: "denied", reason: "invalid-provider" };
|
|
209
|
+
if (!isAllowedModel(model)) return { status: "denied", reason: "invalid-model" };
|
|
210
|
+
return inImmediateTransaction(() => {
|
|
211
|
+
const admission = checkAdmission(provider, model);
|
|
212
|
+
if (admission.status === "denied") return admission;
|
|
213
|
+
const reservationId = reservationIdFactory();
|
|
214
|
+
if (typeof reservationId !== "string" || !RESERVATION_ID.test(reservationId)) {
|
|
215
|
+
throw new Error("Invalid generated reservation identifier");
|
|
216
|
+
}
|
|
217
|
+
const duplicate = db.prepare("SELECT 1 AS found FROM reservations WHERE id = ?").get(reservationId);
|
|
218
|
+
if (duplicate) return { status: "denied", reason: "duplicate-reservation-id" };
|
|
219
|
+
db.prepare(
|
|
220
|
+
`INSERT INTO reservations
|
|
221
|
+
(id, provider, model, period_utc, reserved_micros, actual_micros, state,
|
|
222
|
+
created_at_ms, updated_at_ms)
|
|
223
|
+
VALUES (?, ?, ?, ?, ?, NULL, 'pending', ?, ?)`
|
|
224
|
+
).run(
|
|
225
|
+
reservationId,
|
|
226
|
+
provider,
|
|
227
|
+
model,
|
|
228
|
+
admission.period,
|
|
229
|
+
admission.reservedMicros,
|
|
230
|
+
admission.timestamp,
|
|
231
|
+
admission.timestamp
|
|
232
|
+
);
|
|
233
|
+
return {
|
|
234
|
+
status: "reserved",
|
|
235
|
+
reservationId,
|
|
236
|
+
period: admission.period,
|
|
237
|
+
reservedMicros: admission.reservedMicros
|
|
238
|
+
};
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
function canReserve(provider, model) {
|
|
242
|
+
if (!isAllowedProvider(provider)) return { status: "denied", reason: "invalid-provider" };
|
|
243
|
+
if (!isAllowedModel(model)) return { status: "denied", reason: "invalid-model" };
|
|
244
|
+
return inImmediateTransaction(() => {
|
|
245
|
+
const admission = checkAdmission(provider, model);
|
|
246
|
+
return admission.status === "denied" ? admission : { status: "eligible" };
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
function checkAdmission(provider, model) {
|
|
250
|
+
let timestamp;
|
|
251
|
+
let wallPeriod;
|
|
252
|
+
try {
|
|
253
|
+
timestamp = now();
|
|
254
|
+
wallPeriod = periodFor(timestamp);
|
|
255
|
+
} catch {
|
|
256
|
+
return { status: "denied", reason: "clock-untrusted" };
|
|
257
|
+
}
|
|
258
|
+
const userCaps = readUserCaps();
|
|
259
|
+
const providerCaps = readProviderCaps(provider);
|
|
260
|
+
const modelCaps = readModelCaps(provider, model);
|
|
261
|
+
if (!hasPositiveCaps(userCaps) || !hasPositiveCaps(providerCaps) || !hasPositiveCaps(modelCaps)) {
|
|
262
|
+
return { status: "denied", reason: "no-cap" };
|
|
263
|
+
}
|
|
264
|
+
const period = getActiveBudgetPeriod();
|
|
265
|
+
if (period === null) return { status: "denied", reason: "period-unconfirmed" };
|
|
266
|
+
if (wallPeriod !== period) return { status: "denied", reason: "period-mismatch" };
|
|
267
|
+
const reservedMicros = modelCaps.per_decision_cap_micros;
|
|
268
|
+
if (reservedMicros > userCaps.per_decision_cap_micros || reservedMicros > providerCaps.per_decision_cap_micros) {
|
|
269
|
+
return { status: "denied", reason: "per-decision-cap" };
|
|
270
|
+
}
|
|
271
|
+
if (isFrozen(period, provider, model)) return { status: "denied", reason: "frozen" };
|
|
272
|
+
if (wouldExceed(sumReservations(period), reservedMicros, userCaps.monthly_cap_micros) || wouldExceed(
|
|
273
|
+
sumReservations(period, provider),
|
|
274
|
+
reservedMicros,
|
|
275
|
+
providerCaps.monthly_cap_micros
|
|
276
|
+
) || wouldExceed(
|
|
277
|
+
sumReservations(period, provider, model),
|
|
278
|
+
reservedMicros,
|
|
279
|
+
modelCaps.monthly_cap_micros
|
|
280
|
+
)) {
|
|
281
|
+
return { status: "denied", reason: "monthly-cap" };
|
|
282
|
+
}
|
|
283
|
+
return { status: "eligible", period, reservedMicros, timestamp };
|
|
284
|
+
}
|
|
285
|
+
function reconcileVerified(reservationId, evidence) {
|
|
286
|
+
if (typeof reservationId !== "string" || !RESERVATION_ID.test(reservationId)) {
|
|
287
|
+
return { status: "unknown" };
|
|
288
|
+
}
|
|
289
|
+
const verified = getVerifiedUsageEvidenceDetails(evidence);
|
|
290
|
+
if (!verified || !Number.isSafeInteger(verified.actualCostMicros) || verified.actualCostMicros <= 0 || !isAllowedProvider(verified.provider) || !isAllowedModel(verified.model) || !isValidPeriod(verified.period)) {
|
|
291
|
+
return { status: "unknown" };
|
|
292
|
+
}
|
|
293
|
+
return inImmediateTransaction(() => {
|
|
294
|
+
const row = db.prepare(
|
|
295
|
+
`SELECT provider, model, period_utc, reserved_micros, state
|
|
296
|
+
FROM reservations WHERE id = ?`
|
|
297
|
+
).get(reservationId);
|
|
298
|
+
if (!row) return { status: "missing" };
|
|
299
|
+
if (row.state === "reconciled") return { status: "already-reconciled" };
|
|
300
|
+
if (row.state !== "pending" && row.state !== "uncertain") {
|
|
301
|
+
throw new Error("Invalid reservation state");
|
|
302
|
+
}
|
|
303
|
+
if (verified.reservationId !== reservationId || verified.provider !== row.provider || verified.model !== row.model || verified.period !== row.period_utc) {
|
|
304
|
+
return { status: "mismatch" };
|
|
305
|
+
}
|
|
306
|
+
const timestamp = now();
|
|
307
|
+
const update = db.prepare(
|
|
308
|
+
`UPDATE reservations SET actual_micros = ?, state = 'reconciled', updated_at_ms = ?
|
|
309
|
+
WHERE id = ? AND state IN ('pending', 'uncertain')`
|
|
310
|
+
).run(verified.actualCostMicros, timestamp, reservationId);
|
|
311
|
+
if (safeChangeCount(update.changes) !== 1) {
|
|
312
|
+
throw new Error("Reservation state changed unexpectedly");
|
|
313
|
+
}
|
|
314
|
+
const frozen = verified.actualCostMicros > row.reserved_micros;
|
|
315
|
+
if (frozen) freezeBuckets(row.period_utc, row.provider, row.model, timestamp);
|
|
316
|
+
return { status: "reconciled", actualCostMicros: verified.actualCostMicros, frozen };
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
function sumReservations(period, provider, model) {
|
|
320
|
+
const where = ["period_utc >= ?"];
|
|
321
|
+
const params = [period];
|
|
322
|
+
if (provider !== void 0) {
|
|
323
|
+
where.push("provider = ?");
|
|
324
|
+
params.push(provider);
|
|
325
|
+
}
|
|
326
|
+
if (model !== void 0) {
|
|
327
|
+
where.push("model = ?");
|
|
328
|
+
params.push(model);
|
|
329
|
+
}
|
|
330
|
+
const row = db.prepare(
|
|
331
|
+
`SELECT COALESCE(SUM(CASE WHEN state = 'reconciled' THEN actual_micros ELSE reserved_micros END), 0) AS amount
|
|
332
|
+
FROM reservations WHERE ${where.join(" AND ")}`
|
|
333
|
+
).get(...params);
|
|
334
|
+
return safeMicrosTotal(row.amount);
|
|
335
|
+
}
|
|
336
|
+
function isFrozen(period, provider, model) {
|
|
337
|
+
return Boolean(
|
|
338
|
+
db.prepare(
|
|
339
|
+
`SELECT 1 AS found FROM budget_freezes
|
|
340
|
+
WHERE period_utc >= ? AND (
|
|
341
|
+
(scope = 'user' AND provider IS NULL AND model IS NULL) OR
|
|
342
|
+
(scope = 'provider' AND provider = ? AND model IS NULL) OR
|
|
343
|
+
(scope = 'model' AND provider = ? AND model = ?)
|
|
344
|
+
) LIMIT 1`
|
|
345
|
+
).get(period, provider, provider, model)
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
function freezeBuckets(period, provider, model, timestamp) {
|
|
349
|
+
const insertIfMissing = db.prepare(
|
|
350
|
+
`INSERT INTO budget_freezes (scope, provider, model, period_utc, reason, created_at_ms)
|
|
351
|
+
VALUES (?, ?, ?, ?, 'overrun', ?)
|
|
352
|
+
ON CONFLICT DO NOTHING`
|
|
353
|
+
);
|
|
354
|
+
insertIfMissing.run("user", null, null, period, timestamp);
|
|
355
|
+
insertIfMissing.run("provider", provider, null, period, timestamp);
|
|
356
|
+
insertIfMissing.run("model", provider, model, period, timestamp);
|
|
357
|
+
}
|
|
358
|
+
function listUncertainReservations() {
|
|
359
|
+
const rows = db.prepare(
|
|
360
|
+
`SELECT id, provider, model, period_utc, reserved_micros, state, created_at_ms, updated_at_ms
|
|
361
|
+
FROM reservations WHERE state IN ('pending', 'uncertain') ORDER BY created_at_ms, id`
|
|
362
|
+
).all();
|
|
363
|
+
return rows.map((row) => ({
|
|
364
|
+
reservationId: row.id,
|
|
365
|
+
provider: row.provider,
|
|
366
|
+
model: row.model,
|
|
367
|
+
period: row.period_utc,
|
|
368
|
+
reservedMicros: row.reserved_micros,
|
|
369
|
+
state: row.state,
|
|
370
|
+
createdAtMs: row.created_at_ms,
|
|
371
|
+
updatedAtMs: row.updated_at_ms
|
|
372
|
+
}));
|
|
373
|
+
}
|
|
374
|
+
function recoverPendingReservations() {
|
|
375
|
+
return inImmediateTransaction(() => {
|
|
376
|
+
const timestamp = now();
|
|
377
|
+
const result = db.prepare(
|
|
378
|
+
`UPDATE reservations SET state = 'uncertain', updated_at_ms = ? WHERE state = 'pending'`
|
|
379
|
+
).run(timestamp);
|
|
380
|
+
return safeChangeCount(result.changes);
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
function pruneCompletedPeriods() {
|
|
384
|
+
return inImmediateTransaction(() => {
|
|
385
|
+
let currentPeriod;
|
|
386
|
+
try {
|
|
387
|
+
currentPeriod = periodFor(now());
|
|
388
|
+
} catch {
|
|
389
|
+
return 0;
|
|
390
|
+
}
|
|
391
|
+
const activePeriod = getActiveBudgetPeriod();
|
|
392
|
+
if (activePeriod === null || currentPeriod !== activePeriod) return 0;
|
|
393
|
+
const result = db.prepare(
|
|
394
|
+
`DELETE FROM reservations AS completed
|
|
395
|
+
WHERE completed.period_utc < ? AND completed.state = 'reconciled'
|
|
396
|
+
AND NOT EXISTS (
|
|
397
|
+
SELECT 1 FROM reservations AS unresolved
|
|
398
|
+
WHERE unresolved.period_utc = completed.period_utc
|
|
399
|
+
AND unresolved.state IN ('pending', 'uncertain')
|
|
400
|
+
)`
|
|
401
|
+
).run(activePeriod);
|
|
402
|
+
db.prepare(
|
|
403
|
+
`DELETE FROM budget_freezes
|
|
404
|
+
WHERE period_utc < ? AND NOT EXISTS (
|
|
405
|
+
SELECT 1 FROM reservations AS unresolved
|
|
406
|
+
WHERE unresolved.period_utc = budget_freezes.period_utc
|
|
407
|
+
AND unresolved.state IN ('pending', 'uncertain')
|
|
408
|
+
)`
|
|
409
|
+
).run(activePeriod);
|
|
410
|
+
return safeChangeCount(result.changes);
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
function readUserCaps() {
|
|
414
|
+
return db.prepare("SELECT monthly_cap_micros, per_decision_cap_micros FROM user_caps WHERE id = 1").get();
|
|
415
|
+
}
|
|
416
|
+
function readProviderCaps(provider) {
|
|
417
|
+
return db.prepare(
|
|
418
|
+
"SELECT monthly_cap_micros, per_decision_cap_micros FROM provider_caps WHERE provider = ?"
|
|
419
|
+
).get(provider);
|
|
420
|
+
}
|
|
421
|
+
function readModelCaps(provider, model) {
|
|
422
|
+
return db.prepare(
|
|
423
|
+
`SELECT monthly_cap_micros, per_decision_cap_micros
|
|
424
|
+
FROM model_caps WHERE provider = ? AND model = ?`
|
|
425
|
+
).get(provider, model);
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
configureUserCaps,
|
|
429
|
+
configureProviderCaps,
|
|
430
|
+
configureModelCaps,
|
|
431
|
+
confirmBudgetPeriod,
|
|
432
|
+
getActiveBudgetPeriod,
|
|
433
|
+
canReserve,
|
|
434
|
+
reserve,
|
|
435
|
+
reconcileVerified,
|
|
436
|
+
listUncertainReservations,
|
|
437
|
+
recoverPendingReservations,
|
|
438
|
+
pruneCompletedPeriods,
|
|
439
|
+
close: () => db.close()
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
function ensureSchema(db) {
|
|
443
|
+
db.exec("BEGIN IMMEDIATE");
|
|
444
|
+
try {
|
|
445
|
+
const version = db.prepare("PRAGMA user_version").get().user_version;
|
|
446
|
+
const applicationId = db.prepare("PRAGMA application_id").get().application_id;
|
|
447
|
+
if (version === 0) {
|
|
448
|
+
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all();
|
|
449
|
+
if (applicationId !== 0 || tables.length !== 0) {
|
|
450
|
+
throw new Error("Refusing to initialize an unrecognized SQLite database");
|
|
451
|
+
}
|
|
452
|
+
createSchemaV3(db);
|
|
453
|
+
} else if (version === 1 && applicationId === APPLICATION_ID) {
|
|
454
|
+
migrateVersionOne(db);
|
|
455
|
+
migrateVersionTwoToThree(db);
|
|
456
|
+
} else if (version === VERSION_TWO && applicationId === APPLICATION_ID) {
|
|
457
|
+
migrateVersionTwoToThree(db);
|
|
458
|
+
} else if (version !== SCHEMA_VERSION || applicationId !== APPLICATION_ID) {
|
|
459
|
+
throw new Error("Unsupported or incompatible local decision budget database schema");
|
|
460
|
+
}
|
|
461
|
+
db.exec("COMMIT");
|
|
462
|
+
} catch (error) {
|
|
463
|
+
try {
|
|
464
|
+
db.exec("ROLLBACK");
|
|
465
|
+
} catch {
|
|
466
|
+
}
|
|
467
|
+
throw error;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
function createSchemaV3(db) {
|
|
471
|
+
db.exec(`
|
|
472
|
+
CREATE TABLE user_caps (
|
|
473
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
474
|
+
monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
|
|
475
|
+
per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
|
|
476
|
+
updated_at_ms INTEGER NOT NULL
|
|
477
|
+
) STRICT;
|
|
478
|
+
CREATE TABLE provider_caps (
|
|
479
|
+
provider TEXT PRIMARY KEY NOT NULL,
|
|
480
|
+
monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
|
|
481
|
+
per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
|
|
482
|
+
updated_at_ms INTEGER NOT NULL
|
|
483
|
+
) STRICT;
|
|
484
|
+
CREATE TABLE model_caps (
|
|
485
|
+
provider TEXT NOT NULL,
|
|
486
|
+
model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
|
|
487
|
+
monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
|
|
488
|
+
per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
|
|
489
|
+
updated_at_ms INTEGER NOT NULL,
|
|
490
|
+
PRIMARY KEY (provider, model)
|
|
491
|
+
) STRICT;
|
|
492
|
+
CREATE TABLE reservations (
|
|
493
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
494
|
+
provider TEXT NOT NULL,
|
|
495
|
+
model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
|
|
496
|
+
period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
|
|
497
|
+
reserved_micros INTEGER NOT NULL CHECK (reserved_micros > 0),
|
|
498
|
+
actual_micros INTEGER CHECK (actual_micros IS NULL OR actual_micros >= 0),
|
|
499
|
+
state TEXT NOT NULL CHECK (state IN ('pending', 'uncertain', 'reconciled')),
|
|
500
|
+
created_at_ms INTEGER NOT NULL,
|
|
501
|
+
updated_at_ms INTEGER NOT NULL,
|
|
502
|
+
CHECK ((state = 'reconciled' AND actual_micros IS NOT NULL) OR
|
|
503
|
+
(state IN ('pending', 'uncertain') AND actual_micros IS NULL))
|
|
504
|
+
) STRICT;
|
|
505
|
+
CREATE INDEX reservations_provider_period_idx ON reservations (provider, period_utc, state);
|
|
506
|
+
CREATE INDEX reservations_model_period_idx
|
|
507
|
+
ON reservations (provider, model, period_utc, state);
|
|
508
|
+
CREATE INDEX reservations_period_state_idx ON reservations (period_utc, state);
|
|
509
|
+
CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
|
|
510
|
+
CREATE TABLE ledger_state (
|
|
511
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
512
|
+
active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
|
|
513
|
+
) STRICT;
|
|
514
|
+
CREATE TABLE budget_freezes (
|
|
515
|
+
id INTEGER PRIMARY KEY,
|
|
516
|
+
scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
|
|
517
|
+
provider TEXT,
|
|
518
|
+
model TEXT,
|
|
519
|
+
period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
|
|
520
|
+
reason TEXT NOT NULL CHECK (reason = 'overrun'),
|
|
521
|
+
created_at_ms INTEGER NOT NULL,
|
|
522
|
+
CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
|
|
523
|
+
(scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
|
|
524
|
+
(scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
|
|
525
|
+
) STRICT;
|
|
526
|
+
CREATE UNIQUE INDEX budget_freezes_unique_idx
|
|
527
|
+
ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
|
|
528
|
+
CREATE INDEX budget_freezes_period_scope_idx
|
|
529
|
+
ON budget_freezes (period_utc, scope, provider, model);
|
|
530
|
+
PRAGMA application_id = ${APPLICATION_ID};
|
|
531
|
+
PRAGMA user_version = ${SCHEMA_VERSION};
|
|
532
|
+
`);
|
|
533
|
+
}
|
|
534
|
+
function migrateVersionTwoToThree(db) {
|
|
535
|
+
validateVersionTwoSchema(db);
|
|
536
|
+
db.exec(`
|
|
537
|
+
UPDATE reservations SET
|
|
538
|
+
reserved_micros = CASE
|
|
539
|
+
WHEN actual_micros > reserved_micros THEN actual_micros
|
|
540
|
+
ELSE reserved_micros
|
|
541
|
+
END,
|
|
542
|
+
state = 'uncertain', actual_micros = NULL
|
|
543
|
+
WHERE state = 'reconciled';
|
|
544
|
+
ALTER TABLE ledger_state RENAME TO ledger_state_v2;
|
|
545
|
+
CREATE TABLE ledger_state (
|
|
546
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
547
|
+
active_period_utc TEXT CHECK (active_period_utc IS NULL OR length(active_period_utc) = 7)
|
|
548
|
+
) STRICT;
|
|
549
|
+
INSERT INTO ledger_state (id, active_period_utc)
|
|
550
|
+
SELECT id, NULL FROM ledger_state_v2;
|
|
551
|
+
DROP TABLE ledger_state_v2;
|
|
552
|
+
PRAGMA user_version = ${SCHEMA_VERSION};
|
|
553
|
+
`);
|
|
554
|
+
}
|
|
555
|
+
function migrateVersionOne(db) {
|
|
556
|
+
validateVersionOneSchema(db);
|
|
557
|
+
const providers = db.prepare("SELECT DISTINCT provider FROM reservations UNION SELECT provider FROM provider_caps").all();
|
|
558
|
+
if (providers.some(({ provider }) => provider !== "openai-decisions" && provider !== "jev")) {
|
|
559
|
+
throw new Error("Refusing to migrate an unsupported version-one provider");
|
|
560
|
+
}
|
|
561
|
+
db.exec(`
|
|
562
|
+
ALTER TABLE reservations
|
|
563
|
+
ADD COLUMN model TEXT NOT NULL DEFAULT 'legacy-unknown'
|
|
564
|
+
CHECK (length(model) BETWEEN 1 AND 128);
|
|
565
|
+
UPDATE reservations SET model = 'gpt-6-luna' WHERE provider = 'openai-decisions';
|
|
566
|
+
UPDATE reservations SET provider = 'typesafe-jev', model = 'jev-1.14.0' WHERE provider = 'jev';
|
|
567
|
+
UPDATE provider_caps SET provider = 'typesafe-jev' WHERE provider = 'jev';
|
|
568
|
+
CREATE TABLE user_caps (
|
|
569
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
570
|
+
monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
|
|
571
|
+
per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
|
|
572
|
+
updated_at_ms INTEGER NOT NULL
|
|
573
|
+
) STRICT;
|
|
574
|
+
CREATE TABLE model_caps (
|
|
575
|
+
provider TEXT NOT NULL,
|
|
576
|
+
model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 128),
|
|
577
|
+
monthly_cap_micros INTEGER NOT NULL CHECK (monthly_cap_micros >= 0),
|
|
578
|
+
per_decision_cap_micros INTEGER NOT NULL CHECK (per_decision_cap_micros >= 0),
|
|
579
|
+
updated_at_ms INTEGER NOT NULL,
|
|
580
|
+
PRIMARY KEY (provider, model)
|
|
581
|
+
) STRICT;
|
|
582
|
+
CREATE INDEX reservations_model_period_idx
|
|
583
|
+
ON reservations (provider, model, period_utc, state);
|
|
584
|
+
CREATE INDEX reservations_state_created_idx ON reservations (state, created_at_ms, id);
|
|
585
|
+
CREATE TABLE budget_freezes (
|
|
586
|
+
id INTEGER PRIMARY KEY,
|
|
587
|
+
scope TEXT NOT NULL CHECK (scope IN ('user', 'provider', 'model')),
|
|
588
|
+
provider TEXT,
|
|
589
|
+
model TEXT,
|
|
590
|
+
period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
|
|
591
|
+
reason TEXT NOT NULL CHECK (reason = 'overrun'),
|
|
592
|
+
created_at_ms INTEGER NOT NULL,
|
|
593
|
+
CHECK ((scope = 'user' AND provider IS NULL AND model IS NULL) OR
|
|
594
|
+
(scope = 'provider' AND provider IS NOT NULL AND model IS NULL) OR
|
|
595
|
+
(scope = 'model' AND provider IS NOT NULL AND model IS NOT NULL))
|
|
596
|
+
) STRICT;
|
|
597
|
+
CREATE UNIQUE INDEX budget_freezes_unique_idx
|
|
598
|
+
ON budget_freezes (scope, ifnull(provider, ''), ifnull(model, ''), period_utc);
|
|
599
|
+
CREATE INDEX budget_freezes_period_scope_idx
|
|
600
|
+
ON budget_freezes (period_utc, scope, provider, model);
|
|
601
|
+
PRAGMA user_version = ${VERSION_TWO};
|
|
602
|
+
`);
|
|
603
|
+
}
|
|
604
|
+
function validateVersionOneSchema(db) {
|
|
605
|
+
db.prepare(
|
|
606
|
+
`SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
|
|
607
|
+
FROM provider_caps LIMIT 0`
|
|
608
|
+
);
|
|
609
|
+
db.prepare(
|
|
610
|
+
`SELECT id, provider, period_utc, reserved_micros, actual_micros, state,
|
|
611
|
+
created_at_ms, updated_at_ms FROM reservations LIMIT 0`
|
|
612
|
+
);
|
|
613
|
+
db.prepare("SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0");
|
|
614
|
+
}
|
|
615
|
+
function validateVersionTwoSchema(db) {
|
|
616
|
+
db.prepare(
|
|
617
|
+
"SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0"
|
|
618
|
+
);
|
|
619
|
+
db.prepare(
|
|
620
|
+
"SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM provider_caps LIMIT 0"
|
|
621
|
+
);
|
|
622
|
+
db.prepare(
|
|
623
|
+
"SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM model_caps LIMIT 0"
|
|
624
|
+
);
|
|
625
|
+
db.prepare(
|
|
626
|
+
`SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
|
|
627
|
+
created_at_ms, updated_at_ms FROM reservations LIMIT 0`
|
|
628
|
+
);
|
|
629
|
+
db.prepare("SELECT id, highest_period_utc, last_seen_ms FROM ledger_state LIMIT 0");
|
|
630
|
+
db.prepare(
|
|
631
|
+
"SELECT id, scope, provider, model, period_utc, reason, created_at_ms FROM budget_freezes LIMIT 0"
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
function validateSchema(db) {
|
|
635
|
+
db.prepare(
|
|
636
|
+
`SELECT id, monthly_cap_micros, per_decision_cap_micros, updated_at_ms FROM user_caps LIMIT 0`
|
|
637
|
+
);
|
|
638
|
+
db.prepare(
|
|
639
|
+
`SELECT provider, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
|
|
640
|
+
FROM provider_caps LIMIT 0`
|
|
641
|
+
);
|
|
642
|
+
db.prepare(
|
|
643
|
+
`SELECT provider, model, monthly_cap_micros, per_decision_cap_micros, updated_at_ms
|
|
644
|
+
FROM model_caps LIMIT 0`
|
|
645
|
+
);
|
|
646
|
+
db.prepare(
|
|
647
|
+
`SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
|
|
648
|
+
created_at_ms, updated_at_ms FROM reservations LIMIT 0`
|
|
649
|
+
);
|
|
650
|
+
db.prepare("SELECT id, active_period_utc FROM ledger_state LIMIT 0");
|
|
651
|
+
db.prepare(
|
|
652
|
+
`SELECT id, scope, provider, model, period_utc, reason, created_at_ms
|
|
653
|
+
FROM budget_freezes LIMIT 0`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
function validateConfiguredCaps(value) {
|
|
657
|
+
if (!isPlainRecord(value)) throw new TypeError("Caps must be an object");
|
|
658
|
+
const keys = Object.keys(value).sort();
|
|
659
|
+
if (keys.join(",") !== "monthlyCapMicros,perDecisionCapMicros") {
|
|
660
|
+
throw new TypeError("Caps must contain only monthly and per-decision values");
|
|
661
|
+
}
|
|
662
|
+
if (!isValidCap(value.monthlyCapMicros) || !isValidCap(value.perDecisionCapMicros)) {
|
|
663
|
+
throw new TypeError("Caps must be non-negative safe integer USD micros");
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
monthlyCapMicros: value.monthlyCapMicros,
|
|
667
|
+
perDecisionCapMicros: value.perDecisionCapMicros
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function isPlainRecord(value) {
|
|
671
|
+
try {
|
|
672
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
673
|
+
} catch {
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
function isAllowedProvider(provider) {
|
|
678
|
+
return typeof provider === "string" && ALLOWED_PROVIDERS.has(provider);
|
|
679
|
+
}
|
|
680
|
+
function isAllowedModel(model) {
|
|
681
|
+
return typeof model === "string" && MODEL_KEY.test(model);
|
|
682
|
+
}
|
|
683
|
+
function isValidCap(value) {
|
|
684
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
685
|
+
}
|
|
686
|
+
function hasPositiveCaps(value) {
|
|
687
|
+
return Boolean(
|
|
688
|
+
value && isValidCap(value.monthly_cap_micros) && value.monthly_cap_micros > 0 && isValidCap(value.per_decision_cap_micros) && value.per_decision_cap_micros > 0
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
function wouldExceed(current, additional, cap) {
|
|
692
|
+
return current > cap || additional > cap - current;
|
|
693
|
+
}
|
|
694
|
+
function safeMicrosTotal(value) {
|
|
695
|
+
if (typeof value === "bigint") {
|
|
696
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < 0n) {
|
|
697
|
+
throw new Error("Invalid spend total in budget ledger");
|
|
698
|
+
}
|
|
699
|
+
return Number(value);
|
|
700
|
+
}
|
|
701
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
702
|
+
throw new Error("Invalid spend total in budget ledger");
|
|
703
|
+
}
|
|
704
|
+
return value;
|
|
705
|
+
}
|
|
706
|
+
function periodFor(timestamp) {
|
|
707
|
+
const period = new Date(timestamp).toISOString().slice(0, 7);
|
|
708
|
+
if (!isValidPeriod(period)) throw new Error("Invalid UTC accounting period");
|
|
709
|
+
return period;
|
|
710
|
+
}
|
|
711
|
+
function isValidPeriod(value) {
|
|
712
|
+
return /^\d{4}-(0[1-9]|1[0-2])$/.test(value);
|
|
713
|
+
}
|
|
714
|
+
function nextPeriod(period) {
|
|
715
|
+
if (!isValidPeriod(period)) return null;
|
|
716
|
+
let year = Number(period.slice(0, 4));
|
|
717
|
+
let month = Number(period.slice(5, 7)) + 1;
|
|
718
|
+
if (month === 13) {
|
|
719
|
+
year += 1;
|
|
720
|
+
month = 1;
|
|
721
|
+
}
|
|
722
|
+
if (year > 9999) return null;
|
|
723
|
+
return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}`;
|
|
724
|
+
}
|
|
725
|
+
function safeChangeCount(value) {
|
|
726
|
+
const count = Number(value);
|
|
727
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new Error("Invalid SQLite change count");
|
|
728
|
+
return count;
|
|
729
|
+
}
|
|
730
|
+
function ensureTrustedDirectoryChain(directoryPath) {
|
|
731
|
+
if (process.platform === "win32" || typeof process.getuid !== "function") {
|
|
732
|
+
throw new Error("Secure budget-ledger path validation is unavailable on this platform");
|
|
733
|
+
}
|
|
734
|
+
const uid = process.getuid();
|
|
735
|
+
const absolute = resolve(directoryPath);
|
|
736
|
+
const root = parse(absolute).root;
|
|
737
|
+
let current = root;
|
|
738
|
+
validateDirectoryTrust(lstatSync(current), uid, current === absolute);
|
|
739
|
+
for (const component of absolute.slice(root.length).split(sep).filter(Boolean)) {
|
|
740
|
+
current = join(current, component);
|
|
741
|
+
try {
|
|
742
|
+
lstatSync(current);
|
|
743
|
+
} catch (error) {
|
|
744
|
+
if (error.code !== "ENOENT") throw error;
|
|
745
|
+
try {
|
|
746
|
+
mkdirSync(current, { mode: 448 });
|
|
747
|
+
} catch (mkdirError) {
|
|
748
|
+
if (mkdirError.code !== "EEXIST") throw mkdirError;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const stat = lstatSync(current);
|
|
752
|
+
const isFinalDirectory = current === absolute;
|
|
753
|
+
validateDirectoryTrust(stat, uid, isFinalDirectory);
|
|
754
|
+
if (isFinalDirectory) {
|
|
755
|
+
chmodSync(current, 448);
|
|
756
|
+
validateDirectoryTrust(lstatSync(current), uid, true);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
function validateDirectoryTrust(stat, uid, isFinalDirectory) {
|
|
761
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
762
|
+
throw new Error("Budget ledger path contains a non-directory or symlink ancestor");
|
|
763
|
+
}
|
|
764
|
+
if (stat.uid !== uid && stat.uid !== 0) {
|
|
765
|
+
throw new Error("Budget ledger path contains an untrusted owner");
|
|
766
|
+
}
|
|
767
|
+
if (isFinalDirectory && stat.uid !== uid) {
|
|
768
|
+
throw new Error("Budget ledger directory must be owned by the current user");
|
|
769
|
+
}
|
|
770
|
+
const mode = stat.mode & 4095;
|
|
771
|
+
const writableByOthers = (mode & 18) !== 0;
|
|
772
|
+
const rootStickyDirectory = stat.uid === 0 && (mode & 512) !== 0;
|
|
773
|
+
if (writableByOthers && !rootStickyDirectory) {
|
|
774
|
+
throw new Error("Budget ledger path contains a group/other-writable directory");
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
export {
|
|
778
|
+
LOCAL_DECISION_BUDGET_PROVIDERS,
|
|
779
|
+
openLocalDecisionBudgetLedger,
|
|
780
|
+
resolveLocalDecisionBudgetDbPath
|
|
781
|
+
};
|