@antseed/buyer-core 0.1.44 → 0.1.46

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.
@@ -51,6 +51,29 @@ export type PerRequestResponseStats = {
51
51
  service?: string;
52
52
  requestId?: string;
53
53
  };
54
+ /** What the buyer made of a seller's answer to a paid request. */
55
+ export interface DeliveredResponse {
56
+ /**
57
+ * The buyer's own cost for the response: the usage in the response it
58
+ * received, at the pricing it agreed to. For an attempt the caller aborted,
59
+ * the most the seller may bill for it instead: its prompt plus the output it
60
+ * allows. 0 when nothing verifies what the seller bills: the attempt timed
61
+ * out, its connection closed, or the buyer cannot price it.
62
+ */
63
+ costUsdc: bigint;
64
+ /** The attempt ended after it was sent, with no answer. */
65
+ cutOff?: boolean;
66
+ /** Its cost is counted already (no claim can count it again); only its usage is still to be attributed. */
67
+ costCounted?: boolean;
68
+ /** A received response's service and usage, attributed to it if the buyer's signing before a close pays it. */
69
+ service?: string;
70
+ usage?: {
71
+ inputTokens: bigint;
72
+ cachedInputTokens: bigint;
73
+ outputTokens: bigint;
74
+ unitUsage?: UnitBillingUsage;
75
+ };
76
+ }
54
77
  /** Result of signPerRequestAuth — includes the payload and whether a reserve top-up is needed. */
55
78
  export interface PerRequestAuthResult {
56
79
  payload: SpendingAuthPayload;
@@ -144,6 +167,14 @@ export declare class BuyerPaymentManager {
144
167
  * they were marked. Nothing is owed for them, so a NeedAuth naming one is refused.
145
168
  */
146
169
  private readonly _coveredRequests;
170
+ /**
171
+ * sellerPeerId -> requestId -> what the seller can still be paid for on the
172
+ * active channel: a response the buyer received and priced, or an attempt it
173
+ * cut off. Counting a request toward verified cost removes it, and a request
174
+ * with no entry is owed nothing. Only the buyer's own request path adds
175
+ * entries, and the map is dropped with the seller's verified cost.
176
+ */
177
+ private readonly _requestLedgers;
147
178
  private readonly _observedUsageWaiters;
148
179
  /** sellerPeerId -> full pricing map (defaults + per-service overrides from peer metadata / 402) */
149
180
  private readonly _sessionPricing;
@@ -234,13 +265,6 @@ export declare class BuyerPaymentManager {
234
265
  reconcileReserveAmount(sellerPeerId: string, onChainAmount: bigint): Promise<void>;
235
266
  private _reopenOverdraftWindowIfCollapsed;
236
267
  private _needsCeilingAdvance;
237
- /**
238
- * Both signPerRequestAuth (buyer-initiated) and handleNeedAuth (seller-initiated)
239
- * can fire for the same delivered response. Whichever path accounts for the
240
- * response first records its requestId here so the other path does not
241
- * duplicate its service amount, token totals, or request count.
242
- */
243
- private readonly _serviceTokensCounted;
244
268
  private _spendListener;
245
269
  /**
246
270
  * Observe per-request spend as it is signed. Used to attribute cost to the
@@ -329,7 +353,21 @@ export declare class BuyerPaymentManager {
329
353
  hasPaymentInFlight(sellerPeerId: string): boolean;
330
354
  /** Count a paid request to this seller as in flight until endPaidRequest. */
331
355
  beginPaidRequest(sellerPeerId: string): void;
332
- endPaidRequest(sellerPeerId: string): void;
356
+ /**
357
+ * The attempt is over. Record what arrived (recordDeliveredResponse) before
358
+ * this: an attempt that ends with nothing recorded owes nothing when the
359
+ * seller `answered` it (an error answer, a 402 the buyer retries). When it
360
+ * did not, the attempt was cut off with nothing the buyer can price: the
361
+ * seller may still bill it, and only the overdraft window pays for that.
362
+ */
363
+ endPaidRequest(sellerPeerId: string, requestId?: string, answered?: boolean): void;
364
+ /**
365
+ * The buyer received `sellerPeerId`'s response to paid request `requestId`
366
+ * and priced it itself, or cut the attempt off (`cutOff`). The seller may
367
+ * charge for it once, up to that cost, on the channel live now (the ledger
368
+ * is dropped when a channel starts or ends).
369
+ */
370
+ recordDeliveredResponse(sellerPeerId: string, requestId: string, delivered: DeliveredResponse): void;
333
371
  /**
334
372
  * How much of the current ceiling is a top-up not yet locked on-chain. A
335
373
  * landed top-up the buyer has not heard about is reconciled first, so it is
@@ -1 +1 @@
1
- {"version":3,"file":"buyer-payment-manager.d.ts","sourceRoot":"","sources":["../src/buyer-payment-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,cAAc,EAAE,M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B,GAAG,IAAI;IAIhF,8FAA8F;IAC9F,sBAAsB,CAAC,YAAY,EAAE,MAAM,GAAG;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAIxG,4GAA4G;IAC5G,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI;IAUhF,yDAAyD;IACzD,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;IAI3C,qDAAqD;IACrD,eAAe,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;IAI9C,4EAA4E;IAC5E,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO;IAI7C,wDAAwD;IACxD,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAKxC,iBAAiB,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,EAAE;IAWlD,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAMxC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAKzC,UAAU,IAAI,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAOrE"}
@@ -4,7 +4,7 @@ import { signSpendingAuth, signReserveAuth, makeChannelsDomain, computeMetadataH
4
4
  import { debugLog, debugWarn } from './debug.js';
5
5
  import { peerIdToAddress } from '@antseed/protocol/peer-id';
6
6
  import { CHANNEL_KIND, CHANNEL_ROLE, CHANNEL_STATUS } from './channel-store-types.js';
7
- import { advanceUsageMetadata, CountedRequestTracker, normalizeRequestUsageDelta, RequestServiceTracker, } from './channel-usage-accounting.js';
7
+ import { advanceUsageMetadata, 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
10
  import { isUnitBilledProtocol, nativeVideoUnitUsage } from './unit-billing.js';
@@ -127,6 +127,14 @@ export class BuyerPaymentManager {
127
127
  * they were marked. Nothing is owed for them, so a NeedAuth naming one is refused.
128
128
  */
129
129
  _coveredRequests = new Map();
130
+ /**
131
+ * sellerPeerId -> requestId -> what the seller can still be paid for on the
132
+ * active channel: a response the buyer received and priced, or an attempt it
133
+ * cut off. Counting a request toward verified cost removes it, and a request
134
+ * with no entry is owed nothing. Only the buyer's own request path adds
135
+ * entries, and the map is dropped with the seller's verified cost.
136
+ */
137
+ _requestLedgers = new Map();
130
138
  _observedUsageWaiters = new Map();
131
139
  /** sellerPeerId -> full pricing map (defaults + per-service overrides from peer metadata / 402) */
132
140
  _sessionPricing = new Map();
@@ -219,6 +227,7 @@ export class BuyerPaymentManager {
219
227
  // Without this, maxSignable = 0 + maxPerRequestUsdc after restart, permanently capping
220
228
  // the cumulative and causing non-monotonic SpendingAuth rejections on the seller.
221
229
  this._verifiedCost.set(peerId, persistedCumulative);
230
+ this._requestLedgers.delete(peerId);
222
231
  // Stores predating browser recovery (including the current sqlite node
223
232
  // store) omit these optional fields. Preserve their historical default
224
233
  // ceiling instead of interpreting missing recovery state as a confirmed
@@ -315,6 +324,7 @@ export class BuyerPaymentManager {
315
324
  this._sellerAccepted.delete(sellerPeerId);
316
325
  this._metadata.delete(sellerPeerId);
317
326
  this._verifiedCost.delete(sellerPeerId);
327
+ this._requestLedgers.delete(sellerPeerId);
318
328
  this._sessionPricing.delete(sellerPeerId);
319
329
  this._currentReserveCeiling.delete(sellerPeerId);
320
330
  this._initialReserveAmount.delete(sellerPeerId);
@@ -418,15 +428,16 @@ export class BuyerPaymentManager {
418
428
  + this._config.maxPerRequestUsdc * BigInt(Math.floor(inFlightRequests));
419
429
  maxSignable = catchUpMax < ceiling ? catchUpMax : ceiling;
420
430
  }
421
- // Prefer the seller-supplied target when present — a raw
422
- // `currentCumulative + minBudgetPerRequest` advance may still fall short
423
- // of what the seller has already spent, producing an infinite 402 loop.
431
+ // The seller's target is what it has delivered. Signing more would make
432
+ // undelivered work claimable on-chain, and signing less than the target
433
+ // would leave the seller rejecting us in a 402 loop.
424
434
  const minAdvance = currentCumulative + minBudgetPerRequest;
425
- const requestedAmount = targetCumulative != null && targetCumulative > minAdvance
426
- ? targetCumulative
427
- : minAdvance;
435
+ const requestedAmount = targetCumulative ?? minAdvance;
428
436
  const nextCumulative = requestedAmount < maxSignable ? requestedAmount : maxSignable;
429
- const extendNeedsTopUp = this._needsCeilingAdvance(requestedAmount, maxSignable, ceiling);
437
+ // The top-up still asks for room for the next request: a target at the
438
+ // ceiling fills the reserve, and the seller closes a full channel as
439
+ // exhausted. A top-up locks more deposit but makes nothing claimable.
440
+ const extendNeedsTopUp = this._needsCeilingAdvance(requestedAmount > minAdvance ? requestedAmount : minAdvance, maxSignable, ceiling);
430
441
  if (nextCumulative <= currentCumulative) {
431
442
  // Nothing to sign at current ceiling; a top-up still extends it for the next round.
432
443
  debugWarn(`[BuyerPayment] Cannot extend active session for ${sellerPeerId.slice(0, 12)}... ` +
@@ -440,6 +451,11 @@ export class BuyerPaymentManager {
440
451
  // A SpendingAuth committed while this one was signed already signed past the target.
441
452
  if (spendingAuth === 'superseded')
442
453
  return { sessionId: session.sessionId, topUp: extendNeedsTopUp };
454
+ // Reopening takes everything signed so far as verified. The seller's 402
455
+ // asked for all it had served, so the requests recorded before now are
456
+ // paid: counting one on top later would pay for it twice.
457
+ if (reopened.verifiedCost !== (this._verifiedCost.get(sellerPeerId) ?? 0n))
458
+ this._requestLedgers.delete(sellerPeerId);
443
459
  this._verifiedCost.set(sellerPeerId, reopened.verifiedCost);
444
460
  this._reportSpend({
445
461
  sellerPeerId,
@@ -622,13 +638,6 @@ export class BuyerPaymentManager {
622
638
  _needsCeilingAdvance(requestedAmount, maxSignable, ceiling) {
623
639
  return requestedAmount > maxSignable && maxSignable >= ceiling;
624
640
  }
625
- /**
626
- * Both signPerRequestAuth (buyer-initiated) and handleNeedAuth (seller-initiated)
627
- * can fire for the same delivered response. Whichever path accounts for the
628
- * response first records its requestId here so the other path does not
629
- * duplicate its service amount, token totals, or request count.
630
- */
631
- _serviceTokensCounted = new CountedRequestTracker();
632
641
  _spendListener = null;
633
642
  /**
634
643
  * Observe per-request spend as it is signed. Used to attribute cost to the
@@ -839,6 +848,7 @@ export class BuyerPaymentManager {
839
848
  this._cumulativeAmount.set(sellerPeerId, 0n);
840
849
  this._metadata.set(sellerPeerId, initialMetadata);
841
850
  this._verifiedCost.set(sellerPeerId, 0n);
851
+ this._requestLedgers.delete(sellerPeerId);
842
852
  this._currentReserveCeiling.set(sellerPeerId, 0n);
843
853
  this._initialReserveAmount.set(sellerPeerId, maxAmount);
844
854
  this._reserveSalt.set(sellerPeerId, salt);
@@ -1066,13 +1076,38 @@ export class BuyerPaymentManager {
1066
1076
  beginPaidRequest(sellerPeerId) {
1067
1077
  this._inFlightPaidRequests.set(sellerPeerId, (this._inFlightPaidRequests.get(sellerPeerId) ?? 0) + 1);
1068
1078
  }
1069
- endPaidRequest(sellerPeerId) {
1079
+ /**
1080
+ * The attempt is over. Record what arrived (recordDeliveredResponse) before
1081
+ * this: an attempt that ends with nothing recorded owes nothing when the
1082
+ * seller `answered` it (an error answer, a 402 the buyer retries). When it
1083
+ * did not, the attempt was cut off with nothing the buyer can price: the
1084
+ * seller may still bill it, and only the overdraft window pays for that.
1085
+ */
1086
+ endPaidRequest(sellerPeerId, requestId, answered = false) {
1087
+ if (requestId && !answered && !this._requestLedgers.get(sellerPeerId)?.has(requestId)) {
1088
+ this.recordDeliveredResponse(sellerPeerId, requestId, { costUsdc: 0n, cutOff: true });
1089
+ }
1070
1090
  const remaining = (this._inFlightPaidRequests.get(sellerPeerId) ?? 0) - 1;
1071
1091
  if (remaining > 0)
1072
1092
  this._inFlightPaidRequests.set(sellerPeerId, remaining);
1073
1093
  else
1074
1094
  this._inFlightPaidRequests.delete(sellerPeerId);
1075
1095
  }
1096
+ /**
1097
+ * The buyer received `sellerPeerId`'s response to paid request `requestId`
1098
+ * and priced it itself, or cut the attempt off (`cutOff`). The seller may
1099
+ * charge for it once, up to that cost, on the channel live now (the ledger
1100
+ * is dropped when a channel starts or ends).
1101
+ */
1102
+ recordDeliveredResponse(sellerPeerId, requestId, delivered) {
1103
+ let ledger = this._requestLedgers.get(sellerPeerId);
1104
+ if (!ledger)
1105
+ this._requestLedgers.set(sellerPeerId, ledger = new Map());
1106
+ // Bounded like request billing: forgetting a request only ever pays the seller less.
1107
+ if (ledger.size >= MAX_REQUEST_BILLING_ENTRIES && !ledger.has(requestId))
1108
+ ledger.delete(ledger.keys().next().value);
1109
+ ledger.set(requestId, delivered);
1110
+ }
1076
1111
  /**
1077
1112
  * How much of the current ceiling is a top-up not yet locked on-chain. A
1078
1113
  * landed top-up the buyer has not heard about is reconciled first, so it is
@@ -1152,7 +1187,6 @@ export class BuyerPaymentManager {
1152
1187
  let estimatedCachedInputTokens = 0n;
1153
1188
  let byteEstimatedTokens = false;
1154
1189
  let buyerEstimatedRequestCost;
1155
- let verifiedCostDelta = 0n;
1156
1190
  const requestBilling = responseStats.requestId != null
1157
1191
  ? this.getRequestBilling(responseStats.requestId)
1158
1192
  : undefined;
@@ -1172,7 +1206,6 @@ export class BuyerPaymentManager {
1172
1206
  : 0n;
1173
1207
  const unitCost = validateUnitNormalizedCost(unitBillingModel, requestBilling.context, responseStats.unitUsage);
1174
1208
  buyerEstimatedRequestCost = tokenCost + unitCost;
1175
- verifiedCostDelta += buyerEstimatedRequestCost;
1176
1209
  debugLog(`[BuyerPayment] Hybrid billing-estimated cost=${buyerEstimatedRequestCost} service=${responseStats.service ?? 'unknown'}`);
1177
1210
  }
1178
1211
  else if (hasReportedTokens) {
@@ -1190,14 +1223,12 @@ export class BuyerPaymentManager {
1190
1223
  if (pricing) {
1191
1224
  const cost = computeCostUsdc(Number(freshInputTokens), Number(estimatedOutputTokens), pricing, Number(cachedInputTokens));
1192
1225
  buyerEstimatedRequestCost = cost;
1193
- verifiedCostDelta += cost;
1194
1226
  }
1195
1227
  else if (responseStats.sellerClaimedCost != null && responseStats.sellerClaimedCost > 0n) {
1196
1228
  // No local pricing available (e.g. after buyer restart before session pricing is restored).
1197
1229
  // Use seller's claimed cost for verifiedCost accumulation so _maxSignable can grow.
1198
1230
  // The seller's claim is still validated against tolerance below.
1199
1231
  buyerEstimatedRequestCost = responseStats.sellerClaimedCost;
1200
- verifiedCostDelta += responseStats.sellerClaimedCost;
1201
1232
  }
1202
1233
  else {
1203
1234
  buyerEstimatedRequestCost = 0n;
@@ -1211,9 +1242,6 @@ export class BuyerPaymentManager {
1211
1242
  estimatedInputTokens = estimate ? BigInt(estimate.inputTokens) : 0n;
1212
1243
  estimatedOutputTokens = estimate ? BigInt(estimate.outputTokens) : 0n;
1213
1244
  buyerEstimatedRequestCost = estimate ? estimate.cost : 0n;
1214
- if (estimate) {
1215
- verifiedCostDelta += estimate.cost;
1216
- }
1217
1245
  debugLog(`[BuyerPayment] Byte-estimated tokens (no reported): in=${estimatedInputTokens} out=${estimatedOutputTokens} cost=${buyerEstimatedRequestCost}`);
1218
1246
  }
1219
1247
  // Image attribution (metadata/stats only — never cost). The count is the
@@ -1262,22 +1290,30 @@ export class BuyerPaymentManager {
1262
1290
  }
1263
1291
  // If cost is 0, the cumulative amount stays the same — no spending auth needed
1264
1292
  // but we still sign one to keep the seller's session alive.
1265
- // NeedAuth may have counted this response first; its cost is then already
1266
- // in the verified cost and (unless NeedAuth was capped at the reserve
1267
- // ceiling) the signed cumulative. Charge only the part it left unsigned,
1268
- // so the request is neither paid twice nor left short before a close.
1269
- const alreadyCounted = this._serviceTokensCounted.has(responseStats.requestId);
1270
- if (alreadyCounted) {
1271
- acceptedCost = this._serviceTokensCounted.unpaid(responseStats.requestId);
1272
- verifiedCostDelta = 0n;
1273
- }
1274
- // Advance cumulative amount by the accepted cost.
1293
+ // A response with a request ID is owed only while the ledger holds it: with
1294
+ // no open record it was counted already or nothing is owed for it. What is
1295
+ // owed is every response the buyer received whose cost frame never
1296
+ // arrived, each at the buyer's own cost; an attempt the buyer cut off is
1297
+ // paid only through its NeedAuth. A response with no request ID cannot be
1298
+ // recorded, and is paid as reported.
1299
+ const ledger = this._requestLedgers.get(sellerPeerId);
1300
+ const counted = [...ledger ?? []].filter(([, record]) => !record.cutOff);
1301
+ const alreadyCounted = responseStats.requestId != null && !counted.some(([requestId]) => requestId === responseStats.requestId);
1302
+ const reportedCost = responseStats.requestId != null ? 0n : acceptedCost;
1303
+ acceptedCost = reportedCost;
1304
+ for (const [, record] of counted)
1305
+ acceptedCost += record.costUsdc;
1306
+ // Sign up to the verified cost once these are counted. A cost a NeedAuth
1307
+ // counted but could not sign (reserve ceiling, pending top-up) is signed
1308
+ // here; what a seller prompt or a 402 retry already signed past verified
1309
+ // cost is not signed again.
1275
1310
  // maxSignable already caps at reserve ceiling, so one cap is sufficient
1276
1311
  const prevAmount = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1277
- const previousVerifiedCost = this._verifiedCost.get(sellerPeerId) ?? 0n;
1278
- const nextVerifiedCost = previousVerifiedCost + verifiedCostDelta;
1312
+ const nextVerifiedCost = (this._verifiedCost.get(sellerPeerId) ?? 0n) + acceptedCost;
1279
1313
  const maxSignable = this._maxSignableForVerified(sellerPeerId, nextVerifiedCost);
1280
- let newAmount = prevAmount + acceptedCost;
1314
+ let newAmount = prevAmount + reportedCost;
1315
+ if (newAmount < nextVerifiedCost)
1316
+ newAmount = nextVerifiedCost;
1281
1317
  if (newAmount > maxSignable)
1282
1318
  newAmount = maxSignable;
1283
1319
  // A conservative recovery ceiling may temporarily be below an amount we
@@ -1286,7 +1322,27 @@ export class BuyerPaymentManager {
1286
1322
  newAmount = prevAmount;
1287
1323
  const signedDelta = newAmount - prevAmount;
1288
1324
  // Update cumulative metadata, deduplicating usage for a response NeedAuth already counted.
1289
- const newMeta = this._advanceUsageMetadata(this._metadata.get(sellerPeerId), responseStats.service, {
1325
+ // Each other response counted here goes to its own service, with its own usage.
1326
+ let otherMeta = this._metadata.get(sellerPeerId);
1327
+ let othersAmount = 0n;
1328
+ for (const [requestId, { costUsdc, service, usage }] of counted) {
1329
+ if (requestId === responseStats.requestId || !usage)
1330
+ continue;
1331
+ const images = countUnits(usage.unitUsage, 'output_images');
1332
+ otherMeta = this._advanceUsageMetadata(otherMeta, service, {
1333
+ amount: costUsdc,
1334
+ inputTokens: usage.inputTokens,
1335
+ cachedInputTokens: usage.cachedInputTokens,
1336
+ outputTokens: usage.outputTokens + images * OUTPUT_IMAGE_TOKEN_EQUIVALENT,
1337
+ requests: 1n,
1338
+ outputImages: images,
1339
+ videoGenerations: countUnits(usage.unitUsage, 'video_generations'),
1340
+ videoSeconds: countUnits(usage.unitUsage, 'video_seconds'),
1341
+ inputCharacters: countUnits(usage.unitUsage, 'input_characters'),
1342
+ });
1343
+ othersAmount += costUsdc;
1344
+ }
1345
+ const newMeta = this._advanceUsageMetadata(otherMeta, responseStats.service, {
1290
1346
  ...normalizeRequestUsageDelta({
1291
1347
  amount: signedDelta,
1292
1348
  inputTokens: estimatedInputTokens,
@@ -1298,8 +1354,9 @@ export class BuyerPaymentManager {
1298
1354
  videoSeconds: estimatedVideoSeconds,
1299
1355
  inputCharacters: estimatedInputCharacters,
1300
1356
  }, { deliveredResponse: true, alreadyCounted }),
1301
- // Any remainder of a NeedAuth-counted request is still this service's amount.
1302
- amount: signedDelta,
1357
+ // Any remainder of a NeedAuth-counted request is still this service's amount,
1358
+ // as is a cost counted here that a seller prompt had already signed for.
1359
+ amount: (signedDelta > acceptedCost ? signedDelta : acceptedCost) - othersAmount,
1303
1360
  });
1304
1361
  debugLog(`[BuyerPayment] signPerRequestAuth #${newMeta.cumulativeRequestCount}: ` +
1305
1362
  `thisReq in=${estimatedInputTokens} out=${estimatedOutputTokens} | ` +
@@ -1331,12 +1388,9 @@ export class BuyerPaymentManager {
1331
1388
  this._cumulativeAmount.set(sellerPeerId, newAmount);
1332
1389
  this._verifiedCost.set(sellerPeerId, nextVerifiedCost);
1333
1390
  this._metadata.set(sellerPeerId, newMeta);
1334
- if (alreadyCounted) {
1335
- this._serviceTokensCounted.pay(responseStats.requestId, signedDelta);
1336
- }
1337
- else {
1338
- this._serviceTokensCounted.mark(responseStats.requestId);
1339
- }
1391
+ // Counted: no later NeedAuth may claim a cost for them.
1392
+ for (const [requestId] of counted)
1393
+ ledger.delete(requestId);
1340
1394
  this._reportSpend({
1341
1395
  sellerPeerId,
1342
1396
  requestId: responseStats.requestId ?? null,
@@ -1412,6 +1466,34 @@ export class BuyerPaymentManager {
1412
1466
  const buyerBillingContext = requestBilling?.context;
1413
1467
  const requiredCumulativeAmount = BigInt(payload.requiredCumulativeAmount);
1414
1468
  const currentCumulative = this._cumulativeAmount.get(sellerPeerId) ?? 0n;
1469
+ // A cost counts toward verified cost only for a request the buyer holds an
1470
+ // open record of, and only up to the buyer's own cost in that record. The
1471
+ // token counts in the frame are the seller's own, so they prove nothing:
1472
+ // without this any claimed cost would count as verified, for a request
1473
+ // that failed, was never sent, or was already paid.
1474
+ const ledger = this._requestLedgers.get(sellerPeerId);
1475
+ let record = payload.lastRequestCost != null && payload.requestId ? ledger?.get(payload.requestId) : undefined;
1476
+ if (record?.costCounted)
1477
+ record = undefined;
1478
+ if (hasPositiveCost(payload.lastRequestCost) && !record) {
1479
+ debugWarn(`[BuyerPayment] Refusing NeedAuth from ${sellerPeerId.slice(0, 12)}... claiming a cost for request ` +
1480
+ `${payload.requestId ?? '(none)'}: nothing is owed for it`);
1481
+ return false;
1482
+ }
1483
+ if (record && hasPositiveCost(payload.lastRequestCost) !== record.costUsdc > 0n) {
1484
+ // One side puts a cost on the request and the other none: the buyer cut
1485
+ // the attempt off with nothing it can price, or the frame is for an
1486
+ // earlier attempt (a retry keeps the request ID). Nothing counts as
1487
+ // verified and the record stays: the frame is answered as a prompt,
1488
+ // signed only while it fits the overdraft window.
1489
+ payload = { ...payload, lastRequestCost: undefined, billingUsage: undefined };
1490
+ record = undefined;
1491
+ }
1492
+ else if (record?.costUsdc === 0n) {
1493
+ // Both sides put no cost on it: nothing is owed for it.
1494
+ ledger.delete(payload.requestId);
1495
+ record = undefined;
1496
+ }
1415
1497
  // Reject stale/lower NeedAuth (monotonicity guard)
1416
1498
  if (requiredCumulativeAmount <= currentCumulative) {
1417
1499
  // A catch-up prompt (no response cost) for what is already signed but
@@ -1537,33 +1619,70 @@ export class BuyerPaymentManager {
1537
1619
  // Accumulate verified cost from the seller's report
1538
1620
  verifiedCostDelta += sellerCost;
1539
1621
  }
1622
+ // The most of the claim that counts as verified. A seller can honestly
1623
+ // claim more than the response shows (an agent's internal tool turns, a
1624
+ // different usage report), so the frame is not refused: the rest is signed
1625
+ // only while it fits the overdraft window, like any prompt.
1626
+ const verifiableCost = record
1627
+ ? BigInt(Math.ceil(Number(record.costUsdc) * this._costToleranceFor(requestBilling)))
1628
+ : 0n;
1629
+ if (verifiedCostDelta > verifiableCost) {
1630
+ debugWarn(`[BuyerPayment] NeedAuth from ${sellerPeerId.slice(0, 12)}... claims ${verifiedCostDelta} for request ${payload.requestId}; ` +
1631
+ `the buyer's own cost for it is ${record?.costUsdc ?? 0n}: counting ${verifiableCost}`);
1632
+ verifiedCostDelta = verifiableCost;
1633
+ if (acceptedServiceCost > verifiableCost)
1634
+ acceptedServiceCost = verifiableCost;
1635
+ }
1540
1636
  // Cap at overdraft limit: verifiedCost + maxPerRequestUsdc, then at reserve ceiling.
1541
1637
  // This prevents a malicious seller from claiming a small cost but requesting the full reserve.
1542
1638
  const previousVerifiedCost = this._verifiedCost.get(sellerPeerId) ?? 0n;
1543
- let nextVerifiedCost = previousVerifiedCost + verifiedCostDelta;
1544
- let maxSignable = this._maxSignableForVerified(sellerPeerId, nextVerifiedCost);
1639
+ const nextVerifiedCost = previousVerifiedCost + verifiedCostDelta;
1640
+ const maxSignable = this._maxSignableForVerified(sellerPeerId, nextVerifiedCost);
1545
1641
  const ceiling = this._getCeiling(sellerPeerId);
1546
- let needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
1642
+ const needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
1643
+ // A cost the buyer cannot sign for in this frame (the overdraft window is
1644
+ // used up, or the reserve ceiling is reached and a top-up is pending)
1645
+ // still counts, once, toward verified cost. The seller's next prompt, or
1646
+ // the buyer's own signing before a close, signs up to it. The record stays,
1647
+ // counted at no cost, so that close still attributes the response's usage.
1648
+ const countUnsigned = () => {
1649
+ if (!record)
1650
+ return;
1651
+ ledger.set(payload.requestId, { ...record, costUsdc: 0n, costCounted: true });
1652
+ this._verifiedCost.set(sellerPeerId, nextVerifiedCost);
1653
+ };
1654
+ // A NeedAuth never reopens a used-up overdraft window: the seller could
1655
+ // repeat the frame and have the buyer sign one more window each time,
1656
+ // with no work to show for it. Only the buyer's own 402 retry reopens it
1657
+ // (extendCurrentSpendingAuth).
1547
1658
  if (maxSignable <= currentCumulative && !needsTopUp) {
1548
- const reopened = this._reopenOverdraftWindowIfCollapsed(sellerPeerId, currentCumulative, maxSignable, 'handleNeedAuth', nextVerifiedCost);
1549
- maxSignable = reopened.maxSignable;
1550
- nextVerifiedCost = reopened.verifiedCost;
1551
- needsTopUp = this._needsCeilingAdvance(requiredCumulativeAmount, maxSignable, ceiling);
1552
- if (maxSignable <= currentCumulative && !needsTopUp) {
1553
- debugWarn(`[BuyerPayment] NeedAuth: maxSignable=${maxSignable} <= currentCumulative=${currentCumulative} — overdraft limit reached`);
1554
- return false;
1555
- }
1659
+ countUnsigned();
1660
+ debugWarn(`[BuyerPayment] NeedAuth: maxSignable=${maxSignable} <= currentCumulative=${currentCumulative} — overdraft limit reached`);
1661
+ return false;
1556
1662
  }
1557
1663
  // When a topUp is needed, first sign at the current ceiling so the seller
1558
1664
  // has a high-enough settled amount to pass the on-chain TopUpThresholdNotMet
1559
1665
  // check (contract requires TOP_UP_SETTLED_THRESHOLD_BPS of deposit to be settleable before topUp).
1560
1666
  // We cap at the old ceiling here; the topUp is sent AFTER so the seller
1561
1667
  // processes the SpendingAuth first, then the topUp with adequate settle amount.
1562
- const effectiveAmount = needsTopUp
1668
+ let effectiveAmount = needsTopUp
1563
1669
  ? (maxSignable > currentCumulative ? maxSignable : currentCumulative)
1564
1670
  : (requiredCumulativeAmount < maxSignable ? requiredCumulativeAmount : maxSignable);
1671
+ // While a top-up is pending, the seller can only accept up to the deposit
1672
+ // locked on-chain, and the contract runs topUp() only once enough of that
1673
+ // deposit is settled. Crossing it in one jump (from below the settle
1674
+ // threshold to above the deposit) leaves the seller with no auth it can
1675
+ // use: it rejects the new one, can never submit the top-up, and the
1676
+ // channel strands work above the deposit. Sign exactly the confirmed
1677
+ // deposit first; the next prompt signs the rest.
1678
+ const confirmedDeposit = this._pendingReserveAuth.get(sellerPeerId)?.confirmedAmount ?? 0n;
1679
+ if (confirmedDeposit > 0n && currentCumulative < confirmedDeposit && effectiveAmount > confirmedDeposit) {
1680
+ debugLog(`[BuyerPayment] NeedAuth: signing the confirmed deposit ${confirmedDeposit} first (target ${effectiveAmount}) while a top-up is pending`);
1681
+ effectiveAmount = confirmedDeposit;
1682
+ }
1565
1683
  if (effectiveAmount <= currentCumulative) {
1566
1684
  // Nothing to sign; a top-up still extends the ceiling for the next round.
1685
+ countUnsigned();
1567
1686
  debugWarn(`[BuyerPayment] NeedAuth: effectiveAmount=${effectiveAmount} <= currentCumulative=${currentCumulative} — cannot advance`);
1568
1687
  return needsTopUp;
1569
1688
  }
@@ -1576,9 +1695,6 @@ export class BuyerPaymentManager {
1576
1695
  const serviceAmountDelta = acceptedServiceCost > 0n
1577
1696
  ? (acceptedServiceCost < signedDelta ? acceptedServiceCost : signedDelta)
1578
1697
  : 0n;
1579
- // If post-response signing counted this response first, deduplicate the
1580
- // response's service amount and usage together.
1581
- const alreadyCounted = this._serviceTokensCounted.has(payload.requestId);
1582
1698
  // Attribution only — never cost; mirrors signPerRequestAuth.
1583
1699
  let attributedInputTokens = reportedInputTokens;
1584
1700
  let attributedOutputTokens = reportedOutputTokens;
@@ -1598,7 +1714,7 @@ export class BuyerPaymentManager {
1598
1714
  videoGenerations: acceptedVideoGenerations,
1599
1715
  videoSeconds: acceptedVideoSeconds,
1600
1716
  inputCharacters: acceptedInputCharacters,
1601
- }, { deliveredResponse, alreadyCounted }));
1717
+ }, { deliveredResponse, alreadyCounted: false }));
1602
1718
  // Persistence and transport failures must propagate to the connection
1603
1719
  // owner. In particular, swallowing an IndexedDB failure leaves the browser
1604
1720
  // connected with advanced in-memory counters but no durable signature.
@@ -1607,17 +1723,16 @@ export class BuyerPaymentManager {
1607
1723
  return false;
1608
1724
  this._verifiedCost.set(sellerPeerId, nextVerifiedCost);
1609
1725
  this._metadata.set(sellerPeerId, newMeta);
1610
- if (deliveredResponse && !alreadyCounted) {
1611
- this._serviceTokensCounted.mark(payload.requestId, acceptedServiceCost - serviceAmountDelta);
1612
- }
1726
+ if (record)
1727
+ ledger.delete(payload.requestId);
1613
1728
  this._reportSpend({
1614
1729
  sellerPeerId,
1615
1730
  requestId: payload.requestId ?? null,
1616
1731
  amountUsdc: signedDelta.toString(),
1617
- inputTokens: (deliveredResponse && !alreadyCounted ? attributedInputTokens : 0n).toString(),
1618
- cachedInputTokens: (deliveredResponse && !alreadyCounted ? reportedCachedInputTokens : 0n).toString(),
1619
- outputTokens: (deliveredResponse && !alreadyCounted ? attributedOutputTokens : 0n).toString(),
1620
- outputImages: (deliveredResponse && !alreadyCounted ? acceptedOutputImages : 0n).toString(),
1732
+ inputTokens: (deliveredResponse ? attributedInputTokens : 0n).toString(),
1733
+ cachedInputTokens: (deliveredResponse ? reportedCachedInputTokens : 0n).toString(),
1734
+ outputTokens: (deliveredResponse ? attributedOutputTokens : 0n).toString(),
1735
+ outputImages: (deliveredResponse ? acceptedOutputImages : 0n).toString(),
1621
1736
  });
1622
1737
  paymentMux.sendSpendingAuth(spendingAuth);
1623
1738
  debugLog(`[BuyerPayment] NeedAuth responded: new cumulativeAmount=${effectiveAmount}`);
@@ -2254,6 +2369,8 @@ export class BuyerPaymentManager {
2254
2369
  */
2255
2370
  markRequestCovered(sellerPeerId, requestId) {
2256
2371
  this.clearRequestBilling(requestId);
2372
+ // Nothing is owed for it, even once the covered record below expires.
2373
+ this._requestLedgers.get(sellerPeerId)?.delete(requestId);
2257
2374
  const key = coveredRequestKey(sellerPeerId, requestId);
2258
2375
  const now = Date.now();
2259
2376
  for (const [id, markedAt] of this._coveredRequests) {