@antseed/buyer-core 0.1.12 → 0.1.14

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 (40) hide show
  1. package/dist/buyer-payment-manager.d.ts +88 -5
  2. package/dist/buyer-payment-manager.d.ts.map +1 -1
  3. package/dist/buyer-payment-manager.js +477 -93
  4. package/dist/buyer-payment-manager.js.map +1 -1
  5. package/dist/buyer-payment-negotiator.d.ts +28 -1
  6. package/dist/buyer-payment-negotiator.d.ts.map +1 -1
  7. package/dist/buyer-payment-negotiator.js +236 -14
  8. package/dist/buyer-payment-negotiator.js.map +1 -1
  9. package/dist/buyer-request-handler.d.ts +2 -1
  10. package/dist/buyer-request-handler.d.ts.map +1 -1
  11. package/dist/buyer-request-handler.js +74 -10
  12. package/dist/buyer-request-handler.js.map +1 -1
  13. package/dist/channel-store-types.d.ts +15 -0
  14. package/dist/channel-store-types.d.ts.map +1 -1
  15. package/dist/channel-store-types.js +2 -0
  16. package/dist/channel-store-types.js.map +1 -1
  17. package/dist/channel-usage-accounting.d.ts.map +1 -1
  18. package/dist/channel-usage-accounting.js +4 -0
  19. package/dist/channel-usage-accounting.js.map +1 -1
  20. package/dist/channels-client.d.ts +1 -0
  21. package/dist/channels-client.d.ts.map +1 -1
  22. package/dist/channels-client.js +5 -0
  23. package/dist/channels-client.js.map +1 -1
  24. package/dist/errors.d.ts +1 -1
  25. package/dist/errors.d.ts.map +1 -1
  26. package/dist/errors.js +1 -1
  27. package/dist/errors.js.map +1 -1
  28. package/dist/proxy-mux.d.ts +9 -1
  29. package/dist/proxy-mux.d.ts.map +1 -1
  30. package/dist/proxy-mux.js +116 -4
  31. package/dist/proxy-mux.js.map +1 -1
  32. package/dist/response-auth.d.ts +4 -0
  33. package/dist/response-auth.d.ts.map +1 -1
  34. package/dist/response-auth.js +40 -1
  35. package/dist/response-auth.js.map +1 -1
  36. package/dist/unit-billing.d.ts +32 -7
  37. package/dist/unit-billing.d.ts.map +1 -1
  38. package/dist/unit-billing.js +142 -16
  39. package/dist/unit-billing.js.map +1 -1
  40. package/package.json +4 -3
@@ -3,10 +3,11 @@ import { DepositsClient } from './deposits-client.js';
3
3
  import { signSpendingAuth, signReserveAuth, makeChannelsDomain, computeMetadataHash, encodeMetadata, OUTPUT_IMAGE_TOKEN_EQUIVALENT, ZERO_METADATA, ZERO_METADATA_HASH, computeChannelId, } from '@antseed/protocol/signatures';
4
4
  import { debugLog, debugWarn } from './debug.js';
5
5
  import { peerIdToAddress } from '@antseed/protocol/peer-id';
6
- import { CHANNEL_ROLE, CHANNEL_STATUS } from './channel-store-types.js';
6
+ import { CHANNEL_KIND, CHANNEL_ROLE, CHANNEL_STATUS } from './channel-store-types.js';
7
7
  import { advanceUsageMetadata, CountedRequestTracker, normalizeRequestUsageDelta, RequestServiceTracker, } from './channel-usage-accounting.js';
8
8
  import { estimateCostFromBytes, computeCostUsdc, } from './pricing.js';
9
9
  import { evaluateUnitBilling, unitUsageFromReport, validateUnitBillingUsage } from '@antseed/protocol/billing';
10
+ import { isUnitBilledProtocol, nativeVideoUnitUsage } from './unit-billing.js';
10
11
  import { buyerFault, faultCodeOf } from './errors.js';
11
12
  /** Default tolerance: accept seller claims up to 1.4x buyer's estimate. */
12
13
  const DEFAULT_COST_TOLERANCE = 1.4;
@@ -15,7 +16,12 @@ const INITIAL_TOPUP_HEADROOM_PERCENT = 35n;
15
16
  /** Fixed remaining headroom that triggers every later top-up ($0.50). */
16
17
  const SUBSEQUENT_TOPUP_HEADROOM_USDC = 500000n;
17
18
  const PERCENT_DENOMINATOR = 100n;
19
+ /** Default max price of one video generation ($5.00). */
20
+ export const DEFAULT_MAX_VIDEO_REQUEST_USDC = 5000000n;
18
21
  const REQUEST_BILLING_TTL_MS = 5 * 60_000;
22
+ /** Accepted video jobs awaiting delivery are remembered this long (matches job routes). */
23
+ const VIDEO_JOB_TTL_MS = 30 * 24 * 60 * 60_000;
24
+ const MAX_VIDEO_JOBS = 1_000;
19
25
  const MAX_REQUEST_BILLING_ENTRIES = 512;
20
26
  /** How long NeedAuth validation waits for the buyer's own response processing
21
27
  * to record delivered unit usage before rejecting a positive claim. */
@@ -23,6 +29,12 @@ const OBSERVED_UNIT_USAGE_WAIT_MS = 5_000;
23
29
  function countOutputImages(usage) {
24
30
  return BigInt(Math.max(0, Math.floor(usage?.units.output_images ?? 0)));
25
31
  }
32
+ function countVideoGenerations(usage) {
33
+ return BigInt(Math.max(0, Math.floor(usage?.units.video_generations ?? 0)));
34
+ }
35
+ function countVideoSeconds(usage) {
36
+ return BigInt(Math.max(0, Math.floor(usage?.units.video_seconds ?? 0)));
37
+ }
26
38
  function validateUnitNormalizedCost(model, context, usage) {
27
39
  return evaluateUnitBilling(model, context, usage);
28
40
  }
@@ -72,6 +84,14 @@ export class BuyerPaymentManager {
72
84
  _reserveSalt = new Map();
73
85
  /** Latest ReserveAuth awaiting seller acknowledgement, including top-ups. */
74
86
  _pendingReserveAuth = new Map();
87
+ /**
88
+ * `${sellerPeerId}\n${protocol}\n${jobId}` -> billing of an accepted video
89
+ * that has not been delivered yet. Its price is signed only after the buyer
90
+ * receives the finished video.
91
+ */
92
+ _videoJobs = new Map();
93
+ /** One-off channels keyed by channelId. Never a seller's session channel. */
94
+ _oneOffChannels = new Map();
75
95
  /** Cached EIP-712 domain — static for the lifetime of this manager. */
76
96
  _channelsDomain;
77
97
  constructor(identity, config, channelStore, sellerAddressResolver) {
@@ -106,6 +126,19 @@ export class BuyerPaymentManager {
106
126
  for (const channel of latestByPeer.values()) {
107
127
  this._hydrateChannel(channel, true);
108
128
  }
129
+ for (const channel of this._channelStore.getActiveChannelsByBuyer(CHANNEL_ROLE.BUYER, this._identity.wallet.address, CHANNEL_KIND.ONE_OFF)) {
130
+ if (!channel.oneOffRequestId)
131
+ continue;
132
+ this._oneOffChannels.set(channel.sessionId, {
133
+ sellerPeerId: channel.peerId,
134
+ requestId: channel.oneOffRequestId,
135
+ price: BigInt(channel.reserveMaxAmount ?? '0'),
136
+ cumulative: BigInt(channel.authMax || '0'),
137
+ confirmed: channel.reserveAuthPending !== true,
138
+ ackWaiters: [],
139
+ });
140
+ this._restoreVideoJob(channel);
141
+ }
109
142
  }
110
143
  /** Adopt an authorization durably written outside this manager. */
111
144
  adoptPersistedAuthorization(channel) {
@@ -196,6 +229,8 @@ export class BuyerPaymentManager {
196
229
  cumulativeOutputTokens: current.cumulativeOutputTokens,
197
230
  cumulativeRequestCount: current.cumulativeRequestCount,
198
231
  cumulativeOutputImages: current.cumulativeOutputImages ?? 0n,
232
+ cumulativeVideoGenerations: current.cumulativeVideoGenerations ?? 0n,
233
+ cumulativeVideoSeconds: current.cumulativeVideoSeconds ?? 0n,
199
234
  services: [],
200
235
  };
201
236
  }
@@ -271,7 +306,7 @@ export class BuyerPaymentManager {
271
306
  });
272
307
  return session.sessionId;
273
308
  }
274
- async extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative) {
309
+ async extendCurrentSpendingAuth(sellerPeerId, minBudgetPerRequest, paymentMux, targetCumulative, requestId) {
275
310
  const session = this.getActiveSession(sellerPeerId);
276
311
  if (!session) {
277
312
  throw buyerFault(`[BuyerPayment] No active session for seller ${sellerPeerId.slice(0, 12)}...`, 'buyer-session-state');
@@ -302,6 +337,15 @@ export class BuyerPaymentManager {
302
337
  const currentMeta = this._sanitizeMetadata(this._metadata.get(sellerPeerId));
303
338
  const spendingAuth = await this._commitUpdatedSpendingAuth(session, sellerPeerId, nextCumulative, currentMeta);
304
339
  this._verifiedCost.set(sellerPeerId, reopened.verifiedCost);
340
+ this._reportSpend({
341
+ sellerPeerId,
342
+ requestId: requestId ?? null,
343
+ amountUsdc: (nextCumulative - currentCumulative).toString(),
344
+ inputTokens: '0',
345
+ cachedInputTokens: '0',
346
+ outputTokens: '0',
347
+ outputImages: '0',
348
+ });
305
349
  paymentMux.sendSpendingAuth(spendingAuth);
306
350
  // Send topUp AFTER the SpendingAuth so the seller processes the higher
307
351
  // cumulative first, meeting the on-chain settle threshold for topUp.
@@ -368,13 +412,8 @@ export class BuyerPaymentManager {
368
412
  const maxAmount = replayAmount > this._config.maxReserveAmountUsdc
369
413
  ? this._config.maxReserveAmountUsdc
370
414
  : replayAmount;
371
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
372
- const reserveMsg = {
373
- channelId: session.sessionId,
374
- maxAmount,
375
- deadline: BigInt(deadline),
376
- };
377
- const reserveAuthSig = await signReserveAuth(this._signer, this._channelsDomain, reserveMsg);
415
+ const deadline = this._authDeadline();
416
+ const reserveAuthSig = await this._signReserveAuth(session.sessionId, maxAmount, deadline);
378
417
  const pending = {
379
418
  signature: reserveAuthSig,
380
419
  salt,
@@ -404,11 +443,7 @@ export class BuyerPaymentManager {
404
443
  const now = Math.floor(Date.now() / 1000);
405
444
  if (pending.deadline <= now + 30) {
406
445
  const deadline = now + this._config.defaultAuthDurationSecs;
407
- const signature = await signReserveAuth(this._signer, this._channelsDomain, {
408
- channelId: session.sessionId,
409
- maxAmount: pending.maxAmount,
410
- deadline: BigInt(deadline),
411
- });
446
+ const signature = await this._signReserveAuth(session.sessionId, pending.maxAmount, deadline);
412
447
  pending = { ...pending, signature, deadline };
413
448
  }
414
449
  await this._commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux);
@@ -512,8 +547,14 @@ export class BuyerPaymentManager {
512
547
  }
513
548
  }
514
549
  _clearRequestBillingForSeller(sellerPeerId) {
550
+ // A video paid from its own one-off channel outlives the session channel:
551
+ // keep its job and in-flight retrieve so its delivery can still be signed.
552
+ for (const [key, job] of this._videoJobs) {
553
+ if (job.context.sellerPeerId === sellerPeerId && !job.oneOffChannelId)
554
+ this._videoJobs.delete(key);
555
+ }
515
556
  for (const [requestId, entry] of this._requestBillingEntries) {
516
- if (entry.context.sellerPeerId === sellerPeerId) {
557
+ if (entry.context.sellerPeerId === sellerPeerId && !entry.oneOffChannelId) {
517
558
  this.clearRequestBilling(requestId);
518
559
  }
519
560
  }
@@ -578,27 +619,31 @@ export class BuyerPaymentManager {
578
619
  }
579
620
  async _commitUpdatedSpendingAuth(session, sellerPeerId, cumulativeAmount, metadata) {
580
621
  const sanitizedMetadata = this._sanitizeMetadata(metadata);
581
- const metadataHashHex = computeMetadataHash(sanitizedMetadata);
622
+ const spendingAuth = await this._signAndCommitSpendingAuth(session, cumulativeAmount, sanitizedMetadata);
623
+ this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
624
+ return spendingAuth;
625
+ }
626
+ async _signAndCommitSpendingAuth(channel, cumulativeAmount, metadata) {
627
+ const sanitizedMetadata = this._sanitizeMetadata(metadata);
628
+ const metadataHash = computeMetadataHash(sanitizedMetadata);
582
629
  const encodedMetadata = encodeMetadata(sanitizedMetadata);
583
- const metadataMsg = {
584
- channelId: session.sessionId,
630
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, {
631
+ channelId: channel.sessionId,
585
632
  cumulativeAmount,
586
- metadataHash: metadataHashHex,
587
- };
588
- const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
633
+ metadataHash,
634
+ });
589
635
  await this._commitAuthorization({
590
- ...session,
636
+ ...channel,
591
637
  authMax: cumulativeAmount.toString(),
592
638
  latestBuyerSig: spendingAuthSig,
593
639
  latestSpendingAuthSig: spendingAuthSig,
594
640
  latestMetadata: encodedMetadata,
595
641
  updatedAt: Date.now(),
596
642
  }, sanitizedMetadata);
597
- this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
598
643
  return {
599
- channelId: session.sessionId,
644
+ channelId: channel.sessionId,
600
645
  cumulativeAmount: cumulativeAmount.toString(),
601
- metadataHash: metadataHashHex,
646
+ metadataHash,
602
647
  metadata: encodedMetadata,
603
648
  spendingAuthSig,
604
649
  };
@@ -622,9 +667,7 @@ export class BuyerPaymentManager {
622
667
  * override for the service that triggered the 402.
623
668
  */
624
669
  async authorizeSpending(sellerPeerId, paymentMux, minBudgetPerRequest, reserveAmountOrPricing, pricingArg, pricingMap, metadataArg) {
625
- const sellerEvmAddr = this._sellerAddressResolver
626
- ? await this._sellerAddressResolver.resolveSellerAddress(sellerPeerId, metadataArg)
627
- : peerIdToAddress(sellerPeerId);
670
+ const terms = await this._newChannelTerms(sellerPeerId, metadataArg);
628
671
  const reserveAmount = typeof reserveAmountOrPricing === 'bigint'
629
672
  ? reserveAmountOrPricing
630
673
  : this._config.maxReserveAmountUsdc;
@@ -655,27 +698,13 @@ export class BuyerPaymentManager {
655
698
  services: existing?.services ?? {},
656
699
  });
657
700
  }
658
- // Generate random salt and compute deterministic channelId
659
- const salt = hexlify(randomBytes(32));
660
- const buyerEvmAddr = this._identity.wallet.address;
661
- const channelId = computeChannelId(buyerEvmAddr, sellerEvmAddr, salt);
662
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
701
+ const { channelId, salt, deadline } = terms;
663
702
  debugLog(`[BuyerPayment] authorizeSpending: channel=${channelId.slice(0, 18)}... seller=${sellerPeerId.slice(0, 12)}... amount=${minBudgetPerRequest}`);
664
- // Sign ReserveAuth — binds channelId, maxAmount, deadline on-chain
665
- const channelsDomain = this._channelsDomain;
666
703
  const maxAmount = reserveAmount;
667
- const reserveMsg = {
668
- channelId,
669
- maxAmount,
670
- deadline: BigInt(deadline),
671
- };
672
- const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
673
- // Initialize state for this session.
674
- // Start cumulative at 0 — the initial message is a ReserveAuth (not a SpendingAuth).
675
- // The first real SpendingAuth will be sent by handleNeedAuth after the seller serves
676
- // the first request and reports its cost.
704
+ const reserveAuthSig = await this._signReserveAuth(channelId, maxAmount, deadline);
705
+ const initialMetadata = this._sanitizeMetadata({ ...ZERO_METADATA });
677
706
  this._cumulativeAmount.set(sellerPeerId, 0n);
678
- this._metadata.set(sellerPeerId, this._sanitizeMetadata({ ...ZERO_METADATA }));
707
+ this._metadata.set(sellerPeerId, initialMetadata);
679
708
  this._verifiedCost.set(sellerPeerId, 0n);
680
709
  this._currentReserveCeiling.set(sellerPeerId, 0n);
681
710
  this._initialReserveAmount.set(sellerPeerId, maxAmount);
@@ -687,19 +716,37 @@ export class BuyerPaymentManager {
687
716
  deadline,
688
717
  confirmedAmount: 0n,
689
718
  });
690
- // Store session
719
+ await this._commitAuthorization(this._newBuyerChannel(terms, maxAmount, reserveAuthSig, initialMetadata), initialMetadata);
720
+ this._sendOpeningReserveAuth(paymentMux, terms, maxAmount, reserveAuthSig, initialMetadata);
721
+ this._currentReserveCeiling.set(sellerPeerId, maxAmount);
722
+ return channelId;
723
+ }
724
+ async _newChannelTerms(sellerPeerId, metadata) {
725
+ const sellerEvmAddr = this._sellerAddressResolver
726
+ ? await this._sellerAddressResolver.resolveSellerAddress(sellerPeerId, metadata)
727
+ : peerIdToAddress(sellerPeerId);
728
+ const buyerEvmAddr = this._identity.wallet.address;
729
+ const salt = hexlify(randomBytes(32));
730
+ return {
731
+ sellerPeerId,
732
+ sellerEvmAddr,
733
+ buyerEvmAddr,
734
+ salt,
735
+ channelId: computeChannelId(buyerEvmAddr, sellerEvmAddr, salt),
736
+ deadline: this._authDeadline(),
737
+ };
738
+ }
739
+ _newBuyerChannel(terms, openingReserve, openingReserveSig, metadata, overrides = {}) {
691
740
  const now = Date.now();
692
- const initialMetadata = this._sanitizeMetadata({ ...ZERO_METADATA });
693
- const encodedInitialMetadata = encodeMetadata(initialMetadata);
694
- const session = {
695
- sessionId: channelId,
696
- peerId: sellerPeerId,
741
+ return {
742
+ sessionId: terms.channelId,
743
+ peerId: terms.sellerPeerId,
697
744
  role: CHANNEL_ROLE.BUYER,
698
- sellerEvmAddr,
699
- buyerEvmAddr: this._identity.wallet.address,
745
+ sellerEvmAddr: terms.sellerEvmAddr,
746
+ buyerEvmAddr: terms.buyerEvmAddr,
700
747
  nonce: 0,
701
748
  authMax: '0',
702
- deadline,
749
+ deadline: terms.deadline,
703
750
  previousSessionId: '0x' + '0'.repeat(64),
704
751
  previousConsumption: '0',
705
752
  tokensDelivered: '0',
@@ -708,36 +755,75 @@ export class BuyerPaymentManager {
708
755
  settledAt: null,
709
756
  settledAmount: null,
710
757
  status: CHANNEL_STATUS.ACTIVE,
711
- latestBuyerSig: reserveAuthSig,
758
+ latestBuyerSig: openingReserveSig,
712
759
  latestSpendingAuthSig: null,
713
- latestMetadata: encodedInitialMetadata,
714
- reserveSalt: salt,
715
- initialReserveAmount: maxAmount.toString(),
716
- reserveMaxAmount: maxAmount.toString(),
717
- latestReserveAuthSig: reserveAuthSig,
718
- latestReserveDeadline: deadline,
760
+ latestMetadata: encodeMetadata(metadata),
761
+ reserveSalt: terms.salt,
762
+ initialReserveAmount: openingReserve.toString(),
763
+ reserveMaxAmount: openingReserve.toString(),
764
+ latestReserveAuthSig: openingReserveSig,
765
+ latestReserveDeadline: terms.deadline,
719
766
  reserveAuthPending: true,
720
767
  confirmedReserveAmount: '0',
721
768
  createdAt: now,
722
769
  updatedAt: now,
770
+ ...overrides,
723
771
  };
724
- await this._commitAuthorization(session, initialMetadata);
725
- // Send SpendingAuth via PaymentMux — reserve carries ReserveAuth sig
772
+ }
773
+ _sendOpeningReserveAuth(paymentMux, terms, openingReserve, openingReserveSig, metadata, extra = {}) {
726
774
  paymentMux.sendSpendingAuth({
727
- channelId,
775
+ channelId: terms.channelId,
728
776
  cumulativeAmount: '0',
729
777
  metadataHash: ZERO_METADATA_HASH,
730
- metadata: encodedInitialMetadata,
731
- spendingAuthSig: reserveAuthSig,
732
- reserveSalt: salt,
733
- reserveMaxAmount: maxAmount.toString(),
734
- reserveDeadline: deadline,
778
+ metadata: encodeMetadata(metadata),
779
+ spendingAuthSig: openingReserveSig,
780
+ reserveSalt: terms.salt,
781
+ reserveMaxAmount: openingReserve.toString(),
782
+ reserveDeadline: terms.deadline,
783
+ ...extra,
784
+ });
785
+ }
786
+ /** Sign the threshold SpendingAuth and the final ReserveAuth that let the seller run topUp() right after reserve(). */
787
+ async _signReserveBatch(channelId, cumulativeAmount, metadata, maxAmount, deadline) {
788
+ const metadataHash = computeMetadataHash(metadata);
789
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, { channelId, cumulativeAmount, metadataHash });
790
+ return {
791
+ cumulativeAmount: cumulativeAmount.toString(),
792
+ metadataHash,
793
+ metadata: encodeMetadata(metadata),
794
+ spendingAuthSig,
795
+ maxAmount: maxAmount.toString(),
796
+ deadline,
797
+ reserveAuthSig: await this._signReserveAuth(channelId, maxAmount, deadline),
798
+ };
799
+ }
800
+ _authDeadline() {
801
+ return Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
802
+ }
803
+ _signReserveAuth(channelId, maxAmount, deadline) {
804
+ return signReserveAuth(this._signer, this._channelsDomain, { channelId, maxAmount, deadline: BigInt(deadline) });
805
+ }
806
+ /** Report a unit-billed charge that carries no token usage. */
807
+ _reportUnitSpend(sellerPeerId, requestId, amount) {
808
+ this._reportSpend({
809
+ sellerPeerId,
810
+ requestId,
811
+ amountUsdc: amount.toString(),
812
+ inputTokens: '0',
813
+ cachedInputTokens: '0',
814
+ outputTokens: '0',
815
+ outputImages: '0',
735
816
  });
736
- this._currentReserveCeiling.set(sellerPeerId, maxAmount);
737
- return channelId;
738
817
  }
739
818
  // ── AuthAck handler ───────────────────────────────────────────
740
819
  async handleAuthAck(sellerPeerId, payload) {
820
+ const oneOff = this._oneOffChannels.get(payload.channelId);
821
+ if (oneOff) {
822
+ if (oneOff.sellerPeerId !== sellerPeerId)
823
+ return;
824
+ await this._confirmOneOffChannel(payload.channelId, oneOff);
825
+ return;
826
+ }
741
827
  const session = this.getActiveSession(sellerPeerId);
742
828
  if (!session) {
743
829
  debugWarn(`[BuyerPayment] AuthAck for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
@@ -928,6 +1014,8 @@ export class BuyerPaymentManager {
928
1014
  // buyer's own observation of the delivered response, so it survives a
929
1015
  // headroom NeedAuth having already consumed the request-billing entry.
930
1016
  const estimatedOutputImages = countOutputImages(responseStats.unitUsage);
1017
+ const estimatedVideoGenerations = countVideoGenerations(responseStats.unitUsage);
1018
+ const estimatedVideoSeconds = countVideoSeconds(responseStats.unitUsage);
931
1019
  if (estimatedOutputImages > 0n) {
932
1020
  if (byteEstimatedTokens) {
933
1021
  // Byte estimates of an image response are base64 noise, not tokens.
@@ -937,7 +1025,7 @@ export class BuyerPaymentManager {
937
1025
  }
938
1026
  estimatedOutputTokens += estimatedOutputImages * OUTPUT_IMAGE_TOKEN_EQUIVALENT;
939
1027
  if (estimatedInputTokens <= 0n) {
940
- estimatedInputTokens = BigInt(requestBilling?.requestFacts.promptTokens ?? 0);
1028
+ estimatedInputTokens = BigInt(imagePromptTokens(requestBilling));
941
1029
  }
942
1030
  }
943
1031
  // Determine the accepted cost for this request:
@@ -992,6 +1080,8 @@ export class BuyerPaymentManager {
992
1080
  outputTokens: estimatedOutputTokens,
993
1081
  requests: 1n,
994
1082
  outputImages: estimatedOutputImages,
1083
+ videoGenerations: estimatedVideoGenerations,
1084
+ videoSeconds: estimatedVideoSeconds,
995
1085
  }, { deliveredResponse: true, alreadyCounted }));
996
1086
  debugLog(`[BuyerPayment] signPerRequestAuth #${newMeta.cumulativeRequestCount}: ` +
997
1087
  `thisReq in=${estimatedInputTokens} out=${estimatedOutputTokens} | ` +
@@ -1050,11 +1140,19 @@ export class BuyerPaymentManager {
1050
1140
  * cumulative amount, capped at the reserve ceiling.
1051
1141
  */
1052
1142
  async handleNeedAuth(sellerPeerId, payload, paymentMux) {
1143
+ if (this._oneOffChannels.has(payload.channelId)) {
1144
+ await this._handleOneOffNeedAuth(sellerPeerId, payload, paymentMux);
1145
+ return;
1146
+ }
1053
1147
  const session = this.getActiveSession(sellerPeerId);
1054
1148
  if (!session) {
1055
1149
  debugWarn(`[BuyerPayment] NeedAuth for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
1056
1150
  return;
1057
1151
  }
1152
+ if (session.sessionId !== payload.channelId) {
1153
+ debugWarn(`[BuyerPayment] NeedAuth for unknown channel ${payload.channelId.slice(0, 18)}... — ignoring`);
1154
+ return;
1155
+ }
1058
1156
  const requestBilling = payload.requestId ? this.getRequestBilling(payload.requestId) : undefined;
1059
1157
  const buyerService = requestBilling?.context.service
1060
1158
  ?? this._requestService.get(payload.requestId);
@@ -1068,6 +1166,8 @@ export class BuyerPaymentManager {
1068
1166
  }
1069
1167
  let acceptedServiceCost = 0n;
1070
1168
  let acceptedOutputImages = 0n;
1169
+ let acceptedVideoGenerations = 0n;
1170
+ let acceptedVideoSeconds = 0n;
1071
1171
  let verifiedCostDelta = 0n;
1072
1172
  const reportedInputTokens = BigInt(payload.inputTokens ?? '0');
1073
1173
  const reportedCachedInputTokens = BigInt(payload.cachedInputTokens ?? '0');
@@ -1110,7 +1210,10 @@ export class BuyerPaymentManager {
1110
1210
  ? sellerTotalCost - tokenEstimate
1111
1211
  : 0n;
1112
1212
  acceptedUnitCost = validateUnitBillingUsage(unitBillingModel, requestBilling.context, payload.billingUsage, claimedUnitCost, this._costTolerance, observedUnitUsage);
1113
- acceptedOutputImages = countOutputImages(unitUsageFromReport(payload.billingUsage));
1213
+ const acceptedUnitUsage = unitUsageFromReport(payload.billingUsage);
1214
+ acceptedOutputImages = countOutputImages(acceptedUnitUsage);
1215
+ acceptedVideoGenerations = countVideoGenerations(acceptedUnitUsage);
1216
+ acceptedVideoSeconds = countVideoSeconds(acceptedUnitUsage);
1114
1217
  }
1115
1218
  const buyerEstimate = tokenEstimate + acceptedUnitCost;
1116
1219
  if (sellerTotalCost > 0n && buyerEstimate <= 0n) {
@@ -1131,7 +1234,7 @@ export class BuyerPaymentManager {
1131
1234
  }
1132
1235
  else if (payload.lastRequestCost) {
1133
1236
  const sellerCost = BigInt(payload.lastRequestCost);
1134
- if (sellerCost > 0n && unitBillingModel && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
1237
+ if (sellerCost > 0n && unitBillingModel && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1135
1238
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost omitted verifiable billingUsage`);
1136
1239
  return;
1137
1240
  }
@@ -1155,7 +1258,7 @@ export class BuyerPaymentManager {
1155
1258
  : sellerIn);
1156
1259
  const buyerEstimate = computeCostUsdc(Number(freshIn), Number(sellerOut), pricing, Number(sellerCached));
1157
1260
  const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimate) * this._costTolerance));
1158
- if (buyerEstimate <= 0n && sellerCost > 0n && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
1261
+ if (buyerEstimate <= 0n && sellerCost > 0n && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1159
1262
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost recomputed to zero`);
1160
1263
  return;
1161
1264
  }
@@ -1190,7 +1293,7 @@ export class BuyerPaymentManager {
1190
1293
  }
1191
1294
  // When a topUp is needed, first sign at the current ceiling so the seller
1192
1295
  // has a high-enough settled amount to pass the on-chain TopUpThresholdNotMet
1193
- // check (contract requires 85% of deposit to be settleable before topUp).
1296
+ // check (contract requires TOP_UP_SETTLED_THRESHOLD_BPS of deposit to be settleable before topUp).
1194
1297
  // We cap at the old ceiling here; the topUp is sent AFTER so the seller
1195
1298
  // processes the SpendingAuth first, then the topUp with adequate settle amount.
1196
1299
  const effectiveAmount = needsTopUp
@@ -1222,7 +1325,7 @@ export class BuyerPaymentManager {
1222
1325
  if (acceptedOutputImages > 0n) {
1223
1326
  attributedOutputTokens += acceptedOutputImages * OUTPUT_IMAGE_TOKEN_EQUIVALENT;
1224
1327
  if (attributedInputTokens <= 0n) {
1225
- attributedInputTokens = BigInt(requestBilling?.requestFacts.promptTokens ?? 0);
1328
+ attributedInputTokens = BigInt(imagePromptTokens(requestBilling));
1226
1329
  }
1227
1330
  }
1228
1331
  const newMeta = this._advanceUsageMetadata(this._metadata.get(sellerPeerId), buyerService, normalizeRequestUsageDelta({
@@ -1232,6 +1335,8 @@ export class BuyerPaymentManager {
1232
1335
  outputTokens: attributedOutputTokens,
1233
1336
  requests: 1n,
1234
1337
  outputImages: acceptedOutputImages,
1338
+ videoGenerations: acceptedVideoGenerations,
1339
+ videoSeconds: acceptedVideoSeconds,
1235
1340
  }, { deliveredResponse, alreadyCounted }));
1236
1341
  // Persistence and transport failures must propagate to the connection
1237
1342
  // owner. In particular, swallowing an IndexedDB failure leaves the browser
@@ -1254,7 +1359,7 @@ export class BuyerPaymentManager {
1254
1359
  debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
1255
1360
  // Send topUp AFTER the SpendingAuth so the seller processes the higher
1256
1361
  // cumulative first — this ensures the on-chain settle amount meets the
1257
- // contract's TopUpThresholdNotMet requirement (85% of deposit must be
1362
+ // contract's TopUpThresholdNotMet requirement (TOP_UP_SETTLED_THRESHOLD_BPS of deposit must be
1258
1363
  // settleable before topUp is allowed). Also proactively send the top-up
1259
1364
  // once the signed cumulative reaches the buyer's remaining-headroom
1260
1365
  // threshold; the seller may defer it until the contract gate is satisfied.
@@ -1280,7 +1385,7 @@ export class BuyerPaymentManager {
1280
1385
  const prevCeiling = this._getCeiling(sellerPeerId);
1281
1386
  const newCeiling = prevCeiling + this._config.maxReserveAmountUsdc;
1282
1387
  const additionalReserve = newCeiling - prevCeiling;
1283
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
1388
+ const deadline = this._authDeadline();
1284
1389
  try {
1285
1390
  const balance = await this.getBalance();
1286
1391
  if (balance.available < additionalReserve) {
@@ -1295,14 +1400,7 @@ export class BuyerPaymentManager {
1295
1400
  `${err instanceof Error ? err.message : err}`);
1296
1401
  }
1297
1402
  debugLog(`[BuyerPayment] topUpReserve: channel=${session.sessionId.slice(0, 18)}... ceiling ${prevCeiling} → ${newCeiling}`);
1298
- // Sign ReserveAuth with new maxAmount
1299
- const channelsDomain = this._channelsDomain;
1300
- const reserveMsg = {
1301
- channelId: session.sessionId,
1302
- maxAmount: newCeiling,
1303
- deadline: BigInt(deadline),
1304
- };
1305
- const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
1403
+ const reserveAuthSig = await this._signReserveAuth(session.sessionId, newCeiling, deadline);
1306
1404
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1307
1405
  const salt = this._reserveSalt.get(sellerPeerId) ?? '0x' + '00'.repeat(32);
1308
1406
  const pending = {
@@ -1329,7 +1427,194 @@ export class BuyerPaymentManager {
1329
1427
  get maxReserveAmountUsdc() {
1330
1428
  return this._config.maxReserveAmountUsdc;
1331
1429
  }
1332
- /** Current buyer-verified cost for a seller. */
1430
+ /** Max price of one video generation from buyer config. */
1431
+ get maxVideoRequestUsdc() {
1432
+ return this._config.maxVideoRequestUsdc ?? DEFAULT_MAX_VIDEO_REQUEST_USDC;
1433
+ }
1434
+ // ── One-off channels ─────────────────────────────────────────
1435
+ /**
1436
+ * Open a one-off channel that pays for exactly one video. It is a fresh
1437
+ * on-chain channel (new salt), never this seller's session channel: chat
1438
+ * and image spending cannot touch it, and the seller closes it once the
1439
+ * video is paid or abandoned.
1440
+ *
1441
+ * For a price above the opening reserve, signs the opening ReserveAuth, the
1442
+ * contract-required threshold SpendingAuth (the serious fee, credited toward
1443
+ * the price) and the final ReserveAuth together; the seller runs reserve()
1444
+ * and topUp() before acknowledging. Returns the channelId once persisted
1445
+ * and sent; await `waitForOneOffAck` for the seller's confirmation.
1446
+ */
1447
+ async openOneOffChannel(sellerPeerId, requestId, plan, paymentMux, metadataArg) {
1448
+ const price = BigInt(plan.requestCost);
1449
+ const openingReserve = BigInt(plan.openingReserveAmount);
1450
+ const requiredCumulative = BigInt(plan.requiredCumulativeAmount);
1451
+ const billing = this.getRequestBilling(requestId);
1452
+ const facts = billing?.requestFacts;
1453
+ if (!billing || facts?.kind !== 'video' || facts.video.action !== 'create'
1454
+ || billing.context.sellerPeerId !== sellerPeerId || billing.estimatedCostUsdc !== price) {
1455
+ throw buyerFault(`[BuyerPayment] One-off channel requires a tracked video create (${requestId})`, 'buyer-session-state');
1456
+ }
1457
+ if (price > this.maxVideoRequestUsdc || requiredCumulative >= price) {
1458
+ throw buyerFault(`[BuyerPayment] Refusing one-off channel: price=${price} fee=${requiredCumulative}`, 'buyer-session-state');
1459
+ }
1460
+ const existing = this.getOneOffChannelForRequest(sellerPeerId, requestId);
1461
+ if (existing)
1462
+ return existing;
1463
+ const terms = await this._newChannelTerms(sellerPeerId, metadataArg);
1464
+ const { channelId, deadline } = terms;
1465
+ const metadata = this._sanitizeMetadata({ ...ZERO_METADATA });
1466
+ const openingReserveSig = await this._signReserveAuth(channelId, openingReserve, deadline);
1467
+ const reserveBatch = requiredCumulative > 0n
1468
+ ? await this._signReserveBatch(channelId, requiredCumulative, metadata, price, deadline)
1469
+ : undefined;
1470
+ await this._commitAuthorization(this._newBuyerChannel(terms, openingReserve, openingReserveSig, metadata, {
1471
+ channelKind: CHANNEL_KIND.ONE_OFF,
1472
+ oneOffRequestId: requestId,
1473
+ reserveMaxAmount: price.toString(),
1474
+ ...(reserveBatch ? {
1475
+ authMax: reserveBatch.cumulativeAmount,
1476
+ latestBuyerSig: reserveBatch.spendingAuthSig,
1477
+ latestSpendingAuthSig: reserveBatch.spendingAuthSig,
1478
+ latestReserveAuthSig: reserveBatch.reserveAuthSig,
1479
+ } : {}),
1480
+ }), metadata);
1481
+ this._oneOffChannels.set(channelId, {
1482
+ sellerPeerId,
1483
+ requestId,
1484
+ price,
1485
+ cumulative: requiredCumulative,
1486
+ confirmed: false,
1487
+ ackWaiters: [],
1488
+ });
1489
+ this._sendOpeningReserveAuth(paymentMux, terms, openingReserve, openingReserveSig, metadata, {
1490
+ ...(reserveBatch ? { reserveBatch } : {}),
1491
+ oneOffRequestId: requestId,
1492
+ });
1493
+ if (requiredCumulative > 0n)
1494
+ this._reportUnitSpend(sellerPeerId, requestId, requiredCumulative);
1495
+ debugLog(`[BuyerPayment] One-off channel ${channelId.slice(0, 18)}... sent for request ${requestId} (price=${price}, fee=${requiredCumulative})`);
1496
+ return channelId;
1497
+ }
1498
+ /** The active one-off channel opened for this request, or null. */
1499
+ getOneOffChannelForRequest(sellerPeerId, requestId) {
1500
+ for (const [channelId, state] of this._oneOffChannels) {
1501
+ if (state.sellerPeerId === sellerPeerId && state.requestId === requestId)
1502
+ return channelId;
1503
+ }
1504
+ return null;
1505
+ }
1506
+ isOneOffChannelConfirmed(channelId) {
1507
+ return this._oneOffChannels.get(channelId)?.confirmed === true;
1508
+ }
1509
+ /** Resolve true once the seller acknowledges the channel, false on timeout. */
1510
+ waitForOneOffAck(channelId, timeoutMs) {
1511
+ const state = this._oneOffChannels.get(channelId);
1512
+ if (!state)
1513
+ return Promise.resolve(false);
1514
+ if (state.confirmed)
1515
+ return Promise.resolve(true);
1516
+ return new Promise((resolve) => {
1517
+ let done = false;
1518
+ const finish = (confirmed) => {
1519
+ if (done)
1520
+ return;
1521
+ done = true;
1522
+ clearTimeout(timer);
1523
+ resolve(confirmed);
1524
+ };
1525
+ const timer = setTimeout(() => {
1526
+ state.ackWaiters = state.ackWaiters.filter((waiter) => waiter !== finish);
1527
+ finish(false);
1528
+ }, timeoutMs);
1529
+ timer.unref?.();
1530
+ state.ackWaiters.push(finish);
1531
+ });
1532
+ }
1533
+ /** Mark the one-off channel confirmed once its full reserve is seen on-chain. */
1534
+ async confirmOneOffChannelOnChain(channelId, onChainDeposit) {
1535
+ const state = this._oneOffChannels.get(channelId);
1536
+ if (state && onChainDeposit >= state.price)
1537
+ await this._confirmOneOffChannel(channelId, state);
1538
+ }
1539
+ /**
1540
+ * Forget a one-off channel locally once it is closed or abandoned. If it is
1541
+ * still open on-chain, the buyer can still requestClose() it.
1542
+ */
1543
+ retireOneOffChannel(channelId, status = CHANNEL_STATUS.SETTLED) {
1544
+ const state = this._oneOffChannels.get(channelId);
1545
+ if (!state)
1546
+ return;
1547
+ this._oneOffChannels.delete(channelId);
1548
+ for (const waiter of state.ackWaiters.splice(0))
1549
+ waiter(false);
1550
+ this._channelStore.updateChannelStatus(channelId, status);
1551
+ }
1552
+ async _confirmOneOffChannel(channelId, state) {
1553
+ if (!state.confirmed) {
1554
+ const channel = this._channelStore.getChannel(channelId);
1555
+ if (channel) {
1556
+ this._channelStore.upsertChannel({
1557
+ ...channel,
1558
+ reserveAuthPending: false,
1559
+ confirmedReserveAmount: channel.reserveMaxAmount ?? state.price.toString(),
1560
+ updatedAt: Date.now(),
1561
+ });
1562
+ await this._channelStore.flush?.();
1563
+ }
1564
+ state.confirmed = true;
1565
+ debugLog(`[BuyerPayment] One-off channel confirmed: ${channelId.slice(0, 18)}...`);
1566
+ }
1567
+ for (const waiter of state.ackWaiters.splice(0))
1568
+ waiter(true);
1569
+ }
1570
+ /**
1571
+ * Sign a one-off channel's only charge: the video price, after the buyer
1572
+ * received the finished video. Anything else is refused: the channel never
1573
+ * pays for more than its video, and never before delivery.
1574
+ */
1575
+ async _handleOneOffNeedAuth(sellerPeerId, payload, paymentMux) {
1576
+ const { channelId, requestId } = payload;
1577
+ const state = this._oneOffChannels.get(channelId);
1578
+ const channel = this._channelStore.getChannel(channelId);
1579
+ if (!state || !channel || state.sellerPeerId !== sellerPeerId)
1580
+ return;
1581
+ const required = BigInt(payload.requiredCumulativeAmount);
1582
+ if (required <= state.cumulative)
1583
+ return;
1584
+ const billing = requestId ? this._requestBillingEntries.get(requestId) : undefined;
1585
+ if (required !== state.price || BigInt(payload.lastRequestCost ?? '0') !== state.price
1586
+ || !requestId || !billing?.unitModel || billing.oneOffChannelId !== channelId || !payload.billingUsage) {
1587
+ debugWarn(`[BuyerPayment] One-off NeedAuth rejected: request ${requestId ?? 'n/a'} required=${required} price=${state.price}`);
1588
+ return;
1589
+ }
1590
+ let usage;
1591
+ try {
1592
+ const observed = billing.observedUnitUsage ?? await this._waitForObservedUnitUsage(requestId, OBSERVED_UNIT_USAGE_WAIT_MS);
1593
+ validateUnitBillingUsage(billing.unitModel, billing.context, payload.billingUsage, state.price, this._costTolerance, observed);
1594
+ usage = unitUsageFromReport(payload.billingUsage);
1595
+ }
1596
+ catch (err) {
1597
+ debugWarn(`[BuyerPayment] One-off NeedAuth billingUsage rejected: ${err instanceof Error ? err.message : err}`);
1598
+ return;
1599
+ }
1600
+ const metadata = this._advanceUsageMetadata(this._channelStore.getChannelMetadata(channel), billing.context.service, {
1601
+ amount: state.price,
1602
+ inputTokens: 0n,
1603
+ cachedInputTokens: 0n,
1604
+ outputTokens: 0n,
1605
+ requests: 1n,
1606
+ outputImages: 0n,
1607
+ videoGenerations: countVideoGenerations(usage),
1608
+ videoSeconds: countVideoSeconds(usage),
1609
+ });
1610
+ const spendingAuth = await this._signAndCommitSpendingAuth(channel, state.price, metadata);
1611
+ this._reportUnitSpend(sellerPeerId, requestId, state.price - state.cumulative);
1612
+ state.cumulative = state.price;
1613
+ paymentMux.sendSpendingAuth(spendingAuth);
1614
+ this.clearRequestBilling(requestId);
1615
+ // The seller closes the channel on receiving this; it pays for nothing else.
1616
+ this.retireOneOffChannel(channelId);
1617
+ }
1333
1618
  getVerifiedCost(sellerPeerId) {
1334
1619
  return this._verifiedCost.get(sellerPeerId) ?? 0n;
1335
1620
  }
@@ -1437,15 +1722,107 @@ export class BuyerPaymentManager {
1437
1722
  const { createdAtMs: _createdAtMs, ...publicEntry } = entry;
1438
1723
  return publicEntry;
1439
1724
  }
1725
+ /**
1726
+ * The one-off channel a video create was paid from, for ResponseAuth
1727
+ * verification. Only the create itself is signed with that channel; the
1728
+ * seller signs retrieves of the same job with the session channel, so they
1729
+ * return null and fall back to it.
1730
+ */
1731
+ getResponseAuthChannelId(sellerPeerId, requestId) {
1732
+ return this.getOneOffChannelForRequest(sellerPeerId, requestId);
1733
+ }
1734
+ /** Remember an accepted video job; its price is charged on delivery. */
1735
+ trackVideoJob(sellerPeerId, protocol, jobId, entry, requestId) {
1736
+ const now = Date.now();
1737
+ for (const [key, job] of this._videoJobs) {
1738
+ if (now - job.createdAtMs > VIDEO_JOB_TTL_MS)
1739
+ this._videoJobs.delete(key);
1740
+ }
1741
+ const oneOffChannelId = requestId ? this.getOneOffChannelForRequest(sellerPeerId, requestId) ?? undefined : undefined;
1742
+ this._videoJobs.set(videoJobKey(sellerPeerId, protocol, jobId), {
1743
+ ...entry,
1744
+ createdAtMs: now,
1745
+ ...(oneOffChannelId ? { oneOffChannelId } : {}),
1746
+ });
1747
+ if (oneOffChannelId)
1748
+ this._persistVideoJob(oneOffChannelId, { protocol, jobId, createdAtMs: now, entry });
1749
+ while (this._videoJobs.size > MAX_VIDEO_JOBS) {
1750
+ const oldest = this._videoJobs.keys().next().value;
1751
+ if (oldest === undefined)
1752
+ break;
1753
+ this._videoJobs.delete(oldest);
1754
+ }
1755
+ }
1756
+ /**
1757
+ * Bind a retrieve request to its accepted job so the seller's delivery
1758
+ * NeedAuth is validated against the job's own billing facts.
1759
+ */
1760
+ trackVideoRetrieve(sellerPeerId, protocol, jobId, requestId) {
1761
+ const job = this._videoJobs.get(videoJobKey(sellerPeerId, protocol, jobId));
1762
+ if (!job)
1763
+ return false;
1764
+ const { createdAtMs: _createdAtMs, observedUnitUsage: _observed, oneOffChannelId, ...entry } = job;
1765
+ this.trackRequestBilling(requestId, entry);
1766
+ const tracked = this._requestBillingEntries.get(requestId);
1767
+ if (tracked && oneOffChannelId)
1768
+ tracked.oneOffChannelId = oneOffChannelId;
1769
+ return true;
1770
+ }
1771
+ /**
1772
+ * Record that the buyer received the finished video. Only now may the
1773
+ * seller's NeedAuth for the job's price be signed, and only once.
1774
+ */
1775
+ recordVideoDelivered(sellerPeerId, protocol, jobId, requestId) {
1776
+ const key = videoJobKey(sellerPeerId, protocol, jobId);
1777
+ const job = this._videoJobs.get(key);
1778
+ const entry = this._requestBillingEntries.get(requestId);
1779
+ const facts = entry?.requestFacts;
1780
+ if (!job || facts?.kind !== 'video')
1781
+ return;
1782
+ this._videoJobs.delete(key);
1783
+ if (job.oneOffChannelId)
1784
+ this._persistVideoJob(job.oneOffChannelId, null);
1785
+ this.recordObservedUnitUsage(requestId, nativeVideoUnitUsage(facts.video));
1786
+ }
1787
+ /** Store (or clear) the undelivered job on its one-off channel row. */
1788
+ _persistVideoJob(channelId, job) {
1789
+ const channel = this._channelStore.getChannel(channelId);
1790
+ if (!channel)
1791
+ return;
1792
+ try {
1793
+ this._channelStore.upsertChannel({
1794
+ ...channel,
1795
+ oneOffVideoJob: job ? JSON.stringify(job, (_key, value) => typeof value === 'bigint' ? { $bigint: value.toString() } : value) : null,
1796
+ updatedAt: Date.now(),
1797
+ });
1798
+ }
1799
+ catch (err) {
1800
+ debugWarn(`[BuyerPayment] Failed to persist video job for ${channelId.slice(0, 18)}...: ${err instanceof Error ? err.message : String(err)}`);
1801
+ }
1802
+ }
1803
+ _restoreVideoJob(channel) {
1804
+ if (!channel.oneOffVideoJob)
1805
+ return;
1806
+ try {
1807
+ const job = JSON.parse(channel.oneOffVideoJob, (_key, value) => (value && typeof value === 'object' && typeof value.$bigint === 'string' ? BigInt(value.$bigint) : value));
1808
+ if (Date.now() - job.createdAtMs > VIDEO_JOB_TTL_MS)
1809
+ return;
1810
+ this._videoJobs.set(videoJobKey(channel.peerId, job.protocol, job.jobId), {
1811
+ ...job.entry,
1812
+ createdAtMs: job.createdAtMs,
1813
+ oneOffChannelId: channel.sessionId,
1814
+ });
1815
+ }
1816
+ catch (err) {
1817
+ debugWarn(`[BuyerPayment] Ignoring unreadable video job on ${channel.sessionId.slice(0, 18)}...: ${err instanceof Error ? err.message : String(err)}`);
1818
+ }
1819
+ }
1440
1820
  clearRequestBilling(requestId) {
1441
1821
  this._requestBillingEntries.delete(requestId);
1442
1822
  this._requestService.take(requestId);
1443
1823
  }
1444
1824
  trackRequestBillingContext(requestId, context) {
1445
- this.trackRequestBilling(requestId, {
1446
- context,
1447
- requestFacts: {},
1448
- });
1825
+ this.trackRequestBilling(requestId, { context });
1449
1826
  }
1450
1827
  /** Get the live response token totals for a seller, or null if none recorded this session. */
1451
1828
  getResponseTokenTotals(sellerPeerId) {
@@ -1500,4 +1877,11 @@ export class BuyerPaymentManager {
1500
1877
  return { available: info.available, reserved: info.reserved };
1501
1878
  }
1502
1879
  }
1880
+ function videoJobKey(sellerPeerId, protocol, jobId) {
1881
+ return `${sellerPeerId.toLowerCase()}\n${protocol}\n${jobId}`;
1882
+ }
1883
+ function imagePromptTokens(billing) {
1884
+ const facts = billing?.requestFacts;
1885
+ return facts?.kind === 'image' ? facts.image.promptTokens ?? 0 : 0;
1886
+ }
1503
1887
  //# sourceMappingURL=buyer-payment-manager.js.map