@nevermined-io/payments 1.0.0-rc0 → 1.0.0-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/a2a/agent-card.d.ts +85 -0
  2. package/dist/a2a/agent-card.d.ts.map +1 -0
  3. package/dist/a2a/agent-card.js +79 -0
  4. package/dist/a2a/agent-card.js.map +1 -0
  5. package/dist/a2a/index.d.ts +23 -0
  6. package/dist/a2a/index.d.ts.map +1 -0
  7. package/dist/a2a/index.js +42 -0
  8. package/dist/a2a/index.js.map +1 -0
  9. package/dist/a2a/paymentsRequestHandler.d.ts +107 -0
  10. package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -0
  11. package/dist/a2a/paymentsRequestHandler.js +333 -0
  12. package/dist/a2a/paymentsRequestHandler.js.map +1 -0
  13. package/dist/a2a/server.d.ts +126 -0
  14. package/dist/a2a/server.d.ts.map +1 -0
  15. package/dist/a2a/server.js +189 -0
  16. package/dist/a2a/server.js.map +1 -0
  17. package/dist/a2a/types.d.ts +91 -0
  18. package/dist/a2a/types.d.ts.map +1 -0
  19. package/dist/a2a/types.js +16 -0
  20. package/dist/a2a/types.js.map +1 -0
  21. package/dist/api/agents-api.d.ts +196 -0
  22. package/dist/api/agents-api.d.ts.map +1 -0
  23. package/dist/api/agents-api.js +281 -0
  24. package/dist/api/agents-api.js.map +1 -0
  25. package/dist/api/base-payments.d.ts +35 -0
  26. package/dist/api/base-payments.d.ts.map +1 -0
  27. package/dist/api/base-payments.js +62 -0
  28. package/dist/api/base-payments.js.map +1 -0
  29. package/dist/api/nvm-api.d.ts +12 -12
  30. package/dist/api/nvm-api.d.ts.map +1 -1
  31. package/dist/api/nvm-api.js +57 -59
  32. package/dist/api/nvm-api.js.map +1 -1
  33. package/dist/api/plans-api.d.ts +349 -0
  34. package/dist/api/plans-api.d.ts.map +1 -0
  35. package/dist/api/plans-api.js +465 -0
  36. package/dist/api/plans-api.js.map +1 -0
  37. package/dist/api/query-api.d.ts +12 -41
  38. package/dist/api/query-api.d.ts.map +1 -1
  39. package/dist/api/query-api.js +17 -46
  40. package/dist/api/query-api.js.map +1 -1
  41. package/dist/api/requests-api.d.ts +108 -0
  42. package/dist/api/requests-api.d.ts.map +1 -0
  43. package/dist/api/requests-api.js +171 -0
  44. package/dist/api/requests-api.js.map +1 -0
  45. package/dist/common/helper.js.map +1 -1
  46. package/dist/common/payments.error.d.ts +31 -1
  47. package/dist/common/payments.error.d.ts.map +1 -1
  48. package/dist/common/payments.error.js +39 -1
  49. package/dist/common/payments.error.js.map +1 -1
  50. package/dist/common/types.d.ts +57 -3
  51. package/dist/common/types.d.ts.map +1 -1
  52. package/dist/common/types.js +10 -1
  53. package/dist/common/types.js.map +1 -1
  54. package/dist/environments.d.ts +1 -1
  55. package/dist/environments.d.ts.map +1 -1
  56. package/dist/environments.js +19 -28
  57. package/dist/environments.js.map +1 -1
  58. package/dist/index.d.ts +2 -0
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +14 -0
  61. package/dist/index.js.map +1 -1
  62. package/dist/payments.d.ts +35 -408
  63. package/dist/payments.d.ts.map +1 -1
  64. package/dist/payments.js +71 -618
  65. package/dist/payments.js.map +1 -1
  66. package/dist/plans.js.map +1 -1
  67. package/dist/utils.d.ts +30 -0
  68. package/dist/utils.d.ts.map +1 -1
  69. package/dist/utils.js +74 -1
  70. package/dist/utils.js.map +1 -1
  71. package/package.json +13 -6
@@ -0,0 +1,189 @@
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
@@ -0,0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AC,GAAG,EAAE,EAAE;gCACb,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAA;4BAC9C,CAAC,CAAC,CAAA;wBACN,CAAC;wBACD,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;oBACtC,CAAC,CAAA;gBACH,CAAC;gBACD,IAAI,EAAE,CAAA;YACR,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,IAAI,mBAAmB,EAAE,CAAC;YACxB,UAAU,CAAC,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA,CAAC,gDAAgD;QACxF,CAAC;QAED,IAAI,eAAe,EAAE,CAAC;YACpB,GAAG,CAAC,GAAG,CAAC,GAAG,QAAQ,wBAAwB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;gBACxD,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YACrB,CAAC,CAAC,CAAA;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QACrC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;YACvB,OAAO,CAAC,GAAG,CAAC,oDAAoD,IAAI,GAAG,QAAQ,EAAE,CAAC,CAAA;YAClF,IAAI,eAAe,EAAE,CAAC;gBACpB,OAAO,CAAC,GAAG,CACT,8CAA8C,IAAI,GAAG,QAAQ,wBAAwB,CACtF,CAAA;YACH,CAAC;QACH,CAAC,CAAC,CAAA;QAEF,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAA;IACjC,CAAC;CACF;AArHD,8CAqHC","sourcesContent":["/**\n * PaymentsA2AServer 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"]}
@@ -0,0 +1,91 @@
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
@@ -0,0 +1 @@
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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AM,UAAU,CAAA"}
@@ -0,0 +1,16 @@
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
@@ -0,0 +1 @@
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"]}
@@ -0,0 +1,196 @@
1
+ import { AgentAccessCredentials, AgentAPIAttributes, AgentMetadata, NvmAPIResult, PaginationOptions, PaymentOptions, PlanCreditsConfig, PlanMetadata, PlanPriceConfig } from '../common/types';
2
+ import { BasePaymentsAPI } from './base-payments';
3
+ /**
4
+ * The AgentsAPI class provides methods to register and interact with AI Agents on Nevermined.
5
+ */
6
+ export declare class AgentsAPI extends BasePaymentsAPI {
7
+ /**
8
+ * This method is used to create a singleton instance of the AgentsAPI class.
9
+ *
10
+ * @param options - The options to initialize the payments class.
11
+ * @returns The instance of the AgentsAPI class.
12
+ */
13
+ static getInstance(options: PaymentOptions): AgentsAPI;
14
+ /**
15
+ *
16
+ * It registers a new AI Agent on Nevermined.
17
+ * The agent must be associated to one or multiple Payment Plans. Users that are subscribers of a payment plan can query the agent.
18
+ * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.
19
+ * When the plan expires (because the time is over or the credits are consumed), the user needs to renew the plan to continue using the agent.
20
+ *
21
+ * @remarks This method is oriented to AI Builders
22
+ * @remarks To call this method, the NVM API Key must have publication permissions
23
+ *
24
+ * @see https://docs.nevermined.app/docs/tutorials/builders/register-agent
25
+ *
26
+ * @param agentMetadata - @see {@link AgentMetadata}
27
+ * @param agentApi - @see {@link AgentAPIAttributes}
28
+ * @param paymentPlans - the list of payment plans giving access to the agent.
29
+ *
30
+ * @example
31
+ * ```
32
+ * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }
33
+ * const agentApi = { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }
34
+ * const paymentPlans = [planId]
35
+ *
36
+ * const { agentId } = await payments.agents.registerAgent(agentMetadata, agentApi, paymentPlans)
37
+ * ```
38
+ *
39
+ * @returns The unique identifier of the newly created agent (Agent Id).
40
+ */
41
+ registerAgent(agentMetadata: AgentMetadata, agentApi: AgentAPIAttributes, paymentPlans: string[]): Promise<{
42
+ agentId: string;
43
+ }>;
44
+ /**
45
+ *
46
+ * It registers a new AI Agent and a Payment Plan associated to this new agent.
47
+ * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.
48
+ * When the plan expires (because the time is over or the credits are consumed), the user needs to renew the plan to continue using the agent.
49
+ *
50
+ * @remarks This method is oriented to AI Builders
51
+ * @remarks To call this method, the NVM API Key must have publication permissions
52
+ *
53
+ * @see https://docs.nevermined.app/docs/tutorials/builders/register-agent
54
+ *
55
+ * @param agentMetadata - @see {@link AgentMetadata}
56
+ * @param agentApi - @see {@link AgentAPIAttributes}
57
+ * @param planMetadata - @see {@link PlanMetadata}
58
+ * @param priceConfig - @see {@link PlanPriceConfig}
59
+ * @param creditsConfig - @see {@link PlanCreditsConfig}
60
+ *
61
+ * @example
62
+ * ```
63
+ * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }
64
+ * const agentApi { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }
65
+ * const cryptoPriceConfig = getNativeTokenPriceConfig(100n, builderAddress)
66
+ * const 1dayDurationPlan = getExpirableDurationConfig(ONE_DAY_DURATION)
67
+ * const { agentId, planId } = await payments.agents.registerAgentAndPlan(
68
+ * agentMetadata,
69
+ * agentApi,
70
+ * cryptoPriceConfig,
71
+ * 1dayDurationPlan
72
+ * )
73
+ * ```
74
+ *
75
+ * @returns The unique identifier of the newly created agent (agentId).
76
+ * @returns The unique identifier of the newly created plan (planId).
77
+ */
78
+ registerAgentAndPlan(agentMetadata: AgentMetadata, agentApi: AgentAPIAttributes, planMetadata: PlanMetadata, priceConfig: PlanPriceConfig, creditsConfig: PlanCreditsConfig): Promise<{
79
+ agentId: string;
80
+ planId: string;
81
+ txHash: string;
82
+ }>;
83
+ /**
84
+ * Gets the metadata for a given Agent identifier.
85
+ *
86
+ * @param agentId - The unique identifier of the agent.
87
+ * @returns A promise that resolves to the agent's metadata.
88
+ * @throws PaymentsError if the agent is not found.
89
+ *
90
+ * @example
91
+ * ```
92
+ * const plan = payments.agents.getAgent(agentId)
93
+ * ```
94
+ */
95
+ getAgent(agentId: string): Promise<any>;
96
+ /**
97
+ * Gets the list of plans that can be ordered to get access to an agent.
98
+ *
99
+ * @param agentId - The unique identifier of the agent.
100
+ * @param pagination - Optional pagination options to control the number of results returned.p
101
+ * @returns A promise that resolves to the list of all different plans giving access to the agent.
102
+ * @throws PaymentsError if the agent is not found.
103
+ *
104
+ * @example
105
+ * ```
106
+ * const result = payments.agents.getAgentPlans(planId)
107
+ * // {
108
+ * // total: 10,
109
+ * // page: 1,
110
+ * // offset: 5,
111
+ * // plans: [ ..]
112
+ * // }
113
+ * ```
114
+ */
115
+ getAgentPlans(agentId: string, pagination?: PaginationOptions): Promise<any>;
116
+ /**
117
+ * Adds an existing Payment Plan to an AI Agent.
118
+ * After this operation, users with access to the Payment Plan will be able to access the AI Agent.
119
+ *
120
+ * @remarks
121
+ * Only the owner of the Payment Plan can call this method.
122
+ *
123
+ * @param planId - The unique identifier of the Payment Plan.
124
+ * @param agentId - The unique identifier of the AI Agent.
125
+ * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.
126
+ * @throws PaymentsError if unable to add the plan to the agent.
127
+ *
128
+ * @example
129
+ * ```
130
+ * const result = await payments.agents.addPlanToAgent(planId, agentId)
131
+ * // {
132
+ * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',
133
+ * // success: true
134
+ * // }
135
+ * ```
136
+ */
137
+ addPlanToAgent(planId: string, agentId: string): Promise<NvmAPIResult>;
138
+ /**
139
+ * Removes a Payment Plan from an AI Agent.
140
+ * After this operation, users with access to the Payment Plan will no longer be able to access the AI Agent.
141
+ *
142
+ * @remarks
143
+ * Only the owner of the Payment Plan can call this method.
144
+ *
145
+ * @param planId - The unique identifier of the Payment Plan.
146
+ * @param agentId - The unique identifier of the AI Agent.
147
+ * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.
148
+ * @throws PaymentsError if unable to remove the plan from the agent.
149
+ *
150
+ * @example
151
+ * ```
152
+ * const result = await payments.agents.removePlanFromAgent(planId, agentId)
153
+ * // {
154
+ * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',
155
+ * // success: true
156
+ * // }
157
+ * ```
158
+ */
159
+ removePlanFromAgent(planId: string, agentId: string): Promise<NvmAPIResult>;
160
+ /**
161
+ * When the user calling this method is a valid subscriber, it generates an access token related to the Payment Plan and the AI Agent.
162
+ * The access token can be used to query the AI Agent's API endpoints. The access token is unique for the subscriber, payment plan and agent.
163
+ *
164
+ * @remarks
165
+ * Only a valid subscriber of the Payment Plan can generate a valid access token.
166
+ * @remarks
167
+ * The access token generated can be send by HTTP Authorization header to query the AI Agent's API endpoints.
168
+ *
169
+ * @param planId - The unique identifier of the Payment Plan.
170
+ * @param agentId - The unique identifier of the AI Agent.
171
+ * @returns @see {@link AgentAccessCredentials} The access token and the proxy URL to query the agent.
172
+ * @throws PaymentsError if unable to remove the plan from the agent.
173
+ *
174
+ * @example
175
+ * ```
176
+ * const credentials = await payments.agents.getAgentAccessToken(planId, agentId)
177
+ * // {
178
+ * // accessToken: 'eyJhbGciOiJFUzI1NksifQ.eyJpc3MiOiIweD ...',
179
+ * // proxies: ['https://proxy.nevermined.network/']
180
+ * // }
181
+ *
182
+ * const agentHTTPOptions = {
183
+ * method: 'POST',
184
+ * headers: {
185
+ * Accept: 'application/json',
186
+ * 'Content-Type': 'application/json',
187
+ * Authorization: `Bearer ${credentials.accessToken}`,
188
+ * }
189
+ * }
190
+ *
191
+ * const response = await fetch(new URL(agentEndpoint), agentHTTPOptions)
192
+ * ```
193
+ */
194
+ getAgentAccessToken(planId: string, agentId: string): Promise<AgentAccessCredentials>;
195
+ }
196
+ //# sourceMappingURL=agents-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents-api.d.ts","sourceRoot":"","sources":["../../src/api/agents-api.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,eAAe,EAChB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAWjD;;GAEG;AACH,qBAAa,SAAU,SAAQ,eAAe;IAC5C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAA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