@nevermined-io/payments 1.0.0-rc2 → 1.0.0-rc4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -14
- package/dist/index.js.map +1 -1
- package/dist/payments.d.ts +0 -18
- package/dist/payments.d.ts.map +1 -1
- package/dist/payments.js +0 -37
- package/dist/payments.js.map +1 -1
- package/package.json +1 -2
- package/dist/a2a/agent-card.d.ts +0 -85
- package/dist/a2a/agent-card.d.ts.map +0 -1
- package/dist/a2a/agent-card.js +0 -79
- package/dist/a2a/agent-card.js.map +0 -1
- package/dist/a2a/index.d.ts +0 -23
- package/dist/a2a/index.d.ts.map +0 -1
- package/dist/a2a/index.js +0 -42
- package/dist/a2a/index.js.map +0 -1
- package/dist/a2a/paymentsRequestHandler.d.ts +0 -107
- package/dist/a2a/paymentsRequestHandler.d.ts.map +0 -1
- package/dist/a2a/paymentsRequestHandler.js +0 -333
- package/dist/a2a/paymentsRequestHandler.js.map +0 -1
- package/dist/a2a/server.d.ts +0 -126
- package/dist/a2a/server.d.ts.map +0 -1
- package/dist/a2a/server.js +0 -189
- package/dist/a2a/server.js.map +0 -1
- package/dist/a2a/types.d.ts +0 -91
- package/dist/a2a/types.d.ts.map +0 -1
- package/dist/a2a/types.js +0 -16
- package/dist/a2a/types.js.map +0 -1
package/dist/a2a/server.js
DELETED
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.PaymentsA2AServer = void 0;
|
|
7
|
-
/**
|
|
8
|
-
* PaymentsA2AServer sets up and starts the A2A server for payments agents.
|
|
9
|
-
* Handles A2A protocol endpoints and allows optional custom endpoints.
|
|
10
|
-
*
|
|
11
|
-
* The server provides a complete A2A protocol implementation with:
|
|
12
|
-
* - JSON-RPC endpoint for A2A messages
|
|
13
|
-
* - Agent Card endpoint (.well-known/agent.json)
|
|
14
|
-
* - Bearer token extraction and validation
|
|
15
|
-
* - Credit validation and burning
|
|
16
|
-
* - Task execution and streaming
|
|
17
|
-
* - Customizable routes and handlers
|
|
18
|
-
*/
|
|
19
|
-
const express_1 = __importDefault(require("express"));
|
|
20
|
-
const http_1 = __importDefault(require("http"));
|
|
21
|
-
const sdk_1 = require("@a2a-js/sdk");
|
|
22
|
-
const paymentsRequestHandler_1 = require("./paymentsRequestHandler");
|
|
23
|
-
/**
|
|
24
|
-
* Middleware to extract bearer token from HTTP headers and store it in the global context.
|
|
25
|
-
* This middleware is applied after A2A routes are set up and extracts authentication
|
|
26
|
-
* information for credit validation.
|
|
27
|
-
*
|
|
28
|
-
* @param req - Express request object
|
|
29
|
-
* @param res - Express response object
|
|
30
|
-
* @param next - Express next function
|
|
31
|
-
*/
|
|
32
|
-
function _bearerTokenMiddleware(handler, req, res, next) {
|
|
33
|
-
console.log(`[MIDDLEWARE] Processing ${req.method} ${req.url}`);
|
|
34
|
-
// Only process POST requests (A2A uses POST for all operations)
|
|
35
|
-
if (req.method !== 'POST') {
|
|
36
|
-
console.log(`[MIDDLEWARE] Skipping non-POST request`);
|
|
37
|
-
return next();
|
|
38
|
-
}
|
|
39
|
-
// Extract bearer token from Authorization header
|
|
40
|
-
const authHeader = req.headers.authorization;
|
|
41
|
-
let bearerToken;
|
|
42
|
-
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
43
|
-
bearerToken = authHeader.substring(7); // Remove 'Bearer ' prefix
|
|
44
|
-
console.log(`[MIDDLEWARE] Extracted bearer token: ${bearerToken.substring(0, 20)}...`);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
console.log(`[MIDDLEWARE] No bearer token found in headers`);
|
|
48
|
-
}
|
|
49
|
-
// Transform relative URL to absolute URL
|
|
50
|
-
const absoluteUrl = new URL(req.url, req.protocol + '://' + req.get('host')).toString();
|
|
51
|
-
const context = {
|
|
52
|
-
bearerToken,
|
|
53
|
-
urlRequested: absoluteUrl,
|
|
54
|
-
httpMethodRequested: req.method,
|
|
55
|
-
};
|
|
56
|
-
// Try to associate context with taskId or messageId
|
|
57
|
-
const taskId = req.body?.taskId || req.body?.id;
|
|
58
|
-
const messageId = req.body?.params?.message?.messageId;
|
|
59
|
-
if (taskId) {
|
|
60
|
-
handler.setHttpRequestContextForTask(taskId, context);
|
|
61
|
-
}
|
|
62
|
-
else if (messageId) {
|
|
63
|
-
handler.setHttpRequestContextForMessage(messageId, context);
|
|
64
|
-
}
|
|
65
|
-
next();
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* PaymentsA2AServer sets up the A2A endpoints and starts the server.
|
|
69
|
-
*
|
|
70
|
-
* This class provides a complete A2A protocol implementation with payment integration.
|
|
71
|
-
* It handles:
|
|
72
|
-
* - JSON-RPC message routing
|
|
73
|
-
* - Agent card exposure
|
|
74
|
-
* - Bearer token extraction
|
|
75
|
-
* - Credit validation and burning
|
|
76
|
-
* - Task execution and streaming
|
|
77
|
-
* - Customizable routes and handlers
|
|
78
|
-
*
|
|
79
|
-
* @example
|
|
80
|
-
* ```typescript
|
|
81
|
-
* const server = PaymentsA2AServer.start({
|
|
82
|
-
* agentCard: myAgentCard,
|
|
83
|
-
* executor: new MyExecutor(),
|
|
84
|
-
* paymentsService: payments,
|
|
85
|
-
* port: 41242,
|
|
86
|
-
* basePath: '/a2a/',
|
|
87
|
-
* hooks: {
|
|
88
|
-
* beforeRequest: async (method, params, req) => {
|
|
89
|
-
* console.log(`Processing ${method} request`)
|
|
90
|
-
* }
|
|
91
|
-
* }
|
|
92
|
-
* })
|
|
93
|
-
* ```
|
|
94
|
-
*/
|
|
95
|
-
class PaymentsA2AServer {
|
|
96
|
-
/**
|
|
97
|
-
* Starts the A2A server with the given options.
|
|
98
|
-
*
|
|
99
|
-
* This method sets up the complete A2A server infrastructure including:
|
|
100
|
-
* - Express app configuration
|
|
101
|
-
* - A2A route setup
|
|
102
|
-
* - Middleware for bearer token extraction
|
|
103
|
-
* - Agent card endpoint
|
|
104
|
-
* - HTTP server creation and binding
|
|
105
|
-
*
|
|
106
|
-
* @param options - Server configuration options
|
|
107
|
-
* @returns Server result containing app, server, adapter, and handler instances
|
|
108
|
-
*
|
|
109
|
-
* @example
|
|
110
|
-
* ```typescript
|
|
111
|
-
* const result = PaymentsA2AServer.start({
|
|
112
|
-
* agentCard: buildPaymentAgentCard(baseCard, paymentMetadata),
|
|
113
|
-
* executor: new MyPaymentsExecutor(),
|
|
114
|
-
* paymentsService: payments,
|
|
115
|
-
* port: 41242,
|
|
116
|
-
* basePath: '/a2a/',
|
|
117
|
-
* exposeAgentCard: true,
|
|
118
|
-
* exposeDefaultRoutes: true
|
|
119
|
-
* })
|
|
120
|
-
*
|
|
121
|
-
* // Access the Express app for additional routes
|
|
122
|
-
* result.app.get('/health', (req, res) => res.json({ status: 'ok' }))
|
|
123
|
-
* ```
|
|
124
|
-
*/
|
|
125
|
-
static start(options) {
|
|
126
|
-
const { agentCard, executor, paymentsService, port, taskStore, basePath = '/', exposeAgentCard = true, exposeDefaultRoutes = true, expressApp, customRequestHandler, hooks, } = options;
|
|
127
|
-
// Initialize components
|
|
128
|
-
const store = taskStore || new sdk_1.InMemoryTaskStore();
|
|
129
|
-
const handler = customRequestHandler ||
|
|
130
|
-
new paymentsRequestHandler_1.PaymentsRequestHandler(agentCard, store, executor, paymentsService);
|
|
131
|
-
const appBuilder = new sdk_1.A2AExpressApp(handler);
|
|
132
|
-
const app = expressApp || (0, express_1.default)();
|
|
133
|
-
// Apply hooks middleware if provided
|
|
134
|
-
if (hooks) {
|
|
135
|
-
app.use((req, res, next) => {
|
|
136
|
-
if (req.method === 'POST' && req.body?.method) {
|
|
137
|
-
const { method, params } = req.body;
|
|
138
|
-
// Apply beforeRequest hook
|
|
139
|
-
if (hooks.beforeRequest) {
|
|
140
|
-
hooks.beforeRequest(method, params, req).catch((err) => {
|
|
141
|
-
console.error('[HOOKS] beforeRequest error:', err);
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
// Apply afterRequest hook by intercepting res.json
|
|
145
|
-
const originalJson = res.json;
|
|
146
|
-
res.json = function (data) {
|
|
147
|
-
if (hooks.afterRequest) {
|
|
148
|
-
hooks.afterRequest(method, data, req).catch((err) => {
|
|
149
|
-
console.error('[HOOKS] afterRequest error:', err);
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
return originalJson.call(this, data);
|
|
153
|
-
};
|
|
154
|
-
// Apply onError hook by catching errors
|
|
155
|
-
const originalSend = res.send;
|
|
156
|
-
res.send = function (data) {
|
|
157
|
-
if (data?.error && hooks.onError) {
|
|
158
|
-
hooks
|
|
159
|
-
.onError(method, new Error(data.error.message || 'Unknown error'), req)
|
|
160
|
-
.catch((err) => {
|
|
161
|
-
console.error('[HOOKS] onError error:', err);
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
return originalSend.call(this, data);
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
next();
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
if (exposeDefaultRoutes) {
|
|
171
|
-
appBuilder.setupRoutes(app, basePath); //, [bearerTokenMiddleware.bind(null, handler)])
|
|
172
|
-
}
|
|
173
|
-
if (exposeAgentCard) {
|
|
174
|
-
app.get(`${basePath}.well-known/agent.json`, (req, res) => {
|
|
175
|
-
res.json(agentCard);
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
const server = http_1.default.createServer(app);
|
|
179
|
-
server.listen(port, () => {
|
|
180
|
-
console.log(`[PaymentsA2A] Server started on http://localhost:${port}${basePath}`);
|
|
181
|
-
if (exposeAgentCard) {
|
|
182
|
-
console.log(`[PaymentsA2A] Agent Card: http://localhost:${port}${basePath}.well-known/agent.json`);
|
|
183
|
-
}
|
|
184
|
-
});
|
|
185
|
-
return { app, server, handler };
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
exports.PaymentsA2AServer = PaymentsA2AServer;
|
|
189
|
-
//# sourceMappingURL=server.js.map
|
package/dist/a2a/server.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/a2a/server.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;GAWG;AACH,sDAA6B;AAC7B,gDAAuB;AACvB,qCAA6E;AAE7E,qEAAiE;AAmDjE;;;;;;;;GAQG;AACH,SAAS,sBAAsB,CAC7B,OAA+B,EAC/B,GAAoB,EACpB,GAAqB,EACrB,IAA0B;IAE1B,OAAO,CAAC,GAAG,CAAC,2BAA2B,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC,CAAA;IAE/D,gEAAgE;IAChE,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAA;QACrD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC;IAED,iDAAiD;IACjD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAA;IAC5C,IAAI,WAA+B,CAAA;IAEnC,IAAI,UAAU,IAAI,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACnD,WAAW,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA,CAAC,0BAA0B;QAChE,OAAO,CAAC,GAAG,CAAC,wCAAwC,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAA;IACxF,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,+CAA+C,CAAC,CAAA;IAC9D,CAAC;IAED,yCAAyC;IACzC,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,QA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2AServer sets up and starts the A2A server for payments agents.\n * Handles A2A protocol endpoints and allows optional custom endpoints.\n *\n * The server provides a complete A2A protocol implementation with:\n * - JSON-RPC endpoint for A2A messages\n * - Agent Card endpoint (.well-known/agent.json)\n * - Bearer token extraction and validation\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n */\nimport express from 'express'\nimport http from 'http'\nimport { InMemoryTaskStore, A2AExpressApp, AgentExecutor } from '@a2a-js/sdk'\nimport type { AgentCard } from './types'\nimport { PaymentsRequestHandler } from './paymentsRequestHandler'\n\n/**\n * Options for starting the PaymentsA2AServer.\n * Provides comprehensive configuration for A2A server setup.\n */\nexport interface PaymentsA2AServerOptions {\n /** The agent card defining the agent's capabilities and metadata */\n agentCard: AgentCard\n /** User-implemented executor for handling A2A tasks */\n executor: AgentExecutor\n /** Payments service instance for credit validation and burning */\n paymentsService: any\n /** Port number to bind the server to */\n port: number\n /** Custom task store implementation (defaults to InMemoryTaskStore) */\n taskStore?: any\n /** Base path for all A2A routes (defaults to '/') */\n basePath?: string\n /** Whether to expose the agent card at .well-known/agent.json */\n exposeAgentCard?: boolean\n /** Whether to expose default A2A JSON-RPC routes */\n exposeDefaultRoutes?: boolean\n /** Custom Express app instance (defaults to new express()) */\n expressApp?: express.Express\n /** Custom request handler to override JSON-RPC method handling */\n customRequestHandler?: any\n /** Hooks for intercepting requests before/after processing */\n hooks?: {\n /** Called before processing any JSON-RPC request */\n beforeRequest?: (method: string, params: any, req: express.Request) => Promise<void>\n /** Called after processing any JSON-RPC request */\n afterRequest?: (method: string, result: any, req: express.Request) => Promise<void>\n /** Called when a JSON-RPC request fails */\n onError?: (method: string, error: Error, req: express.Request) => Promise<void>\n }\n}\n\n/**\n * Result returned by the server start method.\n * Contains the Express app and HTTP server instances for further customization.\n */\nexport interface PaymentsA2AServerResult {\n /** The configured Express application */\n app: express.Express\n /** The HTTP server instance */\n server: http.Server\n /** The request handler instance for direct access if needed */\n handler: PaymentsRequestHandler\n}\n\n/**\n * Middleware to extract bearer token from HTTP headers and store it in the global context.\n * This middleware is applied after A2A routes are set up and extracts authentication\n * information for credit validation.\n *\n * @param req - Express request object\n * @param res - Express response object\n * @param next - Express next function\n */\nfunction _bearerTokenMiddleware(\n handler: PaymentsRequestHandler,\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n console.log(`[MIDDLEWARE] Processing ${req.method} ${req.url}`)\n\n // Only process POST requests (A2A uses POST for all operations)\n if (req.method !== 'POST') {\n console.log(`[MIDDLEWARE] Skipping non-POST request`)\n return next()\n }\n\n // Extract bearer token from Authorization header\n const authHeader = req.headers.authorization\n let bearerToken: string | undefined\n\n if (authHeader && authHeader.startsWith('Bearer ')) {\n bearerToken = authHeader.substring(7) // Remove 'Bearer ' prefix\n console.log(`[MIDDLEWARE] Extracted bearer token: ${bearerToken.substring(0, 20)}...`)\n } else {\n console.log(`[MIDDLEWARE] No bearer token found in headers`)\n }\n\n // Transform relative URL to absolute URL\n const absoluteUrl = new URL(req.url, req.protocol + '://' + req.get('host')).toString()\n const context = {\n bearerToken,\n urlRequested: absoluteUrl,\n httpMethodRequested: req.method,\n }\n\n // Try to associate context with taskId or messageId\n const taskId = req.body?.taskId || req.body?.id\n const messageId = req.body?.params?.message?.messageId\n\n if (taskId) {\n handler.setHttpRequestContextForTask(taskId, context)\n } else if (messageId) {\n handler.setHttpRequestContextForMessage(messageId, context)\n }\n\n next()\n}\n\n/**\n * PaymentsA2AServer sets up the A2A endpoints and starts the server.\n *\n * This class provides a complete A2A protocol implementation with payment integration.\n * It handles:\n * - JSON-RPC message routing\n * - Agent card exposure\n * - Bearer token extraction\n * - Credit validation and burning\n * - Task execution and streaming\n * - Customizable routes and handlers\n *\n * @example\n * ```typescript\n * const server = PaymentsA2AServer.start({\n * agentCard: myAgentCard,\n * executor: new MyExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * hooks: {\n * beforeRequest: async (method, params, req) => {\n * console.log(`Processing ${method} request`)\n * }\n * }\n * })\n * ```\n */\nexport class PaymentsA2AServer {\n /**\n * Starts the A2A server with the given options.\n *\n * This method sets up the complete A2A server infrastructure including:\n * - Express app configuration\n * - A2A route setup\n * - Middleware for bearer token extraction\n * - Agent card endpoint\n * - HTTP server creation and binding\n *\n * @param options - Server configuration options\n * @returns Server result containing app, server, adapter, and handler instances\n *\n * @example\n * ```typescript\n * const result = PaymentsA2AServer.start({\n * agentCard: buildPaymentAgentCard(baseCard, paymentMetadata),\n * executor: new MyPaymentsExecutor(),\n * paymentsService: payments,\n * port: 41242,\n * basePath: '/a2a/',\n * exposeAgentCard: true,\n * exposeDefaultRoutes: true\n * })\n *\n * // Access the Express app for additional routes\n * result.app.get('/health', (req, res) => res.json({ status: 'ok' }))\n * ```\n */\n static start(options: PaymentsA2AServerOptions): PaymentsA2AServerResult {\n const {\n agentCard,\n executor,\n paymentsService,\n port,\n taskStore,\n basePath = '/',\n exposeAgentCard = true,\n exposeDefaultRoutes = true,\n expressApp,\n customRequestHandler,\n hooks,\n } = options\n\n // Initialize components\n const store = taskStore || new InMemoryTaskStore()\n const handler =\n customRequestHandler ||\n new PaymentsRequestHandler(agentCard, store, executor, paymentsService)\n const appBuilder = new A2AExpressApp(handler)\n\n const app = expressApp || express()\n\n // Apply hooks middleware if provided\n if (hooks) {\n app.use((req, res, next) => {\n if (req.method === 'POST' && req.body?.method) {\n const { method, params } = req.body\n\n // Apply beforeRequest hook\n if (hooks.beforeRequest) {\n hooks.beforeRequest(method, params, req).catch((err) => {\n console.error('[HOOKS] beforeRequest error:', err)\n })\n }\n\n // Apply afterRequest hook by intercepting res.json\n const originalJson = res.json\n res.json = function (data) {\n if (hooks.afterRequest) {\n hooks.afterRequest(method, data, req).catch((err) => {\n console.error('[HOOKS] afterRequest error:', err)\n })\n }\n return originalJson.call(this, data)\n }\n\n // Apply onError hook by catching errors\n const originalSend = res.send\n res.send = function (data) {\n if (data?.error && hooks.onError) {\n hooks\n .onError(method, new Error(data.error.message || 'Unknown error'), req)\n .catch((err) => {\n console.error('[HOOKS] onError error:', err)\n })\n }\n return originalSend.call(this, data)\n }\n }\n next()\n })\n }\n\n if (exposeDefaultRoutes) {\n appBuilder.setupRoutes(app, basePath) //, [bearerTokenMiddleware.bind(null, handler)])\n }\n\n if (exposeAgentCard) {\n app.get(`${basePath}.well-known/agent.json`, (req, res) => {\n res.json(agentCard)\n })\n }\n\n const server = http.createServer(app)\n server.listen(port, () => {\n console.log(`[PaymentsA2A] Server started on http://localhost:${port}${basePath}`)\n if (exposeAgentCard) {\n console.log(\n `[PaymentsA2A] Agent Card: http://localhost:${port}${basePath}.well-known/agent.json`,\n )\n }\n })\n\n return { app, server, handler }\n }\n}\n"]}
|
package/dist/a2a/types.d.ts
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Types and interfaces for the A2A payments integration.
|
|
3
|
-
*
|
|
4
|
-
* This module defines the core types and interfaces used throughout the A2A
|
|
5
|
-
* payments integration. It provides:
|
|
6
|
-
* - Task context structures for user executors
|
|
7
|
-
* - Handler result definitions
|
|
8
|
-
* - Payment metadata interfaces
|
|
9
|
-
* - Re-exports of A2A SDK types for convenience
|
|
10
|
-
*
|
|
11
|
-
* These types ensure type safety and provide clear contracts between
|
|
12
|
-
* the user's executor implementation and the payments system.
|
|
13
|
-
*/
|
|
14
|
-
import type { AgentCard, Task, Message, Artifact, TaskState, Part, TaskStatusUpdateEvent, ExecutionEventBus, AgentExecutor, RequestContext, PushNotificationConfig } from '@a2a-js/sdk';
|
|
15
|
-
/**
|
|
16
|
-
* Context provided to the user's task handler.
|
|
17
|
-
*
|
|
18
|
-
* This interface contains all the information available to the user's
|
|
19
|
-
* executor when handling an A2A task. It includes:
|
|
20
|
-
* - The original user message
|
|
21
|
-
* - Any existing task state (for continuation)
|
|
22
|
-
* - Authentication information
|
|
23
|
-
* - Request metadata
|
|
24
|
-
*
|
|
25
|
-
* The context is created by the PaymentsA2AAdapter and passed to the
|
|
26
|
-
* user's handleTask method.
|
|
27
|
-
*/
|
|
28
|
-
export interface TaskContext {
|
|
29
|
-
/** The original message from the user containing the request */
|
|
30
|
-
userMessage: Message;
|
|
31
|
-
/** Any existing task state (for task continuation scenarios) */
|
|
32
|
-
existingTask?: Task;
|
|
33
|
-
/** Bearer token for authentication and payment validation */
|
|
34
|
-
bearerToken?: string;
|
|
35
|
-
/** Additional metadata from the original request */
|
|
36
|
-
requestMetadata?: Record<string, any>;
|
|
37
|
-
/**
|
|
38
|
-
* Emit a streaming event to the client (SSE, WebSocket, etc.) during task execution.
|
|
39
|
-
* This function allows the executor to send intermediate messages or progress updates.
|
|
40
|
-
*
|
|
41
|
-
* @param parts - Array of message parts (text, etc.) to send as a streaming event
|
|
42
|
-
* @param metadata - Optional metadata to include with the event
|
|
43
|
-
*/
|
|
44
|
-
emitStreamingEvent?: (parts: Part[], metadata?: Record<string, any>) => void;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Result returned by the user's task handler.
|
|
48
|
-
*
|
|
49
|
-
* This interface defines the structure that user executors must return
|
|
50
|
-
* from their handleTask method. The result includes:
|
|
51
|
-
* - Parts that will be converted to A2A Message or Artifact objects
|
|
52
|
-
* - Optional metadata for payment tracking and other purposes
|
|
53
|
-
* - Task state information
|
|
54
|
-
*
|
|
55
|
-
* The result is processed by the PaymentsA2AAdapter to create the
|
|
56
|
-
* appropriate A2A protocol objects and handle payment operations.
|
|
57
|
-
*/
|
|
58
|
-
export interface TaskHandlerResult {
|
|
59
|
-
/** Parts that will be converted to A2A Message or Artifact objects */
|
|
60
|
-
parts: Part[];
|
|
61
|
-
/** Optional metadata including payment information and custom data */
|
|
62
|
-
metadata?: PaymentMetadata & Record<string, any>;
|
|
63
|
-
/** The final state of the task */
|
|
64
|
-
state?: TaskState;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Metadata for payment/credits information to be included in A2A objects.
|
|
68
|
-
*
|
|
69
|
-
* This interface defines the payment-related metadata that can be included
|
|
70
|
-
* in task handler results. This metadata is used for:
|
|
71
|
-
* - Credit tracking and validation
|
|
72
|
-
* - Payment processing
|
|
73
|
-
* - Cost reporting
|
|
74
|
-
* - Plan management
|
|
75
|
-
*
|
|
76
|
-
* The metadata is embedded in A2A Message objects and can be used by
|
|
77
|
-
* clients to understand the cost of operations.
|
|
78
|
-
*/
|
|
79
|
-
export interface PaymentMetadata {
|
|
80
|
-
/** Number of credits used for this operation */
|
|
81
|
-
creditsUsed?: number;
|
|
82
|
-
/** ID of the payment plan associated with this operation */
|
|
83
|
-
planId?: string;
|
|
84
|
-
/** Type of payment model used */
|
|
85
|
-
paymentType?: 'fixed' | 'dynamic';
|
|
86
|
-
/** Human-readable description of the cost */
|
|
87
|
-
costDescription?: string;
|
|
88
|
-
}
|
|
89
|
-
export type { AgentCard, Task, Message, Artifact, TaskState, Part, TaskStatusUpdateEvent, ExecutionEventBus, AgentExecutor, RequestContext, PushNotificationConfig, };
|
|
90
|
-
export type { PaymentsA2AServerOptions } from './server';
|
|
91
|
-
//# sourceMappingURL=types.d.ts.map
|
package/dist/a2a/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/a2a/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,SAAS,EACT,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,aAAa,CAAA;AAEpB;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B,gEAAgE;IAChE,WAAW,EAAE,OAAO,CAAA;IACpB,gEAAgE;IAChE,YAAY,CAAC,EAAE,IAAI,CAAA;IACnB,6DAA6D;IAC7D,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,oDAAoD;IACpD,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACrC;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAA;CAC7E;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,iBAAiB;IAChC,sEAAsE;IACtE,KAAK,EAAE,IAAI,EAAE,CAAA;IACb,sEAAsE;IACtE,QAAQ,CAAC,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAChD,kCAAkC;IAClC,KAAK,CAAC,EAAE,SAAS,CAAA;CAClB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,eAAe;IAC9B,gDAAgD;IAChD,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,4DAA4D;IAC5D,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,iCAAiC;IACjC,WAAW,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACjC,6CAA6C;IAC7C,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB;AAGD,YAAY,EACV,SAAS,EACT,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,sBAAsB,GACvB,CAAA;AAGD,YAAY,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA"}
|
package/dist/a2a/types.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Types and interfaces for the A2A payments integration.
|
|
4
|
-
*
|
|
5
|
-
* This module defines the core types and interfaces used throughout the A2A
|
|
6
|
-
* payments integration. It provides:
|
|
7
|
-
* - Task context structures for user executors
|
|
8
|
-
* - Handler result definitions
|
|
9
|
-
* - Payment metadata interfaces
|
|
10
|
-
* - Re-exports of A2A SDK types for convenience
|
|
11
|
-
*
|
|
12
|
-
* These types ensure type safety and provide clear contracts between
|
|
13
|
-
* the user's executor implementation and the payments system.
|
|
14
|
-
*/
|
|
15
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
-
//# sourceMappingURL=types.js.map
|
package/dist/a2a/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/a2a/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG","sourcesContent":["/**\n * Types and interfaces for the A2A payments integration.\n *\n * This module defines the core types and interfaces used throughout the A2A\n * payments integration. It provides:\n * - Task context structures for user executors\n * - Handler result definitions\n * - Payment metadata interfaces\n * - Re-exports of A2A SDK types for convenience\n *\n * These types ensure type safety and provide clear contracts between\n * the user's executor implementation and the payments system.\n */\n\nimport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n ExecutionEventBus,\n AgentExecutor,\n RequestContext,\n PushNotificationConfig,\n} from '@a2a-js/sdk'\n\n/**\n * Context provided to the user's task handler.\n *\n * This interface contains all the information available to the user's\n * executor when handling an A2A task. It includes:\n * - The original user message\n * - Any existing task state (for continuation)\n * - Authentication information\n * - Request metadata\n *\n * The context is created by the PaymentsA2AAdapter and passed to the\n * user's handleTask method.\n */\nexport interface TaskContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n /** Bearer token for authentication and payment validation */\n bearerToken?: string\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /**\n * Emit a streaming event to the client (SSE, WebSocket, etc.) during task execution.\n * This function allows the executor to send intermediate messages or progress updates.\n *\n * @param parts - Array of message parts (text, etc.) to send as a streaming event\n * @param metadata - Optional metadata to include with the event\n */\n emitStreamingEvent?: (parts: Part[], metadata?: Record<string, any>) => void\n}\n\n/**\n * Result returned by the user's task handler.\n *\n * This interface defines the structure that user executors must return\n * from their handleTask method. The result includes:\n * - Parts that will be converted to A2A Message or Artifact objects\n * - Optional metadata for payment tracking and other purposes\n * - Task state information\n *\n * The result is processed by the PaymentsA2AAdapter to create the\n * appropriate A2A protocol objects and handle payment operations.\n */\nexport interface TaskHandlerResult {\n /** Parts that will be converted to A2A Message or Artifact objects */\n parts: Part[]\n /** Optional metadata including payment information and custom data */\n metadata?: PaymentMetadata & Record<string, any>\n /** The final state of the task */\n state?: TaskState\n}\n\n/**\n * Metadata for payment/credits information to be included in A2A objects.\n *\n * This interface defines the payment-related metadata that can be included\n * in task handler results. This metadata is used for:\n * - Credit tracking and validation\n * - Payment processing\n * - Cost reporting\n * - Plan management\n *\n * The metadata is embedded in A2A Message objects and can be used by\n * clients to understand the cost of operations.\n */\nexport interface PaymentMetadata {\n /** Number of credits used for this operation */\n creditsUsed?: number\n /** ID of the payment plan associated with this operation */\n planId?: string\n /** Type of payment model used */\n paymentType?: 'fixed' | 'dynamic'\n /** Human-readable description of the cost */\n costDescription?: string\n}\n\n// Re-export A2A SDK types for convenience\nexport type {\n AgentCard,\n Task,\n Message,\n Artifact,\n TaskState,\n Part,\n TaskStatusUpdateEvent,\n ExecutionEventBus,\n AgentExecutor,\n RequestContext,\n PushNotificationConfig,\n}\n\n// Re-export server options type for convenience\nexport type { PaymentsA2AServerOptions } from './server'\n"]}
|