hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3

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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +89 -2
  3. package/dist/adapter-kit.d.ts +37 -0
  4. package/dist/adapter-kit.js +34 -0
  5. package/dist/adapter-kit.js.map +1 -0
  6. package/dist/agent-Bj5YPrO7.d.ts +169 -0
  7. package/dist/agent-D6OXR7UF.js +24 -0
  8. package/dist/agent-D6OXR7UF.js.map +1 -0
  9. package/dist/agent-readiness-KSGNKTGK.js +19 -0
  10. package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
  11. package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
  12. package/dist/chunk-2RK74GCA.js +2397 -0
  13. package/dist/chunk-2RK74GCA.js.map +1 -0
  14. package/dist/chunk-3TIYA3K5.js +55 -0
  15. package/dist/chunk-3TIYA3K5.js.map +1 -0
  16. package/dist/chunk-6FIXXWNM.js +1 -0
  17. package/dist/chunk-6FIXXWNM.js.map +1 -0
  18. package/dist/chunk-6XIJW65Q.js +52 -0
  19. package/dist/chunk-6XIJW65Q.js.map +1 -0
  20. package/dist/chunk-7LDQKJKI.js +248 -0
  21. package/dist/chunk-7LDQKJKI.js.map +1 -0
  22. package/dist/chunk-CPN4DOXH.js +115 -0
  23. package/dist/chunk-CPN4DOXH.js.map +1 -0
  24. package/dist/chunk-DAXPAV2L.js +810 -0
  25. package/dist/chunk-DAXPAV2L.js.map +1 -0
  26. package/dist/chunk-DQEMIGKC.js +291 -0
  27. package/dist/chunk-DQEMIGKC.js.map +1 -0
  28. package/dist/chunk-DZFFGUIA.js +81 -0
  29. package/dist/chunk-DZFFGUIA.js.map +1 -0
  30. package/dist/chunk-EEUYQFCP.js +106 -0
  31. package/dist/chunk-EEUYQFCP.js.map +1 -0
  32. package/dist/chunk-G6JV7WV6.js +521 -0
  33. package/dist/chunk-G6JV7WV6.js.map +1 -0
  34. package/dist/chunk-GFVYNPLS.js +118 -0
  35. package/dist/chunk-GFVYNPLS.js.map +1 -0
  36. package/dist/chunk-GS5U3KUN.js +201 -0
  37. package/dist/chunk-GS5U3KUN.js.map +1 -0
  38. package/dist/chunk-HB7FBSH2.js +960 -0
  39. package/dist/chunk-HB7FBSH2.js.map +1 -0
  40. package/dist/chunk-HZFZX5A3.js +21 -0
  41. package/dist/chunk-HZFZX5A3.js.map +1 -0
  42. package/dist/chunk-J7VAYJKM.js +595 -0
  43. package/dist/chunk-J7VAYJKM.js.map +1 -0
  44. package/dist/chunk-NCNSHOF7.js +52 -0
  45. package/dist/chunk-NCNSHOF7.js.map +1 -0
  46. package/dist/chunk-RH5A5U7G.js +202 -0
  47. package/dist/chunk-RH5A5U7G.js.map +1 -0
  48. package/dist/chunk-RX3XZENU.js +385 -0
  49. package/dist/chunk-RX3XZENU.js.map +1 -0
  50. package/dist/chunk-RXU2Q2HF.js +49 -0
  51. package/dist/chunk-RXU2Q2HF.js.map +1 -0
  52. package/dist/chunk-TG7NTMTR.js +208 -0
  53. package/dist/chunk-TG7NTMTR.js.map +1 -0
  54. package/dist/chunk-TWGEYWMO.js +1217 -0
  55. package/dist/chunk-TWGEYWMO.js.map +1 -0
  56. package/dist/chunk-UZPDDQVJ.js +2910 -0
  57. package/dist/chunk-UZPDDQVJ.js.map +1 -0
  58. package/dist/chunk-WMKO5XOE.js +601 -0
  59. package/dist/chunk-WMKO5XOE.js.map +1 -0
  60. package/dist/chunk-WOQBVJH5.js +175 -0
  61. package/dist/chunk-WOQBVJH5.js.map +1 -0
  62. package/dist/chunk-WVT5SEKC.js +581 -0
  63. package/dist/chunk-WVT5SEKC.js.map +1 -0
  64. package/dist/cli.d.ts +1 -0
  65. package/dist/cli.js +26 -0
  66. package/dist/cli.js.map +1 -0
  67. package/dist/errors-BNHvvjn9.d.ts +98 -0
  68. package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
  69. package/dist/execution-types-ClYYqPQP.d.ts +239 -0
  70. package/dist/host-ledger-VPRWVVOS.js +25 -0
  71. package/dist/host-ledger-VPRWVVOS.js.map +1 -0
  72. package/dist/hosted-runtime.d.ts +168 -0
  73. package/dist/hosted-runtime.js +858 -0
  74. package/dist/hosted-runtime.js.map +1 -0
  75. package/dist/index-B86C6VAD.d.ts +41 -0
  76. package/dist/index.d.ts +344 -0
  77. package/dist/index.js +8825 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/memory-items-BSTC0_R0.d.ts +28 -0
  80. package/dist/memory-tools.d.ts +222 -0
  81. package/dist/memory-tools.js +923 -0
  82. package/dist/memory-tools.js.map +1 -0
  83. package/dist/orchestration/dynamic.d.ts +854 -0
  84. package/dist/orchestration/dynamic.js +3150 -0
  85. package/dist/orchestration/dynamic.js.map +1 -0
  86. package/dist/orchestration/graph.d.ts +11 -0
  87. package/dist/orchestration/graph.js +9 -0
  88. package/dist/orchestration/graph.js.map +1 -0
  89. package/dist/orchestration/index.d.ts +2385 -0
  90. package/dist/orchestration/index.js +6409 -0
  91. package/dist/orchestration/index.js.map +1 -0
  92. package/dist/orchestration/log.d.ts +301 -0
  93. package/dist/orchestration/log.js +3058 -0
  94. package/dist/orchestration/log.js.map +1 -0
  95. package/dist/orchestration/memory.d.ts +711 -0
  96. package/dist/orchestration/memory.js +27 -0
  97. package/dist/orchestration/memory.js.map +1 -0
  98. package/dist/provider-DX5Mf0uq.d.ts +151 -0
  99. package/dist/routing/index.d.ts +29 -0
  100. package/dist/routing/index.js +386 -0
  101. package/dist/routing/index.js.map +1 -0
  102. package/dist/routing/learning/index.d.ts +433 -0
  103. package/dist/routing/learning/index.js +2502 -0
  104. package/dist/routing/learning/index.js.map +1 -0
  105. package/dist/runtime-BSjrnxeF.d.ts +283 -0
  106. package/dist/runtime-OISPXS4I.js +19 -0
  107. package/dist/runtime-OISPXS4I.js.map +1 -0
  108. package/dist/store-types-2YdceOMy.d.ts +78 -0
  109. package/dist/types-BB7KqceP.d.ts +52 -0
  110. package/dist/types-CIqkKXix.d.ts +86 -0
  111. package/dist/types-DTFc1qO6.d.ts +1065 -0
  112. package/dist/types-DYex3p7_.d.ts +88 -0
  113. package/docs/licenses/ruflo-memory-MIT.txt +21 -0
  114. package/docs/releases/0.1.0-beta.3.md +13 -0
  115. package/package.json +114 -4
@@ -0,0 +1,960 @@
1
+ import {
2
+ absolutePath,
3
+ busyTimeout,
4
+ closedRecord,
5
+ identifier,
6
+ integer,
7
+ record,
8
+ validateFiniteOptions
9
+ } from "./chunk-RXU2Q2HF.js";
10
+ import {
11
+ observedUsageLimitReset
12
+ } from "./chunk-TG7NTMTR.js";
13
+
14
+ // src/orchestration/budget/host-ledger.ts
15
+ import { closeSync as closeSync2, lstatSync as lstatSync3, mkdirSync, openSync as openSync2, writeFileSync } from "node:fs";
16
+ import { dirname as dirname2 } from "node:path";
17
+ import { performance } from "node:perf_hooks";
18
+ import { randomUUID as randomUUID3 } from "node:crypto";
19
+
20
+ // src/orchestration/budget/engine.ts
21
+ import { randomUUID as randomUUID2 } from "node:crypto";
22
+ import { types } from "node:util";
23
+
24
+ // src/orchestration/budget/sqlite.ts
25
+ import { createHash, randomUUID } from "node:crypto";
26
+ import { closeSync, fsyncSync, linkSync, lstatSync, openSync, realpathSync, unlinkSync } from "node:fs";
27
+ import { dirname } from "node:path";
28
+ import { DatabaseSync } from "node:sqlite";
29
+ var APPLICATION_ID = 1329680962;
30
+ var CLOCK_AUDIT_TABLE = `
31
+ CREATE TABLE IF NOT EXISTS budget_clock_acknowledgements (
32
+ provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),
33
+ previous_observed_at INTEGER NOT NULL CHECK(previous_observed_at BETWEEN 0 AND 9007199254740991),
34
+ acknowledged_at INTEGER NOT NULL CHECK(acknowledged_at BETWEEN 0 AND 9007199254740991),
35
+ pid INTEGER NOT NULL CHECK(pid BETWEEN 0 AND 9007199254740991)
36
+ ) STRICT;`;
37
+ var PRUNING_SCHEMA = `
38
+ CREATE TABLE IF NOT EXISTS budget_pruning_state (
39
+ provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),
40
+ pruned_through INTEGER NOT NULL CHECK(pruned_through BETWEEN 0 AND 9007199254740991)
41
+ ) STRICT;
42
+ CREATE TRIGGER IF NOT EXISTS budget_track_pruning AFTER DELETE ON budget_reservations
43
+ BEGIN
44
+ INSERT INTO budget_pruning_state(provider_key, pruned_through) VALUES (OLD.provider_key, OLD.admitted_at)
45
+ ON CONFLICT(provider_key) DO UPDATE SET pruned_through = MAX(budget_pruning_state.pruned_through, excluded.pruned_through);
46
+ END;`;
47
+ function installPruningTracking(db) {
48
+ const tracked = db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'budget_pruning_state'").get();
49
+ db.exec(PRUNING_SCHEMA);
50
+ if (!tracked) db.exec(`INSERT INTO budget_pruning_state(provider_key, pruned_through)
51
+ SELECT provider_key, last_observed_at - 86400000 FROM budget_providers WHERE last_observed_at >= 86400000;`);
52
+ }
53
+ var SCHEMA = `
54
+ CREATE TABLE budget_providers (
55
+ provider_key TEXT PRIMARY KEY NOT NULL CHECK(length(provider_key) BETWEEN 1 AND 256),
56
+ max_concurrent INTEGER NOT NULL CHECK(max_concurrent BETWEEN 0 AND 9007199254740991),
57
+ max_hour INTEGER NOT NULL CHECK(max_hour BETWEEN 0 AND 9007199254740991),
58
+ max_day INTEGER NOT NULL CHECK(max_day BETWEEN 0 AND 9007199254740991),
59
+ cooldown_ms INTEGER NOT NULL CHECK(cooldown_ms BETWEEN 1 AND 9007199254740991),
60
+ paused_until INTEGER NOT NULL CHECK(paused_until BETWEEN 0 AND 9007199254740991),
61
+ last_observed_at INTEGER NOT NULL CHECK(last_observed_at BETWEEN 0 AND 9007199254740991)
62
+ ) STRICT;
63
+ CREATE TABLE budget_reservations (
64
+ token TEXT PRIMARY KEY NOT NULL,
65
+ provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),
66
+ owner TEXT NOT NULL CHECK(length(owner) BETWEEN 1 AND 256),
67
+ admitted_at INTEGER NOT NULL CHECK(admitted_at BETWEEN 0 AND 9007199254740991),
68
+ released INTEGER NOT NULL DEFAULT 0 CHECK(released IN (0, 1))
69
+ ) STRICT;
70
+ CREATE INDEX budget_reservations_provider_time ON budget_reservations(provider_key, admitted_at);
71
+ ${CLOCK_AUDIT_TABLE}
72
+ ${PRUNING_SCHEMA}
73
+ PRAGMA application_id = ${APPLICATION_ID};
74
+ PRAGMA user_version = 1;
75
+ `;
76
+ function publishNewDatabase(path) {
77
+ const temporary = `${path}.${randomUUID()}.initializing`;
78
+ closeSync(openSync(temporary, "wx", 384));
79
+ let candidate;
80
+ try {
81
+ candidate = new DatabaseSync(temporary);
82
+ candidate.exec(`PRAGMA synchronous = FULL; BEGIN IMMEDIATE; ${SCHEMA} COMMIT;`);
83
+ candidate.close();
84
+ candidate = void 0;
85
+ try {
86
+ linkSync(temporary, path);
87
+ } catch (error) {
88
+ if (error.code !== "EEXIST") throw error;
89
+ }
90
+ const directory = openSync(dirname(path), "r");
91
+ try {
92
+ fsyncSync(directory);
93
+ } finally {
94
+ closeSync(directory);
95
+ }
96
+ } finally {
97
+ candidate?.close();
98
+ unlinkSync(temporary);
99
+ }
100
+ }
101
+ var BudgetDatabase = class {
102
+ db;
103
+ path;
104
+ identity;
105
+ #configured = false;
106
+ #pruningReady = false;
107
+ #busyTimeoutMs;
108
+ constructor(path, busyTimeoutMs) {
109
+ this.path = path;
110
+ this.#busyTimeoutMs = busyTimeoutMs;
111
+ try {
112
+ lstatSync(path);
113
+ } catch (error) {
114
+ if (error.code !== "ENOENT") throw error;
115
+ publishNewDatabase(path);
116
+ }
117
+ const stat = lstatSync(path, { bigint: true });
118
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Budget database must be a regular file");
119
+ this.identity = { dev: stat.dev, ino: stat.ino };
120
+ this.db = new DatabaseSync(path);
121
+ try {
122
+ this.#configure();
123
+ this.db.exec("BEGIN IMMEDIATE");
124
+ try {
125
+ this.verify();
126
+ installPruningTracking(this.db);
127
+ this.db.exec("COMMIT");
128
+ this.#pruningReady = true;
129
+ } catch (error) {
130
+ this.db.exec("ROLLBACK");
131
+ throw error;
132
+ }
133
+ } catch (error) {
134
+ const code = error instanceof Error && "errcode" in error ? error.errcode : void 0;
135
+ if (typeof code !== "number" || ![5, 6].includes(code & 255)) {
136
+ this.db.close();
137
+ throw error;
138
+ }
139
+ }
140
+ }
141
+ #configure() {
142
+ this.db.exec(`PRAGMA busy_timeout = ${this.#busyTimeoutMs}; PRAGMA foreign_keys = ON; PRAGMA synchronous = FULL;`);
143
+ this.#configured = true;
144
+ }
145
+ verify() {
146
+ const current = lstatSync(this.path, { bigint: true });
147
+ if (!current.isFile() || current.isSymbolicLink() || current.dev !== this.identity.dev || current.ino !== this.identity.ino) {
148
+ throw new Error("Budget database was replaced or removed");
149
+ }
150
+ if (this.db.prepare("PRAGMA application_id").get()?.application_id !== APPLICATION_ID || this.db.prepare("PRAGMA user_version").get()?.user_version !== 1) {
151
+ throw new Error("Unrecognized budget database version");
152
+ }
153
+ const check = this.db.prepare("PRAGMA quick_check(1)").get();
154
+ if (check?.quick_check !== "ok" || this.db.prepare("PRAGMA foreign_key_check").get() !== void 0) {
155
+ throw new Error("Budget database integrity check failed");
156
+ }
157
+ }
158
+ /** Called inside this pinned connection's verified transaction. No mutable budget rows are hashed. */
159
+ storageDigest() {
160
+ const path = realpathSync(this.path);
161
+ this.verify();
162
+ return createHash("sha256").update(JSON.stringify([
163
+ "oar-host-ledger",
164
+ 1,
165
+ APPLICATION_ID,
166
+ path,
167
+ String(this.identity.dev),
168
+ String(this.identity.ino)
169
+ ])).digest("hex");
170
+ }
171
+ transaction(work) {
172
+ if (!this.#configured) this.#configure();
173
+ this.db.exec("BEGIN IMMEDIATE");
174
+ try {
175
+ this.verify();
176
+ if (!this.#pruningReady) installPruningTracking(this.db);
177
+ const result = work(this.db);
178
+ this.db.exec("COMMIT");
179
+ this.#pruningReady = true;
180
+ return result;
181
+ } catch (error) {
182
+ try {
183
+ this.db.exec("ROLLBACK");
184
+ } catch {
185
+ }
186
+ throw error;
187
+ }
188
+ }
189
+ close() {
190
+ this.db.close();
191
+ }
192
+ };
193
+
194
+ // src/orchestration/budget/legacy-migration.ts
195
+ import { createHash as createHash2 } from "node:crypto";
196
+ import { lstatSync as lstatSync2 } from "node:fs";
197
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
198
+ var legacyKey = (path, prefix) => createHash2("sha256").update(JSON.stringify([path, prefix])).digest("hex");
199
+ var legacyToken = (key, token) => `legacy:${createHash2("sha256").update(JSON.stringify([key, token])).digest("hex")}`;
200
+ var LEGACY_MIGRATIONS = `CREATE TABLE IF NOT EXISTS budget_legacy_migrations (
201
+ migration_key TEXT PRIMARY KEY, source_digest TEXT NOT NULL, imported_at INTEGER NOT NULL
202
+ ) STRICT;
203
+ CREATE TABLE IF NOT EXISTS budget_legacy_imported_tokens (token TEXT PRIMARY KEY NOT NULL) STRICT;`;
204
+ function readLegacySnapshot(databasePath) {
205
+ absolutePath(databasePath);
206
+ const before = lstatSync2(databasePath);
207
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 64 * 1024 * 1024) throw new Error("Legacy ledger must be a bounded regular file");
208
+ const db = new DatabaseSync2(databasePath, { readOnly: true });
209
+ try {
210
+ db.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 1000; BEGIN;");
211
+ if (db.prepare("PRAGMA application_id").get()?.application_id !== 1329680962 || db.prepare("PRAGMA user_version").get()?.user_version !== 1 || db.prepare("PRAGMA quick_check(1)").get()?.quick_check !== "ok" || db.prepare("PRAGMA foreign_key_check").get() !== void 0) throw new Error("Unrecognized or corrupt legacy ledger");
212
+ const hasPruning = !!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='budget_pruning_state'").get();
213
+ const pruning = new Map(hasPruning ? db.prepare("SELECT provider_key,pruned_through FROM budget_pruning_state LIMIT 1001").all().map((row) => {
214
+ if (!identifier(row.provider_key) || !integer(row.pruned_through)) throw new Error("Invalid legacy pruning state");
215
+ return [row.provider_key, row.pruned_through];
216
+ }) : []);
217
+ if (pruning.size > 1e3) throw new Error("Legacy pruning count exceeds migration budget");
218
+ const providers = db.prepare("SELECT * FROM budget_providers ORDER BY provider_key LIMIT 1001").all().map((row) => {
219
+ if (!identifier(row.provider_key) || !["max_concurrent", "max_hour", "max_day", "paused_until", "last_observed_at"].every((key) => integer(row[key])) || !integer(row.cooldown_ms, 1)) throw new Error("Invalid legacy provider state");
220
+ return {
221
+ providerKey: row.provider_key,
222
+ pausedUntil: Number(row.paused_until),
223
+ observedAt: Number(row.last_observed_at),
224
+ prunedThrough: pruning.get(row.provider_key) ?? Math.max(0, Number(row.last_observed_at) - 864e5)
225
+ };
226
+ });
227
+ if (providers.length > 1e3) throw new Error("Legacy provider count exceeds migration budget");
228
+ const known = new Set(providers.map((row) => row.providerKey));
229
+ const reservations = db.prepare("SELECT * FROM budget_reservations ORDER BY token LIMIT 100001").all().map((row) => {
230
+ if (!identifier(row.token) || !identifier(row.provider_key) || !known.has(row.provider_key) || !identifier(row.owner) || !integer(row.admitted_at) || ![0, 1].includes(Number(row.released))) throw new Error("Invalid legacy reservation");
231
+ return { token: row.token, providerKey: row.provider_key, owner: row.owner, admittedAt: Number(row.admitted_at), released: Number(row.released) };
232
+ });
233
+ if (reservations.length > 1e5) throw new Error("Legacy reservation count exceeds migration budget");
234
+ const after = lstatSync2(databasePath);
235
+ if (!after.isFile() || after.isSymbolicLink() || after.dev !== before.dev || after.ino !== before.ino) throw new Error("Legacy ledger replaced during inspection");
236
+ const sourceDigest = createHash2("sha256").update(JSON.stringify({ providers, reservations })).digest("hex");
237
+ return { databasePath, sourceDigest, providers, reservations, identity: { dev: before.dev, ino: before.ino } };
238
+ } finally {
239
+ db.close();
240
+ }
241
+ }
242
+ function inspectLegacyLaunchBudget(databasePath) {
243
+ const snapshot = readLegacySnapshot(databasePath);
244
+ return { sourceDigest: snapshot.sourceDigest, providers: snapshot.providers.map((provider) => {
245
+ const rows = snapshot.reservations.filter((row) => row.providerKey === provider.providerKey);
246
+ return { providerKey: provider.providerKey, reservations: rows.length, active: rows.filter((row) => !row.released).length };
247
+ }) };
248
+ }
249
+
250
+ // src/orchestration/budget/host-options.ts
251
+ import { homedir } from "node:os";
252
+ import { join } from "node:path";
253
+ function validateConcurrency(value) {
254
+ if (!record(value) || !(closedRecord(value, ["mode"]) && value.mode === "unlimited" || closedRecord(value, ["mode", "maxConcurrent"]) && value.mode === "limited" && integer(value.maxConcurrent))) {
255
+ throw new TypeError("Concurrency requires explicit limited integer or unlimited mode");
256
+ }
257
+ }
258
+ function hostLaunchLimits(concurrency) {
259
+ validateConcurrency(concurrency);
260
+ return { concurrency: { ...concurrency }, maxLaunchesPerHour: 400, maxLaunchesPerDay: 800, quotaCooldownMs: 6e4 };
261
+ }
262
+ var HOST_LAUNCH_LIMITS = Object.freeze({
263
+ ...hostLaunchLimits({ mode: "limited", maxConcurrent: 3 }),
264
+ concurrency: Object.freeze({ mode: "limited", maxConcurrent: 3 })
265
+ });
266
+ function hostLedgerPath(env = process.env, platform = process.platform) {
267
+ if (env.OAR_HOST_LEDGER !== void 0) {
268
+ absolutePath(env.OAR_HOST_LEDGER);
269
+ return env.OAR_HOST_LEDGER;
270
+ }
271
+ const home = env.HOME || homedir();
272
+ const root = platform === "darwin" ? join(home, "Library", "Application Support") : platform === "win32" ? env.LOCALAPPDATA || join(home, "AppData", "Local") : env.XDG_STATE_HOME || join(home, ".local", "state");
273
+ absolutePath(root);
274
+ return join(root, "open-agent-runtime", "host", "admission.sqlite");
275
+ }
276
+ function validateHostOptions(options) {
277
+ const keys = ["databasePath", "concurrency", "providers", "busyTimeoutMs"];
278
+ if (!closedRecord(options, keys, keys) || Object.values(options).some((value) => value === void 0) || Object.hasOwn(options, "providers") && Object.hasOwn(options, "concurrency")) {
279
+ throw new TypeError("Provide either explicit providers or concurrency shorthand");
280
+ }
281
+ busyTimeout(options.busyTimeoutMs);
282
+ const databasePath = options.databasePath === void 0 ? hostLedgerPath() : options.databasePath;
283
+ absolutePath(databasePath);
284
+ const concurrency = Object.hasOwn(options, "concurrency") ? options.concurrency : HOST_LAUNCH_LIMITS.concurrency;
285
+ validateConcurrency(concurrency);
286
+ const providers = Object.hasOwn(options, "providers") ? options.providers : { claude: hostLaunchLimits(concurrency), codex: hostLaunchLimits(concurrency) };
287
+ if (!record(providers)) throw new TypeError("Explicit providers must be a plain JSON record");
288
+ const policies = /* @__PURE__ */ new Map();
289
+ const fields = ["concurrency", "maxLaunchesPerHour", "maxLaunchesPerDay", "quotaCooldownMs"];
290
+ for (const key of Reflect.ownKeys(providers)) {
291
+ const desc = Object.getOwnPropertyDescriptor(providers, key), value = desc?.value;
292
+ if (!identifier(key) || !desc?.enumerable || !Object.hasOwn(desc, "value") || !closedRecord(value, fields) || !integer(value.maxLaunchesPerHour) || !integer(value.maxLaunchesPerDay) || !integer(value.quotaCooldownMs, 1)) throw new TypeError("Invalid host provider policy");
293
+ validateConcurrency(value.concurrency);
294
+ policies.set(key, { concurrency: { ...value.concurrency }, maxLaunchesPerHour: value.maxLaunchesPerHour, maxLaunchesPerDay: value.maxLaunchesPerDay, quotaCooldownMs: value.quotaCooldownMs });
295
+ }
296
+ return { databasePath, policies, busyTimeoutMs: options.busyTimeoutMs === void 0 ? 1e3 : Number(options.busyTimeoutMs) };
297
+ }
298
+
299
+ // src/orchestration/budget/priority.ts
300
+ var WAITER_LEASE_MS = 9e4;
301
+ var RANK = Object.freeze({ low: 0, normal: 1 });
302
+ var TOP_RANK = RANK.normal;
303
+ var WAITERS_SCHEMA = `
304
+ CREATE TABLE IF NOT EXISTS budget_waiters (
305
+ waiter TEXT PRIMARY KEY NOT NULL CHECK(length(waiter) BETWEEN 1 AND 256),
306
+ provider_key TEXT NOT NULL REFERENCES budget_providers(provider_key),
307
+ priority INTEGER NOT NULL CHECK(priority BETWEEN 0 AND 255),
308
+ seen_at INTEGER NOT NULL CHECK(seen_at BETWEEN 0 AND 9007199254740991)
309
+ ) STRICT;
310
+ CREATE INDEX IF NOT EXISTS budget_waiters_provider ON budget_waiters(provider_key, priority);`;
311
+ function isLaunchPriority(value) {
312
+ return typeof value === "string" && Object.hasOwn(RANK, value);
313
+ }
314
+ function validTurn(turn) {
315
+ return isLaunchPriority(turn.priority) && (turn.waiter === void 0 || identifier(turn.waiter));
316
+ }
317
+ function declareWaiter(db, providerKey, turn, now) {
318
+ if (turn.waiter === void 0) return;
319
+ db.exec(WAITERS_SCHEMA);
320
+ db.prepare("DELETE FROM budget_waiters WHERE seen_at <= ?").run(now - WAITER_LEASE_MS);
321
+ db.prepare(`INSERT INTO budget_waiters(waiter, provider_key, priority, seen_at) VALUES (?, ?, ?, ?)
322
+ ON CONFLICT(waiter) DO UPDATE SET provider_key = excluded.provider_key, priority = excluded.priority, seen_at = excluded.seen_at`).run(turn.waiter, providerKey, RANK[turn.priority], now);
323
+ }
324
+ function isOutranked(db, providerKey, turn, now) {
325
+ const rank = RANK[turn.priority];
326
+ if (rank >= TOP_RANK) return false;
327
+ db.exec(WAITERS_SCHEMA);
328
+ const ahead = db.prepare(`SELECT 1 AS found FROM budget_waiters
329
+ WHERE provider_key = ? AND priority > ? AND seen_at > ? AND waiter <> ? LIMIT 1`).get(providerKey, rank, now - WAITER_LEASE_MS, turn.waiter ?? "");
330
+ return ahead !== void 0;
331
+ }
332
+ function forgetWaiter(db, waiter) {
333
+ db.exec(WAITERS_SCHEMA);
334
+ return db.prepare("DELETE FROM budget_waiters WHERE waiter = ?").run(waiter).changes === 1;
335
+ }
336
+
337
+ // src/orchestration/budget/engine.ts
338
+ var HOUR = 36e5;
339
+ var DAY = 864e5;
340
+ var Denied = class extends Error {
341
+ failure;
342
+ constructor(reason, detail, retryAt) {
343
+ super(detail ?? reason);
344
+ this.failure = { reason, ...detail === void 0 ? {} : { detail }, ...retryAt === void 0 ? {} : { retryAt } };
345
+ }
346
+ };
347
+ function rollback(row) {
348
+ return new Denied("clock-rollback", `The system clock is behind the ledger's last observed time ${new Date(row.last_observed_at).toISOString()}`, row.last_observed_at);
349
+ }
350
+ var CONCURRENCY_MODES = `CREATE TABLE IF NOT EXISTS budget_concurrency_modes (
351
+ provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),
352
+ mode TEXT NOT NULL CHECK(mode IN ('limited', 'unlimited'))
353
+ ) STRICT;`;
354
+ var BudgetEngine = class {
355
+ #modes;
356
+ #providers = /* @__PURE__ */ new Map();
357
+ #database;
358
+ #fault;
359
+ #closed = false;
360
+ /** Invalid configuration throws before I/O; unavailable storage fails closed in results. */
361
+ constructor(options, modes = /* @__PURE__ */ new Map()) {
362
+ validateFiniteOptions(options);
363
+ this.#modes = modes;
364
+ for (const [key, limits] of Object.entries(options.providers)) this.#providers.set(key, { ...limits });
365
+ const busyTimeoutMs = options.busyTimeoutMs ?? 1e3;
366
+ try {
367
+ this.#database = new BudgetDatabase(options.databasePath, busyTimeoutMs);
368
+ } catch (error) {
369
+ this.#fault = error instanceof Error ? error.message : String(error);
370
+ }
371
+ }
372
+ reserve(providerKey, owner, mayAdmit, turn) {
373
+ const result = this.#operate((db) => {
374
+ if (!identifier(owner)) throw new Denied("invalid-input", "Owner must be a nonempty identifier of at most 256 characters");
375
+ const { row, limits, now, mode } = this.#provider(db, providerKey);
376
+ if (mayAdmit && !mayAdmit()) return { allowed: false, reason: "wait-timeout" };
377
+ this.#observe(db, row, now);
378
+ const status = this.#status(db, row, limits, now);
379
+ if (turn !== void 0 && !validTurn(turn)) throw new Denied("invalid-input", "Priority must be normal or low");
380
+ if (turn !== void 0) declareWaiter(db, providerKey, turn, now);
381
+ let reason;
382
+ if (row.paused_until > now) return { allowed: false, reason: "quota-cooldown", retryAt: row.paused_until };
383
+ if (mode !== "unlimited" && status.active >= limits.maxConcurrent) reason = "concurrency-limit";
384
+ else if (status.launchesLastHour >= limits.maxLaunchesPerHour) reason = "hourly-limit";
385
+ else if (status.launchesLastDay >= limits.maxLaunchesPerDay) reason = "daily-limit";
386
+ if (!reason && turn !== void 0 && isOutranked(db, providerKey, turn, now)) {
387
+ return { allowed: false, reason: "concurrency-limit", outranked: true };
388
+ }
389
+ if (reason) return { allowed: false, reason };
390
+ if (mayAdmit && !mayAdmit()) return { allowed: false, reason: "wait-timeout" };
391
+ const reservation = { token: randomUUID2(), providerKey, owner, admittedAt: now };
392
+ db.prepare("INSERT INTO budget_reservations(token, provider_key, owner, admitted_at) VALUES (?, ?, ?, ?)").run(reservation.token, providerKey, owner, now);
393
+ if (turn?.waiter !== void 0) forgetWaiter(db, turn.waiter);
394
+ return { allowed: true, reservation };
395
+ });
396
+ if (!result.ok) {
397
+ const { ok: _ok, ...failure } = result;
398
+ return { allowed: false, ...failure };
399
+ }
400
+ return result.value;
401
+ }
402
+ /** Withdraws a waiting caller's declaration once it stops waiting. Frees and grants nothing. */
403
+ stopWaiting(waiter) {
404
+ return this.#flatten(this.#operate((db) => {
405
+ if (!identifier(waiter)) throw new Denied("invalid-input", "Invalid waiter");
406
+ return { withdrawn: forgetWaiter(db, waiter) };
407
+ }));
408
+ }
409
+ /** Idempotent recovery/completion. Unknown tokens free nothing; no launch is refunded. */
410
+ release(token) {
411
+ return this.#flatten(this.#operate((db) => {
412
+ if (!identifier(token)) throw new Denied("invalid-input", "Invalid reservation token");
413
+ const result = db.prepare("UPDATE budget_reservations SET released = 1 WHERE token = ? AND released = 0").run(token);
414
+ return { released: result.changes === 1 };
415
+ }));
416
+ }
417
+ /** Call only after an explicit observed provider quota error. No text heuristics. */
418
+ recordQuotaError(providerKey, retryAtMs) {
419
+ return this.#flatten(this.#operate((db) => {
420
+ const { row, limits, now } = this.#provider(db, providerKey);
421
+ this.#observe(db, row, now);
422
+ if (retryAtMs !== void 0 && !integer(retryAtMs)) throw new Denied("invalid-input", "Invalid quota reset timestamp");
423
+ const pausedUntil = Math.max(row.paused_until, now + limits.quotaCooldownMs, retryAtMs ?? 0);
424
+ if (!integer(pausedUntil)) throw new Denied("invalid-input", "Cooldown would exceed the safe timestamp range");
425
+ db.prepare("UPDATE budget_providers SET paused_until = ? WHERE provider_key = ?").run(pausedUntil, providerKey);
426
+ return { pausedUntil };
427
+ }));
428
+ }
429
+ /** Read-only: compares the clock with the ledger's mark but never advances it. */
430
+ status(providerKey) {
431
+ return this.#flatten(this.#operate((db) => {
432
+ const { row, limits, now } = this.#provider(db, providerKey);
433
+ if (now < row.last_observed_at) throw rollback(row);
434
+ return { status: this.#status(db, row, limits, now) };
435
+ }));
436
+ }
437
+ hostStatus(providerKey) {
438
+ return this.#flatten(this.#operate((db) => {
439
+ const { row, limits, now, mode } = this.#provider(db, providerKey);
440
+ if (now < row.last_observed_at) throw rollback(row);
441
+ const status = this.#status(db, row, limits, now);
442
+ const { maxConcurrent, ...windows } = limits;
443
+ const concurrency = mode === "unlimited" ? { mode } : { mode: "limited", maxConcurrent };
444
+ return { status: { ...status, limits: { ...windows, concurrency } } };
445
+ }));
446
+ }
447
+ /** One revision per provider. Ordinary admissions never replace an existing operator policy. */
448
+ concurrencyPolicy(providerKey, change) {
449
+ return this.#flatten(this.#operate((db) => {
450
+ if (!identifier(providerKey)) throw new Denied("invalid-input");
451
+ if (change !== void 0) {
452
+ if (types.isProxy(change) || !closedRecord(change, ["expectedRevision", "concurrency"]) || !integer(change.expectedRevision) || types.isProxy(change.concurrency))
453
+ throw new Denied("invalid-input");
454
+ try {
455
+ validateConcurrency(change.concurrency);
456
+ } catch {
457
+ throw new Denied("invalid-input");
458
+ }
459
+ }
460
+ let row = db.prepare("SELECT max_concurrent FROM budget_providers WHERE provider_key=?").get(providerKey);
461
+ if (!row) row = { max_concurrent: this.#provider(db, providerKey).row.max_concurrent };
462
+ db.exec(CONCURRENCY_MODES);
463
+ db.exec(`CREATE TABLE IF NOT EXISTS budget_concurrency_revisions (
464
+ provider_key TEXT PRIMARY KEY REFERENCES budget_providers(provider_key),
465
+ revision INTEGER NOT NULL CHECK(revision > 0)
466
+ ) STRICT;`);
467
+ const mode = db.prepare("SELECT mode FROM budget_concurrency_modes WHERE provider_key=?").get(providerKey)?.mode ?? "limited";
468
+ const revision = Number(db.prepare("SELECT revision FROM budget_concurrency_revisions WHERE provider_key=?").get(providerKey)?.revision ?? 0);
469
+ if (!integer(revision) || !integer(row.max_concurrent) || !["limited", "unlimited"].includes(String(mode)) || mode === "unlimited" && row.max_concurrent !== 0) throw Error("Invalid stored concurrency policy");
470
+ const current = mode === "unlimited" ? { mode } : { mode: "limited", maxConcurrent: Number(row.max_concurrent) };
471
+ if (!change) return { policy: { revision, concurrency: current } };
472
+ const next = change.concurrency;
473
+ const same = next.mode === "unlimited" ? current.mode === "unlimited" : current.mode === "limited" && current.maxConcurrent === next.maxConcurrent;
474
+ if (same && (revision === change.expectedRevision || revision === change.expectedRevision + 1)) return { policy: { revision, concurrency: current } };
475
+ if (revision !== change.expectedRevision) throw new Denied("configuration-mismatch", "Concurrency policy revision changed");
476
+ if (!Number.isSafeInteger(revision + 1)) throw new Denied("invalid-input", "Concurrency revision exhausted");
477
+ db.prepare("UPDATE budget_providers SET max_concurrent=? WHERE provider_key=?").run(next.mode === "limited" ? next.maxConcurrent : 0, providerKey);
478
+ db.prepare("INSERT INTO budget_concurrency_modes(provider_key, mode) VALUES(?,?) ON CONFLICT(provider_key) DO UPDATE SET mode=excluded.mode").run(providerKey, next.mode);
479
+ db.prepare("INSERT INTO budget_concurrency_revisions(provider_key, revision) VALUES(?,?) ON CONFLICT(provider_key) DO UPDATE SET revision=excluded.revision").run(providerKey, revision + 1);
480
+ return { policy: { revision: revision + 1, concurrency: { ...next } } };
481
+ }));
482
+ }
483
+ /** Exact bounded inspection, including retained released rows. Absence never proves an old acquisition cannot commit. */
484
+ lookupOwner(providerKey, owner, options) {
485
+ return this.#flatten(this.#operate((db) => {
486
+ if (!identifier(owner) || !options || types.isProxy(options) || !closedRecord(options, ["limit"]) || !integer(options.limit, 1) || options.limit > 100) throw new Denied("invalid-input", "Exact owner and lookup limit 1..100 required");
487
+ const { row, now } = this.#provider(db, providerKey);
488
+ if (now < row.last_observed_at) throw rollback(row);
489
+ const found = db.prepare(`SELECT token, provider_key AS providerKey, owner, admitted_at AS admittedAt, released
490
+ FROM budget_reservations WHERE provider_key = ? AND owner = ? ORDER BY admitted_at, token LIMIT ?`).all(providerKey, owner, options.limit + 1);
491
+ const reservations = found.slice(0, options.limit).map((value) => Object.freeze({
492
+ token: value.token,
493
+ providerKey: value.providerKey,
494
+ owner: value.owner,
495
+ admittedAt: value.admittedAt,
496
+ released: value.released === 1
497
+ }));
498
+ return { reservations: Object.freeze(reservations), truncated: found.length > options.limit };
499
+ }));
500
+ }
501
+ storageIdentity() {
502
+ const result = this.#flatten(this.#operate(() => ({ identity: Object.freeze({
503
+ format: 1,
504
+ digest: this.#database.storageDigest()
505
+ }) })));
506
+ return result.ok ? result : { ok: false, reason: result.reason };
507
+ }
508
+ /**
509
+ * Explicit operator recovery from `clock-rollback` (a date advanced for a test and restored).
510
+ * Moves the ledger's observed time to now. Nothing is refunded: every reservation stays held,
511
+ * future-dated launches keep counting against the rolling windows and an active cooldown keeps
512
+ * pausing. If pruning already removed history the current window could need, acknowledgement
513
+ * is refused until that window expires; legacy ledgers conservatively assume possible pruning.
514
+ * The acknowledgement is recorded in the ledger itself.
515
+ */
516
+ acknowledgeClock(providerKey, acknowledgement) {
517
+ return this.#flatten(this.#operate((db) => {
518
+ if (!closedRecord(acknowledgement, ["operatorConfirmed"]) || acknowledgement.operatorConfirmed !== true) {
519
+ throw new Denied("invalid-input", "Explicitly confirm that an operator verified the system clock");
520
+ }
521
+ const { row, now } = this.#provider(db, providerKey);
522
+ const history = db.prepare("SELECT pruned_through FROM budget_pruning_state WHERE provider_key = ?").get(providerKey);
523
+ if (history && Number(history.pruned_through) > now - DAY) {
524
+ const safeAt = Number(history.pruned_through) + DAY;
525
+ throw new Denied("clock-rollback", "Pruned launch history may still belong to the current budget window; acknowledgement cannot refund it", Number.isSafeInteger(safeAt) ? safeAt : void 0);
526
+ }
527
+ db.exec(CLOCK_AUDIT_TABLE);
528
+ db.prepare("INSERT INTO budget_clock_acknowledgements(provider_key, previous_observed_at, acknowledged_at, pid) VALUES (?, ?, ?, ?)").run(providerKey, row.last_observed_at, now, process.pid);
529
+ db.prepare("UPDATE budget_providers SET last_observed_at = ? WHERE provider_key = ?").run(now, providerKey);
530
+ return { previousObservedAt: row.last_observed_at, acknowledgedAt: now };
531
+ }));
532
+ }
533
+ /** Exact inspected bearer tokens only; no prefix sweep or automatic owner inference. */
534
+ recover(options) {
535
+ if (!closedRecord(options, ["ownerPrefix", "tokens", "acknowledgement"]) || !identifier(options.ownerPrefix) || !Array.isArray(options.tokens) || options.tokens.length > 1e3 || options.tokens.some((token) => !identifier(token)) || new Set(options.tokens).size !== options.tokens.length || !closedRecord(options.acknowledgement, ["workStopped", "evidenceDigest"]) || options.acknowledgement.workStopped !== true || typeof options.acknowledgement.evidenceDigest !== "string" || !/^[a-fA-F0-9]{64}$/u.test(options.acknowledgement.evidenceDigest)) {
536
+ return { ok: false, reason: "invalid-input", detail: "Exact unique tokens and SHA256 evidence of stopped work are required" };
537
+ }
538
+ return this.#flatten(this.#operate((db) => {
539
+ for (const token of options.tokens) {
540
+ const row = db.prepare("SELECT owner, provider_key FROM budget_reservations WHERE token = ?").get(token);
541
+ if (!row || typeof row.owner !== "string" || !row.owner.startsWith(options.ownerPrefix)) {
542
+ throw new Denied("invalid-input", "Selected token is missing or belongs to another owner");
543
+ }
544
+ this.#provider(db, String(row.provider_key));
545
+ }
546
+ let released = 0;
547
+ const update = db.prepare("UPDATE budget_reservations SET released = 1 WHERE token = ? AND released = 0");
548
+ for (const token of options.tokens) released += Number(update.run(token).changes);
549
+ return { released };
550
+ }));
551
+ }
552
+ /** Closing does not release reservations; an operation may still be running. */
553
+ verifyMigration(snapshot, ownerPrefix) {
554
+ return this.#flatten(this.#operate((db) => {
555
+ const exists = db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='budget_legacy_migrations'").get();
556
+ const row = exists ? db.prepare("SELECT source_digest FROM budget_legacy_migrations WHERE migration_key=?").get(legacyKey(snapshot.databasePath, ownerPrefix)) : void 0;
557
+ return { matched: row?.source_digest === snapshot.sourceDigest, sourceDigest: snapshot.sourceDigest };
558
+ }));
559
+ }
560
+ importLegacy(snapshot, ownerPrefix) {
561
+ return this.#flatten(this.#operate((db) => {
562
+ const key = legacyKey(snapshot.databasePath, ownerPrefix);
563
+ db.exec(LEGACY_MIGRATIONS);
564
+ const prior = db.prepare("SELECT source_digest FROM budget_legacy_migrations WHERE migration_key=?").get(key);
565
+ if (prior?.source_digest === snapshot.sourceDigest) return { imported: 0, sourceDigest: snapshot.sourceDigest };
566
+ for (const provider of snapshot.providers) {
567
+ this.#provider(db, provider.providerKey);
568
+ db.prepare("UPDATE budget_providers SET paused_until=MAX(paused_until,?),last_observed_at=MAX(last_observed_at,?) WHERE provider_key=?").run(provider.pausedUntil, provider.observedAt, provider.providerKey);
569
+ db.prepare(`INSERT INTO budget_pruning_state(provider_key,pruned_through) VALUES (?,?)
570
+ ON CONFLICT(provider_key) DO UPDATE SET pruned_through=MAX(pruned_through,excluded.pruned_through)`).run(provider.providerKey, provider.prunedThrough);
571
+ }
572
+ let imported = 0;
573
+ const remember = db.prepare("INSERT INTO budget_legacy_imported_tokens(token) VALUES (?) ON CONFLICT(token) DO NOTHING");
574
+ const insert = db.prepare("INSERT INTO budget_reservations(token,provider_key,owner,admitted_at,released) VALUES (?,?,?,?,?) ON CONFLICT(token) DO NOTHING");
575
+ for (const reservation of snapshot.reservations) {
576
+ const owner = ownerPrefix + reservation.owner;
577
+ if (!identifier(owner)) throw new Denied("invalid-input", "Prefixed legacy owner exceeds identifier bounds");
578
+ const token = legacyToken(key, reservation.token);
579
+ if (remember.run(token).changes === 0) continue;
580
+ imported += Number(insert.run(token, reservation.providerKey, owner, reservation.admittedAt, reservation.released).changes);
581
+ }
582
+ db.prepare(`INSERT INTO budget_legacy_migrations(migration_key,source_digest,imported_at) VALUES (?,?,?)
583
+ ON CONFLICT(migration_key) DO UPDATE SET source_digest=excluded.source_digest,imported_at=excluded.imported_at`).run(key, snapshot.sourceDigest, Date.now());
584
+ return { imported, sourceDigest: snapshot.sourceDigest };
585
+ }));
586
+ }
587
+ close() {
588
+ if (!this.#closed) {
589
+ this.#closed = true;
590
+ this.#database?.close();
591
+ }
592
+ }
593
+ #provider(db, providerKey) {
594
+ const limits = this.#providers.get(providerKey);
595
+ if (!limits) throw new Denied("unknown-provider");
596
+ const now = Date.now();
597
+ if (!integer(now)) throw new Denied("invalid-input", "Invalid system clock");
598
+ db.exec(CONCURRENCY_MODES);
599
+ const inserted = db.prepare(`INSERT INTO budget_providers
600
+ (provider_key, max_concurrent, max_hour, max_day, cooldown_ms, paused_until, last_observed_at)
601
+ VALUES (?, ?, ?, ?, ?, 0, 0) ON CONFLICT(provider_key) DO NOTHING`).run(providerKey, limits.maxConcurrent, limits.maxLaunchesPerHour, limits.maxLaunchesPerDay, limits.quotaCooldownMs);
602
+ const mode = this.#modes.get(providerKey) ?? "limited";
603
+ if (inserted.changes === 1) db.prepare("INSERT INTO budget_concurrency_modes(provider_key, mode) VALUES (?, ?)").run(providerKey, mode);
604
+ const persistedMode = db.prepare("SELECT mode FROM budget_concurrency_modes WHERE provider_key = ?").get(providerKey)?.mode ?? "limited";
605
+ if (persistedMode !== "limited" && persistedMode !== "unlimited") throw Error("Invalid stored concurrency mode");
606
+ const row = db.prepare("SELECT * FROM budget_providers WHERE provider_key = ?").get(providerKey);
607
+ const legacyMismatch = !this.#modes.has(providerKey) && (persistedMode !== mode || row.max_concurrent !== limits.maxConcurrent);
608
+ if (legacyMismatch || row.max_hour !== limits.maxLaunchesPerHour || row.max_day !== limits.maxLaunchesPerDay || row.cooldown_ms !== limits.quotaCooldownMs) throw new Denied("configuration-mismatch");
609
+ if (persistedMode === "unlimited" && row.max_concurrent !== 0) throw Error("Invalid stored unlimited policy");
610
+ return { row, limits: { ...limits, maxConcurrent: row.max_concurrent }, now, mode: persistedMode };
611
+ }
612
+ /** Only a ledger mutation (reserve, recordQuotaError) advances the observed clock; reads never do. */
613
+ #observe(db, row, now) {
614
+ if (now < row.last_observed_at) throw rollback(row);
615
+ db.prepare("UPDATE budget_providers SET last_observed_at = ? WHERE provider_key = ?").run(now, row.provider_key);
616
+ db.prepare("DELETE FROM budget_reservations WHERE provider_key = ? AND admitted_at <= ? AND released = 1").run(row.provider_key, now - DAY);
617
+ }
618
+ #status(db, row, limits, now) {
619
+ const counts = db.prepare(`SELECT COUNT(*) FILTER (WHERE released = 0) AS active,
620
+ COUNT(*) FILTER (WHERE admitted_at > ?) AS hour,
621
+ COUNT(*) FILTER (WHERE admitted_at > ?) AS day FROM budget_reservations WHERE provider_key = ?`).get(now - HOUR, now - DAY, row.provider_key);
622
+ const reservations = db.prepare(`SELECT token, provider_key AS providerKey, owner, admitted_at AS admittedAt
623
+ FROM budget_reservations WHERE provider_key = ? AND released = 0 ORDER BY admitted_at, token`).all(row.provider_key);
624
+ return {
625
+ providerKey: row.provider_key,
626
+ limits: { ...limits },
627
+ active: Number(counts.active),
628
+ launchesLastHour: Number(counts.hour),
629
+ launchesLastDay: Number(counts.day),
630
+ pausedUntil: row.paused_until > now ? row.paused_until : null,
631
+ reservations
632
+ };
633
+ }
634
+ #operate(work) {
635
+ if (this.#closed) return { ok: false, reason: "closed" };
636
+ if (!this.#database) return { ok: false, reason: "storage-unavailable", detail: this.#fault ?? "Database unavailable" };
637
+ try {
638
+ return { ok: true, value: this.#database.transaction(work) };
639
+ } catch (error) {
640
+ if (error instanceof Denied) return { ok: false, ...error.failure };
641
+ return { ok: false, reason: "storage-unavailable", detail: error instanceof Error ? error.message : String(error) };
642
+ }
643
+ }
644
+ #flatten(result) {
645
+ return result.ok ? { ok: true, ...result.value } : result;
646
+ }
647
+ };
648
+
649
+ // src/orchestration/budget/bell.ts
650
+ import { watch } from "node:fs";
651
+ function armBell(path, signal) {
652
+ let rang = false, settled = false;
653
+ let watcher, timer;
654
+ let resolve, reject;
655
+ let aborted = false;
656
+ const cleanup = () => {
657
+ watcher?.close();
658
+ watcher = void 0;
659
+ clearTimeout(timer);
660
+ timer = void 0;
661
+ signal?.removeEventListener("abort", abort);
662
+ };
663
+ const finish = () => {
664
+ if (settled) return;
665
+ settled = true;
666
+ cleanup();
667
+ if (aborted) reject?.(signal?.reason);
668
+ else resolve?.();
669
+ };
670
+ const abort = () => {
671
+ aborted = true;
672
+ rang = true;
673
+ finish();
674
+ };
675
+ try {
676
+ watcher = watch(path, { persistent: false }, () => {
677
+ rang = true;
678
+ if (resolve) finish();
679
+ });
680
+ watcher.on("error", () => {
681
+ watcher?.close();
682
+ watcher = void 0;
683
+ });
684
+ } catch {
685
+ }
686
+ signal?.addEventListener("abort", abort, { once: true });
687
+ if (signal?.aborted) abort();
688
+ return {
689
+ cancel: finish,
690
+ wait(ms) {
691
+ if (aborted) return Promise.reject(signal?.reason);
692
+ if (settled) return Promise.resolve();
693
+ return new Promise((yes, no) => {
694
+ resolve = yes;
695
+ reject = no;
696
+ timer = setTimeout(finish, Math.max(1, Math.min(2147483647, Math.ceil(ms))));
697
+ if (rang) finish();
698
+ });
699
+ }
700
+ };
701
+ }
702
+
703
+ // src/orchestration/budget/host-types.ts
704
+ var LaunchRefusedError = class extends Error {
705
+ admission;
706
+ constructor(admission) {
707
+ super(`Launch refused: ${admission.reason}`);
708
+ this.name = "LaunchRefusedError";
709
+ this.admission = admission;
710
+ }
711
+ };
712
+ var LaunchReleaseError = class extends Error {
713
+ failure;
714
+ constructor(failure, cause) {
715
+ super(`Launch release failed: ${failure.reason}`, { cause });
716
+ this.name = "LaunchReleaseError";
717
+ this.failure = failure;
718
+ }
719
+ };
720
+ var LaunchQuotaRecordError = class extends Error {
721
+ failure;
722
+ constructor(failure, cause) {
723
+ super(`Launch quota recording failed: ${failure.reason}`, { cause });
724
+ this.name = "LaunchQuotaRecordError";
725
+ this.failure = failure;
726
+ }
727
+ };
728
+
729
+ // src/orchestration/budget/host-ledger.ts
730
+ var BACKSTOP_MS = 3e4;
731
+ function snapshotAcquire(options, slot = false) {
732
+ const keys = ["maxWaitMs", "signal", "priority", ...slot ? ["isQuotaError"] : []];
733
+ if (!closedRecord(options, keys, ["signal", "priority", "isQuotaError"]) || !integer(options.maxWaitMs) || options.signal !== void 0 && !(options.signal instanceof AbortSignal) || "isQuotaError" in options && options.isQuotaError !== void 0 && typeof options.isQuotaError !== "function") {
734
+ throw new TypeError("Wait options require a nonnegative safe integer maxWaitMs and an optional AbortSignal");
735
+ }
736
+ if (options.priority !== void 0 && !isLaunchPriority(options.priority)) throw new TypeError('priority must be "normal" or "low"');
737
+ const snapshot = { maxWaitMs: options.maxWaitMs };
738
+ if (options.priority !== void 0) snapshot.priority = options.priority;
739
+ if (options.signal !== void 0) snapshot.signal = options.signal;
740
+ if ("isQuotaError" in options && options.isQuotaError !== void 0) snapshot.isQuotaError = options.isQuotaError;
741
+ return Object.freeze(snapshot);
742
+ }
743
+ var HostLedger = class {
744
+ #engine;
745
+ #bell;
746
+ #databasePath;
747
+ #waits = /* @__PURE__ */ new Set();
748
+ /** Waiting callers of this handle whose declaration may be recorded in the shared file. */
749
+ #queued = /* @__PURE__ */ new Set();
750
+ #closed = false;
751
+ constructor(options = {}) {
752
+ const config = validateHostOptions(options);
753
+ this.#databasePath = config.databasePath;
754
+ this.#bell = `${config.databasePath}.bell`;
755
+ const providers = /* @__PURE__ */ Object.create(null);
756
+ const modes = /* @__PURE__ */ new Map();
757
+ for (const [key, policy] of config.policies) {
758
+ const { concurrency, ...limits } = policy;
759
+ providers[key] = { ...limits, maxConcurrent: concurrency.mode === "limited" ? concurrency.maxConcurrent : 0 };
760
+ modes.set(key, concurrency.mode);
761
+ }
762
+ mkdirSync(dirname2(config.databasePath), { recursive: true, mode: 448 });
763
+ this.#engine = new BudgetEngine({ databasePath: config.databasePath, providers, busyTimeoutMs: config.busyTimeoutMs }, modes);
764
+ try {
765
+ closeSync2(openSync2(this.#bell, "a", 384));
766
+ } catch {
767
+ }
768
+ }
769
+ /** One immediate attempt. A `low` priority is refused while a `normal` launch is waiting for the slot. */
770
+ reserve(providerKey, owner, priority) {
771
+ return this.#engine.reserve(providerKey, owner, void 0, priority === void 0 ? void 0 : { priority });
772
+ }
773
+ release(token) {
774
+ const result = this.#engine.release(token);
775
+ if (result.ok && result.released) this.#ring();
776
+ return result;
777
+ }
778
+ recordQuotaError(providerKey, retryAtMs) {
779
+ const result = this.#engine.recordQuotaError(providerKey, retryAtMs);
780
+ if (result.ok) this.#ring();
781
+ return result;
782
+ }
783
+ status(providerKey) {
784
+ return this.#engine.hostStatus(providerKey);
785
+ }
786
+ getConcurrency(providerKey) {
787
+ return this.#engine.concurrencyPolicy(providerKey);
788
+ }
789
+ setConcurrency(providerKey, change) {
790
+ if (change === void 0) throw new TypeError("A concurrency change is required");
791
+ const result = this.#engine.concurrencyPolicy(providerKey, change);
792
+ if (result.ok) this.#ring();
793
+ return result;
794
+ }
795
+ /** Private host evidence discovery, not an authorization or stopped-work proof; default bound detects duplicate owners. */
796
+ lookupOwner(providerKey, owner, options = { limit: 2 }) {
797
+ return this.#engine.lookupOwner(providerKey, owner, options);
798
+ }
799
+ /** Opaque identity of the actual pinned local database, never worker-supplied authority or stopped-work evidence. */
800
+ storageIdentity() {
801
+ return this.#engine.storageIdentity();
802
+ }
803
+ recover(options) {
804
+ const result = this.#engine.recover(options);
805
+ if (result.ok && result.released > 0) this.#ring();
806
+ return result;
807
+ }
808
+ verifyLegacyMigration(options) {
809
+ try {
810
+ return this.#engine.verifyMigration(this.#legacy(options, false), options.ownerPrefix);
811
+ } catch (error) {
812
+ return { ok: false, reason: error instanceof TypeError ? "invalid-input" : "storage-unavailable" };
813
+ }
814
+ }
815
+ importLegacy(options) {
816
+ try {
817
+ return this.#engine.importLegacy(this.#legacy(options, true), options.ownerPrefix);
818
+ } catch (error) {
819
+ return { ok: false, reason: error instanceof TypeError ? "invalid-input" : "storage-unavailable" };
820
+ }
821
+ }
822
+ #legacy(options, importing) {
823
+ const keys = ["databasePath", "ownerPrefix", ...importing ? ["sourceStoppedConfirmed", "expectedDigest"] : []];
824
+ if (!closedRecord(options, keys) || typeof options.ownerPrefix !== "string" || !options.ownerPrefix.endsWith(":") || options.ownerPrefix.length > 128 || options.ownerPrefix.trim() !== options.ownerPrefix || /[\x00-\x20\x7f]/.test(options.ownerPrefix) || importing && (!("sourceStoppedConfirmed" in options) || options.sourceStoppedConfirmed !== true || !("expectedDigest" in options) || typeof options.expectedDigest !== "string" || !/^[a-f0-9]{64}$/.test(options.expectedDigest))) {
825
+ throw new TypeError("A reviewed legacy source and explicit stopped-source acknowledgement are required");
826
+ }
827
+ const snapshot = readLegacySnapshot(options.databasePath), target = lstatSync3(this.#databasePath);
828
+ if (snapshot.identity.dev === target.dev && snapshot.identity.ino === target.ino) throw new TypeError("Legacy source and host ledger must differ");
829
+ if (importing && "expectedDigest" in options && options.expectedDigest !== snapshot.sourceDigest) throw new TypeError("Legacy source changed after inspection");
830
+ return snapshot;
831
+ }
832
+ close() {
833
+ this.#closed = true;
834
+ this.#leaveQueue([...this.#queued]);
835
+ this.#engine.close();
836
+ for (const cancel of this.#waits) cancel();
837
+ this.#waits.clear();
838
+ }
839
+ async acquire(providerKey, owner, options) {
840
+ const snapshot = snapshotAcquire(options);
841
+ return this.#acquire(providerKey, owner, snapshot);
842
+ }
843
+ /**
844
+ * Admission in priority order. A caller that waits is declared in the shared file from its first
845
+ * refused attempt until it is admitted or stops waiting, and other handles are woken when it leaves.
846
+ */
847
+ #acquire(providerKey, owner, options) {
848
+ const turn = { priority: options.priority ?? "normal" };
849
+ if (options.maxWaitMs === 0) return this.#attempts(providerKey, owner, options, turn);
850
+ const waiter = randomUUID3();
851
+ turn.waiter = waiter;
852
+ return this.#attempts(providerKey, owner, options, turn).finally(() => {
853
+ if (this.#queued.has(waiter)) this.#leaveQueue([waiter]);
854
+ });
855
+ }
856
+ #leaveQueue(waiters) {
857
+ for (const waiter of waiters) {
858
+ this.#queued.delete(waiter);
859
+ this.#engine.stopWaiting(waiter);
860
+ }
861
+ if (waiters.length > 0) this.#ring();
862
+ }
863
+ async #attempts(providerKey, owner, options, turn) {
864
+ const deadline = performance.now() + options.maxWaitMs;
865
+ for (; ; ) {
866
+ options.signal?.throwIfAborted();
867
+ if (options.maxWaitMs > 0 && performance.now() >= deadline) return { allowed: false, reason: "wait-timeout" };
868
+ const bell = armBell(this.#bell, options.signal);
869
+ this.#waits.add(bell.cancel);
870
+ let admission;
871
+ try {
872
+ if (options.maxWaitMs > 0) await new Promise((resolve) => {
873
+ setImmediate(resolve);
874
+ });
875
+ if (options.maxWaitMs > 0) {
876
+ await new Promise((resolve) => {
877
+ setImmediate(resolve);
878
+ });
879
+ options.signal?.throwIfAborted();
880
+ }
881
+ admission = options.maxWaitMs === 0 ? this.#engine.reserve(providerKey, owner, void 0, turn) : this.#engine.reserve(providerKey, owner, () => performance.now() < deadline && !options.signal?.aborted, turn);
882
+ if (!admission.allowed && turn.waiter !== void 0 && !this.#closed) this.#queued.add(turn.waiter);
883
+ if (!admission.allowed && "outranked" in admission && options.maxWaitMs > 0) {
884
+ options.signal?.throwIfAborted();
885
+ const left = deadline - performance.now();
886
+ if (left <= 0) return { allowed: false, reason: "wait-timeout" };
887
+ await bell.wait(Math.min(left, BACKSTOP_MS));
888
+ continue;
889
+ }
890
+ options.signal?.throwIfAborted();
891
+ if (admission.allowed || options.maxWaitMs === 0 || admission.reason !== "concurrency-limit" && admission.reason !== "quota-cooldown") return admission;
892
+ const status = this.status(providerKey);
893
+ if (!status.ok) {
894
+ const { ok: _ok, ...failure } = status;
895
+ return { allowed: false, ...failure };
896
+ }
897
+ const state = status.status, concurrency = state.limits.concurrency;
898
+ if (concurrency.mode === "limited" && concurrency.maxConcurrent === 0) return admission;
899
+ if (admission.reason === "concurrency-limit" && (concurrency.mode === "unlimited" || state.active < concurrency.maxConcurrent)) continue;
900
+ const exhausted = state.launchesLastHour >= state.limits.maxLaunchesPerHour ? "hourly-limit" : state.launchesLastDay >= state.limits.maxLaunchesPerDay ? "daily-limit" : void 0;
901
+ if (exhausted) return { allowed: false, reason: exhausted };
902
+ const remaining = deadline - performance.now();
903
+ if (remaining <= 0) return { allowed: false, reason: "wait-timeout" };
904
+ const untilQuota = admission.reason === "quota-cooldown" && admission.retryAt !== void 0 ? Math.max(1, admission.retryAt - Date.now()) : BACKSTOP_MS;
905
+ await bell.wait(Math.min(remaining, BACKSTOP_MS, untilQuota));
906
+ } finally {
907
+ bell.cancel();
908
+ this.#waits.delete(bell.cancel);
909
+ }
910
+ }
911
+ }
912
+ async withSlot(providerKey, owner, options, operation) {
913
+ const snapshot = snapshotAcquire(options, true);
914
+ if (typeof operation !== "function") throw new TypeError("An operation is required");
915
+ const admission = await this.#acquire(providerKey, owner, snapshot);
916
+ if (!admission.allowed) throw new LaunchRefusedError(admission);
917
+ let operationError;
918
+ let operationStarted = false;
919
+ try {
920
+ snapshot.signal?.throwIfAborted();
921
+ if (this.#closed) throw new LaunchRefusedError({ allowed: false, reason: "closed" });
922
+ operationStarted = true;
923
+ return await operation();
924
+ } catch (error) {
925
+ operationError = error;
926
+ if (operationStarted && snapshot.isQuotaError?.(error)) {
927
+ const recorded = this.recordQuotaError(providerKey, observedUsageLimitReset(error, providerKey));
928
+ if (!recorded.ok) {
929
+ operationError = new LaunchQuotaRecordError(recorded, error);
930
+ throw operationError;
931
+ }
932
+ }
933
+ throw error;
934
+ } finally {
935
+ const release = this.release(admission.reservation.token);
936
+ if (!release.ok) throw new LaunchReleaseError(release, operationError);
937
+ }
938
+ }
939
+ #ring() {
940
+ try {
941
+ writeFileSync(this.#bell, String(process.hrtime.bigint()), { mode: 384 });
942
+ } catch {
943
+ }
944
+ }
945
+ };
946
+
947
+ export {
948
+ inspectLegacyLaunchBudget,
949
+ hostLaunchLimits,
950
+ HOST_LAUNCH_LIMITS,
951
+ hostLedgerPath,
952
+ WAITER_LEASE_MS,
953
+ BudgetEngine,
954
+ armBell,
955
+ LaunchRefusedError,
956
+ LaunchReleaseError,
957
+ LaunchQuotaRecordError,
958
+ HostLedger
959
+ };
960
+ //# sourceMappingURL=chunk-HB7FBSH2.js.map