@antseed/node 0.2.182 → 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.
- package/README.md +2 -0
- package/dist/buyer-identity-context.d.ts.map +1 -1
- package/dist/buyer-identity-context.js +2 -2
- package/dist/buyer-identity-context.js.map +1 -1
- package/dist/discovery/announcer.d.ts.map +1 -1
- package/dist/discovery/dht-health.d.ts.map +1 -1
- package/dist/discovery/dht-health.js.map +1 -1
- package/dist/discovery/dht-node.d.ts.map +1 -1
- package/dist/discovery/dht-node.js.map +1 -1
- package/dist/discovery/http-metadata-resolver.d.ts.map +1 -1
- package/dist/discovery/metadata/wire.d.ts.map +1 -1
- package/dist/discovery/metadata/wire.js.map +1 -1
- package/dist/discovery/metadata-server.d.ts.map +1 -1
- package/dist/discovery/peer-lookup.d.ts.map +1 -1
- package/dist/discovery/service-catalog.js.map +1 -1
- package/dist/health/gas-auto-refuel.d.ts.map +1 -1
- package/dist/health/gas-auto-refuel.js.map +1 -1
- package/dist/health/gas-health-monitor.d.ts.map +1 -1
- package/dist/health/model-health-checker.d.ts.map +1 -1
- package/dist/health/model-health-checker.js.map +1 -1
- package/dist/health/self-health-error.d.ts +6 -0
- package/dist/health/self-health-error.d.ts.map +1 -1
- package/dist/health/self-health-error.js +33 -0
- package/dist/health/self-health-error.js.map +1 -1
- package/dist/health/service-performance.d.ts.map +1 -1
- package/dist/health/service-performance.js.map +1 -1
- package/dist/health/stream-outcome.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/metering/receipt-generator.d.ts.map +1 -1
- package/dist/metering/receipt-verifier.d.ts.map +1 -1
- package/dist/metering/seller-session-tracker.d.ts.map +1 -1
- package/dist/metering/session-tracker.d.ts.map +1 -1
- package/dist/metering/storage.d.ts +6 -0
- package/dist/metering/storage.d.ts.map +1 -1
- package/dist/metering/storage.js +8 -0
- package/dist/metering/storage.js.map +1 -1
- package/dist/metering/usage-aggregator.d.ts.map +1 -1
- package/dist/metering/usage-aggregator.js.map +1 -1
- package/dist/node.d.ts +21 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +33 -16
- package/dist/node.js.map +1 -1
- package/dist/p2p/connection-auth.d.ts.map +1 -1
- package/dist/p2p/connection-auth.js.map +1 -1
- package/dist/p2p/connection-manager.d.ts +26 -0
- package/dist/p2p/connection-manager.d.ts.map +1 -1
- package/dist/p2p/connection-manager.js +88 -6
- package/dist/p2p/connection-manager.js.map +1 -1
- package/dist/p2p/identity-envelope.js.map +1 -1
- package/dist/p2p/identity.d.ts.map +1 -1
- package/dist/p2p/identity.js.map +1 -1
- package/dist/p2p/inbound-idle-tracker.d.ts +13 -5
- package/dist/p2p/inbound-idle-tracker.d.ts.map +1 -1
- package/dist/p2p/inbound-idle-tracker.js +11 -4
- package/dist/p2p/inbound-idle-tracker.js.map +1 -1
- package/dist/p2p/keepalive.d.ts.map +1 -1
- package/dist/p2p/nat-traversal.d.ts.map +1 -1
- package/dist/p2p/secure-channel.d.ts.map +1 -1
- package/dist/p2p/secure-channel.js.map +1 -1
- package/dist/p2p/sweep-mux.d.ts.map +1 -1
- package/dist/payments/balance-manager.d.ts.map +1 -1
- package/dist/payments/channel-store.d.ts +2 -0
- package/dist/payments/channel-store.d.ts.map +1 -1
- package/dist/payments/channel-store.js +9 -0
- package/dist/payments/channel-store.js.map +1 -1
- package/dist/payments/contract-stack.d.ts.map +1 -1
- package/dist/payments/contract-stack.js.map +1 -1
- package/dist/payments/deposit-relayer.d.ts.map +1 -1
- package/dist/payments/evm/ants-token-client.d.ts.map +1 -1
- package/dist/payments/evm/block-range.js.map +1 -1
- package/dist/payments/evm/deposit-relay-client.d.ts.map +1 -1
- package/dist/payments/evm/emissions-client.d.ts.map +1 -1
- package/dist/payments/evm/emissions-gate-client.d.ts +10 -10
- package/dist/payments/evm/emissions-gate-client.d.ts.map +1 -1
- package/dist/payments/evm/free-usage-client.d.ts.map +1 -1
- package/dist/payments/evm/identity-client.d.ts.map +1 -1
- package/dist/payments/evm/multicall.js.map +1 -1
- package/dist/payments/evm/points-policy-registry-client.d.ts.map +1 -1
- package/dist/payments/evm/position-init-client.d.ts.map +1 -1
- package/dist/payments/evm/registry-client.d.ts.map +1 -1
- package/dist/payments/evm/seller-pools-client.d.ts.map +1 -1
- package/dist/payments/evm/seller-pools-rewards-client.d.ts.map +1 -1
- package/dist/payments/evm/seller-registry-client.d.ts.map +1 -1
- package/dist/payments/evm/seller-registry-client.js.map +1 -1
- package/dist/payments/evm/seller-rewards-pool-client.d.ts.map +1 -1
- package/dist/payments/evm/staking-client.d.ts.map +1 -1
- package/dist/payments/evm/stats-client.d.ts.map +1 -1
- package/dist/payments/evm/trust-signals-client.d.ts.map +1 -1
- package/dist/payments/evm/trust-signals-client.js.map +1 -1
- package/dist/payments/evm/usage-accounting-client.d.ts.map +1 -1
- package/dist/payments/evm/usage-rewards-client.d.ts.map +1 -1
- package/dist/payments/evm/usdc-eth-swap-client.d.ts.map +1 -1
- package/dist/payments/evm/verification-signals-client.d.ts.map +1 -1
- package/dist/payments/evm/verification-signals-client.js.map +1 -1
- package/dist/payments/evm/verifier-client.d.ts +2 -2
- package/dist/payments/evm/verifier-client.d.ts.map +1 -1
- package/dist/payments/evm/verifier-client.js.map +1 -1
- package/dist/payments/evm/wash-trading-registry-client.d.ts.map +1 -1
- package/dist/payments/evm/wash-trading-registry-client.js.map +1 -1
- package/dist/payments/free-tier-conversations.d.ts +59 -0
- package/dist/payments/free-tier-conversations.d.ts.map +1 -0
- package/dist/payments/free-tier-conversations.js +127 -0
- package/dist/payments/free-tier-conversations.js.map +1 -0
- package/dist/payments/free-tier-program.js.map +1 -1
- package/dist/payments/free-tier-stake-resolver.d.ts.map +1 -1
- package/dist/payments/free-tier-stake-resolver.js.map +1 -1
- package/dist/payments/generated-contract-addresses.d.ts +33 -33
- package/dist/payments/generated-contract-addresses.d.ts.map +1 -1
- package/dist/payments/index.d.ts +2 -2
- package/dist/payments/index.d.ts.map +1 -1
- package/dist/payments/index.js +1 -1
- package/dist/payments/index.js.map +1 -1
- package/dist/payments/reward-claims.js.map +1 -1
- package/dist/payments/rpc-health.d.ts.map +1 -1
- package/dist/payments/seller-buyer-limiter.d.ts.map +1 -1
- package/dist/payments/seller-buyer-limiter.js.map +1 -1
- package/dist/payments/seller-free-tier-limiter.d.ts +54 -0
- package/dist/payments/seller-free-tier-limiter.d.ts.map +1 -1
- package/dist/payments/seller-free-tier-limiter.js +89 -2
- package/dist/payments/seller-free-tier-limiter.js.map +1 -1
- package/dist/payments/seller-free-usage-manager.d.ts.map +1 -1
- package/dist/payments/seller-free-usage-manager.js.map +1 -1
- package/dist/payments/seller-payment-manager.d.ts +27 -2
- package/dist/payments/seller-payment-manager.d.ts.map +1 -1
- package/dist/payments/seller-payment-manager.js +140 -39
- package/dist/payments/seller-payment-manager.js.map +1 -1
- package/dist/reputation/identity-history.d.ts.map +1 -1
- package/dist/reputation/identity-history.js.map +1 -1
- package/dist/reputation/model-reputation.js.map +1 -1
- package/dist/reputation/public-json.js.map +1 -1
- package/dist/reputation/rating-manager.d.ts.map +1 -1
- package/dist/reputation/report-manager.d.ts.map +1 -1
- package/dist/reputation/sybil-risk.js.map +1 -1
- package/dist/reputation/trust-score.d.ts.map +1 -1
- package/dist/reputation/uptime-tracker.d.ts.map +1 -1
- package/dist/requested-service.d.ts +4 -0
- package/dist/requested-service.d.ts.map +1 -1
- package/dist/requested-service.js +19 -1
- package/dist/requested-service.js.map +1 -1
- package/dist/resources/resource-ownership-store.d.ts.map +1 -1
- package/dist/resources/resource-ownership-store.js.map +1 -1
- package/dist/routing/default-router.d.ts.map +1 -1
- package/dist/routing/model-route-ranking.js.map +1 -1
- package/dist/routing/seller-health.d.ts.map +1 -1
- package/dist/routing/seller-health.js.map +1 -1
- package/dist/seller-request-handler.d.ts +24 -2
- package/dist/seller-request-handler.d.ts.map +1 -1
- package/dist/seller-request-handler.js +154 -66
- package/dist/seller-request-handler.js.map +1 -1
- package/dist/utils/file-lock.js.map +1 -1
- package/dist/utils/response-body.d.ts.map +1 -1
- package/dist/utils/response-body.js.map +1 -1
- package/dist/verification/samples.d.ts.map +1 -1
- package/dist/verification/samples.js.map +1 -1
- package/dist/verification/storage.d.ts.map +1 -1
- package/dist/verification/tee-status.d.ts +1 -1
- package/dist/verification/tee-status.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1,17 +1,23 @@
|
|
|
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
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';
|
|
14
|
-
import { createResponseAuthPayload, createStreamingResponseHash } from './verification/response-auth.js';
|
|
20
|
+
import { createResponseAuthPayload, createStreamingResponseHash, hashRequest } from './verification/response-auth.js';
|
|
15
21
|
import { ANTSEED_STREAMING_RESPONSE_HEADER, VIDEO_DOWNLOAD_STREAM_HEADER, VIDEO_DOWNLOAD_STREAM_VERSION } from '@antseed/protocol/http';
|
|
16
22
|
import { isServiceHealthFailing, preferHealthyUpstream, serviceHealthOf } from '@antseed/protocol/peer-metadata';
|
|
17
23
|
import { hasJsonContentType, tryParseJsonObject } from './utils/json-codec.js';
|
|
@@ -26,8 +32,8 @@ import { exposedResponseHeaders } from './utils/response-headers.js';
|
|
|
26
32
|
import { ExposedSseStream, exposedJsonBody } from './utils/response-body.js';
|
|
27
33
|
import { usageForBilling } from '@antseed/buyer-core';
|
|
28
34
|
import { isCanonicalRequestPath } from './proxy/request-path.js';
|
|
29
|
-
import { SERVICE_REQUIRED, billedRequestBody } from './requested-service.js';
|
|
30
|
-
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';
|
|
31
37
|
import { StreamOutcome } from './health/stream-outcome.js';
|
|
32
38
|
import { routingProtocolForPath, routingProtocolOf, routingRequestOf, routingWireProtocol, ROUTING_PROTOCOLS } from '@antseed/protocol/routing';
|
|
33
39
|
/** A seller's services of one routing protocol. */
|
|
@@ -133,6 +139,12 @@ function takeHeader(headers, name) {
|
|
|
133
139
|
}
|
|
134
140
|
return value;
|
|
135
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;
|
|
136
148
|
/** Debounce interval for metadata refresh after load changes. */
|
|
137
149
|
const METADATA_REFRESH_DEBOUNCE_MS = 200;
|
|
138
150
|
/** Time to wait for a catch-up SpendingAuth before returning 402. */
|
|
@@ -169,8 +181,11 @@ export class SellerRequestHandler {
|
|
|
169
181
|
/** The provider and service pairs already reported as sending no usage figure; each is reported once. */
|
|
170
182
|
_usageMissingReported = new Set();
|
|
171
183
|
_metadataRefreshTimer = null;
|
|
184
|
+
/** Request bodies in memory on every connection: uploads still arriving and requests being served. */
|
|
185
|
+
_inFlightRequestBytes;
|
|
172
186
|
constructor(deps) {
|
|
173
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));
|
|
174
189
|
}
|
|
175
190
|
_allowAttest(buyerPeerId) {
|
|
176
191
|
const now = Date.now();
|
|
@@ -200,13 +215,14 @@ export class SellerRequestHandler {
|
|
|
200
215
|
handleConnection(conn, buyerPeerId, paymentMux, verificationMux) {
|
|
201
216
|
const mux = new ProxyMux(conn, {
|
|
202
217
|
maxUploadBodyBytes: this._deps.maxUploadBodyBytes,
|
|
218
|
+
sharedUploadBudget: this._inFlightRequestBytes,
|
|
203
219
|
});
|
|
204
220
|
/** A request's buyer-limit reservation, finished with the tokens it used however the request ends. */
|
|
205
221
|
const handleProxyRequest = async (request, usageHold) => {
|
|
206
222
|
debugLog(`[SellerHandler] Received request: ${request.method} ${request.path} (reqId=${request.requestId.slice(0, 8)})`);
|
|
207
223
|
// Response auth signs the request as the buyer sent it, so keep its headers before removing seller-only ones.
|
|
208
224
|
const wireHeaders = { ...request.headers };
|
|
209
|
-
|
|
225
|
+
let wireBody = request.body;
|
|
210
226
|
// Delegations are for this seller only: no route may pass them on to a provider or prover.
|
|
211
227
|
const delegationsHeader = takeHeader(request.headers, FREE_TIER_DELEGATIONS_HEADER);
|
|
212
228
|
// Handle /v1/models locally — free metadata endpoint, no payment required.
|
|
@@ -218,6 +234,12 @@ export class SellerRequestHandler {
|
|
|
218
234
|
mux.sendProxyResponse(modelsResponse);
|
|
219
235
|
return;
|
|
220
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
|
+
}
|
|
221
243
|
const routingRequest = routingRequestOf(request.method, request.path);
|
|
222
244
|
if (routingRequest?.action === 'catalog') {
|
|
223
245
|
mux.sendProxyResponse(await this._handleRoutingCatalog(request, buyerPeerId, routingRequest.protocol));
|
|
@@ -419,17 +441,19 @@ export class SellerRequestHandler {
|
|
|
419
441
|
let coveredByAllowance = false;
|
|
420
442
|
if (!isFreeService && !videoRoute && freeTierLimiter?.appliesTo(freeTierService, { paid: true })) {
|
|
421
443
|
try {
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
buyerPeerId,
|
|
425
|
-
service: freeTierService,
|
|
426
|
-
remoteIp: conn.remoteAddress ?? null,
|
|
427
|
-
standing,
|
|
428
|
-
paid: true,
|
|
444
|
+
const outcome = await this._screenAndConsumeFreeTier(freeTierLimiter, {
|
|
445
|
+
buyerPeerId, service: freeTierService, delegationsHeader, body: request.body, remoteAddress: conn.remoteAddress, paid: true,
|
|
429
446
|
});
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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
|
+
}
|
|
433
457
|
}
|
|
434
458
|
catch (err) {
|
|
435
459
|
// Failing to account leaves the request paid: it can only cost the buyer the listed price.
|
|
@@ -438,15 +462,10 @@ export class SellerRequestHandler {
|
|
|
438
462
|
}
|
|
439
463
|
const isServedFree = isFreeService || coveredByAllowance;
|
|
440
464
|
if (isFreeTierRequest && freeTierLimiter?.appliesTo(freeTierService)) {
|
|
441
|
-
let
|
|
465
|
+
let outcome;
|
|
442
466
|
try {
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
decision = freeTierLimiter.consume({
|
|
446
|
-
buyerPeerId,
|
|
447
|
-
service: freeTierService,
|
|
448
|
-
remoteIp: conn.remoteAddress ?? null,
|
|
449
|
-
standing,
|
|
467
|
+
outcome = await this._screenAndConsumeFreeTier(freeTierLimiter, {
|
|
468
|
+
buyerPeerId, service: freeTierService, delegationsHeader, body: request.body, remoteAddress: conn.remoteAddress, paid: false,
|
|
450
469
|
});
|
|
451
470
|
}
|
|
452
471
|
catch (err) {
|
|
@@ -466,6 +485,17 @@ export class SellerRequestHandler {
|
|
|
466
485
|
});
|
|
467
486
|
return;
|
|
468
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;
|
|
469
499
|
if (!decision.allowed) {
|
|
470
500
|
const limitedBy = decision.limitedBy ?? 'address';
|
|
471
501
|
const program = decision.program;
|
|
@@ -852,8 +882,24 @@ export class SellerRequestHandler {
|
|
|
852
882
|
}
|
|
853
883
|
return;
|
|
854
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
|
+
}
|
|
855
892
|
}
|
|
856
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
|
+
}
|
|
857
903
|
const responseAuthRequest = {
|
|
858
904
|
...request,
|
|
859
905
|
headers: wireHeaders,
|
|
@@ -889,8 +935,12 @@ export class SellerRequestHandler {
|
|
|
889
935
|
let unitCostUsdc = 0n;
|
|
890
936
|
// Hold the channel open for the whole billable span — provider call,
|
|
891
937
|
// spend recording, and NeedAuth — so a buyer-requested close can't land
|
|
892
|
-
// between serving the request and claiming its cost.
|
|
893
|
-
|
|
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;
|
|
894
944
|
if (isBillable && spm.hasClosingChannel(buyerPeerId)) {
|
|
895
945
|
// A close takes seconds on-chain (a disconnect, an exhausted channel).
|
|
896
946
|
// Let it finish, then ask for a new channel: the buyer opens one and
|
|
@@ -959,6 +1009,8 @@ export class SellerRequestHandler {
|
|
|
959
1009
|
if (chunk.data.byteLength > 0)
|
|
960
1010
|
streamTail = [...streamTail, ...chunk.data.subarray(-2)].slice(-2);
|
|
961
1011
|
mux.sendProxyChunk(chunk);
|
|
1012
|
+
// A provider that awaits this stops reading its upstream while the buyer is behind.
|
|
1013
|
+
return mux.whenWritable();
|
|
962
1014
|
},
|
|
963
1015
|
}, isDownload);
|
|
964
1016
|
if (!streamedResponseStarted) {
|
|
@@ -975,10 +1027,12 @@ export class SellerRequestHandler {
|
|
|
975
1027
|
const upstreamBody = response.body ?? new Uint8Array(0);
|
|
976
1028
|
const upstreamError = statusCode >= 400 ? new TextDecoder().decode(upstreamBody.slice(0, 2_000)) : '';
|
|
977
1029
|
this._deps.emit('provider:response', { provider, service: requestedModel, statusCode, body: upstreamError, billable: videoRoute?.action !== 'retrieve' });
|
|
1030
|
+
const upstreamStatusCode = statusCode;
|
|
1031
|
+
let maskedAs = null;
|
|
978
1032
|
if (!streamedResponseStarted && isUpstreamAccountError(statusCode, upstreamError)) {
|
|
979
|
-
debugWarn(`[SellerHandler] Upstream account error: status=${statusCode} provider="${provider.name}" model="${requestedModel}" body=${upstreamError.slice(0, 200)}`);
|
|
980
1033
|
response = buildUpstreamUnavailableResponse(request.requestId, requestedModel);
|
|
981
1034
|
statusCode = response.statusCode;
|
|
1035
|
+
maskedAs = 'account';
|
|
982
1036
|
}
|
|
983
1037
|
else if (!streamedResponseStarted && statusCode === 429) {
|
|
984
1038
|
response = buildUpstreamRateLimitedResponse(request.requestId, requestedModel, takeHeader({ ...response.headers }, 'retry-after'));
|
|
@@ -987,6 +1041,14 @@ export class SellerRequestHandler {
|
|
|
987
1041
|
if (!streamedResponseStarted && isServiceHealthFailing(health) && isUpstreamFailureStatus(statusCode)) {
|
|
988
1042
|
response = buildSelfHealthErrorResponse(request.requestId, requestedModel, health, response);
|
|
989
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
|
+
});
|
|
990
1052
|
}
|
|
991
1053
|
responseBody = response.body ?? new Uint8Array(0);
|
|
992
1054
|
responseForAuth = response;
|
|
@@ -1125,11 +1187,13 @@ export class SellerRequestHandler {
|
|
|
1125
1187
|
}
|
|
1126
1188
|
// Record spend and send NeedAuth with cost data after every request.
|
|
1127
1189
|
// The buyer validates the cost independently and responds with SpendingAuth.
|
|
1128
|
-
if (
|
|
1190
|
+
if (spm && isBillable) {
|
|
1129
1191
|
const usage = responseUsage;
|
|
1130
1192
|
const tokenCostUsdc = computeCostUsdc(usage.freshInputTokens, usage.outputTokens, requestPricing, usage.cachedInputTokens);
|
|
1131
1193
|
const costUsdc = tokenCostUsdc + unitCostUsdc;
|
|
1132
|
-
|
|
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;
|
|
1133
1197
|
if (session && spm.connectionsClosed) {
|
|
1134
1198
|
// The node is stopping and its connections are closed: this
|
|
1135
1199
|
// response never reached the buyer, so it is not billed.
|
|
@@ -1170,7 +1234,6 @@ export class SellerRequestHandler {
|
|
|
1170
1234
|
this._chargeDeliveredVideo(videoRoute, responseForAuth, buyerPeerId, paymentMux, request.requestId);
|
|
1171
1235
|
this._closeFailedVideoJob(videoRoute, responseForAuth, buyerPeerId);
|
|
1172
1236
|
}
|
|
1173
|
-
const buyerSupportsResponseAuth = conn.hasRemoteCapability(CONNECTION_CAPABILITY_RESPONSE_AUTH_V1);
|
|
1174
1237
|
if (responseForAuth && buyerSupportsResponseAuth) {
|
|
1175
1238
|
const channelId = oneOffChannelId ?? spm?.getChannelByPeer(buyerPeerId)?.sessionId ?? null;
|
|
1176
1239
|
this._sendResponseAuthBestEffort(verificationMux, responseAuthRequest, responseForAuth, {
|
|
@@ -1180,6 +1243,7 @@ export class SellerRequestHandler {
|
|
|
1180
1243
|
responseStartedAt,
|
|
1181
1244
|
responseCompletedAt: Date.now(),
|
|
1182
1245
|
channelId,
|
|
1246
|
+
requestHash: wireRequestHash,
|
|
1183
1247
|
});
|
|
1184
1248
|
}
|
|
1185
1249
|
}
|
|
@@ -1193,12 +1257,19 @@ export class SellerRequestHandler {
|
|
|
1193
1257
|
}
|
|
1194
1258
|
};
|
|
1195
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
|
+
}
|
|
1196
1266
|
const usageHold = { reservation: null, estimate: 0, tokens: 0 };
|
|
1197
1267
|
try {
|
|
1198
1268
|
await handleProxyRequest(request, usageHold);
|
|
1199
1269
|
}
|
|
1200
1270
|
finally {
|
|
1201
1271
|
usageHold.reservation?.finish(usageHold.tokens);
|
|
1272
|
+
this._inFlightRequestBytes.release(bodyBytes);
|
|
1202
1273
|
}
|
|
1203
1274
|
});
|
|
1204
1275
|
return { mux };
|
|
@@ -1371,6 +1442,44 @@ export class SellerRequestHandler {
|
|
|
1371
1442
|
this._usageMissingReported.add(key);
|
|
1372
1443
|
this._deps.emit('provider:usage-missing', { provider, service });
|
|
1373
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
|
+
}
|
|
1374
1483
|
_sendJsonError(mux, requestId, statusCode, code, message, extraHeaders = {}) {
|
|
1375
1484
|
mux.sendProxyResponse({
|
|
1376
1485
|
requestId,
|
|
@@ -1635,15 +1744,11 @@ export class SellerRequestHandler {
|
|
|
1635
1744
|
if (isZeroTokenPricing(pricing)) {
|
|
1636
1745
|
return { cost: 0n, inputTokens: 0, maxOutputTokens: 0 };
|
|
1637
1746
|
}
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
}
|
|
1641
|
-
const body = tryParseJsonObject(request.body);
|
|
1642
|
-
if (!body) {
|
|
1747
|
+
const maxOutputTokens = this._requestedMaxOutputTokens(request);
|
|
1748
|
+
if (maxOutputTokens === null) {
|
|
1643
1749
|
return null;
|
|
1644
1750
|
}
|
|
1645
1751
|
const inputTokens = estimateTokensFromBytesSampled(request.body);
|
|
1646
|
-
const maxOutputTokens = this._extractMaxOutputTokens(body);
|
|
1647
1752
|
return {
|
|
1648
1753
|
cost: computeCostUsdc(inputTokens, maxOutputTokens, pricing),
|
|
1649
1754
|
inputTokens,
|
|
@@ -1660,39 +1765,21 @@ export class SellerRequestHandler {
|
|
|
1660
1765
|
if (costEstimate && costEstimate.inputTokens > 0) {
|
|
1661
1766
|
return costEstimate.inputTokens + (costEstimate.maxOutputTokens || DEFAULT_OUTPUT_RESERVATION_TOKENS);
|
|
1662
1767
|
}
|
|
1663
|
-
|
|
1664
|
-
return estimateTokensFromBytesSampled(request.body) + ((body && this._extractMaxOutputTokens(body)) || DEFAULT_OUTPUT_RESERVATION_TOKENS);
|
|
1665
|
-
}
|
|
1666
|
-
_extractMaxOutputTokens(body) {
|
|
1667
|
-
const candidates = [
|
|
1668
|
-
body["max_tokens"],
|
|
1669
|
-
body["max_completion_tokens"],
|
|
1670
|
-
body["max_output_tokens"],
|
|
1671
|
-
body["maxTokens"],
|
|
1672
|
-
body["maxCompletionTokens"],
|
|
1673
|
-
body["maxOutputTokens"],
|
|
1674
|
-
];
|
|
1675
|
-
for (const value of candidates) {
|
|
1676
|
-
const parsed = this._parsePositiveInteger(value);
|
|
1677
|
-
if (parsed !== null)
|
|
1678
|
-
return parsed;
|
|
1679
|
-
}
|
|
1680
|
-
return 0;
|
|
1768
|
+
return estimateTokensFromBytesSampled(request.body) + (this._requestedMaxOutputTokens(request) || DEFAULT_OUTPUT_RESERVATION_TOKENS);
|
|
1681
1769
|
}
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
}
|
|
1690
|
-
else {
|
|
1691
|
-
return null;
|
|
1692
|
-
}
|
|
1693
|
-
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))
|
|
1694
1777
|
return null;
|
|
1695
|
-
|
|
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;
|
|
1696
1783
|
}
|
|
1697
1784
|
async _executeRequest(provider, request, sellerCost, streamCallbacks, isDownload = false) {
|
|
1698
1785
|
// Every provider's response goes through here, so no plugin can expose its
|
|
@@ -1804,6 +1891,7 @@ export class SellerRequestHandler {
|
|
|
1804
1891
|
try {
|
|
1805
1892
|
const payload = createResponseAuthPayload({
|
|
1806
1893
|
request,
|
|
1894
|
+
...(context.requestHash ? { requestHash: context.requestHash } : {}),
|
|
1807
1895
|
response,
|
|
1808
1896
|
buyerPeerId: context.buyerPeerId,
|
|
1809
1897
|
sellerPeerId: this._deps.identity.peerId,
|