@antseed/buyer-core 0.1.13 → 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 +87 -4
  2. package/dist/buyer-payment-manager.d.ts.map +1 -1
  3. package/dist/buyer-payment-manager.js +467 -92
  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 +233 -11
  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
  }
@@ -377,13 +412,8 @@ export class BuyerPaymentManager {
377
412
  const maxAmount = replayAmount > this._config.maxReserveAmountUsdc
378
413
  ? this._config.maxReserveAmountUsdc
379
414
  : replayAmount;
380
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
381
- const reserveMsg = {
382
- channelId: session.sessionId,
383
- maxAmount,
384
- deadline: BigInt(deadline),
385
- };
386
- const reserveAuthSig = await signReserveAuth(this._signer, this._channelsDomain, reserveMsg);
415
+ const deadline = this._authDeadline();
416
+ const reserveAuthSig = await this._signReserveAuth(session.sessionId, maxAmount, deadline);
387
417
  const pending = {
388
418
  signature: reserveAuthSig,
389
419
  salt,
@@ -413,11 +443,7 @@ export class BuyerPaymentManager {
413
443
  const now = Math.floor(Date.now() / 1000);
414
444
  if (pending.deadline <= now + 30) {
415
445
  const deadline = now + this._config.defaultAuthDurationSecs;
416
- const signature = await signReserveAuth(this._signer, this._channelsDomain, {
417
- channelId: session.sessionId,
418
- maxAmount: pending.maxAmount,
419
- deadline: BigInt(deadline),
420
- });
446
+ const signature = await this._signReserveAuth(session.sessionId, pending.maxAmount, deadline);
421
447
  pending = { ...pending, signature, deadline };
422
448
  }
423
449
  await this._commitAndSendReserveAuth(session, sellerPeerId, pending, paymentMux);
@@ -521,8 +547,14 @@ export class BuyerPaymentManager {
521
547
  }
522
548
  }
523
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
+ }
524
556
  for (const [requestId, entry] of this._requestBillingEntries) {
525
- if (entry.context.sellerPeerId === sellerPeerId) {
557
+ if (entry.context.sellerPeerId === sellerPeerId && !entry.oneOffChannelId) {
526
558
  this.clearRequestBilling(requestId);
527
559
  }
528
560
  }
@@ -587,27 +619,31 @@ export class BuyerPaymentManager {
587
619
  }
588
620
  async _commitUpdatedSpendingAuth(session, sellerPeerId, cumulativeAmount, metadata) {
589
621
  const sanitizedMetadata = this._sanitizeMetadata(metadata);
590
- 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);
591
629
  const encodedMetadata = encodeMetadata(sanitizedMetadata);
592
- const metadataMsg = {
593
- channelId: session.sessionId,
630
+ const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, {
631
+ channelId: channel.sessionId,
594
632
  cumulativeAmount,
595
- metadataHash: metadataHashHex,
596
- };
597
- const spendingAuthSig = await signSpendingAuth(this._signer, this._channelsDomain, metadataMsg);
633
+ metadataHash,
634
+ });
598
635
  await this._commitAuthorization({
599
- ...session,
636
+ ...channel,
600
637
  authMax: cumulativeAmount.toString(),
601
638
  latestBuyerSig: spendingAuthSig,
602
639
  latestSpendingAuthSig: spendingAuthSig,
603
640
  latestMetadata: encodedMetadata,
604
641
  updatedAt: Date.now(),
605
642
  }, sanitizedMetadata);
606
- this._cumulativeAmount.set(sellerPeerId, cumulativeAmount);
607
643
  return {
608
- channelId: session.sessionId,
644
+ channelId: channel.sessionId,
609
645
  cumulativeAmount: cumulativeAmount.toString(),
610
- metadataHash: metadataHashHex,
646
+ metadataHash,
611
647
  metadata: encodedMetadata,
612
648
  spendingAuthSig,
613
649
  };
@@ -631,9 +667,7 @@ export class BuyerPaymentManager {
631
667
  * override for the service that triggered the 402.
632
668
  */
633
669
  async authorizeSpending(sellerPeerId, paymentMux, minBudgetPerRequest, reserveAmountOrPricing, pricingArg, pricingMap, metadataArg) {
634
- const sellerEvmAddr = this._sellerAddressResolver
635
- ? await this._sellerAddressResolver.resolveSellerAddress(sellerPeerId, metadataArg)
636
- : peerIdToAddress(sellerPeerId);
670
+ const terms = await this._newChannelTerms(sellerPeerId, metadataArg);
637
671
  const reserveAmount = typeof reserveAmountOrPricing === 'bigint'
638
672
  ? reserveAmountOrPricing
639
673
  : this._config.maxReserveAmountUsdc;
@@ -664,27 +698,13 @@ export class BuyerPaymentManager {
664
698
  services: existing?.services ?? {},
665
699
  });
666
700
  }
667
- // Generate random salt and compute deterministic channelId
668
- const salt = hexlify(randomBytes(32));
669
- const buyerEvmAddr = this._identity.wallet.address;
670
- const channelId = computeChannelId(buyerEvmAddr, sellerEvmAddr, salt);
671
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
701
+ const { channelId, salt, deadline } = terms;
672
702
  debugLog(`[BuyerPayment] authorizeSpending: channel=${channelId.slice(0, 18)}... seller=${sellerPeerId.slice(0, 12)}... amount=${minBudgetPerRequest}`);
673
- // Sign ReserveAuth — binds channelId, maxAmount, deadline on-chain
674
- const channelsDomain = this._channelsDomain;
675
703
  const maxAmount = reserveAmount;
676
- const reserveMsg = {
677
- channelId,
678
- maxAmount,
679
- deadline: BigInt(deadline),
680
- };
681
- const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
682
- // Initialize state for this session.
683
- // Start cumulative at 0 — the initial message is a ReserveAuth (not a SpendingAuth).
684
- // The first real SpendingAuth will be sent by handleNeedAuth after the seller serves
685
- // the first request and reports its cost.
704
+ const reserveAuthSig = await this._signReserveAuth(channelId, maxAmount, deadline);
705
+ const initialMetadata = this._sanitizeMetadata({ ...ZERO_METADATA });
686
706
  this._cumulativeAmount.set(sellerPeerId, 0n);
687
- this._metadata.set(sellerPeerId, this._sanitizeMetadata({ ...ZERO_METADATA }));
707
+ this._metadata.set(sellerPeerId, initialMetadata);
688
708
  this._verifiedCost.set(sellerPeerId, 0n);
689
709
  this._currentReserveCeiling.set(sellerPeerId, 0n);
690
710
  this._initialReserveAmount.set(sellerPeerId, maxAmount);
@@ -696,19 +716,37 @@ export class BuyerPaymentManager {
696
716
  deadline,
697
717
  confirmedAmount: 0n,
698
718
  });
699
- // 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 = {}) {
700
740
  const now = Date.now();
701
- const initialMetadata = this._sanitizeMetadata({ ...ZERO_METADATA });
702
- const encodedInitialMetadata = encodeMetadata(initialMetadata);
703
- const session = {
704
- sessionId: channelId,
705
- peerId: sellerPeerId,
741
+ return {
742
+ sessionId: terms.channelId,
743
+ peerId: terms.sellerPeerId,
706
744
  role: CHANNEL_ROLE.BUYER,
707
- sellerEvmAddr,
708
- buyerEvmAddr: this._identity.wallet.address,
745
+ sellerEvmAddr: terms.sellerEvmAddr,
746
+ buyerEvmAddr: terms.buyerEvmAddr,
709
747
  nonce: 0,
710
748
  authMax: '0',
711
- deadline,
749
+ deadline: terms.deadline,
712
750
  previousSessionId: '0x' + '0'.repeat(64),
713
751
  previousConsumption: '0',
714
752
  tokensDelivered: '0',
@@ -717,36 +755,75 @@ export class BuyerPaymentManager {
717
755
  settledAt: null,
718
756
  settledAmount: null,
719
757
  status: CHANNEL_STATUS.ACTIVE,
720
- latestBuyerSig: reserveAuthSig,
758
+ latestBuyerSig: openingReserveSig,
721
759
  latestSpendingAuthSig: null,
722
- latestMetadata: encodedInitialMetadata,
723
- reserveSalt: salt,
724
- initialReserveAmount: maxAmount.toString(),
725
- reserveMaxAmount: maxAmount.toString(),
726
- latestReserveAuthSig: reserveAuthSig,
727
- 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,
728
766
  reserveAuthPending: true,
729
767
  confirmedReserveAmount: '0',
730
768
  createdAt: now,
731
769
  updatedAt: now,
770
+ ...overrides,
732
771
  };
733
- await this._commitAuthorization(session, initialMetadata);
734
- // Send SpendingAuth via PaymentMux — reserve carries ReserveAuth sig
772
+ }
773
+ _sendOpeningReserveAuth(paymentMux, terms, openingReserve, openingReserveSig, metadata, extra = {}) {
735
774
  paymentMux.sendSpendingAuth({
736
- channelId,
775
+ channelId: terms.channelId,
737
776
  cumulativeAmount: '0',
738
777
  metadataHash: ZERO_METADATA_HASH,
739
- metadata: encodedInitialMetadata,
740
- spendingAuthSig: reserveAuthSig,
741
- reserveSalt: salt,
742
- reserveMaxAmount: maxAmount.toString(),
743
- 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',
744
816
  });
745
- this._currentReserveCeiling.set(sellerPeerId, maxAmount);
746
- return channelId;
747
817
  }
748
818
  // ── AuthAck handler ───────────────────────────────────────────
749
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
+ }
750
827
  const session = this.getActiveSession(sellerPeerId);
751
828
  if (!session) {
752
829
  debugWarn(`[BuyerPayment] AuthAck for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
@@ -937,6 +1014,8 @@ export class BuyerPaymentManager {
937
1014
  // buyer's own observation of the delivered response, so it survives a
938
1015
  // headroom NeedAuth having already consumed the request-billing entry.
939
1016
  const estimatedOutputImages = countOutputImages(responseStats.unitUsage);
1017
+ const estimatedVideoGenerations = countVideoGenerations(responseStats.unitUsage);
1018
+ const estimatedVideoSeconds = countVideoSeconds(responseStats.unitUsage);
940
1019
  if (estimatedOutputImages > 0n) {
941
1020
  if (byteEstimatedTokens) {
942
1021
  // Byte estimates of an image response are base64 noise, not tokens.
@@ -946,7 +1025,7 @@ export class BuyerPaymentManager {
946
1025
  }
947
1026
  estimatedOutputTokens += estimatedOutputImages * OUTPUT_IMAGE_TOKEN_EQUIVALENT;
948
1027
  if (estimatedInputTokens <= 0n) {
949
- estimatedInputTokens = BigInt(requestBilling?.requestFacts.promptTokens ?? 0);
1028
+ estimatedInputTokens = BigInt(imagePromptTokens(requestBilling));
950
1029
  }
951
1030
  }
952
1031
  // Determine the accepted cost for this request:
@@ -1001,6 +1080,8 @@ export class BuyerPaymentManager {
1001
1080
  outputTokens: estimatedOutputTokens,
1002
1081
  requests: 1n,
1003
1082
  outputImages: estimatedOutputImages,
1083
+ videoGenerations: estimatedVideoGenerations,
1084
+ videoSeconds: estimatedVideoSeconds,
1004
1085
  }, { deliveredResponse: true, alreadyCounted }));
1005
1086
  debugLog(`[BuyerPayment] signPerRequestAuth #${newMeta.cumulativeRequestCount}: ` +
1006
1087
  `thisReq in=${estimatedInputTokens} out=${estimatedOutputTokens} | ` +
@@ -1059,11 +1140,19 @@ export class BuyerPaymentManager {
1059
1140
  * cumulative amount, capped at the reserve ceiling.
1060
1141
  */
1061
1142
  async handleNeedAuth(sellerPeerId, payload, paymentMux) {
1143
+ if (this._oneOffChannels.has(payload.channelId)) {
1144
+ await this._handleOneOffNeedAuth(sellerPeerId, payload, paymentMux);
1145
+ return;
1146
+ }
1062
1147
  const session = this.getActiveSession(sellerPeerId);
1063
1148
  if (!session) {
1064
1149
  debugWarn(`[BuyerPayment] NeedAuth for unknown seller: ${sellerPeerId.slice(0, 12)}...`);
1065
1150
  return;
1066
1151
  }
1152
+ if (session.sessionId !== payload.channelId) {
1153
+ debugWarn(`[BuyerPayment] NeedAuth for unknown channel ${payload.channelId.slice(0, 18)}... — ignoring`);
1154
+ return;
1155
+ }
1067
1156
  const requestBilling = payload.requestId ? this.getRequestBilling(payload.requestId) : undefined;
1068
1157
  const buyerService = requestBilling?.context.service
1069
1158
  ?? this._requestService.get(payload.requestId);
@@ -1077,6 +1166,8 @@ export class BuyerPaymentManager {
1077
1166
  }
1078
1167
  let acceptedServiceCost = 0n;
1079
1168
  let acceptedOutputImages = 0n;
1169
+ let acceptedVideoGenerations = 0n;
1170
+ let acceptedVideoSeconds = 0n;
1080
1171
  let verifiedCostDelta = 0n;
1081
1172
  const reportedInputTokens = BigInt(payload.inputTokens ?? '0');
1082
1173
  const reportedCachedInputTokens = BigInt(payload.cachedInputTokens ?? '0');
@@ -1119,7 +1210,10 @@ export class BuyerPaymentManager {
1119
1210
  ? sellerTotalCost - tokenEstimate
1120
1211
  : 0n;
1121
1212
  acceptedUnitCost = validateUnitBillingUsage(unitBillingModel, requestBilling.context, payload.billingUsage, claimedUnitCost, this._costTolerance, observedUnitUsage);
1122
- acceptedOutputImages = countOutputImages(unitUsageFromReport(payload.billingUsage));
1213
+ const acceptedUnitUsage = unitUsageFromReport(payload.billingUsage);
1214
+ acceptedOutputImages = countOutputImages(acceptedUnitUsage);
1215
+ acceptedVideoGenerations = countVideoGenerations(acceptedUnitUsage);
1216
+ acceptedVideoSeconds = countVideoSeconds(acceptedUnitUsage);
1123
1217
  }
1124
1218
  const buyerEstimate = tokenEstimate + acceptedUnitCost;
1125
1219
  if (sellerTotalCost > 0n && buyerEstimate <= 0n) {
@@ -1140,7 +1234,7 @@ export class BuyerPaymentManager {
1140
1234
  }
1141
1235
  else if (payload.lastRequestCost) {
1142
1236
  const sellerCost = BigInt(payload.lastRequestCost);
1143
- if (sellerCost > 0n && unitBillingModel && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
1237
+ if (sellerCost > 0n && unitBillingModel && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1144
1238
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost omitted verifiable billingUsage`);
1145
1239
  return;
1146
1240
  }
@@ -1164,7 +1258,7 @@ export class BuyerPaymentManager {
1164
1258
  : sellerIn);
1165
1259
  const buyerEstimate = computeCostUsdc(Number(freshIn), Number(sellerOut), pricing, Number(sellerCached));
1166
1260
  const maxAcceptable = BigInt(Math.ceil(Number(buyerEstimate) * this._costTolerance));
1167
- if (buyerEstimate <= 0n && sellerCost > 0n && buyerBillingContext?.serviceApiProtocol === 'openai-images') {
1261
+ if (buyerEstimate <= 0n && sellerCost > 0n && isUnitBilledProtocol(buyerBillingContext?.serviceApiProtocol)) {
1168
1262
  debugWarn(`[BuyerPayment] NeedAuth rejected: positive unit cost recomputed to zero`);
1169
1263
  return;
1170
1264
  }
@@ -1199,7 +1293,7 @@ export class BuyerPaymentManager {
1199
1293
  }
1200
1294
  // When a topUp is needed, first sign at the current ceiling so the seller
1201
1295
  // has a high-enough settled amount to pass the on-chain TopUpThresholdNotMet
1202
- // 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).
1203
1297
  // We cap at the old ceiling here; the topUp is sent AFTER so the seller
1204
1298
  // processes the SpendingAuth first, then the topUp with adequate settle amount.
1205
1299
  const effectiveAmount = needsTopUp
@@ -1231,7 +1325,7 @@ export class BuyerPaymentManager {
1231
1325
  if (acceptedOutputImages > 0n) {
1232
1326
  attributedOutputTokens += acceptedOutputImages * OUTPUT_IMAGE_TOKEN_EQUIVALENT;
1233
1327
  if (attributedInputTokens <= 0n) {
1234
- attributedInputTokens = BigInt(requestBilling?.requestFacts.promptTokens ?? 0);
1328
+ attributedInputTokens = BigInt(imagePromptTokens(requestBilling));
1235
1329
  }
1236
1330
  }
1237
1331
  const newMeta = this._advanceUsageMetadata(this._metadata.get(sellerPeerId), buyerService, normalizeRequestUsageDelta({
@@ -1241,6 +1335,8 @@ export class BuyerPaymentManager {
1241
1335
  outputTokens: attributedOutputTokens,
1242
1336
  requests: 1n,
1243
1337
  outputImages: acceptedOutputImages,
1338
+ videoGenerations: acceptedVideoGenerations,
1339
+ videoSeconds: acceptedVideoSeconds,
1244
1340
  }, { deliveredResponse, alreadyCounted }));
1245
1341
  // Persistence and transport failures must propagate to the connection
1246
1342
  // owner. In particular, swallowing an IndexedDB failure leaves the browser
@@ -1263,7 +1359,7 @@ export class BuyerPaymentManager {
1263
1359
  debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
1264
1360
  // Send topUp AFTER the SpendingAuth so the seller processes the higher
1265
1361
  // cumulative first — this ensures the on-chain settle amount meets the
1266
- // contract's TopUpThresholdNotMet requirement (85% of deposit must be
1362
+ // contract's TopUpThresholdNotMet requirement (TOP_UP_SETTLED_THRESHOLD_BPS of deposit must be
1267
1363
  // settleable before topUp is allowed). Also proactively send the top-up
1268
1364
  // once the signed cumulative reaches the buyer's remaining-headroom
1269
1365
  // threshold; the seller may defer it until the contract gate is satisfied.
@@ -1289,7 +1385,7 @@ export class BuyerPaymentManager {
1289
1385
  const prevCeiling = this._getCeiling(sellerPeerId);
1290
1386
  const newCeiling = prevCeiling + this._config.maxReserveAmountUsdc;
1291
1387
  const additionalReserve = newCeiling - prevCeiling;
1292
- const deadline = Math.floor(Date.now() / 1000) + this._config.defaultAuthDurationSecs;
1388
+ const deadline = this._authDeadline();
1293
1389
  try {
1294
1390
  const balance = await this.getBalance();
1295
1391
  if (balance.available < additionalReserve) {
@@ -1304,14 +1400,7 @@ export class BuyerPaymentManager {
1304
1400
  `${err instanceof Error ? err.message : err}`);
1305
1401
  }
1306
1402
  debugLog(`[BuyerPayment] topUpReserve: channel=${session.sessionId.slice(0, 18)}... ceiling ${prevCeiling} → ${newCeiling}`);
1307
- // Sign ReserveAuth with new maxAmount
1308
- const channelsDomain = this._channelsDomain;
1309
- const reserveMsg = {
1310
- channelId: session.sessionId,
1311
- maxAmount: newCeiling,
1312
- deadline: BigInt(deadline),
1313
- };
1314
- const reserveAuthSig = await signReserveAuth(this._signer, channelsDomain, reserveMsg);
1403
+ const reserveAuthSig = await this._signReserveAuth(session.sessionId, newCeiling, deadline);
1315
1404
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1316
1405
  const salt = this._reserveSalt.get(sellerPeerId) ?? '0x' + '00'.repeat(32);
1317
1406
  const pending = {
@@ -1338,7 +1427,194 @@ export class BuyerPaymentManager {
1338
1427
  get maxReserveAmountUsdc() {
1339
1428
  return this._config.maxReserveAmountUsdc;
1340
1429
  }
1341
- /** 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
+ }
1342
1618
  getVerifiedCost(sellerPeerId) {
1343
1619
  return this._verifiedCost.get(sellerPeerId) ?? 0n;
1344
1620
  }
@@ -1446,15 +1722,107 @@ export class BuyerPaymentManager {
1446
1722
  const { createdAtMs: _createdAtMs, ...publicEntry } = entry;
1447
1723
  return publicEntry;
1448
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
+ }
1449
1820
  clearRequestBilling(requestId) {
1450
1821
  this._requestBillingEntries.delete(requestId);
1451
1822
  this._requestService.take(requestId);
1452
1823
  }
1453
1824
  trackRequestBillingContext(requestId, context) {
1454
- this.trackRequestBilling(requestId, {
1455
- context,
1456
- requestFacts: {},
1457
- });
1825
+ this.trackRequestBilling(requestId, { context });
1458
1826
  }
1459
1827
  /** Get the live response token totals for a seller, or null if none recorded this session. */
1460
1828
  getResponseTokenTotals(sellerPeerId) {
@@ -1509,4 +1877,11 @@ export class BuyerPaymentManager {
1509
1877
  return { available: info.available, reserved: info.reserved };
1510
1878
  }
1511
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
+ }
1512
1887
  //# sourceMappingURL=buyer-payment-manager.js.map