@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.22

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 (124) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.d.ts +6 -0
  4. package/dist/assetHealth.js +107 -0
  5. package/dist/assetRepair.d.ts +24 -0
  6. package/dist/assetRepair.js +172 -0
  7. package/dist/assetSidecarRecovery.d.ts +14 -0
  8. package/dist/assetSidecarRecovery.js +171 -0
  9. package/dist/assetTrust.d.ts +24 -0
  10. package/dist/assetTrust.js +231 -0
  11. package/dist/atp.d.ts +10 -5
  12. package/dist/atp.js +119 -26
  13. package/dist/atpAutoBuyer.d.ts +120 -0
  14. package/dist/atpAutoBuyer.js +814 -0
  15. package/dist/atpAutoDeliver.js +2 -2
  16. package/dist/autoDistillAntiGene.js +7 -5
  17. package/dist/autoDistillLlm.d.ts +26 -0
  18. package/dist/autoDistillLlm.js +119 -22
  19. package/dist/autoDistillTranscript.js +3 -2
  20. package/dist/autoexec.d.ts +111 -24
  21. package/dist/autoexec.js +887 -120
  22. package/dist/autoexecConfig.d.ts +10 -0
  23. package/dist/autoexecConfig.js +69 -0
  24. package/dist/cli.js +13 -0
  25. package/dist/cliContracts.d.ts +33 -2
  26. package/dist/cliContracts.js +818 -78
  27. package/dist/commandCatalog.d.ts +72 -0
  28. package/dist/commandCatalog.js +120 -0
  29. package/dist/commands.d.ts +1 -0
  30. package/dist/commands.js +1 -0
  31. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  32. package/dist/curriculumCapabilityGaps.js +24 -0
  33. package/dist/cycleConsumer.d.ts +17 -2
  34. package/dist/cycleConsumer.js +374 -50
  35. package/dist/dashboard.d.ts +13 -1
  36. package/dist/dashboard.js +235 -18
  37. package/dist/dispatch.d.ts +9 -2
  38. package/dist/dispatch.js +29 -6
  39. package/dist/distillAdmission.d.ts +13 -0
  40. package/dist/distillAdmission.js +35 -0
  41. package/dist/distillObserver.js +27 -12
  42. package/dist/distillPrimitives.d.ts +11 -8
  43. package/dist/distillPrimitives.js +116 -22
  44. package/dist/doctor.d.ts +13 -0
  45. package/dist/doctor.js +177 -10
  46. package/dist/identityHome.d.ts +9 -0
  47. package/dist/identityHome.js +47 -0
  48. package/dist/index.d.ts +73 -40
  49. package/dist/index.js +745 -207
  50. package/dist/issueReport.d.ts +7 -0
  51. package/dist/issueReport.js +291 -0
  52. package/dist/learningTrace.d.ts +15 -0
  53. package/dist/learningTrace.js +73 -0
  54. package/dist/lifecycle.d.ts +199 -2
  55. package/dist/lifecycle.js +4999 -152
  56. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  57. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  58. package/dist/localMemoryGraph.d.ts +184 -0
  59. package/dist/localMemoryGraph.js +2689 -0
  60. package/dist/login.d.ts +1 -1
  61. package/dist/login.js +3 -3
  62. package/dist/materialPackage.js +3 -6
  63. package/dist/materialSnapshot.d.ts +35 -1
  64. package/dist/materialSnapshot.js +265 -18
  65. package/dist/memoryGraphOps.d.ts +8 -0
  66. package/dist/memoryGraphOps.js +140 -0
  67. package/dist/migrate/assetFormatMap.d.ts +61 -0
  68. package/dist/migrate/assetFormatMap.js +53 -0
  69. package/dist/migrate/envTranslate.d.ts +26 -0
  70. package/dist/migrate/envTranslate.js +147 -0
  71. package/dist/migrate/fieldMap.d.ts +7 -5
  72. package/dist/migrate/fieldMap.js +20 -14
  73. package/dist/migrate/oauthImport.d.ts +66 -0
  74. package/dist/migrate/oauthImport.js +667 -0
  75. package/dist/migrate/v1Import.d.ts +98 -1
  76. package/dist/migrate/v1Import.js +1532 -71
  77. package/dist/modelCompatibility.d.ts +10 -0
  78. package/dist/modelCompatibility.js +296 -0
  79. package/dist/promptRecallHook.d.ts +24 -0
  80. package/dist/promptRecallHook.js +425 -0
  81. package/dist/recallVerifyReport.d.ts +37 -0
  82. package/dist/recallVerifyReport.js +244 -0
  83. package/dist/recipe.d.ts +14 -2
  84. package/dist/recipe.js +543 -65
  85. package/dist/repairedAssetStore.d.ts +2 -0
  86. package/dist/repairedAssetStore.js +12 -0
  87. package/dist/requiredSandboxValidation.d.ts +5 -0
  88. package/dist/requiredSandboxValidation.js +4 -0
  89. package/dist/reuse.d.ts +18 -4
  90. package/dist/reuse.js +375 -107
  91. package/dist/reviewFilter.d.ts +3 -1
  92. package/dist/reviewFilter.js +3 -1
  93. package/dist/runtimeCapabilities.d.ts +18 -0
  94. package/dist/runtimeCapabilities.js +81 -0
  95. package/dist/runtimeSessionSource.d.ts +8 -2
  96. package/dist/runtimeSessionSource.js +63 -11
  97. package/dist/selectionPolicyConfig.d.ts +8 -0
  98. package/dist/selectionPolicyConfig.js +18 -0
  99. package/dist/semanticIdfConfig.d.ts +2 -0
  100. package/dist/semanticIdfConfig.js +4 -0
  101. package/dist/sessionIngest.d.ts +43 -0
  102. package/dist/sessionIngest.js +180 -0
  103. package/dist/setupHooks.d.ts +5 -0
  104. package/dist/setupHooks.js +330 -14
  105. package/dist/skill2gep.d.ts +13 -9
  106. package/dist/skill2gep.js +99 -36
  107. package/dist/skillDistill.d.ts +8 -4
  108. package/dist/skillDistill.js +39 -9
  109. package/dist/solo/mode.js +1 -0
  110. package/dist/sync.d.ts +13 -1
  111. package/dist/sync.js +1947 -265
  112. package/dist/thesis.d.ts +1 -1
  113. package/dist/thesis.js +20 -3
  114. package/dist/trajectoryExport.js +21 -3
  115. package/dist/v1Compat.d.ts +1 -0
  116. package/dist/v1Compat.js +9 -0
  117. package/dist/valueDigest.js +8 -1
  118. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  119. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  120. package/dist/workflow.d.ts +39 -0
  121. package/dist/workflow.js +386 -0
  122. package/dist/workflowRuntime.d.ts +66 -0
  123. package/dist/workflowRuntime.js +638 -0
  124. package/package.json +14 -7
@@ -0,0 +1,814 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { util } from '@evomap/evolver-core';
5
+ import { HUB_GENERAL_TIMEOUT_MS, resolveHubOperationTimeouts, } from '@evomap/evolver-adapter-public';
6
+ import { AtpSpendConsentError, atpConsentPath, getAtpConsent, placeAtpOrderWithConsent, } from './atp.js';
7
+ export const ATP_AUTOBUY_DEFAULT_DAILY_CAP = 50;
8
+ export const ATP_AUTOBUY_DEFAULT_PER_ORDER_CAP = 10;
9
+ export const ATP_AUTOBUY_DEFAULT_TIMEOUT_MS = 3_000;
10
+ export const ATP_AUTOBUY_COLD_START_MS = 5 * 60 * 1_000;
11
+ export const ATP_AUTOBUY_SUCCESS_DEDUP_MS = 24 * 60 * 60 * 1_000;
12
+ export const ATP_AUTOBUY_FAILURE_DEDUP_MS = 5 * 60 * 1_000;
13
+ export const ATP_AUTOBUY_LEDGER_FILENAME = 'atp-autobuyer-ledger.json';
14
+ export const ATP_AUTOBUY_LEDGER_MAX_BYTES = 1024 * 1024;
15
+ const HASH_PATTERN = /^[a-f0-9]{24}$/;
16
+ const DAY_KEY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
17
+ export class AtpAutoBuyerLedgerError extends Error {
18
+ code;
19
+ constructor(message, code, options) {
20
+ super(message, options);
21
+ this.code = code;
22
+ this.name = 'AtpAutoBuyerLedgerError';
23
+ }
24
+ }
25
+ const SYSTEM_TIMER = {
26
+ setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
27
+ clearTimeout: (handle) => globalThis.clearTimeout(handle),
28
+ };
29
+ function isErrno(error, code) {
30
+ return typeof error === 'object' && error !== null && error.code === code;
31
+ }
32
+ function isRecord(value) {
33
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
34
+ }
35
+ function corrupt(message, cause) {
36
+ return new AtpAutoBuyerLedgerError(message, 'CORRUPT_LEDGER', cause === undefined ? undefined : { cause });
37
+ }
38
+ function unavailable(message, cause) {
39
+ return new AtpAutoBuyerLedgerError(message, 'LEDGER_UNAVAILABLE', cause === undefined ? undefined : { cause });
40
+ }
41
+ function dayKey(now) {
42
+ return new Date(now).toISOString().slice(0, 10);
43
+ }
44
+ function validDayKey(value) {
45
+ if (typeof value !== 'string' || !DAY_KEY_PATTERN.test(value))
46
+ return false;
47
+ const parsed = new Date(`${value}T00:00:00.000Z`);
48
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
49
+ }
50
+ function finiteInteger(value, minimum) {
51
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;
52
+ }
53
+ function boundedInteger(value, fallback, minimum = 0) {
54
+ const parsed = typeof value === 'string' && value.trim().length > 0 ? Number(value) : value;
55
+ return typeof parsed === 'number' && Number.isSafeInteger(Math.floor(parsed)) && parsed >= minimum
56
+ ? Math.floor(parsed)
57
+ : fallback;
58
+ }
59
+ function noFollowFlag() {
60
+ return constants['O_NOFOLLOW'] ?? 0;
61
+ }
62
+ function errorText(error) {
63
+ const text = error instanceof Error ? error.message : String(error);
64
+ return text.slice(0, 500);
65
+ }
66
+ function emptyLedger(now) {
67
+ return { version: 2, dayKey: dayKey(now), spent: 0, dedup: {}, reservations: {}, resolutions: [] };
68
+ }
69
+ function parseResolution(value) {
70
+ if (!isRecord(value)
71
+ || typeof value['reservationId'] !== 'string'
72
+ || typeof value['hash'] !== 'string'
73
+ || !HASH_PATTERN.test(value['hash'])
74
+ || !finiteInteger(value['budget'], 1)
75
+ || (value['outcome'] !== 'success' && value['outcome'] !== 'failure')
76
+ || !finiteInteger(value['resolvedAt'], 0)
77
+ || (value['source'] !== 'operator' && value['source'] !== 'late_result')) {
78
+ throw corrupt('invalid ATP auto-buyer resolution');
79
+ }
80
+ return {
81
+ reservationId: value['reservationId'],
82
+ hash: value['hash'],
83
+ budget: value['budget'],
84
+ outcome: value['outcome'],
85
+ resolvedAt: value['resolvedAt'],
86
+ source: value['source'],
87
+ };
88
+ }
89
+ function parseDedupEntry(hash, value) {
90
+ if (!isRecord(value) || !finiteInteger(value['ts'], 0)) {
91
+ throw corrupt(`invalid dedup entry for ${hash}`);
92
+ }
93
+ const state = value['state'];
94
+ if (state !== 'success' && state !== 'failure' && state !== 'reserved') {
95
+ throw corrupt(`invalid dedup state for ${hash}`);
96
+ }
97
+ const reservationId = value['reservationId'];
98
+ if (reservationId !== undefined && (typeof reservationId !== 'string' || reservationId.length === 0)) {
99
+ throw corrupt(`invalid dedup reservation for ${hash}`);
100
+ }
101
+ if (state === 'reserved' && typeof reservationId !== 'string') {
102
+ throw corrupt(`reserved dedup entry is missing its reservation for ${hash}`);
103
+ }
104
+ return { ts: value['ts'], state, ...(reservationId === undefined ? {} : { reservationId }) };
105
+ }
106
+ function parseReservation(id, value) {
107
+ if (!isRecord(value))
108
+ throw corrupt(`invalid reservation ${id}`);
109
+ const hash = value['hash'];
110
+ const state = value['state'];
111
+ const error = value['error'];
112
+ const resolveAfter = value['resolveAfter'];
113
+ if (value['id'] !== id || typeof hash !== 'string' || !HASH_PATTERN.test(hash)) {
114
+ throw corrupt(`invalid reservation identity ${id}`);
115
+ }
116
+ if (!finiteInteger(value['budget'], 1) || !validDayKey(value['dayKey'])) {
117
+ throw corrupt(`invalid reservation budget or day for ${id}`);
118
+ }
119
+ if (!finiteInteger(value['createdAt'], 0) || !finiteInteger(value['updatedAt'], 0)) {
120
+ throw corrupt(`invalid reservation timestamps for ${id}`);
121
+ }
122
+ if (resolveAfter !== undefined && !finiteInteger(resolveAfter, value['createdAt'])) {
123
+ throw corrupt(`invalid reservation recovery deadline for ${id}`);
124
+ }
125
+ if (state !== 'pending' && state !== 'ambiguous')
126
+ throw corrupt(`invalid reservation state for ${id}`);
127
+ if (error !== undefined && typeof error !== 'string')
128
+ throw corrupt(`invalid reservation error for ${id}`);
129
+ return {
130
+ id,
131
+ hash,
132
+ budget: value['budget'],
133
+ dayKey: value['dayKey'],
134
+ createdAt: value['createdAt'],
135
+ updatedAt: value['updatedAt'],
136
+ ...(resolveAfter === undefined ? {} : { resolveAfter }),
137
+ state,
138
+ ...(error === undefined ? {} : { error }),
139
+ };
140
+ }
141
+ function parseLegacyLedger(value) {
142
+ if (!validDayKey(value['dayKey']) || !finiteInteger(value['spent'], 0) || !isRecord(value['dedup'])) {
143
+ throw corrupt('invalid legacy ATP auto-buyer ledger');
144
+ }
145
+ const dedup = {};
146
+ for (const [hash, entry] of Object.entries(value['dedup'])) {
147
+ if (!HASH_PATTERN.test(hash))
148
+ throw corrupt(`invalid legacy dedup hash ${hash}`);
149
+ if (finiteInteger(entry, 0)) {
150
+ dedup[hash] = { ts: entry, state: 'success' };
151
+ continue;
152
+ }
153
+ if (!isRecord(entry) || !finiteInteger(entry['ts'], 0) || typeof entry['failed'] !== 'boolean') {
154
+ throw corrupt(`invalid legacy dedup entry for ${hash}`);
155
+ }
156
+ dedup[hash] = { ts: entry['ts'], state: entry['failed'] ? 'failure' : 'success' };
157
+ }
158
+ return { version: 2, dayKey: value['dayKey'], spent: value['spent'], dedup, reservations: {}, resolutions: [] };
159
+ }
160
+ function parseLedger(value) {
161
+ if (!isRecord(value))
162
+ throw corrupt('ATP auto-buyer ledger is not an object');
163
+ if (value['version'] === 1)
164
+ return parseLegacyLedger(value);
165
+ if (value['version'] !== 2
166
+ || !validDayKey(value['dayKey'])
167
+ || !finiteInteger(value['spent'], 0)
168
+ || !isRecord(value['dedup'])
169
+ || !isRecord(value['reservations'])) {
170
+ throw corrupt('invalid ATP auto-buyer ledger schema');
171
+ }
172
+ const dedup = {};
173
+ for (const [hash, entry] of Object.entries(value['dedup'])) {
174
+ if (!HASH_PATTERN.test(hash))
175
+ throw corrupt(`invalid dedup hash ${hash}`);
176
+ dedup[hash] = parseDedupEntry(hash, entry);
177
+ }
178
+ const reservations = {};
179
+ for (const [id, entry] of Object.entries(value['reservations'])) {
180
+ if (id.length === 0)
181
+ throw corrupt('empty reservation id');
182
+ reservations[id] = parseReservation(id, entry);
183
+ }
184
+ for (const [hash, entry] of Object.entries(dedup)) {
185
+ if (entry.state !== 'reserved')
186
+ continue;
187
+ const reservation = reservations[entry.reservationId];
188
+ if (reservation === undefined || reservation.hash !== hash) {
189
+ throw corrupt(`dedup reservation mismatch for ${hash}`);
190
+ }
191
+ }
192
+ for (const reservation of Object.values(reservations)) {
193
+ const entry = dedup[reservation.hash];
194
+ if (entry?.state !== 'reserved' || entry.reservationId !== reservation.id) {
195
+ throw corrupt(`reservation dedup mismatch for ${reservation.id}`);
196
+ }
197
+ }
198
+ const rawResolutions = value['resolutions'] ?? [];
199
+ if (!Array.isArray(rawResolutions) || rawResolutions.length > 256) {
200
+ throw corrupt('invalid ATP auto-buyer resolution history');
201
+ }
202
+ const resolutions = rawResolutions.map(parseResolution);
203
+ return { version: 2, dayKey: value['dayKey'], spent: value['spent'], dedup, reservations, resolutions };
204
+ }
205
+ function readLedgerFile(path, optional) {
206
+ let before;
207
+ try {
208
+ before = lstatSync(path);
209
+ }
210
+ catch (error) {
211
+ if (optional && isErrno(error, 'ENOENT'))
212
+ return undefined;
213
+ throw unavailable(`cannot stat ATP auto-buyer ledger: ${path}`, error);
214
+ }
215
+ if (before.isSymbolicLink() || !before.isFile() || before.size > ATP_AUTOBUY_LEDGER_MAX_BYTES) {
216
+ throw corrupt(`unsafe or oversized ATP auto-buyer ledger: ${path}`);
217
+ }
218
+ let descriptor;
219
+ let raw;
220
+ try {
221
+ descriptor = openSync(path, constants.O_RDONLY | noFollowFlag());
222
+ const opened = fstatSync(descriptor);
223
+ if (!opened.isFile() || opened.size > ATP_AUTOBUY_LEDGER_MAX_BYTES || opened.dev !== before.dev || opened.ino !== before.ino) {
224
+ throw corrupt(`ATP auto-buyer ledger changed while opening: ${path}`);
225
+ }
226
+ raw = readFileSync(descriptor, 'utf8');
227
+ }
228
+ catch (error) {
229
+ if (error instanceof AtpAutoBuyerLedgerError)
230
+ throw error;
231
+ throw unavailable(`cannot read ATP auto-buyer ledger: ${path}`, error);
232
+ }
233
+ finally {
234
+ if (descriptor !== undefined)
235
+ closeSync(descriptor);
236
+ }
237
+ try {
238
+ return parseLedger(JSON.parse(raw));
239
+ }
240
+ catch (error) {
241
+ if (error instanceof AtpAutoBuyerLedgerError)
242
+ throw error;
243
+ throw corrupt(`invalid JSON in ATP auto-buyer ledger: ${path}`, error);
244
+ }
245
+ }
246
+ export function readAtpAutoBuyerLedger(path) {
247
+ return readLedgerFile(path, false);
248
+ }
249
+ function writeLedgerAtomic(path, ledger) {
250
+ const payload = `${JSON.stringify(ledger)}\n`;
251
+ if (Buffer.byteLength(payload, 'utf8') > ATP_AUTOBUY_LEDGER_MAX_BYTES) {
252
+ throw unavailable('ATP auto-buyer ledger capacity exceeded; reconcile ambiguous reservations before new orders');
253
+ }
254
+ const parent = dirname(path);
255
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
256
+ if (existsSync(path)) {
257
+ const current = lstatSync(path);
258
+ if (current.isSymbolicLink() || !current.isFile())
259
+ throw corrupt(`unsafe ATP auto-buyer ledger path: ${path}`);
260
+ }
261
+ const temp = join(parent, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
262
+ let descriptor;
263
+ let pendingError;
264
+ try {
265
+ descriptor = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollowFlag(), 0o600);
266
+ writeFileSync(descriptor, payload, 'utf8');
267
+ fsyncSync(descriptor);
268
+ closeSync(descriptor);
269
+ descriptor = undefined;
270
+ renameSync(temp, path);
271
+ if (process.platform !== 'win32') {
272
+ chmodSync(path, 0o600);
273
+ const directory = openSync(parent, constants.O_RDONLY);
274
+ try {
275
+ fsyncSync(directory);
276
+ }
277
+ finally {
278
+ closeSync(directory);
279
+ }
280
+ }
281
+ }
282
+ catch (error) {
283
+ pendingError = error;
284
+ }
285
+ finally {
286
+ if (descriptor !== undefined)
287
+ closeSync(descriptor);
288
+ try {
289
+ unlinkSync(temp);
290
+ }
291
+ catch (error) {
292
+ if (!isErrno(error, 'ENOENT') && pendingError === undefined)
293
+ pendingError = error;
294
+ }
295
+ }
296
+ if (pendingError !== undefined)
297
+ throw unavailable(`cannot persist ATP auto-buyer ledger: ${path}`, pendingError);
298
+ }
299
+ export function resolveAtpAutoBuyerLedgerPath(env = process.env, consentPath = atpConsentPath(env)) {
300
+ return join(dirname(consentPath), ATP_AUTOBUY_LEDGER_FILENAME);
301
+ }
302
+ export function hashAtpCapabilityGap(request) {
303
+ const capabilities = request.capabilities.map((capability) => String(capability).trim()).filter(Boolean).sort();
304
+ const question = String(request.question ?? '').slice(0, 2_000);
305
+ return createHash('sha256').update(`${capabilities.join(',')}|${question}`).digest('hex').slice(0, 24);
306
+ }
307
+ function rotateLedger(ledger, now) {
308
+ const currentDay = dayKey(now);
309
+ if (ledger.dayKey === currentDay)
310
+ return;
311
+ ledger.dayKey = currentDay;
312
+ ledger.spent = 0;
313
+ }
314
+ function pruneDedup(ledger, now, config) {
315
+ for (const [hash, entry] of Object.entries(ledger.dedup)) {
316
+ if (entry.state === 'reserved')
317
+ continue;
318
+ const ttl = entry.state === 'failure' ? config.failureDedupMs : config.successDedupMs;
319
+ if (entry.ts < now - ttl)
320
+ delete ledger.dedup[hash];
321
+ }
322
+ }
323
+ function effectiveCap(value, now, startedAt, coldStartMs) {
324
+ return now - startedAt < coldStartMs ? Math.floor(value / 2) : value;
325
+ }
326
+ function requestedBudget(value, fallback) {
327
+ const numeric = Number(value);
328
+ return Number.isFinite(numeric) ? Math.max(1, Math.floor(numeric)) : fallback;
329
+ }
330
+ function isAmbiguousOrderResult(result) {
331
+ return !result.ok && (result.status === 408 || (result.status !== undefined && result.status >= 500));
332
+ }
333
+ function isGrant(decision) {
334
+ return 'reservation' in decision;
335
+ }
336
+ export class AtpAutoBuyer {
337
+ ledgerPath;
338
+ lockPath;
339
+ client;
340
+ consentPath;
341
+ env;
342
+ now;
343
+ timer;
344
+ reservationId;
345
+ config;
346
+ queue = Promise.resolve();
347
+ startedAt;
348
+ constructor(options) {
349
+ this.client = options.client;
350
+ this.env = options.env ?? process.env;
351
+ this.consentPath = options.consentPath ?? atpConsentPath(this.env);
352
+ this.ledgerPath = options.ledgerPath ?? resolveAtpAutoBuyerLedgerPath(this.env, this.consentPath);
353
+ this.lockPath = options.lockPath ?? `${this.ledgerPath}.lock`;
354
+ this.now = options.now ?? Date.now;
355
+ this.timer = options.timer ?? SYSTEM_TIMER;
356
+ this.reservationId = options.reservationId ?? randomUUID;
357
+ this.config = {
358
+ dailyCap: boundedInteger(options.dailyCap ?? this.env['ATP_AUTOBUY_DAILY_CAP_CREDITS'], ATP_AUTOBUY_DEFAULT_DAILY_CAP),
359
+ perOrderCap: boundedInteger(options.perOrderCap ?? this.env['ATP_AUTOBUY_PER_ORDER_CAP_CREDITS'], ATP_AUTOBUY_DEFAULT_PER_ORDER_CAP),
360
+ timeoutMs: boundedInteger(options.timeoutMs, ATP_AUTOBUY_DEFAULT_TIMEOUT_MS, 1),
361
+ coldStartMs: boundedInteger(options.coldStartMs, ATP_AUTOBUY_COLD_START_MS),
362
+ successDedupMs: boundedInteger(options.successDedupMs, ATP_AUTOBUY_SUCCESS_DEDUP_MS, 1),
363
+ failureDedupMs: boundedInteger(options.failureDedupMs, ATP_AUTOBUY_FAILURE_DEDUP_MS, 1),
364
+ transportSettleMs: boundedInteger(options.transportSettleMs ?? resolveHubOperationTimeouts(this.env).generalMs, HUB_GENERAL_TIMEOUT_MS, 1),
365
+ lockMaxTries: boundedInteger(options.lockMaxTries, 300, 1),
366
+ lockWaitMs: boundedInteger(options.lockWaitMs, 10),
367
+ };
368
+ }
369
+ consider(request) {
370
+ if (!isRecord(request) || request.kind !== 'capability_gap') {
371
+ return Promise.resolve({ ok: false, skipped: true, reason: 'not_capability_gap' });
372
+ }
373
+ const capabilities = Array.isArray(request.capabilities)
374
+ ? request.capabilities.map((capability) => String(capability).trim()).filter(Boolean)
375
+ : [];
376
+ if (capabilities.length === 0) {
377
+ return Promise.resolve({ ok: false, skipped: true, reason: 'no_capabilities' });
378
+ }
379
+ const normalized = { ...request, capabilities };
380
+ const next = this.queue.then(() => this.considerSerialized(normalized), () => this.considerSerialized(normalized));
381
+ this.queue = next.then(() => undefined, () => undefined);
382
+ return next;
383
+ }
384
+ reconcileReservation(reservationId, result) {
385
+ return this.withLedgerLock(() => {
386
+ const now = this.now();
387
+ const ledger = this.loadLedger(now);
388
+ rotateLedger(ledger, now);
389
+ pruneDedup(ledger, now, this.config);
390
+ const reservation = ledger.reservations[reservationId];
391
+ if (reservation === undefined)
392
+ return false;
393
+ if (isAmbiguousOrderResult(result)) {
394
+ reservation.state = 'ambiguous';
395
+ reservation.updatedAt = now;
396
+ reservation.error = result.error ?? `hub_${result.status ?? 'unknown'}`;
397
+ writeLedgerAtomic(this.ledgerPath, ledger);
398
+ return true;
399
+ }
400
+ delete ledger.reservations[reservationId];
401
+ if (result.ok) {
402
+ if (reservation.dayKey === ledger.dayKey)
403
+ ledger.spent += reservation.budget;
404
+ ledger.dedup[reservation.hash] = { ts: now, state: 'success' };
405
+ }
406
+ else {
407
+ ledger.dedup[reservation.hash] = { ts: now, state: 'failure' };
408
+ }
409
+ writeLedgerAtomic(this.ledgerPath, ledger);
410
+ return true;
411
+ });
412
+ }
413
+ resolveReservation(reservationId, outcome) {
414
+ return this.withLedgerLock(() => {
415
+ const now = this.now();
416
+ const ledger = this.loadLedger(now);
417
+ rotateLedger(ledger, now);
418
+ pruneDedup(ledger, now, this.config);
419
+ const reservation = ledger.reservations[reservationId];
420
+ if (reservation === undefined)
421
+ return false;
422
+ if (reservation.state === 'pending'
423
+ && now < (reservation.resolveAfter ?? this.pendingResolveAfter(reservation.createdAt)))
424
+ return false;
425
+ if (reservation.state === 'ambiguous'
426
+ && outcome === 'failure'
427
+ && reservation.error === 'autobuyer_timeout'
428
+ && now < reservation.createdAt + this.config.transportSettleMs)
429
+ return false;
430
+ delete ledger.reservations[reservationId];
431
+ // An operator cannot prove that an ambiguous POST produced no economic side effect. Charge either outcome
432
+ // against the original day's cap; a confirmed terminal Hub failure uses reconcileReservation instead and
433
+ // remains retryable. This prevents an operator release + retry + late success from overspending the cap.
434
+ if (reservation.dayKey === ledger.dayKey)
435
+ ledger.spent += reservation.budget;
436
+ if (outcome === 'success') {
437
+ ledger.dedup[reservation.hash] = { ts: now, state: 'success' };
438
+ }
439
+ else {
440
+ ledger.dedup[reservation.hash] = { ts: now, state: 'failure' };
441
+ }
442
+ ledger.resolutions.push({
443
+ reservationId,
444
+ hash: reservation.hash,
445
+ budget: reservation.budget,
446
+ outcome,
447
+ resolvedAt: now,
448
+ source: 'operator',
449
+ });
450
+ if (ledger.resolutions.length > 256)
451
+ ledger.resolutions.splice(0, ledger.resolutions.length - 256);
452
+ writeLedgerAtomic(this.ledgerPath, ledger);
453
+ return true;
454
+ });
455
+ }
456
+ async considerSerialized(request) {
457
+ const consent = getAtpConsent(this.env, this.consentPath);
458
+ if (!consent.enabled)
459
+ return { ok: false, skipped: true, reason: 'consent_disabled' };
460
+ const now = this.now();
461
+ this.startedAt ??= now;
462
+ let decision;
463
+ try {
464
+ decision = this.reserve(request, now, this.startedAt);
465
+ }
466
+ catch (error) {
467
+ return this.ledgerFailure(error, true);
468
+ }
469
+ if (!isGrant(decision))
470
+ return decision.result;
471
+ const { reservation, order } = decision;
472
+ const orderPromise = placeAtpOrderWithConsent(this.client, order, {
473
+ env: this.env,
474
+ consentPath: this.consentPath,
475
+ });
476
+ const outcome = await this.awaitOrder(orderPromise, reservation);
477
+ if (outcome.kind === 'timeout') {
478
+ return {
479
+ ok: false,
480
+ skipped: false,
481
+ reason: 'order_timeout',
482
+ error: 'autobuyer_timeout',
483
+ hash: reservation.hash,
484
+ reservationId: reservation.id,
485
+ reserved: reservation.budget,
486
+ };
487
+ }
488
+ if (outcome.kind === 'throw') {
489
+ if (outcome.error instanceof AtpSpendConsentError) {
490
+ try {
491
+ this.releaseReservation(reservation.id);
492
+ }
493
+ catch (error) {
494
+ return this.ledgerFailure(error, false, reservation);
495
+ }
496
+ return { ok: false, skipped: true, reason: 'consent_disabled' };
497
+ }
498
+ try {
499
+ this.markAmbiguous(reservation.id, outcome.error);
500
+ }
501
+ catch (error) {
502
+ return this.ledgerFailure(error, false, reservation);
503
+ }
504
+ return {
505
+ ok: false,
506
+ skipped: false,
507
+ reason: 'order_ambiguous',
508
+ error: errorText(outcome.error),
509
+ hash: reservation.hash,
510
+ reservationId: reservation.id,
511
+ reserved: reservation.budget,
512
+ };
513
+ }
514
+ const ambiguous = isAmbiguousOrderResult(outcome.result);
515
+ let reconciled;
516
+ try {
517
+ reconciled = this.reconcileReservation(reservation.id, outcome.result);
518
+ }
519
+ catch (error) {
520
+ return this.ledgerFailure(error, false, reservation);
521
+ }
522
+ if (!reconciled) {
523
+ return this.ledgerFailure(unavailable('ATP auto-buyer reservation disappeared before the order result was recorded'), false, reservation);
524
+ }
525
+ if (outcome.result.ok) {
526
+ return {
527
+ ok: true,
528
+ skipped: false,
529
+ data: outcome.result.data,
530
+ hash: reservation.hash,
531
+ reservationId: reservation.id,
532
+ spent: reservation.budget,
533
+ };
534
+ }
535
+ if (ambiguous) {
536
+ return {
537
+ ok: false,
538
+ skipped: false,
539
+ reason: 'order_ambiguous',
540
+ error: outcome.result.error ?? 'ambiguous_hub_response',
541
+ status: outcome.result.status,
542
+ hash: reservation.hash,
543
+ reservationId: reservation.id,
544
+ reserved: reservation.budget,
545
+ };
546
+ }
547
+ return {
548
+ ok: false,
549
+ skipped: false,
550
+ error: outcome.result.error ?? 'unknown_error',
551
+ status: outcome.result.status,
552
+ hash: reservation.hash,
553
+ reservationId: reservation.id,
554
+ };
555
+ }
556
+ reserve(request, now, startedAt) {
557
+ return this.withLedgerLock(() => {
558
+ const ledger = this.loadLedger(now);
559
+ rotateLedger(ledger, now);
560
+ pruneDedup(ledger, now, this.config);
561
+ const hash = hashAtpCapabilityGap(request);
562
+ if (ledger.dedup[hash] !== undefined) {
563
+ return { result: { ok: false, skipped: true, reason: 'dedup_hit', hash } };
564
+ }
565
+ const dailyCap = effectiveCap(this.config.dailyCap, now, startedAt, this.config.coldStartMs);
566
+ const perOrderCap = effectiveCap(this.config.perOrderCap, now, startedAt, this.config.coldStartMs);
567
+ const reservedToday = Object.values(ledger.reservations)
568
+ .filter((reservation) => reservation.dayKey === ledger.dayKey)
569
+ .reduce((sum, reservation) => sum + reservation.budget, 0);
570
+ const used = ledger.spent + reservedToday;
571
+ const remaining = Math.max(0, dailyCap - used);
572
+ if (remaining <= 0) {
573
+ return {
574
+ result: { ok: false, skipped: true, reason: 'daily_cap_reached', spent: used, cap: dailyCap },
575
+ };
576
+ }
577
+ const requested = requestedBudget(request.budget, perOrderCap);
578
+ const budget = Math.min(requested, perOrderCap, remaining);
579
+ if (budget <= 0) {
580
+ return { result: { ok: false, skipped: true, reason: 'budget_clamped_to_zero' } };
581
+ }
582
+ const id = this.reservationId();
583
+ if (typeof id !== 'string' || id.length === 0 || ledger.reservations[id] !== undefined) {
584
+ throw unavailable('ATP auto-buyer could not allocate a unique reservation id');
585
+ }
586
+ const reservation = {
587
+ id,
588
+ hash,
589
+ budget,
590
+ dayKey: ledger.dayKey,
591
+ createdAt: now,
592
+ updatedAt: now,
593
+ resolveAfter: this.pendingResolveAfter(now),
594
+ state: 'pending',
595
+ };
596
+ ledger.reservations[id] = reservation;
597
+ ledger.dedup[hash] = { ts: now, state: 'reserved', reservationId: id };
598
+ writeLedgerAtomic(this.ledgerPath, ledger);
599
+ const order = {
600
+ capabilities: request.capabilities,
601
+ budget,
602
+ routingMode: request.routingMode || 'fastest',
603
+ verifyMode: request.verifyMode || 'auto',
604
+ question: request.question,
605
+ signals: request.signals,
606
+ minReputation: request.minReputation,
607
+ };
608
+ return { reservation, order };
609
+ });
610
+ }
611
+ awaitOrder(orderPromise, reservation) {
612
+ return new Promise((resolve) => {
613
+ let completed = false;
614
+ let timedOut = false;
615
+ let handle;
616
+ const onTimeout = () => {
617
+ if (completed)
618
+ return;
619
+ completed = true;
620
+ timedOut = true;
621
+ try {
622
+ this.markAmbiguous(reservation.id, new Error('autobuyer_timeout'));
623
+ }
624
+ catch {
625
+ // The already-durable pending reservation remains fail-closed even if this annotation cannot be written.
626
+ }
627
+ resolve({ kind: 'timeout' });
628
+ };
629
+ try {
630
+ handle = this.timer.setTimeout(onTimeout, this.config.timeoutMs);
631
+ }
632
+ catch {
633
+ onTimeout();
634
+ }
635
+ void orderPromise.then((result) => {
636
+ if (timedOut) {
637
+ this.reconcileLate(reservation, result);
638
+ return;
639
+ }
640
+ if (completed)
641
+ return;
642
+ completed = true;
643
+ try {
644
+ this.timer.clearTimeout(handle);
645
+ }
646
+ catch {
647
+ // A broken injected timer must not change an already-settled order result.
648
+ }
649
+ resolve({ kind: 'result', result });
650
+ }, (error) => {
651
+ if (timedOut) {
652
+ try {
653
+ this.markAmbiguous(reservation.id, error);
654
+ }
655
+ catch {
656
+ // Preserve the existing durable reservation on a failed annotation.
657
+ }
658
+ return;
659
+ }
660
+ if (completed)
661
+ return;
662
+ completed = true;
663
+ try {
664
+ this.timer.clearTimeout(handle);
665
+ }
666
+ catch {
667
+ // A broken injected timer must not change the transport outcome.
668
+ }
669
+ resolve({ kind: 'throw', error });
670
+ });
671
+ });
672
+ }
673
+ reconcileLate(reservation, result) {
674
+ try {
675
+ if (this.reconcileReservation(reservation.id, result) || !result.ok)
676
+ return;
677
+ // An operator can settle an ambiguous timeout while the original POST is still
678
+ // in flight. A later positive receipt is stronger evidence and must restore the
679
+ // spend/dedup record so the same capability gap cannot be purchased again.
680
+ this.withLedgerLock(() => {
681
+ const now = this.now();
682
+ const ledger = this.loadLedger(now);
683
+ rotateLedger(ledger, now);
684
+ pruneDedup(ledger, now, this.config);
685
+ const priorResolution = [...ledger.resolutions]
686
+ .reverse()
687
+ .find((resolution) => resolution.reservationId === reservation.id);
688
+ if (priorResolution?.outcome !== 'failure')
689
+ return;
690
+ if (ledger.resolutions.some((resolution) => (resolution.reservationId === reservation.id && resolution.source === 'late_result')))
691
+ return;
692
+ const currentDedup = ledger.dedup[reservation.hash];
693
+ const newerReservationPending = currentDedup?.state === 'reserved'
694
+ && currentDedup.reservationId !== reservation.id;
695
+ if (!newerReservationPending) {
696
+ delete ledger.reservations[reservation.id];
697
+ ledger.dedup[reservation.hash] = { ts: now, state: 'success' };
698
+ }
699
+ // resolveReservation already charged an operator-resolved ambiguous order against the daily cap. The
700
+ // late receipt strengthens its outcome/dedup evidence but must not count the same reservation twice.
701
+ ledger.resolutions.push({
702
+ reservationId: reservation.id,
703
+ hash: reservation.hash,
704
+ budget: reservation.budget,
705
+ outcome: 'success',
706
+ resolvedAt: now,
707
+ source: 'late_result',
708
+ });
709
+ if (ledger.resolutions.length > 256)
710
+ ledger.resolutions.splice(0, ledger.resolutions.length - 256);
711
+ writeLedgerAtomic(this.ledgerPath, ledger);
712
+ });
713
+ }
714
+ catch {
715
+ // Leave durable state unchanged when the late receipt cannot be recorded safely.
716
+ }
717
+ }
718
+ markAmbiguous(reservationId, error) {
719
+ this.withLedgerLock(() => {
720
+ const now = this.now();
721
+ const ledger = this.loadLedger(now);
722
+ rotateLedger(ledger, now);
723
+ pruneDedup(ledger, now, this.config);
724
+ const reservation = ledger.reservations[reservationId];
725
+ if (reservation === undefined)
726
+ return;
727
+ reservation.state = 'ambiguous';
728
+ reservation.updatedAt = now;
729
+ reservation.error = errorText(error);
730
+ writeLedgerAtomic(this.ledgerPath, ledger);
731
+ });
732
+ }
733
+ releaseReservation(reservationId) {
734
+ this.withLedgerLock(() => {
735
+ const now = this.now();
736
+ const ledger = this.loadLedger(now);
737
+ rotateLedger(ledger, now);
738
+ pruneDedup(ledger, now, this.config);
739
+ const reservation = ledger.reservations[reservationId];
740
+ if (reservation === undefined)
741
+ return;
742
+ delete ledger.reservations[reservationId];
743
+ const dedup = ledger.dedup[reservation.hash];
744
+ if (dedup?.state === 'reserved' && dedup.reservationId === reservationId) {
745
+ delete ledger.dedup[reservation.hash];
746
+ }
747
+ writeLedgerAtomic(this.ledgerPath, ledger);
748
+ });
749
+ }
750
+ pendingResolveAfter(createdAt) {
751
+ return Math.min(Number.MAX_SAFE_INTEGER, createdAt + Math.max(this.config.timeoutMs, this.config.transportSettleMs));
752
+ }
753
+ loadLedger(now) {
754
+ return readLedgerFile(this.ledgerPath, true) ?? emptyLedger(now);
755
+ }
756
+ withLedgerLock(operation) {
757
+ try {
758
+ mkdirSync(dirname(this.ledgerPath), { recursive: true, mode: 0o700 });
759
+ mkdirSync(dirname(this.lockPath), { recursive: true, mode: 0o700 });
760
+ util.acquireLock(this.lockPath, {
761
+ maxTries: this.config.lockMaxTries,
762
+ waitMs: this.config.lockWaitMs,
763
+ });
764
+ }
765
+ catch (error) {
766
+ if (error instanceof util.LockTimeoutError)
767
+ throw error;
768
+ throw unavailable(`cannot acquire ATP auto-buyer ledger lock: ${this.lockPath}`, error);
769
+ }
770
+ let value;
771
+ let operationError;
772
+ try {
773
+ value = operation();
774
+ }
775
+ catch (error) {
776
+ operationError = error;
777
+ }
778
+ let releaseError;
779
+ try {
780
+ const released = util.releaseLock(this.lockPath);
781
+ if (!released.released)
782
+ releaseError = new util.LockReleaseError(released.reason);
783
+ }
784
+ catch (error) {
785
+ releaseError = error;
786
+ }
787
+ if (releaseError !== undefined) {
788
+ throw unavailable(`cannot release ATP auto-buyer ledger lock: ${this.lockPath}`, releaseError);
789
+ }
790
+ if (operationError !== undefined)
791
+ throw operationError;
792
+ return value;
793
+ }
794
+ ledgerFailure(error, skipped, reservation) {
795
+ const reason = error instanceof util.LockTimeoutError
796
+ ? 'ledger_busy'
797
+ : error instanceof AtpAutoBuyerLedgerError && error.code === 'CORRUPT_LEDGER'
798
+ ? 'ledger_corrupt'
799
+ : 'ledger_unavailable';
800
+ return {
801
+ ok: false,
802
+ skipped,
803
+ reason,
804
+ error: errorText(error),
805
+ ...(reservation === undefined
806
+ ? {}
807
+ : {
808
+ hash: reservation.hash,
809
+ reservationId: reservation.id,
810
+ reserved: reservation.budget,
811
+ }),
812
+ };
813
+ }
814
+ }