@devlab.group/agent-commerce 1.2.0 → 1.4.0

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/dist/index.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import { I as IsoTimestamp, D as DecimalAmount, P as PaymentMethodName, B as BackendHandler, A as AdapterDescriptor, a as AdapterHealth, C as CommerceResource, R as ResourceRegistry, b as PaymentProvider, L as Logger, c as Clock, d as IdGenerator } from './runtime-Bqg9qW3t.js';
2
- export { e as BackendMethod, f as DEFAULT_BACKEND_TIMEOUT_MS, J as JsonSchema, N as NOOP_LOGGER, g as PROTOCOL_NAMES, h as PaymentChallenge, i as PaymentContext, j as PaymentRequirement, k as PaymentResult, l as PaymentSettlementContext, m as PaymentSubmission, n as PaymentVerificationContext, o as Pricing, p as ProtocolName, s as systemClock } from './runtime-Bqg9qW3t.js';
1
+ import { f as Ap2AuthorizationConfig } from './types-CJtwLu1c.js';
2
+ import { I as IsoTimestamp, D as DecimalAmount, P as PaymentMethodName, a as CommerceResource, b as PaymentSubmission, B as BackendHandler, A as AdapterDescriptor, c as AdapterHealth, R as ResourceRegistry, d as PaymentProvider, L as Logger, C as Clock, e as IdGenerator } from './runtime-CKq3d_3K.js';
3
+ export { f as AuthorizationMethodName, g as BackendMethod, h as DEFAULT_BACKEND_TIMEOUT_MS, J as JsonSchema, N as NOOP_LOGGER, i as PROTOCOL_NAMES, j as PaymentChallenge, k as PaymentContext, l as PaymentRequirement, m as PaymentResult, n as PaymentSettlementContext, o as PaymentVerificationContext, p as Pricing, q as ProtocolName, s as systemClock } from './runtime-CKq3d_3K.js';
3
4
  import { X as X402FacilitatorConfig } from './guardrails-Dmwi63KB.js';
4
- import { D as DeliveredOutcome, P as PaymentRequiredOutcome, C as CommerceEvent, a as PaymentAttempt, b as CommerceReceipt, E as ExecutionPipeline, c as ProtocolAdapter } from './protocol-adapter-BAKGnuZ4.js';
5
- export { A as AdapterHttpRoute, d as COMMERCE_EVENT_TYPES, e as CanonicalRequest, f as CommerceEventType, g as EventSink, h as ExecutionOutcome, H as HttpProtocolAdapter, i as ProtocolAdapterContext, j as isHttpProtocolAdapter } from './protocol-adapter-BAKGnuZ4.js';
5
+ import { a as AuthorizationRequirement, b as AuthorizationSubmission, A as AuthorizationProvider } from './authorization-CPDcpJVa.js';
6
+ export { c as AuthorizationFinalizeContext, d as AuthorizationRecord, e as AuthorizationVerification, f as AuthorizationVerificationContext } from './authorization-CPDcpJVa.js';
7
+ import { D as DeliveredOutcome, P as PaymentRequiredOutcome, C as CommerceEvent, a as PaymentAttempt, b as CommerceReceipt, E as ExecutionPipeline, c as ProtocolAdapter, H as HttpProtocolAdapter, A as AdapterHttpRoute, d as ProtocolAdapterContext } from './protocol-adapter-CaMZj6Wm.js';
8
+ export { e as COMMERCE_EVENT_TYPES, f as CanonicalRequest, g as CommerceEventType, h as EventSink, i as ExecutionOutcome, j as isHttpProtocolAdapter } from './protocol-adapter-CaMZj6Wm.js';
6
9
  import { FastifyInstance } from 'fastify';
7
- import 'node:http';
10
+ import { IncomingMessage, ServerResponse } from 'node:http';
8
11
 
9
12
  /**
10
13
  * Typed domain error codes.
@@ -12,7 +15,7 @@ import 'node:http';
12
15
  * FROZEN CONTRACT. Protocol adapters map these codes into their own response
13
16
  * format. Never throw a bare string or untyped Error across a package boundary.
14
17
  */
15
- declare const COMMERCE_ERROR_CODES: readonly ["CONFIG_INVALID", "RESOURCE_NOT_FOUND", "INPUT_INVALID", "PAYMENT_REQUIRED", "PAYMENT_INVALID", "PAYMENT_REPLAYED", "PAYMENT_PROVIDER_UNAVAILABLE", "PAYMENT_SETTLEMENT_FAILED", "BACKEND_TIMEOUT", "BACKEND_ERROR", "PROTOCOL_UNSUPPORTED", "GATEWAY_BUSY", "STORAGE_ERROR", "INTERNAL_ERROR"];
18
+ declare const COMMERCE_ERROR_CODES: readonly ["CONFIG_INVALID", "RESOURCE_NOT_FOUND", "INPUT_INVALID", "PAYMENT_REQUIRED", "PAYMENT_INVALID", "PAYMENT_REPLAYED", "PAYMENT_PROVIDER_UNAVAILABLE", "PAYMENT_SETTLEMENT_FAILED", "AUTHORIZATION_REQUIRED", "AUTHORIZATION_INVALID", "AUTHORIZATION_REPLAYED", "AUTHORIZATION_PROVIDER_UNAVAILABLE", "BACKEND_TIMEOUT", "BACKEND_ERROR", "PROTOCOL_UNSUPPORTED", "GATEWAY_BUSY", "STORAGE_ERROR", "INTERNAL_ERROR"];
16
19
  type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];
17
20
  /**
18
21
  * Canonical HTTP status for each error code.
@@ -109,6 +112,47 @@ declare const PAYMENT_INPUT_FIELD = "_payment";
109
112
  declare const PAYMENT_HEADER = "payment-signature";
110
113
  /** HTTP response header carrying the settlement result. */
111
114
  declare const PAYMENT_RESPONSE_HEADER = "payment-response";
115
+ /**
116
+ * Reserved input property carrying an authorization proof, the authorization
117
+ * counterpart of {@link PAYMENT_INPUT_FIELD}.
118
+ *
119
+ * Unlike `_payment`, which is a bare string, this one carries an object:
120
+ * `{ method, payload }`. There is exactly one payment rail per resource, so a
121
+ * payment proof's method can be inferred from the resource; an authorization
122
+ * proof cannot lean on that, and guessing the method of a security control is
123
+ * not a thing to do implicitly.
124
+ */
125
+ declare const AUTHORIZATION_INPUT_FIELD = "_authorization";
126
+ /**
127
+ * Every input property name the gateway claims for itself.
128
+ *
129
+ * One list, read by the config loader (which rejects a resource declaring any
130
+ * of them), by the protocol adapters that lift them out of client input, and
131
+ * by the pipeline that strips them again as defence in depth. Those three
132
+ * agree by construction instead of by three copies of two strings.
133
+ */
134
+ declare const RESERVED_INPUT_FIELDS: readonly string[];
135
+ /**
136
+ * HTTP request header carrying the authorization proof, base64url-encoded
137
+ * JSON of the same `{ method, payload }` envelope the reserved input field
138
+ * carries.
139
+ *
140
+ * This is an Agent Commerce transport carrier, not a header defined by any
141
+ * authorization specification, so it is namespaced rather than borrowing
142
+ * `Authorization`, which already means something else on every one of these
143
+ * routes.
144
+ */
145
+ declare const AUTHORIZATION_HEADER = "agent-authorization";
146
+ /**
147
+ * Hard cap on the encoded `Agent-Authorization` header.
148
+ *
149
+ * Node's own limit is ~16 KiB across *all* request headers, so an
150
+ * authorization near that size would start evicting everything else and fail
151
+ * as an unreadable transport error rather than a legible one. Capping well
152
+ * below it means an oversized proof gets a deterministic
153
+ * AUTHORIZATION_INVALID naming the limit.
154
+ */
155
+ declare const MAX_AUTHORIZATION_HEADER_BYTES = 8192;
112
156
  /**
113
157
  * HTTP response header carrying the base64 payment challenge on a 402.
114
158
  *
@@ -154,6 +198,19 @@ interface PaymentRequiredEnvelope {
154
198
  */
155
199
  readonly envelope?: Readonly<Record<string, unknown>>;
156
200
  };
201
+ /**
202
+ * Present only when the resource requires an authorization proof as well.
203
+ *
204
+ * Additive: a client that does not understand the field sees exactly the
205
+ * envelope it saw before. A client that does learns, before it spends
206
+ * anything, that paying alone will not get the resource delivered.
207
+ *
208
+ * This advertises a requirement; it does not issue anything. The proof is
209
+ * obtained from the merchant's own approval flow, outside the gateway.
210
+ */
211
+ readonly authorization?: {
212
+ readonly required: readonly AuthorizationRequirement[];
213
+ };
157
214
  }
158
215
  interface ErrorEnvelope {
159
216
  readonly status: 'error';
@@ -196,6 +253,42 @@ declare function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary;
196
253
  declare function toPaymentRequiredEnvelope(outcome: PaymentRequiredOutcome): PaymentRequiredEnvelope;
197
254
  declare function toErrorEnvelope(error: CommerceError): ErrorEnvelope;
198
255
  declare function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope;
256
+ /**
257
+ * Parses the `{ method, payload }` authorization envelope, whichever carrier
258
+ * brought it.
259
+ *
260
+ * Absent is `undefined`. Present but malformed throws, rather than being
261
+ * dropped the way an unusable `_payment` is. A dropped payment leaves the
262
+ * buyer holding a 402 they can act on. A silently dropped authorization would
263
+ * come back as "not authorized" for a proof the client believes it sent, with
264
+ * no way to tell a rejected mandate from a typo in the envelope around it.
265
+ */
266
+ declare function parseAuthorizationSubmission(value: unknown, requestId?: string): AuthorizationSubmission | undefined;
267
+ /**
268
+ * Decodes the base64url-JSON `Agent-Authorization` header.
269
+ *
270
+ * The size check runs on the encoded value before any decoding, so an
271
+ * oversized header costs a length comparison rather than a base64 decode and
272
+ * a JSON parse of whatever a caller chose to send.
273
+ */
274
+ declare function parseAuthorizationHeader(raw: string | readonly string[] | undefined, requestId?: string): AuthorizationSubmission | undefined;
275
+ /**
276
+ * Splits raw client input into resource input plus the reserved fields the
277
+ * gateway claims, for every protocol that carries them in the input object
278
+ * (MCP tool arguments, A2A message data). HTTP carries both in headers and
279
+ * uses the two parse helpers directly.
280
+ *
281
+ * The payment method comes from the resource's own declaration. This is not
282
+ * the place that decides which rail a resource uses, so a proof for a
283
+ * resource with no configured rail is dropped rather than forwarded under an
284
+ * invented method. The pipeline then treats the request as unpaid and decides
285
+ * on its own terms.
286
+ */
287
+ declare function extractReservedInputFields(rawInput: Record<string, unknown>, resource: CommerceResource | undefined, requestId?: string): {
288
+ input: Record<string, unknown>;
289
+ payment?: PaymentSubmission;
290
+ authorization?: AuthorizationSubmission;
291
+ };
199
292
 
200
293
  /**
201
294
  * Merchant backend execution boundary.
@@ -309,6 +402,33 @@ interface ReceiptStore {
309
402
  close(): Promise<void>;
310
403
  }
311
404
 
405
+ /**
406
+ * ACP protocol constants shared by the config layer and the adapter.
407
+ *
408
+ * Kept dependency-free: `src/config` reads the operation set at load time, so
409
+ * anything imported here would become a config-load dependency too.
410
+ */
411
+ /**
412
+ * The ACP stable snapshot this adapter implements, and the only value accepted
413
+ * in the `API-Version` request header. Both name the same released snapshot;
414
+ * they are separate constants because ACP versions the wire contract and the
415
+ * header independently, and a future snapshot may accept more than one.
416
+ *
417
+ * Changing either means vendoring a new schema directory beside
418
+ * `spec/2026-04-17/` - never editing the vendored one in place.
419
+ */
420
+ declare const ACP_SPEC_VERSION = "2026-04-17";
421
+ declare const ACP_API_VERSION = "2026-04-17";
422
+ /** Discovery path fixed by the ACP specification - never a configurable mount. */
423
+ declare const ACP_WELL_KNOWN_PATH = "/.well-known/acp.json";
424
+ /**
425
+ * The stable checkout operations, by ACP operation id. All five are required
426
+ * when ACP is enabled: a partially configured checkout lifecycle would be
427
+ * advertised as a whole service the seller cannot actually serve.
428
+ */
429
+ declare const ACP_CHECKOUT_OPERATIONS: readonly ["createCheckoutSession", "updateCheckoutSession", "getCheckoutSession", "completeCheckoutSession", "cancelCheckoutSession"];
430
+ type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];
431
+
312
432
  /**
313
433
  * `config.yaml` schema, validation and normalisation into the
314
434
  * canonical `GatewayConfig` (docs/contracts.md).
@@ -335,6 +455,37 @@ interface ReceiptStore {
335
455
  * substitution rule, which this sentence exists to record.
336
456
  */
337
457
 
458
+ /** Optional ACP discovery metadata. Absent fields are omitted from the document. */
459
+ interface AcpDiscoveryConfig {
460
+ readonly documentationUrl?: string;
461
+ readonly supportedCurrencies?: readonly string[];
462
+ readonly supportedLocales?: readonly string[];
463
+ readonly interventionTypes?: readonly string[];
464
+ }
465
+ /**
466
+ * Discriminated on `enabled` so an enabled ACP config carries everything the
467
+ * adapter needs, with no optional-field assertions at the mount point: a
468
+ * half-configured checkout lifecycle is rejected at load instead.
469
+ */
470
+ type AcpProtocolConfig = {
471
+ readonly enabled: false;
472
+ readonly mountPath: string;
473
+ } | {
474
+ readonly enabled: true;
475
+ readonly mountPath: string;
476
+ readonly auth: {
477
+ readonly type: 'bearer';
478
+ readonly token: string;
479
+ };
480
+ readonly idempotency: {
481
+ readonly path: string;
482
+ readonly retentionHours: number;
483
+ };
484
+ readonly checkout: {
485
+ readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;
486
+ };
487
+ readonly discovery?: AcpDiscoveryConfig;
488
+ };
338
489
  interface GatewayConfig {
339
490
  readonly version: 1;
340
491
  readonly merchant: {
@@ -366,6 +517,7 @@ interface GatewayConfig {
366
517
  readonly enabled: boolean;
367
518
  readonly mountPath: string;
368
519
  };
520
+ readonly acp: AcpProtocolConfig;
369
521
  };
370
522
  /** Canonical resources, already normalised. */
371
523
  readonly resources: readonly CommerceResource[];
@@ -385,6 +537,13 @@ interface GatewayConfig {
385
537
  readonly allowUnauthenticatedFacilitator?: boolean;
386
538
  };
387
539
  };
540
+ /**
541
+ * Absent when no `authorization:` block is configured, which is how every
542
+ * config written before AP2 existed reads.
543
+ */
544
+ readonly authorization?: {
545
+ readonly ap2: Ap2AuthorizationConfig;
546
+ };
388
547
  }
389
548
  declare function parseConfig(raw: unknown, env: NodeJS.ProcessEnv): GatewayConfig;
390
549
 
@@ -404,6 +563,8 @@ interface GatewayOptions {
404
563
  readonly config: GatewayConfig;
405
564
  readonly store: ReceiptStore;
406
565
  readonly paymentProviders: readonly PaymentProvider[];
566
+ /** Absent means no resource requires authorization, which is the default */
567
+ readonly authorizationProviders?: readonly AuthorizationProvider[];
407
568
  readonly protocolAdapters: readonly ProtocolAdapter[];
408
569
  readonly logger?: Logger;
409
570
  readonly clock?: Clock;
@@ -423,6 +584,94 @@ interface GatewayInstance {
423
584
  }
424
585
  declare function createGateway(options: GatewayOptions): Promise<GatewayInstance>;
425
586
 
587
+ /** Discovery metadata an operator may configure. Absent fields are omitted, never guessed. */
588
+ interface AcpDiscoveryMetadata {
589
+ readonly documentationUrl?: string;
590
+ readonly supportedCurrencies?: readonly string[];
591
+ readonly supportedLocales?: readonly string[];
592
+ readonly interventionTypes?: readonly string[];
593
+ }
594
+
595
+ /**
596
+ * ACP (Agentic Commerce Protocol) adapter - experimental.
597
+ *
598
+ * Serves two paths: the configured mount (`/acp`), where the five stable
599
+ * checkout routes live, and the specification-fixed `/.well-known/acp.json`,
600
+ * declared through `additionalHttpRoutes` so the gateway needs no ACP-specific
601
+ * routing.
602
+ *
603
+ * Discovery and every protocol guard that must hold before canonical execution
604
+ * are implemented. A guarded request is not executed yet: until checkout
605
+ * operations reach the pipeline, a fully-valid request is answered with an
606
+ * honest "not implemented" rather than a fabricated session.
607
+ *
608
+ * This file never calls a merchant backend and never inspects a payment
609
+ * object.
610
+ */
611
+
612
+ interface AcpAdapterOptions {
613
+ readonly mountPath: string;
614
+ /** The configured bearer token. Never logged, never echoed, never published. */
615
+ readonly token: string;
616
+ /** Which canonical resource implements each ACP checkout operation. */
617
+ readonly operations: Readonly<Record<AcpCheckoutOperation, string>>;
618
+ /** Where checkout idempotency records live, and how long they are kept. */
619
+ readonly idempotency: {
620
+ readonly path: string;
621
+ readonly retentionHours: number;
622
+ };
623
+ readonly discovery?: AcpDiscoveryMetadata;
624
+ }
625
+ declare class AcpProtocolAdapter implements HttpProtocolAdapter {
626
+ readonly name: "acp";
627
+ readonly mountPath: string;
628
+ readonly descriptor: AdapterDescriptor;
629
+ readonly additionalHttpRoutes: readonly AdapterHttpRoute[];
630
+ private readonly token;
631
+ private readonly operations;
632
+ private readonly idempotencyOptions;
633
+ /** Derived once: the token is fixed, and only its digest may be persisted. */
634
+ private readonly identityHash;
635
+ private readonly discoveryMetadata;
636
+ private idempotency;
637
+ private resources;
638
+ private context;
639
+ private started;
640
+ private discovery;
641
+ constructor(options: AcpAdapterOptions);
642
+ start(context: ProtocolAdapterContext): Promise<void>;
643
+ /** `GET /.well-known/acp.json` - public, unauthenticated, cacheable. */
644
+ handleDiscovery(req: IncomingMessage, res: ServerResponse): Promise<void>;
645
+ /** `<mountPath>/checkout_sessions...` - the five stable checkout routes. */
646
+ handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;
647
+ /**
648
+ * One request, at most one execution.
649
+ *
650
+ * A body-bearing route claims its idempotency key *before* the work starts,
651
+ * so a retry that arrives while the first one is still running finds the
652
+ * claim instead of starting a second checkout. A route with no key (the GET)
653
+ * is read-only and needs none.
654
+ */
655
+ private dispatch;
656
+ /**
657
+ * One accepted request, one `pipeline.execute()`.
658
+ *
659
+ * Nothing here prices a resource, inspects a payment proof or calls a
660
+ * merchant backend: the adapter builds a canonical request and reads back
661
+ * what the pipeline decided.
662
+ */
663
+ private runCheckout;
664
+ /**
665
+ * Protocol-owned headers only. A merchant backend's own headers are never
666
+ * proxied onto an ACP response.
667
+ */
668
+ private responseHeaders;
669
+ private fail;
670
+ health(): Promise<AdapterHealth>;
671
+ stop(): Promise<void>;
672
+ }
673
+ declare function createAcpAdapter(options: AcpAdapterOptions): AcpProtocolAdapter;
674
+
426
675
  interface SqliteReceiptStoreOptions {
427
676
  /** File path, or ':memory:' for tests. Parent directory is created if missing. */
428
677
  readonly path: string;
@@ -432,4 +681,4 @@ interface SqliteReceiptStoreOptions {
432
681
  }
433
682
  declare function createSqliteReceiptStore(options: SqliteReceiptStoreOptions): ReceiptStore;
434
683
 
435
- export { AdapterDescriptor, AdapterHealth, type BackendExecutor, BackendHandler, type BackendRequest, type BackendResponse, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, Clock, CommerceError, type CommerceErrorCode, type CommerceErrorInfo, type CommerceErrorOptions, CommerceEvent, CommerceReceipt, CommerceResource, DELIVERY_SUMMARY_META_KEY, DecimalAmount, DeliveredOutcome, type DeliverySummary, type ErrorEnvelope, ExecutionPipeline, type GatewayConfig, type GatewayInstance, type GatewayOptions, IdGenerator, IsoTimestamp, type ListOptions, Logger, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PaymentAttempt, type PaymentAttemptReservation, type PaymentAttemptUpdate, PaymentMethodName, PaymentProvider, type PaymentRequiredEnvelope, PaymentRequiredOutcome, ProtocolAdapter, RETRYABLE_ERROR_CODES, type ReceiptStore, ResourceRegistry, createGateway, createSqliteReceiptStore, isCommerceError, isPaymentRequiredEnvelope, loadConfig, parseConfig, createSqliteReceiptStore as receipts, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope };
684
+ export { ACP_API_VERSION, ACP_SPEC_VERSION, ACP_WELL_KNOWN_PATH, AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, type AcpAdapterOptions, AdapterDescriptor, AdapterHealth, AdapterHttpRoute, AuthorizationProvider, AuthorizationRequirement, AuthorizationSubmission, type BackendExecutor, BackendHandler, type BackendRequest, type BackendResponse, COMMERCE_ERROR_CODES, COMMERCE_ERROR_HTTP_STATUS, Clock, CommerceError, type CommerceErrorCode, type CommerceErrorInfo, type CommerceErrorOptions, CommerceEvent, CommerceReceipt, CommerceResource, DELIVERY_SUMMARY_META_KEY, DecimalAmount, DeliveredOutcome, type DeliverySummary, type ErrorEnvelope, ExecutionPipeline, type GatewayConfig, type GatewayInstance, type GatewayOptions, HttpProtocolAdapter, IdGenerator, IsoTimestamp, type ListOptions, Logger, MAX_AUTHORIZATION_HEADER_BYTES, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PaymentAttempt, type PaymentAttemptReservation, type PaymentAttemptUpdate, PaymentMethodName, PaymentProvider, type PaymentRequiredEnvelope, PaymentRequiredOutcome, PaymentSubmission, ProtocolAdapter, ProtocolAdapterContext, RESERVED_INPUT_FIELDS, RETRYABLE_ERROR_CODES, type ReceiptStore, ResourceRegistry, createAcpAdapter, createGateway, createSqliteReceiptStore, extractReservedInputFields, isCommerceError, isPaymentRequiredEnvelope, loadConfig, parseAuthorizationHeader, parseAuthorizationSubmission, parseConfig, createSqliteReceiptStore as receipts, toCommerceError, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope };