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