@devlab.group/agent-commerce 2.8.0 → 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.
- package/README.md +19 -17
- package/dist/ap2.js +2 -2
- package/dist/{chunk-WDD2ZUR3.js → chunk-46Y5M7BA.js} +3 -2
- package/dist/chunk-46Y5M7BA.js.map +1 -0
- package/dist/{chunk-QZW5YL3G.js → chunk-5Q6W7YTK.js} +3 -3
- package/dist/{chunk-QZW5YL3G.js.map → chunk-5Q6W7YTK.js.map} +1 -1
- package/dist/{chunk-ENK63GKR.js → chunk-JF45GSNA.js} +3 -3
- package/dist/{chunk-ENK63GKR.js.map → chunk-JF45GSNA.js.map} +1 -1
- package/dist/{cli/chunk-APC5BTQM.js → chunk-RF3DFVXH.js} +2 -2
- package/dist/{chunk-IWXVQYG5.js.map → chunk-RF3DFVXH.js.map} +1 -1
- package/dist/cli/{ap2-GYKFGE66.js → ap2-SJZAZQIR.js} +5 -5
- package/dist/cli/{ap2-GYKFGE66.js.map → ap2-SJZAZQIR.js.map} +1 -1
- package/dist/cli/chunk-25WJIUJU.js +8 -0
- package/dist/cli/{chunk-SAAT2XFX.js.map → chunk-25WJIUJU.js.map} +1 -1
- package/dist/cli/{chunk-DKWO6LLX.js → chunk-4WPHZLVO.js} +3 -2
- package/dist/cli/chunk-4WPHZLVO.js.map +1 -0
- package/dist/cli/chunk-IJFPWT4I.js +435 -0
- package/dist/cli/chunk-IJFPWT4I.js.map +1 -0
- package/dist/cli/{chunk-VWQMSWDF.js → chunk-K34CRXKX.js} +3 -3
- package/dist/cli/{chunk-VWQMSWDF.js.map → chunk-K34CRXKX.js.map} +1 -1
- package/dist/cli/{chunk-WFIR374D.js → chunk-L264N3ZV.js} +41 -5
- package/dist/cli/chunk-L264N3ZV.js.map +1 -0
- package/dist/cli/{chunk-SYXLQ5BS.js → chunk-NM7V2Y4I.js} +5 -5
- package/dist/cli/{chunk-SYXLQ5BS.js.map → chunk-NM7V2Y4I.js.map} +1 -1
- package/dist/cli/{chunk-3PGFOEVJ.js → chunk-SHIA2B6G.js} +32 -6
- package/dist/cli/chunk-SHIA2B6G.js.map +1 -0
- package/dist/cli/{chunk-YXXPZFWC.js → chunk-U3SEGD4H.js} +126 -18
- package/dist/cli/chunk-U3SEGD4H.js.map +1 -0
- package/dist/{chunk-IWXVQYG5.js → cli/chunk-UV23DWUY.js} +2 -2
- package/dist/cli/{chunk-APC5BTQM.js.map → chunk-UV23DWUY.js.map} +1 -1
- package/dist/cli/{config-JWMHWVRT.js → config-IBG46HTQ.js} +6 -6
- package/dist/cli/{config-JWMHWVRT.js.map → config-IBG46HTQ.js.map} +1 -1
- package/dist/cli/index.js +33 -13
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-OW5GY7TT.js → mcp-F3EQQWDZ.js} +3 -3
- package/dist/cli/{mcp-OW5GY7TT.js.map → mcp-F3EQQWDZ.js.map} +1 -1
- package/dist/cli/payment-providers-FPTGQBU7.js +6 -0
- package/dist/cli/{payment-providers-QL2BJYMD.js.map → payment-providers-FPTGQBU7.js.map} +1 -1
- package/dist/cli/{provider-3A2LVEQS.js → provider-XACFJ7MG.js} +4 -4
- package/dist/cli/{provider-3A2LVEQS.js.map → provider-XACFJ7MG.js.map} +1 -1
- package/dist/cli/receipts-AXCPPGOK.js +9 -0
- package/dist/cli/{receipts-FQUFGEQD.js.map → receipts-AXCPPGOK.js.map} +1 -1
- package/dist/cli/{run-KF5OQYPL.js → run-C3VWMM57.js} +830 -184
- package/dist/cli/run-C3VWMM57.js.map +1 -0
- package/dist/cli/{x402-5A7CVCIJ.js → x402-SUXWULOP.js} +5 -5
- package/dist/cli/{x402-5A7CVCIJ.js.map → x402-SUXWULOP.js.map} +1 -1
- package/dist/index.d.ts +74 -31
- package/dist/index.js +1290 -255
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/mpp.js +2 -2
- package/dist/{store-BzgwHOPu.d.ts → store-04pazhFP.d.ts} +52 -1
- package/dist/testing.js +468 -273
- package/dist/testing.js.map +1 -1
- package/dist/x402.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-WDD2ZUR3.js.map +0 -1
- package/dist/cli/chunk-3PGFOEVJ.js.map +0 -1
- package/dist/cli/chunk-6BWEHQPJ.js +0 -215
- package/dist/cli/chunk-6BWEHQPJ.js.map +0 -1
- package/dist/cli/chunk-DKWO6LLX.js.map +0 -1
- package/dist/cli/chunk-SAAT2XFX.js +0 -8
- package/dist/cli/chunk-WFIR374D.js.map +0 -1
- package/dist/cli/chunk-YXXPZFWC.js.map +0 -1
- package/dist/cli/payment-providers-QL2BJYMD.js +0 -6
- package/dist/cli/receipts-FQUFGEQD.js +0 -9
- package/dist/cli/run-KF5OQYPL.js.map +0 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-
|
|
1
|
+
import { createConfiguredPaymentProviders, importOptionalPeer } from './chunk-NM7V2Y4I.js';
|
|
2
2
|
import { settlementResponse, settlementResponseFromDetails, settlementFailure, x402ErrorCode, x402RefusalStatus } from './chunk-THH7Y3OO.js';
|
|
3
|
-
import { a2a_default, acp_default
|
|
4
|
-
import { loadConfig } from './chunk-
|
|
5
|
-
import { ACP_CHECKOUT_OPERATIONS, HttpBackendExecutor, createResourceRegistry, assertRetrySupport, createStoreEventSink, createExecutionPipeline, ACP_WELL_KNOWN_PATH, 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-
|
|
6
|
-
import { hasMethodGroup } from './chunk-
|
|
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
7
|
import { readCappedBody, createBearerCheck, joinUrl } from './chunk-RWBUHDU7.js';
|
|
8
|
-
import { createSqliteReceiptStore } from './chunk-
|
|
8
|
+
import { createSqliteReceiptStore } from './chunk-U3SEGD4H.js';
|
|
9
9
|
import { openSqliteDatabase } from './chunk-6EBDOH37.js';
|
|
10
|
-
import { PAYMENT_KEY_ENDPOINT_PREFIX } from './chunk-
|
|
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';
|
|
@@ -16,7 +16,7 @@ import { exclusionNames, featureStatus, descriptorStatus } from './chunk-GISJ73M
|
|
|
16
16
|
import { x402OfferName } from './chunk-5CH5VFC6.js';
|
|
17
17
|
import { exampleObject } from './chunk-4YZULHX2.js';
|
|
18
18
|
import { X402_DEFAULT_PAYMENT_FLOW, resolveDeploymentMode, requireX402Network } from './chunk-2PO65227.js';
|
|
19
|
-
import { PACKAGE_VERSION } from './chunk-
|
|
19
|
+
import { PACKAGE_VERSION } from './chunk-25WJIUJU.js';
|
|
20
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';
|
|
21
21
|
import { CommerceError, isCommerceError, toLogInfo, toCommerceError } from './chunk-C5YISPT6.js';
|
|
22
22
|
import { isRecord } from './chunk-3M6U7ILB.js';
|
|
@@ -38,10 +38,12 @@ var JSONRPC_INTERNAL_ERROR = -32603;
|
|
|
38
38
|
var A2A_ERROR_TASK_NOT_FOUND = -32001;
|
|
39
39
|
var A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED = -32003;
|
|
40
40
|
var A2A_ERROR_UNSUPPORTED_OPERATION = -32004;
|
|
41
|
+
var A2A_ERROR_TASK_NOT_CANCELABLE = -32002;
|
|
41
42
|
var A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED = -32005;
|
|
42
43
|
var A2A_ERROR_VERSION_NOT_SUPPORTED = -32009;
|
|
43
44
|
var A2A_ERROR_REASONS = /* @__PURE__ */ new Map([
|
|
44
45
|
[A2A_ERROR_TASK_NOT_FOUND, "TASK_NOT_FOUND"],
|
|
46
|
+
[A2A_ERROR_TASK_NOT_CANCELABLE, "TASK_NOT_CANCELABLE"],
|
|
45
47
|
[A2A_ERROR_PUSH_NOTIFICATION_NOT_SUPPORTED, "PUSH_NOTIFICATION_NOT_SUPPORTED"],
|
|
46
48
|
[A2A_ERROR_UNSUPPORTED_OPERATION, "UNSUPPORTED_OPERATION"],
|
|
47
49
|
[A2A_ERROR_CONTENT_TYPE_NOT_SUPPORTED, "CONTENT_TYPE_NOT_SUPPORTED"],
|
|
@@ -54,23 +56,24 @@ function readId(value) {
|
|
|
54
56
|
function jsonRpcResult(id, result) {
|
|
55
57
|
return { jsonrpc: "2.0", id, result };
|
|
56
58
|
}
|
|
57
|
-
function jsonRpcError(id, code, message) {
|
|
59
|
+
function jsonRpcError(id, code, message, details = []) {
|
|
58
60
|
const reason = A2A_ERROR_REASONS.get(code);
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
} : {}
|
|
71
|
-
};
|
|
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 } : {} };
|
|
72
72
|
return { jsonrpc: "2.0", id, error };
|
|
73
73
|
}
|
|
74
|
+
function retryInfo(seconds) {
|
|
75
|
+
return { "@type": "type.googleapis.com/google.rpc.RetryInfo", retryDelay: `${seconds}s` };
|
|
76
|
+
}
|
|
74
77
|
function parseJsonRpcRequest(rawBody) {
|
|
75
78
|
let payload;
|
|
76
79
|
try {
|
|
@@ -135,6 +138,205 @@ function parseJsonRpcRequest(rawBody) {
|
|
|
135
138
|
return { ok: true, request: { id, method, params: params ?? {} } };
|
|
136
139
|
}
|
|
137
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
|
+
|
|
138
340
|
// src/protocols/a2a/message-mapping.ts
|
|
139
341
|
var A2A_USER_ROLE = "ROLE_USER";
|
|
140
342
|
var A2A_CALL_SHAPE = 'one data part {"resource": "<skill id>", "input": {...}}';
|
|
@@ -154,21 +356,26 @@ var ParamsSchema = z.object({
|
|
|
154
356
|
taskId: z.string().optional(),
|
|
155
357
|
contextId: z.string().optional()
|
|
156
358
|
});
|
|
157
|
-
function
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
)
|
|
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;
|
|
166
373
|
}
|
|
167
374
|
function assertNoContinuation(params) {
|
|
168
375
|
const message = params.message;
|
|
169
376
|
if (params.taskId !== void 0 || message.taskId !== void 0) {
|
|
170
377
|
throw unsupported(
|
|
171
|
-
"Task not found:
|
|
378
|
+
"Task not found: send the message without a taskId to start a new task.",
|
|
172
379
|
A2A_ERROR_TASK_NOT_FOUND
|
|
173
380
|
);
|
|
174
381
|
}
|
|
@@ -206,21 +413,10 @@ function assertSupportedPart(part) {
|
|
|
206
413
|
}
|
|
207
414
|
}
|
|
208
415
|
function parseInvocation(rawParams) {
|
|
209
|
-
const
|
|
210
|
-
if (!parsed.success) {
|
|
211
|
-
throw invalid(
|
|
212
|
-
'Request must carry a "message" with a "role" and a "parts" array of structured data parts.'
|
|
213
|
-
);
|
|
214
|
-
}
|
|
215
|
-
const params = parsed.data;
|
|
416
|
+
const params = readMessage(rawParams);
|
|
216
417
|
const message = params.message;
|
|
217
|
-
if (message.messageId === void 0 || message.messageId.length === 0) {
|
|
218
|
-
throw invalid('Message must carry a non-empty "messageId".');
|
|
219
|
-
}
|
|
220
418
|
const messageId = message.messageId;
|
|
221
419
|
assertNoContinuation(params);
|
|
222
|
-
const roleProblem = userRoleProblem(message.role);
|
|
223
|
-
if (roleProblem !== void 0) throw invalid(roleProblem);
|
|
224
420
|
if (message.parts.length === 0) {
|
|
225
421
|
throw invalid("Message carries no parts: send exactly one structured data part.");
|
|
226
422
|
}
|
|
@@ -273,6 +469,9 @@ function expiryMs(nowMs, expiresAt) {
|
|
|
273
469
|
const ttl = Number.isFinite(requested) ? requested - nowMs : DEFAULT_PENDING_TTL_MS;
|
|
274
470
|
return nowMs + Math.min(Math.max(ttl, 0), MAX_PENDING_TTL_MS);
|
|
275
471
|
}
|
|
472
|
+
function pendingExpiresAt(nowMs, expiresAt) {
|
|
473
|
+
return new Date(expiryMs(nowMs, expiresAt)).toISOString();
|
|
474
|
+
}
|
|
276
475
|
function createPendingPayments(clock, maxEntries = MAX_PENDING_PAYMENTS) {
|
|
277
476
|
const tasks = /* @__PURE__ */ new Map();
|
|
278
477
|
const now = () => clock.now().getTime();
|
|
@@ -510,11 +709,47 @@ function buildAgentCard(options) {
|
|
|
510
709
|
};
|
|
511
710
|
}
|
|
512
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
|
+
|
|
513
744
|
// src/protocols/a2a/descriptor.ts
|
|
514
745
|
var A2A_CAPABILITIES = [
|
|
515
746
|
"agent-card",
|
|
516
747
|
"jsonrpc",
|
|
517
748
|
"SendMessage",
|
|
749
|
+
"GetTask",
|
|
750
|
+
"ListTasks",
|
|
751
|
+
"CancelTask",
|
|
752
|
+
"returnImmediately",
|
|
518
753
|
// The x402 A2A transport, opt-in per request
|
|
519
754
|
"x402-extension"
|
|
520
755
|
];
|
|
@@ -597,23 +832,63 @@ function failedTask(error, identity) {
|
|
|
597
832
|
identity.statusMessageId
|
|
598
833
|
);
|
|
599
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
|
+
}
|
|
600
878
|
|
|
601
879
|
// src/protocols/a2a/payment-resume.ts
|
|
602
880
|
function taskResult(id, task2) {
|
|
603
881
|
return jsonRpcResult(id, { task: task2 });
|
|
604
882
|
}
|
|
605
|
-
|
|
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;
|
|
606
887
|
const message = isRecord(params) ? params["message"] : void 0;
|
|
607
888
|
const taskId = isRecord(message) ? message["taskId"] : void 0;
|
|
608
|
-
if (
|
|
609
|
-
const pending = await pendingPayments
|
|
889
|
+
if (typeof taskId !== "string") return void 0;
|
|
890
|
+
const pending = await pendingPayments.get(taskId);
|
|
610
891
|
if (pending === void 0) return void 0;
|
|
611
|
-
const messageId = isRecord(message) ? message["messageId"] : void 0;
|
|
612
|
-
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
613
|
-
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message must carry a non-empty "messageId".');
|
|
614
|
-
}
|
|
615
|
-
const roleProblem = userRoleProblem(isRecord(message) ? message["role"] : void 0);
|
|
616
|
-
if (roleProblem !== void 0) return jsonRpcError(id, JSONRPC_INVALID_PARAMS, roleProblem);
|
|
617
892
|
const contextId = isRecord(message) ? message["contextId"] : void 0;
|
|
618
893
|
if (contextId !== void 0 && contextId !== pending.contextId) {
|
|
619
894
|
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, 'Message "contextId" does not match the task.');
|
|
@@ -634,43 +909,78 @@ async function resumePayment(context, pendingPayments, id, params) {
|
|
|
634
909
|
return jsonRpcError(id, JSONRPC_INVALID_PARAMS, toCommerceError(err).message);
|
|
635
910
|
}
|
|
636
911
|
}
|
|
637
|
-
const
|
|
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
|
+
}
|
|
638
924
|
if (taken === void 0) return void 0;
|
|
639
925
|
const authorization = taken.authorization ?? followUp;
|
|
640
|
-
|
|
641
|
-
|
|
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 = {
|
|
642
943
|
taskId,
|
|
643
944
|
contextId: taken.contextId,
|
|
644
945
|
artifactId: context.ids.next("a2a-artifact"),
|
|
645
|
-
statusMessageId
|
|
646
|
-
timestamp: context.clock.nowIso()
|
|
946
|
+
statusMessageId: context.ids.next("a2a-msg")
|
|
647
947
|
};
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
artifacts: []
|
|
654
|
-
};
|
|
655
|
-
return taskResult(
|
|
656
|
-
id,
|
|
657
|
-
withStatusMessage(
|
|
658
|
-
declined,
|
|
659
|
-
"Payment was declined.",
|
|
660
|
-
statusMessageId,
|
|
661
|
-
paymentRejectedMetadata()
|
|
662
|
-
)
|
|
663
|
-
);
|
|
664
|
-
}
|
|
665
|
-
return taskResult(
|
|
666
|
-
id,
|
|
667
|
-
await payPending(
|
|
668
|
-
context,
|
|
669
|
-
{ ...taken, ...authorization !== void 0 ? { authorization } : {} },
|
|
670
|
-
submission.payload,
|
|
671
|
-
identity
|
|
672
|
-
)
|
|
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" }
|
|
673
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);
|
|
674
984
|
}
|
|
675
985
|
function withoutRetryDelay(error) {
|
|
676
986
|
if (error.details?.["reason"] !== "payment_identifier_in_flight") return error;
|
|
@@ -683,7 +993,7 @@ function withoutRetryDelay(error) {
|
|
|
683
993
|
...error.resourceId !== void 0 ? { resourceId: error.resourceId } : {}
|
|
684
994
|
});
|
|
685
995
|
}
|
|
686
|
-
async function payPending(context, pending, payload,
|
|
996
|
+
async function payPending(context, pending, payload, ids) {
|
|
687
997
|
const requestId = context.ids.next("a2a");
|
|
688
998
|
const request = {
|
|
689
999
|
requestId,
|
|
@@ -702,12 +1012,14 @@ async function payPending(context, pending, payload, identity) {
|
|
|
702
1012
|
try {
|
|
703
1013
|
const outcome = await context.pipeline.execute(request);
|
|
704
1014
|
if (outcome.kind === "delivered" && outcome.payment !== void 0) {
|
|
705
|
-
|
|
706
|
-
|
|
1015
|
+
const identity2 = { ...ids, timestamp: context.clock.nowIso() };
|
|
1016
|
+
const task2 = withStatusMessage(
|
|
1017
|
+
completedTask(outcome, identity2),
|
|
707
1018
|
"Payment settled.",
|
|
708
|
-
|
|
1019
|
+
identity2.statusMessageId,
|
|
709
1020
|
paymentCompletedMetadata(outcome.payment)
|
|
710
1021
|
);
|
|
1022
|
+
return { task: task2, evictable: false };
|
|
711
1023
|
}
|
|
712
1024
|
error = new CommerceError("PAYMENT_INVALID", "The payment was not accepted.", { requestId });
|
|
713
1025
|
} catch (err) {
|
|
@@ -717,24 +1029,183 @@ async function payPending(context, pending, payload, identity) {
|
|
|
717
1029
|
"a2a adapter: x402 extension payment failed"
|
|
718
1030
|
);
|
|
719
1031
|
}
|
|
1032
|
+
const identity = { ...ids, timestamp: context.clock.nowIso() };
|
|
720
1033
|
const metadata = paymentFailureMetadata(error, pending.network);
|
|
721
1034
|
const reason = error.details?.["reason"];
|
|
722
|
-
let text
|
|
1035
|
+
let text;
|
|
723
1036
|
if (metadata[X402_PAYMENT_STATUS_KEY] === "payment-completed") {
|
|
724
1037
|
text = "Payment settled, but the resource could not be delivered.";
|
|
725
1038
|
} else if (typeof reason === "string" && reason.startsWith("payment_identifier_")) {
|
|
726
1039
|
text = error.message;
|
|
727
|
-
} else
|
|
728
|
-
|
|
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])}.`;
|
|
729
1043
|
}
|
|
730
|
-
return
|
|
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
|
+
};
|
|
731
1169
|
}
|
|
732
1170
|
|
|
733
1171
|
// src/protocols/a2a/adapter.ts
|
|
734
1172
|
var MAX_REQUEST_BODY_BYTES = 256 * 1024;
|
|
735
1173
|
var VERSION_PATTERN = /^(\d+\.\d+)(?:\.\d+)?$/;
|
|
736
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
|
+
};
|
|
737
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
|
+
}
|
|
738
1209
|
var DEFAULT_AGENT_DESCRIPTION = "Agent Commerce Gateway: canonical commerce resources exposed as A2A skills.";
|
|
739
1210
|
var A2aProtocolAdapter = class {
|
|
740
1211
|
name = "a2a";
|
|
@@ -745,6 +1216,8 @@ var A2aProtocolAdapter = class {
|
|
|
745
1216
|
agentDescription;
|
|
746
1217
|
agentVersion;
|
|
747
1218
|
store;
|
|
1219
|
+
retentionMs;
|
|
1220
|
+
maxRetained;
|
|
748
1221
|
context;
|
|
749
1222
|
started = false;
|
|
750
1223
|
// The card lists only a2a-exposed resources, but a caller can name any id,
|
|
@@ -757,12 +1230,19 @@ var A2aProtocolAdapter = class {
|
|
|
757
1230
|
cardEtag = "";
|
|
758
1231
|
// Purchases waiting for an x402 extension payment
|
|
759
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;
|
|
760
1238
|
constructor(options = {}) {
|
|
761
1239
|
this.mountPath = options.mountPath ?? A2A_DEFAULT_MOUNT_PATH;
|
|
762
1240
|
this.agentName = options.agentName ?? A2A_DEFAULT_AGENT_NAME;
|
|
763
1241
|
this.agentDescription = options.agentDescription ?? DEFAULT_AGENT_DESCRIPTION;
|
|
764
1242
|
this.agentVersion = options.agentVersion ?? PACKAGE_VERSION;
|
|
765
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);
|
|
766
1246
|
this.descriptor = buildDescriptor(PACKAGE_VERSION);
|
|
767
1247
|
this.additionalHttpRoutes = [
|
|
768
1248
|
{
|
|
@@ -795,6 +1275,8 @@ var A2aProtocolAdapter = class {
|
|
|
795
1275
|
resources
|
|
796
1276
|
});
|
|
797
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);
|
|
798
1280
|
this.cardBody = JSON.stringify(this.card);
|
|
799
1281
|
this.cardEtag = `"${createHash("sha256").update(this.cardBody).digest("base64url")}"`;
|
|
800
1282
|
this.started = true;
|
|
@@ -829,6 +1311,7 @@ var A2aProtocolAdapter = class {
|
|
|
829
1311
|
}
|
|
830
1312
|
/** `POST <mountPath>`: the A2A JSON-RPC endpoint */
|
|
831
1313
|
async handleHttp(req, res) {
|
|
1314
|
+
let requestId = null;
|
|
832
1315
|
try {
|
|
833
1316
|
if (!this.started) {
|
|
834
1317
|
this.writeJson(
|
|
@@ -850,8 +1333,8 @@ var A2aProtocolAdapter = class {
|
|
|
850
1333
|
);
|
|
851
1334
|
return;
|
|
852
1335
|
}
|
|
853
|
-
const
|
|
854
|
-
if (
|
|
1336
|
+
const read2 = await readCappedBody(req, MAX_REQUEST_BODY_BYTES);
|
|
1337
|
+
if (read2.kind === "too-large") {
|
|
855
1338
|
this.writeJson(
|
|
856
1339
|
res,
|
|
857
1340
|
413,
|
|
@@ -863,7 +1346,7 @@ var A2aProtocolAdapter = class {
|
|
|
863
1346
|
);
|
|
864
1347
|
return;
|
|
865
1348
|
}
|
|
866
|
-
if (
|
|
1349
|
+
if (read2.kind !== "ok") {
|
|
867
1350
|
this.writeJson(
|
|
868
1351
|
res,
|
|
869
1352
|
200,
|
|
@@ -871,11 +1354,12 @@ var A2aProtocolAdapter = class {
|
|
|
871
1354
|
);
|
|
872
1355
|
return;
|
|
873
1356
|
}
|
|
874
|
-
const parsed = parseJsonRpcRequest(
|
|
1357
|
+
const parsed = parseJsonRpcRequest(read2.text);
|
|
875
1358
|
if (!parsed.ok) {
|
|
876
1359
|
this.writeJson(res, 200, jsonRpcError(parsed.id, parsed.error.code, parsed.error.message));
|
|
877
1360
|
return;
|
|
878
1361
|
}
|
|
1362
|
+
requestId = parsed.request.id;
|
|
879
1363
|
const version = req.headers[A2A_VERSION_HEADER];
|
|
880
1364
|
const declared = (Array.isArray(version) ? version[0] : version) ?? new URL(req.url ?? "/", "http://localhost").searchParams.get(A2A_VERSION_PARAMETER);
|
|
881
1365
|
if (declared?.match(VERSION_PATTERN)?.[1] !== A2A_PROTOCOL_VERSION) {
|
|
@@ -890,24 +1374,21 @@ var A2aProtocolAdapter = class {
|
|
|
890
1374
|
);
|
|
891
1375
|
return;
|
|
892
1376
|
}
|
|
1377
|
+
const activated = requestsX402Extension(req.headers[A2A_EXTENSIONS_HEADER]) || requestsX402Extension(req.headers[A2A_X_EXTENSIONS_HEADER]);
|
|
893
1378
|
const response = await this.dispatch(
|
|
894
1379
|
parsed.request.id,
|
|
895
1380
|
parsed.request.method,
|
|
896
1381
|
parsed.request.params,
|
|
897
|
-
|
|
898
|
-
);
|
|
899
|
-
this.writeJson(
|
|
900
|
-
res,
|
|
901
|
-
200,
|
|
902
|
-
response,
|
|
903
|
-
usesX402Extension(response) ? { [A2A_EXTENSIONS_HEADER]: A2A_X402_EXTENSION_URI } : {}
|
|
1382
|
+
activated
|
|
904
1383
|
);
|
|
1384
|
+
const echo = usesX402Extension(response) || activated && response["error"] === void 0;
|
|
1385
|
+
this.writeJson(res, 200, response, echo ? X402_EXTENSION_ECHO : {});
|
|
905
1386
|
} catch (err) {
|
|
906
1387
|
this.context?.logger.error({ err: toLogInfo(err) }, "a2a adapter: request handling failed");
|
|
907
1388
|
this.writeJson(
|
|
908
1389
|
res,
|
|
909
1390
|
200,
|
|
910
|
-
jsonRpcError(
|
|
1391
|
+
jsonRpcError(requestId, JSONRPC_INTERNAL_ERROR, "Internal server error.")
|
|
911
1392
|
);
|
|
912
1393
|
}
|
|
913
1394
|
}
|
|
@@ -919,13 +1400,6 @@ var A2aProtocolAdapter = class {
|
|
|
919
1400
|
`A2A method "${method}" is not supported: this agent does not support push notifications.`
|
|
920
1401
|
);
|
|
921
1402
|
}
|
|
922
|
-
if (A2A_TASK_LOOKUP_METHODS.includes(method)) {
|
|
923
|
-
return jsonRpcError(
|
|
924
|
-
id,
|
|
925
|
-
A2A_ERROR_TASK_NOT_FOUND,
|
|
926
|
-
"Task not found. Finished tasks are not retained; continue a pending payment with SendMessage."
|
|
927
|
-
);
|
|
928
|
-
}
|
|
929
1403
|
if (A2A_UNSUPPORTED_METHODS.includes(method)) {
|
|
930
1404
|
return jsonRpcError(
|
|
931
1405
|
id,
|
|
@@ -933,49 +1407,198 @@ var A2aProtocolAdapter = class {
|
|
|
933
1407
|
`A2A method "${method}" is not supported by this deployment.`
|
|
934
1408
|
);
|
|
935
1409
|
}
|
|
936
|
-
|
|
937
|
-
|
|
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);
|
|
938
1442
|
}
|
|
939
|
-
const resumed = await resumePayment(
|
|
1443
|
+
const resumed = await resumePayment(
|
|
1444
|
+
this.resume(ops),
|
|
1445
|
+
id,
|
|
1446
|
+
request.params,
|
|
1447
|
+
request.returnImmediately
|
|
1448
|
+
);
|
|
940
1449
|
if (resumed !== void 0) return resumed;
|
|
1450
|
+
const known = await this.answerKnownTask(ops, id, request.params);
|
|
1451
|
+
if (known !== void 0) return known;
|
|
941
1452
|
let invocation;
|
|
942
1453
|
try {
|
|
943
|
-
invocation = parseInvocation(params);
|
|
1454
|
+
invocation = parseInvocation(request.params);
|
|
944
1455
|
} catch (err) {
|
|
945
|
-
|
|
946
|
-
const a2aErrorCode = error.details?.["a2aErrorCode"];
|
|
947
|
-
const code = typeof a2aErrorCode === "number" ? a2aErrorCode : error.code === "PROTOCOL_UNSUPPORTED" ? A2A_ERROR_UNSUPPORTED_OPERATION : JSONRPC_INVALID_PARAMS;
|
|
948
|
-
return jsonRpcError(id, code, error.message);
|
|
1456
|
+
return refusal(id, err);
|
|
949
1457
|
}
|
|
950
|
-
return this.execute(id, invocation, x402Extension);
|
|
1458
|
+
return this.execute(ops, id, invocation, x402Extension, request.returnImmediately);
|
|
951
1459
|
}
|
|
952
|
-
//
|
|
953
|
-
|
|
954
|
-
const context = this
|
|
955
|
-
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) {
|
|
956
1550
|
return jsonRpcError(id, JSONRPC_INTERNAL_ERROR, "A2A adapter is not running.");
|
|
957
1551
|
}
|
|
1552
|
+
const ids = this.taskIds(context);
|
|
1553
|
+
const now = () => ({ ...ids, timestamp: context.clock.nowIso() });
|
|
958
1554
|
const resource = this.skillsById.get(invocation.resourceId);
|
|
959
1555
|
if (resource === void 0) {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
),
|
|
967
|
-
this.taskIdentity(context, context.ids.next("a2a"))
|
|
968
|
-
)
|
|
1556
|
+
const unknown = failedTask(
|
|
1557
|
+
new CommerceError(
|
|
1558
|
+
"RESOURCE_NOT_FOUND",
|
|
1559
|
+
`Unknown canonical resource "${invocation.resourceId}".`
|
|
1560
|
+
),
|
|
1561
|
+
now()
|
|
969
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()));
|
|
970
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() });
|
|
971
1591
|
const requestId = context.ids.next("a2a");
|
|
972
|
-
|
|
1592
|
+
let task2;
|
|
1593
|
+
let evictable = true;
|
|
1594
|
+
let proofSent = false;
|
|
973
1595
|
try {
|
|
974
1596
|
const { input, payment, authorization } = extractReservedInputFields(
|
|
975
1597
|
invocation.input,
|
|
976
1598
|
resource,
|
|
977
1599
|
requestId
|
|
978
1600
|
);
|
|
1601
|
+
proofSent = payment !== void 0;
|
|
979
1602
|
const request = {
|
|
980
1603
|
requestId,
|
|
981
1604
|
resourceId: invocation.resourceId,
|
|
@@ -986,58 +1609,72 @@ var A2aProtocolAdapter = class {
|
|
|
986
1609
|
...authorization !== void 0 ? { authorization } : {}
|
|
987
1610
|
};
|
|
988
1611
|
const outcome = await context.pipeline.execute(request);
|
|
1612
|
+
const identity = now();
|
|
989
1613
|
if (outcome.kind !== "payment-required") {
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
id,
|
|
1012
|
-
failedTask(
|
|
1013
|
-
new CommerceError(
|
|
1014
|
-
"GATEWAY_BUSY",
|
|
1015
|
-
"Too many unpaid purchases are waiting for payment; retry shortly."
|
|
1016
|
-
),
|
|
1017
|
-
identity
|
|
1018
|
-
)
|
|
1019
|
-
);
|
|
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
|
+
}
|
|
1020
1635
|
}
|
|
1021
|
-
return taskResult(
|
|
1022
|
-
id,
|
|
1023
|
-
inputRequired(task2, paymentRequiredMetadata(envelope), identity.statusMessageId)
|
|
1024
|
-
);
|
|
1025
1636
|
} catch (err) {
|
|
1026
1637
|
const error = toCommerceError(err);
|
|
1027
1638
|
context.logger.warn(
|
|
1028
1639
|
{ resourceId: invocation.resourceId, requestId, err: toLogInfo(error) },
|
|
1029
1640
|
"a2a adapter: execution failed"
|
|
1030
1641
|
);
|
|
1031
|
-
|
|
1642
|
+
task2 = failedTask(error, now());
|
|
1643
|
+
evictable = chargedNothing(error, proofSent);
|
|
1032
1644
|
}
|
|
1645
|
+
await this.keep(ops, task2, evictable);
|
|
1646
|
+
return task2;
|
|
1033
1647
|
}
|
|
1034
|
-
|
|
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) {
|
|
1035
1673
|
return {
|
|
1036
|
-
taskId:
|
|
1037
|
-
contextId:
|
|
1674
|
+
taskId: randomUUID(),
|
|
1675
|
+
contextId: randomUUID(),
|
|
1038
1676
|
artifactId: context.ids.next("a2a-artifact"),
|
|
1039
|
-
statusMessageId: context.ids.next("a2a-msg")
|
|
1040
|
-
timestamp: context.clock.nowIso()
|
|
1677
|
+
statusMessageId: context.ids.next("a2a-msg")
|
|
1041
1678
|
};
|
|
1042
1679
|
}
|
|
1043
1680
|
async health() {
|
|
@@ -1049,11 +1686,15 @@ var A2aProtocolAdapter = class {
|
|
|
1049
1686
|
}
|
|
1050
1687
|
async stop() {
|
|
1051
1688
|
this.started = false;
|
|
1689
|
+
await this.background?.settled();
|
|
1690
|
+
this.background = void 0;
|
|
1052
1691
|
this.card = void 0;
|
|
1053
1692
|
this.cardBody = "";
|
|
1054
1693
|
this.cardEtag = "";
|
|
1055
1694
|
this.pendingPayments?.clear();
|
|
1056
1695
|
this.pendingPayments = void 0;
|
|
1696
|
+
this.tasks = void 0;
|
|
1697
|
+
this.running.clear();
|
|
1057
1698
|
this.skillsById = /* @__PURE__ */ new Map();
|
|
1058
1699
|
this.context = void 0;
|
|
1059
1700
|
}
|
|
@@ -1065,7 +1706,8 @@ var A2aProtocolAdapter = class {
|
|
|
1065
1706
|
};
|
|
1066
1707
|
function usesX402Extension(response) {
|
|
1067
1708
|
const result = response["result"];
|
|
1068
|
-
|
|
1709
|
+
const task2 = isRecord(result) && isRecord(result["task"]) ? result["task"] : result;
|
|
1710
|
+
return task2?.status?.message?.extensions?.includes(A2A_X402_EXTENSION_URI) === true;
|
|
1069
1711
|
}
|
|
1070
1712
|
function matchesEtag(header2, etag) {
|
|
1071
1713
|
if (header2 === void 0) return false;
|
|
@@ -5528,8 +6170,8 @@ async function guardAcpRequest(req, options) {
|
|
|
5528
6170
|
}
|
|
5529
6171
|
idempotencyKey = presentedKey;
|
|
5530
6172
|
}
|
|
5531
|
-
const
|
|
5532
|
-
if (
|
|
6173
|
+
const read2 = await readCappedBody(req, options.maxBodyBytes ?? ACP_MAX_REQUEST_BODY_BYTES);
|
|
6174
|
+
if (read2.kind === "too-large") {
|
|
5533
6175
|
return failed(
|
|
5534
6176
|
acpFailure(
|
|
5535
6177
|
413,
|
|
@@ -5539,7 +6181,7 @@ async function guardAcpRequest(req, options) {
|
|
|
5539
6181
|
)
|
|
5540
6182
|
);
|
|
5541
6183
|
}
|
|
5542
|
-
if (
|
|
6184
|
+
if (read2.kind === "unreadable") {
|
|
5543
6185
|
return failed(
|
|
5544
6186
|
acpFailure(
|
|
5545
6187
|
400,
|
|
@@ -5549,7 +6191,7 @@ async function guardAcpRequest(req, options) {
|
|
|
5549
6191
|
)
|
|
5550
6192
|
);
|
|
5551
6193
|
}
|
|
5552
|
-
const raw =
|
|
6194
|
+
const raw = read2.text;
|
|
5553
6195
|
const contentTypeFailure = checkContentType(header(req, "content-type"), raw, route);
|
|
5554
6196
|
if (contentTypeFailure !== void 0) return failed(contentTypeFailure);
|
|
5555
6197
|
const definition = REQUEST_DEFINITIONS[route.operation];
|
|
@@ -6325,6 +6967,7 @@ var CORS_HEADERS = [
|
|
|
6325
6967
|
"mcp-name",
|
|
6326
6968
|
"a2a-version",
|
|
6327
6969
|
"a2a-extensions",
|
|
6970
|
+
"x-a2a-extensions",
|
|
6328
6971
|
"api-version",
|
|
6329
6972
|
"idempotency-key",
|
|
6330
6973
|
"request-id",
|
|
@@ -6340,7 +6983,9 @@ var CORS_EXPOSED_HEADERS = [
|
|
|
6340
6983
|
"idempotency-key",
|
|
6341
6984
|
"request-id",
|
|
6342
6985
|
"idempotent-replayed",
|
|
6343
|
-
"retry-after"
|
|
6986
|
+
"retry-after",
|
|
6987
|
+
"a2a-extensions",
|
|
6988
|
+
"x-a2a-extensions"
|
|
6344
6989
|
].join(",");
|
|
6345
6990
|
function buildAccessControlHook(options) {
|
|
6346
6991
|
const allowedOrigins = new Set(options.allowedOrigins.map((origin) => origin.toLowerCase()));
|
|
@@ -7471,9 +8116,9 @@ async function runGateway(options = {}) {
|
|
|
7471
8116
|
const { core: logger } = createGatewayLogger({ name: config.merchant.id });
|
|
7472
8117
|
const paymentProviders = await createConfiguredPaymentProviders(config.payments, logger);
|
|
7473
8118
|
const ap2 = config.authorization?.ap2;
|
|
7474
|
-
const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-
|
|
8119
|
+
const ap2Module = ap2?.enabled ? await importOptionalPeer("authorization.ap2", () => import('./ap2-SJZAZQIR.js')) : void 0;
|
|
7475
8120
|
const mcp = config.protocols.mcp;
|
|
7476
|
-
const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-
|
|
8121
|
+
const mcpModule = mcp.enabled ? await importOptionalPeer("protocols.mcp", () => import('./mcp-F3EQQWDZ.js')) : void 0;
|
|
7477
8122
|
const acp = config.protocols.acp;
|
|
7478
8123
|
const ap2Replay = ap2?.enabled ? ap2.replay?.path : void 0;
|
|
7479
8124
|
const acpIdempotency = acp.enabled ? acp.idempotency.path : void 0;
|
|
@@ -7525,7 +8170,8 @@ async function runGateway(options = {}) {
|
|
|
7525
8170
|
// The Agent Card names the merchant, not the software: a client
|
|
7526
8171
|
// picking between agents is choosing whose resources to buy
|
|
7527
8172
|
agentName: config.merchant.name,
|
|
7528
|
-
store
|
|
8173
|
+
store,
|
|
8174
|
+
...config.protocols.a2a.tasks !== void 0 ? { tasks: config.protocols.a2a.tasks } : {}
|
|
7529
8175
|
})
|
|
7530
8176
|
);
|
|
7531
8177
|
}
|
|
@@ -7628,5 +8274,5 @@ function printStartupError(error) {
|
|
|
7628
8274
|
}
|
|
7629
8275
|
|
|
7630
8276
|
export { printStartupError, runGateway };
|
|
7631
|
-
//# sourceMappingURL=run-
|
|
7632
|
-
//# sourceMappingURL=run-
|
|
8277
|
+
//# sourceMappingURL=run-C3VWMM57.js.map
|
|
8278
|
+
//# sourceMappingURL=run-C3VWMM57.js.map
|