@nevermined-io/payments 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2a/paymentsRequestHandler.d.ts +5 -1
- package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
- package/dist/a2a/paymentsRequestHandler.js +156 -13
- package/dist/a2a/paymentsRequestHandler.js.map +1 -1
- package/dist/a2a/types.d.ts +25 -0
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/api/agents-api.d.ts +4 -3
- package/dist/api/agents-api.d.ts.map +1 -1
- package/dist/api/agents-api.js +7 -4
- package/dist/api/agents-api.js.map +1 -1
- package/dist/api/base-payments.d.ts +7 -2
- package/dist/api/base-payments.d.ts.map +1 -1
- package/dist/api/base-payments.js +15 -8
- package/dist/api/base-payments.js.map +1 -1
- package/dist/api/nvm-api.d.ts +5 -5
- package/dist/api/observability-api/types.d.ts +34 -6
- package/dist/api/observability-api/types.d.ts.map +1 -1
- package/dist/api/observability-api/types.js.map +1 -1
- package/dist/api/plans-api.d.ts +15 -12
- package/dist/api/plans-api.d.ts.map +1 -1
- package/dist/api/plans-api.js +17 -14
- package/dist/api/plans-api.js.map +1 -1
- package/dist/api/query-api.d.ts +1 -1
- package/dist/common/types.d.ts +88 -18
- package/dist/common/types.d.ts.map +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/mcp/core/paywall.d.ts.map +1 -1
- package/dist/mcp/core/paywall.js +59 -8
- package/dist/mcp/core/paywall.js.map +1 -1
- package/dist/mcp/http/index.d.ts +1 -1
- package/dist/mcp/http/index.d.ts.map +1 -1
- package/dist/mcp/http/index.js +1 -1
- package/dist/mcp/http/index.js.map +1 -1
- package/dist/mcp/http/oauth-metadata.d.ts +32 -0
- package/dist/mcp/http/oauth-metadata.d.ts.map +1 -1
- package/dist/mcp/http/oauth-metadata.js +329 -34
- package/dist/mcp/http/oauth-metadata.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/types/http.types.d.ts +38 -3
- package/dist/mcp/types/http.types.d.ts.map +1 -1
- package/dist/mcp/types/http.types.js.map +1 -1
- package/dist/mcp/types/paywall.types.d.ts +19 -3
- 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.map +1 -1
- package/dist/x402/delegation-api.d.ts +5 -17
- package/dist/x402/delegation-api.d.ts.map +1 -1
- package/dist/x402/delegation-api.js +2 -2
- package/dist/x402/delegation-api.js.map +1 -1
- package/package.json +22 -13
package/dist/a2a/types.d.ts
CHANGED
|
@@ -113,6 +113,31 @@ export interface PaymentMetadata {
|
|
|
113
113
|
agentId?: string;
|
|
114
114
|
/** Configuration for credit redemption behavior */
|
|
115
115
|
redemptionConfig?: PaymentRedemptionConfig;
|
|
116
|
+
/**
|
|
117
|
+
* The settle's transaction reference, written by the SDK after settlement.
|
|
118
|
+
* A chain tx hash on the crypto rails; the PSP transaction id on fiat (a
|
|
119
|
+
* Stripe PaymentIntent `pi_...`), so do not assume it is a hash.
|
|
120
|
+
*
|
|
121
|
+
* ABSENT unless the settle both succeeded AND reported a `transaction`. The
|
|
122
|
+
* wire's `transaction` is an empty string on a failed settle, and publishing
|
|
123
|
+
* that put a blank id on a completed task — so the key is omitted instead,
|
|
124
|
+
* and its PRESENCE means a settlement really happened. Absence does not by
|
|
125
|
+
* itself mean failure: a successful fiat charge is referenced by the receipt's
|
|
126
|
+
* `orderTx` and can carry an empty `transaction`. Same rule as `creditsCharged`.
|
|
127
|
+
*/
|
|
128
|
+
txHash?: string;
|
|
129
|
+
/**
|
|
130
|
+
* Credits the settle ACTUALLY REDEEMED, written by the SDK after settlement —
|
|
131
|
+
* not the credits the request asked to burn, which stay on `creditsUsed`.
|
|
132
|
+
*
|
|
133
|
+
* ⚠️ Its ABSENCE is meaningful and is part of the contract. The key is omitted
|
|
134
|
+
* when there is no measured redemption to report: a pay-as-you-go plan (which
|
|
135
|
+
* holds no credit balance, so its `creditsRedeemed` is '0' even on a charge
|
|
136
|
+
* that succeeded), a settle that failed, or a backend that reported no usable
|
|
137
|
+
* figure. `0` means the opposite — a settle that completed and redeemed
|
|
138
|
+
* nothing. Read it with `in`, never truthiness. See `resolveCreditsCharged`.
|
|
139
|
+
*/
|
|
140
|
+
creditsCharged?: number;
|
|
116
141
|
}
|
|
117
142
|
/**
|
|
118
143
|
* Options required to register or retrieve a client in the registry.
|
package/dist/a2a/types.d.ts.map
CHANGED
|
@@ -1 +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,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACtC,MAAM,aAAa,CAAA;AAEpB,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAC1E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAE9C;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,IAAI,GAAG,qBAAqB,GAAG,uBAAuB,CAAA;AAE7F;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B,gEAAgE;IAChE,WAAW,EAAE,OAAO,CAAA;IACpB,gEAAgE;IAChE,YAAY,CAAC,EAAE,IAAI,CAAA;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O,CAAC,cAAc,EAAE,sBAAsB,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3F,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACvE;AAGD,YAAY,EACV,SAAS,EACT,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,EACrC,iBAAiB,EACjB,aAAa,GACd,CAAA;AAGD,YAAY,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/a2a/types.js.map
CHANGED
|
@@ -1 +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 TaskArtifactUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n\nimport type { ExecutionEventBus, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { StartAgentRequest } from '../common/types.ts'\nimport type { Payments } from '../payments.ts'\n\n/**\n * Union type for A2A streaming events\n *\n * This type represents all possible events that can be yielded by A2A streaming methods.\n * It includes messages, tasks, status updates, and artifact updates.\n */\nexport type A2AStreamEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent\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 * Configuration for credit redemption behavior\n *\n * This interface defines how credits should be redeemed for a specific agent.\n * The configuration is set at the server level and cannot be manipulated by clients.\n */\nexport interface PaymentRedemptionConfig {\n /** Whether to use batch processing for redemptions */\n useBatch?: boolean\n /** Whether to use margin-based redemptions (if false, uses fixed credits) */\n useMargin?: boolean\n /** Margin percentage (0-100) when using margin-based redemptions */\n marginPercent?: number\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 /** Agent ID for payment tracking */\n agentId?: string\n /** Configuration for credit redemption behavior */\n redemptionConfig?: PaymentRedemptionConfig\n}\n\n/**\n * Options required to register or retrieve a client in the registry.\n */\nexport interface ClientRegistryOptions {\n agentBaseUrl: string\n agentId: string\n planId: string\n agentCardPath?: string\n delegationConfig?: import('../common/types.js').DelegationConfig\n /**\n * EIP-712 token version to request. `3` mints a single-use token bound to the\n * agent's service endpoint, minted per paid call instead of cached.\n */\n tokenVersion?: import('../common/types.js').X402TokenVersion\n}\n\n/**\n * Options for agent interaction methods (used by PaymentsClient).\n */\nexport interface AgentOptions {\n agentId: string\n planId?: string\n}\n\n/**\n * HTTP context associated with a task or message (for internal request tracking).\n *\n * INVARIANT — exactly one of two mutually-exclusive states:\n * - **payment-required**: a payment-gated request arrived with NO token, so only\n * `paymentRequired` is set (`bearerToken`/`validation` are absent). The handler\n * short-circuits to an `input-required` task instead of executing the agent.\n * - **authorized**: a token was supplied (in band via `x402.payment.payload` when\n * `inBand` is true, else the deprecated `payment-signature` header), so\n * `bearerToken` + `validation` are set (`paymentRequired` is absent).\n *\n * A `mode`-discriminated union would enforce this at the type level (tracked as a\n * follow-up); for now consumers guard the field they need — e.g. the settlement\n * path asserts `bearerToken` + `validation` are present.\n */\nexport type HttpRequestContext = {\n /** Set only in the authorized state. */\n bearerToken?: string\n urlRequested?: string\n httpMethodRequested?: string\n /** The validated request — set only in the authorized state. */\n validation?: StartAgentRequest\n /**\n * x402 v2 A2A in-band transport: set by the server middleware when a\n * payment-gated request arrives with NO token (neither in-band\n * `x402.payment.payload` nor the deprecated `payment-signature` header). The\n * handler short-circuits and returns an `input-required` task carrying this\n * X402PaymentRequired object under `x402.payment.required`, instead of\n * executing the agent. Set only in the payment-required state.\n */\n paymentRequired?: import('../x402/facilitator-api.js').X402PaymentRequired\n /**\n * Whether the bearer token was supplied in band (via `x402.payment.payload`\n * message metadata) rather than the deprecated `payment-signature` header.\n * When true, settlement receipts are stamped into the task metadata under the\n * spec-defined `x402.payment.*` keys.\n */\n inBand?: boolean\n}\n\n/**\n * Authentication result for A2A requests (equivalent to MCP AuthResult)\n */\nexport interface A2AAuthResult {\n /** The agent request ID for tracking */\n requestId: string\n /** The bearer token for authentication */\n token: string\n /** The agent ID */\n agentId: string\n /** The agent request data */\n agentRequest: StartAgentRequest\n}\n\n/**\n * Agent request context provided to A2A AgentExecutors\n *\n * This context contains all the payment-related data that an AgentExecutor needs\n * to process requests with payment integration. The agent is responsible for\n * calculating and specifying credits in its final response.\n */\nexport interface AgentRequestContext {\n /** Authentication result with request metadata */\n authResult: A2AAuthResult\n /** The HTTP context with request details */\n httpContext: HttpRequestContext\n /** The payments service instance for observability and other operations */\n paymentsService: Payments\n}\n\n/**\n * Base RequestContext interface (local definition based on actual usage)\n *\n * This defines the structure that the A2A SDK RequestContext actually has\n * based on how it's used in PaymentsRequestHandler.\n */\nexport interface RequestContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Unique identifier for the task */\n taskId: string\n /** Unique identifier for the context/conversation */\n contextId: string\n /** Any existing task state (for task continuation scenarios) */\n task?: Task\n /** Reference tasks for multi-turn conversations */\n referenceTasks?: Task[]\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n}\n\n/**\n * Extended RequestContext with agent request data injection\n *\n * This extends the standard A2A RequestContext to include agent request context\n * while maintaining compatibility with the A2A protocol.\n */\nexport interface PaymentsRequestContext extends RequestContext {\n /** Agent request context injection (following MCP pattern) */\n payments?: AgentRequestContext\n}\n\n/**\n * Payments-specific AgentExecutor that uses PaymentsRequestContext\n */\nexport interface PaymentsAgentExecutor {\n execute(requestContext: PaymentsRequestContext, eventBus: ExecutionEventBus): Promise<void>\n cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>\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 PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n ExecutionEventBus,\n AgentExecutor,\n}\n\n// Re-export server options type for convenience\nexport type { PaymentsA2AServerOptions } from './server.ts'\n"]}
|
|
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 TaskArtifactUpdateEvent,\n PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from '@a2a-js/sdk'\n\nimport type { ExecutionEventBus, AgentExecutor } from '@a2a-js/sdk/server'\nimport type { StartAgentRequest } from '../common/types.ts'\nimport type { Payments } from '../payments.ts'\n\n/**\n * Union type for A2A streaming events\n *\n * This type represents all possible events that can be yielded by A2A streaming methods.\n * It includes messages, tasks, status updates, and artifact updates.\n */\nexport type A2AStreamEvent = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent\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 * Configuration for credit redemption behavior\n *\n * This interface defines how credits should be redeemed for a specific agent.\n * The configuration is set at the server level and cannot be manipulated by clients.\n */\nexport interface PaymentRedemptionConfig {\n /** Whether to use batch processing for redemptions */\n useBatch?: boolean\n /** Whether to use margin-based redemptions (if false, uses fixed credits) */\n useMargin?: boolean\n /** Margin percentage (0-100) when using margin-based redemptions */\n marginPercent?: number\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 /** Agent ID for payment tracking */\n agentId?: string\n /** Configuration for credit redemption behavior */\n redemptionConfig?: PaymentRedemptionConfig\n /**\n * The settle's transaction reference, written by the SDK after settlement.\n * A chain tx hash on the crypto rails; the PSP transaction id on fiat (a\n * Stripe PaymentIntent `pi_...`), so do not assume it is a hash.\n *\n * ABSENT unless the settle both succeeded AND reported a `transaction`. The\n * wire's `transaction` is an empty string on a failed settle, and publishing\n * that put a blank id on a completed task — so the key is omitted instead,\n * and its PRESENCE means a settlement really happened. Absence does not by\n * itself mean failure: a successful fiat charge is referenced by the receipt's\n * `orderTx` and can carry an empty `transaction`. Same rule as `creditsCharged`.\n */\n txHash?: string\n /**\n * Credits the settle ACTUALLY REDEEMED, written by the SDK after settlement —\n * not the credits the request asked to burn, which stay on `creditsUsed`.\n *\n * ⚠️ Its ABSENCE is meaningful and is part of the contract. The key is omitted\n * when there is no measured redemption to report: a pay-as-you-go plan (which\n * holds no credit balance, so its `creditsRedeemed` is '0' even on a charge\n * that succeeded), a settle that failed, or a backend that reported no usable\n * figure. `0` means the opposite — a settle that completed and redeemed\n * nothing. Read it with `in`, never truthiness. See `resolveCreditsCharged`.\n */\n creditsCharged?: number\n}\n\n/**\n * Options required to register or retrieve a client in the registry.\n */\nexport interface ClientRegistryOptions {\n agentBaseUrl: string\n agentId: string\n planId: string\n agentCardPath?: string\n delegationConfig?: import('../common/types.js').DelegationConfig\n /**\n * EIP-712 token version to request. `3` mints a single-use token bound to the\n * agent's service endpoint, minted per paid call instead of cached.\n */\n tokenVersion?: import('../common/types.js').X402TokenVersion\n}\n\n/**\n * Options for agent interaction methods (used by PaymentsClient).\n */\nexport interface AgentOptions {\n agentId: string\n planId?: string\n}\n\n/**\n * HTTP context associated with a task or message (for internal request tracking).\n *\n * INVARIANT — exactly one of two mutually-exclusive states:\n * - **payment-required**: a payment-gated request arrived with NO token, so only\n * `paymentRequired` is set (`bearerToken`/`validation` are absent). The handler\n * short-circuits to an `input-required` task instead of executing the agent.\n * - **authorized**: a token was supplied (in band via `x402.payment.payload` when\n * `inBand` is true, else the deprecated `payment-signature` header), so\n * `bearerToken` + `validation` are set (`paymentRequired` is absent).\n *\n * A `mode`-discriminated union would enforce this at the type level (tracked as a\n * follow-up); for now consumers guard the field they need — e.g. the settlement\n * path asserts `bearerToken` + `validation` are present.\n */\nexport type HttpRequestContext = {\n /** Set only in the authorized state. */\n bearerToken?: string\n urlRequested?: string\n httpMethodRequested?: string\n /** The validated request — set only in the authorized state. */\n validation?: StartAgentRequest\n /**\n * x402 v2 A2A in-band transport: set by the server middleware when a\n * payment-gated request arrives with NO token (neither in-band\n * `x402.payment.payload` nor the deprecated `payment-signature` header). The\n * handler short-circuits and returns an `input-required` task carrying this\n * X402PaymentRequired object under `x402.payment.required`, instead of\n * executing the agent. Set only in the payment-required state.\n */\n paymentRequired?: import('../x402/facilitator-api.js').X402PaymentRequired\n /**\n * Whether the bearer token was supplied in band (via `x402.payment.payload`\n * message metadata) rather than the deprecated `payment-signature` header.\n * When true, settlement receipts are stamped into the task metadata under the\n * spec-defined `x402.payment.*` keys.\n */\n inBand?: boolean\n}\n\n/**\n * Authentication result for A2A requests (equivalent to MCP AuthResult)\n */\nexport interface A2AAuthResult {\n /** The agent request ID for tracking */\n requestId: string\n /** The bearer token for authentication */\n token: string\n /** The agent ID */\n agentId: string\n /** The agent request data */\n agentRequest: StartAgentRequest\n}\n\n/**\n * Agent request context provided to A2A AgentExecutors\n *\n * This context contains all the payment-related data that an AgentExecutor needs\n * to process requests with payment integration. The agent is responsible for\n * calculating and specifying credits in its final response.\n */\nexport interface AgentRequestContext {\n /** Authentication result with request metadata */\n authResult: A2AAuthResult\n /** The HTTP context with request details */\n httpContext: HttpRequestContext\n /** The payments service instance for observability and other operations */\n paymentsService: Payments\n}\n\n/**\n * Base RequestContext interface (local definition based on actual usage)\n *\n * This defines the structure that the A2A SDK RequestContext actually has\n * based on how it's used in PaymentsRequestHandler.\n */\nexport interface RequestContext {\n /** The original message from the user containing the request */\n userMessage: Message\n /** Unique identifier for the task */\n taskId: string\n /** Unique identifier for the context/conversation */\n contextId: string\n /** Any existing task state (for task continuation scenarios) */\n task?: Task\n /** Reference tasks for multi-turn conversations */\n referenceTasks?: Task[]\n /** Additional metadata from the original request */\n requestMetadata?: Record<string, any>\n /** Any existing task state (for task continuation scenarios) */\n existingTask?: Task\n}\n\n/**\n * Extended RequestContext with agent request data injection\n *\n * This extends the standard A2A RequestContext to include agent request context\n * while maintaining compatibility with the A2A protocol.\n */\nexport interface PaymentsRequestContext extends RequestContext {\n /** Agent request context injection (following MCP pattern) */\n payments?: AgentRequestContext\n}\n\n/**\n * Payments-specific AgentExecutor that uses PaymentsRequestContext\n */\nexport interface PaymentsAgentExecutor {\n execute(requestContext: PaymentsRequestContext, eventBus: ExecutionEventBus): Promise<void>\n cancelTask(taskId: string, eventBus: ExecutionEventBus): Promise<void>\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 PushNotificationConfig,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n ExecutionEventBus,\n AgentExecutor,\n}\n\n// Re-export server options type for convenience\nexport type { PaymentsA2AServerOptions } from './server.ts'\n"]}
|
package/dist/api/agents-api.d.ts
CHANGED
|
@@ -116,13 +116,14 @@ export declare class AgentsAPI extends BasePaymentsAPI {
|
|
|
116
116
|
* Gets the list of plans that can be ordered to get access to an agent.
|
|
117
117
|
*
|
|
118
118
|
* @param agentId - The unique identifier of the agent.
|
|
119
|
-
* @param pagination - Optional pagination options
|
|
119
|
+
* @param pagination - Optional pagination options. Accepts a plain object
|
|
120
|
+
* (`{ page, offset, sortBy, sortOrder }`) or a `PaginationOptions` instance.
|
|
120
121
|
* @returns A promise that resolves to the list of all different plans giving access to the agent.
|
|
121
122
|
* @throws PaymentsError if the agent is not found.
|
|
122
123
|
*
|
|
123
124
|
* @example
|
|
124
125
|
* ```
|
|
125
|
-
* const result = payments.agents.getAgentPlans(
|
|
126
|
+
* const result = payments.agents.getAgentPlans(agentId, { page: 1, offset: 10 })
|
|
126
127
|
* // {
|
|
127
128
|
* // total: 10,
|
|
128
129
|
* // page: 1,
|
|
@@ -131,7 +132,7 @@ export declare class AgentsAPI extends BasePaymentsAPI {
|
|
|
131
132
|
* // }
|
|
132
133
|
* ```
|
|
133
134
|
*/
|
|
134
|
-
getAgentPlans(agentId: string, pagination?: PaginationOptions): Promise<any>;
|
|
135
|
+
getAgentPlans(agentId: string, pagination?: Partial<PaginationOptions>): Promise<any>;
|
|
135
136
|
/**
|
|
136
137
|
* Lists the AI agents **you** published (the authenticated caller's own
|
|
137
138
|
* agents). This is account management, not a marketplace search — it never
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents-api.d.ts","sourceRoot":"","sources":["../../src/api/agents-api.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,eAAe,EAChB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAA6B,MAAM,oBAAoB,CAAA;AAYnG,YAAY,EAAE,kBAAkB,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,SAAI,EACR,MAAM,SAAM,EACZ,MAAM,SAAY,EAClB,SAAS,GAAE,KAAK,GAAG,MAAe,EAClC,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,GAAG,EAAE,CAAA;KAAE,CAAC;IAc1E;;;;;;;;;;;;;;;;;;;;OAoBG;IACU,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAYnF;;;;;;;;;;;;;;;;;;;;OAoBG;IACU,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;CAiBzF"}
|
package/dist/api/agents-api.js
CHANGED
|
@@ -178,13 +178,14 @@ export class AgentsAPI extends BasePaymentsAPI {
|
|
|
178
178
|
* Gets the list of plans that can be ordered to get access to an agent.
|
|
179
179
|
*
|
|
180
180
|
* @param agentId - The unique identifier of the agent.
|
|
181
|
-
* @param pagination - Optional pagination options
|
|
181
|
+
* @param pagination - Optional pagination options. Accepts a plain object
|
|
182
|
+
* (`{ page, offset, sortBy, sortOrder }`) or a `PaginationOptions` instance.
|
|
182
183
|
* @returns A promise that resolves to the list of all different plans giving access to the agent.
|
|
183
184
|
* @throws PaymentsError if the agent is not found.
|
|
184
185
|
*
|
|
185
186
|
* @example
|
|
186
187
|
* ```
|
|
187
|
-
* const result = payments.agents.getAgentPlans(
|
|
188
|
+
* const result = payments.agents.getAgentPlans(agentId, { page: 1, offset: 10 })
|
|
188
189
|
* // {
|
|
189
190
|
* // total: 10,
|
|
190
191
|
* // page: 1,
|
|
@@ -193,8 +194,10 @@ export class AgentsAPI extends BasePaymentsAPI {
|
|
|
193
194
|
* // }
|
|
194
195
|
* ```
|
|
195
196
|
*/
|
|
196
|
-
async getAgentPlans(agentId, pagination =
|
|
197
|
-
const query = API_URL_GET_AGENT_PLANS.replace(':agentId', agentId) +
|
|
197
|
+
async getAgentPlans(agentId, pagination = {}) {
|
|
198
|
+
const query = API_URL_GET_AGENT_PLANS.replace(':agentId', agentId) +
|
|
199
|
+
'?' +
|
|
200
|
+
new PaginationOptions(pagination).asQueryParams();
|
|
198
201
|
const url = new URL(query, this.environment.backend);
|
|
199
202
|
const response = await fetch(url, this.getPublicHTTPOptions('GET'));
|
|
200
203
|
if (!response.ok) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents-api.js","sourceRoot":"","sources":["../../src/api/agents-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAIL,iBAAiB,GAKlB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,eAAe,EAAsB,yBAAyB,EAAE,MAAM,oBAAoB,CAAA;AACnG,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,kBAAkB,EAClB,uBAAuB,EACvB,sBAAsB,EACtB,gCAAgC,EAChC,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,cAAc,CAAA;AAIrB;;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,EACtB,kBAAuC;QAEvC,MAAM,IAAI,GAAG;YACX,kBAAkB,EAAE,aAAa;YACjC,kBAAkB,EAAE,QAAQ;YAC5B,KAAK,EAAE,YAAY;SACpB,CAAA;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,q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Error } 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, PublicationOptions, resolvePublicationHeaders } from './base-payments.js'\nimport {\n API_URL_ADD_PLAN_AGENT,\n API_URL_GET_AGENT,\n API_URL_GET_AGENTS,\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\nexport type { PublicationOptions } from './base-payments.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 publicationOptions?: PublicationOptions,\n ): Promise<{ agentId: string }> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n plans: paymentPlans,\n }\n\n const options = this.getBackendHTTPOptions(\n 'POST',\n body,\n resolvePublicationHeaders(publicationOptions),\n )\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 safeParseJson(response))\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 publicationOptions?: PublicationOptions,\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(\n 'POST',\n body,\n resolvePublicationHeaders(publicationOptions),\n )\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(\n 'Unable to register agent & plan',\n await safeParseJson(response),\n )\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, this.getPublicHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await safeParseJson(response))\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 safeParseJson(response))\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, this.getPublicHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await safeParseJson(response))\n }\n return response.json()\n }\n\n /**\n * Lists the AI agents **you** published (the authenticated caller's own\n * agents). This is account management, not a marketplace search — it never\n * returns other users' agents.\n *\n * @param page - The page number to retrieve.\n * @param offset - The number of items per page.\n * @param sortBy - The field to sort the results by.\n * @param sortOrder - The order in which to sort the results.\n * @param orgId - Optional organization id. When set, returns every agent in\n * that organization (requires active membership) instead of the caller's.\n * @returns A promise that resolves to the paginated list of your agents.\n */\n public async getAgents(\n page = 1,\n offset = 100,\n sortBy = 'created',\n sortOrder: 'asc' | 'desc' = 'desc',\n orgId?: string,\n ): Promise<{ total: number; page: number; offset: number; agents: any[] }> {\n const url = new URL(API_URL_GET_AGENTS, this.environment.backend)\n url.searchParams.set('page', page.toString())\n url.searchParams.set('offset', offset.toString())\n url.searchParams.set('sortBy', sortBy)\n url.searchParams.set('sortOrder', sortOrder)\n if (orgId) url.searchParams.set('orgId', orgId)\n const response = await fetch(url, this.getBackendHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to get agents', await safeParseJson(response))\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 safeParseJson(response))\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(\n 'Unable to remove plan from agent',\n await safeParseJson(response),\n )\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,qBAAqB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAIL,iBAAiB,GAKlB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,eAAe,EAAsB,yBAAyB,EAAE,MAAM,oBAAoB,CAAA;AACnG,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,kBAAkB,EAClB,uBAAuB,EACvB,sBAAsB,EACtB,gCAAgC,EAChC,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,cAAc,CAAA;AAIrB;;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;;;;;;;;;;;;;;;;;;;;;;;;;;OA0B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AQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,aAAa,CAAC,WAAW,CAC7B,kCAAkC,EAClC,MAAM,aAAa,CAAC,QAAQ,CAAC,CAC9B,CAAA;QACH,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAA;IACxB,CAAC;CACF","sourcesContent":["import { safeParseJson } from '../common/helper.js'\nimport { 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, PublicationOptions, resolvePublicationHeaders } from './base-payments.js'\nimport {\n API_URL_ADD_PLAN_AGENT,\n API_URL_GET_AGENT,\n API_URL_GET_AGENTS,\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\nexport type { PublicationOptions } from './base-payments.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 publicationOptions?: PublicationOptions,\n ): Promise<{ agentId: string }> {\n const body = {\n metadataAttributes: agentMetadata,\n agentApiAttributes: agentApi,\n plans: paymentPlans,\n }\n\n const options = this.getBackendHTTPOptions(\n 'POST',\n body,\n resolvePublicationHeaders(publicationOptions),\n )\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 safeParseJson(response))\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 publicationOptions?: PublicationOptions,\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(\n 'POST',\n body,\n resolvePublicationHeaders(publicationOptions),\n )\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(\n 'Unable to register agent & plan',\n await safeParseJson(response),\n )\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, this.getPublicHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await safeParseJson(response))\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 safeParseJson(response))\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. Accepts a plain object\n * (`{ page, offset, sortBy, sortOrder }`) or a `PaginationOptions` instance.\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(agentId, { page: 1, offset: 10 })\n * // {\n * // total: 10,\n * // page: 1,\n * // offset: 5,\n * // plans: [ ..]\n * // }\n * ```\n */\n public async getAgentPlans(agentId: string, pagination: Partial<PaginationOptions> = {}) {\n const query =\n API_URL_GET_AGENT_PLANS.replace(':agentId', agentId) +\n '?' +\n new PaginationOptions(pagination).asQueryParams()\n const url = new URL(query, this.environment.backend)\n const response = await fetch(url, this.getPublicHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Agent not found', await safeParseJson(response))\n }\n return response.json()\n }\n\n /**\n * Lists the AI agents **you** published (the authenticated caller's own\n * agents). This is account management, not a marketplace search — it never\n * returns other users' agents.\n *\n * @param page - The page number to retrieve.\n * @param offset - The number of items per page.\n * @param sortBy - The field to sort the results by.\n * @param sortOrder - The order in which to sort the results.\n * @param orgId - Optional organization id. When set, returns every agent in\n * that organization (requires active membership) instead of the caller's.\n * @returns A promise that resolves to the paginated list of your agents.\n */\n public async getAgents(\n page = 1,\n offset = 100,\n sortBy = 'created',\n sortOrder: 'asc' | 'desc' = 'desc',\n orgId?: string,\n ): Promise<{ total: number; page: number; offset: number; agents: any[] }> {\n const url = new URL(API_URL_GET_AGENTS, this.environment.backend)\n url.searchParams.set('page', page.toString())\n url.searchParams.set('offset', offset.toString())\n url.searchParams.set('sortBy', sortBy)\n url.searchParams.set('sortOrder', sortOrder)\n if (orgId) url.searchParams.set('orgId', orgId)\n const response = await fetch(url, this.getBackendHTTPOptions('GET'))\n if (!response.ok) {\n throw PaymentsError.fromBackend('Unable to get agents', await safeParseJson(response))\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 safeParseJson(response))\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(\n 'Unable to remove plan from agent',\n await safeParseJson(response),\n )\n }\n\n return response.json()\n }\n}\n"]}
|
|
@@ -56,8 +56,13 @@ export declare abstract class BasePaymentsAPI {
|
|
|
56
56
|
* (`<prefix>:<jwt>`); the key wins whenever its prefix is recognized. The
|
|
57
57
|
* deprecated `environment` option is still honored as a fallback when the
|
|
58
58
|
* key has no recognized prefix (e.g. local/custom dev), and ultimately
|
|
59
|
-
* defaults to `custom`.
|
|
60
|
-
*
|
|
59
|
+
* defaults to `custom`.
|
|
60
|
+
*
|
|
61
|
+
* The deprecation warning fires only when a passed `environment` is actually
|
|
62
|
+
* overridden by the key prefix (i.e. silently ignored). When it matches the
|
|
63
|
+
* derived environment, or is the fallback that's actually used, it's harmless
|
|
64
|
+
* — documented snippets still pass a matching `environment`, so nagging every
|
|
65
|
+
* new integration would be pure noise (#431).
|
|
61
66
|
*/
|
|
62
67
|
private resolveEnvironmentName;
|
|
63
68
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-payments.d.ts","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAClE,OAAO,EACL,eAAe,EACf,eAAe,EAGhB,MAAM,oBAAoB,CAAA;AAM3B;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,qBAAqB,CAAA;AAUvD;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB,CAAA;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,CAAC,EAAE,kBAAkB,GAC3B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAKpC;AAED;;;GAGG;AACH,8BAAsB,eAAe;IACnC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,MAAM,EAAE,aAAa,CAAA;IAC/B,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;;;;OAIG;IACH,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAC1B,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IAChC,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IAChC,SAAS,CAAC,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAA;IACvC,iBAAiB,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C,cAAc,EAAE,MAAM,CAAA;KAAE;IAc9E;;;OAGG;IACI,kBAAkB,IAAI,eAAe;IAI5C;;;OAGG;IACI,iBAAiB,IAAI,MAAM,GAAG,SAAS;IAI9C;;;;;;OAMG;IACI,iBAAiB,IAAI,MAAM,GAAG,IAAI;IAIzC;;;;;;;OAOG;IACI,iBAAiB,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAI7D;;;;;;;;;OASG;IACH,SAAS,CAAC,qBAAqB,CAC7B,MAAM,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,GAAG,EACV,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IA4BvC;;;;;;;;OAQG;IACH,SAAS,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG;gBAE7C,MAAM;iBACL,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;eACxB,MAAM;;CAgBlB"}
|
|
@@ -73,20 +73,27 @@ export class BasePaymentsAPI {
|
|
|
73
73
|
* (`<prefix>:<jwt>`); the key wins whenever its prefix is recognized. The
|
|
74
74
|
* deprecated `environment` option is still honored as a fallback when the
|
|
75
75
|
* key has no recognized prefix (e.g. local/custom dev), and ultimately
|
|
76
|
-
* defaults to `custom`.
|
|
77
|
-
*
|
|
76
|
+
* defaults to `custom`.
|
|
77
|
+
*
|
|
78
|
+
* The deprecation warning fires only when a passed `environment` is actually
|
|
79
|
+
* overridden by the key prefix (i.e. silently ignored). When it matches the
|
|
80
|
+
* derived environment, or is the fallback that's actually used, it's harmless
|
|
81
|
+
* — documented snippets still pass a matching `environment`, so nagging every
|
|
82
|
+
* new integration would be pure noise (#431).
|
|
78
83
|
*/
|
|
79
84
|
resolveEnvironmentName(options) {
|
|
80
85
|
const fromKey = getEnvironmentFromApiKey(options.nvmApiKey);
|
|
81
|
-
|
|
86
|
+
const resolved = fromKey ?? options.environment ?? 'custom';
|
|
87
|
+
if (options.environment &&
|
|
88
|
+
options.environment !== resolved &&
|
|
89
|
+
!environmentOptionDeprecationWarned) {
|
|
82
90
|
environmentOptionDeprecationWarned = true;
|
|
83
|
-
const override = fromKey && fromKey !== options.environment
|
|
84
|
-
? ` It is ignored in favor of the environment derived from the API key ('${fromKey}').`
|
|
85
|
-
: '';
|
|
86
91
|
console.warn("[DEPRECATED] The 'environment' option is deprecated; the environment is now derived " +
|
|
87
|
-
`from the NVM API key prefix
|
|
92
|
+
`from the NVM API key prefix. Your value ('${options.environment}') is ignored in favor of ` +
|
|
93
|
+
`the environment derived from the API key ('${resolved}'). Remove the 'environment' option ` +
|
|
94
|
+
'to silence this warning.');
|
|
88
95
|
}
|
|
89
|
-
return
|
|
96
|
+
return resolved;
|
|
90
97
|
}
|
|
91
98
|
/**
|
|
92
99
|
* Parses the NVM API Key to extract the account address.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-payments.js","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAChC,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAE3D,OAAO,EAGL,YAAY,EACZ,wBAAwB,GACzB,MAAM,oBAAoB,CAAA;AAE3B,8EAA8E;AAC9E,8EAA8E;AAC9E,IAAI,kCAAkC,GAAG,KAAK,CAAA;AAE9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,kBAAkB,CAAA;AAEvD;;;;;GAKG;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAS,CAAC,qBAAqB,CAAC,CAAC,CAAA;AAiBtE;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,OAA4B;IAE5B,IAAI,OAAO,EAAE,cAAc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AU;QACvD,MAAM,OAAO,GAIT;YACF,MAAM;YACN,OAAO,EAAE;gBACP,MAAM,EAAE,kBAAkB;gBAC1B,cAAc,EAAE,kBAAkB;gBAClC,CAAC,kBAAkB,CAAC,EAAE,IAAI,CAAC,OAAO,IAAI,kBAAkB;aACzD;SACF,CAAA;QAED,IAAI,IAAI,EAAE,CAAC;YACT,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;QACnD,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF","sourcesContent":["import { decodeJwt } from 'jose'\nimport { API_VERSION_HEADER, LOCKED_API_VERSION } from '../common/api-version.js'\nimport { jsonReplacer } from '../common/helper.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, PaymentScheme } from '../common/types.js'\nimport {\n EnvironmentInfo,\n EnvironmentName,\n Environments,\n getEnvironmentFromApiKey,\n} from '../environments.js'\n\n// Emit the `environment` deprecation notice at most once per process to avoid\n// log spam when many sub-API instances are constructed from the same options.\nlet environmentOptionDeprecationWarned = false\n\n/**\n * Header used by the Nevermined backend to resolve the active organization\n * context for an authenticated request. Resolution priority is:\n * path `:orgId` > this header > API-key tag > fallback membership > personal.\n * See `apps/api/src/common/guards/current-org-context.guard.ts` in nvm-monorepo.\n */\nexport const CURRENT_ORG_ID_HEADER = 'X-Current-Org-Id'\n\n/**\n * Set of header names that callers can pass to `getBackendHTTPOptions` via\n * `extraHeaders`. Anything outside this set is dropped silently so a stray\n * `Authorization` or `Content-Type` override can't clobber the SDK's\n * transport security headers.\n */\nconst ALLOWED_EXTRA_HEADERS = new Set<string>([CURRENT_ORG_ID_HEADER])\n\n/**\n * Options accepted by publication methods (`registerAgent`,\n * `registerAgentAndPlan`, `registerPlan`, …) that want to override the\n * active organization workspace for a single call.\n */\nexport type PublicationOptions = {\n /**\n * Organization id (e.g. `org-…`) to publish into. When set, the SDK\n * sends an `X-Current-Org-Id` header for this call only — the caller's\n * instance-level pin (set via `Payments.setOrganizationId`) is not\n * affected.\n */\n organizationId?: string\n}\n\n/**\n * Builds the `extraHeaders` argument for `getBackendHTTPOptions` from\n * publication options. Returns `undefined` when no override is requested\n * so existing callers receive identical request shapes.\n */\nexport function resolvePublicationHeaders(\n options?: PublicationOptions,\n): Record<string, string> | undefined {\n if (options?.organizationId) {\n return { [CURRENT_ORG_ID_HEADER]: options.organizationId }\n }\n return undefined\n}\n\n/**\n * Base class extended by all Payments API classes.\n * It provides common functionality such as parsing the NVM API Key and getting the account address.\n */\nexport abstract class BasePaymentsAPI {\n protected nvmApiKey: string\n protected scheme: PaymentScheme\n protected environment: EnvironmentInfo\n protected environmentName: EnvironmentName\n protected returnUrl: string\n protected appId?: string\n /**\n * Backend API version (MAJOR.MINOR) pinned by this instance, set from\n * `options.version`. When unset, every request defaults to\n * {@link LOCKED_API_VERSION}.\n */\n protected version?: string\n protected accountAddress: string\n protected heliconeApiKey: string\n protected currentOrganizationId: string | null\n public isBrowserInstance = true\n\n constructor(options: PaymentOptions) {\n // Type-level narrowing of PaymentScheme to 'nvm' won't protect callers\n // pinned to an older .d.ts that still has 'visa' in the union — they\n // would silently fall through to the standard pipeline and hit a\n // misleading 'Invalid NVM API Key' from parseNvmApiKey when the\n // legacy Visa path tolerated a non-JWT key. Reject up front with a\n // clear migration message.\n if (options.scheme && options.scheme !== 'nvm') {\n throw new PaymentsError(\n `scheme '${options.scheme}' is no longer supported. Visa is now exposed as provider:'visa' on createDelegation; construct Payments without a scheme override.`,\n )\n }\n this.nvmApiKey = options.nvmApiKey\n this.scheme = options.scheme || 'nvm'\n this.returnUrl = options.returnUrl || ''\n this.environmentName = this.resolveEnvironmentName(options)\n this.environment = Environments[this.environmentName]\n this.appId = options.appId\n // `version` is the backend API pin (MAJOR.MINOR) sent verbatim as\n // Nevermined-Version. Fail fast on a malformed value rather than shipping\n // an invalid header (e.g. an SDK package version '1.0.0', 'v1.1', or '')\n // that the backend rejects with 400 on every call.\n if (options.version !== undefined && !/^\\d+\\.\\d+$/.test(options.version)) {\n throw new PaymentsError(\n `Invalid 'version' option '${options.version}': expected a backend API version as MAJOR.MINOR (e.g. '1.1'). Omit it to use the SDK's default pin.`,\n )\n }\n this.version = options.version\n this.currentOrganizationId = options.organizationId ?? null\n\n const { accountAddress, heliconeApiKey } = this.parseNvmApiKey()\n this.accountAddress = accountAddress\n this.heliconeApiKey = heliconeApiKey\n }\n\n /**\n * Resolves the active environment for this instance.\n *\n * The environment is derived from the NVM API key prefix\n * (`<prefix>:<jwt>`); the key wins whenever its prefix is recognized. The\n * deprecated `environment` option is still honored as a fallback when the\n * key has no recognized prefix (e.g. local/custom dev), and ultimately\n * defaults to `custom`. Passing `environment` emits a one-time deprecation\n * warning.\n */\n private resolveEnvironmentName(options: PaymentOptions): EnvironmentName {\n const fromKey = getEnvironmentFromApiKey(options.nvmApiKey)\n\n if (options.environment && !environmentOptionDeprecationWarned) {\n environmentOptionDeprecationWarned = true\n const override =\n fromKey && fromKey !== options.environment\n ? ` It is ignored in favor of the environment derived from the API key ('${fromKey}').`\n : ''\n console.warn(\n \"[DEPRECATED] The 'environment' option is deprecated; the environment is now derived \" +\n `from the NVM API key prefix.${override} Remove the 'environment' option to silence this warning.`,\n )\n }\n\n return fromKey ?? options.environment ?? 'custom'\n }\n\n /**\n * Parses the NVM API Key to extract the account address.\n * @throws PaymentsError if the API key is invalid.\n */\n protected parseNvmApiKey(): { accountAddress: string; heliconeApiKey: string } {\n try {\n if (!this.nvmApiKey) {\n throw new PaymentsError('NVM API Key is required')\n }\n const jwt = decodeJwt(this.nvmApiKey)\n const accountAddress = jwt.sub as string\n const heliconeApiKey = jwt.o11y as string\n return { accountAddress, heliconeApiKey }\n } catch (error) {\n throw new PaymentsError('Invalid NVM API Key')\n }\n }\n\n /**\n * Returns the environment name used to initialize the Payments instance.\n * @returns The environment name (e.g. 'sandbox', 'live')\n */\n public getEnvironmentName(): EnvironmentName {\n return this.environmentName\n }\n\n /**\n * It returns the account address associated with the NVM API Key used to initialize the Payments Library instance.\n * @returns The account address extracted from the NVM API Key\n */\n public getAccountAddress(): string | undefined {\n return this.accountAddress\n }\n\n /**\n * Returns the current organization context applied to every authenticated\n * backend request via the `X-Current-Org-Id` header.\n *\n * `null` means \"no pinned workspace\" — the backend falls back to the\n * caller's API-key tag or most-recent active membership.\n */\n public getOrganizationId(): string | null {\n return this.currentOrganizationId\n }\n\n /**\n * Sets the organization context applied to every subsequent authenticated\n * backend request via the `X-Current-Org-Id` header.\n *\n * Pass `null` to clear the pin and fall back to the backend default.\n *\n * @param organizationId - Org ID (e.g. `org-…`) or `null` to clear.\n */\n public setOrganizationId(organizationId: string | null): void {\n this.currentOrganizationId = organizationId\n }\n\n /**\n * Returns the HTTP options required to query the backend.\n * @param method - HTTP method.\n * @param body - Optional request body.\n * @param extraHeaders - Optional per-call header overrides. Use\n * `{ 'X-Current-Org-Id': orgId }` to target a specific workspace for\n * one call without mutating the instance-level pin.\n * @returns HTTP options object.\n * @internal\n */\n protected getBackendHTTPOptions(\n method: string,\n body?: any,\n extraHeaders?: Record<string, string>,\n ) {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.nvmApiKey}`,\n [API_VERSION_HEADER]: this.version ?? LOCKED_API_VERSION,\n }\n if (this.currentOrganizationId) {\n headers[CURRENT_ORG_ID_HEADER] = this.currentOrganizationId\n }\n if (extraHeaders) {\n // Allowlist callers' header overrides so a passed-in `Authorization`\n // or `Content-Type` can't clobber the SDK's transport security\n // headers. Today only `X-Current-Org-Id` is allowed through.\n for (const [name, value] of Object.entries(extraHeaders)) {\n if (ALLOWED_EXTRA_HEADERS.has(name)) {\n headers[name] = value\n }\n }\n }\n return {\n method,\n headers,\n ...(body && { body: JSON.stringify(body, jsonReplacer) }),\n }\n }\n\n /**\n * Get HTTP options for public backend requests (no authorization header).\n * Converts body keys from snake_case to camelCase for consistency.\n *\n * @param method - HTTP method\n * @param body - Optional request body (keys will be converted to camelCase)\n * @returns HTTP options object\n * @internal\n */\n protected getPublicHTTPOptions(method: string, body?: any) {\n const options: {\n method: string\n headers: Record<string, string>\n body?: string\n } = {\n method,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n [API_VERSION_HEADER]: this.version ?? LOCKED_API_VERSION,\n },\n }\n\n if (body) {\n options.body = JSON.stringify(body, jsonReplacer)\n }\n\n return options\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-payments.js","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAChC,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAE3D,OAAO,EAGL,YAAY,EACZ,wBAAwB,GACzB,MAAM,oBAAoB,CAAA;AAE3B,8EAA8E;AAC9E,8EAA8E;AAC9E,IAAI,kCAAkC,GAAG,KAAK,CAAA;AAE9C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,kBAAkB,CAAA;AAEvD;;;;;GAKG;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAS,CAAC,qBAAqB,CAAC,CAAC,CAAA;AAiBtE;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,OAA4B;IAE5B,IAAI,OAAO,EAAE,cAAc,EAAE,CAAC;QAC5B,OAAO,EAAE,CAAC,qBAAqB,CAAC,EAAE,OAAO,CAAC,cAAc,EAAE,CAAA;IAC5D,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,OAAgB,eAAe;IAkBnC,YAAY,OAAuB;QAF5B,sBAAiB,GAAG,IAAI,CAAA;QAG7B,uEAAuE;QACvE,qEAAqE;QACrE,iEA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AAS,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;QACnD,CAAC;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF","sourcesContent":["import { decodeJwt } from 'jose'\nimport { API_VERSION_HEADER, LOCKED_API_VERSION } from '../common/api-version.js'\nimport { jsonReplacer } from '../common/helper.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, PaymentScheme } from '../common/types.js'\nimport {\n EnvironmentInfo,\n EnvironmentName,\n Environments,\n getEnvironmentFromApiKey,\n} from '../environments.js'\n\n// Emit the `environment` deprecation notice at most once per process to avoid\n// log spam when many sub-API instances are constructed from the same options.\nlet environmentOptionDeprecationWarned = false\n\n/**\n * Header used by the Nevermined backend to resolve the active organization\n * context for an authenticated request. Resolution priority is:\n * path `:orgId` > this header > API-key tag > fallback membership > personal.\n * See `apps/api/src/common/guards/current-org-context.guard.ts` in nvm-monorepo.\n */\nexport const CURRENT_ORG_ID_HEADER = 'X-Current-Org-Id'\n\n/**\n * Set of header names that callers can pass to `getBackendHTTPOptions` via\n * `extraHeaders`. Anything outside this set is dropped silently so a stray\n * `Authorization` or `Content-Type` override can't clobber the SDK's\n * transport security headers.\n */\nconst ALLOWED_EXTRA_HEADERS = new Set<string>([CURRENT_ORG_ID_HEADER])\n\n/**\n * Options accepted by publication methods (`registerAgent`,\n * `registerAgentAndPlan`, `registerPlan`, …) that want to override the\n * active organization workspace for a single call.\n */\nexport type PublicationOptions = {\n /**\n * Organization id (e.g. `org-…`) to publish into. When set, the SDK\n * sends an `X-Current-Org-Id` header for this call only — the caller's\n * instance-level pin (set via `Payments.setOrganizationId`) is not\n * affected.\n */\n organizationId?: string\n}\n\n/**\n * Builds the `extraHeaders` argument for `getBackendHTTPOptions` from\n * publication options. Returns `undefined` when no override is requested\n * so existing callers receive identical request shapes.\n */\nexport function resolvePublicationHeaders(\n options?: PublicationOptions,\n): Record<string, string> | undefined {\n if (options?.organizationId) {\n return { [CURRENT_ORG_ID_HEADER]: options.organizationId }\n }\n return undefined\n}\n\n/**\n * Base class extended by all Payments API classes.\n * It provides common functionality such as parsing the NVM API Key and getting the account address.\n */\nexport abstract class BasePaymentsAPI {\n protected nvmApiKey: string\n protected scheme: PaymentScheme\n protected environment: EnvironmentInfo\n protected environmentName: EnvironmentName\n protected returnUrl: string\n protected appId?: string\n /**\n * Backend API version (MAJOR.MINOR) pinned by this instance, set from\n * `options.version`. When unset, every request defaults to\n * {@link LOCKED_API_VERSION}.\n */\n protected version?: string\n protected accountAddress: string\n protected heliconeApiKey: string\n protected currentOrganizationId: string | null\n public isBrowserInstance = true\n\n constructor(options: PaymentOptions) {\n // Type-level narrowing of PaymentScheme to 'nvm' won't protect callers\n // pinned to an older .d.ts that still has 'visa' in the union — they\n // would silently fall through to the standard pipeline and hit a\n // misleading 'Invalid NVM API Key' from parseNvmApiKey when the\n // legacy Visa path tolerated a non-JWT key. Reject up front with a\n // clear migration message.\n if (options.scheme && options.scheme !== 'nvm') {\n throw new PaymentsError(\n `scheme '${options.scheme}' is no longer supported. Visa is now exposed as provider:'visa' on createDelegation; construct Payments without a scheme override.`,\n )\n }\n this.nvmApiKey = options.nvmApiKey\n this.scheme = options.scheme || 'nvm'\n this.returnUrl = options.returnUrl || ''\n this.environmentName = this.resolveEnvironmentName(options)\n this.environment = Environments[this.environmentName]\n this.appId = options.appId\n // `version` is the backend API pin (MAJOR.MINOR) sent verbatim as\n // Nevermined-Version. Fail fast on a malformed value rather than shipping\n // an invalid header (e.g. an SDK package version '1.0.0', 'v1.1', or '')\n // that the backend rejects with 400 on every call.\n if (options.version !== undefined && !/^\\d+\\.\\d+$/.test(options.version)) {\n throw new PaymentsError(\n `Invalid 'version' option '${options.version}': expected a backend API version as MAJOR.MINOR (e.g. '1.1'). Omit it to use the SDK's default pin.`,\n )\n }\n this.version = options.version\n this.currentOrganizationId = options.organizationId ?? null\n\n const { accountAddress, heliconeApiKey } = this.parseNvmApiKey()\n this.accountAddress = accountAddress\n this.heliconeApiKey = heliconeApiKey\n }\n\n /**\n * Resolves the active environment for this instance.\n *\n * The environment is derived from the NVM API key prefix\n * (`<prefix>:<jwt>`); the key wins whenever its prefix is recognized. The\n * deprecated `environment` option is still honored as a fallback when the\n * key has no recognized prefix (e.g. local/custom dev), and ultimately\n * defaults to `custom`.\n *\n * The deprecation warning fires only when a passed `environment` is actually\n * overridden by the key prefix (i.e. silently ignored). When it matches the\n * derived environment, or is the fallback that's actually used, it's harmless\n * — documented snippets still pass a matching `environment`, so nagging every\n * new integration would be pure noise (#431).\n */\n private resolveEnvironmentName(options: PaymentOptions): EnvironmentName {\n const fromKey = getEnvironmentFromApiKey(options.nvmApiKey)\n const resolved = fromKey ?? options.environment ?? 'custom'\n\n if (\n options.environment &&\n options.environment !== resolved &&\n !environmentOptionDeprecationWarned\n ) {\n environmentOptionDeprecationWarned = true\n console.warn(\n \"[DEPRECATED] The 'environment' option is deprecated; the environment is now derived \" +\n `from the NVM API key prefix. Your value ('${options.environment}') is ignored in favor of ` +\n `the environment derived from the API key ('${resolved}'). Remove the 'environment' option ` +\n 'to silence this warning.',\n )\n }\n\n return resolved\n }\n\n /**\n * Parses the NVM API Key to extract the account address.\n * @throws PaymentsError if the API key is invalid.\n */\n protected parseNvmApiKey(): { accountAddress: string; heliconeApiKey: string } {\n try {\n if (!this.nvmApiKey) {\n throw new PaymentsError('NVM API Key is required')\n }\n const jwt = decodeJwt(this.nvmApiKey)\n const accountAddress = jwt.sub as string\n const heliconeApiKey = jwt.o11y as string\n return { accountAddress, heliconeApiKey }\n } catch (error) {\n throw new PaymentsError('Invalid NVM API Key')\n }\n }\n\n /**\n * Returns the environment name used to initialize the Payments instance.\n * @returns The environment name (e.g. 'sandbox', 'live')\n */\n public getEnvironmentName(): EnvironmentName {\n return this.environmentName\n }\n\n /**\n * It returns the account address associated with the NVM API Key used to initialize the Payments Library instance.\n * @returns The account address extracted from the NVM API Key\n */\n public getAccountAddress(): string | undefined {\n return this.accountAddress\n }\n\n /**\n * Returns the current organization context applied to every authenticated\n * backend request via the `X-Current-Org-Id` header.\n *\n * `null` means \"no pinned workspace\" — the backend falls back to the\n * caller's API-key tag or most-recent active membership.\n */\n public getOrganizationId(): string | null {\n return this.currentOrganizationId\n }\n\n /**\n * Sets the organization context applied to every subsequent authenticated\n * backend request via the `X-Current-Org-Id` header.\n *\n * Pass `null` to clear the pin and fall back to the backend default.\n *\n * @param organizationId - Org ID (e.g. `org-…`) or `null` to clear.\n */\n public setOrganizationId(organizationId: string | null): void {\n this.currentOrganizationId = organizationId\n }\n\n /**\n * Returns the HTTP options required to query the backend.\n * @param method - HTTP method.\n * @param body - Optional request body.\n * @param extraHeaders - Optional per-call header overrides. Use\n * `{ 'X-Current-Org-Id': orgId }` to target a specific workspace for\n * one call without mutating the instance-level pin.\n * @returns HTTP options object.\n * @internal\n */\n protected getBackendHTTPOptions(\n method: string,\n body?: any,\n extraHeaders?: Record<string, string>,\n ) {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.nvmApiKey}`,\n [API_VERSION_HEADER]: this.version ?? LOCKED_API_VERSION,\n }\n if (this.currentOrganizationId) {\n headers[CURRENT_ORG_ID_HEADER] = this.currentOrganizationId\n }\n if (extraHeaders) {\n // Allowlist callers' header overrides so a passed-in `Authorization`\n // or `Content-Type` can't clobber the SDK's transport security\n // headers. Today only `X-Current-Org-Id` is allowed through.\n for (const [name, value] of Object.entries(extraHeaders)) {\n if (ALLOWED_EXTRA_HEADERS.has(name)) {\n headers[name] = value\n }\n }\n }\n return {\n method,\n headers,\n ...(body && { body: JSON.stringify(body, jsonReplacer) }),\n }\n }\n\n /**\n * Get HTTP options for public backend requests (no authorization header).\n * Converts body keys from snake_case to camelCase for consistency.\n *\n * @param method - HTTP method\n * @param body - Optional request body (keys will be converted to camelCase)\n * @returns HTTP options object\n * @internal\n */\n protected getPublicHTTPOptions(method: string, body?: any) {\n const options: {\n method: string\n headers: Record<string, string>\n body?: string\n } = {\n method,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n [API_VERSION_HEADER]: this.version ?? LOCKED_API_VERSION,\n },\n }\n\n if (body) {\n options.body = JSON.stringify(body, jsonReplacer)\n }\n\n return options\n }\n}\n"]}
|
package/dist/api/nvm-api.d.ts
CHANGED
|
@@ -72,10 +72,10 @@ export declare abstract class AbstractHTTPClient {
|
|
|
72
72
|
}, accessToken?: string): {
|
|
73
73
|
Authorization?: string | undefined;
|
|
74
74
|
};
|
|
75
|
-
request(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', url: string, data?: any, reqOptions?: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
76
|
-
get(url: string, reqOptions?: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
77
|
-
post(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
78
|
-
put(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
79
|
-
delete(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
75
|
+
request(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', url: string, data?: any, reqOptions?: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}, any>>;
|
|
76
|
+
get(url: string, reqOptions?: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}, any>>;
|
|
77
|
+
post(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}, any>>;
|
|
78
|
+
put(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}, any>>;
|
|
79
|
+
delete(url: string, data: any, reqOptions: HTTPRequestOptions): Promise<import("axios").AxiosResponse<any, any, {}, any>>;
|
|
80
80
|
}
|
|
81
81
|
//# sourceMappingURL=nvm-api.d.ts.map
|
|
@@ -1,12 +1,36 @@
|
|
|
1
1
|
import type OpenAI from 'openai';
|
|
2
2
|
import type Together from 'together-ai';
|
|
3
|
-
import type * as ChainsModule from 'langchain/chains';
|
|
4
|
-
import type * as AgentsModule from 'langchain/agents';
|
|
5
|
-
import type * as ToolsModule from 'langchain/tools';
|
|
6
3
|
import type * as anthropic from '@anthropic-ai/sdk';
|
|
7
4
|
import type * as cohere from 'cohere-ai';
|
|
8
5
|
import type * as bedrock from '@aws-sdk/client-bedrock-runtime';
|
|
9
6
|
import type * as google_aiplatform from '@google-cloud/aiplatform';
|
|
7
|
+
/**
|
|
8
|
+
* A LangChain entry-point module handed over by the caller.
|
|
9
|
+
*
|
|
10
|
+
* On the resolved `@traceloop/node-server-sdk` (0.26.0) nothing reads a member
|
|
11
|
+
* of it. `observability-api.ts` forwards the bag to
|
|
12
|
+
* `traceloop.initialize({ instrumentModules })` behind an `as any`, and there
|
|
13
|
+
* the field is declared `langchain?: boolean` and never consulted —
|
|
14
|
+
* `instrumentModules?.langchain` appears nowhere in its `dist/` — because
|
|
15
|
+
* LangChain is instrumented unconditionally by hooking
|
|
16
|
+
* `@langchain/core/callbacks/manager`.
|
|
17
|
+
*
|
|
18
|
+
* That was not always so. traceloop 0.14 declared five module fields
|
|
19
|
+
* (`chainsModule`, `agentsModule`, `toolsModule`, `runnablesModule`,
|
|
20
|
+
* `vectorStoreModule`) and passed them to `manuallyInstrument`; #158 took three
|
|
21
|
+
* of them, and they went inert with the 0.26 bump in #312. They stay for source
|
|
22
|
+
* compatibility with callers written against that contract.
|
|
23
|
+
*
|
|
24
|
+
* Typing the three as `typeof import('langchain/chains')` and friends therefore
|
|
25
|
+
* bought no checking, and cost twice. It pinned this SDK's build to one
|
|
26
|
+
* LangChain layout — v1 moved the legacy chains and agents entry points out, so
|
|
27
|
+
* those subpaths stopped resolving and a dev-only bump failed with TS2307
|
|
28
|
+
* (#317) — and, because declaration emit keeps those imports in the published
|
|
29
|
+
* `types.d.ts` while `langchain` is neither a dependency nor a peer, it broke
|
|
30
|
+
* the typecheck of any consumer building with `skipLibCheck: false` unless they
|
|
31
|
+
* happened to have a 0.3-layout `langchain` installed.
|
|
32
|
+
*/
|
|
33
|
+
export type LangChainModule = Record<string, unknown>;
|
|
10
34
|
export type AsyncLoggerProviders = {
|
|
11
35
|
openAI?: typeof OpenAI;
|
|
12
36
|
anthropic?: typeof anthropic;
|
|
@@ -14,10 +38,14 @@ export type AsyncLoggerProviders = {
|
|
|
14
38
|
bedrock?: typeof bedrock;
|
|
15
39
|
google_aiplatform?: typeof google_aiplatform;
|
|
16
40
|
together?: typeof Together;
|
|
41
|
+
/**
|
|
42
|
+
* Inert on the resolved traceloop (0.26.0), which instruments LangChain
|
|
43
|
+
* unconditionally and ignores these modules. See {@link LangChainModule}.
|
|
44
|
+
*/
|
|
17
45
|
langchain?: {
|
|
18
|
-
chainsModule?:
|
|
19
|
-
agentsModule?:
|
|
20
|
-
toolsModule?:
|
|
46
|
+
chainsModule?: LangChainModule;
|
|
47
|
+
agentsModule?: LangChainModule;
|
|
48
|
+
toolsModule?: LangChainModule;
|
|
21
49
|
};
|
|
22
50
|
};
|
|
23
51
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/api/observability-api/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAA;AAChC,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAA;AACvC,OAAO,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/api/observability-api/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAA;AAChC,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAA;AACvC,OAAO,KAAK,KAAK,SAAS,MAAM,mBAAmB,CAAA;AACnD,OAAO,KAAK,KAAK,MAAM,MAAM,WAAW,CAAA;AACxC,OAAO,KAAK,KAAK,O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,OAAO,EAAE,MAAM,CAAA;IACf,cAAc,EAAE,sBAAsB,CAAA;CACvC,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/api/observability-api/types.ts"],"names":[],"mappings":"","sourcesContent":["import type OpenAI from 'openai'\nimport type Together from 'together-ai'\nimport type * as
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/api/observability-api/types.ts"],"names":[],"mappings":"","sourcesContent":["import type OpenAI from 'openai'\nimport type Together from 'together-ai'\nimport type * as anthropic from '@anthropic-ai/sdk'\nimport type * as cohere from 'cohere-ai'\nimport type * as bedrock from '@aws-sdk/client-bedrock-runtime'\nimport type * as google_aiplatform from '@google-cloud/aiplatform'\n\n/**\n * A LangChain entry-point module handed over by the caller.\n *\n * On the resolved `@traceloop/node-server-sdk` (0.26.0) nothing reads a member\n * of it. `observability-api.ts` forwards the bag to\n * `traceloop.initialize({ instrumentModules })` behind an `as any`, and there\n * the field is declared `langchain?: boolean` and never consulted —\n * `instrumentModules?.langchain` appears nowhere in its `dist/` — because\n * LangChain is instrumented unconditionally by hooking\n * `@langchain/core/callbacks/manager`.\n *\n * That was not always so. traceloop 0.14 declared five module fields\n * (`chainsModule`, `agentsModule`, `toolsModule`, `runnablesModule`,\n * `vectorStoreModule`) and passed them to `manuallyInstrument`; #158 took three\n * of them, and they went inert with the 0.26 bump in #312. They stay for source\n * compatibility with callers written against that contract.\n *\n * Typing the three as `typeof import('langchain/chains')` and friends therefore\n * bought no checking, and cost twice. It pinned this SDK's build to one\n * LangChain layout — v1 moved the legacy chains and agents entry points out, so\n * those subpaths stopped resolving and a dev-only bump failed with TS2307\n * (#317) — and, because declaration emit keeps those imports in the published\n * `types.d.ts` while `langchain` is neither a dependency nor a peer, it broke\n * the typecheck of any consumer building with `skipLibCheck: false` unless they\n * happened to have a 0.3-layout `langchain` installed.\n */\nexport type LangChainModule = Record<string, unknown>\n\nexport type AsyncLoggerProviders = {\n openAI?: typeof OpenAI\n anthropic?: typeof anthropic\n cohere?: typeof cohere\n bedrock?: typeof bedrock\n google_aiplatform?: typeof google_aiplatform\n together?: typeof Together\n /**\n * Inert on the resolved traceloop (0.26.0), which instruments LangChain\n * unconditionally and ignores these modules. See {@link LangChainModule}.\n */\n langchain?: {\n chainsModule?: LangChainModule\n agentsModule?: LangChainModule\n toolsModule?: LangChainModule\n }\n}\n\n/**\n * Configuration for creating a Helicone payload\n */\nexport interface HeliconePayloadConfig {\n model: string\n inputData: Record<string, any>\n temperature?: number\n top_p?: number\n frequency_penalty?: number\n presence_penalty?: number\n n?: number\n stream?: boolean\n}\n\n/**\n * Configuration for creating a Helicone response\n */\nexport interface HeliconeResponseConfig {\n idPrefix: string\n model: string\n resultData: any\n usage: {\n prompt_tokens: number\n completion_tokens: number\n total_tokens: number\n prompt_tokens_details?: {\n cached_tokens: number\n audio_tokens: number\n }\n completion_tokens_details?: {\n reasoning_tokens: number\n audio_tokens: number\n accepted_prediction_tokens: number\n rejected_prediction_tokens: number\n }\n }\n systemFingerprint?: string\n}\n\nexport type CustomProperties = Record<string, string>\n\nexport type NeverminedHeliconeHeaders = {\n 'Helicone-Auth': string\n 'Helicone-Property-accountaddress': string\n 'Helicone-Property-consumeraddress': string\n 'Helicone-Property-agentid': string\n 'Helicone-Property-planid': string\n 'Helicone-Property-plantype': string\n 'Helicone-Property-planname': string\n 'Helicone-Property-agentname': string\n 'Helicone-Property-agentrequestid': string\n 'Helicone-Property-pricepercredit': string\n 'Helicone-Property-environmentname': string\n 'Helicone-Property-batch': string\n 'Helicone-Property-ismarginbased': string\n 'Helicone-Property-marginpercent': string\n}\n\nexport type DefaultHeliconeHeaders = NeverminedHeliconeHeaders & CustomProperties\n\nexport type ChatOpenAIConfiguration = {\n model: string\n apiKey: string\n configuration: {\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n }\n}\n\nexport type OpenAIConfiguration = {\n apiKey: string\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n}\n"]}
|