@naturalpay/sdk 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,24 +1,102 @@
1
+ /**
2
+ * Agent config and model usage for LLM observability.
3
+ *
4
+ * Tracks static agent configuration (system prompt, tools) and per-request
5
+ * model usage so the observability service can attribute API calls to
6
+ * specific LLM sessions.
7
+ */
8
+ /**
9
+ * Static agent configuration — set once per client, sent to observability.
10
+ *
11
+ * Describes the agent's identity (system prompt and available tools).
12
+ * Model/provider are per-request and belong in ModelUsage.
13
+ */
14
+ interface AgentConfig {
15
+ systemPrompt: string;
16
+ toolsAvailable: string[];
17
+ }
18
+ interface ModelUsage {
19
+ model?: string;
20
+ provider?: string;
21
+ inputTokens?: number;
22
+ outputTokens?: number;
23
+ toolsCalled?: string[];
24
+ }
25
+ interface AgentConfigDict {
26
+ system_prompt: string;
27
+ tools_available: string[];
28
+ }
29
+ interface ModelUsageDict {
30
+ model?: string;
31
+ provider?: string;
32
+ input_tokens?: number;
33
+ output_tokens?: number;
34
+ tools_called?: string[];
35
+ }
36
+ /**
37
+ * SHA-256 hash for change detection.
38
+ *
39
+ * Covers only {system_prompt, tools_available} — model/provider
40
+ * are dynamic per-request and excluded from the config hash.
41
+ */
42
+ declare function configHash(cfg: AgentConfig): string;
43
+ declare function agentConfigToDict(cfg: AgentConfig): AgentConfigDict;
44
+ declare function modelUsageToDict(usage: ModelUsage): ModelUsageDict;
45
+
1
46
  /**
2
47
  * HTTP client for Natural Server API with JWT caching.
3
48
  */
49
+
50
+ /**
51
+ * Parse an API key and return its environment label.
52
+ *
53
+ * Accepts keys matching `sk_ntl_(dev|sandbox|prod)_*`. Throws
54
+ * `InvalidRequestError` for anything else. The return type is a narrowed
55
+ * literal union so callers can discriminate on the env without a second
56
+ * parse.
57
+ */
58
+ declare function parseApiKeyEnv(key: string): 'dev' | 'sandbox' | 'prod';
59
+ /**
60
+ * Validate that a base URL uses HTTPS, with a localhost auto-allow and an
61
+ * `NATURAL_ALLOW_HTTP=1` escape hatch for non-localhost plaintext hosts.
62
+ *
63
+ * Throws `InvalidRequestError` if the URL is not HTTPS and neither escape
64
+ * hatch applies. Runs at client construction, not per-request.
65
+ */
66
+ declare function validateBaseUrl(baseUrl: string): void;
4
67
  interface HTTPClientOptions {
5
68
  apiKey?: string;
6
69
  baseUrl?: string;
7
70
  timeout?: number;
71
+ agentConfig?: AgentConfig;
72
+ /** Default model/provider sent with every request as X-Model-Usage. */
73
+ defaultModelUsage?: Pick<ModelUsage, 'model' | 'provider'>;
74
+ maxRetries?: number;
8
75
  }
9
76
  interface RequestOptions {
10
77
  body?: Record<string, unknown>;
11
78
  params?: Record<string, unknown>;
12
79
  headers?: Record<string, string>;
80
+ modelUsage?: ModelUsage;
13
81
  }
14
82
  declare class HTTPClient {
15
83
  private readonly apiKey;
16
84
  private readonly baseUrl;
17
85
  private readonly timeout;
86
+ private readonly maxRetries;
18
87
  private readonly jwtCache;
88
+ private readonly agentConfig?;
89
+ private readonly _defaultModelUsage?;
90
+ private _configResolved;
91
+ private _configAttempted;
92
+ private _registerConfigPromise;
93
+ private _nextRetryAt;
94
+ private _retryBackoffMs;
95
+ private static readonly MAX_RETRY_BACKOFF_MS;
19
96
  constructor(options?: HTTPClientOptions);
20
97
  /**
21
98
  * Get a cached JWT or exchange API key for a new one.
99
+ * Retries on transient failures (5xx, network) but not on 401.
22
100
  */
23
101
  private getJwt;
24
102
  /**
@@ -30,7 +108,18 @@ declare class HTTPClient {
30
108
  */
31
109
  private handleResponse;
32
110
  /**
33
- * Make an authenticated request.
111
+ * Register agent config with the observability service.
112
+ *
113
+ * Called lazily before the first request. Errors are caught and logged,
114
+ * never thrown.
115
+ */
116
+ private registerConfig;
117
+ /**
118
+ * Add agent config hash and model usage headers if configured.
119
+ */
120
+ private injectModelContextHeaders;
121
+ /**
122
+ * Make an authenticated request with automatic retries.
34
123
  */
35
124
  request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
36
125
  get<T>(path: string, options?: Omit<RequestOptions, 'body'>): Promise<T>;
@@ -66,6 +155,8 @@ interface PaymentCreateParams {
66
155
  idempotencyKey: string;
67
156
  /** Developer's session/conversation ID for observability grouping. */
68
157
  instanceId?: string;
158
+ /** Trace ID for distributed tracing correlation. */
159
+ traceId?: string;
69
160
  }
70
161
 
71
162
  /**
@@ -108,8 +199,12 @@ interface Transaction {
108
199
  interface TransactionGetParams {
109
200
  /** Customer party ID (pty_xxx) for delegated transaction lookup. */
110
201
  customerPartyId?: string;
202
+ /** Agent ID (agt_xxx) for observability attribution. */
203
+ agentId?: string;
111
204
  /** Developer's session/conversation ID for observability grouping. */
112
205
  instanceId?: string;
206
+ /** Trace ID for distributed tracing correlation. */
207
+ traceId?: string;
113
208
  }
114
209
  interface TransactionListParams {
115
210
  limit?: number;
@@ -119,6 +214,8 @@ interface TransactionListParams {
119
214
  type?: TransactionTypeFilter;
120
215
  /** Developer's session/conversation ID for observability grouping. */
121
216
  instanceId?: string;
217
+ /** Trace ID for distributed tracing correlation. */
218
+ traceId?: string;
122
219
  }
123
220
  interface TransactionListResponse {
124
221
  transactions: Transaction[];
@@ -163,8 +260,12 @@ interface AccountBalance {
163
260
  interface BalanceOptions {
164
261
  /** Customer party ID (pty_xxx) when acting on behalf of customer. */
165
262
  customerPartyId?: string;
263
+ /** Agent ID (agt_xxx) for observability attribution. */
264
+ agentId?: string;
166
265
  /** Developer's session/conversation ID for observability grouping. */
167
266
  instanceId?: string;
267
+ /** Trace ID for distributed tracing correlation. */
268
+ traceId?: string;
168
269
  }
169
270
  interface WithdrawParams {
170
271
  /** Withdrawal amount in minor units (cents). 5000 = $50.00. */
@@ -174,6 +275,12 @@ interface WithdrawParams {
174
275
  currency?: string;
175
276
  description?: string;
176
277
  idempotencyKey: string;
278
+ /** Agent ID (agt_xxx) for observability attribution. */
279
+ agentId?: string;
280
+ /** Developer's session/conversation ID for observability grouping. */
281
+ instanceId?: string;
282
+ /** Trace ID for distributed tracing correlation. */
283
+ traceId?: string;
177
284
  }
178
285
  interface WithdrawResponse {
179
286
  transferId?: string;
@@ -257,8 +364,12 @@ interface AgentCreateParams {
257
364
  description?: string;
258
365
  limits?: TransactionLimits;
259
366
  idempotencyKey?: string;
367
+ /** Agent ID (agt_xxx) for observability attribution. */
368
+ agentId?: string;
260
369
  /** Developer's session/conversation ID for observability grouping. */
261
370
  instanceId?: string;
371
+ /** Trace ID for distributed tracing correlation. */
372
+ traceId?: string;
262
373
  }
263
374
  /** @deprecated Use Agent instead — server returns full resource for all operations. */
264
375
  type AgentCreateResponse = Agent;
@@ -267,8 +378,12 @@ interface AgentUpdateParams {
267
378
  description?: string;
268
379
  status?: AgentStatus;
269
380
  idempotencyKey?: string;
381
+ /** Agent ID (agt_xxx) for observability attribution. */
382
+ agentId?: string;
270
383
  /** Developer's session/conversation ID for observability grouping. */
271
384
  instanceId?: string;
385
+ /** Trace ID for distributed tracing correlation. */
386
+ traceId?: string;
272
387
  }
273
388
  /** @deprecated Use Agent instead — server returns full resource for all operations. */
274
389
  type AgentUpdateResponse = Agent;
@@ -276,16 +391,28 @@ interface AgentListParams {
276
391
  status?: AgentStatus;
277
392
  limit?: number;
278
393
  cursor?: string;
394
+ /** Agent ID (agt_xxx) for observability attribution. */
395
+ agentId?: string;
279
396
  /** Developer's session/conversation ID for observability grouping. */
280
397
  instanceId?: string;
398
+ /** Trace ID for distributed tracing correlation. */
399
+ traceId?: string;
281
400
  }
282
401
  interface AgentGetOptions {
402
+ /** Agent ID (agt_xxx) for observability attribution. */
403
+ agentId?: string;
283
404
  /** Developer's session/conversation ID for observability grouping. */
284
405
  instanceId?: string;
406
+ /** Trace ID for distributed tracing correlation. */
407
+ traceId?: string;
285
408
  }
286
409
  interface AgentDeleteOptions {
410
+ /** Agent ID (agt_xxx) for observability attribution. */
411
+ agentId?: string;
287
412
  /** Developer's session/conversation ID for observability grouping. */
288
413
  instanceId?: string;
414
+ /** Trace ID for distributed tracing correlation. */
415
+ traceId?: string;
289
416
  }
290
417
  interface AgentListResponse {
291
418
  agents: Agent[];
@@ -365,6 +492,8 @@ interface AgentDelegationListParams {
365
492
  cursor?: string;
366
493
  /** Developer's session/conversation ID for observability grouping. */
367
494
  instanceId?: string;
495
+ /** Trace ID for distributed tracing correlation. */
496
+ traceId?: string;
368
497
  }
369
498
  interface AgentDelegationListResponse {
370
499
  agentDelegations: AgentDelegation[];
@@ -416,8 +545,12 @@ interface Customer {
416
545
  interface CustomerListParams {
417
546
  limit?: number;
418
547
  cursor?: string;
548
+ /** Agent ID (agt_xxx) for observability attribution. */
549
+ agentId?: string;
419
550
  /** Developer's session/conversation ID for observability grouping. */
420
551
  instanceId?: string;
552
+ /** Trace ID for distributed tracing correlation. */
553
+ traceId?: string;
421
554
  }
422
555
  interface CustomerListResponse {
423
556
  items: Customer[];
@@ -450,9 +583,9 @@ interface NaturalClientOptions extends HTTPClientOptions {
450
583
  *
451
584
  * @example
452
585
  * ```typescript
453
- * import { NaturalClient } from 'naturalpay';
586
+ * import { NaturalClient } from '@naturalpay/sdk';
454
587
  *
455
- * const client = new NaturalClient({ apiKey: 'sk_ntl_sandbox_xxx' });
588
+ * const client = new NaturalClient({ apiKey: process.env['NATURAL_API_KEY'] });
456
589
  *
457
590
  * // Create a payment
458
591
  * const payment = await client.payments.create({
@@ -493,6 +626,48 @@ declare class NaturalClient {
493
626
  constructor(options?: NaturalClientOptions);
494
627
  }
495
628
 
629
+ /** Branded string types for observability IDs */
630
+ type InstanceId = string & {
631
+ readonly __brand: 'InstanceId';
632
+ };
633
+ type TraceId = string & {
634
+ readonly __brand: 'TraceId';
635
+ };
636
+ type ToolCallId = string & {
637
+ readonly __brand: 'ToolCallId';
638
+ };
639
+
640
+ /**
641
+ * Tool call context for MCP server -> HTTP layer communication.
642
+ *
643
+ * The MCP server sets tool call data (id + name + arguments) before invoking
644
+ * SDK methods. The HTTP layer reads it and sends the X-Tool-Call header to the
645
+ * BFF for audit/observability. Direct SDK users never interact with this module.
646
+ */
647
+
648
+ /**
649
+ * Generate a unique tool call ID with the `tc_` prefix.
650
+ */
651
+ declare function generateToolCallId(): ToolCallId;
652
+ /**
653
+ * Get the base64-encoded X-Tool-Call header value, or undefined if not in
654
+ * a tool call context.
655
+ *
656
+ * If the full header (with arguments) exceeds 16 KB, the arguments are
657
+ * omitted and a warning is logged.
658
+ */
659
+ declare function getToolCallHeader(): string | undefined;
660
+ /**
661
+ * Run a function within a tool call context. The HTTP layer will automatically
662
+ * pick up the tool call data and send it as the X-Tool-Call header.
663
+ *
664
+ * @param toolCallId - Unique ID for this invocation (tc_<uuid>).
665
+ * @param name - Tool name (e.g. "create_payment").
666
+ * @param args - Raw tool arguments.
667
+ * @param fn - The function to execute within the context.
668
+ */
669
+ declare function runWithToolCall<T>(toolCallId: ToolCallId, name: string, args: Record<string, unknown>, fn: () => T): T;
670
+
496
671
  /**
497
672
  * Structured logging for Natural Payments SDK.
498
673
  *
@@ -667,10 +842,38 @@ declare class RateLimitError extends NaturalError {
667
842
  declare class ServerError extends NaturalError {
668
843
  constructor(message?: string);
669
844
  }
845
+ /**
846
+ * Webhook signature verification failed.
847
+ */
848
+ declare class WebhookVerificationError extends NaturalError {
849
+ constructor(message: string);
850
+ }
851
+
852
+ /**
853
+ * Webhook signature verification using Standard Webhooks HMAC-SHA256.
854
+ */
855
+ interface VerifyWebhookOptions {
856
+ toleranceInSeconds?: number;
857
+ }
858
+ /**
859
+ * Verify a webhook signature using Standard Webhooks HMAC-SHA256.
860
+ *
861
+ * The body must be the raw request body — not a parsed and re-serialized
862
+ * JSON object, as whitespace or key ordering differences would produce a
863
+ * different signature.
864
+ *
865
+ * @param body - Raw request body (string, Buffer, or Uint8Array)
866
+ * @param headers - Request headers containing webhook-id, webhook-timestamp, webhook-signature
867
+ * @param secret - Signing secret (with or without whsec_ prefix)
868
+ * @param options - Optional configuration (toleranceInSeconds)
869
+ * @returns Parsed JSON payload
870
+ * @throws WebhookVerificationError on any verification failure
871
+ */
872
+ declare function verifyWebhookSignature(body: string | Buffer | Uint8Array, headers: Record<string, string> | Headers, secret: string, options?: VerifyWebhookOptions): unknown;
670
873
 
671
874
  /**
672
875
  * Single source of truth for the SDK version string.
673
876
  */
674
- declare const VERSION = "0.1.1";
877
+ declare const VERSION = "0.1.4";
675
878
 
676
- export { type AccountBalance, type Agent, type AgentCreateParams, type AgentCreateResponse, type AgentDelegation, type AgentDelegationListParams, type AgentDelegationListResponse, type AgentDeleteOptions, type AgentGetOptions, type AgentListParams, type AgentListResponse, type AgentStatus, type AgentUpdateParams, type AgentUpdateResponse, type AmountInfo, AuthenticationError, type BalanceBreakdown, type Customer, type CustomerListParams, type CustomerListResponse, type CustomerPartyInfo, InsufficientFundsError, InvalidRequestError, type LogLevel, Logger, NaturalClient, type NaturalClientOptions, NaturalError, type PaymentCreateParams, PaymentError, RateLimitError, RecipientNotFoundError, ServerError, type Transaction, type TransactionGetParams, type TransactionListParams, type TransactionListResponse, TransactionTypeFilter, VERSION, type WithdrawParams, type WithdrawResponse, bindContext, clearContext, configureLogging, getContext, getLogger, logApiCall, logError, logToolCall, runWithContext };
879
+ export { type AccountBalance, type Agent, type AgentConfig, type AgentConfigDict, type AgentCreateParams, type AgentCreateResponse, type AgentDelegation, type AgentDelegationListParams, type AgentDelegationListResponse, type AgentDeleteOptions, type AgentGetOptions, type AgentListParams, type AgentListResponse, type AgentStatus, type AgentUpdateParams, type AgentUpdateResponse, type AmountInfo, AuthenticationError, type BalanceBreakdown, type Customer, type CustomerListParams, type CustomerListResponse, type CustomerPartyInfo, type InstanceId, InsufficientFundsError, InvalidRequestError, type LogLevel, Logger, type ModelUsage, type ModelUsageDict, NaturalClient, type NaturalClientOptions, NaturalError, type PaymentCreateParams, PaymentError, RateLimitError, RecipientNotFoundError, ServerError, type ToolCallId, type TraceId, type Transaction, type TransactionGetParams, type TransactionListParams, type TransactionListResponse, TransactionTypeFilter, VERSION, type VerifyWebhookOptions, WebhookVerificationError, type WithdrawParams, type WithdrawResponse, agentConfigToDict, bindContext, clearContext, configHash, configureLogging, generateToolCallId, getContext, getLogger, getToolCallHeader, logApiCall, logError, logToolCall, modelUsageToDict, parseApiKeyEnv, runWithContext, runWithToolCall, validateBaseUrl, verifyWebhookSignature };