@dvmkit/dvm-cli 0.1.4 → 0.1.5

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 (58) hide show
  1. package/dist/{_esm-M2HUAA3B.js → _esm-MN4BUYV6.js} +56 -54
  2. package/dist/{accounts-S747UW3A.js → accounts-2WZE4N5F.js} +5 -5
  3. package/dist/actions-LR65XILR.js +244 -0
  4. package/dist/{ccip-XZ5F5J6R.js → ccip-JXYJSXTW.js} +3 -3
  5. package/dist/{chains-PINFXYUE.js → chains-LJ7XK6H3.js} +8 -8
  6. package/dist/{chunk-YZUBKHHA.js → chunk-2VVVWBQA.js} +471 -471
  7. package/dist/chunk-3SWX5BQP.js +66 -0
  8. package/dist/chunk-3W2M46WM.js +61142 -0
  9. package/dist/chunk-4JXFXP4Y.js +757 -0
  10. package/dist/{chunk-GIDSTROG.js → chunk-4NWEJTAW.js} +160 -158
  11. package/dist/{chunk-UXQCP26E.js → chunk-65EY7CT4.js} +2 -2
  12. package/dist/{chunk-6UGZAFIR.js → chunk-6CC6JGEU.js} +348 -18
  13. package/dist/{chunk-PHZHPRQE.js → chunk-6O27TEXD.js} +173 -173
  14. package/dist/{chunk-HPRIQEJS.js → chunk-7OK7MBT6.js} +19 -19
  15. package/dist/{chunk-7UPZZGC5.js → chunk-BECPI5H5.js} +193 -193
  16. package/dist/chunk-CJTE5TS3.js +1298 -0
  17. package/dist/{chunk-RWBYCM47.js → chunk-ECEM3ZAS.js} +10 -10
  18. package/dist/{chunk-ACNNU5RY.js → chunk-ECK465AY.js} +694 -565
  19. package/dist/{chunk-XGABM4H5.js → chunk-EGY4KDBW.js} +3822 -2012
  20. package/dist/{chunk-SLDVIXCS.js → chunk-EVQERRCP.js} +12 -12
  21. package/dist/{chunk-4AQ4G7L5.js → chunk-EZHT2RLJ.js} +383 -383
  22. package/dist/{chunk-IC6OXFYW.js → chunk-F55NNH2F.js} +63 -63
  23. package/dist/chunk-G5C6E6PJ.js +9063 -0
  24. package/dist/{chunk-6AJ7H2VX.js → chunk-GZWKCIYN.js} +213 -1281
  25. package/dist/{chunk-ZGXCK43G.js → chunk-LH3QPVN6.js} +8499 -8498
  26. package/dist/{chunk-MMJR6N3J.js → chunk-MLDUKBU3.js} +1368 -1368
  27. package/dist/chunk-N3UJT2NJ.js +3 -0
  28. package/dist/{chunk-BZNZWRBB.js → chunk-OWJZYYMG.js} +11 -15
  29. package/dist/chunk-ZJYO7OLO.js +514 -0
  30. package/dist/{client-D3XFLWOK.js → client-OWIOFBKS.js} +18 -16
  31. package/dist/{dist-7MMV3EZA.js → dist-2G3QBGID.js} +11 -10
  32. package/dist/dvm.js +26781 -4423
  33. package/dist/esm-RQLHAH2K.js +5183 -0
  34. package/dist/internal-QFQ7MJ5V.js +1228 -0
  35. package/dist/payout-reporter-3UB5WRCV-XTVZFIAO.js +17 -0
  36. package/dist/{pocket-refill-GDYSTECR.js → pocket-refill-PQ5ZVSBY.js} +26 -30
  37. package/dist/revenue-reporter-JIKUPXOK-TYUBTF4P.js +11 -0
  38. package/dist/{secp256k1-4YWQEMGF.js → secp256k1-JLZEQ2H7.js} +2 -2
  39. package/dist/tempo-lifecycle-SQL3KLEZ-AATA2SKI.js +28 -0
  40. package/dist/{tempo-wallet-5FEOI4CF.js → tempo-wallet-QOLEIPCV-SWCXRBDS.js} +2 -4
  41. package/dist/{x402-VNFA3DBY.js → x402-FTG2GRAQ-UGAUMUL6.js} +13 -24
  42. package/package.json +2 -10
  43. package/dist/channel-store-GOV7TEDN.js +0 -62
  44. package/dist/chunk-3PPOU55E.js +0 -312
  45. package/dist/chunk-3TBULV3F.js +0 -551
  46. package/dist/chunk-5BUV73FO.js +0 -2351
  47. package/dist/chunk-EY5K4BM3.js +0 -1780
  48. package/dist/chunk-G3RLVJF5.js +0 -19
  49. package/dist/chunk-KC4UPK44.js +0 -113
  50. package/dist/chunk-MTBCEXJ6.js +0 -4602
  51. package/dist/chunk-ONQMRWY3.js +0 -83
  52. package/dist/chunk-TO47XRK7.js +0 -24890
  53. package/dist/chunk-U5TNSUYW.js +0 -1757
  54. package/dist/chunk-UU6QMSTQ.js +0 -171
  55. package/dist/chunk-ZELLQI7F.js +0 -248
  56. package/dist/lifecycle-5RLM5JMN.js +0 -29
  57. package/dist/tempo-lifecycle-DHZPQTSB.js +0 -31
  58. package/dist/wallet-G3VOUCL4.js +0 -30
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __dvmCreateRequire } from "node:module";
3
+ const require = __dvmCreateRequire(import.meta.url);
@@ -2,21 +2,17 @@
2
2
  import { createRequire as __dvmCreateRequire } from "node:module";
3
3
  const require = __dvmCreateRequire(import.meta.url);
4
4
  import {
5
+ DvmError,
5
6
  isValidEvmPrivateKey,
6
7
  loadConfig,
7
- updateConfig
8
- } from "./chunk-XGABM4H5.js";
9
- import {
10
8
  redactUrl,
11
9
  redactUrlsInText,
12
10
  resolveRpcHttpTransportOptions,
13
- resolveRpcOverride
14
- } from "./chunk-ONQMRWY3.js";
15
- import {
16
- DvmError
17
- } from "./chunk-U5TNSUYW.js";
11
+ resolveRpcOverride,
12
+ updateConfig
13
+ } from "./chunk-EGY4KDBW.js";
18
14
 
19
- // src/lib/payment-rails/tempo-wallet.ts
15
+ // node_modules/@dvmkit/sdk/dist/chunk-ANFX5HEG.js
20
16
  var TEMPO_USDC_MAINNET = "0x20C000000000000000000000b9537d11c60E8b50";
21
17
  var TEMPO_CHAIN_ID = 4217;
22
18
  function resolveTempoAsset(env = process.env) {
@@ -86,10 +82,10 @@ async function generateTempoKey(opts = {}) {
86
82
  );
87
83
  }
88
84
  if (existing && opts.force) {
89
- const { assertTempoWalletIdle } = await import("./tempo-lifecycle-DHZPQTSB.js");
85
+ const { assertTempoWalletIdle } = await import("./tempo-lifecycle-SQL3KLEZ-AATA2SKI.js");
90
86
  await assertTempoWalletIdle("replace");
91
87
  }
92
- const { privateKeyToAccount, generatePrivateKey } = await import("./accounts-S747UW3A.js");
88
+ const { privateKeyToAccount, generatePrivateKey } = await import("./accounts-2WZE4N5F.js");
93
89
  const privateKey = generatePrivateKey();
94
90
  const account = privateKeyToAccount(privateKey);
95
91
  const generated = {
@@ -105,8 +101,8 @@ async function generateTempoKey(opts = {}) {
105
101
  }
106
102
  async function getTempoUsdcBalance(account) {
107
103
  const tokenAddress = resolveTempoAsset().address;
108
- const { createPublicClient, http, erc20Abi } = await import("./_esm-M2HUAA3B.js");
109
- const { tempo } = await import("./chains-PINFXYUE.js");
104
+ const { createPublicClient, http, erc20Abi } = await import("./_esm-MN4BUYV6.js");
105
+ const { tempo } = await import("./chains-LJ7XK6H3.js");
110
106
  const { url: rpcUrl, source: rpcSource } = resolveRpcOverride(
111
107
  process.env.DVM_TEMPO_RPC_URL,
112
108
  tempo.rpcUrls.default.http[0]
@@ -132,7 +128,7 @@ async function getTempoUsdcBalance(account) {
132
128
  usdc: Number(raw) / 1e6,
133
129
  tokenAddress,
134
130
  chainId: TEMPO_CHAIN_ID,
135
- // an internal review: redacted here rather than at a display surface, so the clear
131
+ // internal-review: redacted here rather than at a display surface, so the clear
136
132
  // endpoint never leaves this function on the success path either.
137
133
  rpcUrlRedacted: redactUrl(rpcUrl),
138
134
  rpcSource,
@@ -151,7 +147,7 @@ async function getTempoUsdcBalance(account) {
151
147
  }
152
148
  async function deriveTempoAddress(privateKey) {
153
149
  if (!isValidEvmPrivateKey(privateKey)) throw invalidTempoPrivateKey();
154
- const { privateKeyToAccount } = await import("./accounts-S747UW3A.js");
150
+ const { privateKeyToAccount } = await import("./accounts-2WZE4N5F.js");
155
151
  return privateKeyToAccount(privateKey).address.toLowerCase();
156
152
  }
157
153
  function shortAddress(addr) {
@@ -0,0 +1,514 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __dvmCreateRequire } from "node:module";
3
+ const require = __dvmCreateRequire(import.meta.url);
4
+ import {
5
+ withSdkInitLock
6
+ } from "./chunk-3SWX5BQP.js";
7
+
8
+ // node_modules/@dvmkit/sdk/dist/chunk-2ABMGUDS.js
9
+ import { randomUUID } from "crypto";
10
+ var ENDPOINTS = {
11
+ revenue: "/_internal/job-revenue",
12
+ deposit: "/_internal/credit-deposit",
13
+ release: "/_internal/credit-draw-release",
14
+ drain: "/_internal/credit-drain",
15
+ payout: "/_internal/payout",
16
+ expiry_release: "/_internal/credit-expiry-release"
17
+ };
18
+ var RevenueReporter = class _RevenueReporter {
19
+ // 24h of failed retries
20
+ constructor(db, platformUrl, platformToken) {
21
+ this.db = db;
22
+ this.platformUrl = platformUrl;
23
+ this.platformToken = platformToken;
24
+ }
25
+ db;
26
+ platformUrl;
27
+ platformToken;
28
+ retryTimer = null;
29
+ static RETRY_INTERVAL_MS = 3e4;
30
+ static MAX_BACKOFF_MS = 3e5;
31
+ // 5 min
32
+ static ABANDON_AFTER_MS = 24 * 60 * 60 * 1e3;
33
+ /** Create the pending-reports table (idempotent). */
34
+ async init() {
35
+ await withSdkInitLock(this.db, () => this.createTables());
36
+ }
37
+ /** The boot DDL itself — always runs under {@link withSdkInitLock} (internal-review). */
38
+ async createTables() {
39
+ await this.db.query(`
40
+ CREATE TABLE IF NOT EXISTS pending_revenue_reports (
41
+ id TEXT PRIMARY KEY,
42
+ payload JSONB NOT NULL,
43
+ retry_count INTEGER NOT NULL DEFAULT 0,
44
+ next_retry_at BIGINT NOT NULL DEFAULT 0,
45
+ stale BOOLEAN NOT NULL DEFAULT false,
46
+ stale_reason TEXT,
47
+ created_at BIGINT NOT NULL,
48
+ kind TEXT NOT NULL DEFAULT 'revenue'
49
+ )
50
+ `);
51
+ await this.db.query(
52
+ "ALTER TABLE pending_revenue_reports ADD COLUMN IF NOT EXISTS stale_reason TEXT"
53
+ );
54
+ await this.db.query(
55
+ "ALTER TABLE pending_revenue_reports ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'revenue'"
56
+ );
57
+ }
58
+ /** Persist a revenue report and attempt immediate delivery. */
59
+ async report(payload) {
60
+ return this.enqueue("revenue", payload, payload.jobId);
61
+ }
62
+ /**
63
+ * Join a credit deposit to the caller-owned rail transaction.
64
+ *
65
+ * This method performs no network I/O: it only writes the reporter-owned
66
+ * durable queue row through `tx`. The retry drain delivers the row after the
67
+ * rail transaction commits, including after a process restart.
68
+ */
69
+ async enqueueDeposit(tx, payload) {
70
+ await this.insertPending(tx, "deposit", payload);
71
+ }
72
+ /** Join a released draw to the transaction that made the hold terminal. */
73
+ async enqueueCreditDrawRelease(tx, payload) {
74
+ await this.insertPending(tx, "release", payload);
75
+ }
76
+ /**
77
+ * Join a credit drain to the transaction that made it terminal (internal-review).
78
+ *
79
+ * Same discipline as {@link enqueueDeposit} and the same reason: no network
80
+ * I/O here, only the durable queue row, written through `tx` so the report
81
+ * and the status CAS commit or roll back together. A drain whose row was
82
+ * lost between the two would overstate outstanding liability forever —
83
+ * the mirror image of a lost deposit.
84
+ *
85
+ * Named for the payload rather than the verb because `drain` already means
86
+ * "flush the queue" in this class (see {@link drainPending}).
87
+ */
88
+ async enqueueCreditDrain(tx, payload) {
89
+ await this.insertPending(tx, "drain", payload);
90
+ }
91
+ /**
92
+ * Join a payout to the transaction that commits the movement it reports
93
+ * (internal-review) — the batch close, the accumulator mark, the drain booking.
94
+ * No network I/O, only the durable queue row through `tx`, the discipline
95
+ * {@link enqueueCreditDrain} set and for the same reason: the money has
96
+ * already moved on a rail this ledger does not own, so the platform row is
97
+ * the only record the builder's dashboard has of it, and a row lost between
98
+ * the fact and the queue would understate "paid out" forever. Without `tx`
99
+ * the row is queued on the pool, for callers with no fact of their own to
100
+ * commit. Idempotent on `(dvmId, payoutId)` platform-side, so the retry
101
+ * loop redelivers freely.
102
+ */
103
+ async enqueuePayout(payload, tx) {
104
+ await this.insertPending(tx ?? this.db, "payout", payload);
105
+ }
106
+ /**
107
+ * Report one landed payout on its own and try to deliver it at once — the
108
+ * live Tempo settlement, which has no dvmkit transaction to join. Durable
109
+ * like {@link report}.
110
+ */
111
+ async reportPayout(payload) {
112
+ return this.enqueue("payout", payload, payload.payoutId);
113
+ }
114
+ /**
115
+ * Report one rail's pending-pool snapshot (internal-review). Best-effort and
116
+ * fire-and-forget, deliberately unlike {@link reportPayout}: a snapshot is
117
+ * replaced by the next tick, so queueing a stale one behind an outage would
118
+ * only deliver figures the platform already has newer ones for.
119
+ */
120
+ async reportPayoutPending(payload) {
121
+ const url = `${this.platformUrl}/_internal/payout-pending`;
122
+ try {
123
+ const res = await fetch(url, {
124
+ method: "POST",
125
+ headers: {
126
+ "Content-Type": "application/json",
127
+ Authorization: `Bearer ${this.platformToken}`
128
+ },
129
+ body: JSON.stringify(payload),
130
+ signal: AbortSignal.timeout(1e4)
131
+ });
132
+ if (!res.ok) {
133
+ console.warn(
134
+ JSON.stringify({
135
+ level: "payout_pending_report_failed",
136
+ rail: payload.rail,
137
+ status: res.status
138
+ })
139
+ );
140
+ }
141
+ } catch (err) {
142
+ console.warn(
143
+ JSON.stringify({
144
+ level: "payout_pending_report_failed",
145
+ rail: payload.rail,
146
+ error: err instanceof Error ? err.message : String(err)
147
+ })
148
+ );
149
+ }
150
+ }
151
+ /**
152
+ * Join a credit-expiry release — or the revival that reverses one — to the
153
+ * transaction that made it true (internal-review).
154
+ *
155
+ * Same discipline as {@link enqueueCreditDrain}: no network I/O, only the
156
+ * durable queue row written through `tx`. A release whose row was lost after
157
+ * the sweep committed would understate committed value forever; a lost
158
+ * reversal would overstate it, which is the worse direction — the builder
159
+ * would see money as theirs that a revived credit can still buy work with.
160
+ */
161
+ async enqueueCreditExpiryRelease(tx, payload) {
162
+ await this.insertPending(tx, "expiry_release", payload);
163
+ }
164
+ /**
165
+ * Report a reaper-force-failed paid job to the platform (internal-review) so the
166
+ * operator receives an ambient notice that a DVM died or wedged mid-job.
167
+ * Best-effort and fire-and-forget: unlike {@link report} there is no local
168
+ * durable queue — a non-2xx or transport failure is structured-logged
169
+ * (`paid_job_death_report_failed`) and dropped, since the reaper's own
170
+ * `stale_job_failed` log is the durable record and a failed *alert* must never
171
+ * wedge the sweep.
172
+ */
173
+ async reportPaidJobDeath(payload) {
174
+ const url = `${this.platformUrl}/_internal/paid-job-death`;
175
+ try {
176
+ const res = await fetch(url, {
177
+ method: "POST",
178
+ headers: {
179
+ "Content-Type": "application/json",
180
+ Authorization: `Bearer ${this.platformToken}`
181
+ },
182
+ body: JSON.stringify(payload),
183
+ signal: AbortSignal.timeout(1e4)
184
+ });
185
+ if (!res.ok) {
186
+ console.warn(
187
+ JSON.stringify({
188
+ level: "paid_job_death_report_failed",
189
+ jobId: payload.jobId,
190
+ status: res.status
191
+ })
192
+ );
193
+ }
194
+ } catch (err) {
195
+ console.warn(
196
+ JSON.stringify({
197
+ level: "paid_job_death_report_failed",
198
+ jobId: payload.jobId,
199
+ error: err instanceof Error ? err.message : String(err)
200
+ })
201
+ );
202
+ }
203
+ }
204
+ /**
205
+ * Report a settled draw whose revenue event was skipped (internal-review).
206
+ * Best-effort and fire-and-forget: the SDK's structured
207
+ * `revenue_skipped_no_rail` log is the durable backstop, so a failed notice
208
+ * must never wedge terminal handling or the orphan-draw reconciler.
209
+ */
210
+ async reportRevenueSkippedNoRail(payload) {
211
+ const url = `${this.platformUrl}/_internal/revenue-skipped-no-rail`;
212
+ try {
213
+ const res = await fetch(url, {
214
+ method: "POST",
215
+ headers: {
216
+ "Content-Type": "application/json",
217
+ Authorization: `Bearer ${this.platformToken}`
218
+ },
219
+ body: JSON.stringify(payload),
220
+ signal: AbortSignal.timeout(1e4)
221
+ });
222
+ if (!res.ok) {
223
+ console.warn(
224
+ JSON.stringify({
225
+ level: "revenue_skipped_no_rail_report_failed",
226
+ jobId: payload.jobId,
227
+ drawId: payload.drawId,
228
+ reason: payload.reason,
229
+ status: res.status
230
+ })
231
+ );
232
+ }
233
+ } catch (err) {
234
+ console.warn(
235
+ JSON.stringify({
236
+ level: "revenue_skipped_no_rail_report_failed",
237
+ jobId: payload.jobId,
238
+ drawId: payload.drawId,
239
+ reason: payload.reason,
240
+ error: err instanceof Error ? err.message : String(err)
241
+ })
242
+ );
243
+ }
244
+ }
245
+ /** Report the self-relay's Base gas gauge for platform-side paging and recovery. */
246
+ async reportX402SelfRelayGasBalance(payload) {
247
+ const url = `${this.platformUrl}/_internal/x402-self-relay-gas-balance`;
248
+ try {
249
+ const res = await fetch(url, {
250
+ method: "POST",
251
+ headers: {
252
+ "Content-Type": "application/json",
253
+ Authorization: `Bearer ${this.platformToken}`
254
+ },
255
+ body: JSON.stringify(payload),
256
+ signal: AbortSignal.timeout(1e4)
257
+ });
258
+ if (!res.ok) {
259
+ console.warn(
260
+ JSON.stringify({
261
+ level: "x402_self_relay_gas_balance_report_failed",
262
+ address: payload.address,
263
+ status: res.status
264
+ })
265
+ );
266
+ }
267
+ } catch (err) {
268
+ console.warn(
269
+ JSON.stringify({
270
+ level: "x402_self_relay_gas_balance_report_failed",
271
+ address: payload.address,
272
+ error: err instanceof Error ? err.message : String(err)
273
+ })
274
+ );
275
+ }
276
+ }
277
+ /** Report redacted self-relay RPC health for platform-side paging and recovery. */
278
+ async reportX402SelfRelayRpcHealth(payload) {
279
+ const url = `${this.platformUrl}/_internal/x402-self-relay-rpc-health`;
280
+ try {
281
+ const res = await fetch(url, {
282
+ method: "POST",
283
+ headers: {
284
+ "Content-Type": "application/json",
285
+ Authorization: `Bearer ${this.platformToken}`
286
+ },
287
+ body: JSON.stringify(payload),
288
+ signal: AbortSignal.timeout(1e4)
289
+ });
290
+ if (!res.ok) {
291
+ console.warn(
292
+ JSON.stringify({
293
+ level: "x402_self_relay_rpc_health_report_failed",
294
+ address: payload.address,
295
+ status: res.status
296
+ })
297
+ );
298
+ }
299
+ } catch {
300
+ console.warn(
301
+ JSON.stringify({
302
+ level: "x402_self_relay_rpc_health_report_failed",
303
+ address: payload.address,
304
+ reason: "transport"
305
+ })
306
+ );
307
+ }
308
+ }
309
+ /** Report the Tempo operator's fee-token gauge for paging and recovery. */
310
+ async reportTempoSettlementBalance(payload) {
311
+ await this.postTempoSettlementReadiness("balance", payload);
312
+ }
313
+ /** Report a redacted operator fee rejection immediately. */
314
+ async reportTempoSettlementFailure(payload) {
315
+ await this.postTempoSettlementReadiness("failure", payload);
316
+ }
317
+ async postTempoSettlementReadiness(kind, payload) {
318
+ const url = `${this.platformUrl}/_internal/tempo-settlement-${kind}`;
319
+ try {
320
+ const res = await fetch(url, {
321
+ method: "POST",
322
+ headers: {
323
+ "Content-Type": "application/json",
324
+ Authorization: `Bearer ${this.platformToken}`
325
+ },
326
+ body: JSON.stringify(payload),
327
+ signal: AbortSignal.timeout(1e4)
328
+ });
329
+ if (!res.ok) {
330
+ console.warn(
331
+ JSON.stringify({
332
+ level: "tempo_settlement_readiness_report_failed",
333
+ kind,
334
+ address: payload.address,
335
+ status: res.status
336
+ })
337
+ );
338
+ }
339
+ } catch {
340
+ console.warn(
341
+ JSON.stringify({
342
+ level: "tempo_settlement_readiness_report_failed",
343
+ kind,
344
+ address: payload.address,
345
+ reason: "transport"
346
+ })
347
+ );
348
+ }
349
+ }
350
+ /** Start the background retry loop. */
351
+ startRetryLoop() {
352
+ if (this.retryTimer) return;
353
+ this.retryTimer = setInterval(() => {
354
+ void this.drainPending();
355
+ }, _RevenueReporter.RETRY_INTERVAL_MS);
356
+ }
357
+ /** Stop the background retry loop. */
358
+ stop() {
359
+ if (this.retryTimer) {
360
+ clearInterval(this.retryTimer);
361
+ this.retryTimer = null;
362
+ }
363
+ }
364
+ /**
365
+ * Operator-facing queue snapshot: distinguishes the live retry queue from
366
+ * terminal (stale) rows and breaks the latter down by classification reason
367
+ * (`token_rotated`, `client_error:<status>`, `abandoned`). Lets monitoring tell
368
+ * transient backlog apart from permanently-failed rows.
369
+ */
370
+ async getQueueStats() {
371
+ const { rows } = await this.db.query(
372
+ `SELECT stale, stale_reason, COUNT(*)::int AS count
373
+ FROM pending_revenue_reports
374
+ GROUP BY stale, stale_reason`
375
+ );
376
+ let liveRetry = 0;
377
+ let stale = 0;
378
+ const byReason = {};
379
+ for (const row of rows) {
380
+ const count = Number(row.count);
381
+ if (row.stale) {
382
+ stale += count;
383
+ const reason = row.stale_reason ?? "unknown";
384
+ byReason[reason] = (byReason[reason] ?? 0) + count;
385
+ } else {
386
+ liveRetry += count;
387
+ }
388
+ }
389
+ return { liveRetry, stale, byReason };
390
+ }
391
+ /**
392
+ * Deliver one bounded batch from the durable queue.
393
+ *
394
+ * Public so startup/recovery tests and operator tooling can drive the same
395
+ * drain the background timer uses without reaching into private state.
396
+ */
397
+ async drainPending() {
398
+ try {
399
+ const { rows } = await this.db.query(
400
+ `SELECT id, payload, retry_count, created_at, kind FROM pending_revenue_reports
401
+ WHERE stale = false AND next_retry_at <= $1
402
+ ORDER BY created_at LIMIT 10`,
403
+ [Date.now()]
404
+ );
405
+ for (const row of rows) {
406
+ const label = row.payload.jobId ?? row.payload.creditId ?? row.payload.payoutId ?? row.id;
407
+ try {
408
+ await this.attemptDelivery(row.id, row.payload, row.kind, label);
409
+ } catch {
410
+ const retryCount = row.retry_count + 1;
411
+ if (Date.now() - Number(row.created_at) >= _RevenueReporter.ABANDON_AFTER_MS) {
412
+ await this.markStale(row.id, "abandoned");
413
+ console.warn(
414
+ JSON.stringify({
415
+ level: "revenue_reporter_abandoned",
416
+ id: row.id,
417
+ kind: row.kind,
418
+ retryCount,
419
+ dvmId: row.payload.dvmId,
420
+ label,
421
+ // A drain names its payout rail `method`; every other kind
422
+ // carries `rail`. An abandoned row is the one place an
423
+ // operator sees this payload at all, so don't log it blank.
424
+ rail: row.payload.rail ?? row.payload.method
425
+ })
426
+ );
427
+ continue;
428
+ }
429
+ const backoff = Math.min(
430
+ 3e4 * Math.pow(2, retryCount - 1),
431
+ _RevenueReporter.MAX_BACKOFF_MS
432
+ );
433
+ await this.db.query(
434
+ `UPDATE pending_revenue_reports
435
+ SET retry_count = $1, next_retry_at = $2
436
+ WHERE id = $3`,
437
+ [retryCount, Date.now() + backoff, row.id]
438
+ );
439
+ }
440
+ }
441
+ } catch (err) {
442
+ console.error("[revenue-reporter] Retry loop error:", err);
443
+ }
444
+ }
445
+ /** Durably queue one report of either kind, then try it once immediately. */
446
+ async enqueue(kind, payload, label) {
447
+ const id = await this.insertPending(this.db, kind, payload);
448
+ void this.attemptDelivery(id, payload, kind, label).catch(() => {
449
+ });
450
+ }
451
+ /** Insert one pending report through either the pool or an open transaction. */
452
+ async insertPending(q, kind, payload) {
453
+ const id = randomUUID();
454
+ await q.query(
455
+ `INSERT INTO pending_revenue_reports (id, payload, created_at, kind)
456
+ VALUES ($1, $2, $3, $4)`,
457
+ [id, JSON.stringify(payload), Date.now(), kind]
458
+ );
459
+ return id;
460
+ }
461
+ async attemptDelivery(id, payload, kind, label) {
462
+ const url = `${this.platformUrl}${ENDPOINTS[kind]}`;
463
+ let res;
464
+ try {
465
+ res = await fetch(url, {
466
+ method: "POST",
467
+ headers: {
468
+ "Content-Type": "application/json",
469
+ Authorization: `Bearer ${this.platformToken}`
470
+ },
471
+ body: JSON.stringify(payload),
472
+ signal: AbortSignal.timeout(1e4)
473
+ });
474
+ } catch (err) {
475
+ const reason = err instanceof Error ? err.message : String(err);
476
+ console.warn(
477
+ `[revenue-reporter] delivery failed for ${id}: transport error (${reason}) \u2014 will retry`
478
+ );
479
+ throw err;
480
+ }
481
+ if (res.ok) {
482
+ await this.db.query("DELETE FROM pending_revenue_reports WHERE id = $1", [id]);
483
+ console.log(`[revenue-reporter] reported ${kind} ${label}`);
484
+ return;
485
+ }
486
+ if (res.status === 401) {
487
+ await this.markStale(id, "token_rotated");
488
+ console.warn(
489
+ `[revenue-reporter] Report ${id} got 401 \u2014 marking stale (token likely rotated)`
490
+ );
491
+ return;
492
+ }
493
+ if (res.status >= 400 && res.status < 500) {
494
+ await this.markStale(id, `client_error:${res.status}`);
495
+ console.warn(
496
+ `[revenue-reporter] Report ${id} got HTTP ${res.status} \u2014 marking stale (permanent client error, will not retry)`
497
+ );
498
+ return;
499
+ }
500
+ console.warn(`[revenue-reporter] delivery failed for ${id}: HTTP ${res.status} \u2014 will retry`);
501
+ throw new Error(`Platform returned ${res.status}`);
502
+ }
503
+ /** Mark a pending row terminal (stale) with a classification reason. */
504
+ async markStale(id, reason) {
505
+ await this.db.query(
506
+ "UPDATE pending_revenue_reports SET stale = true, stale_reason = $1 WHERE id = $2",
507
+ [reason, id]
508
+ );
509
+ }
510
+ };
511
+
512
+ export {
513
+ RevenueReporter
514
+ };
@@ -16,21 +16,23 @@ import {
16
16
  sessionManager2,
17
17
  stripe,
18
18
  tempo
19
- } from "./chunk-GIDSTROG.js";
19
+ } from "./chunk-4NWEJTAW.js";
20
+ import "./chunk-BECPI5H5.js";
21
+ import "./chunk-N3UJT2NJ.js";
20
22
  import {
21
23
  Constants_exports,
22
24
  Expires_exports
23
- } from "./chunk-YZUBKHHA.js";
24
- import "./chunk-6AJ7H2VX.js";
25
- import "./chunk-SLDVIXCS.js";
26
- import "./chunk-7UPZZGC5.js";
27
- import "./chunk-4AQ4G7L5.js";
28
- import "./chunk-ZGXCK43G.js";
29
- import "./chunk-IC6OXFYW.js";
30
- import "./chunk-PHZHPRQE.js";
31
- import "./chunk-UXQCP26E.js";
32
- import "./chunk-MMJR6N3J.js";
33
- import "./chunk-HPRIQEJS.js";
25
+ } from "./chunk-2VVVWBQA.js";
26
+ import "./chunk-EZHT2RLJ.js";
27
+ import "./chunk-EVQERRCP.js";
28
+ import "./chunk-CJTE5TS3.js";
29
+ import "./chunk-GZWKCIYN.js";
30
+ import "./chunk-LH3QPVN6.js";
31
+ import "./chunk-6O27TEXD.js";
32
+ import "./chunk-65EY7CT4.js";
33
+ import "./chunk-F55NNH2F.js";
34
+ import "./chunk-MLDUKBU3.js";
35
+ import "./chunk-7OK7MBT6.js";
34
36
  import "./chunk-IYHTITNZ.js";
35
37
  export {
36
38
  Constants_exports as Constants,
@@ -43,10 +45,10 @@ export {
43
45
  entryKey,
44
46
  evm,
45
47
  sessionClient as session,
46
- session as sessionLegacy,
47
- sessionManager as sessionLegacyManager,
48
- sessionManager2 as sessionManager,
49
- session2 as sessionMethod,
48
+ session2 as sessionLegacy,
49
+ sessionManager2 as sessionLegacyManager,
50
+ sessionManager,
51
+ session as sessionMethod,
50
52
  stripe,
51
53
  tempo
52
54
  };
@@ -7,7 +7,7 @@ import {
7
7
  Store_exports,
8
8
  evm_exports,
9
9
  x402_exports
10
- } from "./chunk-RWBYCM47.js";
10
+ } from "./chunk-ECEM3ZAS.js";
11
11
  import {
12
12
  Challenge_exports,
13
13
  Constants_exports,
@@ -18,15 +18,16 @@ import {
18
18
  Method_exports,
19
19
  PaymentRequest_exports,
20
20
  zod_exports
21
- } from "./chunk-YZUBKHHA.js";
22
- import "./chunk-6AJ7H2VX.js";
23
- import "./chunk-4AQ4G7L5.js";
24
- import "./chunk-ZGXCK43G.js";
25
- import "./chunk-IC6OXFYW.js";
26
- import "./chunk-PHZHPRQE.js";
27
- import "./chunk-UXQCP26E.js";
28
- import "./chunk-MMJR6N3J.js";
29
- import "./chunk-HPRIQEJS.js";
21
+ } from "./chunk-2VVVWBQA.js";
22
+ import "./chunk-EZHT2RLJ.js";
23
+ import "./chunk-CJTE5TS3.js";
24
+ import "./chunk-GZWKCIYN.js";
25
+ import "./chunk-LH3QPVN6.js";
26
+ import "./chunk-6O27TEXD.js";
27
+ import "./chunk-65EY7CT4.js";
28
+ import "./chunk-F55NNH2F.js";
29
+ import "./chunk-MLDUKBU3.js";
30
+ import "./chunk-7OK7MBT6.js";
30
31
  import "./chunk-IYHTITNZ.js";
31
32
  export {
32
33
  BodyDigest_exports as BodyDigest,