@antseed/node 0.2.181 → 0.2.183

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 (200) hide show
  1. package/README.md +2 -0
  2. package/dist/buyer-identity-context.d.ts.map +1 -1
  3. package/dist/buyer-identity-context.js +2 -2
  4. package/dist/buyer-identity-context.js.map +1 -1
  5. package/dist/discovery/announcer.d.ts.map +1 -1
  6. package/dist/discovery/dht-health.d.ts.map +1 -1
  7. package/dist/discovery/dht-health.js.map +1 -1
  8. package/dist/discovery/dht-node.d.ts.map +1 -1
  9. package/dist/discovery/dht-node.js.map +1 -1
  10. package/dist/discovery/http-metadata-resolver.d.ts.map +1 -1
  11. package/dist/discovery/metadata/define-version.d.ts +11 -2
  12. package/dist/discovery/metadata/define-version.d.ts.map +1 -1
  13. package/dist/discovery/metadata/define-version.js +7 -3
  14. package/dist/discovery/metadata/define-version.js.map +1 -1
  15. package/dist/discovery/metadata/field.d.ts +17 -1
  16. package/dist/discovery/metadata/field.d.ts.map +1 -1
  17. package/dist/discovery/metadata/field.js +12 -1
  18. package/dist/discovery/metadata/field.js.map +1 -1
  19. package/dist/discovery/metadata/fields/provider-basics.d.ts +1 -1
  20. package/dist/discovery/metadata/fields/provider-basics.d.ts.map +1 -1
  21. package/dist/discovery/metadata/fields/provider-basics.js +5 -2
  22. package/dist/discovery/metadata/fields/provider-basics.js.map +1 -1
  23. package/dist/discovery/metadata/fields/service-api-protocols.d.ts +1 -1
  24. package/dist/discovery/metadata/fields/service-api-protocols.d.ts.map +1 -1
  25. package/dist/discovery/metadata/fields/service-api-protocols.js +2 -1
  26. package/dist/discovery/metadata/fields/service-api-protocols.js.map +1 -1
  27. package/dist/discovery/metadata/fields/service-categories.d.ts +1 -1
  28. package/dist/discovery/metadata/fields/service-categories.d.ts.map +1 -1
  29. package/dist/discovery/metadata/fields/service-categories.js +2 -1
  30. package/dist/discovery/metadata/fields/service-categories.js.map +1 -1
  31. package/dist/discovery/metadata/fields/service-unit-billing.d.ts +1 -1
  32. package/dist/discovery/metadata/fields/service-unit-billing.d.ts.map +1 -1
  33. package/dist/discovery/metadata/fields/service-unit-billing.js +4 -2
  34. package/dist/discovery/metadata/fields/service-unit-billing.js.map +1 -1
  35. package/dist/discovery/metadata/index.d.ts +3 -2
  36. package/dist/discovery/metadata/index.d.ts.map +1 -1
  37. package/dist/discovery/metadata/index.js +2 -2
  38. package/dist/discovery/metadata/index.js.map +1 -1
  39. package/dist/discovery/metadata/wire.d.ts.map +1 -1
  40. package/dist/discovery/metadata/wire.js.map +1 -1
  41. package/dist/discovery/metadata-server.d.ts.map +1 -1
  42. package/dist/discovery/peer-lookup.d.ts.map +1 -1
  43. package/dist/discovery/peer-lookup.js +9 -2
  44. package/dist/discovery/peer-lookup.js.map +1 -1
  45. package/dist/discovery/service-catalog.js.map +1 -1
  46. package/dist/health/gas-auto-refuel.d.ts.map +1 -1
  47. package/dist/health/gas-auto-refuel.js.map +1 -1
  48. package/dist/health/gas-health-monitor.d.ts.map +1 -1
  49. package/dist/health/model-health-checker.d.ts.map +1 -1
  50. package/dist/health/model-health-checker.js.map +1 -1
  51. package/dist/health/self-health-error.d.ts +6 -0
  52. package/dist/health/self-health-error.d.ts.map +1 -1
  53. package/dist/health/self-health-error.js +33 -0
  54. package/dist/health/self-health-error.js.map +1 -1
  55. package/dist/health/service-performance.d.ts.map +1 -1
  56. package/dist/health/service-performance.js.map +1 -1
  57. package/dist/health/stream-outcome.d.ts.map +1 -1
  58. package/dist/index.d.ts +5 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +2 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/metering/receipt-generator.d.ts.map +1 -1
  63. package/dist/metering/receipt-verifier.d.ts.map +1 -1
  64. package/dist/metering/seller-session-tracker.d.ts.map +1 -1
  65. package/dist/metering/session-tracker.d.ts.map +1 -1
  66. package/dist/metering/storage.d.ts +6 -0
  67. package/dist/metering/storage.d.ts.map +1 -1
  68. package/dist/metering/storage.js +8 -0
  69. package/dist/metering/storage.js.map +1 -1
  70. package/dist/metering/usage-aggregator.d.ts.map +1 -1
  71. package/dist/metering/usage-aggregator.js.map +1 -1
  72. package/dist/node.d.ts +21 -2
  73. package/dist/node.d.ts.map +1 -1
  74. package/dist/node.js +34 -16
  75. package/dist/node.js.map +1 -1
  76. package/dist/p2p/connection-auth.d.ts.map +1 -1
  77. package/dist/p2p/connection-auth.js.map +1 -1
  78. package/dist/p2p/connection-manager.d.ts +26 -0
  79. package/dist/p2p/connection-manager.d.ts.map +1 -1
  80. package/dist/p2p/connection-manager.js +88 -6
  81. package/dist/p2p/connection-manager.js.map +1 -1
  82. package/dist/p2p/identity-envelope.js.map +1 -1
  83. package/dist/p2p/identity.d.ts.map +1 -1
  84. package/dist/p2p/identity.js.map +1 -1
  85. package/dist/p2p/inbound-idle-tracker.d.ts +13 -5
  86. package/dist/p2p/inbound-idle-tracker.d.ts.map +1 -1
  87. package/dist/p2p/inbound-idle-tracker.js +11 -4
  88. package/dist/p2p/inbound-idle-tracker.js.map +1 -1
  89. package/dist/p2p/keepalive.d.ts.map +1 -1
  90. package/dist/p2p/nat-traversal.d.ts.map +1 -1
  91. package/dist/p2p/secure-channel.d.ts.map +1 -1
  92. package/dist/p2p/secure-channel.js.map +1 -1
  93. package/dist/p2p/sweep-mux.d.ts.map +1 -1
  94. package/dist/payments/balance-manager.d.ts.map +1 -1
  95. package/dist/payments/channel-store.d.ts +2 -0
  96. package/dist/payments/channel-store.d.ts.map +1 -1
  97. package/dist/payments/channel-store.js +9 -0
  98. package/dist/payments/channel-store.js.map +1 -1
  99. package/dist/payments/contract-stack.d.ts.map +1 -1
  100. package/dist/payments/contract-stack.js.map +1 -1
  101. package/dist/payments/deposit-relayer.d.ts.map +1 -1
  102. package/dist/payments/evm/ants-token-client.d.ts.map +1 -1
  103. package/dist/payments/evm/block-range.js.map +1 -1
  104. package/dist/payments/evm/deposit-relay-client.d.ts.map +1 -1
  105. package/dist/payments/evm/emissions-client.d.ts.map +1 -1
  106. package/dist/payments/evm/emissions-gate-client.d.ts +10 -10
  107. package/dist/payments/evm/emissions-gate-client.d.ts.map +1 -1
  108. package/dist/payments/evm/free-usage-client.d.ts.map +1 -1
  109. package/dist/payments/evm/identity-client.d.ts.map +1 -1
  110. package/dist/payments/evm/multicall.js.map +1 -1
  111. package/dist/payments/evm/points-policy-registry-client.d.ts.map +1 -1
  112. package/dist/payments/evm/position-init-client.d.ts.map +1 -1
  113. package/dist/payments/evm/registry-client.d.ts.map +1 -1
  114. package/dist/payments/evm/seller-pools-client.d.ts.map +1 -1
  115. package/dist/payments/evm/seller-pools-rewards-client.d.ts.map +1 -1
  116. package/dist/payments/evm/seller-registry-client.d.ts.map +1 -1
  117. package/dist/payments/evm/seller-registry-client.js.map +1 -1
  118. package/dist/payments/evm/seller-rewards-pool-client.d.ts.map +1 -1
  119. package/dist/payments/evm/staking-client.d.ts.map +1 -1
  120. package/dist/payments/evm/stats-client.d.ts.map +1 -1
  121. package/dist/payments/evm/trust-signals-client.d.ts.map +1 -1
  122. package/dist/payments/evm/trust-signals-client.js.map +1 -1
  123. package/dist/payments/evm/usage-accounting-client.d.ts.map +1 -1
  124. package/dist/payments/evm/usage-rewards-client.d.ts.map +1 -1
  125. package/dist/payments/evm/usdc-eth-swap-client.d.ts.map +1 -1
  126. package/dist/payments/evm/verification-signals-client.d.ts.map +1 -1
  127. package/dist/payments/evm/verification-signals-client.js.map +1 -1
  128. package/dist/payments/evm/verifier-client.d.ts +2 -2
  129. package/dist/payments/evm/verifier-client.d.ts.map +1 -1
  130. package/dist/payments/evm/verifier-client.js.map +1 -1
  131. package/dist/payments/evm/wash-trading-registry-client.d.ts.map +1 -1
  132. package/dist/payments/evm/wash-trading-registry-client.js.map +1 -1
  133. package/dist/payments/free-tier-conversations.d.ts +59 -0
  134. package/dist/payments/free-tier-conversations.d.ts.map +1 -0
  135. package/dist/payments/free-tier-conversations.js +127 -0
  136. package/dist/payments/free-tier-conversations.js.map +1 -0
  137. package/dist/payments/free-tier-program.js.map +1 -1
  138. package/dist/payments/free-tier-stake-resolver.d.ts.map +1 -1
  139. package/dist/payments/free-tier-stake-resolver.js.map +1 -1
  140. package/dist/payments/generated-contract-addresses.d.ts +33 -33
  141. package/dist/payments/generated-contract-addresses.d.ts.map +1 -1
  142. package/dist/payments/index.d.ts +4 -4
  143. package/dist/payments/index.d.ts.map +1 -1
  144. package/dist/payments/index.js +2 -2
  145. package/dist/payments/index.js.map +1 -1
  146. package/dist/payments/reward-claims.js.map +1 -1
  147. package/dist/payments/rpc-health.d.ts.map +1 -1
  148. package/dist/payments/seller-buyer-limiter.d.ts.map +1 -1
  149. package/dist/payments/seller-buyer-limiter.js.map +1 -1
  150. package/dist/payments/seller-free-tier-limiter.d.ts +54 -0
  151. package/dist/payments/seller-free-tier-limiter.d.ts.map +1 -1
  152. package/dist/payments/seller-free-tier-limiter.js +89 -2
  153. package/dist/payments/seller-free-tier-limiter.js.map +1 -1
  154. package/dist/payments/seller-free-usage-manager.d.ts.map +1 -1
  155. package/dist/payments/seller-free-usage-manager.js.map +1 -1
  156. package/dist/payments/seller-payment-manager.d.ts +37 -4
  157. package/dist/payments/seller-payment-manager.d.ts.map +1 -1
  158. package/dist/payments/seller-payment-manager.js +155 -46
  159. package/dist/payments/seller-payment-manager.js.map +1 -1
  160. package/dist/reputation/identity-history.d.ts.map +1 -1
  161. package/dist/reputation/identity-history.js.map +1 -1
  162. package/dist/reputation/model-reputation.js.map +1 -1
  163. package/dist/reputation/public-json.js.map +1 -1
  164. package/dist/reputation/rating-manager.d.ts.map +1 -1
  165. package/dist/reputation/report-manager.d.ts.map +1 -1
  166. package/dist/reputation/sybil-risk.js.map +1 -1
  167. package/dist/reputation/trust-score.d.ts.map +1 -1
  168. package/dist/reputation/uptime-tracker.d.ts.map +1 -1
  169. package/dist/requested-service.d.ts +4 -0
  170. package/dist/requested-service.d.ts.map +1 -1
  171. package/dist/requested-service.js +19 -1
  172. package/dist/requested-service.js.map +1 -1
  173. package/dist/resources/resource-ownership-store.d.ts.map +1 -1
  174. package/dist/resources/resource-ownership-store.js.map +1 -1
  175. package/dist/routing/default-router.d.ts.map +1 -1
  176. package/dist/routing/model-route-ranking.d.ts +12 -2
  177. package/dist/routing/model-route-ranking.d.ts.map +1 -1
  178. package/dist/routing/model-route-ranking.js +74 -9
  179. package/dist/routing/model-route-ranking.js.map +1 -1
  180. package/dist/routing/seller-health.d.ts.map +1 -1
  181. package/dist/routing/seller-health.js.map +1 -1
  182. package/dist/seller-request-handler.d.ts +24 -2
  183. package/dist/seller-request-handler.d.ts.map +1 -1
  184. package/dist/seller-request-handler.js +278 -79
  185. package/dist/seller-request-handler.js.map +1 -1
  186. package/dist/utils/file-lock.js.map +1 -1
  187. package/dist/utils/response-body.d.ts +33 -0
  188. package/dist/utils/response-body.d.ts.map +1 -0
  189. package/dist/utils/response-body.js +191 -0
  190. package/dist/utils/response-body.js.map +1 -0
  191. package/dist/utils/response-headers.d.ts +4 -0
  192. package/dist/utils/response-headers.d.ts.map +1 -0
  193. package/dist/utils/response-headers.js +19 -0
  194. package/dist/utils/response-headers.js.map +1 -0
  195. package/dist/verification/samples.d.ts.map +1 -1
  196. package/dist/verification/samples.js.map +1 -1
  197. package/dist/verification/storage.d.ts.map +1 -1
  198. package/dist/verification/tee-status.d.ts +1 -1
  199. package/dist/verification/tee-status.d.ts.map +1 -1
  200. package/package.json +5 -5
@@ -1,19 +1,24 @@
1
1
  import { ANTSEED_ATTEST_PATH, ANTSEED_CHANNEL_BINDING_HEADER } from './interfaces/plugin.js';
2
2
  import { FREE_TIER_SERVED_COVERED, FREE_TIER_SERVED_HEADER, powerToAntsEpochs } from './payments/free-tier-program.js';
3
3
  import { FREE_TIER_DELEGATIONS_HEADER } from './payments/free-tier-delegation.js';
4
+ function describeFreeTierScreenRefusal(refusal) {
5
+ return refusal.reason === 'new_buyer_context'
6
+ ? `new buyer context inputTokens~${refusal.inputTokens} > ${refusal.maxInputTokens}`
7
+ : `moved conversation from ${refusal.owner} (${refusal.messages} messages, ~${refusal.tokens} tokens)`;
8
+ }
4
9
  const FREE_TIER_EXHAUSTED_MESSAGES = {
5
10
  address: 'This seller free tier has been exhausted for your buyer address.',
6
11
  ip: 'This seller free tier has been exhausted for your IP address.',
7
12
  stake: 'This seller staked free tier has been exhausted for your stake.',
8
13
  stake_required: 'This model is free only for buyers staked on this seller.',
9
14
  };
10
- import { ProxyMux } from './proxy/proxy-mux.js';
15
+ import { ByteBudget, DEFAULT_MAX_UPLOAD_BODY_BYTES, ProxyMux } from './proxy/proxy-mux.js';
16
+ import { ConnectionState } from './types/connection.js';
11
17
  import { computeCostUsdc, estimateTokensFromBytesSampled, } from './payments/pricing.js';
12
18
  import { debugLog, debugWarn, isContentFreeLogging } from './utils/debug.js';
13
- import { buyerFacingResponseHeaders } from './proxy/buyer-response-headers.js';
14
19
  import { CONNECTION_CAPABILITY_RESPONSE_AUTH_V1, DEFAULT_FIRST_SIGN_CAP, DEFAULT_TOP_UP_SETTLED_THRESHOLD_BPS, computeOneOffChannelPlan, PAYMENT_CODE_CHANNEL_EXHAUSTED, PAYMENT_CODE_ONE_OFF_CHANNEL_REQUIRED, } from './types/protocol.js';
15
- import { createResponseAuthPayload, createStreamingResponseHash } from './verification/response-auth.js';
16
- import { VIDEO_DOWNLOAD_STREAM_HEADER, VIDEO_DOWNLOAD_STREAM_VERSION } from '@antseed/protocol/http';
20
+ import { createResponseAuthPayload, createStreamingResponseHash, hashRequest } from './verification/response-auth.js';
21
+ import { ANTSEED_STREAMING_RESPONSE_HEADER, VIDEO_DOWNLOAD_STREAM_HEADER, VIDEO_DOWNLOAD_STREAM_VERSION } from '@antseed/protocol/http';
17
22
  import { isServiceHealthFailing, preferHealthyUpstream, serviceHealthOf } from '@antseed/protocol/peer-metadata';
18
23
  import { hasJsonContentType, tryParseJsonObject } from './utils/json-codec.js';
19
24
  import { captureUnitBillingContext, computeFinalUnitBilling, estimateUnitRequestCost, isFreeUnitBillingModel } from './billing/unit.js';
@@ -23,10 +28,12 @@ import { isNativeVideoProtocol } from '@antseed/protocol/service-api';
23
28
  import { speechVoiceProblem } from '@antseed/protocol/peer-metadata';
24
29
  import { detectRequestServiceApiProtocol, selectTargetProtocolForRequest, } from '@antseed/api-adapter';
25
30
  import { parseResponseUsage } from './utils/response-usage.js';
31
+ import { exposedResponseHeaders } from './utils/response-headers.js';
32
+ import { ExposedSseStream, exposedJsonBody } from './utils/response-body.js';
26
33
  import { usageForBilling } from '@antseed/buyer-core';
27
34
  import { isCanonicalRequestPath } from './proxy/request-path.js';
28
- import { SERVICE_REQUIRED, billedRequestBody } from './requested-service.js';
29
- import { buildSelfHealthErrorResponse, buildUpstreamRateLimitedResponse, buildUpstreamUnavailableResponse, isUpstreamAccountError, isUpstreamFailureStatus } from './health/self-health-error.js';
35
+ import { SERVICE_REQUIRED, billedRequestBody, requestedMaxOutputTokens } from './requested-service.js';
36
+ import { buildSelfHealthErrorResponse, buildUpstreamRateLimitedResponse, buildUpstreamUnavailableResponse, describeUpstreamError, isUpstreamAccountError, isUpstreamFailureStatus } from './health/self-health-error.js';
30
37
  import { StreamOutcome } from './health/stream-outcome.js';
31
38
  import { routingProtocolForPath, routingProtocolOf, routingRequestOf, routingWireProtocol, ROUTING_PROTOCOLS } from '@antseed/protocol/routing';
32
39
  /** A seller's services of one routing protocol. */
@@ -132,6 +139,12 @@ function takeHeader(headers, name) {
132
139
  }
133
140
  return value;
134
141
  }
142
+ /**
143
+ * Most request body bytes a seller holds at once, uploads still arriving included.
144
+ * A request is held in memory until its response is sent, so this bounds what a
145
+ * burst of large requests can make the seller allocate.
146
+ */
147
+ export const DEFAULT_MAX_IN_FLIGHT_REQUEST_BYTES = 256 * 1024 * 1024;
135
148
  /** Debounce interval for metadata refresh after load changes. */
136
149
  const METADATA_REFRESH_DEBOUNCE_MS = 200;
137
150
  /** Time to wait for a catch-up SpendingAuth before returning 402. */
@@ -168,8 +181,11 @@ export class SellerRequestHandler {
168
181
  /** The provider and service pairs already reported as sending no usage figure; each is reported once. */
169
182
  _usageMissingReported = new Set();
170
183
  _metadataRefreshTimer = null;
184
+ /** Request bodies in memory on every connection: uploads still arriving and requests being served. */
185
+ _inFlightRequestBytes;
171
186
  constructor(deps) {
172
187
  this._deps = deps;
188
+ this._inFlightRequestBytes = new ByteBudget(Math.max(deps.maxInFlightRequestBytes ?? DEFAULT_MAX_IN_FLIGHT_REQUEST_BYTES, deps.maxUploadBodyBytes ?? DEFAULT_MAX_UPLOAD_BODY_BYTES));
173
189
  }
174
190
  _allowAttest(buyerPeerId) {
175
191
  const now = Date.now();
@@ -199,13 +215,14 @@ export class SellerRequestHandler {
199
215
  handleConnection(conn, buyerPeerId, paymentMux, verificationMux) {
200
216
  const mux = new ProxyMux(conn, {
201
217
  maxUploadBodyBytes: this._deps.maxUploadBodyBytes,
218
+ sharedUploadBudget: this._inFlightRequestBytes,
202
219
  });
203
220
  /** A request's buyer-limit reservation, finished with the tokens it used however the request ends. */
204
221
  const handleProxyRequest = async (request, usageHold) => {
205
222
  debugLog(`[SellerHandler] Received request: ${request.method} ${request.path} (reqId=${request.requestId.slice(0, 8)})`);
206
223
  // Response auth signs the request as the buyer sent it, so keep its headers before removing seller-only ones.
207
224
  const wireHeaders = { ...request.headers };
208
- const wireBody = request.body;
225
+ let wireBody = request.body;
209
226
  // Delegations are for this seller only: no route may pass them on to a provider or prover.
210
227
  const delegationsHeader = takeHeader(request.headers, FREE_TIER_DELEGATIONS_HEADER);
211
228
  // Handle /v1/models locally — free metadata endpoint, no payment required.
@@ -217,6 +234,12 @@ export class SellerRequestHandler {
217
234
  mux.sendProxyResponse(modelsResponse);
218
235
  return;
219
236
  }
237
+ if (this._deps.isBuyerBlocked?.(buyerPeerId)) {
238
+ debugLog(`[SellerHandler] Refusing blocked buyer ${buyerPeerId.slice(0, 12)}... (reqId=${request.requestId.slice(0, 8)})`);
239
+ this._deps.emit('request:blocked', { buyerPeerId, requestId: request.requestId, path: pathOnly });
240
+ this._sendJsonError(mux, request.requestId, 403, 'buyer_blocked', 'This seller does not serve your requests.');
241
+ return;
242
+ }
220
243
  const routingRequest = routingRequestOf(request.method, request.path);
221
244
  if (routingRequest?.action === 'catalog') {
222
245
  mux.sendProxyResponse(await this._handleRoutingCatalog(request, buyerPeerId, routingRequest.protocol));
@@ -418,17 +441,19 @@ export class SellerRequestHandler {
418
441
  let coveredByAllowance = false;
419
442
  if (!isFreeService && !videoRoute && freeTierLimiter?.appliesTo(freeTierService, { paid: true })) {
420
443
  try {
421
- const standing = await freeTierLimiter.resolveStanding(buyerPeerId, delegationsHeader ?? '');
422
- const decision = freeTierLimiter.consume({
423
- buyerPeerId,
424
- service: freeTierService,
425
- remoteIp: conn.remoteAddress ?? null,
426
- standing,
427
- paid: true,
444
+ const outcome = await this._screenAndConsumeFreeTier(freeTierLimiter, {
445
+ buyerPeerId, service: freeTierService, delegationsHeader, body: request.body, remoteAddress: conn.remoteAddress, paid: true,
428
446
  });
429
- coveredByAllowance = decision.allowed;
430
- debugLog(`[SellerHandler] Free allowance ${coveredByAllowance ? 'covers' : `does not cover (limitedBy=${decision.limitedBy})`} ` +
431
- `${freeTierService} for ${decision.buyerAddress}`);
447
+ if (outcome.kind === 'refused') {
448
+ // A request screening refuses is paid as usual and leaves the allowance untouched.
449
+ debugLog(`[SellerHandler] Free allowance does not cover ${freeTierService} for ${buyerPeerId.slice(0, 12)}...: screened out`);
450
+ }
451
+ else {
452
+ const { decision } = outcome;
453
+ coveredByAllowance = decision.allowed;
454
+ debugLog(`[SellerHandler] Free allowance ${coveredByAllowance ? 'covers' : `does not cover (limitedBy=${decision.limitedBy})`} ` +
455
+ `${freeTierService} for ${decision.buyerAddress}`);
456
+ }
432
457
  }
433
458
  catch (err) {
434
459
  // Failing to account leaves the request paid: it can only cost the buyer the listed price.
@@ -437,15 +462,10 @@ export class SellerRequestHandler {
437
462
  }
438
463
  const isServedFree = isFreeService || coveredByAllowance;
439
464
  if (isFreeTierRequest && freeTierLimiter?.appliesTo(freeTierService)) {
440
- let decision;
465
+ let outcome;
441
466
  try {
442
- // No header means the buyer has no codes any more: '' forgets the remembered ones.
443
- const standing = await freeTierLimiter.resolveStanding(buyerPeerId, delegationsHeader ?? '');
444
- decision = freeTierLimiter.consume({
445
- buyerPeerId,
446
- service: freeTierService,
447
- remoteIp: conn.remoteAddress ?? null,
448
- standing,
467
+ outcome = await this._screenAndConsumeFreeTier(freeTierLimiter, {
468
+ buyerPeerId, service: freeTierService, delegationsHeader, body: request.body, remoteAddress: conn.remoteAddress, paid: false,
449
469
  });
450
470
  }
451
471
  catch (err) {
@@ -465,6 +485,17 @@ export class SellerRequestHandler {
465
485
  });
466
486
  return;
467
487
  }
488
+ if (outcome.kind === 'refused') {
489
+ const { refusal } = outcome;
490
+ const message = refusal.reason === 'new_buyer_context'
491
+ ? `This seller serves a new buyer's first ${refusal.requests} free requests up to ${refusal.maxInputTokens} input tokens; `
492
+ + `this one has about ${refusal.inputTokens}. Start with a shorter conversation, or use a paid model.`
493
+ : 'This conversation was started from another buyer identity, so this seller does not serve it free here. '
494
+ + 'Continue it from that identity, or use a paid model.';
495
+ this._sendJsonError(mux, request.requestId, 403, refusal.reason === 'new_buyer_context' ? 'free_tier_new_buyer_context' : 'free_tier_moved_conversation', message);
496
+ return;
497
+ }
498
+ const { decision } = outcome;
468
499
  if (!decision.allowed) {
469
500
  const limitedBy = decision.limitedBy ?? 'address';
470
501
  const program = decision.program;
@@ -851,8 +882,24 @@ export class SellerRequestHandler {
851
882
  }
852
883
  return;
853
884
  }
885
+ // The connection ended or the session was dropped while this request
886
+ // waited: don't start work that cannot reach the buyer or be billed.
887
+ const connectionEnded = conn.state === ConnectionState.Closed || conn.state === ConnectionState.Failed;
888
+ if (spmAuthorized && (connectionEnded || !spm.hasSession(buyerPeerId))) {
889
+ sendSessionExpired('the admission checks');
890
+ return;
891
+ }
854
892
  }
855
893
  }
894
+ const buyerSupportsResponseAuth = conn.hasRemoteCapability(CONNECTION_CAPABILITY_RESPONSE_AUTH_V1);
895
+ // When the provider is handed a body the seller wrote, the buyer's is only needed for the hash
896
+ // response auth signs: it is hashed here, so both bodies are not held while the request is served.
897
+ let wireRequestHash;
898
+ if (wireBody !== request.body) {
899
+ if (buyerSupportsResponseAuth)
900
+ wireRequestHash = hashRequest({ ...request, headers: wireHeaders, body: wireBody });
901
+ wireBody = new Uint8Array(0);
902
+ }
856
903
  const responseAuthRequest = {
857
904
  ...request,
858
905
  headers: wireHeaders,
@@ -888,8 +935,12 @@ export class SellerRequestHandler {
888
935
  let unitCostUsdc = 0n;
889
936
  // Hold the channel open for the whole billable span — provider call,
890
937
  // spend recording, and NeedAuth — so a buyer-requested close can't land
891
- // between serving the request and claiming its cost.
892
- const isBillable = !isServedFree && !oneOffChannelId && (spm?.hasSession(buyerPeerId) ?? false);
938
+ // between serving the request and claiming its cost. The channel is fixed
939
+ // here: a buyer that disconnects before the answer ends still owes for it.
940
+ const billedChannelId = !isServedFree && !oneOffChannelId && spm?.hasSession(buyerPeerId)
941
+ ? spm.getChannelByPeer(buyerPeerId)?.sessionId ?? null
942
+ : null;
943
+ const isBillable = billedChannelId !== null;
893
944
  if (isBillable && spm.hasClosingChannel(buyerPeerId)) {
894
945
  // A close takes seconds on-chain (a disconnect, an exhausted channel).
895
946
  // Let it finish, then ask for a new channel: the buyer opens one and
@@ -922,7 +973,12 @@ export class SellerRequestHandler {
922
973
  this.adjustProviderLoad(provider.name, 1);
923
974
  try {
924
975
  try {
925
- let response = await this._executeRequest(provider, request, {
976
+ // Token-priced services show the buyer the seller's own price in the body; a per-unit
977
+ // charge (images, video) is settled on delivery, so no estimate is shown for those. A request
978
+ // served free (a free service or the free allowance) costs the buyer nothing, and says so.
979
+ const sellerCost = unitBillingModel ? undefined
980
+ : isServedFree ? () => 0 : (usage) => tokenCostUsd(usage, requestPricing);
981
+ let response = await this._executeRequest(provider, request, sellerCost, {
926
982
  signal: isDownload ? mux.downloadSignal(request.requestId) : undefined,
927
983
  onResponseStart: (streamResponseStart) => {
928
984
  markFreeAllowance(streamResponseStart.headers, coveredByAllowance);
@@ -953,8 +1009,10 @@ export class SellerRequestHandler {
953
1009
  if (chunk.data.byteLength > 0)
954
1010
  streamTail = [...streamTail, ...chunk.data.subarray(-2)].slice(-2);
955
1011
  mux.sendProxyChunk(chunk);
1012
+ // A provider that awaits this stops reading its upstream while the buyer is behind.
1013
+ return mux.whenWritable();
956
1014
  },
957
- });
1015
+ }, isDownload);
958
1016
  if (!streamedResponseStarted) {
959
1017
  response = { ...response, headers: { ...response.headers } };
960
1018
  markFreeAllowance(response.headers, coveredByAllowance);
@@ -969,10 +1027,12 @@ export class SellerRequestHandler {
969
1027
  const upstreamBody = response.body ?? new Uint8Array(0);
970
1028
  const upstreamError = statusCode >= 400 ? new TextDecoder().decode(upstreamBody.slice(0, 2_000)) : '';
971
1029
  this._deps.emit('provider:response', { provider, service: requestedModel, statusCode, body: upstreamError, billable: videoRoute?.action !== 'retrieve' });
1030
+ const upstreamStatusCode = statusCode;
1031
+ let maskedAs = null;
972
1032
  if (!streamedResponseStarted && isUpstreamAccountError(statusCode, upstreamError)) {
973
- debugWarn(`[SellerHandler] Upstream account error: status=${statusCode} provider="${provider.name}" model="${requestedModel}" body=${upstreamError.slice(0, 200)}`);
974
1033
  response = buildUpstreamUnavailableResponse(request.requestId, requestedModel);
975
1034
  statusCode = response.statusCode;
1035
+ maskedAs = 'account';
976
1036
  }
977
1037
  else if (!streamedResponseStarted && statusCode === 429) {
978
1038
  response = buildUpstreamRateLimitedResponse(request.requestId, requestedModel, takeHeader({ ...response.headers }, 'retry-after'));
@@ -981,6 +1041,14 @@ export class SellerRequestHandler {
981
1041
  if (!streamedResponseStarted && isServiceHealthFailing(health) && isUpstreamFailureStatus(statusCode)) {
982
1042
  response = buildSelfHealthErrorResponse(request.requestId, requestedModel, health, response);
983
1043
  statusCode = response.statusCode;
1044
+ maskedAs ??= 'self-health';
1045
+ }
1046
+ if (maskedAs) {
1047
+ // The buyer gets a generic 503; the seller's log keeps what the upstream said.
1048
+ this._deps.emit('provider:error-masked', {
1049
+ provider: provider.name, service: requestedModel, reason: maskedAs, statusCode,
1050
+ upstreamStatusCode, detail: describeUpstreamError(upstreamStatusCode, upstreamError),
1051
+ });
984
1052
  }
985
1053
  responseBody = response.body ?? new Uint8Array(0);
986
1054
  responseForAuth = response;
@@ -1119,11 +1187,13 @@ export class SellerRequestHandler {
1119
1187
  }
1120
1188
  // Record spend and send NeedAuth with cost data after every request.
1121
1189
  // The buyer validates the cost independently and responds with SpendingAuth.
1122
- if (!isServedFree && !oneOffChannelId && spm?.hasSession(buyerPeerId)) {
1190
+ if (spm && isBillable) {
1123
1191
  const usage = responseUsage;
1124
1192
  const tokenCostUsdc = computeCostUsdc(usage.freshInputTokens, usage.outputTokens, requestPricing, usage.cachedInputTokens);
1125
1193
  const costUsdc = tokenCostUsdc + unitCostUsdc;
1126
- const session = spm.getChannelByPeer(buyerPeerId);
1194
+ // Only the channel that admitted this request, never one that replaced it.
1195
+ const current = spm.getChannelByPeer(buyerPeerId);
1196
+ const session = current?.sessionId === billedChannelId ? current : null;
1127
1197
  if (session && spm.connectionsClosed) {
1128
1198
  // The node is stopping and its connections are closed: this
1129
1199
  // response never reached the buyer, so it is not billed.
@@ -1164,7 +1234,6 @@ export class SellerRequestHandler {
1164
1234
  this._chargeDeliveredVideo(videoRoute, responseForAuth, buyerPeerId, paymentMux, request.requestId);
1165
1235
  this._closeFailedVideoJob(videoRoute, responseForAuth, buyerPeerId);
1166
1236
  }
1167
- const buyerSupportsResponseAuth = conn.hasRemoteCapability(CONNECTION_CAPABILITY_RESPONSE_AUTH_V1);
1168
1237
  if (responseForAuth && buyerSupportsResponseAuth) {
1169
1238
  const channelId = oneOffChannelId ?? spm?.getChannelByPeer(buyerPeerId)?.sessionId ?? null;
1170
1239
  this._sendResponseAuthBestEffort(verificationMux, responseAuthRequest, responseForAuth, {
@@ -1174,6 +1243,7 @@ export class SellerRequestHandler {
1174
1243
  responseStartedAt,
1175
1244
  responseCompletedAt: Date.now(),
1176
1245
  channelId,
1246
+ requestHash: wireRequestHash,
1177
1247
  });
1178
1248
  }
1179
1249
  }
@@ -1187,12 +1257,19 @@ export class SellerRequestHandler {
1187
1257
  }
1188
1258
  };
1189
1259
  mux.onProxyRequest(async (request) => {
1260
+ // The body stays in memory until the response is sent, so it counts until then.
1261
+ const bodyBytes = request.body.length;
1262
+ if (!this._inFlightRequestBytes.tryReserve(bodyBytes)) {
1263
+ this._sendJsonError(mux, request.requestId, 503, 'seller_busy', 'Seller is at its limit for request bytes in flight; retry shortly', { 'retry-after': '1' });
1264
+ return;
1265
+ }
1190
1266
  const usageHold = { reservation: null, estimate: 0, tokens: 0 };
1191
1267
  try {
1192
1268
  await handleProxyRequest(request, usageHold);
1193
1269
  }
1194
1270
  finally {
1195
1271
  usageHold.reservation?.finish(usageHold.tokens);
1272
+ this._inFlightRequestBytes.release(bodyBytes);
1196
1273
  }
1197
1274
  });
1198
1275
  return { mux };
@@ -1365,6 +1442,44 @@ export class SellerRequestHandler {
1365
1442
  this._usageMissingReported.add(key);
1366
1443
  this._deps.emit('provider:usage-missing', { provider, service });
1367
1444
  }
1445
+ /**
1446
+ * Resolve the buyer's staked standing, screen a free request, and count it
1447
+ * unless screening refused it. An admitted request is recorded for
1448
+ * conversation matching.
1449
+ */
1450
+ async _screenAndConsumeFreeTier(limiter, input) {
1451
+ const { buyerPeerId, service } = input;
1452
+ // No header means the buyer has no codes any more: '' forgets the remembered ones.
1453
+ const standing = await limiter.resolveStanding(buyerPeerId, input.delegationsHeader ?? '');
1454
+ // Token estimation and parsing happen only when a check needs them.
1455
+ const screen = limiter.screen({
1456
+ buyerPeerId,
1457
+ service,
1458
+ standing,
1459
+ paid: input.paid,
1460
+ inputTokens: () => estimateTokensFromBytesSampled(input.body),
1461
+ body: () => tryParseJsonObject(input.body),
1462
+ });
1463
+ const ip = input.remoteAddress ?? 'unknown';
1464
+ if (screen.refusal) {
1465
+ debugLog(`[SellerHandler] Free tier refused ${service} for ${buyerPeerId.slice(0, 12)}... ip=${ip}: ${describeFreeTierScreenRefusal(screen.refusal)}`);
1466
+ }
1467
+ else if (screen.wouldRefuse) {
1468
+ debugLog(`[SellerHandler] Free tier would refuse ${service} for ${buyerPeerId.slice(0, 12)}... ip=${ip} (log only): ${describeFreeTierScreenRefusal(screen.wouldRefuse)}`);
1469
+ }
1470
+ if (screen.refusal)
1471
+ return { kind: 'refused', refusal: screen.refusal };
1472
+ const decision = limiter.consume({
1473
+ buyerPeerId,
1474
+ service,
1475
+ remoteIp: input.remoteAddress ?? null,
1476
+ standing,
1477
+ ...(input.paid ? { paid: true } : {}),
1478
+ });
1479
+ if (decision.allowed)
1480
+ screen.served();
1481
+ return { kind: 'counted', decision };
1482
+ }
1368
1483
  _sendJsonError(mux, requestId, statusCode, code, message, extraHeaders = {}) {
1369
1484
  mux.sendProxyResponse({
1370
1485
  requestId,
@@ -1392,7 +1507,7 @@ export class SellerRequestHandler {
1392
1507
  setTrustedHeader(request.headers, 'x-antseed-buyer-peer-id', buyerPeerId);
1393
1508
  try {
1394
1509
  const response = await provider.handleRequest(request);
1395
- return { ...response, requestId: request.requestId, headers: buyerFacingResponseHeaders(response.headers) };
1510
+ return { ...response, requestId: request.requestId, headers: exposedResponseHeaders(response.headers) };
1396
1511
  }
1397
1512
  catch (error) {
1398
1513
  return failure(503, 'unavailable', `Routing catalog failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -1629,15 +1744,11 @@ export class SellerRequestHandler {
1629
1744
  if (isZeroTokenPricing(pricing)) {
1630
1745
  return { cost: 0n, inputTokens: 0, maxOutputTokens: 0 };
1631
1746
  }
1632
- if (!this._isJsonRequest(request)) {
1633
- return null;
1634
- }
1635
- const body = tryParseJsonObject(request.body);
1636
- if (!body) {
1747
+ const maxOutputTokens = this._requestedMaxOutputTokens(request);
1748
+ if (maxOutputTokens === null) {
1637
1749
  return null;
1638
1750
  }
1639
1751
  const inputTokens = estimateTokensFromBytesSampled(request.body);
1640
- const maxOutputTokens = this._extractMaxOutputTokens(body);
1641
1752
  return {
1642
1753
  cost: computeCostUsdc(inputTokens, maxOutputTokens, pricing),
1643
1754
  inputTokens,
@@ -1654,45 +1765,45 @@ export class SellerRequestHandler {
1654
1765
  if (costEstimate && costEstimate.inputTokens > 0) {
1655
1766
  return costEstimate.inputTokens + (costEstimate.maxOutputTokens || DEFAULT_OUTPUT_RESERVATION_TOKENS);
1656
1767
  }
1657
- const body = this._isJsonRequest(request) ? tryParseJsonObject(request.body) : null;
1658
- return estimateTokensFromBytesSampled(request.body) + ((body && this._extractMaxOutputTokens(body)) || DEFAULT_OUTPUT_RESERVATION_TOKENS);
1659
- }
1660
- _extractMaxOutputTokens(body) {
1661
- const candidates = [
1662
- body["max_tokens"],
1663
- body["max_completion_tokens"],
1664
- body["max_output_tokens"],
1665
- body["maxTokens"],
1666
- body["maxCompletionTokens"],
1667
- body["maxOutputTokens"],
1668
- ];
1669
- for (const value of candidates) {
1670
- const parsed = this._parsePositiveInteger(value);
1671
- if (parsed !== null)
1672
- return parsed;
1673
- }
1674
- return 0;
1768
+ return estimateTokensFromBytesSampled(request.body) + (this._requestedMaxOutputTokens(request) || DEFAULT_OUTPUT_RESERVATION_TOKENS);
1675
1769
  }
1676
- _parsePositiveInteger(value) {
1677
- let numeric;
1678
- if (typeof value === 'number') {
1679
- numeric = value;
1680
- }
1681
- else if (typeof value === 'string') {
1682
- numeric = Number(value);
1683
- }
1684
- else {
1685
- return null;
1686
- }
1687
- if (!Number.isFinite(numeric) || numeric <= 0)
1770
+ /**
1771
+ * The most output tokens a JSON request asks for (0 when it names no limit), or null when its body
1772
+ * is not a JSON object. A body the seller wrote was read for this as it was written; any other is
1773
+ * parsed here.
1774
+ */
1775
+ _requestedMaxOutputTokens(request) {
1776
+ if (!this._isJsonRequest(request))
1688
1777
  return null;
1689
- return Math.floor(numeric);
1778
+ const billed = this._requestedServices.get(request);
1779
+ if (billed && billed.service !== null && billed.body === request.body && billed.maxOutputTokens !== undefined)
1780
+ return billed.maxOutputTokens;
1781
+ const body = tryParseJsonObject(request.body);
1782
+ return body ? requestedMaxOutputTokens(body) : null;
1690
1783
  }
1691
- async _executeRequest(provider, request, streamCallbacks) {
1692
- // Buyers only ever see the headers buyerFacingResponseHeaders lets through.
1784
+ async _executeRequest(provider, request, sellerCost, streamCallbacks, isDownload = false) {
1785
+ // Every provider's response goes through here, so no plugin can expose its
1786
+ // upstream's own headers or costs: the body's cost is the seller's price.
1787
+ const withHeaders = (response) => ({ ...response, headers: exposedResponseHeaders(response.headers) });
1788
+ // A video download (a retrieval the router recognized, not just the buyer's header)
1789
+ // is the provider's own bytes, hashed as they pass; it carries no usage.
1693
1790
  if (streamCallbacks && provider.handleRequestStream) {
1694
- // A streamed 429 is held back like a buffered one, so its upstream body can be replaced before the buyer sees it.
1791
+ // An event stream is rewritten as it passes. A JSON body can only be rewritten
1792
+ // whole, so it is held back and sent as the returned response instead.
1793
+ let mode = 'passthrough';
1794
+ let events = null;
1795
+ // A streamed 429 is held back so its upstream body can be replaced before the buyer sees it.
1695
1796
  let heldRateLimit = false;
1797
+ const sent = [];
1798
+ // A provider that fails mid-stream leaves its last line or event held here: it is sent
1799
+ // (rewritten) before the failure, so the buyer has every byte and the error frame follows them.
1800
+ const sendHeld = () => {
1801
+ const rest = events?.flush();
1802
+ if (!rest?.length)
1803
+ return;
1804
+ sent.push(rest);
1805
+ streamCallbacks.onResponseChunk({ requestId: request.requestId, data: rest, done: false });
1806
+ };
1696
1807
  const response = await provider.handleRequestStream(request, {
1697
1808
  ...streamCallbacks,
1698
1809
  onResponseStart: (start) => {
@@ -1700,14 +1811,47 @@ export class SellerRequestHandler {
1700
1811
  heldRateLimit = true;
1701
1812
  return;
1702
1813
  }
1703
- streamCallbacks.onResponseStart({ ...start, headers: buyerFacingResponseHeaders(start.headers) });
1814
+ if (isDownload)
1815
+ return streamCallbacks.onResponseStart(withHeaders(start));
1816
+ if (contentTypeOf(start.headers).includes('json')) {
1817
+ mode = 'held';
1818
+ return;
1819
+ }
1820
+ if (!isEventStream(request, start))
1821
+ return streamCallbacks.onResponseStart(withHeaders(start));
1822
+ mode = 'events';
1823
+ events = new ExposedSseStream(sellerCost);
1824
+ const body = start.body?.length ? events.push(start.body) : start.body;
1825
+ if (body?.length)
1826
+ sent.push(body);
1827
+ streamCallbacks.onResponseStart({ ...withHeaders(start), body });
1704
1828
  },
1705
- onResponseChunk: (chunk) => (heldRateLimit ? undefined : streamCallbacks.onResponseChunk(chunk)),
1829
+ onResponseChunk: (chunk) => {
1830
+ if (heldRateLimit || mode === 'held')
1831
+ return;
1832
+ if (!events)
1833
+ return streamCallbacks.onResponseChunk(chunk);
1834
+ const data = chunk.done ? concatBytes([events.push(chunk.data), events.flush()]) : events.push(chunk.data);
1835
+ sent.push(data);
1836
+ if (!chunk.done && data.length === 0)
1837
+ return;
1838
+ return streamCallbacks.onResponseChunk({ ...chunk, data });
1839
+ },
1840
+ }).catch((err) => {
1841
+ sendHeld();
1842
+ throw err;
1706
1843
  });
1707
- return { ...response, headers: buyerFacingResponseHeaders(response.headers) };
1844
+ // The returned body is what the buyer was sent, so usage and payment read the same bytes.
1845
+ if (events)
1846
+ return { ...withHeaders(response), body: concatBytes(sent) };
1847
+ if (isDownload)
1848
+ return withHeaders(response);
1849
+ // Held JSON goes out as one complete response, which a streaming marker would leave the buyer waiting on.
1850
+ const whole = mode === 'held' || heldRateLimit ? withoutStreamingMarker(response) : response;
1851
+ return withExposedBody(request, withHeaders(whole), sellerCost);
1708
1852
  }
1709
- const response = await provider.handleRequest(request);
1710
- return { ...response, headers: buyerFacingResponseHeaders(response.headers) };
1853
+ const response = withHeaders(await provider.handleRequest(request));
1854
+ return isDownload ? response : withExposedBody(request, response, sellerCost);
1711
1855
  }
1712
1856
  _sendNeedAuthBestEffort(paymentMux, payload, buyerPeerId, phase) {
1713
1857
  try {
@@ -1747,6 +1891,7 @@ export class SellerRequestHandler {
1747
1891
  try {
1748
1892
  const payload = createResponseAuthPayload({
1749
1893
  request,
1894
+ ...(context.requestHash ? { requestHash: context.requestHash } : {}),
1750
1895
  response,
1751
1896
  buyerPeerId: context.buyerPeerId,
1752
1897
  sellerPeerId: this._deps.identity.peerId,
@@ -1763,4 +1908,58 @@ export class SellerRequestHandler {
1763
1908
  }
1764
1909
  }
1765
1910
  }
1911
+ function contentTypeOf(headers) {
1912
+ return headerOf(headers, 'content-type').toLowerCase();
1913
+ }
1914
+ /**
1915
+ * Whether a response is a server-sent event stream: its content type says so,
1916
+ * or it is a successful response without one that its provider marked as
1917
+ * streaming (HttpRelay streams a typeless response to a request it sent
1918
+ * accepting events) or whose request accepts events.
1919
+ */
1920
+ function isEventStream(request, response) {
1921
+ const contentType = contentTypeOf(response.headers);
1922
+ if (contentType)
1923
+ return contentType.includes('text/event-stream');
1924
+ if (response.statusCode < 200 || response.statusCode >= 300)
1925
+ return false;
1926
+ return headerOf(response.headers, ANTSEED_STREAMING_RESPONSE_HEADER) === '1'
1927
+ || headerOf(request.headers, 'accept').toLowerCase().includes('text/event-stream');
1928
+ }
1929
+ function withoutStreamingMarker(response) {
1930
+ const headers = Object.fromEntries(Object.entries(response.headers).filter(([name]) => name.toLowerCase() !== ANTSEED_STREAMING_RESPONSE_HEADER));
1931
+ return { ...response, headers };
1932
+ }
1933
+ function headerOf(headers, name) {
1934
+ return Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1] ?? '';
1935
+ }
1936
+ /** A whole JSON or event-stream response priced at the seller's own cost, without the upstream's. */
1937
+ function withExposedBody(request, response, sellerCost) {
1938
+ if (!response.body?.length)
1939
+ return response;
1940
+ if (isEventStream(request, response)) {
1941
+ const events = new ExposedSseStream(sellerCost);
1942
+ return { ...response, body: concatBytes([events.push(response.body), events.flush()]) };
1943
+ }
1944
+ if (!contentTypeOf(response.headers).includes('json'))
1945
+ return response;
1946
+ const body = exposedJsonBody(response.body, sellerCost);
1947
+ return body === response.body ? response : { ...response, body };
1948
+ }
1949
+ function concatBytes(parts) {
1950
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
1951
+ let offset = 0;
1952
+ for (const part of parts) {
1953
+ out.set(part, offset);
1954
+ offset += part.byteLength;
1955
+ }
1956
+ return out;
1957
+ }
1958
+ /** What the seller charges for these tokens, in USD: `computeCostUsdc` before rounding to USDC units. */
1959
+ function tokenCostUsd(usage, pricing) {
1960
+ const cachedPrice = pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion;
1961
+ return (usage.freshInputTokens * pricing.inputUsdPerMillion
1962
+ + usage.cachedInputTokens * cachedPrice
1963
+ + usage.outputTokens * pricing.outputUsdPerMillion) / 1_000_000;
1964
+ }
1766
1965
  //# sourceMappingURL=seller-request-handler.js.map