@naturalpay/sdk 0.1.3 → 0.2.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/index.d.ts CHANGED
@@ -1,6 +1,52 @@
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
+
4
50
  /**
5
51
  * Parse an API key and return its environment label.
6
52
  *
@@ -22,20 +68,35 @@ interface HTTPClientOptions {
22
68
  apiKey?: string;
23
69
  baseUrl?: string;
24
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;
25
75
  }
26
76
  interface RequestOptions {
27
77
  body?: Record<string, unknown>;
28
78
  params?: Record<string, unknown>;
29
79
  headers?: Record<string, string>;
80
+ modelUsage?: ModelUsage;
30
81
  }
31
82
  declare class HTTPClient {
32
83
  private readonly apiKey;
33
84
  private readonly baseUrl;
34
85
  private readonly timeout;
86
+ private readonly maxRetries;
35
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;
36
96
  constructor(options?: HTTPClientOptions);
37
97
  /**
38
98
  * Get a cached JWT or exchange API key for a new one.
99
+ * Retries on transient failures (5xx, network) but not on 401.
39
100
  */
40
101
  private getJwt;
41
102
  /**
@@ -47,7 +108,18 @@ declare class HTTPClient {
47
108
  */
48
109
  private handleResponse;
49
110
  /**
50
- * 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.
51
123
  */
52
124
  request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
53
125
  get<T>(path: string, options?: Omit<RequestOptions, 'body'>): Promise<T>;
@@ -73,16 +145,24 @@ interface PaymentCreateParams {
73
145
  agentId?: string;
74
146
  /** Payment amount in minor units (cents). 5000 = $50.00. */
75
147
  amount: number;
76
- customerPartyId: string;
148
+ /** Sender party ID (pty_xxx). Omit to send from your own wallet; provide for delegated payments on behalf of a customer. */
149
+ customerPartyId?: string;
77
150
  /** Recipient email, phone number, or party ID (pty_xxx). */
78
151
  recipient: string;
79
- /** Payment memo/description. */
80
- memo: string;
152
+ /**
153
+ * Human-readable description of the payment's purpose. Required for all SDK
154
+ * callers. For agent-initiated payments, write a rich rationale (≥20 chars
155
+ * recommended) so the user can confidently approve and the audit trail is
156
+ * legible.
157
+ */
158
+ description: string;
81
159
  /** Currency code (default: USD). */
82
160
  currency?: string;
83
161
  idempotencyKey: string;
84
162
  /** Developer's session/conversation ID for observability grouping. */
85
163
  instanceId?: string;
164
+ /** Trace ID for distributed tracing correlation. */
165
+ traceId?: string;
86
166
  }
87
167
 
88
168
  /**
@@ -101,8 +181,9 @@ interface Transaction {
101
181
  amount: number;
102
182
  currency: string;
103
183
  status: string;
184
+ escalationId?: string;
185
+ disputeId?: string;
104
186
  description?: string;
105
- memo?: string;
106
187
  createdAt: string;
107
188
  updatedAt?: string;
108
189
  isDelegated: boolean;
@@ -110,6 +191,8 @@ interface Transaction {
110
191
  customerAgentId?: string;
111
192
  senderName?: string;
112
193
  recipientName?: string;
194
+ initiatorName?: string;
195
+ initiatorIsAgent?: boolean;
113
196
  transactionType: string;
114
197
  category: string;
115
198
  direction: string;
@@ -117,7 +200,7 @@ interface Transaction {
117
200
  destinationPartyId?: string;
118
201
  sourceWalletId?: string;
119
202
  destinationWalletId?: string;
120
- /** Internal instance ID (ins_xxx) assigned by server. */
203
+ /** Present on payment creation responses when agent instance metadata was supplied. */
121
204
  instanceId?: string;
122
205
  /** Claim link URL for unclaimed payments. */
123
206
  claimLink?: string;
@@ -125,8 +208,12 @@ interface Transaction {
125
208
  interface TransactionGetParams {
126
209
  /** Customer party ID (pty_xxx) for delegated transaction lookup. */
127
210
  customerPartyId?: string;
211
+ /** Agent ID (agt_xxx) for observability attribution. */
212
+ agentId?: string;
128
213
  /** Developer's session/conversation ID for observability grouping. */
129
214
  instanceId?: string;
215
+ /** Trace ID for distributed tracing correlation. */
216
+ traceId?: string;
130
217
  }
131
218
  interface TransactionListParams {
132
219
  limit?: number;
@@ -136,6 +223,8 @@ interface TransactionListParams {
136
223
  type?: TransactionTypeFilter;
137
224
  /** Developer's session/conversation ID for observability grouping. */
138
225
  instanceId?: string;
226
+ /** Trace ID for distributed tracing correlation. */
227
+ traceId?: string;
139
228
  }
140
229
  interface TransactionListResponse {
141
230
  transactions: Transaction[];
@@ -166,9 +255,9 @@ interface AmountInfo {
166
255
  interface BalanceBreakdown {
167
256
  operatingFunded: AmountInfo;
168
257
  operatingAdvanced: AmountInfo;
169
- escrowFundedSettled: AmountInfo;
170
- escrowAdvanced: AmountInfo;
171
- holdsOutbound: AmountInfo;
258
+ pendingIn: AmountInfo;
259
+ pendingOut: AmountInfo;
260
+ held: AmountInfo;
172
261
  }
173
262
  interface AccountBalance {
174
263
  walletId: string;
@@ -180,8 +269,12 @@ interface AccountBalance {
180
269
  interface BalanceOptions {
181
270
  /** Customer party ID (pty_xxx) when acting on behalf of customer. */
182
271
  customerPartyId?: string;
272
+ /** Agent ID (agt_xxx) for observability attribution. */
273
+ agentId?: string;
183
274
  /** Developer's session/conversation ID for observability grouping. */
184
275
  instanceId?: string;
276
+ /** Trace ID for distributed tracing correlation. */
277
+ traceId?: string;
185
278
  }
186
279
  interface WithdrawParams {
187
280
  /** Withdrawal amount in minor units (cents). 5000 = $50.00. */
@@ -191,6 +284,12 @@ interface WithdrawParams {
191
284
  currency?: string;
192
285
  description?: string;
193
286
  idempotencyKey: string;
287
+ /** Agent ID (agt_xxx) for observability attribution. */
288
+ agentId?: string;
289
+ /** Developer's session/conversation ID for observability grouping. */
290
+ instanceId?: string;
291
+ /** Trace ID for distributed tracing correlation. */
292
+ traceId?: string;
194
293
  }
195
294
  interface WithdrawResponse {
196
295
  transferId?: string;
@@ -274,8 +373,12 @@ interface AgentCreateParams {
274
373
  description?: string;
275
374
  limits?: TransactionLimits;
276
375
  idempotencyKey?: string;
376
+ /** Agent ID (agt_xxx) for observability attribution. */
377
+ agentId?: string;
277
378
  /** Developer's session/conversation ID for observability grouping. */
278
379
  instanceId?: string;
380
+ /** Trace ID for distributed tracing correlation. */
381
+ traceId?: string;
279
382
  }
280
383
  /** @deprecated Use Agent instead — server returns full resource for all operations. */
281
384
  type AgentCreateResponse = Agent;
@@ -284,8 +387,12 @@ interface AgentUpdateParams {
284
387
  description?: string;
285
388
  status?: AgentStatus;
286
389
  idempotencyKey?: string;
390
+ /** Agent ID (agt_xxx) for observability attribution. */
391
+ agentId?: string;
287
392
  /** Developer's session/conversation ID for observability grouping. */
288
393
  instanceId?: string;
394
+ /** Trace ID for distributed tracing correlation. */
395
+ traceId?: string;
289
396
  }
290
397
  /** @deprecated Use Agent instead — server returns full resource for all operations. */
291
398
  type AgentUpdateResponse = Agent;
@@ -293,16 +400,28 @@ interface AgentListParams {
293
400
  status?: AgentStatus;
294
401
  limit?: number;
295
402
  cursor?: string;
403
+ /** Agent ID (agt_xxx) for observability attribution. */
404
+ agentId?: string;
296
405
  /** Developer's session/conversation ID for observability grouping. */
297
406
  instanceId?: string;
407
+ /** Trace ID for distributed tracing correlation. */
408
+ traceId?: string;
298
409
  }
299
410
  interface AgentGetOptions {
411
+ /** Agent ID (agt_xxx) for observability attribution. */
412
+ agentId?: string;
300
413
  /** Developer's session/conversation ID for observability grouping. */
301
414
  instanceId?: string;
415
+ /** Trace ID for distributed tracing correlation. */
416
+ traceId?: string;
302
417
  }
303
418
  interface AgentDeleteOptions {
419
+ /** Agent ID (agt_xxx) for observability attribution. */
420
+ agentId?: string;
304
421
  /** Developer's session/conversation ID for observability grouping. */
305
422
  instanceId?: string;
423
+ /** Trace ID for distributed tracing correlation. */
424
+ traceId?: string;
306
425
  }
307
426
  interface AgentListResponse {
308
427
  agents: Agent[];
@@ -382,6 +501,8 @@ interface AgentDelegationListParams {
382
501
  cursor?: string;
383
502
  /** Developer's session/conversation ID for observability grouping. */
384
503
  instanceId?: string;
504
+ /** Trace ID for distributed tracing correlation. */
505
+ traceId?: string;
385
506
  }
386
507
  interface AgentDelegationListResponse {
387
508
  agentDelegations: AgentDelegation[];
@@ -420,9 +541,8 @@ interface CustomerPartyInfo {
420
541
  }
421
542
  interface Customer {
422
543
  id: string;
423
- type: 'party' | 'delegationInvitation';
544
+ type: 'party';
424
545
  party?: CustomerPartyInfo;
425
- email?: string;
426
546
  status: string;
427
547
  permissions: string[];
428
548
  createdAt: string;
@@ -430,17 +550,34 @@ interface Customer {
430
550
  walletAvailableDollars?: string;
431
551
  walletAccess: 'granted' | 'denied' | 'noWallet';
432
552
  }
553
+ interface PendingInvitation {
554
+ id: string;
555
+ type: 'delegationInvitation';
556
+ email?: string;
557
+ status: string;
558
+ permissions: string[];
559
+ createdAt: string;
560
+ }
433
561
  interface CustomerListParams {
434
562
  limit?: number;
435
563
  cursor?: string;
564
+ /** Agent ID (agt_xxx) for observability attribution. */
565
+ agentId?: string;
436
566
  /** Developer's session/conversation ID for observability grouping. */
437
567
  instanceId?: string;
568
+ /** Trace ID for distributed tracing correlation. */
569
+ traceId?: string;
438
570
  }
439
571
  interface CustomerListResponse {
440
572
  items: Customer[];
441
573
  hasMore: boolean;
442
574
  nextCursor?: string | null;
443
575
  }
576
+ interface PendingInvitationListResponse {
577
+ items: PendingInvitation[];
578
+ hasMore: boolean;
579
+ nextCursor?: string | null;
580
+ }
444
581
 
445
582
  /**
446
583
  * Customers resource.
@@ -448,12 +585,16 @@ interface CustomerListResponse {
448
585
 
449
586
  declare class CustomersResource extends BaseResource {
450
587
  /**
451
- * List customers who have delegated access to the partner.
588
+ * List active customers who have delegated access to the partner.
452
589
  *
453
- * @param params - Pagination parameters
454
- * @returns CustomerListResponse with items, hasMore, nextCursor
590
+ * Returns only accepted delegations. Use {@link listInvitations} for pending
591
+ * invitations that have not yet been accepted.
455
592
  */
456
593
  list(params?: CustomerListParams): Promise<CustomerListResponse>;
594
+ /**
595
+ * List pending customer invitations you've sent that have not yet been accepted.
596
+ */
597
+ listInvitations(params?: CustomerListParams): Promise<PendingInvitationListResponse>;
457
598
  }
458
599
 
459
600
  /**
@@ -477,7 +618,7 @@ interface NaturalClientOptions extends HTTPClientOptions {
477
618
  * amount: 5000,
478
619
  * customerPartyId: 'pty_xxx',
479
620
  * recipient: 'alice@example.com',
480
- * memo: 'For consulting',
621
+ * description: 'For consulting',
481
622
  * idempotencyKey: 'unique-key-for-this-payment',
482
623
  * });
483
624
  *
@@ -510,6 +651,73 @@ declare class NaturalClient {
510
651
  constructor(options?: NaturalClientOptions);
511
652
  }
512
653
 
654
+ /** Branded string types for observability IDs */
655
+ type InstanceId = string & {
656
+ readonly __brand: 'InstanceId';
657
+ };
658
+ type TraceId = string & {
659
+ readonly __brand: 'TraceId';
660
+ };
661
+ type ToolCallId = string & {
662
+ readonly __brand: 'ToolCallId';
663
+ };
664
+
665
+ /**
666
+ * Natural's canonical tool-name vocabulary.
667
+ *
668
+ * These are the names Natural recognizes on the `X-Tool-Call` header and
669
+ * displays in admin audit views. The `runWithToolCall` helper accepts only
670
+ * these names, so callers typing a custom label get a TypeScript error at the
671
+ * call site — the SDK is the single source of truth.
672
+ *
673
+ * When Natural adds or renames a tool, update this constant in the same
674
+ * change. Callers with their own caller-side metadata should use the
675
+ * `developer_context` field instead.
676
+ */
677
+ declare const NATURAL_TOOL_NAMES: {
678
+ readonly CREATE_PAYMENT: "create_payment";
679
+ readonly GET_PAYMENT_STATUS: "get_payment_status";
680
+ readonly GET_ACCOUNT_BALANCE: "get_account_balance";
681
+ readonly LIST_TRANSACTIONS: "list_transactions";
682
+ readonly LIST_AGENTS: "list_agents";
683
+ readonly LIST_CUSTOMERS: "list_customers";
684
+ readonly LIST_CUSTOMER_INVITATIONS: "list_customer_invitations";
685
+ };
686
+ type NaturalToolName = (typeof NATURAL_TOOL_NAMES)[keyof typeof NATURAL_TOOL_NAMES];
687
+
688
+ /**
689
+ * Tool call context for MCP server -> HTTP layer communication.
690
+ *
691
+ * The MCP server sets tool call data (id + name + arguments) before invoking
692
+ * SDK methods. The HTTP layer reads it and sends the X-Tool-Call header to the
693
+ * BFF for audit/observability. Direct SDK users never interact with this module.
694
+ */
695
+
696
+ /**
697
+ * Generate a unique tool call ID with the `tc_` prefix.
698
+ */
699
+ declare function generateToolCallId(): ToolCallId;
700
+ /**
701
+ * Get the base64-encoded X-Tool-Call header value, or undefined if not in
702
+ * a tool call context.
703
+ *
704
+ * If the full header (with arguments) exceeds 16 KB, the arguments are
705
+ * omitted and a warning is logged.
706
+ */
707
+ declare function getToolCallHeader(): string | undefined;
708
+ /**
709
+ * Run a function within a tool call context. The HTTP layer will automatically
710
+ * pick up the tool call data and send it as the X-Tool-Call header.
711
+ *
712
+ * @param toolCallId - Unique ID for this invocation (tc_<uuid>).
713
+ * @param name - Canonical Natural tool name (see `NATURAL_TOOL_NAMES`).
714
+ * Custom caller-side labels are not accepted here; use the
715
+ * `developer_context` field for caller-side metadata.
716
+ * @param args - Raw tool arguments.
717
+ * @param fn - The function to execute within the context.
718
+ */
719
+ declare function runWithToolCall<T>(toolCallId: ToolCallId, name: NaturalToolName, args: Record<string, unknown>, fn: () => T): T;
720
+
513
721
  /**
514
722
  * Structured logging for Natural Payments SDK.
515
723
  *
@@ -684,10 +892,38 @@ declare class RateLimitError extends NaturalError {
684
892
  declare class ServerError extends NaturalError {
685
893
  constructor(message?: string);
686
894
  }
895
+ /**
896
+ * Webhook signature verification failed.
897
+ */
898
+ declare class WebhookVerificationError extends NaturalError {
899
+ constructor(message: string);
900
+ }
901
+
902
+ /**
903
+ * Webhook signature verification using Standard Webhooks HMAC-SHA256.
904
+ */
905
+ interface VerifyWebhookOptions {
906
+ toleranceInSeconds?: number;
907
+ }
908
+ /**
909
+ * Verify a webhook signature using Standard Webhooks HMAC-SHA256.
910
+ *
911
+ * The body must be the raw request body — not a parsed and re-serialized
912
+ * JSON object, as whitespace or key ordering differences would produce a
913
+ * different signature.
914
+ *
915
+ * @param body - Raw request body (string, Buffer, or Uint8Array)
916
+ * @param headers - Request headers containing webhook-id, webhook-timestamp, webhook-signature
917
+ * @param secret - Signing secret (with or without whsec_ prefix)
918
+ * @param options - Optional configuration (toleranceInSeconds)
919
+ * @returns Parsed JSON payload
920
+ * @throws WebhookVerificationError on any verification failure
921
+ */
922
+ declare function verifyWebhookSignature(body: string | Buffer | Uint8Array, headers: Record<string, string> | Headers, secret: string, options?: VerifyWebhookOptions): unknown;
687
923
 
688
924
  /**
689
925
  * Single source of truth for the SDK version string.
690
926
  */
691
- declare const VERSION = "0.1.3";
927
+ declare const VERSION = "0.1.4";
692
928
 
693
- 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, parseApiKeyEnv, runWithContext, validateBaseUrl };
929
+ 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, NATURAL_TOOL_NAMES, NaturalClient, type NaturalClientOptions, NaturalError, type NaturalToolName, type PaymentCreateParams, PaymentError, type PendingInvitation, type PendingInvitationListResponse, 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 };