@nevermined-io/payments 1.0.2 → 1.0.4
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 +39 -0
- package/dist/a2a/paymentsClient.d.ts +6 -0
- package/dist/a2a/paymentsClient.d.ts.map +1 -1
- package/dist/a2a/paymentsClient.js +8 -0
- package/dist/a2a/paymentsClient.js.map +1 -1
- package/dist/a2a/server.d.ts +0 -1
- package/dist/a2a/server.d.ts.map +1 -1
- package/dist/api/agents-api.d.ts +2 -2
- package/dist/api/agents-api.js +2 -2
- package/dist/api/agents-api.js.map +1 -1
- package/dist/api/base-payments.d.ts +2 -2
- package/dist/api/base-payments.d.ts.map +1 -1
- package/dist/api/nvm-api.d.ts +1 -1
- package/dist/api/nvm-api.js.map +1 -1
- package/dist/api/plans-api.d.ts +5 -5
- package/dist/api/plans-api.js +5 -5
- package/dist/api/plans-api.js.map +1 -1
- package/dist/common/helper.d.ts.map +1 -1
- package/dist/common/types.d.ts +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/mcp/core/auth.d.ts +14 -2
- package/dist/mcp/core/auth.d.ts.map +1 -1
- package/dist/mcp/core/auth.js +107 -197
- package/dist/mcp/core/auth.js.map +1 -1
- package/dist/mcp/core/paywall.d.ts.map +1 -1
- package/dist/mcp/core/paywall.js +42 -20
- package/dist/mcp/core/paywall.js.map +1 -1
- package/dist/mcp/http/mcp-handler.d.ts +0 -1
- package/dist/mcp/http/mcp-handler.d.ts.map +1 -1
- package/dist/mcp/http/oauth-router.d.ts.map +1 -1
- package/dist/mcp/index.d.ts +7 -8
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/types/http.types.d.ts +0 -1
- package/dist/mcp/types/http.types.d.ts.map +1 -1
- package/dist/mcp/types/paywall.types.d.ts +6 -0
- package/dist/mcp/types/paywall.types.d.ts.map +1 -1
- package/dist/mcp/types/paywall.types.js.map +1 -1
- package/dist/payments.d.ts +12 -13
- package/dist/payments.d.ts.map +1 -1
- package/dist/plans.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -467,6 +467,45 @@ const result = await client.callTool({
|
|
|
467
467
|
- `credits` can be a `bigint` or `(ctx) => bigint` with `{ args, result }`. Use `args` for input-based pricing and `result` for output-based pricing.
|
|
468
468
|
- `name` builds the logical URL `mcp://{serverName}/{kind}/{name}`.
|
|
469
469
|
|
|
470
|
+
## Documentation
|
|
471
|
+
|
|
472
|
+
Comprehensive markdown documentation is available in the `markdown/` directory:
|
|
473
|
+
|
|
474
|
+
- **Installation** - Setup and prerequisites
|
|
475
|
+
- **Initialization** - Getting started with the SDK
|
|
476
|
+
- **Payment Plans** - Creating and managing payment plans
|
|
477
|
+
- **Agents** - Registering and managing AI agents
|
|
478
|
+
- **Static Resources** - Publishing static content
|
|
479
|
+
- **Payments & Balance** - Ordering plans and checking balances
|
|
480
|
+
- **Querying Agents** - Using X402 access tokens
|
|
481
|
+
- **Request Validation** - Verifying and settling permissions
|
|
482
|
+
- **MCP Integration** - Model Context Protocol setup
|
|
483
|
+
- **A2A Integration** - Agent-to-Agent protocol setup
|
|
484
|
+
- **X402 Protocol** - Complete payment protocol specification
|
|
485
|
+
|
|
486
|
+
### Automated Documentation
|
|
487
|
+
|
|
488
|
+
The documentation is automatically maintained and published:
|
|
489
|
+
|
|
490
|
+
- **On Push**: Documentation metadata is updated when source code changes
|
|
491
|
+
- **On Tag**: Documentation is published to [nevermined-io/docs_mintlify](https://github.com/nevermined-io/docs_mintlify) repository
|
|
492
|
+
|
|
493
|
+
For more details, see [DOCUMENTATION.md](./DOCUMENTATION.md).
|
|
494
|
+
|
|
495
|
+
### Quick Commands
|
|
496
|
+
|
|
497
|
+
```bash
|
|
498
|
+
# Validate documentation
|
|
499
|
+
./scripts/generate-docs.sh
|
|
500
|
+
|
|
501
|
+
# Publish documentation (manual)
|
|
502
|
+
./scripts/publish-docs.sh
|
|
503
|
+
|
|
504
|
+
# View workflows
|
|
505
|
+
gh run list --workflow=update-docs.yml
|
|
506
|
+
gh run list --workflow=publish-docs.yml
|
|
507
|
+
```
|
|
508
|
+
|
|
470
509
|
## License
|
|
471
510
|
|
|
472
511
|
```text
|
|
@@ -33,6 +33,12 @@ export declare class PaymentsClient extends A2AClient {
|
|
|
33
33
|
* Clears the cached access token for this client instance.
|
|
34
34
|
*/
|
|
35
35
|
clearToken(): void;
|
|
36
|
+
/**
|
|
37
|
+
* Type guard to check if a JSON-RPC response is an error response.
|
|
38
|
+
* @param response - The JSON-RPC response to check
|
|
39
|
+
* @returns true if the response contains an error, false otherwise
|
|
40
|
+
*/
|
|
41
|
+
private isErrorResponse;
|
|
36
42
|
/**
|
|
37
43
|
* Sends a message to the agent, managing authentication automatically.
|
|
38
44
|
* @param params - The parameters for sending the message.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paymentsClient.d.ts","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACtC,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAI9C;;;GAGG;AACH,qBAAa,cAAe,SAAQ,SAAS;IACpC,QAAQ,EAAE,QAAQ,CAAA;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,WAAW,CAAe;IAElC;;;;;;;OAOG;IACH,OAAO;IAQP;;;OAGG;WACiB,MAAM,CACxB,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,aAAa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,CAAC,qCAAqC,CAAC;IASjD;;;;OAIG;IACU,gCAAgC,CAC3C,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,qCAAqC,CAAC;IAUjD;;;;;;OAMG;cACa,0BAA0B,CAAC,OAAO,EAAE,SAAS,EAC3D,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,SAAS,CAAC;CA2CtB;AAED,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,GACtC,MAAM,aAAa,CAAA"}
|
|
@@ -49,6 +49,14 @@ export class PaymentsClient extends A2AClient {
|
|
|
49
49
|
clearToken() {
|
|
50
50
|
this.accessToken = null;
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Type guard to check if a JSON-RPC response is an error response.
|
|
54
|
+
* @param response - The JSON-RPC response to check
|
|
55
|
+
* @returns true if the response contains an error, false otherwise
|
|
56
|
+
*/
|
|
57
|
+
isErrorResponse(response) {
|
|
58
|
+
return response && typeof response === 'object' && 'error' in response;
|
|
59
|
+
}
|
|
52
60
|
/**
|
|
53
61
|
* Sends a message to the agent, managing authentication automatically.
|
|
54
62
|
* @param params - The parameters for sending the message.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAW3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAGnC;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAM3C;;;;;;;OAOG;IACH,YAAoB,SAAoB,EAAE,Q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C,OAAO,CAAM,EAAE,CAAC;gBAChB,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;oBAAE,MAAM,CAAC,CAAA;gBAC5F,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAA;QAC7C,IAAI,WAAW,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CACrB,iDAAiD,MAAM,cAAc,SAAS,SAAS,WAAW,CAAC,EAAE,iDAAiD,EACtJ,gBAAgB,CACjB,CAAA;QACH,CAAC;QACD,OAAO,WAAwB,CAAA;IACjC,CAAC;CACF","sourcesContent":["import { Payments } from '../index.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\nimport { A2AClient } from '@a2a-js/sdk/client'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { AgentCard } from './types.js'\n\n/**\n * PaymentsClient is a high-level client for A2A agents with payments integration.\n * Each instance is bound to a specific agentId and planId.\n */\nexport class PaymentsClient extends A2AClient {\n public payments: Payments\n private readonly agentId: string\n private readonly planId: string\n private accessToken: string | null\n\n /**\n * Creates a new PaymentsClient instance.\n * @param agentBaseUrl - The base URL of the agent (e.g. http://localhost:3005/a2a/).\n * @param payments - The Payments object.\n * @param agentId - The ID of the agent.\n * @param planId - The ID of the plan.\n * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').\n */\n private constructor(agentCard: AgentCard, payments: Payments, agentId: string, planId: string) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.accessToken = null\n }\n\n /**\n * Creates a PaymentsClient by fetching the AgentCard first and then\n * constructing the underlying A2AClient with the AgentCard object.\n */\n public static async create(\n agentBaseUrl: string,\n payments: Payments,\n agentId: string,\n planId: string,\n agentCardPath = '.well-known/agent.json',\n ): Promise<PaymentsClient> {\n const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString()\n const a2a = await A2AClient.fromCardUrl(agentCardUrl)\n const agentCard = await (a2a as any).getAgentCard()\n return new PaymentsClient(agentCard as AgentCard, payments, agentId, planId)\n }\n\n /**\n * Gets and caches the access token for this client instance.\n * @returns The access token string.\n */\n private async _getX402AccessToken(): Promise<string> {\n if (this.accessToken) {\n return this.accessToken\n }\n const accessParams = await this.payments.x402.getX402AccessToken(this.planId, this.agentId)\n this.accessToken = accessParams.accessToken\n return this.accessToken\n }\n\n /**\n * Clears the cached access token for this client instance.\n */\n public clearToken() {\n this.accessToken = null\n }\n\n /**\n * Sends a message to the agent, managing authentication automatically.\n * @param params - The parameters for sending the message.\n * @returns The response from the agent.\n */\n public async sendA2AMessage(params: MessageSendParams): Promise<SendMessageResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n params,\n headers,\n )\n }\n\n /**\n * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).\n * Push notification configuration can be specified in `params.configuration`.\n * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - The parameters for sending the message.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.\n */\n public async *sendA2AMessageStream(\n params: MessageSendParams,\n ): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error(\n 'Agent does not support streaming (AgentCard.capabilities.streaming is not true).',\n )\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\"Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.\")\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Parses an HTTP response body as an A2A Server-Sent Event stream.\n * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,\n * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).\n * @param response -The HTTP Response object whose body is the SSE stream.\n * @param originalRequestId - The ID of the client's JSON-RPC request that initiated this stream.\n * Used to validate the `id` in the streamed JSON-RPC responses.\n * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.\n */\n private async *_parseA2AStream<TStreamItem>(\n response: Response,\n originalRequestId: number | string | null,\n ): AsyncGenerator<TStreamItem, void, undefined> {\n if (!response.body) {\n throw new Error('SSE response body is undefined. Cannot read stream.')\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()\n let buffer = '' // Holds incomplete lines from the stream\n let eventDataBuffer = '' // Holds accumulated 'data:' lines for the current event\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n // Process any final buffered event data if the stream ends abruptly after a 'data:' line\n if (eventDataBuffer.trim()) {\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n }\n break // Stream finished\n }\n\n buffer += value // Append new chunk to buffer\n let lineEndIndex\n // Process all complete lines in the buffer\n while ((lineEndIndex = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.substring(0, lineEndIndex).trim() // Get and trim the line\n buffer = buffer.substring(lineEndIndex + 1) // Remove processed line from buffer\n\n if (line === '') {\n // Empty line: signifies the end of an event\n if (eventDataBuffer) {\n // If we have accumulated data for an event\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n eventDataBuffer = '' // Reset buffer for the next event\n }\n } else if (line.startsWith('data:')) {\n eventDataBuffer += line.substring(5).trimStart() + '\\n' // Append data (multi-line data is possible)\n } else if (line.startsWith(':')) {\n // This is a comment line in SSE, ignore it.\n }\n }\n }\n } catch (error: any) {\n throw new PaymentsError(error.message, 'payments_error')\n } finally {\n reader.releaseLock() // Ensure the reader lock is released\n }\n }\n\n /**\n * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.\n * @param jsonData - The string content from one or more 'data:' lines of an SSE event.\n * @param originalRequestId - The ID of the client's request that initiated the stream.\n * @returns The `result` field of the parsed JSON-RPC success response.\n * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.\n */\n private _processEventData<TStreamItem>(\n jsonData: string,\n originalRequestId: number | string | null,\n ): TStreamItem {\n if (!jsonData.trim()) {\n throw new Error('Attempted to process empty SSE event data.')\n }\n try {\n // SSE data can be multi-line, ensure it's treated as a single JSON string.\n const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\\n$/, ''))\n\n // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.\n const a2aStreamResponse: any = sseJsonRpcResponse\n\n if (a2aStreamResponse.id !== originalRequestId) {\n // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,\n // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.\n throw new PaymentsError(\n `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`,\n 'payments_error',\n )\n }\n\n if (this.isErrorResponse && this.isErrorResponse(a2aStreamResponse)) {\n const err = a2aStreamResponse.error\n throw new PaymentsError(\n `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`,\n )\n }\n\n // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses\n if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {\n throw new PaymentsError(\n `SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`,\n 'payments_error',\n )\n }\n\n return a2aStreamResponse as TStreamItem\n } catch (e: any) {\n // Catch errors from JSON.parse or if it's an error response that was thrown by this function\n if (\n e.message.startsWith('SSE event contained an error') ||\n e.message.startsWith(\"SSE event JSON-RPC response is missing 'result' field\")\n ) {\n throw new PaymentsError(e.message, 'payments_error')\n }\n\n throw new PaymentsError(\n `Failed to parse SSE event data: \"${jsonData.substring(0, 100)}...\". Original error: ${e.message}`,\n 'payments_error',\n )\n }\n }\n\n /**\n * Resubscribes to a task's event stream using Server-Sent Events (SSE).\n * This is used if a previous SSE connection for an active task was broken.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - Parameters containing the taskId.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n */\n public async *resubscribeA2ATask(params: TaskIdParams): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error('Agent does not support streaming (required for tasks/resubscribe).')\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'tasks/resubscribe',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\n \"Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.\",\n )\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Retrieves a task by its ID, managing authentication automatically.\n * @param params - The parameters for the task query.\n * @returns The task response.\n */\n public async getA2ATask(params: TaskQueryParams): Promise<GetTaskResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskQueryParams, GetTaskResponse>(\n 'tasks/get',\n params,\n headers,\n )\n }\n\n /**\n * Sets or updates the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async setA2ATaskPushNotificationConfig(\n params: TaskPushNotificationConfig,\n ): Promise<SetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse\n >('tasks/pushNotificationConfig/set', params, headers)\n }\n\n /**\n * Gets the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async getA2ATaskPushNotificationConfig(\n params: TaskIdParams,\n ): Promise<GetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskIdParams, GetTaskPushNotificationConfigResponse>(\n 'tasks/pushNotificationConfig/get',\n params,\n headers,\n )\n }\n\n /**\n * Internal helper to make a JSON-RPC POST request with custom headers.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @param headers - Optional custom headers.\n * @returns The response from the agent.\n */\n protected async _postRpcRequestWithHeaders<TParams, TResponse>(\n method: string,\n params: TParams,\n headers?: Record<string, string>,\n ): Promise<TResponse> {\n const endpoint = await (this as any)._getServiceEndpoint()\n const requestId = uuidv4()\n const rpcRequest = { jsonrpc: '2.0', method, params, id: requestId }\n const httpResponse = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(headers || {}),\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!httpResponse.ok) {\n let errorBodyText = '(empty or non-JSON response)'\n try {\n errorBodyText = await httpResponse.text()\n const errorJson = JSON.parse(errorBodyText)\n if (!errorJson.jsonrpc && errorJson.error) {\n throw new Error(\n `RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`,\n )\n } else if (!errorJson.jsonrpc) {\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n }\n const rpcResponse = await httpResponse.json()\n if (rpcResponse.id !== requestId) {\n throw new PaymentsError(\n `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`,\n 'payments_error',\n )\n }\n return rpcResponse as TResponse\n }\n}\n\nexport type {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n"]}
|
|
1
|
+
{"version":3,"file":"paymentsClient.js","sourceRoot":"","sources":["../../src/a2a/paymentsClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAW3D,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAGnC;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,SAAS;IAM3C;;;;;;;OAOG;IACH,YAAoB,SAAoB,EAAE,QAAkB,EAAE,OAAe,EAAE,MAAc;QAC3F,KAAK,CAAC,SAAS,CAAC,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;IACzB,CAAC;IAED;;;O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AC,gBAAgB,CAAC;oBAAE,MAAM,CAAC,CAAA;gBAC5F,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,aAAa,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,UAAU,eAAe,aAAa,EAAE,CAClH,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAA;QAC7C,IAAI,WAAW,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACjC,MAAM,IAAI,aAAa,CACrB,iDAAiD,MAAM,cAAc,SAAS,SAAS,WAAW,CAAC,EAAE,iDAAiD,EACtJ,gBAAgB,CACjB,CAAA;QACH,CAAC;QACD,OAAO,WAAwB,CAAA;IACjC,CAAC;CACF","sourcesContent":["import { Payments } from '../index.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\nimport { A2AClient } from '@a2a-js/sdk/client'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { AgentCard } from './types.js'\n\n/**\n * PaymentsClient is a high-level client for A2A agents with payments integration.\n * Each instance is bound to a specific agentId and planId.\n */\nexport class PaymentsClient extends A2AClient {\n public payments: Payments\n private readonly agentId: string\n private readonly planId: string\n private accessToken: string | null\n\n /**\n * Creates a new PaymentsClient instance.\n * @param agentBaseUrl - The base URL of the agent (e.g. http://localhost:3005/a2a/).\n * @param payments - The Payments object.\n * @param agentId - The ID of the agent.\n * @param planId - The ID of the plan.\n * @param agentCardPath - Optional path to the agent card relative to base URL (defaults to '.well-known/agent.json').\n */\n private constructor(agentCard: AgentCard, payments: Payments, agentId: string, planId: string) {\n super(agentCard)\n this.payments = payments\n this.agentId = agentId\n this.planId = planId\n this.accessToken = null\n }\n\n /**\n * Creates a PaymentsClient by fetching the AgentCard first and then\n * constructing the underlying A2AClient with the AgentCard object.\n */\n public static async create(\n agentBaseUrl: string,\n payments: Payments,\n agentId: string,\n planId: string,\n agentCardPath = '.well-known/agent.json',\n ): Promise<PaymentsClient> {\n const agentCardUrl = new URL(agentCardPath, agentBaseUrl).toString()\n const a2a = await A2AClient.fromCardUrl(agentCardUrl)\n const agentCard = await (a2a as any).getAgentCard()\n return new PaymentsClient(agentCard as AgentCard, payments, agentId, planId)\n }\n\n /**\n * Gets and caches the access token for this client instance.\n * @returns The access token string.\n */\n private async _getX402AccessToken(): Promise<string> {\n if (this.accessToken) {\n return this.accessToken\n }\n const accessParams = await this.payments.x402.getX402AccessToken(this.planId, this.agentId)\n this.accessToken = accessParams.accessToken\n return this.accessToken\n }\n\n /**\n * Clears the cached access token for this client instance.\n */\n public clearToken() {\n this.accessToken = null\n }\n\n /**\n * Type guard to check if a JSON-RPC response is an error response.\n * @param response - The JSON-RPC response to check\n * @returns true if the response contains an error, false otherwise\n */\n private isErrorResponse(response: any): boolean {\n return response && typeof response === 'object' && 'error' in response\n }\n\n /**\n * Sends a message to the agent, managing authentication automatically.\n * @param params - The parameters for sending the message.\n * @returns The response from the agent.\n */\n public async sendA2AMessage(params: MessageSendParams): Promise<SendMessageResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<MessageSendParams, SendMessageResponse>(\n 'message/send',\n params,\n headers,\n )\n }\n\n /**\n * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).\n * Push notification configuration can be specified in `params.configuration`.\n * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - The parameters for sending the message.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.\n */\n public async *sendA2AMessageStream(\n params: MessageSendParams,\n ): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error(\n 'Agent does not support streaming (AgentCard.capabilities.streaming is not true).',\n )\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'message/stream',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\"Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.\")\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Parses an HTTP response body as an A2A Server-Sent Event stream.\n * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,\n * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).\n * @param response -The HTTP Response object whose body is the SSE stream.\n * @param originalRequestId - The ID of the client's JSON-RPC request that initiated this stream.\n * Used to validate the `id` in the streamed JSON-RPC responses.\n * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.\n */\n private async *_parseA2AStream<TStreamItem>(\n response: Response,\n originalRequestId: number | string | null,\n ): AsyncGenerator<TStreamItem, void, undefined> {\n if (!response.body) {\n throw new Error('SSE response body is undefined. Cannot read stream.')\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()\n let buffer = '' // Holds incomplete lines from the stream\n let eventDataBuffer = '' // Holds accumulated 'data:' lines for the current event\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n // Process any final buffered event data if the stream ends abruptly after a 'data:' line\n if (eventDataBuffer.trim()) {\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n }\n break // Stream finished\n }\n\n buffer += value // Append new chunk to buffer\n let lineEndIndex\n // Process all complete lines in the buffer\n while ((lineEndIndex = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.substring(0, lineEndIndex).trim() // Get and trim the line\n buffer = buffer.substring(lineEndIndex + 1) // Remove processed line from buffer\n\n if (line === '') {\n // Empty line: signifies the end of an event\n if (eventDataBuffer) {\n // If we have accumulated data for an event\n const result = this._processEventData<TStreamItem>(eventDataBuffer, originalRequestId)\n yield result\n eventDataBuffer = '' // Reset buffer for the next event\n }\n } else if (line.startsWith('data:')) {\n eventDataBuffer += line.substring(5).trimStart() + '\\n' // Append data (multi-line data is possible)\n } else if (line.startsWith(':')) {\n // This is a comment line in SSE, ignore it.\n }\n }\n }\n } catch (error: any) {\n throw new PaymentsError(error.message, 'payments_error')\n } finally {\n reader.releaseLock() // Ensure the reader lock is released\n }\n }\n\n /**\n * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.\n * @param jsonData - The string content from one or more 'data:' lines of an SSE event.\n * @param originalRequestId - The ID of the client's request that initiated the stream.\n * @returns The `result` field of the parsed JSON-RPC success response.\n * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.\n */\n private _processEventData<TStreamItem>(\n jsonData: string,\n originalRequestId: number | string | null,\n ): TStreamItem {\n if (!jsonData.trim()) {\n throw new Error('Attempted to process empty SSE event data.')\n }\n try {\n // SSE data can be multi-line, ensure it's treated as a single JSON string.\n const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\\n$/, ''))\n\n // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.\n const a2aStreamResponse: any = sseJsonRpcResponse\n\n if (a2aStreamResponse.id !== originalRequestId) {\n // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,\n // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.\n throw new PaymentsError(\n `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`,\n 'payments_error',\n )\n }\n\n if (this.isErrorResponse && this.isErrorResponse(a2aStreamResponse)) {\n const err = a2aStreamResponse.error\n throw new PaymentsError(\n `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`,\n )\n }\n\n // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses\n if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {\n throw new PaymentsError(\n `SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`,\n 'payments_error',\n )\n }\n\n return a2aStreamResponse as TStreamItem\n } catch (e: any) {\n // Catch errors from JSON.parse or if it's an error response that was thrown by this function\n if (\n e.message.startsWith('SSE event contained an error') ||\n e.message.startsWith(\"SSE event JSON-RPC response is missing 'result' field\")\n ) {\n throw new PaymentsError(e.message, 'payments_error')\n }\n\n throw new PaymentsError(\n `Failed to parse SSE event data: \"${jsonData.substring(0, 100)}...\". Original error: ${e.message}`,\n 'payments_error',\n )\n }\n }\n\n /**\n * Resubscribes to a task's event stream using Server-Sent Events (SSE).\n * This is used if a previous SSE connection for an active task was broken.\n * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).\n * @param params - Parameters containing the taskId.\n * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).\n */\n public async *resubscribeA2ATask(params: TaskIdParams): AsyncGenerator<any, void, undefined> {\n const agentCard = await (this as any).agentCardPromise\n if (!agentCard.capabilities?.streaming) {\n throw new Error('Agent does not support streaming (required for tasks/resubscribe).')\n }\n const endpoint = await (this as any)._getServiceEndpoint()\n const clientRequestId = uuidv4()\n const rpcRequest = {\n jsonrpc: '2.0',\n method: 'tasks/resubscribe',\n params: params as { [key: string]: any },\n id: clientRequestId,\n }\n const accessToken = await this._getX402AccessToken()\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n const errorJson = JSON.parse(errorBody)\n if (errorJson.error) {\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('HTTP error establishing stream')) throw e\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`,\n )\n }\n throw new Error(\n `HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`,\n )\n }\n if (!response.headers.get('Content-Type')?.startsWith('text/event-stream')) {\n throw new Error(\n \"Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.\",\n )\n }\n // Parse and yield SSE events\n for await (const event of this._parseA2AStream(response, clientRequestId)) {\n yield event\n }\n }\n\n /**\n * Retrieves a task by its ID, managing authentication automatically.\n * @param params - The parameters for the task query.\n * @returns The task response.\n */\n public async getA2ATask(params: TaskQueryParams): Promise<GetTaskResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskQueryParams, GetTaskResponse>(\n 'tasks/get',\n params,\n headers,\n )\n }\n\n /**\n * Sets or updates the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async setA2ATaskPushNotificationConfig(\n params: TaskPushNotificationConfig,\n ): Promise<SetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse\n >('tasks/pushNotificationConfig/set', params, headers)\n }\n\n /**\n * Gets the push notification configuration for a given task, managing authentication automatically.\n * @param params - The parameters for the task push notification configuration.\n * @returns The response from the agent.\n */\n public async getA2ATaskPushNotificationConfig(\n params: TaskIdParams,\n ): Promise<GetTaskPushNotificationConfigResponse> {\n const accessToken = await this._getX402AccessToken()\n const headers = { Authorization: `Bearer ${accessToken}` }\n return this._postRpcRequestWithHeaders<TaskIdParams, GetTaskPushNotificationConfigResponse>(\n 'tasks/pushNotificationConfig/get',\n params,\n headers,\n )\n }\n\n /**\n * Internal helper to make a JSON-RPC POST request with custom headers.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @param headers - Optional custom headers.\n * @returns The response from the agent.\n */\n protected async _postRpcRequestWithHeaders<TParams, TResponse>(\n method: string,\n params: TParams,\n headers?: Record<string, string>,\n ): Promise<TResponse> {\n const endpoint = await (this as any)._getServiceEndpoint()\n const requestId = uuidv4()\n const rpcRequest = { jsonrpc: '2.0', method, params, id: requestId }\n const httpResponse = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(headers || {}),\n },\n body: JSON.stringify(rpcRequest),\n })\n if (!httpResponse.ok) {\n let errorBodyText = '(empty or non-JSON response)'\n try {\n errorBodyText = await httpResponse.text()\n const errorJson = JSON.parse(errorBodyText)\n if (!errorJson.jsonrpc && errorJson.error) {\n throw new Error(\n `RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`,\n )\n } else if (!errorJson.jsonrpc) {\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n } catch (e: any) {\n if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for')) throw e\n throw new Error(\n `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,\n )\n }\n }\n const rpcResponse = await httpResponse.json()\n if (rpcResponse.id !== requestId) {\n throw new PaymentsError(\n `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`,\n 'payments_error',\n )\n }\n return rpcResponse as TResponse\n }\n}\n\nexport type {\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n"]}
|
package/dist/a2a/server.d.ts
CHANGED
package/dist/a2a/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/a2a/server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/a2a/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAA8C,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC9F,OAAO,KAAK,EAAE,SAAS,EAAsB,MAAM,YAAY,CAAA;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAA;AA4BpE;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,SAAS,EAAE,SAAS,CAAA;IACpB,uDAAuD;I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C,OAAO,CAAA;IACpB,+BAA+B;IAC/B,MAAM,EAAE,IAAI,CAAC,MAAM,CAAA;IACnB,+DAA+D;IAC/D,OAAO,EAAE,sBAAsB,CAAA;IAC/B,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAA;IACZ;;;OAGG;IACH,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAC3B;AAiHD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,qBAAa,iBAAiB;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,wBAAwB,GAAG,uBAAuB;CAmKzE"}
|
package/dist/api/agents-api.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export declare class AgentsAPI extends BasePaymentsAPI {
|
|
|
21
21
|
* @remarks This method is oriented to AI Builders
|
|
22
22
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
23
23
|
*
|
|
24
|
-
* @see https://
|
|
24
|
+
* @see https://nevermined.ai/docs/tutorials/builders/register-agent
|
|
25
25
|
*
|
|
26
26
|
* @param agentMetadata - @see {@link AgentMetadata}
|
|
27
27
|
* @param agentApi - @see {@link AgentAPIAttributes}
|
|
@@ -50,7 +50,7 @@ export declare class AgentsAPI extends BasePaymentsAPI {
|
|
|
50
50
|
* @remarks This method is oriented to AI Builders
|
|
51
51
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
52
52
|
*
|
|
53
|
-
* @see https://
|
|
53
|
+
* @see https://nevermined.ai/docs/tutorials/builders/register-agent
|
|
54
54
|
*
|
|
55
55
|
* @param agentMetadata - @see {@link AgentMetadata}
|
|
56
56
|
* @param agentApi - @see {@link AgentAPIAttributes}
|
package/dist/api/agents-api.js
CHANGED
|
@@ -25,7 +25,7 @@ export class AgentsAPI extends BasePaymentsAPI {
|
|
|
25
25
|
* @remarks This method is oriented to AI Builders
|
|
26
26
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
27
27
|
*
|
|
28
|
-
* @see https://
|
|
28
|
+
* @see https://nevermined.ai/docs/tutorials/builders/register-agent
|
|
29
29
|
*
|
|
30
30
|
* @param agentMetadata - @see {@link AgentMetadata}
|
|
31
31
|
* @param agentApi - @see {@link AgentAPIAttributes}
|
|
@@ -66,7 +66,7 @@ export class AgentsAPI extends BasePaymentsAPI {
|
|
|
66
66
|
* @remarks This method is oriented to AI Builders
|
|
67
67
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
68
68
|
*
|
|
69
|
-
* @see https://
|
|
69
|
+
* @see https://nevermined.ai/docs/tutorials/builders/register-agent
|
|
70
70
|
*
|
|
71
71
|
* @param agentMetadata - @see {@link AgentMetadata}
|
|
72
72
|
* @param agentApi - @see {@link AgentAPIAttributes}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents-api.js","sourceRoot":"","sources":["../../src/api/agents-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAIL,iBAAiB,GAKlB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACpD,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,uBAAuB,EACvB,sBAAsB,EACtB,gCAAgC,EAChC,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,cAAc,CAAA;AAErB;;GAEG;AACH,MAAM,OAAO,SAAU,SAAQ,eAAe;IAC5C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,SAAS,CAAC,OAAO,CAAC,CAAA;IAC/B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACI,KAAK,CAAC,aAAa,CACxB,aAA4B,EAC5B,QAA4B,EAC5B,YAAsB;QAEtB,MAAM,IAAI,GAAG;YACX,kBAAkB,EAAE,aAAa;YACjC,kBAAkB,EAAE,QAAQ;YA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AAC,IAAI,EAAE,CAAC,CAAA;QAC5F,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAA;IACxB,CAAC;CACF","sourcesContent":["import { PaymentsError } from '../common/payments.error.js'\nimport {\n AgentAPIAttributes,\n AgentMetadata,\n NvmAPIResult,\n PaginationOptions,\n PaymentOptions,\n PlanCreditsConfig,\n PlanMetadata,\n PlanPriceConfig,\n} from '../common/types.js'\nimport { BasePaymentsAPI } from './base-payments.js'\nimport {\n API_URL_ADD_PLAN_AGENT,\n API_URL_GET_AGENT,\n API_URL_GET_AGENT_PLANS,\n API_URL_REGISTER_AGENT,\n API_URL_REGISTER_AGENTS_AND_PLAN,\n API_URL_REMOVE_PLAN_AGENT,\n API_URL_UPDATE_AGENT,\n} from './nvm-api.js'\n\n/**\n * The AgentsAPI class provides methods to register and interact with AI Agents on Nevermined.\n */\nexport class AgentsAPI extends BasePaymentsAPI {\n /**\n * This method is used to create a singleton instance of the AgentsAPI class.\n *\n * @param options - The options to initialize the payments class.\n * @returns The instance of the AgentsAPI class.\n */\n static getInstance(options: PaymentOptions): AgentsAPI {\n return new AgentsAPI(options)\n }\n\n /**\n *\n * It registers a new AI Agent on Nevermined.\n * The agent must be associated to one or multiple Payment Plans. Users that are subscribers of a payment plan can query the agent.\n * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.\n * 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.\n *\n * @remarks This method is oriented to AI Builders\n * @remarks To call this method, the NVM API Key must have publication permissions\n *\n * @see https://docs.nevermined.app/docs/tutorials/builders/register-agent\n *\n * @param agentMetadata - @see {@link AgentMetadata}\n * @param agentApi - @see {@link AgentAPIAttributes}\n * @param paymentPlans - the list of payment plans giving access to the agent.\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }\n * const agentApi = { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }\n * const paymentPlans = [planId]\n *\n * const { agentId } = await payments.agents.registerAgent(agentMetadata, agentApi, paymentPlans)\n * ```\n *\n * @returns The unique identifier of the newly created agent (Agent Id).\n */\n public async registerAgent(\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n paymentPlans: string[],\n ): Promise<{ agentId: string }> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n plans: paymentPlans,\n }\n\n const options = this.getBackendHTTPOptions('POST', body)\n const url = new URL(API_URL_REGISTER_AGENT, this.environment.backend)\n\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to register agent', await response.json())\n }\n const agentData = await response.json()\n return { agentId: agentData.data.agentId }\n }\n\n /**\n *\n * It registers a new AI Agent and a Payment Plan associated to this new agent.\n * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.\n * 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.\n *\n * @remarks This method is oriented to AI Builders\n * @remarks To call this method, the NVM API Key must have publication permissions\n *\n * @see https://docs.nevermined.app/docs/tutorials/builders/register-agent\n *\n * @param agentMetadata - @see {@link AgentMetadata}\n * @param agentApi - @see {@link AgentAPIAttributes}\n * @param planMetadata - @see {@link PlanMetadata}\n * @param priceConfig - @see {@link PlanPriceConfig}\n * @param creditsConfig - @see {@link PlanCreditsConfig}\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }\n * const agentApi { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }\n * const cryptoPriceConfig = getNativeTokenPriceConfig(100n, builderAddress)\n * const 1dayDurationPlan = getExpirableDurationConfig(ONE_DAY_DURATION)\n * const { agentId, planId } = await payments.agents.registerAgentAndPlan(\n * agentMetadata,\n * agentApi,\n * cryptoPriceConfig,\n * 1dayDurationPlan\n * )\n * ```\n *\n * @returns The unique identifier of the newly created agent (agentId).\n * @returns The unique identifier of the newly created plan (planId).\n */\n public async registerAgentAndPlan(\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n planMetadata: PlanMetadata,\n priceConfig: PlanPriceConfig,\n creditsConfig: PlanCreditsConfig,\n accessLimit?: 'credits' | 'time',\n ): Promise<{\n agentId: string\n planId: string\n txHash: string\n }> {\n if (accessLimit && !['credits', 'time'].includes(accessLimit)) {\n throw new PaymentsError(\n 'Invalid access limit',\n 'accessLimit must be either \"credits\" or \"time\"',\n )\n }\n if (!accessLimit) {\n accessLimit = creditsConfig.durationSecs > 0n ? 'time' : 'credits'\n }\n const body = {\n plan: {\n metadataAttributes: planMetadata,\n priceConfig: priceConfig,\n creditsConfig: creditsConfig,\n accessLimit,\n },\n agent: {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n },\n }\n const options = this.getBackendHTTPOptions('POST', body)\n const url = new URL(API_URL_REGISTER_AGENTS_AND_PLAN, this.environment.backend)\n\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to register agent & plan', await response.json())\n }\n const result = await response.json()\n return {\n agentId: result.data.agentId,\n planId: result.data.planId,\n txHash: result.txHash,\n }\n }\n\n /**\n * Gets the metadata for a given Agent identifier.\n *\n * @param agentId - The unique identifier of the agent.\n * @returns A promise that resolves to the agent's metadata.\n * @throws PaymentsError if the agent is not found.\n *\n * @example\n * ```\n * const plan = payments.agents.getAgent(agentId)\n * ```\n */\n public async getAgent(agentId: string) {\n const url = new URL(API_URL_GET_AGENT.replace(':agentId', agentId), this.environment.backend)\n const response = await fetch(url)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await response.json())\n }\n return response.json()\n }\n\n /**\n * Updates the metadata and API attributes of an existing AI Agent.\n *\n * @param agentId - The unique identifier of the agent.\n * @param agentMetadata - The new metadata attributes for the agent.\n * @param agentApi - The new API attributes for the agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if the agent is not found or if the update fails.\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My Updated Agent', tags: ['test'] }\n * const agentApi = { endpoints: [{ 'POST': 'https://nevermined.app/api/v1/agents/:agentId/tasks' }] }\n *\n * await payments.agents.updateAgentMetadata(agentId, agentMetadata, agentApi)\n * ```\n */\n public async updateAgentMetadata(\n agentId: string,\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n ): Promise<NvmAPIResult> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n }\n const url = new URL(API_URL_UPDATE_AGENT.replace(':agentId', agentId), this.environment.backend)\n const options = this.getBackendHTTPOptions('PUT', body)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Error updating agent', await response.json())\n }\n return response.json()\n }\n\n /**\n * Gets the list of plans that can be ordered to get access to an agent.\n *\n * @param agentId - The unique identifier of the agent.\n * @param pagination - Optional pagination options to control the number of results returned.p\n * @returns A promise that resolves to the list of all different plans giving access to the agent.\n * @throws PaymentsError if the agent is not found.\n *\n * @example\n * ```\n * const result = payments.agents.getAgentPlans(planId)\n * // {\n * // total: 10,\n * // page: 1,\n * // offset: 5,\n * // plans: [ ..]\n * // }\n * ```\n */\n public async getAgentPlans(agentId: string, pagination = new PaginationOptions()) {\n const query =\n API_URL_GET_AGENT_PLANS.replace(':agentId', agentId) + '?' + pagination.asQueryParams()\n const url = new URL(query, this.environment.backend)\n const response = await fetch(url)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await response.json())\n }\n return response.json()\n }\n\n /**\n * Adds an existing Payment Plan to an AI Agent.\n * After this operation, users with access to the Payment Plan will be able to access the AI Agent.\n *\n * @remarks\n * Only the owner of the Payment Plan can call this method.\n *\n * @param planId - The unique identifier of the Payment Plan.\n * @param agentId - The unique identifier of the AI Agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if unable to add the plan to the agent.\n *\n * @example\n * ```\n * const result = await payments.agents.addPlanToAgent(planId, agentId)\n * // {\n * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',\n * // success: true\n * // }\n * ```\n */\n public async addPlanToAgent(planId: string, agentId: string): Promise<NvmAPIResult> {\n const options = this.getBackendHTTPOptions('POST')\n const endpoint = API_URL_ADD_PLAN_AGENT.replace(':planId', planId).replace(':agentId', agentId)\n const url = new URL(endpoint, this.environment.backend)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to add plan to agent', await response.json())\n }\n\n return response.json()\n }\n\n /**\n * Removes a Payment Plan from an AI Agent.\n * After this operation, users with access to the Payment Plan will no longer be able to access the AI Agent.\n *\n * @remarks\n * Only the owner of the Payment Plan can call this method.\n *\n * @param planId - The unique identifier of the Payment Plan.\n * @param agentId - The unique identifier of the AI Agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if unable to remove the plan from the agent.\n *\n * @example\n * ```\n * const result = await payments.agents.removePlanFromAgent(planId, agentId)\n * // {\n * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',\n * // success: true\n * // }\n * ```\n */\n public async removePlanFromAgent(planId: string, agentId: string): Promise<NvmAPIResult> {\n const options = this.getBackendHTTPOptions('DELETE')\n const endpoint = API_URL_REMOVE_PLAN_AGENT.replace(':planId', planId).replace(\n ':agentId',\n agentId,\n )\n const url = new URL(endpoint, this.environment.backend)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to remove plan from agent', await response.json())\n }\n\n return response.json()\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agents-api.js","sourceRoot":"","sources":["../../src/api/agents-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAIL,iBAAiB,GAKlB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACpD,OAA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QAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAA;QACpD,MAAM,QAAQ,GAAG,yBAAyB,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,OAAO,CAC3E,UAAU,EACV,OAAO,CACR,CAAA;QACD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;QACvD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;QAC1C,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,aAAa,CAAC,WAAW,CAAC,kCAAkC,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;QAC5F,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAA;IACxB,CAAC;CACF","sourcesContent":["import { PaymentsError } from '../common/payments.error.js'\nimport {\n AgentAPIAttributes,\n AgentMetadata,\n NvmAPIResult,\n PaginationOptions,\n PaymentOptions,\n PlanCreditsConfig,\n PlanMetadata,\n PlanPriceConfig,\n} from '../common/types.js'\nimport { BasePaymentsAPI } from './base-payments.js'\nimport {\n API_URL_ADD_PLAN_AGENT,\n API_URL_GET_AGENT,\n API_URL_GET_AGENT_PLANS,\n API_URL_REGISTER_AGENT,\n API_URL_REGISTER_AGENTS_AND_PLAN,\n API_URL_REMOVE_PLAN_AGENT,\n API_URL_UPDATE_AGENT,\n} from './nvm-api.js'\n\n/**\n * The AgentsAPI class provides methods to register and interact with AI Agents on Nevermined.\n */\nexport class AgentsAPI extends BasePaymentsAPI {\n /**\n * This method is used to create a singleton instance of the AgentsAPI class.\n *\n * @param options - The options to initialize the payments class.\n * @returns The instance of the AgentsAPI class.\n */\n static getInstance(options: PaymentOptions): AgentsAPI {\n return new AgentsAPI(options)\n }\n\n /**\n *\n * It registers a new AI Agent on Nevermined.\n * The agent must be associated to one or multiple Payment Plans. Users that are subscribers of a payment plan can query the agent.\n * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.\n * 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.\n *\n * @remarks This method is oriented to AI Builders\n * @remarks To call this method, the NVM API Key must have publication permissions\n *\n * @see https://nevermined.ai/docs/tutorials/builders/register-agent\n *\n * @param agentMetadata - @see {@link AgentMetadata}\n * @param agentApi - @see {@link AgentAPIAttributes}\n * @param paymentPlans - the list of payment plans giving access to the agent.\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }\n * const agentApi = { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }\n * const paymentPlans = [planId]\n *\n * const { agentId } = await payments.agents.registerAgent(agentMetadata, agentApi, paymentPlans)\n * ```\n *\n * @returns The unique identifier of the newly created agent (Agent Id).\n */\n public async registerAgent(\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n paymentPlans: string[],\n ): Promise<{ agentId: string }> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n plans: paymentPlans,\n }\n\n const options = this.getBackendHTTPOptions('POST', body)\n const url = new URL(API_URL_REGISTER_AGENT, this.environment.backend)\n\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to register agent', await response.json())\n }\n const agentData = await response.json()\n return { agentId: agentData.data.agentId }\n }\n\n /**\n *\n * It registers a new AI Agent and a Payment Plan associated to this new agent.\n * Depending on the Payment Plan and the configuration of the agent, the usage of the agent/service will consume credits.\n * 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.\n *\n * @remarks This method is oriented to AI Builders\n * @remarks To call this method, the NVM API Key must have publication permissions\n *\n * @see https://nevermined.ai/docs/tutorials/builders/register-agent\n *\n * @param agentMetadata - @see {@link AgentMetadata}\n * @param agentApi - @see {@link AgentAPIAttributes}\n * @param planMetadata - @see {@link PlanMetadata}\n * @param priceConfig - @see {@link PlanPriceConfig}\n * @param creditsConfig - @see {@link PlanCreditsConfig}\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My AI Payments Agent', tags: ['test'] }\n * const agentApi { endpoints: [{ 'POST': 'https://example.com/api/v1/agents/:agentId/tasks' }] }\n * const cryptoPriceConfig = getNativeTokenPriceConfig(100n, builderAddress)\n * const 1dayDurationPlan = getExpirableDurationConfig(ONE_DAY_DURATION)\n * const { agentId, planId } = await payments.agents.registerAgentAndPlan(\n * agentMetadata,\n * agentApi,\n * cryptoPriceConfig,\n * 1dayDurationPlan\n * )\n * ```\n *\n * @returns The unique identifier of the newly created agent (agentId).\n * @returns The unique identifier of the newly created plan (planId).\n */\n public async registerAgentAndPlan(\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n planMetadata: PlanMetadata,\n priceConfig: PlanPriceConfig,\n creditsConfig: PlanCreditsConfig,\n accessLimit?: 'credits' | 'time',\n ): Promise<{\n agentId: string\n planId: string\n txHash: string\n }> {\n if (accessLimit && !['credits', 'time'].includes(accessLimit)) {\n throw new PaymentsError(\n 'Invalid access limit',\n 'accessLimit must be either \"credits\" or \"time\"',\n )\n }\n if (!accessLimit) {\n accessLimit = creditsConfig.durationSecs > 0n ? 'time' : 'credits'\n }\n const body = {\n plan: {\n metadataAttributes: planMetadata,\n priceConfig: priceConfig,\n creditsConfig: creditsConfig,\n accessLimit,\n },\n agent: {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n },\n }\n const options = this.getBackendHTTPOptions('POST', body)\n const url = new URL(API_URL_REGISTER_AGENTS_AND_PLAN, this.environment.backend)\n\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to register agent & plan', await response.json())\n }\n const result = await response.json()\n return {\n agentId: result.data.agentId,\n planId: result.data.planId,\n txHash: result.txHash,\n }\n }\n\n /**\n * Gets the metadata for a given Agent identifier.\n *\n * @param agentId - The unique identifier of the agent.\n * @returns A promise that resolves to the agent's metadata.\n * @throws PaymentsError if the agent is not found.\n *\n * @example\n * ```\n * const plan = payments.agents.getAgent(agentId)\n * ```\n */\n public async getAgent(agentId: string) {\n const url = new URL(API_URL_GET_AGENT.replace(':agentId', agentId), this.environment.backend)\n const response = await fetch(url)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await response.json())\n }\n return response.json()\n }\n\n /**\n * Updates the metadata and API attributes of an existing AI Agent.\n *\n * @param agentId - The unique identifier of the agent.\n * @param agentMetadata - The new metadata attributes for the agent.\n * @param agentApi - The new API attributes for the agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if the agent is not found or if the update fails.\n *\n * @example\n * ```\n * const agentMetadata = { name: 'My Updated Agent', tags: ['test'] }\n * const agentApi = { endpoints: [{ 'POST': 'https://nevermined.app/api/v1/agents/:agentId/tasks' }] }\n *\n * await payments.agents.updateAgentMetadata(agentId, agentMetadata, agentApi)\n * ```\n */\n public async updateAgentMetadata(\n agentId: string,\n agentMetadata: AgentMetadata,\n agentApi: AgentAPIAttributes,\n ): Promise<NvmAPIResult> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n }\n const url = new URL(API_URL_UPDATE_AGENT.replace(':agentId', agentId), this.environment.backend)\n const options = this.getBackendHTTPOptions('PUT', body)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Error updating agent', await response.json())\n }\n return response.json()\n }\n\n /**\n * Gets the list of plans that can be ordered to get access to an agent.\n *\n * @param agentId - The unique identifier of the agent.\n * @param pagination - Optional pagination options to control the number of results returned.p\n * @returns A promise that resolves to the list of all different plans giving access to the agent.\n * @throws PaymentsError if the agent is not found.\n *\n * @example\n * ```\n * const result = payments.agents.getAgentPlans(planId)\n * // {\n * // total: 10,\n * // page: 1,\n * // offset: 5,\n * // plans: [ ..]\n * // }\n * ```\n */\n public async getAgentPlans(agentId: string, pagination = new PaginationOptions()) {\n const query =\n API_URL_GET_AGENT_PLANS.replace(':agentId', agentId) + '?' + pagination.asQueryParams()\n const url = new URL(query, this.environment.backend)\n const response = await fetch(url)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await response.json())\n }\n return response.json()\n }\n\n /**\n * Adds an existing Payment Plan to an AI Agent.\n * After this operation, users with access to the Payment Plan will be able to access the AI Agent.\n *\n * @remarks\n * Only the owner of the Payment Plan can call this method.\n *\n * @param planId - The unique identifier of the Payment Plan.\n * @param agentId - The unique identifier of the AI Agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if unable to add the plan to the agent.\n *\n * @example\n * ```\n * const result = await payments.agents.addPlanToAgent(planId, agentId)\n * // {\n * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',\n * // success: true\n * // }\n * ```\n */\n public async addPlanToAgent(planId: string, agentId: string): Promise<NvmAPIResult> {\n const options = this.getBackendHTTPOptions('POST')\n const endpoint = API_URL_ADD_PLAN_AGENT.replace(':planId', planId).replace(':agentId', agentId)\n const url = new URL(endpoint, this.environment.backend)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to add plan to agent', await response.json())\n }\n\n return response.json()\n }\n\n /**\n * Removes a Payment Plan from an AI Agent.\n * After this operation, users with access to the Payment Plan will no longer be able to access the AI Agent.\n *\n * @remarks\n * Only the owner of the Payment Plan can call this method.\n *\n * @param planId - The unique identifier of the Payment Plan.\n * @param agentId - The unique identifier of the AI Agent.\n * @returns @see {@link NvmAPIResult} A promise that resolves indicating if the operation was successful.\n * @throws PaymentsError if unable to remove the plan from the agent.\n *\n * @example\n * ```\n * const result = await payments.agents.removePlanFromAgent(planId, agentId)\n * // {\n * // txHash: '0x8d29d5769e832a35e53f80cd4e8890d941c50a09c33dbd975533debc894f2535',\n * // success: true\n * // }\n * ```\n */\n public async removePlanFromAgent(planId: string, agentId: string): Promise<NvmAPIResult> {\n const options = this.getBackendHTTPOptions('DELETE')\n const endpoint = API_URL_REMOVE_PLAN_AGENT.replace(':planId', planId).replace(\n ':agentId',\n agentId,\n )\n const url = new URL(endpoint, this.environment.backend)\n const response = await fetch(url, options)\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to remove plan from agent', await response.json())\n }\n\n return response.json()\n }\n}\n"]}
|
|
@@ -49,9 +49,9 @@ export declare abstract class BasePaymentsAPI {
|
|
|
49
49
|
method: string;
|
|
50
50
|
headers: {
|
|
51
51
|
Accept: string;
|
|
52
|
-
|
|
52
|
+
"Content-Type": string;
|
|
53
53
|
};
|
|
54
|
-
body?: string
|
|
54
|
+
body?: string;
|
|
55
55
|
};
|
|
56
56
|
}
|
|
57
57
|
//# sourceMappingURL=base-payments.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-payments.d.ts","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAgB,MAAM,oBAAoB,CAAA;AAEnF;;;GAGG;AACH,8BAAsB,eAAe;IACnC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,WAAW,EAAE,eAAe,CAAA;IACtC,SAAS,CAAC,eAAe,EAAE,eAAe,CAAA;IAC1C,SAAS,CAAC,SAAS,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACxB,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAC1B,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IAChC,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IACzB,iBAAiB,UAAO;gBAEnB,OAAO,EAAE,cAAc;IAYnC;;;OAGG;IACH,SAAS,CAAC,cAAc,IAAI;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,cAAc,E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AAI,CAAC,EAAE,GAAG;IAY1D;;;;;;;;OAQG;IACH,SAAS,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG;gBAE7C,MAAM;iBACL;YACP,MAAM,EAAE,MAAM,CAAA;YACd,cAAc,EAAE,MAAM,CAAA;SACvB;eACM,MAAM;;CAelB"}
|
package/dist/api/nvm-api.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export interface BackendApiOptions {
|
|
|
34
34
|
/**
|
|
35
35
|
* The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.
|
|
36
36
|
* You can get your API key by logging in to the Nevermined App.
|
|
37
|
-
* @see https://
|
|
37
|
+
* @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys
|
|
38
38
|
*/
|
|
39
39
|
apiKey?: string;
|
|
40
40
|
/**
|
package/dist/api/nvm-api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nvm-api.js","sourceRoot":"","sources":["../../src/api/nvm-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,MAAM,CAAC,MAAM,qBAAqB,GAAG,wBAAwB,CAAA;AAC7D,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAA;AAC/D,MAAM,CAAC,MAAM,gCAAgC,GAAG,+BAA+B,CAAA;AAC/E,MAAM,CAAC,MAAM,iBAAiB,GAAG,kCAAkC,CAAA;AACnE,MAAM,CAAC,MAAM,oBAAoB,GAAG,kCAAkC,CAAA;AACtE,MAAM,CAAC,MAAM,uBAAuB,GAAG,wCAAwC,CAAA;AAC/E,MAAM,CAAC,MAAM,gBAAgB,GAAG,gCAAgC,CAAA;AAChE,MAAM,CAAC,MAAM,iBAAiB,GAAG,wBAAwB,CAAA;AACzD,MAAM,CAAC,MAAM,uBAAuB,GAAG,uCAAuC,CAAA;AAC9E,MAAM,CAAC,MAAM,kBAAkB,GAAG,sCAAsC,CAAA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,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACtD,CAAC;CACF","sourcesContent":["import axios from 'axios'\n\nexport const API_URL_REGISTER_PLAN = '/api/v1/protocol/plans'\nexport const API_URL_REGISTER_AGENT = '/api/v1/protocol/agents'\nexport const API_URL_REGISTER_AGENTS_AND_PLAN = '/api/v1/protocol/agents/plans'\nexport const API_URL_GET_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_UPDATE_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_GET_AGENT_PLANS = '/api/v1/protocol/agents/:agentId/plans'\nexport const API_URL_GET_PLAN = '/api/v1/protocol/plans/:planId'\nexport const API_URL_GET_PLANS = '/api/v1/protocol/plans'\nexport const API_URL_GET_PLAN_AGENTS = '/api/v1/protocol/plans/:planId/agents'\nexport const API_URL_ORDER_PLAN = '/api/v1/protocol/plans/:planId/order'\nexport const API_URL_MINT_PLAN = '/api/v1/protocol/plans/mint'\nexport const API_URL_MINT_EXPIRABLE_PLAN = '/api/v1/protocol/plans/mintExpirable'\nexport const API_URL_ADD_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REMOVE_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REDEEM_PLAN = '/api/v1/protocol/plans/redeem'\nexport const API_URL_PLAN_BALANCE = '/api/v1/protocol/plans/:planId/balance/:holderAddress'\nexport const API_URL_INITIALIZE_AGENT = '/api/v1/protocol/agents/initialize/:agentId'\nexport const API_URL_SIMULATE_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/start'\nexport const API_URL_SIMULATE_REDEEM_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/finish'\nexport const API_URL_TRACK_AGENT_SUB_TASK = '/api/v1/protocol/agent-sub-tasks'\nexport const API_URL_VALIDATE_AGENT_ACCESS_TOKEN = '/api/v1/protocol/token/validate/:agentId'\nexport const API_URL_CREATE_PERMISSION = '/api/v1/x402/permissions'\nexport const API_URL_VERIFY_PERMISSIONS = '/api/v1/x402/verify'\nexport const API_URL_SETTLE_PERMISSIONS = '/api/v1/x402/settle'\nexport const API_URL_STRIPE_CHECKOUT = '/api/v1/stripe/checkout'\nexport const API_URL_CREATE_USER = '/api/v1/organizations/account'\nexport const API_URL_GET_MEMBERS = '/api/v1/organizations/members'\nexport const API_URL_CONNECT_STRIPE_ACCOUNT = '/api/v1/stripe/account'\n\nexport interface BackendApiOptions {\n /**\n * The host of the backend server\n */\n backendHost: string\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://
|
|
1
|
+
{"version":3,"file":"nvm-api.js","sourceRoot":"","sources":["../../src/api/nvm-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,MAAM,CAAC,MAAM,qBAAqB,GAAG,wBAAwB,CAAA;AAC7D,MAAM,CAAC,MAAM,sBAAsB,GAAG,yBAAyB,CAAA;AAC/D,MAAM,CAAC,MAAM,gCAAgC,GAAG,+BAA+B,CAAA;AAC/E,MAAM,CAAC,MAAM,iBAAiB,GAAG,kCAAkC,CAAA;AACnE,MAAM,CAAC,MAAM,oBAAoB,GAAG,kCAAkC,CAAA;AACtE,MAAM,CAAC,MAAM,uBAAuB,GAAG,wCAAwC,CAAA;AAC/E,MAAM,CAAC,MAAM,gBAAgB,GAAG,gCAAgC,CAAA;AAChE,MAAM,CAAC,MAAM,iBAAiB,GAAG,wBAAwB,CAAA;AACzD,MAAM,CAAC,MAAM,uBAAuB,GAAG,uCAAuC,CAAA;AAC9E,MAAM,CAAC,MAAM,kBAAkB,GAAG,sCAAsC,CAAA;AACxE,MAAM,CAAC,MAAM,iBAAiB,GAAG,6BAA6B,CAAA;AAC9D,MAAM,CAAC,MAAM,2BAA2B,GAAG,sCAAsC,CAAA;AACjF,MAAM,CAAC,MAAM,sBAAsB,GAAG,+CAA+C,CAAA;AACrF,MAAM,CAAC,MA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CAAC,EAAE,kDAAkD;aAC1E,CAAC,CAAA;YAEF,OAAO,QAAQ,CAAA;QACjB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;gBAC5C,MAAM,IAAI,KAAK,CACb,QAAQ,GAAG,CAAC,QAAQ,CAAC,MAAM,KAAK,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,IAAI,gBAAgB,EAAE,CACjF,CAAA;YACH,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAA;QACxE,CAAC;IACH,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,aAAiC,EAAE,gBAAgB,EAAE,IAAI,EAAE;QAChF,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,UAAU,CAAC,CAAA;IACxD,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QAC/D,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACpD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QAC9D,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACnD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,IAAS,EAAE,UAA8B;QACjE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC,CAAA;IACtD,CAAC;CACF","sourcesContent":["import axios from 'axios'\n\nexport const API_URL_REGISTER_PLAN = '/api/v1/protocol/plans'\nexport const API_URL_REGISTER_AGENT = '/api/v1/protocol/agents'\nexport const API_URL_REGISTER_AGENTS_AND_PLAN = '/api/v1/protocol/agents/plans'\nexport const API_URL_GET_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_UPDATE_AGENT = '/api/v1/protocol/agents/:agentId'\nexport const API_URL_GET_AGENT_PLANS = '/api/v1/protocol/agents/:agentId/plans'\nexport const API_URL_GET_PLAN = '/api/v1/protocol/plans/:planId'\nexport const API_URL_GET_PLANS = '/api/v1/protocol/plans'\nexport const API_URL_GET_PLAN_AGENTS = '/api/v1/protocol/plans/:planId/agents'\nexport const API_URL_ORDER_PLAN = '/api/v1/protocol/plans/:planId/order'\nexport const API_URL_MINT_PLAN = '/api/v1/protocol/plans/mint'\nexport const API_URL_MINT_EXPIRABLE_PLAN = '/api/v1/protocol/plans/mintExpirable'\nexport const API_URL_ADD_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REMOVE_PLAN_AGENT = '/api/v1/protocol/agents/:agentId/plan/:planId'\nexport const API_URL_REDEEM_PLAN = '/api/v1/protocol/plans/redeem'\nexport const API_URL_PLAN_BALANCE = '/api/v1/protocol/plans/:planId/balance/:holderAddress'\nexport const API_URL_INITIALIZE_AGENT = '/api/v1/protocol/agents/initialize/:agentId'\nexport const API_URL_SIMULATE_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/start'\nexport const API_URL_SIMULATE_REDEEM_AGENT_REQUEST = '/api/v1/protocol/agents/simulate/finish'\nexport const API_URL_TRACK_AGENT_SUB_TASK = '/api/v1/protocol/agent-sub-tasks'\nexport const API_URL_VALIDATE_AGENT_ACCESS_TOKEN = '/api/v1/protocol/token/validate/:agentId'\nexport const API_URL_CREATE_PERMISSION = '/api/v1/x402/permissions'\nexport const API_URL_VERIFY_PERMISSIONS = '/api/v1/x402/verify'\nexport const API_URL_SETTLE_PERMISSIONS = '/api/v1/x402/settle'\nexport const API_URL_STRIPE_CHECKOUT = '/api/v1/stripe/checkout'\nexport const API_URL_CREATE_USER = '/api/v1/organizations/account'\nexport const API_URL_GET_MEMBERS = '/api/v1/organizations/members'\nexport const API_URL_CONNECT_STRIPE_ACCOUNT = '/api/v1/stripe/account'\n\nexport interface BackendApiOptions {\n /**\n * The host of the backend server\n */\n backendHost: string\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys\n */\n apiKey?: string\n\n /**\n * The host of the Nevermined Proxy\n */\n proxyHost?: string\n\n /**\n * Additional headers to send with the requests\n */\n headers?: { [key: string]: string }\n}\n\nexport class HTTPRequestOptions {\n accessToken?: string\n sendThroughProxy = true\n proxyHost?: string = undefined\n headers?: { [key: string]: string } = {}\n}\n\nexport abstract class AbstractHTTPClient {\n // protected opts: BackendApiOptions\n // private hasKey = false\n // private agentId = ''\n\n // constructor(opts: BackendApiOptions) {\n // const defaultHeaders = {\n // Accept: 'application/json',\n // ...opts.headers,\n // ...(opts.apiKey && { Authorization: `Bearer ${opts.apiKey}` }),\n // }\n\n // this.opts = {\n // ...opts,\n // headers: defaultHeaders,\n // }\n\n // try {\n // if (this.opts.apiKey && this.opts.apiKey.length > 0) {\n // const jwt = decodeJwt(this.opts.apiKey)\n // if (isEthereumAddress(jwt.sub)) {\n // this.hasKey = true\n // }\n // }\n // } catch {\n // this.hasKey = false\n // }\n\n // let backendUrl\n // try {\n // backendUrl = new URL(this.opts.backendHost)\n // this.opts.backendHost = backendUrl.origin\n // } catch (error) {\n // throw new Error(`Invalid URL: ${this.opts.backendHost} - ${(error as Error).message}`)\n // }\n // }\n\n constructor() {\n // Empty constructor - required for abstract class implementation\n }\n\n parseUrl(urlRequested: string, reqOptions: HTTPRequestOptions) {\n let _host: URL\n if (reqOptions.sendThroughProxy) {\n if (!reqOptions.proxyHost)\n throw new Error('Proxy host is required when sendThroughProxy is true')\n return `${new URL(reqOptions.proxyHost).origin}${new URL(urlRequested).href}`\n } else {\n return urlRequested\n }\n }\n\n parseHeaders(requestHeaders: { [key: string]: string }, accessToken?: string) {\n return {\n ...(accessToken && { Authorization: `Bearer ${accessToken}` }),\n ...requestHeaders,\n }\n }\n\n // setBearerToken(token: string) {\n // this.opts.headers = {\n // ...this.opts.headers,\n // Authorization: `Bearer ${token}`,\n // }\n // }\n\n async request(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: string,\n data?: any,\n reqOptions: HTTPRequestOptions = {\n sendThroughProxy: false,\n },\n ) {\n try {\n const response = await axios({\n method,\n url: this.parseUrl(url, reqOptions),\n headers: this.parseHeaders(reqOptions.headers || {}, reqOptions.accessToken),\n ...(data && { data }), // Only include `data` for methods that support it\n })\n\n return response\n } catch (err) {\n if (axios.isAxiosError(err) && err.response) {\n throw new Error(\n `HTTP ${err.response.status}: ${err.response.data?.message || 'Request failed'}`,\n )\n }\n throw new Error('Network error or request failed without a response.')\n }\n }\n\n async get(url: string, reqOptions: HTTPRequestOptions = { sendThroughProxy: true }) {\n return this.request('GET', url, undefined, reqOptions)\n }\n\n async post(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('POST', url, data, reqOptions)\n }\n\n async put(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('PUT', url, data, reqOptions)\n }\n\n async delete(url: string, data: any, reqOptions: HTTPRequestOptions) {\n return this.request('DELETE', url, data, reqOptions)\n }\n}\n"]}
|
package/dist/api/plans-api.d.ts
CHANGED
|
@@ -123,7 +123,7 @@ export declare class PlansAPI extends BasePaymentsAPI {
|
|
|
123
123
|
* This method is oriented to AI Builders.
|
|
124
124
|
* The NVM API Key must have publication permissions.
|
|
125
125
|
*
|
|
126
|
-
* @see https://
|
|
126
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
127
127
|
*
|
|
128
128
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
129
129
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -152,7 +152,7 @@ export declare class PlansAPI extends BasePaymentsAPI {
|
|
|
152
152
|
* @remarks This method is oriented to AI Builders
|
|
153
153
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
154
154
|
*
|
|
155
|
-
* @see https://
|
|
155
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
156
156
|
*
|
|
157
157
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
158
158
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -185,7 +185,7 @@ export declare class PlansAPI extends BasePaymentsAPI {
|
|
|
185
185
|
* @remarks This method is oriented to AI Builders
|
|
186
186
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
187
187
|
*
|
|
188
|
-
* @see https://
|
|
188
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
189
189
|
*
|
|
190
190
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
191
191
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -216,7 +216,7 @@ export declare class PlansAPI extends BasePaymentsAPI {
|
|
|
216
216
|
* @remarks This method is oriented to AI Builders
|
|
217
217
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
218
218
|
*
|
|
219
|
-
* @see https://
|
|
219
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
220
220
|
*
|
|
221
221
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
222
222
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -247,7 +247,7 @@ export declare class PlansAPI extends BasePaymentsAPI {
|
|
|
247
247
|
* @remarks This method is oriented to AI Builders
|
|
248
248
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
249
249
|
*
|
|
250
|
-
* @see https://
|
|
250
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
251
251
|
*
|
|
252
252
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
253
253
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
package/dist/api/plans-api.js
CHANGED
|
@@ -160,7 +160,7 @@ export class PlansAPI extends BasePaymentsAPI {
|
|
|
160
160
|
* This method is oriented to AI Builders.
|
|
161
161
|
* The NVM API Key must have publication permissions.
|
|
162
162
|
*
|
|
163
|
-
* @see https://
|
|
163
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
164
164
|
*
|
|
165
165
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
166
166
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -209,7 +209,7 @@ export class PlansAPI extends BasePaymentsAPI {
|
|
|
209
209
|
* @remarks This method is oriented to AI Builders
|
|
210
210
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
211
211
|
*
|
|
212
|
-
* @see https://
|
|
212
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
213
213
|
*
|
|
214
214
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
215
215
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -247,7 +247,7 @@ export class PlansAPI extends BasePaymentsAPI {
|
|
|
247
247
|
* @remarks This method is oriented to AI Builders
|
|
248
248
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
249
249
|
*
|
|
250
|
-
* @see https://
|
|
250
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
251
251
|
*
|
|
252
252
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
253
253
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -283,7 +283,7 @@ export class PlansAPI extends BasePaymentsAPI {
|
|
|
283
283
|
* @remarks This method is oriented to AI Builders
|
|
284
284
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
285
285
|
*
|
|
286
|
-
* @see https://
|
|
286
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
287
287
|
*
|
|
288
288
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
289
289
|
* @param priceConfig - @see {@link PlanPriceConfig}
|
|
@@ -315,7 +315,7 @@ export class PlansAPI extends BasePaymentsAPI {
|
|
|
315
315
|
* @remarks This method is oriented to AI Builders
|
|
316
316
|
* @remarks To call this method, the NVM API Key must have publication permissions
|
|
317
317
|
*
|
|
318
|
-
* @see https://
|
|
318
|
+
* @see https://nevermined.ai/docs/tutorials/builders/create-plan
|
|
319
319
|
*
|
|
320
320
|
* @param planMetadata - @see {@link PlanMetadata}
|
|
321
321
|
* @param priceConfig - @see {@link PlanPriceConfig}
|