@devlab.group/agent-commerce 2.7.2 → 2.9.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.
Files changed (133) hide show
  1. package/README.md +79 -30
  2. package/dist/ap2.d.ts +3 -11
  3. package/dist/ap2.js +97 -28
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-77HLISG4.js → chunk-2PVRHMVT.js} +14 -10
  6. package/dist/chunk-2PVRHMVT.js.map +1 -0
  7. package/dist/{chunk-WDD2ZUR3.js → chunk-46Y5M7BA.js} +3 -2
  8. package/dist/chunk-46Y5M7BA.js.map +1 -0
  9. package/dist/{chunk-XXHC6AA3.js → chunk-5Q6W7YTK.js} +160 -41
  10. package/dist/chunk-5Q6W7YTK.js.map +1 -0
  11. package/dist/chunk-JF45GSNA.js +22 -0
  12. package/dist/chunk-JF45GSNA.js.map +1 -0
  13. package/dist/{chunk-YHNTTMED.js → chunk-MDOGXTZD.js} +2 -2
  14. package/dist/chunk-MDOGXTZD.js.map +1 -0
  15. package/dist/chunk-MNI6APE6.js +64 -0
  16. package/dist/chunk-MNI6APE6.js.map +1 -0
  17. package/dist/{chunk-IWXVQYG5.js → chunk-RF3DFVXH.js} +2 -2
  18. package/dist/{chunk-IWXVQYG5.js.map → chunk-RF3DFVXH.js.map} +1 -1
  19. package/dist/{chunk-DJRWYDKJ.js → chunk-RXYGC7A3.js} +3 -3
  20. package/dist/{chunk-DJRWYDKJ.js.map → chunk-RXYGC7A3.js.map} +1 -1
  21. package/dist/{chunk-5AO5N2XY.js → chunk-VHS6MGXJ.js} +621 -4
  22. package/dist/chunk-VHS6MGXJ.js.map +1 -0
  23. package/dist/cli/{ap2-O3HJSS2E.js → ap2-SJZAZQIR.js} +36 -9
  24. package/dist/cli/ap2-SJZAZQIR.js.map +1 -0
  25. package/dist/cli/chunk-25WJIUJU.js +8 -0
  26. package/dist/cli/{chunk-B4QJV7OC.js.map → chunk-25WJIUJU.js.map} +1 -1
  27. package/dist/cli/chunk-2PO65227.js +619 -0
  28. package/dist/cli/chunk-2PO65227.js.map +1 -0
  29. package/dist/cli/{chunk-DKWO6LLX.js → chunk-4WPHZLVO.js} +3 -2
  30. package/dist/cli/chunk-4WPHZLVO.js.map +1 -0
  31. package/dist/cli/chunk-4YZULHX2.js +64 -0
  32. package/dist/cli/chunk-4YZULHX2.js.map +1 -0
  33. package/dist/cli/chunk-526C4KZA.js +93 -0
  34. package/dist/cli/chunk-526C4KZA.js.map +1 -0
  35. package/dist/cli/{chunk-FETTSOMT.js → chunk-5CH5VFC6.js} +139 -4
  36. package/dist/cli/chunk-5CH5VFC6.js.map +1 -0
  37. package/dist/cli/chunk-GISJ73ML.js +20 -0
  38. package/dist/cli/chunk-GISJ73ML.js.map +1 -0
  39. package/dist/cli/chunk-IJFPWT4I.js +435 -0
  40. package/dist/cli/chunk-IJFPWT4I.js.map +1 -0
  41. package/dist/cli/{chunk-QUFFT5K3.js → chunk-K34CRXKX.js} +141 -42
  42. package/dist/cli/chunk-K34CRXKX.js.map +1 -0
  43. package/dist/cli/{chunk-OETKXDGA.js → chunk-L264N3ZV.js} +127 -274
  44. package/dist/cli/chunk-L264N3ZV.js.map +1 -0
  45. package/dist/cli/chunk-MASLG557.js +26 -0
  46. package/dist/cli/chunk-MASLG557.js.map +1 -0
  47. package/dist/cli/{chunk-S5TQXKQ7.js → chunk-NM7V2Y4I.js} +7 -5
  48. package/dist/cli/chunk-NM7V2Y4I.js.map +1 -0
  49. package/dist/cli/chunk-RQ7W3NA5.js +143 -0
  50. package/dist/cli/chunk-RQ7W3NA5.js.map +1 -0
  51. package/dist/cli/chunk-RWBUHDU7.js +48 -0
  52. package/dist/cli/chunk-RWBUHDU7.js.map +1 -0
  53. package/dist/cli/{chunk-GBBG66O6.js → chunk-SHIA2B6G.js} +161 -106
  54. package/dist/cli/chunk-SHIA2B6G.js.map +1 -0
  55. package/dist/cli/{chunk-FL4HPCD4.js → chunk-THH7Y3OO.js} +3 -35
  56. package/dist/cli/chunk-THH7Y3OO.js.map +1 -0
  57. package/dist/cli/{chunk-XRG5UTIC.js → chunk-U3SEGD4H.js} +127 -19
  58. package/dist/cli/chunk-U3SEGD4H.js.map +1 -0
  59. package/dist/cli/{chunk-55AI6CLW.js → chunk-USIXWAXZ.js} +2 -2
  60. package/dist/cli/chunk-USIXWAXZ.js.map +1 -0
  61. package/dist/cli/{chunk-APC5BTQM.js → chunk-UV23DWUY.js} +2 -2
  62. package/dist/cli/{chunk-APC5BTQM.js.map → chunk-UV23DWUY.js.map} +1 -1
  63. package/dist/cli/config-IBG46HTQ.js +14 -0
  64. package/dist/cli/{config-ODN4IEMZ.js.map → config-IBG46HTQ.js.map} +1 -1
  65. package/dist/cli/index.js +373 -82
  66. package/dist/cli/index.js.map +1 -1
  67. package/dist/cli/{mcp-G2D2Z77G.js → mcp-F3EQQWDZ.js} +84 -45
  68. package/dist/cli/mcp-F3EQQWDZ.js.map +1 -0
  69. package/dist/cli/payment-providers-FPTGQBU7.js +6 -0
  70. package/dist/cli/{payment-providers-7RIIZ5OF.js.map → payment-providers-FPTGQBU7.js.map} +1 -1
  71. package/dist/cli/{provider-ARV3VAQ7.js → provider-XACFJ7MG.js} +145 -23
  72. package/dist/cli/provider-XACFJ7MG.js.map +1 -0
  73. package/dist/cli/receipts-AXCPPGOK.js +9 -0
  74. package/dist/cli/{receipts-HLQ7D722.js.map → receipts-AXCPPGOK.js.map} +1 -1
  75. package/dist/cli/{run-BHODKC6H.js → run-C3VWMM57.js} +912 -237
  76. package/dist/cli/run-C3VWMM57.js.map +1 -0
  77. package/dist/cli/{x402-LHW2YQ6W.js → x402-SUXWULOP.js} +12 -8
  78. package/dist/cli/x402-SUXWULOP.js.map +1 -0
  79. package/dist/index.d.ts +108 -41
  80. package/dist/index.js +1614 -633
  81. package/dist/index.js.map +1 -1
  82. package/dist/mcp.d.ts +2 -2
  83. package/dist/mcp.js +80 -42
  84. package/dist/mcp.js.map +1 -1
  85. package/dist/mpp.d.ts +3 -2
  86. package/dist/mpp.js +139 -20
  87. package/dist/mpp.js.map +1 -1
  88. package/dist/{protocol-adapter-DdFL5LBU.d.ts → protocol-adapter-D6JH_kk-.d.ts} +2 -2
  89. package/dist/{runtime-BmaSp2Ce.d.ts → runtime-D8u6lYfx.d.ts} +10 -0
  90. package/dist/{store-DQwbKhnc.d.ts → store-04pazhFP.d.ts} +54 -3
  91. package/dist/testing.d.ts +1 -1
  92. package/dist/testing.js +469 -274
  93. package/dist/testing.js.map +1 -1
  94. package/dist/{transaction-BXXJltZ-.d.ts → transaction-F9ZvhokH.d.ts} +1 -1
  95. package/dist/types-Dl27vhEc.d.ts +167 -0
  96. package/dist/x402.d.ts +7 -110
  97. package/dist/x402.js +6 -5
  98. package/dist/x402.js.map +1 -1
  99. package/package.json +3 -1
  100. package/dist/chunk-2573DASO.js +0 -8
  101. package/dist/chunk-2573DASO.js.map +0 -1
  102. package/dist/chunk-5AO5N2XY.js.map +0 -1
  103. package/dist/chunk-77HLISG4.js.map +0 -1
  104. package/dist/chunk-WDD2ZUR3.js.map +0 -1
  105. package/dist/chunk-XXHC6AA3.js.map +0 -1
  106. package/dist/chunk-YHNTTMED.js.map +0 -1
  107. package/dist/cli/ap2-O3HJSS2E.js.map +0 -1
  108. package/dist/cli/chunk-3NVJAQRO.js +0 -119
  109. package/dist/cli/chunk-3NVJAQRO.js.map +0 -1
  110. package/dist/cli/chunk-55AI6CLW.js.map +0 -1
  111. package/dist/cli/chunk-66NTYSXI.js +0 -277
  112. package/dist/cli/chunk-66NTYSXI.js.map +0 -1
  113. package/dist/cli/chunk-B4QJV7OC.js +0 -8
  114. package/dist/cli/chunk-DKWO6LLX.js.map +0 -1
  115. package/dist/cli/chunk-FETTSOMT.js.map +0 -1
  116. package/dist/cli/chunk-FL4HPCD4.js.map +0 -1
  117. package/dist/cli/chunk-GBBG66O6.js.map +0 -1
  118. package/dist/cli/chunk-H7EBJ4I3.js +0 -53
  119. package/dist/cli/chunk-H7EBJ4I3.js.map +0 -1
  120. package/dist/cli/chunk-OETKXDGA.js.map +0 -1
  121. package/dist/cli/chunk-QUFFT5K3.js.map +0 -1
  122. package/dist/cli/chunk-S5TQXKQ7.js.map +0 -1
  123. package/dist/cli/chunk-TPC4EJLT.js +0 -11
  124. package/dist/cli/chunk-TPC4EJLT.js.map +0 -1
  125. package/dist/cli/chunk-XRG5UTIC.js.map +0 -1
  126. package/dist/cli/config-ODN4IEMZ.js +0 -13
  127. package/dist/cli/mcp-G2D2Z77G.js.map +0 -1
  128. package/dist/cli/payment-providers-7RIIZ5OF.js +0 -6
  129. package/dist/cli/provider-ARV3VAQ7.js.map +0 -1
  130. package/dist/cli/receipts-HLQ7D722.js +0 -9
  131. package/dist/cli/run-BHODKC6H.js.map +0 -1
  132. package/dist/cli/x402-LHW2YQ6W.js.map +0 -1
  133. package/dist/networks-DDHYJLcg.d.ts +0 -39
@@ -1,20 +1,23 @@
1
- import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-S5TQXKQ7.js';
2
- import { readCappedBody, createBearerCheck, joinUrl, settlementResponse, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-FL4HPCD4.js';
3
- import { A2A_DEFAULT_MOUNT_PATH, A2A_DEFAULT_AGENT_NAME, buildDescriptor, A2A_AGENT_CARD_PATH, A2A_JSON_MEDIA_TYPE, A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION, A2A_EXTENSIONS_HEADER, A2A_PUSH_CONFIG_METHODS, A2A_TASK_LOOKUP_METHODS, A2A_UNSUPPORTED_METHODS, A2A_METHOD_SEND_MESSAGE, buildDescriptor2, A2A_PROTOCOL_BINDING, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_INPUT_REQUIRED } from './chunk-3NVJAQRO.js';
4
- import { loadConfig } from './chunk-GBBG66O6.js';
5
- import { HttpBackendExecutor, createResourceRegistry, assertRetrySupport, createStoreEventSink, createExecutionPipeline, ACP_WELL_KNOWN_PATH, ACP_CHECKOUT_OPERATIONS, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IDEMPOTENCY_KEY_HEADER, ACP_REQUEST_ID_HEADER, ACP_SPEC_VERSION, ACP_JSON_MEDIA_TYPE, ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_MAX_REQUEST_ID_LENGTH, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY, ACP_FORWARDED_HEADERS, ACP_MAX_FORWARDED_HEADER_LENGTH, BackendErrorResponse, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS } from './chunk-OETKXDGA.js';
6
- import { hasMethodGroup } from './chunk-DKWO6LLX.js';
7
- import './chunk-TPC4EJLT.js';
8
- import { createSqliteReceiptStore } from './chunk-XRG5UTIC.js';
1
+ import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-NM7V2Y4I.js';
2
+ import { settlementResponse, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-THH7Y3OO.js';
3
+ import { a2a_default, acp_default } from './chunk-IJFPWT4I.js';
4
+ import { loadConfig } from './chunk-SHIA2B6G.js';
5
+ import { ACP_CHECKOUT_OPERATIONS, HttpBackendExecutor, createResourceRegistry, assertRetrySupport, createStoreEventSink, createExecutionPipeline, A2A_DEFAULT_MOUNT_PATH, A2A_DEFAULT_AGENT_NAME, A2A_AGENT_CARD_PATH, A2A_MAX_BACKGROUND_RUNS, A2A_JSON_MEDIA_TYPE, A2A_VERSION_HEADER, A2A_PROTOCOL_VERSION, A2A_EXTENSIONS_HEADER, A2A_X_EXTENSIONS_HEADER, A2A_PUSH_CONFIG_METHODS, A2A_UNSUPPORTED_METHODS, A2A_METHOD_CANCEL_TASK, A2A_METHOD_LIST_TASKS, A2A_METHOD_GET_TASK, A2A_METHOD_SEND_MESSAGE, ACP_WELL_KNOWN_PATH, ACP_IN_FLIGHT_RETRY_AFTER_SECONDS, ACP_IDEMPOTENT_REPLAYED_HEADER, ACP_IDEMPOTENCY_KEY_HEADER, ACP_REQUEST_ID_HEADER, A2A_SPEC_VERSION, A2A_PROTOCOL_BINDING, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_WORKING, A2A_TASK_STATE_COMPLETED, ACP_SPEC_VERSION, ACP_JSON_MEDIA_TYPE, ACP_API_VERSION, ACP_API_VERSION_HEADER, ACP_MAX_REQUEST_ID_LENGTH, ACP_OPERATION_INPUT_KEYS, ACP_OPERATION_OPTIONAL_INPUT_KEYS, ACP_SESSION_ID_INPUT_KEY, ACP_FORWARDED_HEADERS, ACP_MAX_FORWARDED_HEADER_LENGTH, BackendErrorResponse, ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS, ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS, A2A_TASK_STATE_INPUT_REQUIRED, A2A_TASK_RETENTION_HOURS, A2A_MAX_RETAINED_TASKS, A2A_TASK_STATE_CANCELED } from './chunk-L264N3ZV.js';
6
+ import { hasMethodGroup } from './chunk-4WPHZLVO.js';
7
+ import { readCappedBody, createBearerCheck, joinUrl } from './chunk-RWBUHDU7.js';
8
+ import { createSqliteReceiptStore } from './chunk-U3SEGD4H.js';
9
9
  import { openSqliteDatabase } from './chunk-6EBDOH37.js';
10
- import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-APC5BTQM.js';
10
+ import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-UV23DWUY.js';
11
11
  import { resolveManually, journalOf } from './chunk-VSSSU4AU.js';
12
12
  import { contentDigest, CONTENT_DIGEST_METADATA_KEY, mppProblem, mppProblemDetail } from './chunk-3IEXJ7I3.js';
13
13
  import { MPP_DEFAULT_PAYMENT_FLOW, MPP_PROFILE } from './chunk-AA3FIEAR.js';
14
- import { x402OfferName } from './chunk-FETTSOMT.js';
15
- import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-66NTYSXI.js';
16
- import { PACKAGE_VERSION } from './chunk-B4QJV7OC.js';
17
- import { PAYMENT_HEADER, AUTHORIZATION_HEADER, systemClock, extractReservedInputFields, isHttpProtocolAdapter, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, toPaymentRequiredEnvelope, NOOP_LOGGER, parseAuthorizationHeader, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, TRANSACTION_STATES } from './chunk-55AI6CLW.js';
14
+ import { x402_default } from './chunk-RQ7W3NA5.js';
15
+ import { exclusionNames, featureStatus, descriptorStatus } from './chunk-GISJ73ML.js';
16
+ import { x402OfferName } from './chunk-5CH5VFC6.js';
17
+ import { exampleObject } from './chunk-4YZULHX2.js';
18
+ import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-2PO65227.js';
19
+ import { PACKAGE_VERSION } from './chunk-25WJIUJU.js';
20
+ import { PAYMENT_HEADER, AUTHORIZATION_HEADER, systemClock, extractReservedInputFields, isHttpProtocolAdapter, toErrorEnvelope, DELIVERY_SUMMARY_META_KEY, toDeliverySummary, toPaymentRequiredEnvelope, NOOP_LOGGER, parseAuthorizationHeader, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PAYMENT_INPUT_FIELD, AUTHORIZATION_INPUT_FIELD, parseAuthorizationSubmission, TRANSACTION_STATES } from './chunk-USIXWAXZ.js';
18
21
  import { CommerceError, isCommerceError, toLogInfo, toCommerceError } from './chunk-C5YISPT6.js';
19
22
  import { isRecord } from './chunk-3M6U7ILB.js';
20
23
  import { createHash, randomUUID } from 'crypto';
@@ -35,10 +38,12 @@ var JSONRPC_INTERNAL_ERROR = -32603;
35
38
  var A2A_ERROR_TASK_NOT_FOUND = -32001;
36
39
  var A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED = -32003;
37
40
  var A2A_ERROR_UNSUPPORTED_OPERATION = -32004;
41
+ var A2A_ERROR_TASK_NOT_CANCELABLE = -32002;
38
42
  var A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED = -32005;
39
43
  var A2A_ERROR_VERSION_NOT_SUPPORTED = -32009;
40
44
  var A2A_ERROR_REASONS = /* @__PURE__ */ new Map([
41
45
  [A2A_ERROR_TASK_NOT_FOUND, "TASK_NOT_FOUND"],
46
+ [A2A_ERROR_TASK_NOT_CANCELABLE, "TASK_NOT_CANCELABLE"],
42
47
  [A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, "PUSH_NOTIFICATION_NOT_SUPPORTED"],
43
48
  [A2A_ERROR_UNSUPPORTED_OPERATION, "UNSUPPORTED_OPERATION"],
44
49
  [A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, "CONTENT_TYPE_NOT_SUPPORTED"],
@@ -51,23 +56,24 @@ function readId(value) {
51
56
  function jsonRpcResult(id, result) {
52
57
  return { jsonrpc: "2.0", id, result };
53
58
  }
54
- function jsonRpcError(id, code, message) {
59
+ function jsonRpcError(id, code, message, details = []) {
55
60
  const reason = A2A_ERROR_REASONS.get(code);
56
- const error = {
57
- code,
58
- message,
59
- ...reason !== void 0 ? {
60
- data: [
61
- {
62
- "@type": "type.googleapis.com/google.rpc.ErrorInfo",
63
- reason,
64
- domain: "a2a-protocol.org"
65
- }
66
- ]
67
- } : {}
68
- };
61
+ const data = [
62
+ ...reason !== void 0 ? [
63
+ {
64
+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",
65
+ reason,
66
+ domain: "a2a-protocol.org"
67
+ }
68
+ ] : [],
69
+ ...details
70
+ ];
71
+ const error = { code, message, ...data.length > 0 ? { data } : {} };
69
72
  return { jsonrpc: "2.0", id, error };
70
73
  }
74
+ function retryInfo(seconds) {
75
+ return { "@type": "type.googleapis.com/google.rpc.RetryInfo", retryDelay: `${seconds}s` };
76
+ }
71
77
  function parseJsonRpcRequest(rawBody) {
72
78
  let payload;
73
79
  try {
@@ -132,6 +138,205 @@ function parseJsonRpcRequest(rawBody) {
132
138
  return { ok: true, request: { id, method, params: params ?? {} } };
133
139
  }
134
140
 
141
+ // src/protocols/a2a/params.ts
142
+ function invalid(message) {
143
+ return new CommerceError("INPUT_INVALID", message);
144
+ }
145
+ function unsupported(message, a2aErrorCode) {
146
+ return new CommerceError(
147
+ "PROTOCOL_UNSUPPORTED",
148
+ message,
149
+ a2aErrorCode !== void 0 ? { details: { a2aErrorCode } } : {}
150
+ );
151
+ }
152
+ var PROTO_NAME_WORD = /_([a-z0-9])/g;
153
+ function jsonNames(value, where) {
154
+ const sentAs = /* @__PURE__ */ new Map();
155
+ const entries = [];
156
+ for (const [key, field] of Object.entries(value)) {
157
+ const name = key.replace(PROTO_NAME_WORD, (_, next) => next.toUpperCase());
158
+ const earlier = sentAs.get(name);
159
+ if (earlier !== void 0) {
160
+ throw invalid(`${where} sends "${earlier}" and "${key}", two names for one field: send one.`);
161
+ }
162
+ sentAs.set(name, key);
163
+ entries.push([name, field]);
164
+ }
165
+ return Object.fromEntries(entries);
166
+ }
167
+ function read(params, key) {
168
+ const value = params[key];
169
+ return value === null ? void 0 : value;
170
+ }
171
+ function checkTenant(params) {
172
+ const tenant = read(params, "tenant");
173
+ if (tenant === void 0 || tenant === "") return;
174
+ if (typeof tenant !== "string") throw invalid('"tenant" must be a string.');
175
+ throw unsupported('Tenants are not supported: omit "tenant" or send an empty string.');
176
+ }
177
+ function checkMetadata(params) {
178
+ const metadata = read(params, "metadata");
179
+ if (metadata !== void 0 && !isRecord(metadata)) {
180
+ throw invalid('"metadata" must be a JSON object.');
181
+ }
182
+ }
183
+ var INT32_MAX = 2147483647;
184
+ function readInteger(value, name, min, max = INT32_MAX) {
185
+ if (value === void 0) return void 0;
186
+ const n = typeof value === "number" ? value : typeof value === "string" && /^-?\d+$/.test(value) ? Number(value) : Number.NaN;
187
+ if (!Number.isInteger(n) || n < min || n > max) {
188
+ throw invalid(`"${name}" must be an integer from ${min} to ${max}.`);
189
+ }
190
+ return n;
191
+ }
192
+ function readBoolean(value, name) {
193
+ if (value === void 0) return void 0;
194
+ if (typeof value !== "boolean") throw invalid(`"${name}" must be true or false.`);
195
+ return value;
196
+ }
197
+ var UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/;
198
+ function isUtcTimestamp(value) {
199
+ if (!UTC_TIMESTAMP.test(value)) return false;
200
+ const ms = Date.parse(value);
201
+ return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 19) === value.slice(0, 19);
202
+ }
203
+ function admitsJson(range) {
204
+ const type = (range.split(";")[0] ?? "").trim().toLowerCase();
205
+ return type === A2A_JSON_MEDIA_TYPE || type === "application/*" || type === "*/*";
206
+ }
207
+ function readSendMessageParams(raw) {
208
+ const params = jsonNames(raw, "The request");
209
+ const message = params["message"];
210
+ if (isRecord(message)) {
211
+ const named = jsonNames(message, "The message");
212
+ const parts = named["parts"];
213
+ params["message"] = Array.isArray(parts) ? {
214
+ ...named,
215
+ parts: parts.map((part) => isRecord(part) ? jsonNames(part, "A message part") : part)
216
+ } : named;
217
+ }
218
+ checkTenant(params);
219
+ checkMetadata(params);
220
+ const configuration = read(params, "configuration");
221
+ if (configuration === void 0) return { params, returnImmediately: false };
222
+ if (!isRecord(configuration)) throw invalid('"configuration" must be a JSON object.');
223
+ const options = jsonNames(configuration, "The configuration");
224
+ if (read(options, "taskPushNotificationConfig") !== void 0) {
225
+ throw unsupported(
226
+ 'Push notifications are not supported: omit "configuration.taskPushNotificationConfig".',
227
+ A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED
228
+ );
229
+ }
230
+ const modes = read(options, "acceptedOutputModes");
231
+ if (modes !== void 0) {
232
+ if (!Array.isArray(modes) || !modes.every((mode) => typeof mode === "string")) {
233
+ throw invalid('"configuration.acceptedOutputModes" must be an array of media types.');
234
+ }
235
+ if (modes.length > 0 && !modes.some(admitsJson)) {
236
+ throw unsupported(
237
+ `This agent answers in ${A2A_JSON_MEDIA_TYPE} only: list it in "configuration.acceptedOutputModes", or omit the field.`,
238
+ A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED
239
+ );
240
+ }
241
+ }
242
+ const historyLength = readInteger(
243
+ read(options, "historyLength"),
244
+ "configuration.historyLength",
245
+ 0
246
+ );
247
+ return {
248
+ params,
249
+ ...historyLength !== void 0 ? { historyLength } : {},
250
+ returnImmediately: readBoolean(read(options, "returnImmediately"), "configuration.returnImmediately") ?? false
251
+ };
252
+ }
253
+ function taskOperationParams(raw) {
254
+ const params = jsonNames(raw, "The request");
255
+ checkTenant(params);
256
+ return params;
257
+ }
258
+ function readTaskId(params) {
259
+ const id = read(params, "id");
260
+ if (typeof id !== "string" || id.length === 0) {
261
+ throw invalid('The request must carry a non-empty task "id".');
262
+ }
263
+ return id;
264
+ }
265
+ function readGetTaskParams(raw) {
266
+ const params = taskOperationParams(raw);
267
+ const id = readTaskId(params);
268
+ const historyLength = readInteger(read(params, "historyLength"), "historyLength", 0);
269
+ return { id, ...historyLength !== void 0 ? { historyLength } : {} };
270
+ }
271
+ function readCancelTaskParams(raw) {
272
+ const params = taskOperationParams(raw);
273
+ checkMetadata(params);
274
+ return { id: readTaskId(params) };
275
+ }
276
+ var TASK_STATES = [
277
+ "TASK_STATE_SUBMITTED",
278
+ "TASK_STATE_WORKING",
279
+ "TASK_STATE_COMPLETED",
280
+ "TASK_STATE_FAILED",
281
+ "TASK_STATE_CANCELED",
282
+ "TASK_STATE_INPUT_REQUIRED",
283
+ "TASK_STATE_REJECTED",
284
+ "TASK_STATE_AUTH_REQUIRED"
285
+ ];
286
+ var A2A_LIST_PAGE_SIZE = { default: 50, max: 100 };
287
+ function encodePageToken(cursor) {
288
+ return Buffer.from(JSON.stringify([cursor.updatedAt, cursor.id]), "utf8").toString("base64url");
289
+ }
290
+ function decodePageToken(token) {
291
+ if (!/^[A-Za-z0-9_-]+$/.test(token)) return void 0;
292
+ let value;
293
+ try {
294
+ value = JSON.parse(Buffer.from(token, "base64url").toString("utf8"));
295
+ } catch {
296
+ return void 0;
297
+ }
298
+ if (!Array.isArray(value) || value.length !== 2) return void 0;
299
+ const [updatedAt, id] = value;
300
+ return typeof updatedAt === "string" && isUtcTimestamp(updatedAt) && typeof id === "string" && id.length > 0 ? { updatedAt, id } : void 0;
301
+ }
302
+ function readListTasksParams(raw) {
303
+ const params = taskOperationParams(raw);
304
+ const contextId = read(params, "contextId");
305
+ if (contextId !== void 0 && typeof contextId !== "string") {
306
+ throw invalid('"contextId" must be a string.');
307
+ }
308
+ const status = read(params, "status");
309
+ if (status !== void 0 && status !== "TASK_STATE_UNSPECIFIED" && !(typeof status === "string" && TASK_STATES.includes(status))) {
310
+ throw invalid('"status" must be a TaskState name, such as "TASK_STATE_COMPLETED".');
311
+ }
312
+ const pageSize = readInteger(read(params, "pageSize"), "pageSize", 1, A2A_LIST_PAGE_SIZE.max) ?? A2A_LIST_PAGE_SIZE.default;
313
+ const pageToken = read(params, "pageToken");
314
+ let after;
315
+ if (pageToken !== void 0 && pageToken !== "") {
316
+ after = typeof pageToken === "string" ? decodePageToken(pageToken) : void 0;
317
+ if (after === void 0) {
318
+ throw invalid('"pageToken" must be a nextPageToken this agent returned.');
319
+ }
320
+ }
321
+ const historyLength = readInteger(read(params, "historyLength"), "historyLength", 0);
322
+ const statusTimestampAfter = read(params, "statusTimestampAfter");
323
+ if (statusTimestampAfter !== void 0 && !(typeof statusTimestampAfter === "string" && isUtcTimestamp(statusTimestampAfter))) {
324
+ throw invalid(
325
+ '"statusTimestampAfter" must be a UTC timestamp such as "2026-01-01T00:00:00.000Z".'
326
+ );
327
+ }
328
+ const includeArtifacts = readBoolean(read(params, "includeArtifacts"), "includeArtifacts");
329
+ return {
330
+ ...typeof contextId === "string" && contextId !== "" ? { contextId } : {},
331
+ ...typeof status === "string" && status !== "TASK_STATE_UNSPECIFIED" ? { status } : {},
332
+ pageSize,
333
+ ...after !== void 0 ? { after } : {},
334
+ ...historyLength !== void 0 ? { historyLength } : {},
335
+ ...typeof statusTimestampAfter === "string" ? { statusTimestampAfter } : {},
336
+ includeArtifacts: includeArtifacts ?? false
337
+ };
338
+ }
339
+
135
340
  // src/protocols/a2a/message-mapping.ts
136
341
  var A2A_USER_ROLE = "ROLE_USER";
137
342
  var A2A_CALL_SHAPE = 'one data part {"resource": "<skill id>", "input": {...}}';
@@ -151,21 +356,26 @@ var ParamsSchema = z.object({
151
356
  taskId: z.string().optional(),
152
357
  contextId: z.string().optional()
153
358
  });
154
- function invalid(message) {
155
- return new CommerceError("INPUT_INVALID", message);
156
- }
157
- function unsupported(message, a2aErrorCode) {
158
- return new CommerceError(
159
- "PROTOCOL_UNSUPPORTED",
160
- message,
161
- a2aErrorCode !== void 0 ? { details: { a2aErrorCode } } : {}
162
- );
359
+ function readMessage(rawParams) {
360
+ const parsed = ParamsSchema.safeParse(rawParams);
361
+ if (!parsed.success) {
362
+ throw invalid(
363
+ 'Request must carry a "message" with a "role" and a "parts" array of structured data parts.'
364
+ );
365
+ }
366
+ const message = parsed.data.message;
367
+ if (message.messageId === void 0 || message.messageId.length === 0) {
368
+ throw invalid('Message must carry a non-empty "messageId".');
369
+ }
370
+ const roleProblem = userRoleProblem(message.role);
371
+ if (roleProblem !== void 0) throw invalid(roleProblem);
372
+ return parsed.data;
163
373
  }
164
374
  function assertNoContinuation(params) {
165
375
  const message = params.message;
166
376
  if (params.taskId !== void 0 || message.taskId !== void 0) {
167
377
  throw unsupported(
168
- "Task not found: only a task waiting for payment can be continued, so send a request with no taskId.",
378
+ "Task not found: send the message without a taskId to start a new task.",
169
379
  A2A_ERROR_TASK_NOT_FOUND
170
380
  );
171
381
  }
@@ -203,21 +413,10 @@ function assertSupportedPart(part) {
203
413
  }
204
414
  }
205
415
  function parseInvocation(rawParams) {
206
- const parsed = ParamsSchema.safeParse(rawParams);
207
- if (!parsed.success) {
208
- throw invalid(
209
- 'Request must carry a "message" with a "role" and a "parts" array of structured data parts.'
210
- );
211
- }
212
- const params = parsed.data;
416
+ const params = readMessage(rawParams);
213
417
  const message = params.message;
214
- if (message.messageId === void 0 || message.messageId.length === 0) {
215
- throw invalid('Message must carry a non-empty "messageId".');
216
- }
217
418
  const messageId = message.messageId;
218
419
  assertNoContinuation(params);
219
- const roleProblem = userRoleProblem(message.role);
220
- if (roleProblem !== void 0) throw invalid(roleProblem);
221
420
  if (message.parts.length === 0) {
222
421
  throw invalid("Message carries no parts: send exactly one structured data part.");
223
422
  }
@@ -270,6 +469,9 @@ function expiryMs(nowMs, expiresAt) {
270
469
  const ttl = Number.isFinite(requested) ? requested - nowMs : DEFAULT_PENDING_TTL_MS;
271
470
  return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
272
471
  }
472
+ function pendingExpiresAt(nowMs, expiresAt) {
473
+ return new Date(expiryMs(nowMs, expiresAt)).toISOString();
474
+ }
273
475
  function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
274
476
  const tasks = /* @__PURE__ */ new Map();
275
477
  const now = () => clock.now().getTime();
@@ -449,42 +651,6 @@ function skillDescription(resource) {
449
651
  }
450
652
  return base;
451
653
  }
452
- function exampleValue(schema, name) {
453
- if (!isRecord(schema)) return `<${name}>`;
454
- const examples = schema["examples"];
455
- if (Array.isArray(examples) && examples.length > 0) return examples[0];
456
- if (schema["default"] !== void 0) return schema["default"];
457
- const allowed = schema["enum"];
458
- if (Array.isArray(allowed) && allowed.length > 0) return allowed[0];
459
- const declared = schema["type"];
460
- const type = Array.isArray(declared) ? declared[0] : declared;
461
- switch (type) {
462
- case "object":
463
- return exampleObject(schema);
464
- case "array":
465
- return schema["items"] !== void 0 ? [exampleValue(schema["items"], name)] : [];
466
- case "number":
467
- case "integer":
468
- return 0;
469
- case "boolean":
470
- return false;
471
- case "null":
472
- return null;
473
- default:
474
- return `<${name}>`;
475
- }
476
- }
477
- function exampleObject(schema) {
478
- const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
479
- const required = Array.isArray(schema["required"]) ? schema["required"] : [];
480
- const example = {};
481
- for (const key of required) {
482
- if (typeof key !== "string" || key === PAYMENT_INPUT_FIELD || key === AUTHORIZATION_INPUT_FIELD)
483
- continue;
484
- example[key] = exampleValue(properties[key], key);
485
- }
486
- return example;
487
- }
488
654
  function skillExample(resource) {
489
655
  return JSON.stringify({
490
656
  resource: resource.id,
@@ -543,6 +709,63 @@ function buildAgentCard(options) {
543
709
  };
544
710
  }
545
711
 
712
+ // src/protocols/a2a/background.ts
713
+ function createBackgroundRuns(limit, logger) {
714
+ let claimed = 0;
715
+ const runs = /* @__PURE__ */ new Set();
716
+ return {
717
+ reserve() {
718
+ if (claimed >= limit) return false;
719
+ claimed += 1;
720
+ return true;
721
+ },
722
+ release() {
723
+ claimed -= 1;
724
+ },
725
+ start(work) {
726
+ const run = work().then(
727
+ () => void 0,
728
+ // Callers record task outcomes; log unexpected rejections at error
729
+ (err) => {
730
+ logger.error({ err: toLogInfo(err) }, "a2a adapter: background task failed");
731
+ }
732
+ ).finally(() => {
733
+ claimed -= 1;
734
+ runs.delete(run);
735
+ });
736
+ runs.add(run);
737
+ },
738
+ async settled() {
739
+ while (runs.size > 0) await Promise.allSettled([...runs]);
740
+ }
741
+ };
742
+ }
743
+
744
+ // src/protocols/a2a/descriptor.ts
745
+ var A2A_CAPABILITIES = [
746
+ "agent-card",
747
+ "jsonrpc",
748
+ "SendMessage",
749
+ "GetTask",
750
+ "ListTasks",
751
+ "CancelTask",
752
+ "returnImmediately",
753
+ // The x402 A2A transport, opt-in per request
754
+ "x402-extension"
755
+ ];
756
+ var A2A_UNSUPPORTED = exclusionNames(a2a_default);
757
+ function buildDescriptor(implementationVersion) {
758
+ return {
759
+ name: "a2a",
760
+ kind: "protocol",
761
+ implementationVersion,
762
+ supportedSpec: A2A_SPEC_VERSION,
763
+ capabilities: A2A_CAPABILITIES,
764
+ status: descriptorStatus(a2a_default),
765
+ unsupported: A2A_UNSUPPORTED
766
+ };
767
+ }
768
+
546
769
  // src/protocols/a2a/task-mapping.ts
547
770
  function dataPayload(body) {
548
771
  return isRecord(body) ? body : { value: body ?? null };
@@ -609,23 +832,63 @@ function failedTask(error, identity) {
609
832
  identity.statusMessageId
610
833
  );
611
834
  }
835
+ var UNCHARGED_CODES = /* @__PURE__ */ new Set([
836
+ "RESOURCE_NOT_FOUND",
837
+ "INPUT_INVALID",
838
+ "PAYMENT_INVALID",
839
+ "PAYMENT_REPLAYED",
840
+ "AUTHORIZATION_REQUIRED",
841
+ "AUTHORIZATION_INVALID",
842
+ "AUTHORIZATION_REPLAYED",
843
+ "AUTHORIZATION_PROVIDER_UNAVAILABLE"
844
+ ]);
845
+ function chargedNothing(error, proofSent) {
846
+ if (!proofSent || UNCHARGED_CODES.has(error.code)) return true;
847
+ const backend = error.code === "BACKEND_ERROR" || error.code === "BACKEND_TIMEOUT";
848
+ return backend && error.details?.["payment"] === void 0;
849
+ }
850
+ function workingTask(taskId, contextId, timestamp) {
851
+ return {
852
+ id: taskId,
853
+ contextId,
854
+ status: { state: A2A_TASK_STATE_WORKING, timestamp },
855
+ artifacts: []
856
+ };
857
+ }
858
+ function canceledTask(taskId, contextId, timestamp, messageId) {
859
+ return withStatusMessage(
860
+ { id: taskId, contextId, status: { state: A2A_TASK_STATE_CANCELED, timestamp }, artifacts: [] },
861
+ "Task canceled.",
862
+ messageId
863
+ );
864
+ }
865
+ function interruptedTask(task2) {
866
+ const error = new CommerceError(
867
+ "INTERNAL_ERROR",
868
+ "This task stopped before its result was recorded. Any payment is in the gateway records: check with the merchant before paying again."
869
+ );
870
+ return failedTask(error, {
871
+ taskId: task2.id,
872
+ contextId: task2.contextId,
873
+ artifactId: `${task2.id}-interrupted`,
874
+ statusMessageId: `${task2.id}-interrupted`,
875
+ timestamp: task2.status.timestamp
876
+ });
877
+ }
612
878
 
613
879
  // src/protocols/a2a/payment-resume.ts
614
880
  function taskResult(id, task2) {
615
881
  return jsonRpcResult(id, { task: task2 });
616
882
  }
617
- async function resumePayment(context, pendingPayments, id, params) {
883
+ var BACKGROUND_FULL = "Too many tasks are running in the background; retry shortly.";
884
+ var BACKGROUND_RETRY_SECONDS = 1;
885
+ async function resumePayment(resume, id, params, returnImmediately) {
886
+ const { context, pendingPayments } = resume;
618
887
  const message = isRecord(params) ? params["message"] : void 0;
619
888
  const taskId = isRecord(message) ? message["taskId"] : void 0;
620
- if (context === void 0 || typeof taskId !== "string") return void 0;
621
- const pending = await pendingPayments?.get(taskId);
889
+ if (typeof taskId !== "string") return void 0;
890
+ const pending = await pendingPayments.get(taskId);
622
891
  if (pending === void 0) return void 0;
623
- const messageId = isRecord(message) ? message["messageId"] : void 0;
624
- if (typeof messageId !== "string" || messageId.length === 0) {
625
- return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message must carry a non-empty "messageId".');
626
- }
627
- const roleProblem = userRoleProblem(isRecord(message) ? message["role"] : void 0);
628
- if (roleProblem !== void 0) return jsonRpcError(id, JSONRPC_INVALID_PARAMS, roleProblem);
629
892
  const contextId = isRecord(message) ? message["contextId"] : void 0;
630
893
  if (contextId !== void 0 && contextId !== pending.contextId) {
631
894
  return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message "contextId" does not match the task.');
@@ -646,43 +909,78 @@ async function resumePayment(context, pendingPayments, id, params) {
646
909
  return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
647
910
  }
648
911
  }
649
- const taken = await pendingPayments?.take(taskId);
912
+ const immediate = returnImmediately && submission.kind === "submitted";
913
+ if (immediate && !resume.background.reserve()) {
914
+ return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, BACKGROUND_FULL, [
915
+ retryInfo(BACKGROUND_RETRY_SECONDS)
916
+ ]);
917
+ }
918
+ let taken;
919
+ try {
920
+ taken = await pendingPayments.take(taskId);
921
+ } finally {
922
+ if (immediate && taken === void 0) resume.background.release();
923
+ }
650
924
  if (taken === void 0) return void 0;
651
925
  const authorization = taken.authorization ?? followUp;
652
- const statusMessageId = context.ids.next("a2a-msg");
653
- const identity = {
926
+ if (submission.kind === "rejected") {
927
+ const timestamp = context.clock.nowIso();
928
+ const declined = withStatusMessage(
929
+ {
930
+ id: taskId,
931
+ contextId: taken.contextId,
932
+ status: { state: A2A_TASK_STATE_FAILED, timestamp },
933
+ artifacts: []
934
+ },
935
+ "Payment was declined.",
936
+ context.ids.next("a2a-msg"),
937
+ paymentRejectedMetadata()
938
+ );
939
+ await resume.keep(declined, true);
940
+ return taskResult(id, declined);
941
+ }
942
+ const ids = {
654
943
  taskId,
655
944
  contextId: taken.contextId,
656
945
  artifactId: context.ids.next("a2a-artifact"),
657
- statusMessageId,
658
- timestamp: context.clock.nowIso()
946
+ statusMessageId: context.ids.next("a2a-msg")
659
947
  };
660
- if (submission.kind === "rejected") {
661
- const declined = {
662
- id: taskId,
663
- contextId: taken.contextId,
664
- status: { state: A2A_TASK_STATE_FAILED, timestamp: identity.timestamp },
665
- artifacts: []
666
- };
667
- return taskResult(
668
- id,
669
- withStatusMessage(
670
- declined,
671
- "Payment was declined.",
672
- statusMessageId,
673
- paymentRejectedMetadata()
674
- )
675
- );
676
- }
677
- return taskResult(
678
- id,
679
- await payPending(
680
- context,
681
- { ...taken, ...authorization !== void 0 ? { authorization } : {} },
682
- submission.payload,
683
- identity
684
- )
948
+ const working = withStatusMessage(
949
+ workingTask(taskId, taken.contextId, context.clock.nowIso()),
950
+ "Payment received; processing it.",
951
+ context.ids.next("a2a-msg"),
952
+ { [X402_PAYMENT_STATUS_KEY]: "payment-submitted" }
685
953
  );
954
+ resume.running.add(taskId);
955
+ if (!immediate) {
956
+ await resume.keep(working, false);
957
+ } else {
958
+ const refused = await resume.recordWorking(working);
959
+ if (refused !== void 0) {
960
+ resume.running.delete(taskId);
961
+ resume.background.release();
962
+ const failed = failedTask(refused, { ...ids, timestamp: context.clock.nowIso() });
963
+ await resume.keep(failed, true);
964
+ return taskResult(id, failed);
965
+ }
966
+ }
967
+ const pay = async () => {
968
+ try {
969
+ const { task: paid, evictable } = await payPending(
970
+ context,
971
+ { ...taken, ...authorization !== void 0 ? { authorization } : {} },
972
+ submission.payload,
973
+ ids
974
+ );
975
+ await resume.keep(paid, evictable);
976
+ return paid;
977
+ } finally {
978
+ resume.running.delete(taskId);
979
+ }
980
+ };
981
+ if (!immediate) return taskResult(id, await pay());
982
+ resume.background.start(pay);
983
+ return taskResult(id, working);
686
984
  }
687
985
  function withoutRetryDelay(error) {
688
986
  if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
@@ -695,7 +993,7 @@ function withoutRetryDelay(error) {
695
993
  ...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
696
994
  });
697
995
  }
698
- async function payPending(context, pending, payload, identity) {
996
+ async function payPending(context, pending, payload, ids) {
699
997
  const requestId = context.ids.next("a2a");
700
998
  const request = {
701
999
  requestId,
@@ -714,12 +1012,14 @@ async function payPending(context, pending, payload, identity) {
714
1012
  try {
715
1013
  const outcome = await context.pipeline.execute(request);
716
1014
  if (outcome.kind === "delivered" && outcome.payment !== void 0) {
717
- return withStatusMessage(
718
- completedTask(outcome, identity),
1015
+ const identity2 = { ...ids, timestamp: context.clock.nowIso() };
1016
+ const task2 = withStatusMessage(
1017
+ completedTask(outcome, identity2),
719
1018
  "Payment settled.",
720
- identity.statusMessageId,
1019
+ identity2.statusMessageId,
721
1020
  paymentCompletedMetadata(outcome.payment)
722
1021
  );
1022
+ return { task: task2, evictable: false };
723
1023
  }
724
1024
  error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
725
1025
  } catch (err) {
@@ -729,24 +1029,183 @@ async function payPending(context, pending, payload, identity) {
729
1029
  "a2a adapter: x402 extension payment failed"
730
1030
  );
731
1031
  }
1032
+ const identity = { ...ids, timestamp: context.clock.nowIso() };
732
1033
  const metadata = paymentFailureMetadata(error, pending.network);
733
1034
  const reason = error.details?.["reason"];
734
- let text = "Payment failed.";
1035
+ let text;
735
1036
  if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
736
1037
  text = "Payment settled, but the resource could not be delivered.";
737
1038
  } else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
738
1039
  text = error.message;
739
- } else if (!error.code.startsWith("PAYMENT_")) {
740
- text = "The resource could not be delivered.";
1040
+ } else {
1041
+ const outcome = error.code.startsWith("PAYMENT_") ? "Payment failed" : "The resource could not be delivered";
1042
+ text = `${outcome}: ${String(metadata[X402_PAYMENT_ERROR_KEY])}.`;
741
1043
  }
742
- return withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata);
1044
+ return {
1045
+ task: withStatusMessage(failedTask(error, identity), text, identity.statusMessageId, metadata),
1046
+ evictable: chargedNothing(error, true)
1047
+ };
1048
+ }
1049
+
1050
+ // src/protocols/a2a/task-operations.ts
1051
+ var NOT_FOUND = "Task not found.";
1052
+ function reported(task2, running) {
1053
+ return task2.status.state === A2A_TASK_STATE_WORKING && !running.has(task2.id) ? interruptedTask(task2) : task2;
1054
+ }
1055
+ async function getTask(ops, id, params) {
1056
+ const task2 = await ops.tasks.get(params.id);
1057
+ if (task2 === void 0) return jsonRpcError(id, A2A_ERROR_TASK_NOT_FOUND, NOT_FOUND);
1058
+ return jsonRpcResult(id, reported(task2, ops.running));
1059
+ }
1060
+ function before(a, b) {
1061
+ return a.at > b.at || a.at === b.at && a.id > b.id;
1062
+ }
1063
+ async function listTasks(ops, id, params) {
1064
+ const recorded = params.contextId === void 0 ? [] : await ops.tasks.list(params.contextId);
1065
+ const after = params.statusTimestampAfter !== void 0 ? Date.parse(params.statusTimestampAfter) : void 0;
1066
+ const matching = recorded.map((task2) => reported(task2, ops.running)).filter((task2) => params.status === void 0 || task2.status.state === params.status).filter((task2) => after === void 0 || Date.parse(task2.status.timestamp) >= after).map((task2) => ({ task: task2, key: { at: Date.parse(task2.status.timestamp), id: task2.id } })).sort((a, b) => before(a.key, b.key) ? -1 : before(b.key, a.key) ? 1 : 0);
1067
+ let start = 0;
1068
+ if (params.after !== void 0) {
1069
+ const key = { at: Date.parse(params.after.updatedAt), id: params.after.id };
1070
+ start = matching.findIndex((entry) => before(key, entry.key));
1071
+ if (start === -1) start = matching.length;
1072
+ }
1073
+ const page = matching.slice(start, start + params.pageSize);
1074
+ const last = page.at(-1);
1075
+ const more = start + page.length < matching.length;
1076
+ return jsonRpcResult(id, {
1077
+ tasks: page.map(({ task: task2 }) => {
1078
+ if (params.includeArtifacts) return task2;
1079
+ const { artifacts: _artifacts, ...rest } = task2;
1080
+ return rest;
1081
+ }),
1082
+ nextPageToken: more && last !== void 0 ? encodePageToken({ updatedAt: last.task.status.timestamp, id: last.task.id }) : "",
1083
+ pageSize: params.pageSize,
1084
+ totalSize: matching.length
1085
+ });
1086
+ }
1087
+ async function cancelTask(ops, id, params) {
1088
+ const taken = await ops.pendingPayments.take(params.id);
1089
+ if (taken !== void 0) {
1090
+ const canceled = canceledTask(
1091
+ params.id,
1092
+ taken.contextId,
1093
+ ops.clock.nowIso(),
1094
+ ops.nextMessageId()
1095
+ );
1096
+ if (!await ops.tasks.put(canceled, ops.retainedUntil(), true)) {
1097
+ throw new CommerceError("STORAGE_ERROR", "The canceled task did not fit in the task store.");
1098
+ }
1099
+ return jsonRpcResult(id, canceled);
1100
+ }
1101
+ const task2 = await ops.tasks.get(params.id);
1102
+ if (task2 === void 0) return jsonRpcError(id, A2A_ERROR_TASK_NOT_FOUND, NOT_FOUND);
1103
+ if (task2.status.state === A2A_TASK_STATE_CANCELED) return jsonRpcResult(id, task2);
1104
+ return jsonRpcError(
1105
+ id,
1106
+ A2A_ERROR_TASK_NOT_CANCELABLE,
1107
+ "Only a task waiting for payment can be canceled; this one is running or finished."
1108
+ );
1109
+ }
1110
+
1111
+ // src/protocols/a2a/task-store.ts
1112
+ function createStoredTasks(store, maxRecords) {
1113
+ return {
1114
+ put: (task2, expiresAt, evictable) => store.putTaskRecord(
1115
+ {
1116
+ id: task2.id,
1117
+ protocol: "a2a",
1118
+ groupId: task2.contextId,
1119
+ state: task2.status.state,
1120
+ updatedAt: task2.status.timestamp,
1121
+ document: task2,
1122
+ expiresAt,
1123
+ ...evictable === true ? { evictable } : {}
1124
+ },
1125
+ { maxRecords }
1126
+ ),
1127
+ async get(id) {
1128
+ const record = await store.getTaskRecord(id);
1129
+ return record?.protocol === "a2a" ? record.document : void 0;
1130
+ },
1131
+ async list(contextId) {
1132
+ const records = await store.listTaskRecords({ protocol: "a2a", groupId: contextId });
1133
+ return records.map((record) => record.document);
1134
+ }
1135
+ };
1136
+ }
1137
+ function createMemoryTasks(clock, maxRecords) {
1138
+ const tasks = /* @__PURE__ */ new Map();
1139
+ const live = (expiresAtMs) => expiresAtMs > clock.now().getTime();
1140
+ return {
1141
+ async put(task2, expiresAt, evictable = false) {
1142
+ if (!tasks.has(task2.id) && tasks.size >= maxRecords) {
1143
+ for (const [id, held] of tasks) if (!live(held.expiresAtMs)) tasks.delete(id);
1144
+ if (tasks.size >= maxRecords) {
1145
+ let oldest;
1146
+ for (const [id, held] of tasks) {
1147
+ if (held.evictable) {
1148
+ oldest = id;
1149
+ break;
1150
+ }
1151
+ }
1152
+ if (oldest === void 0) return false;
1153
+ tasks.delete(oldest);
1154
+ }
1155
+ }
1156
+ tasks.delete(task2.id);
1157
+ tasks.set(task2.id, { task: task2, expiresAtMs: Date.parse(expiresAt), evictable });
1158
+ return true;
1159
+ },
1160
+ async get(id) {
1161
+ const held = tasks.get(id);
1162
+ return held !== void 0 && live(held.expiresAtMs) ? held.task : void 0;
1163
+ },
1164
+ // ponytail: listing scans all tasks; add a context index if large stores become slow
1165
+ async list(contextId) {
1166
+ return [...tasks.values()].filter((held) => held.task.contextId === contextId && live(held.expiresAtMs)).map((held) => held.task);
1167
+ }
1168
+ };
743
1169
  }
744
1170
 
745
1171
  // src/protocols/a2a/adapter.ts
746
1172
  var MAX_REQUEST_BODY_BYTES = 256 * 1024;
747
1173
  var VERSION_PATTERN = /^(\d+\.\d+)(?:\.\d+)?$/;
748
1174
  var A2A_VERSION_PARAMETER = "A2A-Version";
1175
+ var X402_EXTENSION_ECHO = {
1176
+ [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI,
1177
+ [A2A_X_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI
1178
+ };
749
1179
  var AGENT_CARD_CACHE_CONTROL = "public, max-age=300";
1180
+ function taskLimit(value, name, bounds) {
1181
+ if (value === void 0) return bounds.default;
1182
+ if (!Number.isInteger(value) || value < bounds.min || value > bounds.max) {
1183
+ throw new CommerceError(
1184
+ "CONFIG_INVALID",
1185
+ `A2A adapter option "tasks.${name}" must be an integer from ${bounds.min} to ${bounds.max}`,
1186
+ { details: { path: `tasks.${name}` } }
1187
+ );
1188
+ }
1189
+ return value;
1190
+ }
1191
+ function storeFull() {
1192
+ return new CommerceError("GATEWAY_BUSY", "Too many answered tasks are retained; retry shortly.");
1193
+ }
1194
+ async function withParams(id, read2, run) {
1195
+ let params;
1196
+ try {
1197
+ params = read2();
1198
+ } catch (err) {
1199
+ return refusal(id, err);
1200
+ }
1201
+ return run(params);
1202
+ }
1203
+ function refusal(id, err) {
1204
+ const error = toCommerceError(err);
1205
+ const a2aErrorCode = error.details?.["a2aErrorCode"];
1206
+ const code = typeof a2aErrorCode === "number" ? a2aErrorCode : error.code === "PROTOCOL_UNSUPPORTED" ? A2A_ERROR_UNSUPPORTED_OPERATION : JSONRPC_INVALID_PARAMS;
1207
+ return jsonRpcError(id, code, error.message);
1208
+ }
750
1209
  var DEFAULT_AGENT_DESCRIPTION = "Agent Commerce Gateway: canonical commerce resources exposed as A2A skills.";
751
1210
  var A2aProtocolAdapter = class {
752
1211
  name = "a2a";
@@ -757,6 +1216,8 @@ var A2aProtocolAdapter = class {
757
1216
  agentDescription;
758
1217
  agentVersion;
759
1218
  store;
1219
+ retentionMs;
1220
+ maxRetained;
760
1221
  context;
761
1222
  started = false;
762
1223
  // The card lists only a2a-exposed resources, but a caller can name any id,
@@ -769,12 +1230,19 @@ var A2aProtocolAdapter = class {
769
1230
  cardEtag = "";
770
1231
  // Purchases waiting for an x402 extension payment
771
1232
  pendingPayments;
1233
+ // Retained responses for task lookup, listing and cancellation
1234
+ tasks;
1235
+ // Active task ids; see TaskOperations.running
1236
+ running = /* @__PURE__ */ new Set();
1237
+ background;
772
1238
  constructor(options = {}) {
773
1239
  this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH;
774
1240
  this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
775
1241
  this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
776
1242
  this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
777
1243
  this.store = options.store;
1244
+ this.retentionMs = taskLimit(options.tasks?.retentionHours, "retentionHours", A2A_TASK_RETENTION_HOURS) * 36e5;
1245
+ this.maxRetained = taskLimit(options.tasks?.maxRetained, "maxRetained", A2A_MAX_RETAINED_TASKS);
778
1246
  this.descriptor = buildDescriptor(PACKAGE_VERSION);
779
1247
  this.additionalHttpRoutes = [
780
1248
  {
@@ -807,6 +1275,8 @@ var A2aProtocolAdapter = class {
807
1275
  resources
808
1276
  });
809
1277
  this.pendingPayments = hasMethodGroup(this.store, "pending_tasks") ? createStoredPendingPayments(this.store, context.clock) : createPendingPayments(context.clock);
1278
+ this.tasks = hasMethodGroup(this.store, "task_records") ? createStoredTasks(this.store, this.maxRetained) : createMemoryTasks(context.clock, this.maxRetained);
1279
+ this.background = createBackgroundRuns(A2A_MAX_BACKGROUND_RUNS, context.logger);
810
1280
  this.cardBody = JSON.stringify(this.card);
811
1281
  this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
812
1282
  this.started = true;
@@ -841,6 +1311,7 @@ var A2aProtocolAdapter = class {
841
1311
  }
842
1312
  /** `POST <mountPath>`: the A2A JSON-RPC endpoint */
843
1313
  async handleHttp(req, res) {
1314
+ let requestId = null;
844
1315
  try {
845
1316
  if (!this.started) {
846
1317
  this.writeJson(
@@ -862,8 +1333,8 @@ var A2aProtocolAdapter = class {
862
1333
  );
863
1334
  return;
864
1335
  }
865
- const read = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);
866
- if (read.kind === "too-large") {
1336
+ const read2 = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);
1337
+ if (read2.kind === "too-large") {
867
1338
  this.writeJson(
868
1339
  res,
869
1340
  413,
@@ -875,7 +1346,7 @@ var A2aProtocolAdapter = class {
875
1346
  );
876
1347
  return;
877
1348
  }
878
- if (read.kind !== "ok") {
1349
+ if (read2.kind !== "ok") {
879
1350
  this.writeJson(
880
1351
  res,
881
1352
  200,
@@ -883,11 +1354,12 @@ var A2aProtocolAdapter = class {
883
1354
  );
884
1355
  return;
885
1356
  }
886
- const parsed = parseJsonRpcRequest(read.text);
1357
+ const parsed = parseJsonRpcRequest(read2.text);
887
1358
  if (!parsed.ok) {
888
1359
  this.writeJson(res, 200, jsonRpcError(parsed.id, parsed.error.code, parsed.error.message));
889
1360
  return;
890
1361
  }
1362
+ requestId = parsed.request.id;
891
1363
  const version = req.headers[A2A_VERSION_HEADER];
892
1364
  const declared = (Array.isArray(version) ? version[0] : version) ?? new URL(req.url ?? "/", "http://localhost").searchParams.get(A2A_VERSION_PARAMETER);
893
1365
  if (declared?.match(VERSION_PATTERN)?.[1] !== A2A_PROTOCOL_VERSION) {
@@ -902,24 +1374,21 @@ var A2aProtocolAdapter = class {
902
1374
  );
903
1375
  return;
904
1376
  }
1377
+ const activated = requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]) || requestsX402Extension(req.headers[A2A_X_EXTENSIONS_HEADER]);
905
1378
  const response = await this.dispatch(
906
1379
  parsed.request.id,
907
1380
  parsed.request.method,
908
1381
  parsed.request.params,
909
- requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER])
910
- );
911
- this.writeJson(
912
- res,
913
- 200,
914
- response,
915
- usesX402Extension(response) ? { [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI } : {}
1382
+ activated
916
1383
  );
1384
+ const echo = usesX402Extension(response) || activated && response["error"] === void 0;
1385
+ this.writeJson(res, 200, response, echo ? X402_EXTENSION_ECHO : {});
917
1386
  } catch (err) {
918
1387
  this.context?.logger.error({ err: toLogInfo(err) }, "a2a adapter: request handling failed");
919
1388
  this.writeJson(
920
1389
  res,
921
1390
  200,
922
- jsonRpcError(null, JSONRPC_INTERNAL_ERROR, "Internal server error.")
1391
+ jsonRpcError(requestId, JSONRPC_INTERNAL_ERROR, "Internal server error.")
923
1392
  );
924
1393
  }
925
1394
  }
@@ -931,13 +1400,6 @@ var A2aProtocolAdapter = class {
931
1400
  `A2A method "${method}" is not supported: this agent does not support push notifications.`
932
1401
  );
933
1402
  }
934
- if (A2A_TASK_LOOKUP_METHODS.includes(method)) {
935
- return jsonRpcError(
936
- id,
937
- A2A_ERROR_TASK_NOT_FOUND,
938
- "Task not found. Finished tasks are not retained; continue a pending payment with SendMessage."
939
- );
940
- }
941
1403
  if (A2A_UNSUPPORTED_METHODS.includes(method)) {
942
1404
  return jsonRpcError(
943
1405
  id,
@@ -945,49 +1407,198 @@ var A2aProtocolAdapter = class {
945
1407
  `A2A method "${method}" is not supported by this deployment.`
946
1408
  );
947
1409
  }
948
- if (method !== A2A_METHOD_SEND_MESSAGE) {
949
- return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method "${method}".`);
1410
+ const raw = isRecord(params) ? params : {};
1411
+ const ops = this.operations();
1412
+ switch (method) {
1413
+ case A2A_METHOD_SEND_MESSAGE:
1414
+ break;
1415
+ case A2A_METHOD_GET_TASK:
1416
+ return withParams(
1417
+ id,
1418
+ () => readGetTaskParams(raw),
1419
+ (read2) => getTask(ops, id, read2)
1420
+ );
1421
+ case A2A_METHOD_LIST_TASKS:
1422
+ return withParams(
1423
+ id,
1424
+ () => readListTasksParams(raw),
1425
+ (read2) => listTasks(ops, id, read2)
1426
+ );
1427
+ case A2A_METHOD_CANCEL_TASK:
1428
+ return withParams(
1429
+ id,
1430
+ () => readCancelTaskParams(raw),
1431
+ (read2) => cancelTask(ops, id, read2)
1432
+ );
1433
+ default:
1434
+ return jsonRpcError(id, JSONRPC_METHOD_NOT_FOUND, `Unknown method "${method}".`);
1435
+ }
1436
+ let request;
1437
+ try {
1438
+ request = readSendMessageParams(raw);
1439
+ readMessage(request.params);
1440
+ } catch (err) {
1441
+ return refusal(id, err);
950
1442
  }
951
- const resumed = await resumePayment(this.context, this.pendingPayments, id, params);
1443
+ const resumed = await resumePayment(
1444
+ this.resume(ops),
1445
+ id,
1446
+ request.params,
1447
+ request.returnImmediately
1448
+ );
952
1449
  if (resumed !== void 0) return resumed;
1450
+ const known = await this.answerKnownTask(ops, id, request.params);
1451
+ if (known !== void 0) return known;
953
1452
  let invocation;
954
1453
  try {
955
- invocation = parseInvocation(params);
1454
+ invocation = parseInvocation(request.params);
956
1455
  } catch (err) {
957
- const error = toCommerceError(err);
958
- const a2aErrorCode = error.details?.["a2aErrorCode"];
959
- const code = typeof a2aErrorCode === "number" ? a2aErrorCode : error.code === "PROTOCOL_UNSUPPORTED" ? A2A_ERROR_UNSUPPORTED_OPERATION : JSONRPC_INVALID_PARAMS;
960
- return jsonRpcError(id, code, error.message);
1456
+ return refusal(id, err);
961
1457
  }
962
- return this.execute(id, invocation, x402Extension);
1458
+ return this.execute(ops, id, invocation, x402Extension, request.returnImmediately);
963
1459
  }
964
- // One accepted invocation, one `pipeline.execute()`
965
- async execute(id, invocation, x402Extension) {
966
- const context = this.context;
967
- if (context === void 0) {
1460
+ // Collect task-operation state after startup; handleHttp returns 503 before startup
1461
+ operations() {
1462
+ const { context, tasks, pendingPayments } = this;
1463
+ if (context === void 0 || tasks === void 0 || pendingPayments === void 0) {
1464
+ throw new CommerceError("INTERNAL_ERROR", "A2A adapter is not running.");
1465
+ }
1466
+ return {
1467
+ tasks,
1468
+ pendingPayments,
1469
+ running: this.running,
1470
+ clock: context.clock,
1471
+ retainedUntil: () => this.retainedUntil(context),
1472
+ nextMessageId: () => context.ids.next("a2a-msg")
1473
+ };
1474
+ }
1475
+ resume(ops) {
1476
+ const { context, background } = this;
1477
+ if (context === void 0 || background === void 0) {
1478
+ throw new CommerceError("INTERNAL_ERROR", "A2A adapter is not running.");
1479
+ }
1480
+ return {
1481
+ context,
1482
+ pendingPayments: ops.pendingPayments,
1483
+ keep: (task2, evictable) => this.keep(ops, task2, evictable),
1484
+ running: this.running,
1485
+ background,
1486
+ recordWorking: (task2) => this.recordWorking(ops, task2)
1487
+ };
1488
+ }
1489
+ retainedUntil(context) {
1490
+ return new Date(context.clock.now().getTime() + this.retentionMs).toISOString();
1491
+ }
1492
+ // Retain a response without failing the call. Log capacity refusals at warn
1493
+ // and write exceptions at error; return false in either case.
1494
+ async keep(ops, task2, evictable) {
1495
+ const logger = this.context?.logger;
1496
+ try {
1497
+ if (await ops.tasks.put(task2, ops.retainedUntil(), evictable)) return true;
1498
+ logger?.warn(
1499
+ { state: task2.status.state },
1500
+ "a2a adapter: task not retained: the task store is full"
1501
+ );
1502
+ } catch (err) {
1503
+ logger?.error(
1504
+ { state: task2.status.state, err: toLogInfo(err) },
1505
+ "a2a adapter: task not retained"
1506
+ );
1507
+ }
1508
+ return false;
1509
+ }
1510
+ // Store the working response before starting background work; return any
1511
+ // failure so the caller can stop admission
1512
+ async recordWorking(ops, task2) {
1513
+ try {
1514
+ return await ops.tasks.put(task2, ops.retainedUntil()) ? void 0 : storeFull();
1515
+ } catch (err) {
1516
+ this.context?.logger.error({ err: toLogInfo(err) }, "a2a adapter: working task not recorded");
1517
+ return toCommerceError(err);
1518
+ }
1519
+ }
1520
+ /**
1521
+ * Reject further messages on a retained task after the pending-payment path
1522
+ * declines it, including tasks taken by another call. Terminal tasks accept
1523
+ * no further messages (A2A 1.0.1 section 3.1.1). Missing records fall through
1524
+ * to `parseInvocation`, which returns `TaskNotFoundError`.
1525
+ */
1526
+ async answerKnownTask(ops, id, params) {
1527
+ const message = params["message"];
1528
+ const taskId = isRecord(message) ? message["taskId"] : void 0;
1529
+ if (typeof taskId !== "string") return void 0;
1530
+ const task2 = await ops.tasks.get(taskId);
1531
+ if (task2 === void 0) return void 0;
1532
+ const contextId = isRecord(message) ? message["contextId"] : void 0;
1533
+ if (contextId !== void 0 && contextId !== task2.contextId) {
1534
+ return jsonRpcError(
1535
+ id,
1536
+ JSONRPC_INVALID_PARAMS,
1537
+ 'Message "contextId" does not match the task.'
1538
+ );
1539
+ }
1540
+ return jsonRpcError(
1541
+ id,
1542
+ A2A_ERROR_UNSUPPORTED_OPERATION,
1543
+ "This task accepts no further messages: send a new message without a taskId."
1544
+ );
1545
+ }
1546
+ // Return the purchase result, or a stored working task for returnImmediately
1547
+ async execute(ops, id, invocation, x402Extension, returnImmediately) {
1548
+ const { context, background } = this;
1549
+ if (context === void 0 || background === void 0) {
968
1550
  return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, "A2A adapter is not running.");
969
1551
  }
1552
+ const ids = this.taskIds(context);
1553
+ const now = () => ({ ...ids, timestamp: context.clock.nowIso() });
970
1554
  const resource = this.skillsById.get(invocation.resourceId);
971
1555
  if (resource === void 0) {
972
- return taskResult(
973
- id,
974
- failedTask(
975
- new CommerceError(
976
- "RESOURCE_NOT_FOUND",
977
- `Unknown canonical resource "${invocation.resourceId}".`
978
- ),
979
- this.taskIdentity(context, context.ids.next("a2a"))
980
- )
1556
+ const unknown = failedTask(
1557
+ new CommerceError(
1558
+ "RESOURCE_NOT_FOUND",
1559
+ `Unknown canonical resource "${invocation.resourceId}".`
1560
+ ),
1561
+ now()
981
1562
  );
1563
+ await this.keep(ops, unknown, true);
1564
+ return taskResult(id, unknown);
1565
+ }
1566
+ const run = () => this.purchase(ops, context, ids, invocation, resource, x402Extension);
1567
+ if (!returnImmediately) return taskResult(id, await run());
1568
+ if (!background.reserve()) {
1569
+ return taskResult(id, failedTask(new CommerceError("GATEWAY_BUSY", BACKGROUND_FULL), now()));
982
1570
  }
1571
+ const working = workingTask(ids.taskId, ids.contextId, context.clock.nowIso());
1572
+ this.running.add(ids.taskId);
1573
+ const refused = await this.recordWorking(ops, working);
1574
+ if (refused !== void 0) {
1575
+ this.running.delete(ids.taskId);
1576
+ background.release();
1577
+ return taskResult(id, failedTask(refused, now()));
1578
+ }
1579
+ background.start(async () => {
1580
+ try {
1581
+ await run();
1582
+ } finally {
1583
+ this.running.delete(ids.taskId);
1584
+ }
1585
+ });
1586
+ return taskResult(id, working);
1587
+ }
1588
+ // Execute the purchase through the pipeline and retain its response when possible
1589
+ async purchase(ops, context, ids, invocation, resource, x402Extension) {
1590
+ const now = () => ({ ...ids, timestamp: context.clock.nowIso() });
983
1591
  const requestId = context.ids.next("a2a");
984
- const identity = this.taskIdentity(context, requestId);
1592
+ let task2;
1593
+ let evictable = true;
1594
+ let proofSent = false;
985
1595
  try {
986
1596
  const { input, payment, authorization } = extractReservedInputFields(
987
1597
  invocation.input,
988
1598
  resource,
989
1599
  requestId
990
1600
  );
1601
+ proofSent = payment !== void 0;
991
1602
  const request = {
992
1603
  requestId,
993
1604
  resourceId: invocation.resourceId,
@@ -998,58 +1609,72 @@ var A2aProtocolAdapter = class {
998
1609
  ...authorization !== void 0 ? { authorization } : {}
999
1610
  };
1000
1611
  const outcome = await context.pipeline.execute(request);
1612
+ const identity = now();
1001
1613
  if (outcome.kind !== "payment-required") {
1002
- return taskResult(id, completedTask(outcome, identity));
1003
- }
1004
- const task2 = paymentRequiredTask(outcome, identity);
1005
- const envelope = outcome.requirement.challenge.envelope;
1006
- if (!x402Extension || outcome.requirement.provider !== "x402" || !isRecord(envelope)) {
1007
- return taskResult(id, task2);
1008
- }
1009
- const network = outcome.requirement.network;
1010
- const held = await this.pendingPayments?.put(
1011
- identity.taskId,
1012
- {
1013
- contextId: identity.contextId,
1014
- resourceId: invocation.resourceId,
1015
- input,
1016
- ...authorization !== void 0 ? { authorization } : {},
1017
- ...network !== void 0 ? { network } : {}
1018
- },
1019
- outcome.requirement.expiresAt
1020
- );
1021
- if (held === false) {
1022
- return taskResult(
1023
- id,
1024
- failedTask(
1025
- new CommerceError(
1026
- "GATEWAY_BUSY",
1027
- "Too many unpaid purchases are waiting for payment; retry shortly."
1028
- ),
1029
- identity
1030
- )
1031
- );
1614
+ task2 = completedTask(outcome, identity);
1615
+ evictable = outcome.payment === void 0;
1616
+ } else {
1617
+ task2 = paymentRequiredTask(outcome, identity);
1618
+ const envelope = outcome.requirement.challenge.envelope;
1619
+ if (x402Extension && outcome.requirement.provider === "x402" && isRecord(envelope)) {
1620
+ const network = outcome.requirement.network;
1621
+ return await this.awaitPayment(
1622
+ ops,
1623
+ identity,
1624
+ inputRequired(task2, paymentRequiredMetadata(envelope), identity.statusMessageId),
1625
+ {
1626
+ contextId: identity.contextId,
1627
+ resourceId: invocation.resourceId,
1628
+ input,
1629
+ ...authorization !== void 0 ? { authorization } : {},
1630
+ ...network !== void 0 ? { network } : {}
1631
+ },
1632
+ pendingExpiresAt(context.clock.now().getTime(), outcome.requirement.expiresAt)
1633
+ );
1634
+ }
1032
1635
  }
1033
- return taskResult(
1034
- id,
1035
- inputRequired(task2, paymentRequiredMetadata(envelope), identity.statusMessageId)
1036
- );
1037
1636
  } catch (err) {
1038
1637
  const error = toCommerceError(err);
1039
1638
  context.logger.warn(
1040
1639
  { resourceId: invocation.resourceId, requestId, err: toLogInfo(error) },
1041
1640
  "a2a adapter: execution failed"
1042
1641
  );
1043
- return taskResult(id, failedTask(error, identity));
1642
+ task2 = failedTask(error, now());
1643
+ evictable = chargedNothing(error, proofSent);
1044
1644
  }
1645
+ await this.keep(ops, task2, evictable);
1646
+ return task2;
1045
1647
  }
1046
- taskIdentity(context, requestId) {
1648
+ /**
1649
+ * Record the input-required response before holding its pending purchase,
1650
+ * using the same expiry. Refuse the purchase if the record does not fit.
1651
+ * If pending storage throws, `execute` returns a failed task and attempts
1652
+ * to replace the waiting response with it.
1653
+ */
1654
+ async awaitPayment(ops, identity, waiting, purchase, expiresAt) {
1655
+ if (!await ops.tasks.put(waiting, expiresAt)) {
1656
+ return failedTask(storeFull(), identity);
1657
+ }
1658
+ if (!await ops.pendingPayments.put(waiting.id, purchase, expiresAt)) {
1659
+ const busy = failedTask(
1660
+ new CommerceError(
1661
+ "GATEWAY_BUSY",
1662
+ "Too many unpaid purchases are waiting for payment; retry shortly."
1663
+ ),
1664
+ identity
1665
+ );
1666
+ await this.keep(ops, busy, true);
1667
+ return busy;
1668
+ }
1669
+ return waiting;
1670
+ }
1671
+ // Generate access keys independently of IdGenerator; keep them out of log fields
1672
+ taskIds(context) {
1047
1673
  return {
1048
- taskId: requestId,
1049
- contextId: context.ids.next("a2a-ctx"),
1674
+ taskId: randomUUID(),
1675
+ contextId: randomUUID(),
1050
1676
  artifactId: context.ids.next("a2a-artifact"),
1051
- statusMessageId: context.ids.next("a2a-msg"),
1052
- timestamp: context.clock.nowIso()
1677
+ statusMessageId: context.ids.next("a2a-msg")
1053
1678
  };
1054
1679
  }
1055
1680
  async health() {
@@ -1061,11 +1686,15 @@ var A2aProtocolAdapter = class {
1061
1686
  }
1062
1687
  async stop() {
1063
1688
  this.started = false;
1689
+ await this.background?.settled();
1690
+ this.background = void 0;
1064
1691
  this.card = void 0;
1065
1692
  this.cardBody = "";
1066
1693
  this.cardEtag = "";
1067
1694
  this.pendingPayments?.clear();
1068
1695
  this.pendingPayments = void 0;
1696
+ this.tasks = void 0;
1697
+ this.running.clear();
1069
1698
  this.skillsById = /* @__PURE__ */ new Map();
1070
1699
  this.context = void 0;
1071
1700
  }
@@ -1077,7 +1706,8 @@ var A2aProtocolAdapter = class {
1077
1706
  };
1078
1707
  function usesX402Extension(response) {
1079
1708
  const result = response["result"];
1080
- return result?.task?.status.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true;
1709
+ const task2 = isRecord(result) && isRecord(result["task"]) ? result["task"] : result;
1710
+ return task2?.status?.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true;
1081
1711
  }
1082
1712
  function matchesEtag(header2, etag) {
1083
1713
  if (header2 === void 0) return false;
@@ -1115,6 +1745,30 @@ function canonicalInput(request) {
1115
1745
  return input;
1116
1746
  }
1117
1747
 
1748
+ // src/protocols/acp/descriptor.ts
1749
+ var ACP_CAPABILITIES = [
1750
+ "rest transport",
1751
+ "well-known discovery",
1752
+ "bearer authentication",
1753
+ "API-Version enforcement",
1754
+ // Forwarded as received: the gateway verifies neither signature header
1755
+ "request header forwarding to the merchant",
1756
+ "checkout service",
1757
+ ...ACP_CHECKOUT_OPERATIONS
1758
+ ];
1759
+ var ACP_UNSUPPORTED = exclusionNames(acp_default);
1760
+ function buildDescriptor2(implementationVersion) {
1761
+ return {
1762
+ name: "acp",
1763
+ kind: "protocol",
1764
+ implementationVersion,
1765
+ supportedSpec: ACP_SPEC_VERSION,
1766
+ capabilities: ACP_CAPABILITIES,
1767
+ status: descriptorStatus(acp_default),
1768
+ unsupported: ACP_UNSUPPORTED
1769
+ };
1770
+ }
1771
+
1118
1772
  // src/protocols/acp/discovery.ts
1119
1773
  function buildAcpDiscoveryDocument(options) {
1120
1774
  const metadata = options.metadata ?? {};
@@ -5516,8 +6170,8 @@ async function guardAcpRequest(req, options) {
5516
6170
  }
5517
6171
  idempotencyKey = presentedKey;
5518
6172
  }
5519
- const read = await readCappedBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);
5520
- if (read.kind === "too-large") {
6173
+ const read2 = await readCappedBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);
6174
+ if (read2.kind === "too-large") {
5521
6175
  return failed(
5522
6176
  acpFailure(
5523
6177
  413,
@@ -5527,7 +6181,7 @@ async function guardAcpRequest(req, options) {
5527
6181
  )
5528
6182
  );
5529
6183
  }
5530
- if (read.kind === "unreadable") {
6184
+ if (read2.kind === "unreadable") {
5531
6185
  return failed(
5532
6186
  acpFailure(
5533
6187
  400,
@@ -5537,7 +6191,7 @@ async function guardAcpRequest(req, options) {
5537
6191
  )
5538
6192
  );
5539
6193
  }
5540
- const raw = read.text;
6194
+ const raw = read2.text;
5541
6195
  const contentTypeFailure = checkContentType(header(req, "content-type"), raw, route);
5542
6196
  if (contentTypeFailure !== void 0) return failed(contentTypeFailure);
5543
6197
  const definition = REQUEST_DEFINITIONS[route.operation];
@@ -6313,6 +6967,7 @@ var CORS_HEADERS = [
6313
6967
  "mcp-name",
6314
6968
  "a2a-version",
6315
6969
  "a2a-extensions",
6970
+ "x-a2a-extensions",
6316
6971
  "api-version",
6317
6972
  "idempotency-key",
6318
6973
  "request-id",
@@ -6328,7 +6983,9 @@ var CORS_EXPOSED_HEADERS = [
6328
6983
  "idempotency-key",
6329
6984
  "request-id",
6330
6985
  "idempotent-replayed",
6331
- "retry-after"
6986
+ "retry-after",
6987
+ "a2a-extensions",
6988
+ "x-a2a-extensions"
6332
6989
  ].join(",");
6333
6990
  function buildAccessControlHook(options) {
6334
6991
  const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));
@@ -6742,6 +7399,7 @@ function createReadinessProbe(options, ttlMs = READINESS_TTL_MS) {
6742
7399
 
6743
7400
  // src/gateway/well-known.ts
6744
7401
  var GATEWAY_SUPPORTED_SPEC = "agent-commerce/v1.0.0";
7402
+ var QUOTE_STATUS = featureStatus(x402_default, "erc-8409-quotes");
6745
7403
  function publicHealth(health) {
6746
7404
  const { detail: _detail, ...rest } = health;
6747
7405
  return rest;
@@ -6754,9 +7412,15 @@ function publicProtocols(protocols) {
6754
7412
  acp: { enabled: protocols.acp.enabled, mountPath: protocols.acp.mountPath }
6755
7413
  };
6756
7414
  }
6757
- function publicOffer(option, statuses) {
7415
+ function offerHealth(health, offer) {
7416
+ const name = x402OfferName(offer);
7417
+ const component = health?.components?.find((candidate) => candidate.name === name);
7418
+ if (component === void 0) return {};
7419
+ const { status, undetermined } = component;
7420
+ return { status, ...undetermined !== void 0 ? { undetermined } : {} };
7421
+ }
7422
+ function publicOffer(option, health) {
6758
7423
  const { network, asset, assetName, assetVersion, assetDecimals, payTo, assetTransferMethod } = option;
6759
- const status = statuses.get(x402OfferName(option));
6760
7424
  return {
6761
7425
  network,
6762
7426
  asset,
@@ -6765,7 +7429,7 @@ function publicOffer(option, statuses) {
6765
7429
  assetDecimals,
6766
7430
  payTo,
6767
7431
  ...assetTransferMethod !== void 0 ? { assetTransferMethod } : {},
6768
- ...status !== void 0 ? { status } : {}
7432
+ ...offerHealth(health, option)
6769
7433
  };
6770
7434
  }
6771
7435
  function flowOverrides(flows) {
@@ -6775,7 +7439,7 @@ function publicQuote(providers) {
6775
7439
  const x402 = providers.find((provider) => provider.name === "x402");
6776
7440
  if (x402?.quote === void 0) return void 0;
6777
7441
  const { issuer, requestScheme, extension } = x402.quote;
6778
- return { issuer, requestScheme, extension, status: "experimental" };
7442
+ return { issuer, requestScheme, extension, status: QUOTE_STATUS };
6779
7443
  }
6780
7444
  function buildWellKnownDocument(options) {
6781
7445
  const adapters = options.adapters.map(({ descriptor, health }) => ({
@@ -6783,10 +7447,9 @@ function buildWellKnownDocument(options) {
6783
7447
  health: publicHealth(health)
6784
7448
  }));
6785
7449
  const { x402, mpp } = options.config.payments;
6786
- const x402Health = options.paymentHealth?.find((probed) => probed.name === "x402")?.health;
6787
- const offerStatuses = new Map(
6788
- (x402Health?.components ?? []).map((component) => [component.name, component.status])
6789
- );
7450
+ const probed = (name) => options.paymentHealth?.find((provider) => provider.name === name)?.health;
7451
+ const x402Health = probed("x402");
7452
+ const x402Options = x402?.options !== void 0 && x402.options.length > 1 ? x402.options : [];
6790
7453
  const quote = publicQuote(options.paymentProviders);
6791
7454
  return {
6792
7455
  gateway: {
@@ -6819,12 +7482,12 @@ function buildWellKnownDocument(options) {
6819
7482
  ),
6820
7483
  paymentFlow: x402.paymentFlow ?? X402_DEFAULT_PAYMENT_FLOW,
6821
7484
  ...flowOverrides(x402.resourcePaymentFlows),
6822
- ...x402.options !== void 0 && x402.options.length > 1 ? { options: x402.options.map((option) => publicOffer(option, offerStatuses)) } : {},
7485
+ ...x402Options.length > 0 ? { options: x402Options.map((option) => publicOffer(option, x402Health)) } : offerHealth(x402Health, x402),
6823
7486
  ...x402.resourceOptions !== void 0 ? {
6824
7487
  resourceOptions: Object.fromEntries(
6825
7488
  Object.entries(x402.resourceOptions).map(([id, list]) => [
6826
7489
  id,
6827
- list.map((option) => publicOffer(option, offerStatuses))
7490
+ list.map((option) => publicOffer(option, x402Health))
6828
7491
  ])
6829
7492
  )
6830
7493
  } : {},
@@ -6843,7 +7506,13 @@ function buildWellKnownDocument(options) {
6843
7506
  facilitator: { mode: mpp.facilitator.mode },
6844
7507
  mode: resolveDeploymentMode(requireX402Network(mpp.network, "payments.mpp.network")),
6845
7508
  paymentFlow: mpp.paymentFlow ?? MPP_DEFAULT_PAYMENT_FLOW,
6846
- ...flowOverrides(mpp.resourcePaymentFlows)
7509
+ ...flowOverrides(mpp.resourcePaymentFlows),
7510
+ // MPP settles through an x402 provider, which names the offer
7511
+ ...offerHealth(probed("mpp"), {
7512
+ network: mpp.network,
7513
+ asset: mpp.asset,
7514
+ payTo: mpp.recipient
7515
+ })
6847
7516
  }
6848
7517
  } : {}
6849
7518
  }
@@ -7447,9 +8116,9 @@ async function runGateway(options = {}) {
7447
8116
  const { core: logger } = createGatewayLogger({ name: config.merchant.id });
7448
8117
  const paymentProviders = await createConfiguredPaymentProviders(config.payments, logger);
7449
8118
  const ap2 = config.authorization?.ap2;
7450
- const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-O3HJSS2E.js')) : void 0;
8119
+ const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-SJZAZQIR.js')) : void 0;
7451
8120
  const mcp = config.protocols.mcp;
7452
- const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-G2D2Z77G.js')) : void 0;
8121
+ const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-F3EQQWDZ.js')) : void 0;
7453
8122
  const acp = config.protocols.acp;
7454
8123
  const ap2Replay = ap2?.enabled ? ap2.replay?.path : void 0;
7455
8124
  const acpIdempotency = acp.enabled ? acp.idempotency.path : void 0;
@@ -7487,7 +8156,12 @@ async function runGateway(options = {}) {
7487
8156
  }
7488
8157
  const protocolAdapters = [];
7489
8158
  if (mcpModule !== void 0) {
7490
- protocolAdapters.push(mcpModule.createMcpAdapter({ mountPath: mcp.mountPath }));
8159
+ protocolAdapters.push(
8160
+ mcpModule.createMcpAdapter({
8161
+ mountPath: mcp.mountPath,
8162
+ ...mcp.registry !== void 0 ? { serverName: mcp.registry.name, serverVersion: mcp.registry.version } : {}
8163
+ })
8164
+ );
7491
8165
  }
7492
8166
  if (config.protocols.a2a.enabled) {
7493
8167
  protocolAdapters.push(
@@ -7496,7 +8170,8 @@ async function runGateway(options = {}) {
7496
8170
  // The Agent Card names the merchant, not the software: a client
7497
8171
  // picking between agents is choosing whose resources to buy
7498
8172
  agentName: config.merchant.name,
7499
- store
8173
+ store,
8174
+ ...config.protocols.a2a.tasks !== void 0 ? { tasks: config.protocols.a2a.tasks } : {}
7500
8175
  })
7501
8176
  );
7502
8177
  }
@@ -7599,5 +8274,5 @@ function printStartupError(error) {
7599
8274
  }
7600
8275
 
7601
8276
  export { printStartupError, runGateway };
7602
- //# sourceMappingURL=run-BHODKC6H.js.map
7603
- //# sourceMappingURL=run-BHODKC6H.js.map
8277
+ //# sourceMappingURL=run-C3VWMM57.js.map
8278
+ //# sourceMappingURL=run-C3VWMM57.js.map