@dakota-xyz/ts-sdk 2.2.0 → 3.0.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/README.md +140 -16
- package/dist/index.d.mts +2122 -501
- package/dist/index.d.ts +2122 -501
- package/dist/index.js +388 -67
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +388 -67
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/environment.ts","../src/client/errors.ts","../src/client/config.ts","../src/client/transport.ts","../src/client/pagination.ts","../src/client/resources/base.ts","../src/client/resources/customers.ts","../src/client/resources/recipients.ts","../src/client/resources/destinations.ts","../src/client/resources/accounts.ts","../src/client/resources/transactions.ts","../src/client/resources/wallets.ts","../src/client/resources/events.ts","../src/client/resources/applications.ts","../src/client/resources/policies.ts","../src/client/resources/signer-groups.ts","../src/client/resources/api-keys.ts","../src/client/resources/users.ts","../src/client/resources/webhooks.ts","../src/client/resources/info.ts","../src/client/resources/sandbox.ts","../src/client/resources/self-serve.ts","../src/client/resources/fee-payout-destination.ts","../src/client/resources/payment-agents.ts","../src/client/resources/instructions.ts","../src/client/resources/mandates.ts","../src/client/resources/scheduled-payments.ts","../src/client/resources/insights.ts","../src/client/resources/agentic-policy.ts","../src/agentic/chat.ts","../src/agentic/wallets.ts","../src/client/client.ts","../src/agentic/canonicalize.ts","../src/agentic/sign.ts"],"names":["Environment","AuthMode","RETRYABLE_STATUS_CODES"],"mappings":";;;AAGO,IAAK,WAAA,qBAAAA,YAAAA,KAAL;AAEL,EAAAA,aAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,aAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,aAAA,aAAA,CAAA,GAAc,aAAA;AAEd,EAAAA,aAAA,OAAA,CAAA,GAAQ,OAAA;AARE,EAAA,OAAAA,YAAAA;AAAA,CAAA,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AC3C;AACF;AAWO,SAAS,sBAAA,CACd,eAAA,EACA,OAAA,EACA,eAAA,EACM;AACN,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,eAAA,CAAgB;AAAA,MAC1B,GAAA,EAAK,MAAA,CAAO,IAAA,CAAK,eAAA,EAAiB,QAAQ,CAAA;AAAA,MAC1C,MAAA,EAAQ,KAAA;AAAA,MACR,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAsB,GAAA,CAAc,OAAO,CAAA,CAAE,CAAA;AAAA,EAC/D;AACA,EAAA,IAAI,SAAA,CAAU,sBAAsB,IAAA,EAAM;AACxC,IAAA,MAAM,IAAI,MAAM,+CAA+C,CAAA;AAAA,EACjE;AACA,EAAA,IAAI,SAAA,CAAU,oBAAA,EAAsB,UAAA,KAAe,YAAA,EAAc;AAC/D,IAAA,MAAM,IAAI,MAAM,+CAA+C,CAAA;AAAA,EACjE;AACA,EAAA,MAAM,QAAA,GAAW,aAAa,QAAQ,CAAA;AACtC,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,MAAM,KAAK,QAAA,CAAS,MAAA;AAAA,IAClB,EAAE,GAAA,EAAK,SAAA,EAAW,WAAA,EAAa,KAAA,EAAM;AAAA,IACrC,MAAA,CAAO,IAAA,CAAK,eAAA,EAAiB,QAAQ;AAAA,GACvC;AACA,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AACF","file":"index.mjs","sourcesContent":["/**\n * Environment configuration for Dakota Platform API.\n */\nexport enum Environment {\n /** Sandbox environment for testing - no real money moves */\n Sandbox = 'sandbox',\n /** Production environment - real transactions with real money */\n Production = 'production',\n /** Development environment (internal use) */\n Development = 'development',\n /** Local environment (internal use) */\n Local = 'local',\n}\n\nconst ENVIRONMENT_URLS: Record<Environment, string> = {\n [Environment.Sandbox]: 'https://api.platform.sandbox.dakota.xyz',\n [Environment.Production]: 'https://api.platform.dakota.xyz',\n [Environment.Development]: 'https://api.platform.development.dakota.xyz',\n [Environment.Local]: 'http://localhost:6464',\n};\n\n/**\n * Get the base URL for a given environment.\n */\nexport function getEnvironmentURL(env: Environment): string {\n const url = ENVIRONMENT_URLS[env];\n if (!url) {\n throw new Error(`Unknown environment: ${env}`);\n }\n return url;\n}\n","/**\n * Error classes for Dakota SDK.\n */\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Represents a structured Dakota Platform API error response.\n */\nexport class APIError extends Error {\n /** HTTP status code */\n readonly statusCode: number;\n /** Machine-readable error code */\n readonly code: string;\n /** Additional error details */\n readonly details: Record<string, unknown> | null;\n /** Request ID for support tickets */\n readonly requestId: string | null;\n /** Raw response body */\n readonly rawBody: string | null;\n /** Whether this error is safe to retry */\n readonly retryable: boolean;\n\n constructor(\n statusCode: number,\n code: string,\n message: string,\n options?: {\n details?: Record<string, unknown> | null;\n requestId?: string | null;\n rawBody?: string | null;\n }\n ) {\n super(message);\n this.name = 'APIError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = options?.details ?? null;\n this.requestId = options?.requestId ?? null;\n this.rawBody = options?.rawBody ?? null;\n this.retryable = RETRYABLE_STATUS_CODES.has(statusCode);\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, APIError);\n }\n }\n\n /**\n * Create an APIError from an HTTP response.\n */\n static async fromResponse(response: Response): Promise<APIError> {\n const requestId = response.headers.get('x-request-id');\n let rawBody: string | null = null;\n let code = `http_${response.status}`;\n let message = response.statusText || 'Unknown error';\n let details: Record<string, unknown> | null = null;\n\n try {\n rawBody = await response.text();\n const parsed = JSON.parse(rawBody);\n\n // Try ProblemDetails format (RFC 7807)\n if (parsed.type && typeof parsed.type === 'string') {\n // Extract code from type URI fragment (e.g., \"...#invalid-request\")\n const hashIndex = parsed.type.lastIndexOf('#');\n if (hashIndex !== -1) {\n code = parsed.type.substring(hashIndex + 1);\n }\n }\n\n // Use code if directly provided\n if (parsed.code) {\n code = parsed.code;\n }\n\n // Build message from title and detail\n if (parsed.title) {\n message = parsed.title;\n if (parsed.detail) {\n message = `${parsed.title}: ${parsed.detail}`;\n }\n } else if (parsed.message) {\n message = parsed.message;\n } else if (parsed.detail) {\n message = parsed.detail;\n }\n\n // Extract details\n if (parsed.details && typeof parsed.details === 'object') {\n details = parsed.details;\n }\n } catch {\n // Failed to parse JSON, use defaults\n }\n\n return new APIError(response.status, code, message, {\n details,\n requestId,\n rawBody,\n });\n }\n\n override toString(): string {\n if (this.code) {\n return `APIError [${this.statusCode} ${this.code}]: ${this.message}`;\n }\n return `APIError [${this.statusCode}]: ${this.message}`;\n }\n}\n\n/**\n * Represents a transport-level error (network, timeout, etc.).\n */\nexport class TransportError extends Error {\n /** The underlying error that caused this transport error */\n readonly cause: Error | undefined;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'TransportError';\n this.cause = cause;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TransportError);\n }\n }\n\n override toString(): string {\n if (this.cause) {\n return `TransportError: ${this.message} (caused by: ${this.cause.message})`;\n }\n return `TransportError: ${this.message}`;\n }\n}\n\n/**\n * Represents a configuration error.\n */\nexport class ConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigurationError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ConfigurationError);\n }\n }\n}\n","/**\n * Configuration types and validation for Dakota SDK.\n */\n\nimport { Environment, getEnvironmentURL } from './environment.js';\nimport { ConfigurationError } from './errors.js';\n\n/**\n * Authentication mode for API requests.\n */\nexport enum AuthMode {\n /** Automatically select the best auth method based on the endpoint */\n Auto = 'auto',\n /** Always use x-api-key header */\n APIKey = 'api_key',\n /** Always use X-Application-Token header */\n ApplicationToken = 'application_token',\n}\n\n/**\n * Retry policy configuration.\n */\nexport interface RetryPolicy {\n /** Maximum number of attempts including the initial request (default: 3) */\n maxAttempts: number;\n /** Initial backoff delay in milliseconds (default: 200) */\n initialBackoffMs: number;\n /** Maximum backoff delay in milliseconds (default: 2000) */\n maxBackoffMs: number;\n}\n\n/**\n * Logger interface for SDK logging.\n */\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Configuration options for DakotaClient.\n */\nexport interface DakotaClientConfig {\n /** API key for authentication (required unless applicationToken is provided) */\n apiKey?: string;\n /** Application token for authentication (alternative to apiKey) */\n applicationToken?: string;\n /** Target environment (default: Sandbox) */\n environment?: Environment;\n /** Override the base URL (takes precedence over environment) */\n baseURL?: string;\n /** Authentication mode (default: Auto) */\n authMode?: AuthMode;\n /**\n * Request timeout in milliseconds (default: 15000).\n *\n * Setting this explicitly applies it to EVERY request, including the\n * model-backed agentic endpoints that otherwise get a longer default\n * ({@link AGENTIC_MODEL_TIMEOUT_MS}) — so you keep full control, but a\n * global value tuned for fast reads will also cap agent turns. To keep\n * the long agentic default while tightening everything else, leave this\n * unset and pass `{ timeout }` per request instead.\n *\n * Note this is a per-ATTEMPT deadline: with the default retry policy a\n * timing-out request can be attempted up to `retryPolicy.maxAttempts`\n * times, so worst-case wall clock is roughly `timeout × maxAttempts`.\n */\n timeout?: number;\n /** Retry policy configuration */\n retryPolicy?: Partial<RetryPolicy>;\n /** Logger instance */\n logger?: Logger;\n /** Automatically generate idempotency keys for POST requests (default: true) */\n automaticIdempotency?: boolean;\n /** Custom idempotency key generator */\n idempotencyKeyGenerator?: () => string;\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n}\n\n/**\n * Resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n apiKey: string | null;\n applicationToken: string | null;\n baseURL: string;\n authMode: AuthMode;\n timeout: number;\n /**\n * Whether `timeout` came from the caller rather than the default.\n *\n * An explicit timeout is a deliberate choice and wins everywhere. An\n * inherited default does not, so endpoints that know they are slow (the\n * model-backed agentic ones) can raise it without overriding a value the\n * caller actually asked for.\n */\n timeoutWasExplicit: boolean;\n retryPolicy: RetryPolicy;\n logger: Logger;\n automaticIdempotency: boolean;\n idempotencyKeyGenerator: () => string;\n fetch: typeof fetch;\n}\n\n/**\n * Default per-request timeout (ms).\n *\n * Sized for ordinary CRUD reads and writes, which answer in well under a\n * second. It is deliberately NOT the deadline for the agentic endpoints\n * that call a model — see {@link AGENTIC_MODEL_TIMEOUT_MS}.\n */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Default per-request timeout (ms) for the agentic endpoints whose work is\n * a sequence of model calls: drafting proposals and insight chat.\n *\n * A multi-payee drafting turn (\"pay these nine vendors every Friday\")\n * legitimately runs minutes — it reads payees, checks balances, drafts, and\n * revises, each a separate model round. Under the ordinary 15s deadline\n * those turns abort client-side while the server is still working, which\n * reads as flakiness rather than as a deadline: the simple turns finish in\n * time and the complex ones do not.\n *\n * Applies only when the caller did not set `timeout` on the client (an\n * explicit choice always wins) and can be overridden per request.\n */\nexport const AGENTIC_MODEL_TIMEOUT_MS = 180_000;\n\n/**\n * Default retry policy.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialBackoffMs: 200,\n maxBackoffMs: 2000,\n};\n\n/**\n * No-op logger that discards all messages.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for development.\n */\nexport const consoleLogger: Logger = {\n debug: (msg, ...args) => console.debug(`[Dakota SDK] ${msg}`, ...args),\n info: (msg, ...args) => console.info(`[Dakota SDK] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[Dakota SDK] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[Dakota SDK] ${msg}`, ...args),\n};\n\n/**\n * Generate a UUID v4 for idempotency keys.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Validate and resolve configuration with defaults.\n */\nexport function resolveConfig(config: DakotaClientConfig): ResolvedConfig {\n const authMode = config.authMode ?? AuthMode.Auto;\n\n // Validate authentication\n if (authMode === AuthMode.Auto) {\n if (!config.apiKey && !config.applicationToken) {\n throw new ConfigurationError('API key or application token is required');\n }\n } else if (authMode === AuthMode.APIKey) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required when using AuthMode.APIKey');\n }\n } else if (authMode === AuthMode.ApplicationToken) {\n if (!config.applicationToken) {\n throw new ConfigurationError(\n 'Application token is required when using AuthMode.ApplicationToken'\n );\n }\n }\n\n // Resolve base URL\n let baseURL: string;\n if (config.baseURL) {\n baseURL = config.baseURL.replace(/\\/$/, ''); // Remove trailing slash\n // Validate URL\n try {\n new URL(baseURL);\n } catch {\n throw new ConfigurationError('Invalid base URL');\n }\n } else {\n const env = config.environment ?? Environment.Sandbox;\n baseURL = getEnvironmentURL(env);\n }\n\n // Validate timeout\n const timeoutWasExplicit = config.timeout !== undefined;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n if (timeout <= 0) {\n throw new ConfigurationError('Timeout must be greater than zero');\n }\n\n // Resolve retry policy\n const retryPolicy: RetryPolicy = {\n maxAttempts: config.retryPolicy?.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n initialBackoffMs: config.retryPolicy?.initialBackoffMs ?? DEFAULT_RETRY_POLICY.initialBackoffMs,\n maxBackoffMs: config.retryPolicy?.maxBackoffMs ?? DEFAULT_RETRY_POLICY.maxBackoffMs,\n };\n\n // Validate retry policy\n if (retryPolicy.maxAttempts <= 0) {\n throw new ConfigurationError('Retry max attempts must be greater than zero');\n }\n if (retryPolicy.initialBackoffMs <= 0) {\n throw new ConfigurationError('Retry initial backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs <= 0) {\n throw new ConfigurationError('Retry max backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs < retryPolicy.initialBackoffMs) {\n throw new ConfigurationError('Retry max backoff must be >= initial backoff');\n }\n\n return {\n apiKey: config.apiKey ?? null,\n applicationToken: config.applicationToken ?? null,\n baseURL,\n authMode,\n timeout,\n timeoutWasExplicit,\n retryPolicy,\n logger: config.logger ?? noopLogger,\n automaticIdempotency: config.automaticIdempotency ?? true,\n idempotencyKeyGenerator: config.idempotencyKeyGenerator ?? generateUUID,\n fetch: config.fetch ?? globalThis.fetch,\n };\n}\n","/**\n * HTTP transport layer with retry, authentication, and idempotency.\n */\n\nimport { ResolvedConfig, AuthMode } from './config.js';\nimport { APIError, TransportError } from './errors.js';\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/** HTTP methods that are safe to retry without idempotency key */\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n\n/**\n * HTTP methods that accept an idempotency key. Dakota's spec marks\n * `IdempotencyKeyHeader` as required on every mutating endpoint, so the\n * SDK must forward it for POST, PUT, PATCH, and DELETE. Earlier versions\n * only attached the header on POST and silently dropped it on PUT/PATCH.\n * DELETE is included because the platform's agentic detach endpoints\n * (e.g. DELETE /signer-groups/{id}/signers/{signer_id}) 400 without one.\n */\nconst IDEMPOTENT_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Request options for the transport layer.\n */\nexport interface TransportRequestOptions {\n method: string;\n path: string;\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n signal?: AbortSignal;\n /**\n * Caller-supplied deadline (ms) for this one request. Beats everything —\n * it is the most specific statement of intent available.\n */\n timeout?: number;\n /**\n * The deadline (ms) this ENDPOINT wants when nobody has said otherwise —\n * how long its work actually takes. Used only when the caller passed no\n * per-request timeout AND set no explicit client-wide one, so it can\n * never override a deadline someone deliberately chose.\n */\n endpointTimeout?: number;\n}\n\n/**\n * HTTP transport with retry, auth, and idempotency support.\n */\nexport class Transport {\n private readonly config: ResolvedConfig;\n\n constructor(config: ResolvedConfig) {\n this.config = config;\n }\n\n /**\n * Make an HTTP request with automatic retry and error handling.\n */\n async request<T>(options: TransportRequestOptions): Promise<T> {\n const { method, path, body, query, headers, idempotencyKey, signal } = options;\n\n // Build URL with query parameters\n const url = this.buildURL(path, query);\n\n // Build headers\n const requestHeaders = this.buildHeaders(method, path, headers, idempotencyKey);\n\n // Build request body\n const requestBody = body !== undefined ? JSON.stringify(body) : undefined;\n\n // Execute with retry\n return this.executeWithRetry<T>(\n url,\n {\n method,\n headers: requestHeaders,\n body: requestBody,\n signal,\n },\n this.resolveTimeout(options)\n );\n }\n\n /**\n * Build the full URL with query parameters.\n */\n private buildURL(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): string {\n const url = new URL(path, this.config.baseURL);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n }\n\n /**\n * Build request headers with authentication.\n */\n private buildHeaders(\n method: string,\n path: string,\n customHeaders?: Record<string, string>,\n idempotencyKey?: string\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': 'dakota-ts-sdk/1.0.0',\n ...customHeaders,\n };\n\n // Add authentication header\n this.addAuthHeader(headers, path);\n\n // Add idempotency key for mutating requests (POST, PUT, PATCH).\n if (IDEMPOTENT_METHODS.has(method)) {\n const key =\n idempotencyKey ??\n (this.config.automaticIdempotency ? this.config.idempotencyKeyGenerator() : undefined);\n if (key) {\n headers['x-idempotency-key'] = key;\n }\n }\n\n return headers;\n }\n\n /**\n * Add authentication header based on auth mode and path.\n */\n private addAuthHeader(headers: Record<string, string>, path: string): void {\n // Don't override existing auth headers\n if (headers['x-api-key'] || headers['x-application-token']) {\n return;\n }\n\n const { authMode, apiKey, applicationToken } = this.config;\n\n switch (authMode) {\n case AuthMode.APIKey:\n if (apiKey) {\n headers['x-api-key'] = apiKey;\n }\n break;\n\n case AuthMode.ApplicationToken:\n if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n\n case AuthMode.Auto:\n default:\n // For /applications routes, prefer application token\n if (path.startsWith('/applications') && applicationToken) {\n headers['x-application-token'] = applicationToken;\n } else if (apiKey) {\n headers['x-api-key'] = apiKey;\n } else if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n }\n }\n\n /**\n * Resolve the deadline for one request, most specific intent first:\n *\n * 1. the caller's per-request `timeout`\n * 2. an explicit client-wide `timeout`\n * 3. the endpoint's own default (slow endpoints raise their own)\n * 4. the client-wide default\n *\n * (2) sits above (3) on purpose: a caller who configured a timeout chose\n * it, and an endpoint must not quietly overrule that. (3) exists so the\n * far more common caller — the one who configured nothing — gets a\n * deadline that matches what the endpoint actually does.\n */\n private resolveTimeout(options: TransportRequestOptions): number {\n if (options.timeout !== undefined) {\n return options.timeout;\n }\n if (this.config.timeoutWasExplicit) {\n return this.config.timeout;\n }\n return options.endpointTimeout ?? this.config.timeout;\n }\n\n /**\n * Execute request with exponential backoff retry.\n *\n * `timeout` is per ATTEMPT, not per call: each attempt gets its own\n * deadline, so a request that keeps timing out can take up to\n * `timeout × maxAttempts` before it throws.\n */\n private async executeWithRetry<T>(url: string, init: RequestInit, timeout: number): Promise<T> {\n const { maxAttempts, initialBackoffMs, maxBackoffMs } = this.config.retryPolicy;\n const method = init.method ?? 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Declared outside the try so the catch can tell OUR deadline firing\n // apart from the caller aborting.\n let timedOut = false;\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n\n // Merge signals if provided\n const signal = init.signal\n ? this.mergeAbortSignals(init.signal, controller.signal)\n : controller.signal;\n\n this.logRequest(method, url, attempt);\n\n const response = await this.config.fetch(url, {\n ...init,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n this.logResponse(method, url, response.status, attempt);\n\n // Check for successful response\n if (response.ok) {\n // Handle 204 No Content\n if (response.status === 204) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n // Convert to API error\n const apiError = await APIError.fromResponse(response);\n\n // Check if we should retry\n if (this.shouldRetry(response.status, method, init, attempt)) {\n lastError = apiError;\n const delay = this.calculateBackoff(attempt, response, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Request failed with ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw apiError;\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Handle abort/timeout. Only OUR deadline firing is a timeout — an\n // AbortError from the caller's own signal is a cancellation, and\n // reporting that as \"timed out\" sends people hunting a deadline\n // that never elapsed.\n if (error instanceof Error && error.name === 'AbortError' && timedOut) {\n lastError = new TransportError(\n `Request timed out after ${timeout}ms. ` +\n `This is the SDK's client-side deadline, not a server error — raise it with ` +\n `\\`new DakotaClient({ timeout })\\`, or per call with \\`{ timeout }\\` in the ` +\n `request options. Agent conversations are the usual cause: pass ` +\n `\\`{ timeout }\\` to \\`newAgentConversation\\`.`,\n error\n );\n } else if (error instanceof Error && error.name === 'AbortError') {\n // The caller cancelled. Retrying would re-issue a request they\n // explicitly called off, so this is terminal.\n throw new TransportError('Request aborted by caller', error);\n } else if (error instanceof Error) {\n lastError = new TransportError('Network error', error);\n } else {\n lastError = new TransportError('Unknown error');\n }\n\n // Retry on network errors for safe methods\n if (this.shouldRetryNetworkError(method, init, attempt)) {\n const delay = this.calculateBackoff(attempt, null, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Network error, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw lastError;\n }\n }\n\n // All retries exhausted\n throw lastError ?? new TransportError('Request failed after all retries');\n }\n\n /**\n * Determine if a request should be retried based on status code.\n */\n private shouldRetry(status: number, method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n if (!RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key. PUT/PATCH are already in SAFE_METHODS so they hit\n // the branch above; this catches POST.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Determine if a network error should be retried.\n */\n private shouldRetryNetworkError(method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Calculate backoff delay with jitter.\n */\n private calculateBackoff(\n attempt: number,\n response: Response | null,\n initialBackoffMs: number,\n maxBackoffMs: number\n ): number {\n // Check for Retry-After header\n if (response) {\n const retryAfter = response.headers.get('retry-after');\n if (retryAfter) {\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds)) {\n return seconds * 1000;\n }\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n return Math.max(0, date - Date.now());\n }\n }\n }\n\n // Exponential backoff with jitter (±20%)\n const exponentialDelay = initialBackoffMs * Math.pow(2, attempt - 1);\n const cappedDelay = Math.min(exponentialDelay, maxBackoffMs);\n const jitter = cappedDelay * 0.2 * (Math.random() * 2 - 1);\n return Math.round(cappedDelay + jitter);\n }\n\n /**\n * Merge multiple abort signals.\n */\n private mergeAbortSignals(signal1: AbortSignal, signal2: AbortSignal): AbortSignal {\n const controller = new AbortController();\n\n const abort = () => controller.abort();\n\n signal1.addEventListener('abort', abort);\n signal2.addEventListener('abort', abort);\n\n if (signal1.aborted || signal2.aborted) {\n controller.abort();\n }\n\n return controller.signal;\n }\n\n /**\n * Sleep for the specified duration.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Log outgoing request.\n */\n private logRequest(method: string, url: string, attempt: number): void {\n this.config.logger.debug(\n `Request: ${method} ${url}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n\n /**\n * Log response.\n */\n private logResponse(method: string, url: string, status: number, attempt: number): void {\n this.config.logger.debug(\n `Response: ${method} ${url} -> ${status}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n}\n","/**\n * Pagination utilities with async iterators.\n */\n\n/**\n * Pagination metadata from API responses.\n */\nexport interface PaginationMeta {\n total_count?: number;\n has_more_after?: boolean;\n has_more_before?: boolean;\n}\n\n/**\n * Paginated response structure.\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n meta?: PaginationMeta;\n}\n\n/**\n * Parameters for paginated requests.\n */\nexport interface PaginationParams {\n starting_after?: string;\n ending_before?: string;\n limit?: number;\n}\n\n/**\n * Function to fetch a page of results.\n */\nexport type PageFetcher<T> = (cursor?: string) => Promise<PaginatedResponse<T>>;\n\n/**\n * Function to extract cursor from an item.\n */\nexport type CursorExtractor<T> = (item: T) => string;\n\n/**\n * Default cursor extractor that uses the 'id' field.\n */\nexport function defaultCursorExtractor<T extends { id?: string }>(item: T): string {\n if (!item.id) {\n throw new Error('Item does not have an id field for cursor extraction');\n }\n return item.id;\n}\n\n/**\n * Async iterator for paginated results.\n */\nexport class PaginatedIterator<T> implements AsyncIterable<T> {\n private readonly fetcher: PageFetcher<T>;\n private readonly cursorExtractor: CursorExtractor<T>;\n private cursor: string | undefined;\n private buffer: T[] = [];\n private hasMore = true;\n private started = false;\n\n constructor(fetcher: PageFetcher<T>, cursorExtractor?: CursorExtractor<T>) {\n this.fetcher = fetcher;\n this.cursorExtractor = cursorExtractor ?? (defaultCursorExtractor as CursorExtractor<T>);\n }\n\n /**\n * Implement async iterator protocol.\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: async (): Promise<IteratorResult<T>> => {\n const item = await this.next();\n if (item === null) {\n return { done: true, value: undefined };\n }\n return { done: false, value: item };\n },\n };\n }\n\n /**\n * Get the next item, or null if no more items.\n */\n async next(): Promise<T | null> {\n // If buffer has items, return next one\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n // If no more pages, we're done\n if (!this.hasMore && this.started) {\n return null;\n }\n\n // Fetch next page\n await this.fetchNextPage();\n\n // Return first item from buffer, or null if empty\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n return null;\n }\n\n /**\n * Collect all items into an array.\n */\n async toArray(): Promise<T[]> {\n const items: T[] = [];\n for await (const item of this) {\n items.push(item);\n }\n return items;\n }\n\n /**\n * Get the first item, or null if none.\n */\n async first(): Promise<T | null> {\n return this.next();\n }\n\n /**\n * Fetch the next page of results.\n */\n private async fetchNextPage(): Promise<void> {\n this.started = true;\n\n const response = await this.fetcher(this.cursor);\n this.buffer = response.data ?? [];\n\n // Update cursor for next page\n if (this.buffer.length > 0) {\n const lastItem = this.buffer[this.buffer.length - 1];\n if (lastItem) {\n this.cursor = this.cursorExtractor(lastItem);\n }\n }\n\n // Check if there are more pages\n this.hasMore = response.meta?.has_more_after ?? false;\n }\n}\n\n/**\n * Create a paginated iterator.\n */\nexport function paginate<T>(\n fetcher: PageFetcher<T>,\n cursorExtractor?: CursorExtractor<T>\n): PaginatedIterator<T> {\n return new PaginatedIterator(fetcher, cursorExtractor);\n}\n","/**\n * Base resource class for API resources.\n */\n\nimport { Transport } from '../transport.js';\nimport { PaginatedIterator, paginate, PageFetcher, CursorExtractor } from '../pagination.js';\n\n/**\n * Base class for API resources.\n */\nexport abstract class BaseResource {\n protected readonly transport: Transport;\n\n constructor(transport: Transport) {\n this.transport = transport;\n }\n\n /**\n * Create a paginated iterator for a list endpoint.\n */\n protected paginate<T>(\n path: string,\n params?: Record<string, unknown>,\n cursorExtractor?: CursorExtractor<T>\n ): PaginatedIterator<T> {\n const fetcher: PageFetcher<T> = async (cursor?: string) => {\n const query: Record<string, string | number | boolean | undefined> = {};\n\n // Add pagination params\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n\n if (cursor) {\n query.starting_after = cursor;\n }\n\n const response = await this.transport.request<\n | {\n data: T[];\n meta?: { has_more_after?: boolean };\n }\n | T[]\n >({\n method: 'GET',\n path,\n query,\n });\n\n // Not every list endpoint returns the `{data, meta}` envelope: a few\n // answer with a BARE ARRAY (GET /mandates and\n // GET /wallets/{id}/signer-groups today). Reading `.data` off those\n // yields undefined, which the old code turned into an empty page —\n // so the iterator finished immediately and the caller saw zero\n // results with no error, for records that plainly exist. Treat an\n // array as one complete page: there is no cursor to follow, so\n // `meta` is absent and `has_more_after` correctly reads false.\n if (Array.isArray(response)) {\n return { data: response, meta: undefined };\n }\n\n return {\n data: response.data ?? [],\n meta: response.meta,\n };\n };\n\n return paginate(fetcher, cursorExtractor);\n }\n}\n","/**\n * Customers resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n BulkImportSumsubTokensRequest,\n BulkImportSumsubTokensResponse,\n Customer,\n CustomerCapabilities,\n CustomerCreateRequest,\n CustomerCreateResponse,\n CustomerListParams,\n CustomerReEngagementResponse,\n ImportPersonaTokensRequest,\n ImportPersonaTokensResponse,\n PersonaImportJob,\n PersonaImportJobListParams,\n PersonaImportJobParams,\n PersonaImportJobsPage,\n RequestOptions,\n SubClientSummary,\n UpdateCustomerSubClientRequest,\n} from '../types.js';\n\n/**\n * Customers API resource.\n */\nexport class CustomersResource extends BaseResource {\n /**\n * Create a new customer.\n *\n * Creates a customer record and initiates KYB onboarding.\n * Returns a URL where the customer can complete verification.\n *\n * @param data - Customer creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created customer with KYB onboarding URL\n *\n * @example\n * ```typescript\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customerType: 'business',\n * externalId: 'your-internal-id',\n * });\n *\n * // With custom idempotency key\n * const customer = await client.customers.create(\n * { name: 'Acme Corp', customerType: 'business' },\n * { idempotencyKey: 'create-acme-corp-001' }\n * );\n * console.log(customer.applicationUrl); // KYB onboarding URL\n *\n * // Designate as a sub-client at creation (ENG-2454).\n * // `is_sub_client` can only be set here — a regular customer cannot\n * // be promoted afterwards. Cannot be combined with `sub_client_id`.\n * const subClient = await client.customers.create({\n * name: 'Partner Corp',\n * customer_type: 'business',\n * is_sub_client: true,\n * });\n * ```\n */\n async create(\n data: CustomerCreateRequest,\n options?: RequestOptions\n ): Promise<CustomerCreateResponse> {\n return this.transport.request<CustomerCreateResponse>({\n method: 'POST',\n path: '/customers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List all customers.\n *\n * Returns a paginated async iterator over customer records.\n *\n * @param params - Optional filter and pagination parameters\n * @returns Async iterator of customers\n *\n * @example\n * ```typescript\n * // Iterate through all customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // With filters\n * const active = client.customers.list({ kyb_status: 'active' });\n *\n * // Collect all to array\n * const all = await client.customers.list().toArray();\n * ```\n */\n list(params?: CustomerListParams): PaginatedIterator<Customer> {\n return this.paginate<Customer>('/customers', params);\n }\n\n /**\n * Get a customer by ID.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns Customer record\n *\n * @example\n * ```typescript\n * const customer = await client.customers.get('cust_abc123');\n * console.log(customer.kybStatus);\n * ```\n */\n async get(customerId: string): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'GET',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * Delete a customer record.\n *\n * Soft-deletes the customer. Blocked with a 409 if the customer still has\n * associated accounts, or is referenced as a sub-client by another customer.\n *\n * @param customerId - Customer ID (KSUID)\n *\n * @example\n * ```typescript\n * await client.customers.delete('cust_abc123');\n * ```\n */\n async delete(customerId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * List a customer's capabilities and what is still needed to unlock each.\n *\n * Returns the customer's rails (e.g. `international_wire`) with a status and\n * the OUTSTANDING requirements — terms to accept, documents to upload — that\n * gate them. Partner-agnostic: requirements are keyed by an opaque terms id\n * or document type, never a provider or partner name.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns The customer's capabilities and their outstanding requirements\n *\n * @example\n * ```typescript\n * const { capabilities } = await client.customers.getCapabilities(customerId);\n * for (const cap of capabilities) {\n * if (cap.status !== 'action_required') continue;\n * for (const req of cap.requirements) {\n * console.log(`${cap.capability}: ${req.title} → ${req.url}`);\n * }\n * }\n * ```\n */\n async getCapabilities(customerId: string): Promise<CustomerCapabilities> {\n return this.transport.request<CustomerCapabilities>({\n method: 'GET',\n path: `/customers/${customerId}/capabilities`,\n });\n }\n\n /**\n * Mint a fresh application link for re-engaging an APPROVED customer.\n *\n * Issues a new onboarding token for an existing approved customer's\n * application and returns the rebuilt `application_url` — use it when the\n * original token has expired and the customer needs to come back through\n * the hosted flow (e.g. to accept outstanding partner disclosures).\n *\n * @param customerId - Customer ID (KSUID)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The rebuilt application URL\n *\n * @example\n * ```typescript\n * const { application_url } = await client.customers.reEngage(customerId);\n * ```\n */\n async reEngage(\n customerId: string,\n options?: RequestOptions\n ): Promise<CustomerReEngagementResponse> {\n return this.transport.request<CustomerReEngagementResponse>({\n method: 'POST',\n path: `/customers/${customerId}/re-engagement`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update the sub-client association for a customer.\n *\n * Associates or disassociates a customer with a sub-client.\n * Set `sub_client_id` to associate, or set it to `null` to disassociate.\n *\n * @deprecated The sub-client association can only be set when a customer is\n * created (`is_sub_client` / `sub_client_id` on `create`) and can no longer\n * be changed afterwards — this endpoint now returns 400.\n *\n * @param customerId - Customer ID (KSUID)\n * @param data - Sub-client association data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Updated customer record\n *\n * @example\n * ```typescript\n * // Associate customer with a sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: 'cust_sub456',\n * });\n *\n * // Disassociate customer from sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: null,\n * });\n * ```\n */\n async updateSubClient(\n customerId: string,\n data: UpdateCustomerSubClientRequest,\n options?: RequestOptions\n ): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'PATCH',\n path: `/customers/${customerId}/sub-client`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a summary of all sub-clients and their associated customer counts.\n *\n * @returns Array of sub-client summaries\n *\n * @example\n * ```typescript\n * const summaries = await client.customers.getSubClientSummary();\n * for (const summary of summaries) {\n * console.log(`${summary.sub_client_name}: ${summary.customer_count} customers`);\n * }\n * ```\n */\n async getSubClientSummary(): Promise<SubClientSummary[]> {\n const response = await this.transport.request<{ data: SubClientSummary[] }>({\n method: 'GET',\n path: '/customers/sub-client-summary',\n });\n return response.data;\n }\n\n /**\n * Bulk-import customers from Sumsub share tokens.\n *\n * Exchanges one or more Sumsub share tokens for Dakota customers + applications.\n * The response surfaces per-token results — individual tokens can fail while\n * others succeed.\n *\n * @param data - Bulk-import request containing the share tokens to redeem\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Bulk-import summary with per-token results\n *\n * @example\n * ```typescript\n * const result = await client.customers.bulkImportFromSumsubTokens({\n * tokens: ['_act-sbx-jwt-...', '_act-sbx-jwt-...'],\n * });\n * console.log(`Imported ${result.succeeded}/${result.total}`);\n * for (const r of result.results ?? []) {\n * if (!r.success) console.error(r.name, r.error);\n * }\n * ```\n */\n async bulkImportFromSumsubTokens(\n data: BulkImportSumsubTokensRequest,\n options?: RequestOptions\n ): Promise<BulkImportSumsubTokensResponse> {\n return this.transport.request<BulkImportSumsubTokensResponse>({\n method: 'POST',\n path: '/customers/bulk-import-sumsub-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Import customers from Persona Connect share tokens (`cnst_...`).\n *\n * Unlike the Sumsub import, Persona redemption is asynchronous on Persona's\n * side, so this returns a JOB immediately (HTTP 202). Poll\n * `getPersonaImportJob` for per-token results. Up to 5,000 tokens per\n * request — split larger migrations into multiple batches.\n *\n * Tokens are validated and de-duplicated up front, and a skipped token\n * never blocks an accepted one. A `skipped` entry is about the token STRING\n * (malformed, duplicated in the batch, or already imported) — it is never a\n * compliance decision about a person or application.\n *\n * @param data - The share tokens to import\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The queued job, with any tokens that could not be enqueued\n *\n * @example\n * ```typescript\n * const job = await client.customers.importPersonaTokens({\n * tokens: ['cnst_ABC123def456', 'cnst_GHI789jkl012'],\n * });\n * console.log(`${job.accepted}/${job.total} queued as ${job.job_id}`);\n * ```\n */\n async importPersonaTokens(\n data: ImportPersonaTokensRequest,\n options?: RequestOptions\n ): Promise<ImportPersonaTokensResponse> {\n return this.transport.request<ImportPersonaTokensResponse>({\n method: 'POST',\n path: '/customers/import-persona-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List this client's Persona share-token import jobs, newest first.\n *\n * This endpoint pages on its own cursor (`starting_after` + `has_more`), not\n * the standard list envelope, so it returns a single page rather than an\n * async iterator.\n *\n * @param params - Optional `limit` and `starting_after` job-id cursor\n * @returns One page of job summaries plus a `has_more` flag\n *\n * @example\n * ```typescript\n * const { jobs, has_more } = await client.customers.listPersonaImportJobs({ limit: 20 });\n * ```\n */\n async listPersonaImportJobs(params?: PersonaImportJobListParams): Promise<PersonaImportJobsPage> {\n return this.transport.request<PersonaImportJobsPage>({\n method: 'GET',\n path: '/customers/persona-import-jobs',\n query: { ...params },\n });\n }\n\n /**\n * Get a Persona import job's status and its per-token results.\n *\n * Result rows page on a row-index cursor: pass the last row's `index` as\n * `results_after_index` while `has_more_results` is true.\n *\n * @param jobId - Import job ID (`pij_...`)\n * @param params - Optional `results_limit` (1-500) and `results_after_index`\n * @returns Job status, row counts, and one page of result rows\n *\n * @example\n * ```typescript\n * let after: number | undefined;\n * do {\n * const job = await client.customers.getPersonaImportJob(jobId, {\n * results_after_index: after,\n * });\n * for (const row of job.results ?? []) {\n * if (row.state === 'failed') console.error(row.token, row.error);\n * after = row.index;\n * }\n * if (!job.has_more_results) break;\n * } while (true);\n * ```\n */\n async getPersonaImportJob(\n jobId: string,\n params?: PersonaImportJobParams\n ): Promise<PersonaImportJob> {\n return this.transport.request<PersonaImportJob>({\n method: 'GET',\n path: `/customers/persona-import-jobs/${jobId}`,\n query: { ...params },\n });\n }\n}\n","/**\n * Recipients resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Recipient,\n RecipientRequest,\n RecipientUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Recipients API resource.\n */\nexport class RecipientsResource extends BaseResource {\n /**\n * Create a new recipient for a customer.\n *\n * Recipients represent entities that can receive payments.\n *\n * @param customerId - Customer ID\n * @param data - Recipient creation data\n * @returns Created recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.create(customerId, {\n * name: 'Treasury Account',\n * });\n * ```\n */\n async create(\n customerId: string,\n data: RecipientRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'POST',\n path: `/customers/${customerId}/recipients`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List recipients for a customer.\n *\n * @param customerId - Customer ID\n * @param params - Pagination parameters\n * @returns Async iterator of recipients\n *\n * @example\n * ```typescript\n * for await (const recipient of client.recipients.list(customerId)) {\n * console.log(recipient.name);\n * }\n * ```\n */\n list(customerId: string, params?: ListParams): PaginatedIterator<Recipient> {\n return this.paginate<Recipient>(`/customers/${customerId}/recipients`, params);\n }\n\n /**\n * Get a recipient by ID.\n *\n * @param recipientId - Recipient ID\n * @returns Recipient record\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.get(recipientId);\n * ```\n */\n async get(recipientId: string): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'GET',\n path: `/recipients/${recipientId}`,\n });\n }\n\n /**\n * Update a recipient.\n *\n * @param recipientId - Recipient ID\n * @param data - Update data\n * @returns Updated recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.update(recipientId, {\n * name: 'Updated Name',\n * });\n * ```\n */\n async update(\n recipientId: string,\n data: RecipientUpdateRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'PUT',\n path: `/recipients/${recipientId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a recipient.\n *\n * @param recipientId - Recipient ID\n *\n * @example\n * ```typescript\n * await client.recipients.delete(recipientId);\n * ```\n */\n async delete(recipientId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}`,\n });\n }\n}\n","/**\n * Destinations resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Destination,\n DestinationCreateResponse,\n DestinationRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Destinations API resource.\n */\nexport class DestinationsResource extends BaseResource {\n /**\n * Create a new destination for a recipient.\n *\n * Destinations can be bank accounts (fiat_us / fiat_iban) or crypto\n * wallets (crypto).\n *\n * The platform returns just `{ id }` here (per `IDResponse`), not the\n * full destination object. Call `destinations.list(recipientId)` if\n * you need the rest of the fields.\n *\n * @param recipientId - Recipient ID\n * @param data - Destination creation data\n * @returns `{ id }` of the newly-created destination\n *\n * @example\n * ```typescript\n * // Crypto destination (for on-ramp)\n * const cryptoDest = await client.destinations.create(recipientId, {\n * destination_type: 'crypto',\n * name: 'Treasury USDC',\n * crypto_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f...',\n * network_id: 'ethereum-mainnet',\n * });\n * // → cryptoDest.id\n *\n * // Fiat US destination (for off-ramp)\n * const bankDest = await client.destinations.create(recipientId, {\n * destination_type: 'fiat_us',\n * name: 'Acme Chase Checking',\n * bank_name: 'JPMorgan Chase',\n * account_holder_name: 'Acme Corp',\n * account_number: '000123456789',\n * aba_routing_number: '021000021',\n * account_type: 'checking',\n * });\n * // → bankDest.id\n * ```\n */\n async create(\n recipientId: string,\n data: DestinationRequest,\n options?: RequestOptions\n ): Promise<DestinationCreateResponse> {\n return this.transport.request<DestinationCreateResponse>({\n method: 'POST',\n path: `/recipients/${recipientId}/destinations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List destinations for a recipient.\n *\n * @param recipientId - Recipient ID\n * @param params - Pagination parameters\n * @returns Async iterator of destinations\n *\n * @example\n * ```typescript\n * for await (const dest of client.destinations.list(recipientId)) {\n * console.log(dest);\n * }\n * ```\n */\n list(recipientId: string, params?: ListParams): PaginatedIterator<Destination> {\n return this.paginate<Destination>(\n `/recipients/${recipientId}/destinations`,\n params,\n (item) => item.destination_id\n );\n }\n\n /**\n * Delete a destination.\n *\n * @param recipientId - Recipient ID\n * @param destinationId - Destination ID\n *\n * @example\n * ```typescript\n * await client.destinations.delete(recipientId, destinationId);\n * ```\n */\n async delete(recipientId: string, destinationId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}/destinations/${destinationId}`,\n });\n }\n}\n","/**\n * Accounts resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Account,\n AccountCreateRequest,\n AccountUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/** Account list parameters */\nexport interface AccountListParams extends ListParams {\n /** Account type filter. Required by the API. */\n account_type: 'onramp' | 'offramp' | 'swap';\n customer_id?: string;\n source_network_id?: string;\n destination_network_id?: string;\n destination_asset?: string;\n crypto_destination_id?: string;\n fiat_destination_id?: string;\n}\n\n/**\n * Accounts API resource.\n */\nexport class AccountsResource extends BaseResource {\n /**\n * Create a new account.\n *\n * Accounts define the flow of funds:\n * - **onramp**: USD → crypto (customer sends USD, receives stablecoin)\n * - **offramp**: crypto → USD (customer sends stablecoin, receives USD)\n * - **swap**: crypto → crypto (stablecoin conversion)\n *\n * @param data - Account creation data\n * @returns Created account\n *\n * @example\n * ```typescript\n * // Create an off-ramp account (crypto → USD)\n * const offramp = await client.accounts.create({\n * account_type: 'offramp',\n * customer_id: customerId,\n * fiat_destination_id: bankDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { crypto_address: '0x...' } - customer sends USDC here\n *\n * // Create an on-ramp account (USD → crypto)\n * const onramp = await client.accounts.create({\n * account_type: 'onramp',\n * customer_id: customerId,\n * crypto_destination_id: cryptoDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { bank_account: { bank_name, aba_routing_number, account_number } } - customer sends USD here\n * ```\n *\n * @remarks\n * `max_transactions` caps how many transactions the account may ever\n * create — `1` makes it a one-off. Know what reaching the cap does before\n * you set one: further deposits are **refused, not returned**. The funds\n * still arrive and are then held pending manual intervention, with nothing\n * converted, nothing forwarded, and no transaction on the account for\n * them. Stop sending to the deposit details once the cap is reached.\n */\n async create(data: AccountCreateRequest, options?: RequestOptions): Promise<Account> {\n return this.transport.request<Account>({\n method: 'POST',\n path: '/accounts',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List accounts.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of accounts\n *\n * @example\n * ```typescript\n * // List all accounts\n * for await (const account of client.accounts.list()) {\n * console.log(account);\n * }\n *\n * // Filter by customer\n * const customerAccounts = client.accounts.list({ customer_id: customerId });\n * ```\n */\n list(params?: AccountListParams): PaginatedIterator<Account> {\n return this.paginate<Account>('/accounts', params);\n }\n\n /**\n * Get an account by ID.\n *\n * @param accountId - Account ID\n * @returns Account record\n *\n * @example\n * ```typescript\n * const account = await client.accounts.get(accountId);\n * ```\n */\n async get(accountId: string): Promise<Account> {\n return this.transport.request<Account>({\n method: 'GET',\n path: `/accounts/${accountId}`,\n });\n }\n\n /**\n * Update an account.\n *\n * @param accountId - Account ID\n * @param data - Update data\n * @returns Updated account\n *\n * @example\n * ```typescript\n * const account = await client.accounts.update(accountId, {\n * status: 'inactive',\n * });\n * ```\n */\n async update(\n accountId: string,\n data: AccountUpdateRequest,\n options?: RequestOptions\n ): Promise<Account> {\n return this.transport.request<Account>({\n method: 'PATCH',\n path: `/accounts/${accountId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an account.\n *\n * @param accountId - Account ID\n *\n * @example\n * ```typescript\n * await client.accounts.delete(accountId);\n * ```\n */\n async delete(accountId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/accounts/${accountId}`,\n });\n }\n}\n","/**\n * Transactions resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n OneOffTransaction,\n OneOffTransactionRequest,\n AutoTransaction,\n TransactionListParams,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Transactions API resource.\n */\nexport class TransactionsResource extends BaseResource {\n /**\n * Create a one-off transaction.\n *\n * One-off transactions allow single transfers without setting up accounts.\n *\n * @param data - Transaction creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.create({\n * customer_id: customerId,\n * amount: '1000.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-mainnet',\n * destination_id: destinationId,\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * payment_reference: 'Invoice #12345',\n * });\n *\n * // With custom idempotency key\n * const tx = await client.transactions.create(\n * { customer_id: customerId, amount: '1000.00', ... },\n * { idempotencyKey: 'invoice-12345-payment' }\n * );\n *\n * console.log(tx.crypto_address); // Send USDC here\n * console.log(tx.status); // Transaction status\n * ```\n */\n async create(\n data: OneOffTransactionRequest,\n options?: RequestOptions\n ): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: '/transactions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List one-off transactions.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of transactions\n *\n * @example\n * ```typescript\n * // List all transactions\n * for await (const tx of client.transactions.list()) {\n * console.log(tx.id, tx.status);\n * }\n *\n * // Filter by customer and status\n * const completed = client.transactions.list({\n * customer_id: customerId,\n * status: 'completed',\n * });\n *\n * // Wallet-scoped filters (require transaction_type: 'wallet')\n * const sent = client.transactions.list({\n * transaction_type: 'wallet',\n * wallet_id: walletId,\n * direction: 'out',\n * });\n * ```\n */\n list(params?: TransactionListParams): PaginatedIterator<OneOffTransaction> {\n return this.paginate<OneOffTransaction>('/transactions', params);\n }\n\n /**\n * Get a transaction by ID.\n *\n * @param transactionId - Transaction ID\n * @returns Transaction record\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.get(transactionId);\n * console.log(tx.status);\n * ```\n */\n async get(transactionId: string): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'GET',\n path: `/transactions/${transactionId}`,\n });\n }\n\n /**\n * Cancel a transaction.\n *\n * Only pending transactions can be cancelled.\n *\n * @param transactionId - Transaction ID\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Cancelled transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.cancel(transactionId);\n * console.log(tx.status); // 'cancelled'\n * ```\n */\n async cancel(transactionId: string, options?: RequestOptions): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: `/transactions/${transactionId}/cancellations`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n\n/**\n * Auto Transactions API resource.\n */\nexport class AutoTransactionsResource extends BaseResource {\n /**\n * List auto transactions.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of auto transactions\n */\n list(params?: ListParams): PaginatedIterator<AutoTransaction> {\n return this.paginate<AutoTransaction>('/auto-transactions', params);\n }\n\n /**\n * Get an auto transaction by ID.\n *\n * @param transactionId - Auto transaction ID\n * @returns Auto transaction record\n */\n async get(transactionId: string): Promise<AutoTransaction> {\n return this.transport.request<AutoTransaction>({\n method: 'GET',\n path: `/auto-transactions/${transactionId}`,\n });\n }\n}\n","/**\n * Wallets resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n Wallet,\n WalletCreateRequest,\n WalletBalances,\n WalletTransactionRequest,\n WalletTransaction,\n AttachedPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Wallets API resource.\n */\nexport class WalletsResource extends BaseResource {\n /**\n * Create a new wallet.\n *\n * Creates a non-custodial multi-sig wallet for a customer.\n *\n * @param data - Wallet creation data\n * @returns Created wallet\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.create({\n * customer_id: customerId,\n * family: 'evm',\n * name: 'Treasury Wallet',\n * });\n * console.log(wallet.address);\n * ```\n */\n async create(data: WalletCreateRequest, options?: RequestOptions): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'POST',\n path: '/wallets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a single wallet by ID.\n *\n * @param walletId - Wallet ID\n * @returns Wallet record (includes `customer_name` and `created_at`)\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.get(walletId);\n * console.log(wallet.address, wallet.customer_name);\n * ```\n */\n async get(walletId: string): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'GET',\n path: `/wallets/${walletId}`,\n });\n }\n\n /**\n * Get policies attached to a wallet.\n *\n * Returns slim references (id + name) for the policies currently attached to the wallet.\n *\n * @param walletId - Wallet ID\n * @returns Array of attached policies\n *\n * @example\n * ```typescript\n * const policies = await client.wallets.getPolicies(walletId);\n * for (const policy of policies) {\n * console.log(policy.id, policy.name);\n * }\n * ```\n */\n async getPolicies(walletId: string): Promise<AttachedPolicy[]> {\n return this.transport.request<AttachedPolicy[]>({\n method: 'GET',\n path: `/wallets/${walletId}/policies`,\n });\n }\n\n /**\n * Get wallet balances.\n *\n * Returns the platform's full `WalletBalances` response: the wallet id,\n * its on-chain address, every per-asset balance, and a pre-computed\n * `total_amount_usd` across all assets. The previous return shape\n * (`WalletBalance[]`) silently dropped `address` and `total_amount_usd`,\n * forcing callers to do a second `wallets.get()` and sum the balances\n * by hand. This is a small breaking change with a one-line migration\n * (`balances` → `balances.balances`); the prior shape had been broken\n * since 1.3.x anyway.\n *\n * @param walletId - Wallet ID\n * @returns `{ wallet_id, address, balances, total_amount_usd }`\n *\n * @example\n * ```typescript\n * const { address, total_amount_usd, balances } =\n * await client.wallets.getBalances(walletId);\n * console.log(`${address} → $${total_amount_usd}`);\n * for (const b of balances) {\n * console.log(b.asset.id, b.amount_usd);\n * }\n * ```\n */\n async getBalances(walletId: string): Promise<WalletBalances> {\n // /wallets/{id}/balances returns the WalletBalances object directly\n // ({ wallet_id, address, balances, total_amount_usd }), not the\n // paginated { data, meta } envelope. The 1.3.x impl read\n // response.data here and silently returned undefined; the 1.4.x /\n // 1.5.x impl returned just the balances array, dropping the wrapper\n // fields. Now we return what the platform actually sends.\n return this.transport.request<WalletBalances>({\n method: 'GET',\n path: `/wallets/${walletId}/balances`,\n });\n }\n\n /**\n * Send a transaction from a wallet.\n *\n * The platform expects an **endorsed request** envelope —\n * `{ signatures, intent }` — at this endpoint. Build the\n * `SendTransactionIntent`, canonicalize it per RFC 8785 (JCS), sign\n * with the wallet's signer-group ECDSA P-256 key, base64-encode the\n * DER signature, then post the envelope.\n *\n * @param walletId - Wallet ID\n * @param data - Endorsed wallet transaction request: `{ signatures, intent }`\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * import canonicalize from 'canonicalize';\n * import { createSign, createPrivateKey, randomUUID } from 'node:crypto';\n *\n * const intent = {\n * wallet_id: walletId,\n * caip2: 'eip155:1', // 11155111 for sepolia\n * operation: {\n * kind: 'transfer',\n * from: wallet.address,\n * to: '0x...',\n * amount: '100.00',\n * asset_id: 'USDC',\n * },\n * idempotency_key: randomUUID(),\n * };\n * const canonical = canonicalize(intent)!;\n * const sig = createSign('SHA256').update(canonical).sign({\n * key: createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' }),\n * dsaEncoding: 'der',\n * });\n * const tx = await client.wallets.createTransaction(walletId, {\n * signatures: [sig.toString('base64')],\n * intent,\n * });\n * ```\n *\n * @see https://docs.dakota.xyz/documentation/signing-guide\n */\n async createTransaction(\n walletId: string,\n data: WalletTransactionRequest,\n options?: RequestOptions\n ): Promise<WalletTransaction> {\n return this.transport.request<WalletTransaction>({\n method: 'POST',\n path: `/wallets/${walletId}/transactions`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Events resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type { Event, EventListParams } from '../types.js';\n\n/**\n * Events API resource.\n */\nexport class EventsResource extends BaseResource {\n /**\n * List events.\n *\n * Events track all platform activity and can be used for audit trails.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of events\n *\n * @example\n * ```typescript\n * for await (const event of client.events.list()) {\n * console.log(event.type, event.data);\n * }\n *\n * // Filter by event type\n * const customerEvents = client.events.list({\n * event_type: 'customer.created',\n * });\n * ```\n */\n list(params?: EventListParams): PaginatedIterator<Event> {\n return this.paginate<Event>('/events', params);\n }\n}\n","/**\n * Applications resource (Onboarding/KYB).\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Application,\n ApplicationDocumentUploadRequest,\n ApplicationDocumentUploadUrlRequest,\n ApplicationSubmissionRequest,\n AssociatedIndividual,\n AssociatedIndividualRequest,\n AttestationSubmitRequest,\n BusinessApplicationCreateRequest,\n BusinessDetailsResponse,\n DocumentUploadResponse,\n DocumentUploadUrlResponse,\n EDDRequest,\n EDDWithApplicationID,\n IndividualDetailsResponse,\n IndividualDocumentUploadRequest,\n IndividualDocumentUploadUrlRequest,\n IndividualRequest,\n ListParams,\n RequestOptions,\n UploadedDocumentMetadata,\n} from '../types.js';\n\n/** Parameters for listing application documents */\nexport interface DocumentListParams extends ListParams {\n category?: 'business' | 'identity' | 'edd';\n document_type?: string;\n}\n\n/**\n * Applications API resource for KYB onboarding.\n */\nexport class ApplicationsResource extends BaseResource {\n /**\n * List applications.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of applications\n */\n list(params?: ListParams): PaginatedIterator<Application> {\n return this.paginate<Application>('/applications', params);\n }\n\n /**\n * Get an application by ID.\n *\n * @param applicationId - Application ID\n * @returns Application record\n */\n async get(applicationId: string): Promise<Application> {\n return this.transport.request<Application>({\n method: 'GET',\n path: `/applications/${applicationId}`,\n });\n }\n\n /**\n * Submit an application for review.\n *\n * @param applicationId - Application ID\n * @param data - Submission data\n * @returns Submitted application\n */\n async submit(\n applicationId: string,\n data?: ApplicationSubmissionRequest,\n options?: RequestOptions\n ): Promise<Application> {\n return this.transport.request<Application>({\n method: 'POST',\n path: `/applications/${applicationId}/submissions`,\n body: data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Business Details\n // ==========================================================================\n\n /**\n * Update business details for an application.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param data - Business details (full BusinessApplicationCreateRequest)\n * @returns Updated business details with application context\n */\n async updateBusinessDetails(\n applicationId: string,\n data: BusinessApplicationCreateRequest,\n options?: RequestOptions\n ): Promise<BusinessDetailsResponse> {\n return this.transport.request<BusinessDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/business-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Details (non-business applications)\n // ==========================================================================\n\n /**\n * Update individual details for a non-business application.\n *\n * Uses PUT (full replace) per the OpenAPI spec. Only callable when the\n * application status is 'pending'.\n *\n * @param applicationId - Application ID\n * @param data - Individual details (full IndividualRequest)\n * @returns Updated individual details with application context\n */\n async updateIndividualDetails(\n applicationId: string,\n data: IndividualRequest,\n options?: RequestOptions\n ): Promise<IndividualDetailsResponse> {\n return this.transport.request<IndividualDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/individual-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Associated Individuals\n // ==========================================================================\n\n /**\n * Add an associated individual to an application.\n *\n * @param applicationId - Application ID\n * @param data - Individual data\n * @returns Created individual\n */\n async addIndividual(\n applicationId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update an associated individual.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Full individual data (replaces existing)\n * @returns Updated individual\n */\n async updateIndividual(\n applicationId: string,\n individualId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'PUT',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an associated individual.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n */\n async deleteIndividual(applicationId: string, individualId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n });\n }\n\n // ==========================================================================\n // Attestations\n // ==========================================================================\n\n /**\n * Submit an attestation for an application.\n *\n * Additionally supplying `disclosure_id` (a terms key the provider\n * declared, e.g. `partner_disclosures`) and `disclosure_version` records the\n * attestation as a PARTNER DISCLOSURE acknowledgment instead of a standard\n * onboarding one: acceptance is stamped `customer_online`, the\n * partner-onboarding substatus advances, and an already-approved\n * application is reprovisioned. The API stays partner-agnostic — callers\n * supply a terms key and version, never a partner name. Get the outstanding\n * ones from `customers.getCapabilities(customerId)`.\n *\n * @param applicationId - Application ID\n * @param data - Attestation data (type, timestamp, applicant_id), plus\n * `disclosure_id` + `disclosure_version` to accept a partner disclosure\n */\n async submitAttestation(\n applicationId: string,\n data: AttestationSubmitRequest,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/applications/${applicationId}/attestations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Enhanced Due Diligence (EDD)\n // ==========================================================================\n\n /**\n * Get the EDD record for an application.\n *\n * @param applicationId - Application ID\n * @returns EDD record with application context\n */\n async getEDD(applicationId: string): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'GET',\n path: `/applications/${applicationId}/edd`,\n });\n }\n\n /**\n * Create or update the EDD record for an application.\n *\n * This endpoint is idempotent (uses PUT).\n *\n * @param applicationId - Application ID\n * @param data - EDD data\n * @returns Updated EDD record with application context\n */\n async createOrUpdateEDD(\n applicationId: string,\n data: EDDRequest,\n options?: RequestOptions\n ): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'PUT',\n path: `/applications/${applicationId}/edd`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Application Documents\n // ==========================================================================\n\n /**\n * Upload an application document using base64-encoded content.\n *\n * For files larger than 20MB, use {@link getDocumentUploadUrl} and upload\n * directly to cloud storage, then call {@link verifyDocument}.\n *\n * @param applicationId - Application ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async createDocument(\n applicationId: string,\n data: ApplicationDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List documents for an application.\n *\n * Supports filtering by category and document type.\n *\n * @param applicationId - Application ID\n * @param params - Pagination and filter parameters\n * @returns Paginated iterator of document metadata\n */\n listDocuments(\n applicationId: string,\n params?: DocumentListParams\n ): PaginatedIterator<UploadedDocumentMetadata> {\n return this.paginate<UploadedDocumentMetadata>(\n `/applications/${applicationId}/documents`,\n params\n );\n }\n\n /**\n * Download/get a document by ID.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n * @returns Document content (binary)\n */\n async getDocument(applicationId: string, documentId: string): Promise<unknown> {\n return this.transport.request<unknown>({\n method: 'GET',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Delete a document from a pending application.\n *\n * Only documents from applications in 'pending' status can be deleted.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n */\n async deleteDocument(applicationId: string, documentId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Verify a document uploaded via presigned URL.\n *\n * After uploading a file to the presigned URL from {@link getDocumentUploadUrl},\n * call this endpoint to register and verify the upload.\n *\n * @param applicationId - Application ID\n * @param documentId - The upload_id from the presigned URL response\n * @returns Document upload response with document_id\n */\n async verifyDocument(\n applicationId: string,\n documentId: string,\n _data?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents/${documentId}/verifications`,\n body: _data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an application document.\n *\n * Use this for files larger than 20MB. Upload the file directly to the\n * returned URL, then call {@link verifyDocument} to register it.\n *\n * @param applicationId - Application ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getDocumentUploadUrl(\n applicationId: string,\n data: ApplicationDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Documents\n // ==========================================================================\n\n /**\n * Upload a document for an associated individual using base64-encoded content.\n *\n * Supports identity documents (passport, driver's license, residence permit)\n * and EDD documents (bank statement, etc.). For files larger than 10MB, use\n * {@link getIndividualDocumentUploadUrl} instead.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async uploadIndividualDocument(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an individual document.\n *\n * Use this for files larger than 10MB. Upload the file directly to the\n * returned URL.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getIndividualDocumentUploadUrl(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Policies resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Policy,\n PolicyCreateRequest,\n PolicyRule,\n PolicyRuleCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Policies API resource.\n */\nexport class PoliciesResource extends BaseResource {\n /**\n * Create a new policy.\n *\n * @param data - Policy creation data\n * @returns Created policy\n */\n async create(data: PolicyCreateRequest, options?: RequestOptions): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'POST',\n path: '/policies',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List policies.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of policies\n */\n list(params?: ListParams): PaginatedIterator<Policy> {\n return this.paginate<Policy>('/policies', params);\n }\n\n /**\n * Get a policy by ID.\n *\n * @param policyId - Policy ID\n * @returns Policy record\n */\n async get(policyId: string): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'GET',\n path: `/policies/${policyId}`,\n });\n }\n\n /**\n * Delete a policy.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DeletePolicyIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param options - Request options (must include `endorsement`)\n */\n async delete(policyId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Add a rule to a policy.\n *\n * @param policyId - Policy ID\n * @param data - Rule creation data\n * @returns Created rule\n */\n async addRule(\n policyId: string,\n data: PolicyRuleCreateRequest,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'POST',\n path: `/policies/${policyId}/rules`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update a policy rule.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param data - Update data\n * @returns Updated rule\n */\n async updateRule(\n policyId: string,\n ruleId: string,\n data: Partial<PolicyRuleCreateRequest>,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'PATCH',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a policy rule.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `RemovePolicyRuleIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param options - Request options (must include `endorsement`)\n */\n async deleteRule(policyId: string, ruleId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a policy.\n *\n * Returns slim references (id + name + family) for the wallets the policy is currently attached to.\n *\n * @param policyId - Policy ID\n * @returns Array of attached wallets\n */\n async getWallets(policyId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/policies/${policyId}/wallets`,\n });\n }\n\n /**\n * Attach a policy to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachPolicyToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a policy from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachPolicyFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Signer Groups resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SignerGroup,\n SignerGroupCreateRequest,\n SignerGroupGetParams,\n SignerGroupSignerAddRequest,\n Signer,\n SignerCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Signer Groups API resource.\n */\nexport class SignerGroupsResource extends BaseResource {\n /**\n * Create a new signer group.\n *\n * @param data - Signer group creation data\n * @returns Created signer group\n */\n async create(data: SignerGroupCreateRequest, options?: RequestOptions): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: '/signer-groups',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n list(params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>('/signer-groups', params);\n }\n\n /**\n * Get a signer group by ID.\n *\n * Pass `{ include_removed: true }` to also get a `removed_members` array of\n * signers that were removed from this group, each carrying its `removed_at`\n * timestamp. Defaults to active members only.\n *\n * @param signerGroupId - Signer group ID\n * @param params - Optional `{ include_removed }`\n * @returns Signer group record\n *\n * @example\n * ```typescript\n * const group = await client.signerGroups.get(groupId, { include_removed: true });\n * for (const s of group.removed_members ?? []) {\n * console.log(s.name, 'removed at', s.removed_at);\n * }\n * ```\n */\n async get(signerGroupId: string, params?: SignerGroupGetParams): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}`,\n query: { ...params },\n });\n }\n\n /**\n * Add an existing signer's public key to a group.\n *\n * The endpoint takes `{ member_key }` — the base64 PKIX (SPKI) public\n * key of an existing signer resource — not a fresh signer definition.\n * Returns the updated group (with the new member included).\n *\n * @param signerGroupId - Signer group ID\n * @param data - `{ member_key }` (the signer's base64 PKIX public key)\n * @returns The updated signer group\n */\n async addSigner(\n signerGroupId: string,\n data: SignerGroupSignerAddRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: `/signer-groups/${signerGroupId}/signers`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove a signer from a group.\n *\n * @param signerGroupId - Signer group ID\n * @param signerId - The signer's KSUID `signer_id` — NOT its public key.\n * (The standalone `client.signers.delete()` takes the public key instead.)\n * @param options - Optional request options (e.g. an explicit idempotency\n * key — the platform requires one on this DELETE)\n */\n async removeSigner(\n signerGroupId: string,\n signerId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signer-groups/${signerGroupId}/signers/${signerId}`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a signer group.\n *\n * Returns slim references (id + name + family) for the wallets the signer group is currently attached to.\n *\n * @param signerGroupId - Signer group ID\n * @returns Array of attached wallets\n */\n async getWallets(signerGroupId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}/wallets`,\n });\n }\n\n /**\n * Attach a signer group to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachGroupToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a signer group from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachGroupFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups attached to a wallet.\n *\n * @param walletId - Wallet ID\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n listForWallet(walletId: string, params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>(`/wallets/${walletId}/signer-groups`, params);\n }\n}\n\n/**\n * Signers API resource.\n */\nexport class SignersResource extends BaseResource {\n /**\n * Create a new signer.\n *\n * @param data - Signer creation data (name, public_key, key_type)\n * @param options - Request options\n * @returns Created signer\n */\n async create(data: SignerCreateRequest, options?: RequestOptions): Promise<Signer> {\n return this.transport.request<Signer>({\n method: 'POST',\n path: '/signers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a signer by public key.\n *\n * Soft-deletes all signers with the given public key.\n *\n * @param publicKey - Signer public key\n */\n async delete(publicKey: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signers/${publicKey}`,\n });\n }\n}\n","/**\n * API Keys resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n ApiKey,\n ApiKeyResponse,\n ApiKeyCreateRequest,\n CreateApiKeyForClientRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * API Keys API resource.\n */\nexport class ApiKeysResource extends BaseResource {\n /**\n * Create a new API key.\n *\n * @param data - API key creation data\n * @returns Created API key (includes secret, only shown once)\n */\n async create(data: ApiKeyCreateRequest, options?: RequestOptions): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List API keys.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of API keys\n */\n list(params?: ListParams): PaginatedIterator<ApiKey> {\n return this.paginate<ApiKey>('/api-keys', params);\n }\n\n /**\n * Delete an API key.\n *\n * @param apiKeyId - API key ID\n */\n async delete(apiKeyId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/api-keys/${apiKeyId}`,\n });\n }\n\n /**\n * Delete all API keys.\n *\n * Intended for incident response only.\n */\n async deleteAll(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/api-keys',\n });\n }\n\n /**\n * Create an API key for a specific client (admin only).\n *\n * Requires admin access token.\n *\n * @param data - Request data containing `client_id`\n * @param options - Request options\n * @returns Created API key response (includes key, only shown once)\n */\n async createForClient(\n data: CreateApiKeyForClientRequest,\n options?: RequestOptions\n ): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys/admin',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Users resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n User,\n UserCreateRequest,\n UserUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Users API resource.\n */\nexport class UsersResource extends BaseResource {\n /**\n * Create a new user.\n *\n * @param data - User creation data\n * @returns Created user\n */\n async create(data: UserCreateRequest, options?: RequestOptions): Promise<User> {\n return this.transport.request<User>({\n method: 'POST',\n path: '/users',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List users.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of users\n */\n list(params?: ListParams): PaginatedIterator<User> {\n return this.paginate<User>('/users', params);\n }\n\n /**\n * Update a user.\n *\n * @param userId - User ID\n * @param data - Update data (first_name, last_name, role)\n */\n async update(userId: string, data: UserUpdateRequest, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'PATCH',\n path: `/users/${userId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a user.\n *\n * @param userId - User ID\n */\n async delete(userId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/users/${userId}`,\n });\n }\n}\n","/**\n * Webhooks resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n WebhookTarget,\n WebhookTargetCreateRequest,\n WebhookTargetUpdateRequest,\n WebhookEvent,\n WebhookReplayResponse,\n WebhookHistoryListParams,\n WebhookHistoryResponse,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Webhooks API resource.\n */\nexport class WebhooksResource extends BaseResource {\n /**\n * Create a new webhook target.\n *\n * @param data - Webhook target creation data\n * @returns Created webhook target\n */\n async createTarget(\n data: WebhookTargetCreateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'POST',\n path: '/webhooks/targets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List webhook targets.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of webhook targets\n */\n listTargets(params?: ListParams): PaginatedIterator<WebhookTarget> {\n return this.paginate<WebhookTarget>('/webhooks/targets', params);\n }\n\n /**\n * Get a webhook target by ID.\n *\n * @param targetId - Webhook target ID\n * @returns Webhook target record\n */\n async getTarget(targetId: string): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'GET',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * Update a webhook target.\n *\n * @param targetId - Webhook target ID\n * @param data - Update data\n * @returns Updated webhook target\n */\n async updateTarget(\n targetId: string,\n data: WebhookTargetUpdateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'PATCH',\n path: `/webhooks/targets/${targetId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a webhook target.\n *\n * @param targetId - Webhook target ID\n */\n async deleteTarget(targetId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * List webhook delivery history.\n *\n * Note: This endpoint uses cursor-based pagination (`cursor`/`has_more`) instead\n * of the standard `starting_after`/`has_more_after` format. Because of this,\n * it returns the raw response rather than a `PaginatedIterator`. Use the `cursor`\n * field from the response to fetch subsequent pages.\n *\n * @param params - Webhook history query parameters\n * @returns Webhook history response with `data`, `has_more`, and `cursor`\n *\n * @example\n * ```typescript\n * let cursor: string | undefined;\n * do {\n * const page = await client.webhooks.listEvents({ limit: 50, cursor });\n * for (const event of page.data) {\n * console.log(event);\n * }\n * cursor = page.cursor ?? undefined;\n * } while (page.has_more);\n * ```\n */\n async listEvents(params?: WebhookHistoryListParams): Promise<WebhookHistoryResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n return this.transport.request<WebhookHistoryResponse>({\n method: 'GET',\n path: '/webhooks',\n query,\n });\n }\n\n /**\n * Get a webhook event by ID.\n *\n * @param eventId - Webhook event ID\n * @returns Webhook event record\n */\n async getEvent(eventId: string): Promise<WebhookEvent> {\n return this.transport.request<WebhookEvent>({\n method: 'GET',\n path: `/webhooks/${eventId}`,\n });\n }\n\n /**\n * Replay a webhook event.\n *\n * Re-queues the webhook for delivery to all configured targets.\n *\n * @param eventId - Webhook event ID\n * @param options - Request options\n * @returns Replay response with `webhook_id`, `status`, and `replayed_to_count`\n */\n async replayEvent(eventId: string, options?: RequestOptions): Promise<WebhookReplayResponse> {\n return this.transport.request<WebhookReplayResponse>({\n method: 'POST',\n path: `/webhooks/events/${eventId}/replay`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Info resource for platform capabilities.\n */\n\nimport { BaseResource } from './base.js';\nimport type { Country } from '../types.js';\n\n/**\n * Info API resource for platform capabilities.\n */\nexport class InfoResource extends BaseResource {\n /**\n * Get supported countries.\n *\n * @returns Array of supported countries\n *\n * @example\n * ```typescript\n * const countries = await client.info.getCountries();\n * ```\n */\n async getCountries(): Promise<Country[]> {\n // /capabilities/countries returns Country[] directly, not the\n // paginated { data, meta } envelope. Earlier versions read\n // response.data here and silently returned undefined.\n return this.transport.request<Country[]>({\n method: 'GET',\n path: '/capabilities/countries',\n });\n }\n\n /**\n * Get supported networks.\n *\n * @returns Array of supported networks\n *\n * @example\n * ```typescript\n * const networks = await client.info.getNetworks();\n * for (const network of networks) {\n * console.log(network.id, network.name);\n * }\n * ```\n */\n async getNetworks(): Promise<string[]> {\n // /capabilities/networks returns string[] (network IDs like\n // \"ethereum-mainnet\") directly, not the paginated { data, meta }\n // envelope. Earlier versions typed this as Network[] and read\n // response.data, which silently returned undefined.\n return this.transport.request<string[]>({\n method: 'GET',\n path: '/capabilities/networks',\n });\n }\n}\n","/**\n * Sandbox resource for testing simulations.\n *\n * @remarks\n * These endpoints are only available in the Sandbox environment.\n * In sandbox, Dakota does NOT monitor testnet blockchains - you must\n * use these simulation endpoints to trigger payment events.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SimulateInboundRequest,\n SimulationResponse,\n SimulateOnboardingRequest,\n SimulateOnboardingResponse,\n AdvanceSimulationRequest,\n AdvanceSimulationResult,\n SimulationInspection,\n SandboxScenario,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Sandbox API resource for testing simulations.\n *\n * These endpoints are only available in the Sandbox environment.\n *\n * @remarks\n * **Important:** In sandbox, Dakota does NOT monitor testnet blockchains.\n * You must use these simulation endpoints to trigger payment events.\n *\n * @example\n * ```typescript\n * // Simulate ACH deposit to on-ramp account\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n *\n * // Simulate off-ramp ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * movement_id: 'tx_456',\n * amount: '500.00',\n * currency: 'USD',\n * });\n * ```\n */\nexport class SandboxResource extends BaseResource {\n /**\n * Simulate an inbound payment event.\n *\n * Triggers a simulated payment event through the mock banking provider.\n * The required fields depend on the simulation `type`:\n *\n * | Type | Required Fields |\n * |------|-----------------|\n * | `ach_inbound`, `wire_inbound` | `account_id` |\n * | `crypto_inbound` | `wallet_id` |\n * | `*_outbound_*`, `*_reversal` | `movement_id` |\n *\n * @param data - Simulation request data\n * @returns Simulation response with ID and state\n *\n * @example Simulate ACH deposit to on-ramp\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate off-ramp ACH settlement\n * ```typescript\n * // After creating a one-off transaction for off-ramp testing\n * const tx = await client.transactions.create({\n * customer_id: 'cust_123',\n * amount: '100.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-sepolia',\n * destination_id: 'dest_456',\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * });\n *\n * // Simulate the ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * movement_id: tx.id,\n * amount: '100.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate crypto deposit to wallet\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'crypto_inbound',\n * wallet_id: 'wallet_789',\n * amount: '500.00',\n * currency: 'USDC',\n * });\n * ```\n */\n async simulateInbound(\n data: SimulateInboundRequest,\n options?: RequestOptions\n ): Promise<SimulationResponse> {\n return this.transport.request<SimulationResponse>({\n method: 'POST',\n path: '/sandbox/simulate/inbound',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Simulate an onboarding state transition.\n *\n * Drives KYB, KYC, or applicant account status through a sandbox transition\n * without waiting for real compliance review.\n *\n * **Important:** Use `kyb_approve` to fully approve any customer type (individual or\n * business). This triggers the complete onboarding flow including endorsement and\n * recipient creation. The `kyc_*` types only update the individual applicant's KYC\n * application status without triggering the full onboarding flow.\n *\n * @param data - Simulation request data\n * @returns Simulation response with previous and new state\n *\n * @example Approve KYB and activate applicant\n * ```typescript\n * // Step 1: Approve the KYB application\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_approve',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_kyb_${Date.now()}`,\n * });\n *\n * // Step 2: Activate the applicant (triggers provisioning)\n * await client.sandbox.simulateOnboarding({\n * type: 'applicant_activate',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_activate_${Date.now()}`,\n * });\n * ```\n *\n * @example Reject a KYB application\n * ```typescript\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_reject',\n * applicant_id: applicationId,\n * simulation_id: `sim_${Date.now()}`,\n * reason_code: 'MISSING_DOCUMENTS',\n * });\n * ```\n */\n async simulateOnboarding(\n data: SimulateOnboardingRequest,\n options?: RequestOptions\n ): Promise<SimulateOnboardingResponse> {\n return this.transport.request<SimulateOnboardingResponse>({\n method: 'POST',\n path: '/sandbox/simulate/onboarding',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get detailed simulation status and callback history.\n *\n * Returns the current state and callback delivery history for a sandbox simulation.\n * Use this to debug async flows and see whether callbacks have been delivered.\n *\n * @param simulationId - Simulation ID returned from simulateInbound/simulateOnboarding\n * @returns Full simulation inspection including state and callbacks\n *\n * @example\n * ```typescript\n * const inspection = await client.sandbox.getSimulation('sim_123');\n * console.log('State:', inspection.state);\n * console.log('Callbacks:', inspection.callbacks);\n * ```\n */\n async getSimulation(simulationId: string): Promise<SimulationInspection> {\n return this.transport.request<SimulationInspection>({\n method: 'GET',\n path: `/sandbox/simulations/${simulationId}`,\n });\n }\n\n /**\n * Advance a stateful simulation to the next state.\n *\n * Some scenarios pause and wait for explicit advancement. Use this method\n * to continue a paused simulation with a specific action.\n *\n * @param simulationId - Simulation ID\n * @param data - Action to take (e.g., 'release', 'reject', 'confirm', 'expire')\n * @returns Updated simulation state\n *\n * @example\n * ```typescript\n * const result = await client.sandbox.advanceSimulation('sim_123', {\n * action: 'release',\n * });\n * console.log('New state:', result.new_state);\n * ```\n */\n async advanceSimulation(\n simulationId: string,\n data?: AdvanceSimulationRequest,\n options?: RequestOptions\n ): Promise<AdvanceSimulationResult> {\n return this.transport.request<AdvanceSimulationResult>({\n method: 'POST',\n path: `/sandbox/simulations/${simulationId}/advance`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List available sandbox scenarios.\n *\n * Returns all simulation scenarios supported by the platform.\n * Use these scenario names in the `scenario` field of simulateInbound.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of scenarios\n *\n * @example\n * ```typescript\n * const scenarios = await client.sandbox.listScenarios().toArray();\n * for (const scenario of scenarios) {\n * console.log(`${scenario.name}: ${scenario.description}`);\n * }\n * ```\n */\n listScenarios(params?: ListParams): PaginatedIterator<SandboxScenario> {\n return this.paginate<SandboxScenario>('/sandbox/scenarios', params);\n }\n}\n","/**\n * Self-Serve Credits resource for managing prepaid transfer credits.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n SelfServeCreditsPurchaseRequest,\n SelfServeCreditsPurchaseResponse,\n SelfServeCreditsBalanceResponse,\n SelfServeCreditsLedgerResponse,\n SelfServeCreditsLedgerParams,\n SelfServeCreditsPricingResponse,\n SelfServeCreditTiersResponse,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Self-Serve Credits API resource.\n *\n * Manage prepaid credits for self-serve transfer capacity.\n */\nexport class SelfServeResource extends BaseResource {\n /**\n * Purchase self-serve credits.\n *\n * Creates a Stripe checkout session for purchasing credits at the specified tier.\n *\n * @param data - Purchase request with the tier price\n * @param options - Optional request options (e.g., idempotency key)\n * @returns Response containing the Stripe checkout URL\n *\n * @example\n * ```typescript\n * const { checkout_url } = await client.selfServe.purchaseCredits({\n * tier_price_cents: 10000,\n * });\n * // Redirect user to checkout_url\n * ```\n */\n async purchaseCredits(\n data: SelfServeCreditsPurchaseRequest,\n options?: RequestOptions\n ): Promise<SelfServeCreditsPurchaseResponse> {\n return this.transport.request<SelfServeCreditsPurchaseResponse>({\n method: 'POST',\n path: '/self-serve/credits/purchase',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get current credits balance.\n *\n * @returns The current balance and transfer capacity in cents\n *\n * @example\n * ```typescript\n * const balance = await client.selfServe.getBalance();\n * console.log(`Balance: $${balance.balance_cents / 100}`);\n * console.log(`Transfer capacity: $${balance.transfer_capacity_cents / 100}`);\n * ```\n */\n async getBalance(): Promise<SelfServeCreditsBalanceResponse> {\n return this.transport.request<SelfServeCreditsBalanceResponse>({\n method: 'GET',\n path: '/self-serve/credits/balance',\n });\n }\n\n /**\n * List credits ledger entries.\n *\n * Returns a cursor-paginated list of ledger entries (purchases, deductions, refunds).\n *\n * @param params - Optional query parameters for filtering and pagination\n * @returns Ledger response with entries and has_more flag\n *\n * @example\n * ```typescript\n * // Get recent ledger entries\n * const ledger = await client.selfServe.listLedger();\n * for (const entry of ledger.entries) {\n * console.log(entry.entry_type, entry.amount_cents, entry.description);\n * }\n *\n * // Filter by type with pagination\n * const purchases = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * });\n * ```\n */\n async listLedger(params?: SelfServeCreditsLedgerParams): Promise<SelfServeCreditsLedgerResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params?.cursor !== undefined) query.cursor = params.cursor;\n if (params?.limit !== undefined) query.limit = params.limit;\n if (params?.type !== undefined) query.type = params.type;\n\n return this.transport.request<SelfServeCreditsLedgerResponse>({\n method: 'GET',\n path: '/self-serve/credits/ledger',\n query,\n });\n }\n\n /**\n * List available credit tiers.\n *\n * Returns all available pricing tiers for purchasing credits.\n *\n * @returns Response containing the list of available tiers\n *\n * @example\n * ```typescript\n * const { tiers } = await client.selfServe.listTiers();\n * for (const tier of tiers) {\n * console.log(`$${tier.price_cents / 100} → $${tier.transfer_capacity_cents / 100} capacity`);\n * }\n * ```\n */\n async listTiers(): Promise<SelfServeCreditTiersResponse> {\n return this.transport.request<SelfServeCreditTiersResponse>({\n method: 'GET',\n path: '/self-serve/credits/tiers',\n });\n }\n\n /**\n * Get the self-serve client's pricing config (fee schedule).\n *\n * Returns the caller's current `ClientPricingConfig` — transfer/ACH/wire/SEPA/SWIFT/KYC/KYB\n * fees plus the monthly minimum. Self-serve clients only.\n *\n * @returns The current pricing configuration\n *\n * @example\n * ```typescript\n * const pricing = await client.selfServe.getPricing();\n * console.log(`ACH fee: ${pricing.achFeeCents} cents`);\n * console.log(`Wire fee: ${pricing.wireFeeCents} cents`);\n * ```\n */\n async getPricing(): Promise<SelfServeCreditsPricingResponse> {\n return this.transport.request<SelfServeCreditsPricingResponse>({\n method: 'GET',\n path: '/self-serve/credits/pricing',\n });\n }\n}\n","/**\n * Fee Payout Destination resource.\n *\n * Where Dakota pays your accrued developer fees. Exactly ONE destination\n * exists per organization, and it is crypto-only — a USDC wallet on any\n * supported chain.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n FeePayoutDestination,\n PutFeePayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Fee Payout Destination API resource.\n */\nexport class FeePayoutDestinationResource extends BaseResource {\n /**\n * Get the destination registered to receive your developer-fee payouts.\n *\n * @returns The registered destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.get();\n * console.log(dest.chain, dest.wallet_address);\n * ```\n */\n async get(): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'GET',\n path: '/fee-payout-destination',\n });\n }\n\n /**\n * Register or replace your fee payout destination.\n *\n * There is exactly one destination per organization, so this REPLACES any\n * existing one. Emits `fee_payout_destination.updated`.\n *\n * `chain` is a CAIP-2 chain id (e.g. `eip155:8453`) from the supported\n * networks list — see `client.info.getNetworks()`.\n *\n * @param data - The USDC wallet to pay fees to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.set({\n * usdc_wallet: {\n * chain: 'eip155:8453',\n * address: '0x1234567890123456789012345678901234567890',\n * },\n * });\n * ```\n */\n async set(\n data: PutFeePayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'PUT',\n path: '/fee-payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove the registered fee payout destination, if one exists.\n *\n * Emits `fee_payout_destination.deleted`.\n *\n * @example\n * ```typescript\n * await client.feePayoutDestination.delete();\n * ```\n */\n async delete(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/fee-payout-destination',\n });\n }\n}\n","/**\n * Payment Agents resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { AGENTIC_MODEL_TIMEOUT_MS } from '../config.js';\nimport type {\n PaymentAgent,\n PaymentAgentCreateRequest,\n AgenticProposalsProgress,\n AgenticProposalsResult,\n CreateProposalsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Payment Agents API resource (ALPHA).\n */\nexport class PaymentAgentsResource extends BaseResource {\n /**\n * Create a hosted payment agent.\n *\n * @param data - Payment agent creation data (customer_id, name, hosted)\n * @returns The created payment agent (id, signer_id, signer_public_key, state)\n */\n async create(data: PaymentAgentCreateRequest, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: '/payment-agents',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a hosted payment agent.\n *\n * Returns the agent together with the wallets it can currently spend\n * from. `wallet_ids` are DERIVED at query time from the agent signer's\n * live signer-group membership, so they reflect the agent's access\n * right now — not just at creation time.\n *\n * @param paymentAgentId - Payment agent ID\n */\n async get(paymentAgentId: string): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}`,\n });\n }\n\n /**\n * Revoke a hosted payment agent.\n *\n * The agent can no longer be used, and its signing key is destroyed\n * in the isolated signer service (best-effort — the revoked state is\n * authoritative). Idempotent.\n *\n * The response's `signer_group_cleanup` names the signer groups the\n * (now-revoked) agent's signer still belongs to. A revoked signer can't\n * sign, but its group membership lingers — remove it with\n * `client.signerGroups.removeSigner(signer_group_id, signer_id)` to\n * finish de-provisioning.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The revoked payment agent (state=revoked, signer_group_cleanup?)\n */\n async revoke(paymentAgentId: string, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/revoke`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Draft payment proposals from a conversation.\n *\n * Pure cognition, no side effects: turn a customer's natural-language\n * request into reviewable proposals. Stateless — send the whole\n * conversation so far in `messages` on each call. Prefer\n * `AgentConversation` for multi-turn chat; use this directly only for\n * one-shot proposals.\n *\n * SLOW BY NATURE. A turn is a sequence of model calls — read the payees,\n * check balances, draft, revise — so a multi-payee request legitimately\n * runs minutes. It therefore defaults to {@link AGENTIC_MODEL_TIMEOUT_MS}\n * rather than the client's ordinary deadline. Pass `{ timeout }` to\n * change it for one call; an explicit client-wide `timeout` still wins.\n *\n * The result may carry `blockers` ALONGSIDE proposals — they are not\n * alternatives. Branch on `blocker.code`, not on `reply`, and ignore codes\n * you do not recognize.\n *\n * `data.client_policy` is a DEVELOPMENT override of the vocabulary the\n * agent drafts under; prefer registering it once with\n * `client.agenticPolicy.set()`, since forgetting to send it here fails\n * silently.\n *\n * @param paymentAgentId - Payment agent ID\n * @param data - Prompt and/or messages\n * @returns Proposals (at high confidence) and/or a conversational reply\n */\n async createProposals(\n paymentAgentId: string,\n data: CreateProposalsRequest,\n options?: RequestOptions\n ): Promise<AgenticProposalsResult> {\n return this.transport.request<AgenticProposalsResult>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/proposals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n endpointTimeout: AGENTIC_MODEL_TIMEOUT_MS,\n });\n }\n\n /**\n * Live progress of an in-flight drafting turn.\n *\n * A multi-payee drafting turn legitimately runs minutes (several sequential\n * model calls). While a `createProposals` call is in flight, poll this every\n * few seconds to show the customer what the agent is doing right now.\n *\n * Advisory display only. `active: false` means no turn is currently\n * publishing progress for this agent — idle, just finished, or served by\n * another instance — so fall back to a generic spinner. Never gate any\n * behaviour on this endpoint.\n *\n * The snapshot is coarse and customer-safe: a phase enum, one human\n * sentence, and the model round. Tool counts only — never payee names,\n * amounts, or addresses.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The current progress snapshot\n *\n * @example\n * ```typescript\n * const pending = client.paymentAgents.createProposals(agentId, { prompt });\n * const poll = setInterval(async () => {\n * const p = await client.paymentAgents.getProposalsProgress(agentId);\n * if (p.active) console.log(p.detail);\n * }, 3000);\n * const result = await pending.finally(() => clearInterval(poll));\n * ```\n */\n async getProposalsProgress(paymentAgentId: string): Promise<AgenticProposalsProgress> {\n return this.transport.request<AgenticProposalsProgress>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}/proposals/progress`,\n });\n }\n}\n","/**\n * Instructions resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticInstruction,\n AgenticInstructionsResult,\n CreateInstructionsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Instructions API resource (ALPHA).\n *\n * Each accepted proposal becomes one persisted instruction whose action\n * series is actuated deterministically.\n */\nexport class InstructionsResource extends BaseResource {\n /**\n * Accept proposals — actuate them into persisted instructions.\n *\n * Two optional fields shape the actuation:\n *\n * - `developer_fee` declares your fee PER PAYOUT TYPE — `swap_bps` for a\n * crypto payout, `offramp_bps` for a bank payout. They are independent,\n * so one conversation can charge a swap and stay silent about a bank\n * payout in the same turn. Omit a rate (or send zero) and that payout\n * type carries no fee: nothing is charged, nothing is added to the\n * amount, and the agent is told nothing about a fee it could mention.\n * Both are DEFAULTS for the auto-accounts this request creates — an\n * action-level `fee_bps` still wins outright.\n * - `client_policy` is the same development override the proposals call\n * takes. Prefer registering it once with `client.agenticPolicy.set()`.\n *\n * @param data - The payment agent id and the proposals to accept\n * @returns instruction_ids + the mandates the batch drafted (in full\n * wire shape; sign the §8 approval immediately)\n */\n async create(\n data: CreateInstructionsRequest,\n options?: RequestOptions\n ): Promise<AgenticInstructionsResult> {\n return this.transport.request<AgenticInstructionsResult>({\n method: 'POST',\n path: '/instructions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get an accepted instruction — its action series and the per-action\n * downstream artifacts actuation produced.\n *\n * @param instructionId - Instruction ID\n */\n async get(instructionId: string): Promise<AgenticInstruction> {\n return this.transport.request<AgenticInstruction>({\n method: 'GET',\n path: `/instructions/${instructionId}`,\n });\n }\n}\n","/**\n * Mandates resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n AmendMandateRequest,\n ApproveMandateRequest,\n CancelMandateRequest,\n CreateMandateRequest,\n Mandate,\n MandateBudget,\n MandateListParams,\n MandateResponse,\n MandateVersion,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Mandates API resource (ALPHA).\n */\nexport class MandatesResource extends BaseResource {\n /**\n * List mandates (newest first), with the EFFECTIVE status — a pending or\n * active mandate past its valid_until reads \"expired\". Filter with\n * customer_id / signer_id / status; omit them all for the full collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of mandates\n */\n list(params?: MandateListParams): PaginatedIterator<Mandate> {\n return this.paginate<Mandate>('/mandates', params);\n }\n\n /**\n * Get a mandate — the signer it binds, its rule exactly as the customer\n * approves it, validity, and status.\n *\n * @param mandateId - Mandate ID\n */\n async get(mandateId: string): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'GET',\n path: `/mandates/${mandateId}`,\n });\n }\n\n /**\n * Create a mandate directly.\n *\n * Drafts a PENDING mandate from a direct user interaction — no instruction\n * back-link. Exactly one binding form names the signer the mandate binds:\n * `payment_agent_id` (hosted convenience — binds that agent's signer and\n * anchors to the agent's customer), or `signer_id` together with\n * `customer_id` (any of the client's signers, BYO keys included). The rule\n * is the one the customer will approve (via `approve`, a recognized signer\n * other than the bound one, §8).\n *\n * @param data - One binding form + rule + optional validity window\n * @returns The drafted (pending) mandate\n */\n async create(data: CreateMandateRequest, options?: RequestOptions): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: '/mandates',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Approve a mandate.\n *\n * A recognized signer OTHER than the bound one signs the mandate payload\n * (see `mandateSignPayload` + `MandateSigner`) to activate it; arms its\n * scheduled payments.\n *\n * @param mandateId - Mandate ID\n * @param data - Approver public key (base64 PKIX) + base64 ASN.1 signature\n */\n async approve(\n mandateId: string,\n data: ApproveMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/approve`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel a mandate.\n *\n * Revokes a pending or active mandate. The canceller must be a recognized\n * signer OTHER than the bound one, with a valid signature over the mandate\n * payload — the bound signer can never mutate its own mandate.\n *\n * @param mandateId - Mandate ID\n * @param data - Signer public key (base64 PKIX) + base64 ASN.1 signature\n */\n async cancel(\n mandateId: string,\n data: CancelMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/cancel`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Amend a mandate — append a new signed version of its rule.\n *\n * Carries a changed rule into force with ONE signature and WITHOUT resetting\n * the spend already made in the current window: usage accrues to the\n * MANDATE, so an agent that has spent 9,000 of a 10,000 monthly limit and is\n * amended to 20,000 has 11,000 left, not 20,000.\n *\n * The `rule` is stored and verified VERBATIM — this endpoint does not\n * normalize it. It must already be canonical: `window` present and non-empty\n * (send `'NONE'` for a lifetime window), `targets` as recipient ids rather\n * than payee names, and `asset` uppercase. `target_type`, `window`, `asset`\n * and `network_id` must also match the current version exactly; only the\n * amount fields and `targets` may differ. Anything else is a 400 naming the\n * offending field.\n *\n * Build `signature` from `mandateAmendSignPayload(mandate, version, rule)` —\n * the amend payload commits to the version being created, so a signature for\n * v2 can never be replayed to append v3.\n *\n * @param mandateId - Mandate ID\n * @param data - Amending signer public key + signature + the complete NEW rule\n * @returns The mandate at its new current version\n *\n * @example\n * ```typescript\n * const mandate = await client.mandates.get(mandateId);\n * const nextVersion = (mandate.version ?? 1) + 1;\n * const rule = { ...mandate.rule, max_amount_in_window: '20000' };\n * const payload = mandateAmendSignPayload(mandate, nextVersion, rule);\n *\n * const amended = await client.mandates.amend(mandateId, {\n * signer_public_key: signer.publicKeyBase64(),\n * signature: await signer.sign(payload),\n * rule,\n * });\n * ```\n */\n async amend(\n mandateId: string,\n data: AmendMandateRequest,\n options?: RequestOptions\n ): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: `/mandates/${mandateId}/amend`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List a mandate's versions, oldest first.\n *\n * The append-only history of every rule that was ever in force under this\n * mandate, and the §8 signer that put each one there. Versions are\n * immutable, so a rule listed here never changes — this is what makes an\n * executed payment's `mandate_version` audit stamp legible.\n *\n * @param mandateId - Mandate ID\n * @returns Every version, oldest first\n */\n async listVersions(mandateId: string): Promise<MandateVersion[]> {\n return this.transport.request<MandateVersion[]>({\n method: 'GET',\n path: `/mandates/${mandateId}/versions`,\n });\n }\n\n /**\n * Get a mandate's remaining budget right now.\n *\n * The mandate's `rule` gives the ceilings; this gives the CONSUMPTION — what\n * has already been spent, what is earmarked by scheduled payments that have\n * not fired yet, and therefore what is left. Read it before scheduling:\n * otherwise an over-budget payment is only discovered when the gate denies\n * it at its due date, days later, with the payee unpaid.\n *\n * Advisory — nothing here reserves budget, and the gate remains the\n * authority at fire time. Two things to honour when reading a line:\n * an ABSENT `remaining_amount` / `remaining_count` means \"not capped\", never\n * \"nothing left\"; a `remaining_amount` of `'?'` means the figure could not\n * be summed and MUST be treated as no headroom (the gate fails closed on the\n * same data).\n *\n * @param mandateId - Mandate ID\n * @returns Per-target and aggregate budget lines, as of a stated instant\n *\n * @example\n * ```typescript\n * const budget = await client.mandates.getBudget(mandateId);\n * for (const line of budget.aggregate) {\n * console.log(line.bucket, line.remaining_amount ?? 'uncapped');\n * }\n * ```\n */\n async getBudget(mandateId: string): Promise<MandateBudget> {\n return this.transport.request<MandateBudget>({\n method: 'GET',\n path: `/mandates/${mandateId}/budget`,\n });\n }\n}\n","/**\n * Scheduled Payments resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n CreateScheduledPaymentRequest,\n RequestOptions,\n ScheduledPayment,\n ScheduledPaymentListParams,\n} from '../types.js';\n\n/**\n * Scheduled Payments API resource (ALPHA).\n */\nexport class ScheduledPaymentsResource extends BaseResource {\n /**\n * List scheduled payments (oldest due first).\n *\n * Narrow the collection with the optional customer_id, signer_id,\n * wallet_id, mandate_id, and status filters; omit them all for the full\n * client collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of scheduled payments\n */\n list(params?: ScheduledPaymentListParams): PaginatedIterator<ScheduledPayment> {\n return this.paginate<ScheduledPayment>('/scheduled-payments', params);\n }\n\n /**\n * Schedule payments directly — bypass the proposal flow.\n *\n * Creates one or more scheduled payments for a signer under an existing\n * active mandate (coverage is matched at fire time, so no new signature\n * is needed here). The schedule is explicit `dates` OR `count` ×\n * `interval_seconds` from `start_at`.\n *\n * @param data - Signer + wallet + destination (or address+network_id) + schedule\n * @returns The rows that were created (one per date)\n */\n async create(\n data: CreateScheduledPaymentRequest,\n options?: RequestOptions\n ): Promise<ScheduledPayment[]> {\n return this.transport.request<ScheduledPayment[]>({\n method: 'POST',\n path: '/scheduled-payments',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel one still-scheduled payment.\n *\n * Finalizes the row as cancelled. No signature is required — schedule rows\n * are bookkeeping, not authorization; the signed grant is the MANDATE,\n * which this does not touch.\n *\n * @param scheduledPaymentId - Scheduled payment ID\n */\n async cancel(scheduledPaymentId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/scheduled-payments/${scheduledPaymentId}/cancel`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Insights resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { AGENTIC_MODEL_TIMEOUT_MS } from '../config.js';\nimport type {\n InsightReport,\n InsightChatRequest,\n InsightChatResponse,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Insights API resource (ALPHA).\n *\n * Read-only, advisory reporting over a customer's agentic activity. Nothing\n * here moves money or changes state.\n */\nexport class InsightsResource extends BaseResource {\n /**\n * Get the customer's account insight report.\n *\n * A deterministic, read-only report: a snapshot of typed facts\n * (funding-wallet balances, upcoming totals, open payments, active\n * mandates), observations (`insights`), and advisory recommendations\n * (`suggestions`). Every item carries `evidence` — typed references to\n * the platform objects it was computed from. `kind` is an OPEN set;\n * ignore kinds you do not recognize.\n *\n * @param customerId - Customer ID\n * @returns The customer's insight report\n */\n async get(customerId: string): Promise<InsightReport> {\n return this.transport.request<InsightReport>({\n method: 'GET',\n path: `/customers/${customerId}/insights`,\n });\n }\n\n /**\n * Ask about the customer's account.\n *\n * A read-only, advisory conversation. Stateless: send the conversation so\n * far in `messages` on each call; the response is the assistant's next\n * plain-text `reply`. The assistant narrates the same deterministic report\n * {@link get} returns — it never originates a number, never proposes, and\n * never moves money. Rate-limited per customer (hourly burst + daily\n * window) — a 429 means back off and retry later.\n *\n * Model-backed, so it defaults to {@link AGENTIC_MODEL_TIMEOUT_MS} rather\n * than the client's ordinary deadline. Pass `{ timeout }` to change it for\n * one call; an explicit client-wide `timeout` still wins.\n *\n * @param customerId - Customer ID\n * @param data - The conversation so far (1–40 messages)\n * @returns The assistant's reply (+ how the boundary screen treated the turn)\n */\n async chat(\n customerId: string,\n data: InsightChatRequest,\n options?: RequestOptions\n ): Promise<InsightChatResponse> {\n return this.transport.request<InsightChatResponse>({\n method: 'POST',\n path: `/customers/${customerId}/insights/chat`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n endpointTimeout: AGENTIC_MODEL_TIMEOUT_MS,\n });\n }\n}\n","/**\n * Agentic Client Policy resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticClientPolicy,\n RegisteredAgenticClientPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Agentic Client Policy API resource (ALPHA).\n *\n * The policy is per CLIENT — it belongs to the `client_id` behind your API\n * key, never to a key, since API keys are N:1 to clients and a per-key policy\n * would fragment for anyone running one service key per deployment.\n *\n * You may read and write your OWN policy; another client's is a 403.\n */\nexport class AgenticPolicyResource extends BaseResource {\n /**\n * Get the policy registered for this client.\n *\n * A 404 here is the DEFAULT, not an error condition: with no registration\n * and no per-request policy the agent drafts on platform defaults, exactly\n * as it did before registration existed.\n *\n * @param clientId - Your client ID\n * @returns The normalized registered policy + its timestamps\n *\n * @example\n * ```typescript\n * try {\n * const { policy } = await client.agenticPolicy.get(clientId);\n * console.log(policy.labels);\n * } catch (e) {\n * if (e instanceof APIError && e.statusCode === 404) {\n * // No registration — platform defaults apply.\n * }\n * }\n * ```\n */\n async get(clientId: string): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'GET',\n path: `/clients/${clientId}/agentic-policy`,\n });\n }\n\n /**\n * Register — or fully replace — this client's agentic policy.\n *\n * Declaring the vocabulary once removes a silent failure mode. Sending\n * `client_policy` in each proposals request still works and still wins, but\n * FORGETTING to send it fails silently: the agent just narrates in the\n * platform's nouns again (\"destination\", \"mandate\") and nothing errors\n * anywhere. A registration makes that impossible.\n *\n * FULL REPLACE, not a merge — the registration IS your declared vocabulary,\n * so an omitted field means you no longer want it, and an empty body (`{}`)\n * clears the registration back to platform defaults.\n *\n * Validated exactly like the per-request copy, so an unknown key, an\n * unsupported value, or a label for an unimplemented concept is a 400 HERE,\n * at registration — not a surprise on a customer's first conversation.\n *\n * @param clientId - Your client ID\n * @param policy - The complete policy (`{}` clears it)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The normalized stored policy + its timestamps\n *\n * @example\n * ```typescript\n * await client.agenticPolicy.set(clientId, {\n * payee_model: 'flat',\n * payout_assets: ['USDC', 'USDT'],\n * labels: { limit: 'spending limit', payee: 'recipient', limit_unit: 'USD' },\n * payout_route: 'conversion_account_only',\n * mandate_strategy: 'external_only',\n * });\n * ```\n */\n async set(\n clientId: string,\n policy: AgenticClientPolicy,\n options?: RequestOptions\n ): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'PUT',\n path: `/clients/${clientId}/agentic-policy`,\n body: policy,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Multi-turn agent chat. The platform's proposals endpoint is STATELESS —\n * it holds no session and must be sent the whole transcript on every turn.\n * `AgentConversation` hides that bookkeeping so a caller just sends user\n * messages and reads the agent's clarifying questions / final proposals.\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport type { DakotaClient } from '../client/client.js';\nimport type {\n AgenticBlocker,\n AgenticClientPolicy,\n AgenticProposal,\n AgenticProposalsResult,\n} from '../client/types.js';\n\n/**\n * MIME types the platform accepts for a document attachment.\n */\nexport type AttachmentMediaType =\n | 'application/pdf'\n | 'image/png'\n | 'image/jpeg'\n | 'image/webp'\n | 'image/gif';\n\n/**\n * An input artifact on a user turn for the agent to read — today a document\n * (a PDF or image, e.g. an invoice to draft a payment from). `data` is the\n * RAW document bytes; the SDK base64-encodes them on the wire.\n */\nexport interface Attachment {\n mediaType: AttachmentMediaType;\n /** raw document bytes (not base64) */\n data: Uint8Array;\n /** optional, for display/audit */\n filename?: string;\n}\n\n/**\n * One turn of an agent conversation.\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n /**\n * Input artifacts attached to this turn for the agent to investigate.\n * Attachments ride only on the turn they are passed; they are NOT\n * persisted in the transcript.\n */\n attachments?: Attachment[];\n}\n\n/**\n * The agent's response to one user message.\n */\nexport interface ConversationTurn {\n /**\n * The agent's conversational text — a clarifying question or a\n * confirmation. May be empty when only proposals are returned.\n */\n reply: string;\n /**\n * The reviewable action series, present once the agent reaches high\n * confidence. Accept it via the instructions flow.\n */\n proposals: AgenticProposal[];\n /** Whether the agent drafted proposals this turn. */\n hasProposals: boolean;\n /**\n * Machine-actionable reasons the turn could not complete — for YOUR\n * application, not the customer. `reply` says the same thing in prose,\n * which software cannot branch on: \"extend the limit to cover Priya\",\n * \"I need her bank details\" and \"that rail is not supported\" all arrive\n * as some text.\n *\n * These ACCOMPANY proposals rather than replacing them, and routinely do.\n * The common case is a payee who does not exist yet: the turn proposes\n * creating them AND reports that the limit will not reach them, because\n * you have to do both, in that order — accept the proposal so the payee\n * has an id, then amend the limit to include it. Never treat proposals\n * and blockers as alternatives.\n *\n * Empty when nothing blocked the turn. Always switch on `code` and ignore\n * codes you do not know; new ones are added over time.\n */\n blockers: AgenticBlocker[];\n /** Whether the turn reported any blocker. */\n hasBlockers: boolean;\n /**\n * The boundary screen's verdict for this turn: `\"ok\"` (normal), `\"warned\"`\n * (off-topic — the customer was warned), or `\"blocked\"` (the chat is\n * terminated; stop serving and offer a fresh conversation). Empty when\n * the platform sent none.\n */\n conversationStatus: string;\n}\n\n/** Options for an {@link AgentConversation}. */\nexport interface AgentConversationOptions {\n /**\n * The customer's IANA timezone (e.g. `'America/Los_Angeles'`).\n *\n * When set, the agent resolves every relative date (\"tomorrow\", \"Friday\")\n * and clock time (\"10 am\") in THIS zone: a date without a time is drafted\n * for 10:00 local, and a time without a date means its next local\n * occurrence. Left unset, times resolve as UTC and the agent says so when a\n * specific clock time matters.\n *\n * The conversation resends it on every turn, since the endpoint is\n * stateless. Note the zone's UTC offset is captured at drafting time, so a\n * DST transition before a far-future fire date shifts it by the DST delta.\n */\n timezone?: string;\n\n /**\n * Deadline (ms) for each turn of this conversation.\n *\n * Turns default to {@link AGENTIC_MODEL_TIMEOUT_MS}, which is sized for a\n * multi-payee drafting turn. Set this when your own turns are longer (a\n * very large payee list) or shorter (you would rather show the customer a\n * failure than keep them waiting).\n *\n * Required if the client was built with an explicit `timeout`: that\n * choice wins over the endpoint default, so a client configured with a\n * short global deadline will cut turns off unless you raise it here.\n */\n timeout?: number;\n\n /**\n * Per-turn `client_policy` override — the vocabulary and payout\n * constraints the agent drafts under.\n *\n * This is a DEVELOPMENT override. It wins for the turns of this\n * conversation and the server logs that it did. For production, register\n * the policy once with `client.agenticPolicy.set(clientId, policy)`\n * instead: forgetting to pass it here fails SILENTLY — the agent simply\n * narrates in the platform's nouns again, with no error anywhere.\n *\n * Resolution per request is: a non-empty policy here, else the client's\n * registration, else platform defaults.\n */\n clientPolicy?: AgenticClientPolicy;\n}\n\n/**\n * A stateful, multi-turn proposals chat with one agent.\n *\n * Keeps the running transcript, appends each user message and the agent's\n * reply, and resends the whole transcript on every {@link send} — so\n * callers never deal with the stateless endpoint's \"send all history each\n * time\" contract.\n *\n * For a stateless backend (one HTTP request per chat message), persist\n * {@link messages} between requests and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\nexport class AgentConversation {\n private readonly client: DakotaClient;\n private readonly paymentAgentId: string;\n private readonly timezone?: string;\n private readonly timeout?: number;\n private readonly clientPolicy?: AgenticClientPolicy;\n private history: ChatMessage[] = [];\n\n constructor(\n client: DakotaClient,\n paymentAgentId: string,\n history?: ChatMessage[],\n options?: AgentConversationOptions\n ) {\n this.client = client;\n this.paymentAgentId = paymentAgentId;\n this.timezone = options?.timezone;\n this.timeout = options?.timeout;\n this.clientPolicy = options?.clientPolicy;\n if (history && history.length > 0) {\n this.history = history.map(cloneMessage);\n }\n }\n\n /**\n * Adds the user's message to the transcript, asks the agent, records the\n * agent's reply, and returns the turn. When `hasProposals` is true the\n * agent has drafted a reviewable action series; otherwise `reply` holds\n * its next question.\n *\n * On error the optimistic user turn is rolled back, so the caller may\n * retry the same call without duplicating it.\n */\n async send(userMessage: string): Promise<ConversationTurn> {\n return this.sendWithAttachments(userMessage);\n }\n\n /**\n * {@link send} with documents (e.g. an invoice PDF) attached to the user\n * turn for the agent to read and draft payments from. Same turn semantics\n * and rollback-on-error behavior as `send`. Attachments ride only on the\n * turn they are passed; the stateless transcript keeps the agent's text\n * reply, so a follow-up turn relies on that summary rather than re-sending\n * the document.\n */\n async sendWithAttachments(\n userMessage: string,\n attachments?: Attachment[]\n ): Promise<ConversationTurn> {\n const hasAttachments = attachments !== undefined && attachments.length > 0;\n this.history.push({\n role: 'user',\n content: userMessage,\n ...(hasAttachments ? { attachments } : {}),\n });\n\n const messages = this.history.map(serializeMessage);\n\n // Attachments ride only on THIS request: they are serialized into\n // `messages` above, then dropped from the stored transcript so they are\n // neither persisted via messages() / resumeAgentConversation nor\n // re-sent on later turns.\n if (hasAttachments) {\n const last = this.history[this.history.length - 1];\n if (last) {\n delete last.attachments;\n }\n }\n\n let result: AgenticProposalsResult;\n try {\n result = await this.client.paymentAgents.createProposals(\n this.paymentAgentId,\n {\n messages,\n // Resent on EVERY turn — the endpoint is stateless, so a zone given\n // once would be forgotten on the next one. Same for the policy\n // override: an omitted one silently falls back to the client's\n // registration (or platform defaults).\n ...(this.timezone ? { timezone: this.timezone } : {}),\n ...(this.clientPolicy ? { client_policy: this.clientPolicy } : {}),\n },\n this.timeout !== undefined ? { timeout: this.timeout } : undefined\n );\n } catch (err) {\n // Roll back the optimistic user turn so a retry does not duplicate it.\n this.history.pop();\n throw err;\n }\n\n const turn: ConversationTurn = {\n reply: result.reply ?? '',\n proposals: result.proposals ? [...result.proposals] : [],\n hasProposals: !!result.proposals && result.proposals.length > 0,\n blockers: result.blockers ? [...result.blockers] : [],\n hasBlockers: !!result.blockers && result.blockers.length > 0,\n conversationStatus: result.conversation_status ?? '',\n };\n\n // Record an assistant turn so the transcript keeps alternating — the\n // platform (and the underlying model) reject two consecutive user\n // turns. Fall back to a placeholder when the agent returned only\n // proposals with no reply text.\n let assistant = turn.reply;\n if (!assistant) {\n assistant = turn.hasProposals ? '(drafted proposals for your review)' : '(no reply)';\n }\n this.history.push({ role: 'assistant', content: assistant });\n\n return turn;\n }\n\n /**\n * A copy of the full transcript so far. Persist this between requests in\n * a stateless backend and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\n messages(): ChatMessage[] {\n return this.history.map(cloneMessage);\n }\n}\n\nfunction cloneMessage(m: ChatMessage): ChatMessage {\n const out: ChatMessage = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => ({ ...a }));\n }\n return out;\n}\n\nfunction serializeMessage(m: ChatMessage): {\n role: 'user' | 'assistant';\n content: string;\n attachments?: {\n type: 'document';\n document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n };\n }[];\n} {\n const out: ReturnType<typeof serializeMessage> = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => {\n const document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n } = {\n media_type: a.mediaType,\n data: Buffer.from(a.data).toString('base64'),\n };\n if (a.filename) {\n document.filename = a.filename;\n }\n return { type: 'document' as const, document };\n });\n }\n return out;\n}\n","/**\n * High-level agentic helpers: collapse the multi-step, crypto-heavy hosted-\n * agent flows into single calls with good defaults, so a partner integration\n * stays short. The raw operations remain reachable via the resource classes\n * on `DakotaClient`.\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport type { DakotaClient } from '../client/client.js';\n\n/**\n * Grant a principal — a user OR an agent, both are just signers — permission\n * to spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet: the group whose attached policies should govern it.\n *\n * That membership change is the whole operation, and it is UNENDORSED: group\n * membership is a client-admin action, not a wallet endorsement, so it needs\n * NO signature — not from the wallet owner, not from the principal being\n * added. From then on the principal's transactions are subject to exactly\n * the policies bound to `spendingGroupId`, the same as any other member of\n * that group. The per-payment spend bound remains the agentic mandate gate,\n * not the policy.\n *\n * Deliberately reuses the wallet's pre-built policies and creates NO\n * per-signer policy. Two policy-engine realities make a per-signer policy\n * the wrong tool: a policy → wallet attach is endorsed by the policy's OWN\n * signer group (so only that group's key could attach it), and an\n * unconditional approval-threshold ALLOW policy inverts to a deny for any\n * transaction its group didn't sign, so a second signer's policy would veto\n * the first. Prepare the wallet's groups + policies in advance and point\n * each principal at the group whose constraints you want it to inherit.\n *\n * Idempotent: if the signer is already a member, returns\n * `alreadyMember: true` and makes no write. Rejects `spendingGroupId` if it\n * is not attached to `walletId`, so a wrong group fails loudly instead of\n * silently granting nothing.\n *\n * The key must already exist as a signer resource — the add endpoint takes\n * a `member_key` reference, it does not register keys. A hosted agent's key\n * is minted by `paymentAgents.create`; for a bare user key, register it\n * first (`POST /signers`) or the add fails with a signer-not-found error.\n *\n * @param client - Dakota client\n * @param walletId - The wallet the principal will spend from\n * @param signerPublicKey - The principal's registered signer public key\n * (base64 PKIX) — e.g. `signer_public_key` returned by\n * `paymentAgents.create` for a hosted agent\n * @param spendingGroupId - The signer group whose attached policies should\n * govern the principal; must already be attached to `walletId`\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID — the\n * platform rejects other formats with 400) to make the WHOLE helper\n * safely retryable — a crashed or partitioned call replayed with the\n * same key dedupes the underlying write server-side. Defaults to a\n * fresh random UUID per call.\n * @returns `{ alreadyMember }` — true when the signer was already a member\n * (no write performed)\n */\nexport async function attachUserToWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ alreadyMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Idempotency: skip the add if the signer's key is already a member.\n const group = await client.signerGroups.get(spendingGroupId);\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n return { alreadyMember: true };\n }\n }\n\n // Add the signer to the group (unendorsed). Granting spend permission is\n // security-relevant, so set an explicit idempotency key rather than depend\n // on transport config (`automaticIdempotency: false` would otherwise send\n // this POST without the required header and 400).\n await client.signerGroups.addSigner(\n spendingGroupId,\n { member_key: signerPublicKey },\n { idempotencyKey: options?.idempotencyKey ?? randomUUID() }\n );\n return { alreadyMember: false };\n}\n\n/**\n * Revoke a principal's spend permission by removing its signer from\n * `spendingGroupId` — the inverse of {@link attachUserToWallet}, and\n * likewise UNENDORSED (no signature).\n *\n * Deliberately SCOPED to the one group you pass, NOT a sweep across every\n * group on the wallet, for two reasons:\n * - signer groups are NOT wallet-exclusive — the same group can govern\n * multiple wallets — so removing a signer from a group revokes it on\n * EVERY wallet that group governs; passing one explicit group keeps\n * that blast radius known instead of multiplying it across all of the\n * wallet's groups;\n * - a sweep cannot tell \"added for this agent\" from \"belongs here for\n * another reason\" (e.g. the human owner sitting in the admin group),\n * so it can lock out a legitimate member.\n *\n * Pass the same group you used to attach. Idempotent: if the signer isn't\n * a member, it is a no-op (`wasMember: false`). Rejects `spendingGroupId`\n * if it is not attached to `walletId`.\n *\n * NOTE: this does not guard against removing a group's LAST member —\n * emptying the group that governs a wallet can leave it with no authorized\n * signer. The caller must avoid stranding the wallet. For a hosted agent,\n * prefer `paymentAgents.revoke` (it destroys the agent's key, so the signer\n * can authorize nothing even while still listed) and use this for\n * membership hygiene.\n *\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID) to\n * make the WHOLE helper safely retryable across crashes/partitions;\n * defaults to a fresh random UUID per call.\n */\nexport async function detachUserFromWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ wasMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Resolve the signer's public key → its resource id within the group: the\n // delete endpoint addresses members by id, not key. Absent ⇒ idempotent\n // no-op.\n const group = await client.signerGroups.get(spendingGroupId);\n let signerId = '';\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n signerId = member.id ?? '';\n break;\n }\n }\n if (!signerId) {\n return { wasMember: false };\n }\n\n // The platform requires an idempotency key on this DELETE. The transport\n // now injects one on DELETEs too, but revoking spend permission is\n // security-relevant, so we set one explicitly — this path must not depend\n // on transport configuration.\n await client.signerGroups.removeSigner(spendingGroupId, signerId, {\n idempotencyKey: options?.idempotencyKey ?? randomUUID(),\n });\n return { wasMember: true };\n}\n\n/**\n * Errors unless `spendingGroupId` is one of the signer groups attached to\n * `walletId` — so attach/detach can't silently operate on a group that has\n * nothing to do with the named wallet.\n *\n * Uses the symmetric group → wallets read (`GET /signer-groups/{id}/wallets`)\n * because it returns a bare array with a stable shape. Semantically\n * equivalent to `GET /wallets/{id}/signer-groups`; the check succeeds iff\n * the pair is attached.\n */\nasync function requireGroupOnWallet(\n client: DakotaClient,\n walletId: string,\n spendingGroupId: string\n): Promise<void> {\n const wallets = await client.signerGroups.getWallets(spendingGroupId);\n for (const w of wallets) {\n if (w.id === walletId) {\n return;\n }\n }\n throw new Error(`signer group ${spendingGroupId} is not attached to wallet ${walletId}`);\n}\n","/**\n * Dakota Platform API Client.\n */\n\nimport { DakotaClientConfig, ResolvedConfig, resolveConfig } from './config.js';\nimport { Transport } from './transport.js';\nimport {\n CustomersResource,\n RecipientsResource,\n DestinationsResource,\n AccountsResource,\n TransactionsResource,\n AutoTransactionsResource,\n WalletsResource,\n EventsResource,\n ApplicationsResource,\n PoliciesResource,\n SignerGroupsResource,\n SignersResource,\n ApiKeysResource,\n UsersResource,\n WebhooksResource,\n InfoResource,\n SandboxResource,\n SelfServeResource,\n FeePayoutDestinationResource,\n PaymentAgentsResource,\n InstructionsResource,\n MandatesResource,\n ScheduledPaymentsResource,\n InsightsResource,\n AgenticPolicyResource,\n} from './resources/index.js';\nimport {\n AgentConversation,\n type AgentConversationOptions,\n type ChatMessage,\n} from '../agentic/chat.js';\nimport {\n attachUserToWallet as attachUserToWalletHelper,\n detachUserFromWallet as detachUserFromWalletHelper,\n} from '../agentic/wallets.js';\n\n/**\n * Dakota Platform API Client.\n *\n * The main entry point for interacting with the Dakota Platform API.\n *\n * @example\n * ```typescript\n * import { DakotaClient, Environment } from 'dakota-ts-sdk';\n *\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * environment: Environment.Sandbox, // default\n * });\n *\n * // List customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // Create a customer\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customer_type: 'business',\n * });\n * ```\n */\nexport class DakotaClient {\n private readonly config: ResolvedConfig;\n private readonly transport: Transport;\n\n // API Resources\n /** Customers API - manage customer records and KYB */\n readonly customers: CustomersResource;\n /** Recipients API - manage payment recipients */\n readonly recipients: RecipientsResource;\n /** Destinations API - manage bank accounts and crypto wallets */\n readonly destinations: DestinationsResource;\n /** Accounts API - manage on-ramp, off-ramp, and swap accounts */\n readonly accounts: AccountsResource;\n /** Transactions API - manage one-off transactions */\n readonly transactions: TransactionsResource;\n /** Auto Transactions API - manage automated transactions */\n readonly autoTransactions: AutoTransactionsResource;\n /** Wallets API - manage non-custodial wallets */\n readonly wallets: WalletsResource;\n /** Events API - query platform events */\n readonly events: EventsResource;\n /** Applications API - manage KYB applications */\n readonly applications: ApplicationsResource;\n /** Policies API - manage transaction policies */\n readonly policies: PoliciesResource;\n /** Signer Groups API - manage multi-sig signer groups */\n readonly signerGroups: SignerGroupsResource;\n /** Signers API - manage individual signers */\n readonly signers: SignersResource;\n /** API Keys API - manage API keys */\n readonly apiKeys: ApiKeysResource;\n /** Users API - manage platform users */\n readonly users: UsersResource;\n /** Webhooks API - manage webhook targets and events */\n readonly webhooks: WebhooksResource;\n /** Info API - query platform capabilities */\n readonly info: InfoResource;\n /** Sandbox API - testing simulations (sandbox only) */\n readonly sandbox: SandboxResource;\n /** Self-Serve Credits API - manage prepaid transfer credits */\n readonly selfServe: SelfServeResource;\n /** Fee Payout Destination API - where Dakota pays your accrued developer fees */\n readonly feePayoutDestination: FeePayoutDestinationResource;\n /** Payment Agents API (ALPHA) - hosted signing agents that draft payments */\n readonly paymentAgents: PaymentAgentsResource;\n /** Instructions API (ALPHA) - accept and inspect actuated proposals */\n readonly instructions: InstructionsResource;\n /** Mandates API (ALPHA) - the §8 authorizations that arm scheduled payments */\n readonly mandates: MandatesResource;\n /** Scheduled Payments API (ALPHA) - schedule rows created from instructions */\n readonly scheduledPayments: ScheduledPaymentsResource;\n /** Insights API (ALPHA) - read-only advisory reporting over agentic activity */\n readonly insights: InsightsResource;\n /** Agentic Policy API (ALPHA) - register the vocabulary the agent speaks for your product */\n readonly agenticPolicy: AgenticPolicyResource;\n\n /**\n * Create a new Dakota client.\n *\n * @param config - Client configuration\n * @throws ConfigurationError if configuration is invalid\n *\n * @example\n * ```typescript\n * // Basic usage (sandbox)\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * });\n *\n * // Production\n * const client = new DakotaClient({\n * apiKey: 'your_production_api_key',\n * environment: Environment.Production,\n * });\n *\n * // With custom configuration\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * timeout: 30000,\n * retryPolicy: {\n * maxAttempts: 5,\n * initialBackoffMs: 100,\n * maxBackoffMs: 5000,\n * },\n * logger: console,\n * });\n * ```\n */\n constructor(config: DakotaClientConfig) {\n this.config = resolveConfig(config);\n this.transport = new Transport(this.config);\n\n // Initialize resources\n this.customers = new CustomersResource(this.transport);\n this.recipients = new RecipientsResource(this.transport);\n this.destinations = new DestinationsResource(this.transport);\n this.accounts = new AccountsResource(this.transport);\n this.transactions = new TransactionsResource(this.transport);\n this.autoTransactions = new AutoTransactionsResource(this.transport);\n this.wallets = new WalletsResource(this.transport);\n this.events = new EventsResource(this.transport);\n this.applications = new ApplicationsResource(this.transport);\n this.policies = new PoliciesResource(this.transport);\n this.signerGroups = new SignerGroupsResource(this.transport);\n this.signers = new SignersResource(this.transport);\n this.apiKeys = new ApiKeysResource(this.transport);\n this.users = new UsersResource(this.transport);\n this.webhooks = new WebhooksResource(this.transport);\n this.info = new InfoResource(this.transport);\n this.sandbox = new SandboxResource(this.transport);\n this.selfServe = new SelfServeResource(this.transport);\n this.feePayoutDestination = new FeePayoutDestinationResource(this.transport);\n this.paymentAgents = new PaymentAgentsResource(this.transport);\n this.instructions = new InstructionsResource(this.transport);\n this.mandates = new MandatesResource(this.transport);\n this.scheduledPayments = new ScheduledPaymentsResource(this.transport);\n this.insights = new InsightsResource(this.transport);\n this.agenticPolicy = new AgenticPolicyResource(this.transport);\n }\n\n // ==========================================================================\n // Agentic Payments high-level helpers (ALPHA)\n //\n // Collapse the multi-step, crypto-heavy hosted-agent flows into single\n // calls with good defaults. The raw operations remain reachable via\n // `signerGroups.addSigner` / `signerGroups.removeSigner` and friends.\n // ==========================================================================\n\n /**\n * Start a fresh multi-turn conversation with a payment agent.\n *\n * Pass `{ timezone }` (an IANA zone) so the agent resolves \"tomorrow\" and\n * \"10 am\" in the customer's local time rather than UTC. The conversation\n * resends it on every turn.\n *\n * @see AgentConversation\n */\n newAgentConversation(\n paymentAgentId: string,\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, undefined, options);\n }\n\n /**\n * Rebuild a conversation from a persisted transcript (oldest first) —\n * for backends that store the history between requests.\n *\n * A stateless backend must pass `{ timezone }` again here: the transcript\n * carries the messages, not the zone.\n */\n resumeAgentConversation(\n paymentAgentId: string,\n history: ChatMessage[],\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, history, options);\n }\n\n /**\n * Grant a principal (user or agent — both are just signers) permission to\n * spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet. Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see attachUserToWallet in `agentic/wallets.ts` for the full contract.\n */\n attachUserToWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ alreadyMember: boolean }> {\n return attachUserToWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Revoke a principal's spend permission by removing its signer from the\n * given signer group — the inverse of {@link attachUserToWallet}.\n * Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see detachUserFromWallet in `agentic/wallets.ts` for the full contract.\n */\n detachUserFromWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ wasMember: boolean }> {\n return detachUserFromWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Get the resolved base URL.\n */\n get baseURL(): string {\n return this.config.baseURL;\n }\n}\n","/**\n * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.\n *\n * A payload canonicalized here matches the platform's `enc.C14nJSON`\n * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a\n * signature produced from the result verifies server-side.\n *\n * This implementation covers the value shapes the SDK ever puts into a\n * signed payload: nulls, booleans, finite integers/floats, strings,\n * arrays, and plain object maps. It intentionally does NOT handle\n * non-integer numbers with fractional parts differently from\n * JSON.stringify, because every mandate/endorsement payload the SDK\n * produces uses only integers, strings, arrays, and object maps — decimal\n * amounts are always sent as strings.\n */\n\n/**\n * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.\n *\n * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a\n * circular reference — any of which cannot be encoded to canonical JSON.\n */\nexport function canonicalJSON(value: unknown): string {\n return canonicalize(value);\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonical JSON: non-finite number ${value}`);\n }\n // JSON.stringify already emits ES6 Number.prototype.toString() for\n // finite numbers, which is exactly what RFC 8785 § 3.2.2.3 mandates.\n return JSON.stringify(value);\n }\n if (typeof value === 'string') {\n // JSON.stringify handles JSON escape sequences per RFC 8259, matching\n // JCS's string-escape rules (§ 3.2.2.2).\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n // BigInts have no unambiguous number representation for JSON;\n // fail loudly rather than produce bytes that won't verify.\n throw new TypeError('canonical JSON: bigint values are not supported');\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => canonicalize(item));\n return `[${parts.join(',')}]`;\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // JCS sorts object member keys by their UTF-16 code-unit order,\n // which is exactly what a JavaScript `Array.prototype.sort()` on\n // strings produces (§ 3.2.3).\n const keys = Object.keys(obj).sort();\n const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);\n return `{${parts.join(',')}}`;\n }\n throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);\n}\n","/**\n * §8 mandate signing. Approving (or cancelling) a mandate is not a bare API\n * call: it requires a cryptographic signature over the mandate's canonical\n * bytes, proving the action came from a holder of the registered key. This\n * file reproduces the platform's exact signed payload (RFC 8785 / JCS\n * canonical JSON) and a P-256 signing/verification path, so partners never\n * hand-roll JCS + ECDSA.\n *\n * The canonical bytes a signature covers — matched byte-for-byte with the\n * platform's MandatePayload — are JCS JSON of:\n *\n * {action, id, bound_signer, rule, valid_from, valid_until}\n *\n * signed as base64( ASN.1( ECDSA-P256( SHA-256(payload) ))), with the public\n * key as base64 PKIX (SPKI).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n createSign,\n createVerify,\n generateKeyPairSync,\n KeyObject,\n} from 'node:crypto';\n\nimport type { Mandate, MandateRule } from '../client/types.js';\nimport { canonicalJSON } from './canonicalize.js';\n\n/**\n * The §8 verb a signature authorizes. It is part of the signed payload so\n * an approval and a cancellation can never be each other's replay: a signed\n * cancel must not be byte-identical to a signed approve.\n */\nexport type MandateAction = 'approve' | 'cancel';\n\n/**\n * Produces the §8 signature the platform verifies for a mandate\n * approve/cancel. The caller holds the private key; the SDK never sees it.\n *\n * Implement this over your own key custody (HSM/KMS) for production. For\n * sandbox and tests, `P256MandateSigner` is a ready in-memory implementation.\n */\nexport interface MandateSigner {\n /**\n * The base64 PKIX (SPKI) P-256 public key — the exact form the platform\n * registered for this signer and verifies signatures against.\n */\n publicKeyBase64(): string;\n\n /**\n * Returns a base64 ASN.1 ECDSA signature over SHA-256(payload).\n */\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform signs for one\n * §8 action on a mandate. Build it straight from the mandate as returned by\n * `mandates.get` / `mandates.list` — no server state is needed, and field\n * order is irrelevant (JCS sorts).\n *\n * `valid_from` / `valid_until` are always present in the signed payload\n * (even when zero); the wire omits a zero value, so a missing field\n * canonicalizes to 0 — matching the platform, which signs the int64\n * directly.\n */\nexport function mandateSignPayload(mandate: Mandate, action: MandateAction): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!mandate.rule) {\n throw new Error('mandate has no rule');\n }\n const encoded = canonicalJSON({\n action,\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule: mandate.rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n });\n return new TextEncoder().encode(encoded);\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform verifies for an\n * AMEND — appending version `version`, carrying `rule`, to `mandate`.\n *\n * The approve/cancel bytes are frozen, so amend gets its own payload rather\n * than an extra key on `mandateSignPayload`. It is the same JCS JSON plus one\n * key, `version`:\n *\n * {action: 'amend', id, bound_signer, rule, valid_from, valid_until, version}\n *\n * **`version` is what stops cross-version replay.** Without it, a signature\n * over `{amend, rule R}` would authorize \"make the current rule R\" forever: a\n * customer who signs v2 raising a limit to 20,000 and then v3 lowering it to\n * 5,000 could have the v2 signature replayed as a v4 — a rollback of their own\n * reduction, using their own signature. Binding the exact version number makes\n * each amend signature usable once, at one point in the mandate's history.\n *\n * `rule` is the NEW rule (what the signer is agreeing to), not the outgoing\n * one, and is taken verbatim — the amend endpoint never normalizes it, so the\n * bytes signed here are the bytes the server verifies. Pass the SAME rule\n * object to `mandates.amend`.\n *\n * @param mandate - The mandate as it is NOW (the amend is a compare-and-set on\n * its current version)\n * @param version - The version this amend creates — the mandate's current\n * `version` + 1\n * @param rule - The complete new rule, in canonical form\n */\nexport function mandateAmendSignPayload(\n mandate: Mandate,\n version: number,\n rule: MandateRule\n): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!Number.isInteger(version) || version < 2) {\n throw new Error('amend version must be an integer >= 2 (the version being created)');\n }\n const encoded = canonicalJSON({\n action: 'amend',\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n version,\n });\n return new TextEncoder().encode(encoded);\n}\n\n// ---------------------------------------------------------------------------\n// Endorsed-intent payload helpers.\n// ---------------------------------------------------------------------------\n//\n// Each reproduces, byte-for-byte, the canonical map the platform's policy\n// engine rebuilds to verify the endorsement (its intent reconstruction).\n// The idempotency_key is part of the signed bytes — reuse the SAME key on\n// the corresponding request.\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a signer\n * group to a wallet.\n */\nexport function attachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_group_to_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a policy to\n * a wallet.\n */\nexport function attachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_policy_to_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a signer\n * group from a wallet — the inverse of {@link attachGroupPayload}.\n */\nexport function detachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_group_from_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a policy\n * from a wallet — the inverse of {@link attachPolicyPayload}.\n */\nexport function detachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_policy_from_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to delete a policy.\n */\nexport function deletePolicyPayload(policyId: string, idempotencyKey: string): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'delete_policy',\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to remove a rule from a policy.\n */\nexport function removePolicyRulePayload(\n policyId: string,\n ruleId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'remove_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to update a rule's definition. `updatedDefinition` is the rule definition\n * as a JSON STRING; it is signed opaquely, exactly as sent on the update\n * request.\n */\nexport function updatePolicyRulePayload(\n policyId: string,\n ruleId: string,\n updatedDefinition: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'update_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n updated_definition: updatedDefinition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to add a rule to a policy. `action` (e.g. `\"allow\"`), `ruleType` (e.g.\n * `\"amount_threshold\"`), and `definition` (the rule-type-specific config,\n * in API format) must match the values sent on the add request, or the\n * endorsement won't verify against it.\n */\nexport function addPolicyRulePayload(\n policyId: string,\n action: string,\n ruleType: string,\n definition: Record<string, unknown>,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'add_policy_rule',\n action,\n rule_type: ruleType,\n policy_id: policyId,\n definition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\nfunction textBytes(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n// ---------------------------------------------------------------------------\n// P256MandateSigner — default in-memory signer (sandbox / tests)\n// ---------------------------------------------------------------------------\n\n/**\n * A {@link MandateSigner} holding a P-256 (ES256) private key in memory.\n *\n * Convenient for sandbox and tests; for production, implement\n * {@link MandateSigner} over your own key custody so the private key never\n * lives in the process.\n */\nexport class P256MandateSigner implements MandateSigner {\n private readonly privateKey: KeyObject;\n private readonly publicKey: KeyObject;\n\n private constructor(privateKey: KeyObject, publicKey: KeyObject) {\n this.privateKey = privateKey;\n this.publicKey = publicKey;\n }\n\n /**\n * Generate a fresh P-256 keypair.\n */\n static generate(): P256MandateSigner {\n const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a\n * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.\n */\n static fromPrivateKey(key: KeyObject | string | Uint8Array): P256MandateSigner {\n const privateKey =\n typeof key === 'string' || key instanceof Uint8Array\n ? createPrivateKey({\n key: key as string | Buffer,\n format: typeof key === 'string' ? 'pem' : 'der',\n type: 'pkcs8',\n })\n : key;\n if (privateKey.asymmetricKeyType !== 'ec') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const details = privateKey.asymmetricKeyDetails;\n if (details?.namedCurve !== 'prime256v1') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const publicKey = createPublicKey(privateKey);\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * base64 PKIX (SPKI) public key — pass this as the signer's registered\n * public key at agent creation / mandate approval.\n */\n publicKeyBase64(): string {\n const der = this.publicKey.export({ format: 'der', type: 'spki' });\n return Buffer.from(der).toString('base64');\n }\n\n /**\n * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).\n */\n sign(payload: Uint8Array): string {\n const signer = createSign('SHA256');\n signer.update(payload);\n const sig = signer.sign({ key: this.privateKey, dsaEncoding: 'der' });\n return Buffer.from(sig).toString('base64');\n }\n}\n\n/**\n * Check a base64 ASN.1 signature over SHA-256 of the canonical payload\n * against a base64 PKIX P-256 public key — the platform's exact\n * verification. Exposed so callers (and tests) can self-check a signature\n * before submitting it.\n *\n * @throws if the public key or signature can't be parsed, or the signature\n * does not verify against the payload.\n */\nexport function verifyMandateSignature(\n publicKeyBase64: string,\n payload: Uint8Array,\n signatureBase64: string\n): void {\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({\n key: Buffer.from(publicKeyBase64, 'base64'),\n format: 'der',\n type: 'spki',\n });\n } catch (err) {\n throw new Error(`parse public key: ${(err as Error).message}`);\n }\n if (publicKey.asymmetricKeyType !== 'ec') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n if (publicKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n const verifier = createVerify('SHA256');\n verifier.update(payload);\n const ok = verifier.verify(\n { key: publicKey, dsaEncoding: 'der' },\n Buffer.from(signatureBase64, 'base64')\n );\n if (!ok) {\n throw new Error('signature verification failed');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/environment.ts","../src/client/errors.ts","../src/client/config.ts","../src/client/transport.ts","../src/client/pagination.ts","../src/client/resources/base.ts","../src/client/resources/customers.ts","../src/client/resources/recipients.ts","../src/client/resources/destinations.ts","../src/client/resources/accounts.ts","../src/client/resources/transactions.ts","../src/client/resources/wallets.ts","../src/client/resources/events.ts","../src/client/resources/applications.ts","../src/client/resources/policies.ts","../src/client/resources/signer-groups.ts","../src/client/resources/api-keys.ts","../src/client/resources/users.ts","../src/client/resources/webhooks.ts","../src/client/resources/info.ts","../src/client/resources/legal.ts","../src/client/resources/rd-marketing-fee.ts","../src/client/resources/sandbox.ts","../src/client/resources/self-serve.ts","../src/client/resources/fee-payout-destination.ts","../src/client/resources/payment-agents.ts","../src/client/resources/instructions.ts","../src/client/resources/mandates.ts","../src/client/resources/scheduled-payments.ts","../src/client/resources/insights.ts","../src/client/resources/agentic-policy.ts","../src/agentic/chat.ts","../src/agentic/wallets.ts","../src/client/client.ts","../src/agentic/canonicalize.ts","../src/agentic/sign.ts"],"names":["Environment","AuthMode","RETRYABLE_STATUS_CODES"],"mappings":";;;AAGO,IAAK,WAAA,qBAAAA,YAAAA,KAAL;AAEL,EAAAA,aAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,aAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,aAAA,aAAA,CAAA,GAAc,aAAA;AAEd,EAAAA,aAAA,OAAA,CAAA,GAAQ,OAAA;AARE,EAAA,OAAAA,YAAAA;AAAA,CAAA,EAAA,WAAA,IAAA,EAAA;AAWZ,IAAM,gBAAA,GAAgD;AAAA,EACpD,CAAC,0BAAsB,yCAAA;AAAA,EACvB,CAAC,gCAAyB,iCAAA;AAAA,EAC1B,CAAC,kCAA0B,6CAAA;AAAA,EAC3B,CAAC,sBAAoB;AACvB,CAAA;AAKO,SAAS,kBAAkB,GAAA,EAA0B;AAC1D,EAAA,MAAM,GAAA,GAAM,iBAAiB,GAAG,CAAA;AAChC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,GAAG,CAAA,CAAE,CAAA;AAAA,EAC/C;AACA,EAAA,OAAO,GAAA;AACT;;;ACzBA,IAAM,sBAAA,uBAA6B,GAAA,CAAI,CAAC,KAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAG,CAAC,CA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S,QAAQ,CAAA;AAAA,EAC3C;AACF;AAWO,SAAS,sBAAA,CACd,eAAA,EACA,OAAA,EACA,eAAA,EACM;AACN,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,eAAA,CAAgB;AAAA,MAC1B,GAAA,EAAK,MAAA,CAAO,IAAA,CAAK,eAAA,EAAiB,QAAQ,CAAA;AAAA,MAC1C,MAAA,EAAQ,KAAA;AAAA,MACR,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAsB,GAAA,CAAc,OAAO,CAAA,CAAE,CAAA;AAAA,EAC/D;AACA,EAAA,IAAI,SAAA,CAAU,sBAAsB,IAAA,EAAM;AACxC,IAAA,MAAM,IAAI,MAAM,+CAA+C,CAAA;AAAA,EACjE;AACA,EAAA,IAAI,SAAA,CAAU,oBAAA,EAAsB,UAAA,KAAe,YAAA,EAAc;AAC/D,IAAA,MAAM,IAAI,MAAM,+CAA+C,CAAA;AAAA,EACjE;AACA,EAAA,MAAM,QAAA,GAAW,aAAa,QAAQ,CAAA;AACtC,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,MAAM,KAAK,QAAA,CAAS,MAAA;AAAA,IAClB,EAAE,GAAA,EAAK,SAAA,EAAW,WAAA,EAAa,KAAA,EAAM;AAAA,IACrC,MAAA,CAAO,IAAA,CAAK,eAAA,EAAiB,QAAQ;AAAA,GACvC;AACA,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AACF","file":"index.mjs","sourcesContent":["/**\n * Environment configuration for Dakota Platform API.\n */\nexport enum Environment {\n /** Sandbox environment for testing - no real money moves */\n Sandbox = 'sandbox',\n /** Production environment - real transactions with real money */\n Production = 'production',\n /** Development environment (internal use) */\n Development = 'development',\n /** Local environment (internal use) */\n Local = 'local',\n}\n\nconst ENVIRONMENT_URLS: Record<Environment, string> = {\n [Environment.Sandbox]: 'https://api.platform.sandbox.dakota.xyz',\n [Environment.Production]: 'https://api.platform.dakota.xyz',\n [Environment.Development]: 'https://api.platform.development.dakota.xyz',\n [Environment.Local]: 'http://localhost:6464',\n};\n\n/**\n * Get the base URL for a given environment.\n */\nexport function getEnvironmentURL(env: Environment): string {\n const url = ENVIRONMENT_URLS[env];\n if (!url) {\n throw new Error(`Unknown environment: ${env}`);\n }\n return url;\n}\n","/**\n * Error classes for Dakota SDK.\n */\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Represents a structured Dakota Platform API error response.\n */\nexport class APIError extends Error {\n /** HTTP status code */\n readonly statusCode: number;\n /** Machine-readable error code */\n readonly code: string;\n /** Additional error details */\n readonly details: Record<string, unknown> | null;\n /** Request ID for support tickets */\n readonly requestId: string | null;\n /** Raw response body */\n readonly rawBody: string | null;\n /** Whether this error is safe to retry */\n readonly retryable: boolean;\n /**\n * A plain-language rendition of the problem, written for the END CUSTOMER,\n * when one exists for this error.\n *\n * `message` names request fields and actions so a machine caller can\n * self-correct. This says the same thing without API vocabulary. Show it\n * when relaying an error into a human surface (chat, email, UI), and fall\n * back to `message` when it is null.\n */\n readonly userMessage: string | null;\n /**\n * A link the customer can follow to CLEAR this error, present only on\n * problems with a concrete self-service remedy.\n *\n * Today `terms-not-accepted` returns one, pointing at the hosted flow where\n * the outstanding agreement can be signed. It is token-gated and usable\n * as-is — send the customer to it rather than parsing one out of the\n * message.\n */\n readonly resolutionUrl: string | null;\n\n constructor(\n statusCode: number,\n code: string,\n message: string,\n options?: {\n details?: Record<string, unknown> | null;\n requestId?: string | null;\n rawBody?: string | null;\n userMessage?: string | null;\n resolutionUrl?: string | null;\n }\n ) {\n super(message);\n this.name = 'APIError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = options?.details ?? null;\n this.requestId = options?.requestId ?? null;\n this.rawBody = options?.rawBody ?? null;\n this.retryable = RETRYABLE_STATUS_CODES.has(statusCode);\n this.userMessage = options?.userMessage ?? null;\n this.resolutionUrl = options?.resolutionUrl ?? null;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, APIError);\n }\n }\n\n /**\n * Create an APIError from an HTTP response.\n */\n static async fromResponse(response: Response): Promise<APIError> {\n const requestId = response.headers.get('x-request-id');\n let rawBody: string | null = null;\n let code = `http_${response.status}`;\n let message = response.statusText || 'Unknown error';\n let details: Record<string, unknown> | null = null;\n let userMessage: string | null = null;\n let resolutionUrl: string | null = null;\n\n try {\n rawBody = await response.text();\n const parsed = JSON.parse(rawBody);\n\n // Try ProblemDetails format (RFC 7807)\n if (parsed.type && typeof parsed.type === 'string') {\n // Extract code from type URI fragment (e.g., \"...#invalid-request\")\n const hashIndex = parsed.type.lastIndexOf('#');\n if (hashIndex !== -1) {\n code = parsed.type.substring(hashIndex + 1);\n }\n }\n\n // Use code if directly provided\n if (parsed.code) {\n code = parsed.code;\n }\n\n // Build message from title and detail\n if (parsed.title) {\n message = parsed.title;\n if (parsed.detail) {\n message = `${parsed.title}: ${parsed.detail}`;\n }\n } else if (parsed.message) {\n message = parsed.message;\n } else if (parsed.detail) {\n message = parsed.detail;\n }\n\n // Extract details\n if (parsed.details && typeof parsed.details === 'object') {\n details = parsed.details;\n }\n\n // RFC 9457 extensions. `message` stays the machine-facing rendition;\n // these two are what a human surface should show instead.\n if (typeof parsed.user_message === 'string') {\n userMessage = parsed.user_message;\n }\n if (typeof parsed.resolution_url === 'string') {\n resolutionUrl = parsed.resolution_url;\n }\n } catch {\n // Failed to parse JSON, use defaults\n }\n\n return new APIError(response.status, code, message, {\n details,\n requestId,\n rawBody,\n userMessage,\n resolutionUrl,\n });\n }\n\n override toString(): string {\n if (this.code) {\n return `APIError [${this.statusCode} ${this.code}]: ${this.message}`;\n }\n return `APIError [${this.statusCode}]: ${this.message}`;\n }\n}\n\n/**\n * Represents a transport-level error (network, timeout, etc.).\n */\nexport class TransportError extends Error {\n /** The underlying error that caused this transport error */\n readonly cause: Error | undefined;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'TransportError';\n this.cause = cause;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TransportError);\n }\n }\n\n override toString(): string {\n if (this.cause) {\n return `TransportError: ${this.message} (caused by: ${this.cause.message})`;\n }\n return `TransportError: ${this.message}`;\n }\n}\n\n/**\n * Represents a configuration error.\n */\nexport class ConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigurationError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ConfigurationError);\n }\n }\n}\n","/**\n * Configuration types and validation for Dakota SDK.\n */\n\nimport { Environment, getEnvironmentURL } from './environment.js';\nimport { ConfigurationError } from './errors.js';\n\n/**\n * Authentication mode for API requests.\n */\nexport enum AuthMode {\n /** Automatically select the best auth method based on the endpoint */\n Auto = 'auto',\n /** Always use x-api-key header */\n APIKey = 'api_key',\n /** Always use X-Application-Token header */\n ApplicationToken = 'application_token',\n}\n\n/**\n * Retry policy configuration.\n */\nexport interface RetryPolicy {\n /** Maximum number of attempts including the initial request (default: 3) */\n maxAttempts: number;\n /** Initial backoff delay in milliseconds (default: 200) */\n initialBackoffMs: number;\n /** Maximum backoff delay in milliseconds (default: 2000) */\n maxBackoffMs: number;\n}\n\n/**\n * Logger interface for SDK logging.\n */\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Configuration options for DakotaClient.\n */\nexport interface DakotaClientConfig {\n /** API key for authentication (required unless applicationToken is provided) */\n apiKey?: string;\n /** Application token for authentication (alternative to apiKey) */\n applicationToken?: string;\n /** Target environment (default: Sandbox) */\n environment?: Environment;\n /** Override the base URL (takes precedence over environment) */\n baseURL?: string;\n /** Authentication mode (default: Auto) */\n authMode?: AuthMode;\n /**\n * Request timeout in milliseconds (default: 15000).\n *\n * Setting this explicitly applies it to EVERY request, including the\n * model-backed agentic endpoints that otherwise get a longer default\n * ({@link AGENTIC_MODEL_TIMEOUT_MS}) — so you keep full control, but a\n * global value tuned for fast reads will also cap agent turns. To keep\n * the long agentic default while tightening everything else, leave this\n * unset and pass `{ timeout }` per request instead.\n *\n * Note this is a per-ATTEMPT deadline: with the default retry policy a\n * timing-out request can be attempted up to `retryPolicy.maxAttempts`\n * times, so worst-case wall clock is roughly `timeout × maxAttempts`.\n */\n timeout?: number;\n /** Retry policy configuration */\n retryPolicy?: Partial<RetryPolicy>;\n /** Logger instance */\n logger?: Logger;\n /** Automatically generate idempotency keys for POST requests (default: true) */\n automaticIdempotency?: boolean;\n /** Custom idempotency key generator */\n idempotencyKeyGenerator?: () => string;\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n}\n\n/**\n * Resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n apiKey: string | null;\n applicationToken: string | null;\n baseURL: string;\n authMode: AuthMode;\n timeout: number;\n /**\n * Whether `timeout` came from the caller rather than the default.\n *\n * An explicit timeout is a deliberate choice and wins everywhere. An\n * inherited default does not, so endpoints that know they are slow (the\n * model-backed agentic ones) can raise it without overriding a value the\n * caller actually asked for.\n */\n timeoutWasExplicit: boolean;\n retryPolicy: RetryPolicy;\n logger: Logger;\n automaticIdempotency: boolean;\n idempotencyKeyGenerator: () => string;\n fetch: typeof fetch;\n}\n\n/**\n * Default per-request timeout (ms).\n *\n * Sized for ordinary CRUD reads and writes, which answer in well under a\n * second. It is deliberately NOT the deadline for the agentic endpoints\n * that call a model — see {@link AGENTIC_MODEL_TIMEOUT_MS}.\n */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Default per-request timeout (ms) for the agentic endpoints whose work is\n * a sequence of model calls: drafting proposals.\n *\n * A multi-payee drafting turn (\"pay these nine vendors every Friday\")\n * legitimately runs minutes — it reads payees, checks balances, drafts, and\n * revises, each a separate model round. Under the ordinary 15s deadline\n * those turns abort client-side while the server is still working, which\n * reads as flakiness rather than as a deadline: the simple turns finish in\n * time and the complex ones do not.\n *\n * Applies only when the caller did not set `timeout` on the client (an\n * explicit choice always wins) and can be overridden per request.\n */\nexport const AGENTIC_MODEL_TIMEOUT_MS = 180_000;\n\n/**\n * Default retry policy.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialBackoffMs: 200,\n maxBackoffMs: 2000,\n};\n\n/**\n * No-op logger that discards all messages.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for development.\n */\nexport const consoleLogger: Logger = {\n debug: (msg, ...args) => console.debug(`[Dakota SDK] ${msg}`, ...args),\n info: (msg, ...args) => console.info(`[Dakota SDK] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[Dakota SDK] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[Dakota SDK] ${msg}`, ...args),\n};\n\n/**\n * Generate a UUID v4 for idempotency keys.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Validate and resolve configuration with defaults.\n */\nexport function resolveConfig(config: DakotaClientConfig): ResolvedConfig {\n const authMode = config.authMode ?? AuthMode.Auto;\n\n // Validate authentication\n if (authMode === AuthMode.Auto) {\n if (!config.apiKey && !config.applicationToken) {\n throw new ConfigurationError('API key or application token is required');\n }\n } else if (authMode === AuthMode.APIKey) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required when using AuthMode.APIKey');\n }\n } else if (authMode === AuthMode.ApplicationToken) {\n if (!config.applicationToken) {\n throw new ConfigurationError(\n 'Application token is required when using AuthMode.ApplicationToken'\n );\n }\n }\n\n // Resolve base URL\n let baseURL: string;\n if (config.baseURL) {\n baseURL = config.baseURL.replace(/\\/$/, ''); // Remove trailing slash\n // Validate URL\n try {\n new URL(baseURL);\n } catch {\n throw new ConfigurationError('Invalid base URL');\n }\n } else {\n const env = config.environment ?? Environment.Sandbox;\n baseURL = getEnvironmentURL(env);\n }\n\n // Validate timeout\n const timeoutWasExplicit = config.timeout !== undefined;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n if (timeout <= 0) {\n throw new ConfigurationError('Timeout must be greater than zero');\n }\n\n // Resolve retry policy\n const retryPolicy: RetryPolicy = {\n maxAttempts: config.retryPolicy?.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n initialBackoffMs: config.retryPolicy?.initialBackoffMs ?? DEFAULT_RETRY_POLICY.initialBackoffMs,\n maxBackoffMs: config.retryPolicy?.maxBackoffMs ?? DEFAULT_RETRY_POLICY.maxBackoffMs,\n };\n\n // Validate retry policy\n if (retryPolicy.maxAttempts <= 0) {\n throw new ConfigurationError('Retry max attempts must be greater than zero');\n }\n if (retryPolicy.initialBackoffMs <= 0) {\n throw new ConfigurationError('Retry initial backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs <= 0) {\n throw new ConfigurationError('Retry max backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs < retryPolicy.initialBackoffMs) {\n throw new ConfigurationError('Retry max backoff must be >= initial backoff');\n }\n\n return {\n apiKey: config.apiKey ?? null,\n applicationToken: config.applicationToken ?? null,\n baseURL,\n authMode,\n timeout,\n timeoutWasExplicit,\n retryPolicy,\n logger: config.logger ?? noopLogger,\n automaticIdempotency: config.automaticIdempotency ?? true,\n idempotencyKeyGenerator: config.idempotencyKeyGenerator ?? generateUUID,\n fetch: config.fetch ?? globalThis.fetch,\n };\n}\n","/**\n * HTTP transport layer with retry, authentication, and idempotency.\n */\n\nimport { ResolvedConfig, AuthMode } from './config.js';\nimport { APIError, TransportError } from './errors.js';\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/** HTTP methods that are safe to retry without idempotency key */\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n\n/**\n * HTTP methods that accept an idempotency key. Dakota's spec marks\n * `IdempotencyKeyHeader` as required on every mutating endpoint, so the\n * SDK must forward it for POST, PUT, PATCH, and DELETE. Earlier versions\n * only attached the header on POST and silently dropped it on PUT/PATCH.\n * DELETE is included because the platform's agentic detach endpoints\n * (e.g. DELETE /signer-groups/{id}/signers/{signer_id}) 400 without one.\n */\nconst IDEMPOTENT_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Request options for the transport layer.\n */\nexport interface TransportRequestOptions {\n method: string;\n path: string;\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n signal?: AbortSignal;\n /**\n * Caller-supplied deadline (ms) for this one request. Beats everything —\n * it is the most specific statement of intent available.\n */\n timeout?: number;\n /**\n * The deadline (ms) this ENDPOINT wants when nobody has said otherwise —\n * how long its work actually takes. Used only when the caller passed no\n * per-request timeout AND set no explicit client-wide one, so it can\n * never override a deadline someone deliberately chose.\n */\n endpointTimeout?: number;\n}\n\n/**\n * HTTP transport with retry, auth, and idempotency support.\n */\nexport class Transport {\n private readonly config: ResolvedConfig;\n\n constructor(config: ResolvedConfig) {\n this.config = config;\n }\n\n /**\n * Make an HTTP request with automatic retry and error handling.\n */\n async request<T>(options: TransportRequestOptions): Promise<T> {\n const { method, path, body, query, headers, idempotencyKey, signal } = options;\n\n // Build URL with query parameters\n const url = this.buildURL(path, query);\n\n // Build headers\n const requestHeaders = this.buildHeaders(method, path, headers, idempotencyKey);\n\n // Build request body\n const requestBody = body !== undefined ? JSON.stringify(body) : undefined;\n\n // Execute with retry\n return this.executeWithRetry<T>(\n url,\n {\n method,\n headers: requestHeaders,\n body: requestBody,\n signal,\n },\n this.resolveTimeout(options)\n );\n }\n\n /**\n * Build the full URL with query parameters.\n */\n private buildURL(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): string {\n const url = new URL(path, this.config.baseURL);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n }\n\n /**\n * Build request headers with authentication.\n */\n private buildHeaders(\n method: string,\n path: string,\n customHeaders?: Record<string, string>,\n idempotencyKey?: string\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': 'dakota-ts-sdk/1.0.0',\n ...customHeaders,\n };\n\n // Add authentication header\n this.addAuthHeader(headers, path);\n\n // Add idempotency key for mutating requests (POST, PUT, PATCH).\n if (IDEMPOTENT_METHODS.has(method)) {\n const key =\n idempotencyKey ??\n (this.config.automaticIdempotency ? this.config.idempotencyKeyGenerator() : undefined);\n if (key) {\n headers['x-idempotency-key'] = key;\n }\n }\n\n return headers;\n }\n\n /**\n * Add authentication header based on auth mode and path.\n */\n private addAuthHeader(headers: Record<string, string>, path: string): void {\n // Don't override existing auth headers\n if (headers['x-api-key'] || headers['x-application-token']) {\n return;\n }\n\n const { authMode, apiKey, applicationToken } = this.config;\n\n switch (authMode) {\n case AuthMode.APIKey:\n if (apiKey) {\n headers['x-api-key'] = apiKey;\n }\n break;\n\n case AuthMode.ApplicationToken:\n if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n\n case AuthMode.Auto:\n default:\n // For /applications routes, prefer application token\n if (path.startsWith('/applications') && applicationToken) {\n headers['x-application-token'] = applicationToken;\n } else if (apiKey) {\n headers['x-api-key'] = apiKey;\n } else if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n }\n }\n\n /**\n * Resolve the deadline for one request, most specific intent first:\n *\n * 1. the caller's per-request `timeout`\n * 2. an explicit client-wide `timeout`\n * 3. the endpoint's own default (slow endpoints raise their own)\n * 4. the client-wide default\n *\n * (2) sits above (3) on purpose: a caller who configured a timeout chose\n * it, and an endpoint must not quietly overrule that. (3) exists so the\n * far more common caller — the one who configured nothing — gets a\n * deadline that matches what the endpoint actually does.\n */\n private resolveTimeout(options: TransportRequestOptions): number {\n if (options.timeout !== undefined) {\n return options.timeout;\n }\n if (this.config.timeoutWasExplicit) {\n return this.config.timeout;\n }\n return options.endpointTimeout ?? this.config.timeout;\n }\n\n /**\n * Execute request with exponential backoff retry.\n *\n * `timeout` is per ATTEMPT, not per call: each attempt gets its own\n * deadline, so a request that keeps timing out can take up to\n * `timeout × maxAttempts` before it throws.\n */\n private async executeWithRetry<T>(url: string, init: RequestInit, timeout: number): Promise<T> {\n const { maxAttempts, initialBackoffMs, maxBackoffMs } = this.config.retryPolicy;\n const method = init.method ?? 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Declared outside the try so the catch can tell OUR deadline firing\n // apart from the caller aborting.\n let timedOut = false;\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n\n // Merge signals if provided\n const signal = init.signal\n ? this.mergeAbortSignals(init.signal, controller.signal)\n : controller.signal;\n\n this.logRequest(method, url, attempt);\n\n const response = await this.config.fetch(url, {\n ...init,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n this.logResponse(method, url, response.status, attempt);\n\n // Check for successful response\n if (response.ok) {\n // Handle 204 No Content\n if (response.status === 204) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n // Convert to API error\n const apiError = await APIError.fromResponse(response);\n\n // Check if we should retry\n if (this.shouldRetry(response.status, method, init, attempt)) {\n lastError = apiError;\n const delay = this.calculateBackoff(attempt, response, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Request failed with ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw apiError;\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Handle abort/timeout. Only OUR deadline firing is a timeout — an\n // AbortError from the caller's own signal is a cancellation, and\n // reporting that as \"timed out\" sends people hunting a deadline\n // that never elapsed.\n if (error instanceof Error && error.name === 'AbortError' && timedOut) {\n lastError = new TransportError(\n `Request timed out after ${timeout}ms. ` +\n `This is the SDK's client-side deadline, not a server error — raise it with ` +\n `\\`new DakotaClient({ timeout })\\`, or per call with \\`{ timeout }\\` in the ` +\n `request options. Agent conversations are the usual cause: pass ` +\n `\\`{ timeout }\\` to \\`newAgentConversation\\`.`,\n error\n );\n } else if (error instanceof Error && error.name === 'AbortError') {\n // The caller cancelled. Retrying would re-issue a request they\n // explicitly called off, so this is terminal.\n throw new TransportError('Request aborted by caller', error);\n } else if (error instanceof Error) {\n lastError = new TransportError('Network error', error);\n } else {\n lastError = new TransportError('Unknown error');\n }\n\n // Retry on network errors for safe methods\n if (this.shouldRetryNetworkError(method, init, attempt)) {\n const delay = this.calculateBackoff(attempt, null, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Network error, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw lastError;\n }\n }\n\n // All retries exhausted\n throw lastError ?? new TransportError('Request failed after all retries');\n }\n\n /**\n * Determine if a request should be retried based on status code.\n */\n private shouldRetry(status: number, method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n if (!RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key. PUT/PATCH are already in SAFE_METHODS so they hit\n // the branch above; this catches POST.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Determine if a network error should be retried.\n */\n private shouldRetryNetworkError(method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Calculate backoff delay with jitter.\n */\n private calculateBackoff(\n attempt: number,\n response: Response | null,\n initialBackoffMs: number,\n maxBackoffMs: number\n ): number {\n // Check for Retry-After header\n if (response) {\n const retryAfter = response.headers.get('retry-after');\n if (retryAfter) {\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds)) {\n return seconds * 1000;\n }\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n return Math.max(0, date - Date.now());\n }\n }\n }\n\n // Exponential backoff with jitter (±20%)\n const exponentialDelay = initialBackoffMs * Math.pow(2, attempt - 1);\n const cappedDelay = Math.min(exponentialDelay, maxBackoffMs);\n const jitter = cappedDelay * 0.2 * (Math.random() * 2 - 1);\n return Math.round(cappedDelay + jitter);\n }\n\n /**\n * Merge multiple abort signals.\n */\n private mergeAbortSignals(signal1: AbortSignal, signal2: AbortSignal): AbortSignal {\n const controller = new AbortController();\n\n const abort = () => controller.abort();\n\n signal1.addEventListener('abort', abort);\n signal2.addEventListener('abort', abort);\n\n if (signal1.aborted || signal2.aborted) {\n controller.abort();\n }\n\n return controller.signal;\n }\n\n /**\n * Sleep for the specified duration.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Log outgoing request.\n */\n private logRequest(method: string, url: string, attempt: number): void {\n this.config.logger.debug(\n `Request: ${method} ${url}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n\n /**\n * Log response.\n */\n private logResponse(method: string, url: string, status: number, attempt: number): void {\n this.config.logger.debug(\n `Response: ${method} ${url} -> ${status}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n}\n","/**\n * Pagination utilities with async iterators.\n */\n\n/**\n * Pagination metadata from API responses.\n */\nexport interface PaginationMeta {\n total_count?: number;\n has_more_after?: boolean;\n has_more_before?: boolean;\n}\n\n/**\n * Paginated response structure.\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n meta?: PaginationMeta;\n}\n\n/**\n * Parameters for paginated requests.\n */\nexport interface PaginationParams {\n starting_after?: string;\n ending_before?: string;\n limit?: number;\n}\n\n/**\n * Function to fetch a page of results.\n */\nexport type PageFetcher<T> = (cursor?: string) => Promise<PaginatedResponse<T>>;\n\n/**\n * Function to extract cursor from an item.\n */\nexport type CursorExtractor<T> = (item: T) => string;\n\n/**\n * Default cursor extractor that uses the 'id' field.\n */\nexport function defaultCursorExtractor<T extends { id?: string }>(item: T): string {\n if (!item.id) {\n throw new Error('Item does not have an id field for cursor extraction');\n }\n return item.id;\n}\n\n/**\n * Async iterator for paginated results.\n */\nexport class PaginatedIterator<T> implements AsyncIterable<T> {\n private readonly fetcher: PageFetcher<T>;\n private readonly cursorExtractor: CursorExtractor<T>;\n private cursor: string | undefined;\n private buffer: T[] = [];\n private hasMore = true;\n private started = false;\n\n constructor(fetcher: PageFetcher<T>, cursorExtractor?: CursorExtractor<T>) {\n this.fetcher = fetcher;\n this.cursorExtractor = cursorExtractor ?? (defaultCursorExtractor as CursorExtractor<T>);\n }\n\n /**\n * Implement async iterator protocol.\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: async (): Promise<IteratorResult<T>> => {\n const item = await this.next();\n if (item === null) {\n return { done: true, value: undefined };\n }\n return { done: false, value: item };\n },\n };\n }\n\n /**\n * Get the next item, or null if no more items.\n */\n async next(): Promise<T | null> {\n // If buffer has items, return next one\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n // If no more pages, we're done\n if (!this.hasMore && this.started) {\n return null;\n }\n\n // Fetch next page\n await this.fetchNextPage();\n\n // Return first item from buffer, or null if empty\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n return null;\n }\n\n /**\n * Collect all items into an array.\n */\n async toArray(): Promise<T[]> {\n const items: T[] = [];\n for await (const item of this) {\n items.push(item);\n }\n return items;\n }\n\n /**\n * Get the first item, or null if none.\n */\n async first(): Promise<T | null> {\n return this.next();\n }\n\n /**\n * Fetch the next page of results.\n */\n private async fetchNextPage(): Promise<void> {\n this.started = true;\n\n const response = await this.fetcher(this.cursor);\n this.buffer = response.data ?? [];\n\n // Update cursor for next page\n if (this.buffer.length > 0) {\n const lastItem = this.buffer[this.buffer.length - 1];\n if (lastItem) {\n this.cursor = this.cursorExtractor(lastItem);\n }\n }\n\n // Check if there are more pages\n this.hasMore = response.meta?.has_more_after ?? false;\n }\n}\n\n/**\n * Create a paginated iterator.\n */\nexport function paginate<T>(\n fetcher: PageFetcher<T>,\n cursorExtractor?: CursorExtractor<T>\n): PaginatedIterator<T> {\n return new PaginatedIterator(fetcher, cursorExtractor);\n}\n","/**\n * Base resource class for API resources.\n */\n\nimport { Transport } from '../transport.js';\nimport { PaginatedIterator, paginate, PageFetcher, CursorExtractor } from '../pagination.js';\n\n/**\n * Base class for API resources.\n */\nexport abstract class BaseResource {\n protected readonly transport: Transport;\n\n constructor(transport: Transport) {\n this.transport = transport;\n }\n\n /**\n * Create a paginated iterator for a list endpoint.\n *\n * `inspectMeta` is called with each page's raw `meta` before the page is\n * yielded, for endpoints whose meta says something the caller must act on.\n * Throw from it to fail the page.\n */\n protected paginate<T>(\n path: string,\n params?: Record<string, unknown>,\n cursorExtractor?: CursorExtractor<T>,\n inspectMeta?: (meta: Record<string, unknown> | undefined) => void\n ): PaginatedIterator<T> {\n const fetcher: PageFetcher<T> = async (cursor?: string) => {\n const query: Record<string, string | number | boolean | undefined> = {};\n\n // Add pagination params\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n\n if (cursor) {\n query.starting_after = cursor;\n }\n\n const response = await this.transport.request<\n | {\n data: T[];\n meta?: { has_more_after?: boolean };\n }\n | T[]\n >({\n method: 'GET',\n path,\n query,\n });\n\n // Not every list endpoint returns the `{data, meta}` envelope: a few\n // answer with a BARE ARRAY (GET /mandates and\n // GET /wallets/{id}/signer-groups today). Reading `.data` off those\n // yields undefined, which the old code turned into an empty page —\n // so the iterator finished immediately and the caller saw zero\n // results with no error, for records that plainly exist. Treat an\n // array as one complete page: there is no cursor to follow, so\n // `meta` is absent and `has_more_after` correctly reads false.\n if (Array.isArray(response)) {\n inspectMeta?.(undefined);\n return { data: response, meta: undefined };\n }\n\n inspectMeta?.(response.meta as Record<string, unknown> | undefined);\n\n return {\n data: response.data ?? [],\n meta: response.meta,\n };\n };\n\n return paginate(fetcher, cursorExtractor);\n }\n}\n","/**\n * Customers resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n BulkImportSumsubTokensRequest,\n BulkImportSumsubTokensResponse,\n Customer,\n CustomerCapabilities,\n CustomerCreateRequest,\n CustomerCreateResponse,\n CustomerListParams,\n CustomerPage,\n CustomerReEngagementResponse,\n ImportPersonaTokensRequest,\n ImportPersonaTokensResponse,\n PersonaImportJob,\n PersonaImportJobListParams,\n PersonaImportJobParams,\n PersonaImportJobsPage,\n RequestOptions,\n SubClientSummary,\n UpdateCustomerSubClientRequest,\n} from '../types.js';\n\n/**\n * Customers API resource.\n */\nexport class CustomersResource extends BaseResource {\n /**\n * Create a new customer.\n *\n * Creates a customer record and initiates KYB onboarding.\n * Returns a URL where the customer can complete verification.\n *\n * @param data - Customer creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created customer with KYB onboarding URL\n *\n * @example\n * ```typescript\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customerType: 'business',\n * externalId: 'your-internal-id',\n * });\n *\n * // With custom idempotency key\n * const customer = await client.customers.create(\n * { name: 'Acme Corp', customerType: 'business' },\n * { idempotencyKey: 'create-acme-corp-001' }\n * );\n * console.log(customer.applicationUrl); // KYB onboarding URL\n *\n * // Designate as a sub-client at creation (ENG-2454).\n * // `is_sub_client` can only be set here — a regular customer cannot\n * // be promoted afterwards. Cannot be combined with `sub_client_id`.\n * const subClient = await client.customers.create({\n * name: 'Partner Corp',\n * customer_type: 'business',\n * is_sub_client: true,\n * });\n * ```\n */\n async create(\n data: CustomerCreateRequest,\n options?: RequestOptions\n ): Promise<CustomerCreateResponse> {\n return this.transport.request<CustomerCreateResponse>({\n method: 'POST',\n path: '/customers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List all customers.\n *\n * Returns a paginated async iterator over customer records.\n *\n * @param params - Optional filter and pagination parameters\n * @returns Async iterator of customers\n *\n * @example\n * ```typescript\n * // Iterate through all customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // With filters\n * const active = client.customers.list({ kyb_status: 'active' });\n *\n * // Several statuses at once — one comma-separated string, not an array\n * const needsAttention = client.customers.list({\n * status: 'info_requested,frozen',\n * });\n *\n * // Collect all to array\n * const all = await client.customers.list().toArray();\n * ```\n */\n list(params?: CustomerListParams): PaginatedIterator<Customer> {\n return this.paginate<Customer>('/customers', params);\n }\n\n /**\n * One page of customers, with the per-status counts.\n *\n * {@link list} iterates rows and drops the envelope, so `status_counts` —\n * the counts a dashboard's status header renders — is unreachable through\n * it. This returns the raw page instead: same filters, one request, no\n * iteration.\n *\n * The counts are computed under the same filters but IGNORING the `status`\n * selection, so every chip keeps its count while one of them is the active\n * filter.\n *\n * @param params - The same filters {@link list} accepts\n * @returns One page: rows, pagination meta, and `status_counts`\n *\n * @example\n * ```typescript\n * const page = await client.customers.listPage({ limit: 25 });\n * console.log(page.status_counts?.info_requested ?? 0);\n * for (const customer of page.data) {\n * console.log(customer.name, customer.status);\n * }\n * ```\n */\n async listPage(params?: CustomerListParams): Promise<CustomerPage> {\n const page = await this.transport.request<CustomerPage>({\n method: 'GET',\n path: '/customers',\n query: params as Record<string, string | number | boolean | undefined> | undefined,\n });\n return { ...page, data: page.data ?? [] };\n }\n\n /**\n * Get a customer by ID.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns Customer record\n *\n * @example\n * ```typescript\n * const customer = await client.customers.get('cust_abc123');\n * console.log(customer.kybStatus);\n * ```\n */\n async get(customerId: string): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'GET',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * Delete a customer record.\n *\n * Soft-deletes the customer. Blocked with a 409 if the customer still has\n * associated accounts, or is referenced as a sub-client by another customer.\n *\n * @param customerId - Customer ID (KSUID)\n *\n * @example\n * ```typescript\n * await client.customers.delete('cust_abc123');\n * ```\n */\n async delete(customerId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * List a customer's capabilities and what is still needed to unlock each.\n *\n * Returns the customer's rails (e.g. `international_wire`) with a status and\n * the OUTSTANDING requirements — terms to accept, documents to upload — that\n * gate them. Partner-agnostic: requirements are keyed by an opaque terms id\n * or document type, never a provider or partner name.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns The customer's capabilities and their outstanding requirements\n *\n * @example\n * ```typescript\n * const { capabilities } = await client.customers.getCapabilities(customerId);\n * for (const cap of capabilities) {\n * if (cap.status !== 'action_required') continue;\n * for (const req of cap.requirements) {\n * console.log(`${cap.capability}: ${req.title} → ${req.url}`);\n * }\n * }\n * ```\n */\n async getCapabilities(customerId: string): Promise<CustomerCapabilities> {\n return this.transport.request<CustomerCapabilities>({\n method: 'GET',\n path: `/customers/${customerId}/capabilities`,\n });\n }\n\n /**\n * Mint a fresh application link for re-engaging an APPROVED customer.\n *\n * Issues a new onboarding token for an existing approved customer's\n * application and returns the rebuilt `application_url` — use it when the\n * original token has expired and the customer needs to come back through\n * the hosted flow (e.g. to accept outstanding partner disclosures).\n *\n * @param customerId - Customer ID (KSUID)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The rebuilt application URL\n *\n * @example\n * ```typescript\n * const { application_url } = await client.customers.reEngage(customerId);\n * ```\n */\n async reEngage(\n customerId: string,\n options?: RequestOptions\n ): Promise<CustomerReEngagementResponse> {\n return this.transport.request<CustomerReEngagementResponse>({\n method: 'POST',\n path: `/customers/${customerId}/re-engagement`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update the sub-client association for a customer.\n *\n * Associates or disassociates a customer with a sub-client.\n * Set `sub_client_id` to associate, or set it to `null` to disassociate.\n *\n * @deprecated The sub-client association can only be set when a customer is\n * created (`is_sub_client` / `sub_client_id` on `create`) and can no longer\n * be changed afterwards — this endpoint now returns 400.\n *\n * @param customerId - Customer ID (KSUID)\n * @param data - Sub-client association data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Updated customer record\n *\n * @example\n * ```typescript\n * // Associate customer with a sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: 'cust_sub456',\n * });\n *\n * // Disassociate customer from sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: null,\n * });\n * ```\n */\n async updateSubClient(\n customerId: string,\n data: UpdateCustomerSubClientRequest,\n options?: RequestOptions\n ): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'PATCH',\n path: `/customers/${customerId}/sub-client`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a summary of all sub-clients and their associated customer counts.\n *\n * @returns Array of sub-client summaries\n *\n * @example\n * ```typescript\n * const summaries = await client.customers.getSubClientSummary();\n * for (const summary of summaries) {\n * console.log(`${summary.sub_client_name}: ${summary.customer_count} customers`);\n * }\n * ```\n */\n async getSubClientSummary(): Promise<SubClientSummary[]> {\n const response = await this.transport.request<{ data: SubClientSummary[] }>({\n method: 'GET',\n path: '/customers/sub-client-summary',\n });\n return response.data;\n }\n\n /**\n * Bulk-import customers from Sumsub share tokens.\n *\n * Exchanges one or more Sumsub share tokens for Dakota customers + applications.\n * The response surfaces per-token results — individual tokens can fail while\n * others succeed.\n *\n * @param data - Bulk-import request containing the share tokens to redeem\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Bulk-import summary with per-token results\n *\n * @example\n * ```typescript\n * const result = await client.customers.bulkImportFromSumsubTokens({\n * tokens: ['_act-sbx-jwt-...', '_act-sbx-jwt-...'],\n * });\n * console.log(`Imported ${result.succeeded}/${result.total}`);\n * for (const r of result.results ?? []) {\n * if (!r.success) console.error(r.name, r.error);\n * }\n * ```\n */\n async bulkImportFromSumsubTokens(\n data: BulkImportSumsubTokensRequest,\n options?: RequestOptions\n ): Promise<BulkImportSumsubTokensResponse> {\n return this.transport.request<BulkImportSumsubTokensResponse>({\n method: 'POST',\n path: '/customers/bulk-import-sumsub-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Import customers from Persona Connect share tokens (`cnst_...`).\n *\n * Unlike the Sumsub import, Persona redemption is asynchronous on Persona's\n * side, so this returns a JOB immediately (HTTP 202). Poll\n * `getPersonaImportJob` for per-token results. Up to 5,000 tokens per\n * request — split larger migrations into multiple batches.\n *\n * Tokens are validated and de-duplicated up front, and a skipped token\n * never blocks an accepted one. A `skipped` entry is about the token STRING\n * (malformed, duplicated in the batch, or already imported) — it is never a\n * compliance decision about a person or application.\n *\n * @param data - The share tokens to import\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The queued job, with any tokens that could not be enqueued\n *\n * @example\n * ```typescript\n * const job = await client.customers.importPersonaTokens({\n * tokens: ['cnst_ABC123def456', 'cnst_GHI789jkl012'],\n * });\n * console.log(`${job.accepted}/${job.total} queued as ${job.job_id}`);\n * ```\n */\n async importPersonaTokens(\n data: ImportPersonaTokensRequest,\n options?: RequestOptions\n ): Promise<ImportPersonaTokensResponse> {\n return this.transport.request<ImportPersonaTokensResponse>({\n method: 'POST',\n path: '/customers/import-persona-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List this client's Persona share-token import jobs, newest first.\n *\n * This endpoint pages on its own cursor (`starting_after` + `has_more`), not\n * the standard list envelope, so it returns a single page rather than an\n * async iterator.\n *\n * @param params - Optional `limit` and `starting_after` job-id cursor\n * @returns One page of job summaries plus a `has_more` flag\n *\n * @example\n * ```typescript\n * const { jobs, has_more } = await client.customers.listPersonaImportJobs({ limit: 20 });\n * ```\n */\n async listPersonaImportJobs(params?: PersonaImportJobListParams): Promise<PersonaImportJobsPage> {\n return this.transport.request<PersonaImportJobsPage>({\n method: 'GET',\n path: '/customers/persona-import-jobs',\n query: { ...params },\n });\n }\n\n /**\n * Get a Persona import job's status and its per-token results.\n *\n * Result rows page on a row-index cursor: pass the last row's `index` as\n * `results_after_index` while `has_more_results` is true.\n *\n * @param jobId - Import job ID (`pij_...`)\n * @param params - Optional `results_limit` (1-500) and `results_after_index`\n * @returns Job status, row counts, and one page of result rows\n *\n * @example\n * ```typescript\n * let after: number | undefined;\n * do {\n * const job = await client.customers.getPersonaImportJob(jobId, {\n * results_after_index: after,\n * });\n * for (const row of job.results ?? []) {\n * if (row.state === 'failed') console.error(row.token, row.error);\n * after = row.index;\n * }\n * if (!job.has_more_results) break;\n * } while (true);\n * ```\n */\n async getPersonaImportJob(\n jobId: string,\n params?: PersonaImportJobParams\n ): Promise<PersonaImportJob> {\n return this.transport.request<PersonaImportJob>({\n method: 'GET',\n path: `/customers/persona-import-jobs/${jobId}`,\n query: { ...params },\n });\n }\n}\n","/**\n * Recipients resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Recipient,\n RecipientRequest,\n RecipientUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Recipients API resource.\n */\nexport class RecipientsResource extends BaseResource {\n /**\n * Create a new recipient for a customer.\n *\n * Recipients represent entities that can receive payments.\n *\n * @param customerId - Customer ID\n * @param data - Recipient creation data\n * @returns Created recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.create(customerId, {\n * name: 'Treasury Account',\n * });\n * ```\n */\n async create(\n customerId: string,\n data: RecipientRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'POST',\n path: `/customers/${customerId}/recipients`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List recipients for a customer.\n *\n * @param customerId - Customer ID\n * @param params - Pagination parameters\n * @returns Async iterator of recipients\n *\n * @example\n * ```typescript\n * for await (const recipient of client.recipients.list(customerId)) {\n * console.log(recipient.name);\n * }\n * ```\n */\n list(customerId: string, params?: ListParams): PaginatedIterator<Recipient> {\n return this.paginate<Recipient>(`/customers/${customerId}/recipients`, params);\n }\n\n /**\n * Get a recipient by ID.\n *\n * @param recipientId - Recipient ID\n * @returns Recipient record\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.get(recipientId);\n * ```\n */\n async get(recipientId: string): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'GET',\n path: `/recipients/${recipientId}`,\n });\n }\n\n /**\n * Update a recipient.\n *\n * @param recipientId - Recipient ID\n * @param data - Update data\n * @returns Updated recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.update(recipientId, {\n * name: 'Updated Name',\n * });\n * ```\n */\n async update(\n recipientId: string,\n data: RecipientUpdateRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'PUT',\n path: `/recipients/${recipientId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a recipient.\n *\n * @param recipientId - Recipient ID\n *\n * @example\n * ```typescript\n * await client.recipients.delete(recipientId);\n * ```\n */\n async delete(recipientId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}`,\n });\n }\n}\n","/**\n * Destinations resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Destination,\n DestinationCreateResponse,\n DestinationListParams,\n DestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Destinations API resource.\n */\nexport class DestinationsResource extends BaseResource {\n /**\n * Create a new destination for a recipient.\n *\n * Destinations can be bank accounts (fiat_us / fiat_iban) or crypto\n * wallets (crypto).\n *\n * The platform returns just `{ id }` here (per `IDResponse`), not the\n * full destination object. Call `destinations.list(recipientId)` if\n * you need the rest of the fields.\n *\n * @param recipientId - Recipient ID\n * @param data - Destination creation data\n * @returns `{ id }` of the newly-created destination\n *\n * @example\n * ```typescript\n * // Crypto destination (for on-ramp)\n * const cryptoDest = await client.destinations.create(recipientId, {\n * destination_type: 'crypto',\n * name: 'Treasury USDC',\n * crypto_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f...',\n * network_id: 'ethereum-mainnet',\n * });\n * // → cryptoDest.id\n *\n * // Fiat US destination (for off-ramp)\n * const bankDest = await client.destinations.create(recipientId, {\n * destination_type: 'fiat_us',\n * name: 'Acme Chase Checking',\n * bank_name: 'JPMorgan Chase',\n * account_holder_name: 'Acme Corp',\n * account_number: '000123456789',\n * aba_routing_number: '021000021',\n * account_type: 'checking',\n * });\n * // → bankDest.id\n * ```\n */\n async create(\n recipientId: string,\n data: DestinationRequest,\n options?: RequestOptions\n ): Promise<DestinationCreateResponse> {\n return this.transport.request<DestinationCreateResponse>({\n method: 'POST',\n path: `/recipients/${recipientId}/destinations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List destinations for a recipient.\n *\n * @param recipientId - Recipient ID\n * @param params - Pagination parameters\n * @returns Async iterator of destinations\n *\n * @example\n * ```typescript\n * for await (const dest of client.destinations.list(recipientId)) {\n * console.log(dest);\n * }\n * ```\n */\n list(recipientId: string, params?: DestinationListParams): PaginatedIterator<Destination> {\n return this.paginate<Destination>(\n `/recipients/${recipientId}/destinations`,\n params,\n (item) => item.destination_id\n );\n }\n\n /**\n * Delete a destination.\n *\n * @param recipientId - Recipient ID\n * @param destinationId - Destination ID\n *\n * @example\n * ```typescript\n * await client.destinations.delete(recipientId, destinationId);\n * ```\n */\n async delete(recipientId: string, destinationId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}/destinations/${destinationId}`,\n });\n }\n}\n","/**\n * Accounts resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Account,\n AccountCreateRequest,\n AccountUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/** Account list parameters */\nexport interface AccountListParams extends ListParams {\n /** Account type filter. Required by the API. */\n account_type: 'onramp' | 'offramp' | 'swap';\n customer_id?: string;\n source_network_id?: string;\n destination_network_id?: string;\n destination_asset?: string;\n crypto_destination_id?: string;\n fiat_destination_id?: string;\n}\n\n/**\n * Accounts API resource.\n */\nexport class AccountsResource extends BaseResource {\n /**\n * Create a new account.\n *\n * Accounts define the flow of funds:\n * - **onramp**: USD → crypto (customer sends USD, receives stablecoin)\n * - **offramp**: crypto → USD (customer sends stablecoin, receives USD)\n * - **swap**: crypto → crypto (stablecoin conversion)\n *\n * @param data - Account creation data\n * @returns Created account\n *\n * @example\n * ```typescript\n * // Create an off-ramp account (crypto → USD)\n * const offramp = await client.accounts.create({\n * account_type: 'offramp',\n * customer_id: customerId,\n * fiat_destination_id: bankDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { crypto_address: '0x...' } - customer sends USDC here\n *\n * // Create an on-ramp account (USD → crypto)\n * const onramp = await client.accounts.create({\n * account_type: 'onramp',\n * customer_id: customerId,\n * crypto_destination_id: cryptoDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { bank_account: { bank_name, aba_routing_number, account_number } } - customer sends USD here\n * ```\n *\n * @remarks\n * `max_transactions` caps how many transactions the account may ever\n * create — `1` makes it a one-off. Know what reaching the cap does before\n * you set one: further deposits are **refused, not returned**. The funds\n * still arrive and are then held pending manual intervention, with nothing\n * converted, nothing forwarded, and no transaction on the account for\n * them. Stop sending to the deposit details once the cap is reached.\n */\n async create(data: AccountCreateRequest, options?: RequestOptions): Promise<Account> {\n return this.transport.request<Account>({\n method: 'POST',\n path: '/accounts',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List accounts.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of accounts\n *\n * @example\n * ```typescript\n * // List all accounts\n * for await (const account of client.accounts.list()) {\n * console.log(account);\n * }\n *\n * // Filter by customer\n * const customerAccounts = client.accounts.list({ customer_id: customerId });\n * ```\n */\n list(params?: AccountListParams): PaginatedIterator<Account> {\n return this.paginate<Account>('/accounts', params);\n }\n\n /**\n * Get an account by ID.\n *\n * @param accountId - Account ID\n * @returns Account record\n *\n * @example\n * ```typescript\n * const account = await client.accounts.get(accountId);\n * ```\n */\n async get(accountId: string): Promise<Account> {\n return this.transport.request<Account>({\n method: 'GET',\n path: `/accounts/${accountId}`,\n });\n }\n\n /**\n * Update an account.\n *\n * @param accountId - Account ID\n * @param data - Update data\n * @returns Updated account\n *\n * @example\n * ```typescript\n * const account = await client.accounts.update(accountId, {\n * status: 'inactive',\n * });\n * ```\n */\n async update(\n accountId: string,\n data: AccountUpdateRequest,\n options?: RequestOptions\n ): Promise<Account> {\n return this.transport.request<Account>({\n method: 'PATCH',\n path: `/accounts/${accountId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an account.\n *\n * @param accountId - Account ID\n *\n * @example\n * ```typescript\n * await client.accounts.delete(accountId);\n * ```\n */\n async delete(accountId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/accounts/${accountId}`,\n });\n }\n}\n","/**\n * Transactions resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport { APIError } from '../errors.js';\nimport type {\n OneOffTransaction,\n OneOffTransactionRequest,\n AutoTransaction,\n AutoTransactionListParams,\n TransactionListParams,\n TransactionResourceType,\n WalletTransaction,\n RequestOptions,\n} from '../types.js';\n\n/**\n * The row shape `GET /transactions` yields for a given set of filters.\n *\n * The family decides the shape, so the filters decide the element type: name\n * `wallet` or `auto_account` and you get that family's rows, anything else is\n * the `one_off` family this endpoint defaults to.\n */\nexport type TransactionRowFor<P extends TransactionListParams | undefined> = P extends {\n transaction_type: 'wallet';\n}\n ? WalletTransaction\n : P extends { transaction_type: 'auto_account' }\n ? AutoTransaction\n : OneOffTransaction;\n\n/**\n * Transactions API resource.\n */\nexport class TransactionsResource extends BaseResource {\n /**\n * Create a one-off transaction.\n *\n * One-off transactions allow single transfers without setting up accounts.\n *\n * @param data - Transaction creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.create({\n * customer_id: customerId,\n * amount: '1000.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-mainnet',\n * destination_id: destinationId,\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * payment_reference: 'Invoice #12345',\n * });\n *\n * // With custom idempotency key\n * const tx = await client.transactions.create(\n * { customer_id: customerId, amount: '1000.00', ... },\n * { idempotencyKey: 'invoice-12345-payment' }\n * );\n *\n * console.log(tx.crypto_address); // Send USDC here\n * console.log(tx.status); // Transaction status\n * ```\n */\n async create(\n data: OneOffTransactionRequest,\n options?: RequestOptions\n ): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: '/transactions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List transactions.\n *\n * `GET /transactions` serves three resource families from one path, and the\n * family decides the row shape — so the family you ask for decides what this\n * iterator yields:\n *\n * | `transaction_type` | Yields |\n * |--------------------|--------|\n * | omitted or `'one_off'` | {@link OneOffTransaction} |\n * | `'wallet'` | {@link WalletTransaction} |\n * | `'auto_account'` | {@link AutoTransaction} (requires `customer_id`) |\n *\n * **The family is always named on the wire.** Left to the server, it is\n * INFERRED from the other filters, and `customer_id` on its own infers\n * `auto_account` — so `list({ customer_id })` would return that customer's\n * auto-account transactions while this method's type promised one-off ones.\n * Those rows parse into `OneOffTransaction` with missing fields rather than\n * failing, so nothing surfaced the substitution. Omitting the family here\n * therefore sends `transaction_type=one_off` rather than leaving it open.\n *\n * The family the server reports back (`meta.transaction_type`) is checked\n * against the one requested, and a mismatch throws instead of yielding rows\n * of the wrong shape.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator over the requested family\n *\n * @example\n * ```typescript\n * // One-off transactions (the default family)\n * for await (const tx of client.transactions.list()) {\n * console.log(tx.id, tx.status);\n * }\n *\n * // This customer's ONE-OFF transactions\n * const completed = client.transactions.list({\n * customer_id: customerId,\n * status: 'completed',\n * });\n *\n * // This customer's AUTO-ACCOUNT transactions — a different family,\n * // and a different row shape\n * for await (const tx of client.transactions.list({\n * transaction_type: 'auto_account',\n * customer_id: customerId,\n * })) {\n * console.log(tx.id);\n * }\n *\n * // Wallet transactions\n * const sent = client.transactions.list({\n * transaction_type: 'wallet',\n * wallet_id: walletId,\n * direction: 'out',\n * });\n * ```\n */\n list<P extends TransactionListParams | undefined = undefined>(\n params?: P\n ): PaginatedIterator<TransactionRowFor<P>> {\n // Name the family rather than letting the server infer one. See the doc\n // comment: an inferred family is how `{ customer_id }` came back as\n // auto-account rows typed as one-off ones.\n const requested: TransactionResourceType = params?.transaction_type ?? 'one_off';\n\n return this.paginate<TransactionRowFor<P>>(\n '/transactions',\n { ...params, transaction_type: requested },\n undefined,\n (meta) => assertFamily(meta, requested)\n );\n }\n\n /**\n * Get a transaction by ID.\n *\n * @param transactionId - Transaction ID\n * @returns Transaction record\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.get(transactionId);\n * console.log(tx.status);\n * ```\n */\n async get(transactionId: string): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'GET',\n path: `/transactions/${transactionId}`,\n });\n }\n\n /**\n * Cancel a transaction.\n *\n * Only pending transactions can be cancelled.\n *\n * @param transactionId - Transaction ID\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Cancelled transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.cancel(transactionId);\n * console.log(tx.status); // 'cancelled'\n * ```\n */\n async cancel(transactionId: string, options?: RequestOptions): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: `/transactions/${transactionId}/cancellations`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n\n/**\n * Fail a page whose family is not the one asked for.\n *\n * A POSITIVE mismatch only. An absent `transaction_type` means the response\n * made no claim about its family — older servers and the bare-array list\n * shapes do not send one — and treating silence as a mismatch would turn a\n * backstop into a new way for a working call to fail.\n */\nfunction assertFamily(\n meta: Record<string, unknown> | undefined,\n requested: TransactionResourceType\n): void {\n const served = meta?.transaction_type;\n if (typeof served !== 'string' || served === requested) return;\n\n throw new APIError(\n 200,\n 'transaction_family_mismatch',\n `Asked for ${requested} transactions but the server listed ${served}. ` +\n 'The rows in this page are not the shape this iterator yields, so they ' +\n 'are not returned.',\n { details: { requested, served } }\n );\n}\n\n/**\n * Auto Transactions API resource.\n */\nexport class AutoTransactionsResource extends BaseResource {\n /**\n * List auto transactions.\n *\n * `statuses` and `types` take a comma-separated string, not an array, and\n * `start_date` / `end_date` are Unix epoch SECONDS rather than the ISO\n * strings the other list endpoints take.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of auto transactions\n *\n * @example\n * ```typescript\n * const recent = client.autoTransactions.list({\n * auto_account_id: accountId,\n * statuses: 'pending,processing',\n * start_date: Math.floor(Date.now() / 1000) - 86_400,\n * sort_dir: 'desc',\n * });\n * ```\n */\n list(params?: AutoTransactionListParams): PaginatedIterator<AutoTransaction> {\n return this.paginate<AutoTransaction>('/auto-transactions', params);\n }\n\n /**\n * Get an auto transaction by ID.\n *\n * @param transactionId - Auto transaction ID\n * @returns Auto transaction record\n */\n async get(transactionId: string): Promise<AutoTransaction> {\n return this.transport.request<AutoTransaction>({\n method: 'GET',\n path: `/auto-transactions/${transactionId}`,\n });\n }\n}\n","/**\n * Wallets resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n Wallet,\n WalletCreateRequest,\n WalletBalances,\n WalletTransactionRequest,\n WalletTransaction,\n AttachedPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Wallets API resource.\n */\nexport class WalletsResource extends BaseResource {\n /**\n * Create a new wallet.\n *\n * Creates a non-custodial multi-sig wallet for a customer.\n *\n * @param data - Wallet creation data\n * @returns Created wallet\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.create({\n * customer_id: customerId,\n * family: 'evm',\n * name: 'Treasury Wallet',\n * });\n * console.log(wallet.address);\n * ```\n */\n async create(data: WalletCreateRequest, options?: RequestOptions): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'POST',\n path: '/wallets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a single wallet by ID.\n *\n * @param walletId - Wallet ID\n * @returns Wallet record (includes `customer_name` and `created_at`)\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.get(walletId);\n * console.log(wallet.address, wallet.customer_name);\n * ```\n */\n async get(walletId: string): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'GET',\n path: `/wallets/${walletId}`,\n });\n }\n\n /**\n * Get policies attached to a wallet.\n *\n * Returns slim references (id + name) for the policies currently attached to the wallet.\n *\n * @param walletId - Wallet ID\n * @returns Array of attached policies\n *\n * @example\n * ```typescript\n * const policies = await client.wallets.getPolicies(walletId);\n * for (const policy of policies) {\n * console.log(policy.id, policy.name);\n * }\n * ```\n */\n async getPolicies(walletId: string): Promise<AttachedPolicy[]> {\n return this.transport.request<AttachedPolicy[]>({\n method: 'GET',\n path: `/wallets/${walletId}/policies`,\n });\n }\n\n /**\n * Get wallet balances.\n *\n * Returns the platform's full `WalletBalances` response: the wallet id,\n * its on-chain address, every per-asset balance, and a pre-computed\n * `total_amount_usd` across all assets. The previous return shape\n * (`WalletBalance[]`) silently dropped `address` and `total_amount_usd`,\n * forcing callers to do a second `wallets.get()` and sum the balances\n * by hand. This is a small breaking change with a one-line migration\n * (`balances` → `balances.balances`); the prior shape had been broken\n * since 1.3.x anyway.\n *\n * @param walletId - Wallet ID\n * @returns `{ wallet_id, address, balances, total_amount_usd }`\n *\n * @example\n * ```typescript\n * const { address, total_amount_usd, balances } =\n * await client.wallets.getBalances(walletId);\n * console.log(`${address} → $${total_amount_usd}`);\n * for (const b of balances) {\n * console.log(b.asset.id, b.amount_usd);\n * }\n * ```\n */\n async getBalances(walletId: string): Promise<WalletBalances> {\n // /wallets/{id}/balances returns the WalletBalances object directly\n // ({ wallet_id, address, balances, total_amount_usd }), not the\n // paginated { data, meta } envelope. The 1.3.x impl read\n // response.data here and silently returned undefined; the 1.4.x /\n // 1.5.x impl returned just the balances array, dropping the wrapper\n // fields. Now we return what the platform actually sends.\n return this.transport.request<WalletBalances>({\n method: 'GET',\n path: `/wallets/${walletId}/balances`,\n });\n }\n\n /**\n * Send a transaction from a wallet.\n *\n * The platform expects an **endorsed request** envelope —\n * `{ signatures, intent }` — at this endpoint. Build the\n * `SendTransactionIntent`, canonicalize it per RFC 8785 (JCS), sign\n * with the wallet's signer-group ECDSA P-256 key, base64-encode the\n * DER signature, then post the envelope.\n *\n * @param walletId - Wallet ID\n * @param data - Endorsed wallet transaction request: `{ signatures, intent }`\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * import canonicalize from 'canonicalize';\n * import { createSign, createPrivateKey, randomUUID } from 'node:crypto';\n *\n * const intent = {\n * wallet_id: walletId,\n * caip2: 'eip155:1', // 11155111 for sepolia\n * operation: {\n * kind: 'transfer',\n * from: wallet.address,\n * to: '0x...',\n * amount: '100.00',\n * asset_id: 'USDC',\n * },\n * idempotency_key: randomUUID(),\n * };\n * const canonical = canonicalize(intent)!;\n * const sig = createSign('SHA256').update(canonical).sign({\n * key: createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' }),\n * dsaEncoding: 'der',\n * });\n * const tx = await client.wallets.createTransaction(walletId, {\n * signatures: [sig.toString('base64')],\n * intent,\n * });\n * ```\n *\n * @see https://docs.dakota.xyz/documentation/signing-guide\n */\n async createTransaction(\n walletId: string,\n data: WalletTransactionRequest,\n options?: RequestOptions\n ): Promise<WalletTransaction> {\n return this.transport.request<WalletTransaction>({\n method: 'POST',\n path: `/wallets/${walletId}/transactions`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Events resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type { Event, EventListParams } from '../types.js';\n\n/**\n * Events API resource.\n */\nexport class EventsResource extends BaseResource {\n /**\n * List events.\n *\n * Events track all platform activity and can be used for audit trails.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of events\n *\n * @example\n * ```typescript\n * for await (const event of client.events.list()) {\n * console.log(event.type, event.data);\n * }\n *\n * // Filter by event type\n * const customerEvents = client.events.list({\n * event_type: 'customer.created',\n * });\n * ```\n */\n list(params?: EventListParams): PaginatedIterator<Event> {\n return this.paginate<Event>('/events', params);\n }\n}\n","/**\n * Applications resource (Onboarding/KYB).\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Application,\n ApplicationDocumentUploadRequest,\n ApplicationGetParams,\n ApplicationDocumentUploadUrlRequest,\n ApplicationSubmissionRequest,\n AssociatedIndividual,\n AssociatedIndividualRequest,\n AttestationSubmitRequest,\n BusinessApplicationCreateRequest,\n BusinessDetailsResponse,\n DocumentUploadResponse,\n DocumentUploadUrlResponse,\n EDDRequest,\n EDDWithApplicationID,\n IndividualDetailsResponse,\n IndividualDocumentUploadRequest,\n IndividualDocumentUploadUrlRequest,\n IndividualRequest,\n LegalAcceptanceContext,\n ListParams,\n RequestOptions,\n UploadedDocumentMetadata,\n} from '../types.js';\n\n/** Parameters for listing application documents */\nexport interface DocumentListParams extends ListParams {\n category?: 'business' | 'identity' | 'edd';\n document_type?: string;\n}\n\n/**\n * Applications API resource for KYB onboarding.\n */\nexport class ApplicationsResource extends BaseResource {\n /**\n * List applications.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of applications\n */\n list(params?: ListParams): PaginatedIterator<Application> {\n return this.paginate<Application>('/applications', params);\n }\n\n /**\n * Get an application by ID.\n *\n * `include` inlines extra sections — a comma-separated list of `entities`,\n * `validation`, `edd`, `attestations`, or `all`. Each adds weight, and\n * `'all'` carries the full KYB record including every associated\n * individual's date of birth, nationality and email, so ask for what the\n * page renders.\n *\n * To render an accept-agreements page, use {@link getLegalAcceptance}\n * instead: it returns exactly that page's inputs and none of the personal\n * data.\n *\n * @param applicationId - Application ID\n * @param params - Optional `{ include }`\n * @returns Application record\n *\n * @example\n * ```typescript\n * const app = await client.applications.get(applicationId, {\n * include: 'entities,validation',\n * });\n * ```\n */\n async get(applicationId: string, params?: ApplicationGetParams): Promise<Application> {\n return this.transport.request<Application>({\n method: 'GET',\n path: `/applications/${applicationId}`,\n query: { ...params },\n });\n }\n\n /**\n * Submit an application for review.\n *\n * @param applicationId - Application ID\n * @param data - Submission data\n * @returns Submitted application\n */\n async submit(\n applicationId: string,\n data?: ApplicationSubmissionRequest,\n options?: RequestOptions\n ): Promise<Application> {\n return this.transport.request<Application>({\n method: 'POST',\n path: `/applications/${applicationId}/submissions`,\n body: data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Business Details\n // ==========================================================================\n\n /**\n * Update business details for an application.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param data - Business details (full BusinessApplicationCreateRequest)\n * @returns Updated business details with application context\n */\n async updateBusinessDetails(\n applicationId: string,\n data: BusinessApplicationCreateRequest,\n options?: RequestOptions\n ): Promise<BusinessDetailsResponse> {\n return this.transport.request<BusinessDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/business-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Details (non-business applications)\n // ==========================================================================\n\n /**\n * Update individual details for a non-business application.\n *\n * Uses PUT (full replace) per the OpenAPI spec. Only callable when the\n * application status is 'pending'.\n *\n * @param applicationId - Application ID\n * @param data - Individual details (full IndividualRequest)\n * @returns Updated individual details with application context\n */\n async updateIndividualDetails(\n applicationId: string,\n data: IndividualRequest,\n options?: RequestOptions\n ): Promise<IndividualDetailsResponse> {\n return this.transport.request<IndividualDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/individual-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Associated Individuals\n // ==========================================================================\n\n /**\n * Add an associated individual to an application.\n *\n * @param applicationId - Application ID\n * @param data - Individual data\n * @returns Created individual\n */\n async addIndividual(\n applicationId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update an associated individual.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Full individual data (replaces existing)\n * @returns Updated individual\n */\n async updateIndividual(\n applicationId: string,\n individualId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'PUT',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an associated individual.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n */\n async deleteIndividual(applicationId: string, individualId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n });\n }\n\n // ==========================================================================\n // Attestations\n // ==========================================================================\n\n /**\n * What this application still needs to accept, and who may accept it.\n *\n * Exactly what an accept-agreements page renders, and deliberately nothing\n * more. `get(applicationId)` would answer with the full KYB record — the\n * business entity, and every associated individual's date of birth,\n * nationality and email — none of which that page displays. The link that\n * reaches this endpoint is EMAILED and travels in a URL query string, so its\n * credential is scoped to this call and the attestation submission, and\n * cannot read the application.\n *\n * Authenticates with an Application Token (`X-Application-Token`), including\n * the narrow legal-acceptance token a terms refusal issues.\n *\n * The documents come back as identity only. Fetch the text to display with\n * `client.legal.get(key)`, then pass the `version` you displayed back as\n * `legal_document_version` on {@link submitAttestation}.\n *\n * @param applicationId - Application ID\n * @returns Outstanding agreements, prior acceptances, and permitted attestors\n *\n * @example\n * ```typescript\n * const ctx = await client.applications.getLegalAcceptance(applicationId);\n *\n * for (const doc of ctx.outstanding_documents) {\n * const text = await client.legal.get(doc.key, doc.version);\n * render(text.content);\n * }\n *\n * // A business may have several control persons; an individual application\n * // has exactly one permissible attestor, so there is nobody to pick.\n * const attestor =\n * ctx.application_type === 'individual' ? ctx.attestors[0] : await pick(ctx.attestors);\n * ```\n */\n async getLegalAcceptance(applicationId: string): Promise<LegalAcceptanceContext> {\n return this.transport.request<LegalAcceptanceContext>({\n method: 'GET',\n path: `/applications/${applicationId}/legal-acceptance`,\n });\n }\n\n /**\n * Submit an attestation for an application.\n *\n * Additionally supplying `disclosure_id` (a terms key the provider\n * declared, e.g. `partner_disclosures`) and `disclosure_version` records the\n * attestation as a PARTNER DISCLOSURE acknowledgment instead of a standard\n * onboarding one: acceptance is stamped `customer_online`, the\n * partner-onboarding substatus advances, and an already-approved\n * application is reprovisioned. The API stays partner-agnostic — callers\n * supply a terms key and version, never a partner name. Get the outstanding\n * ones from `customers.getCapabilities(customerId)`.\n *\n * @param applicationId - Application ID\n * @param data - Attestation data (type, timestamp, applicant_id), plus\n * `disclosure_id` + `disclosure_version` to accept a partner disclosure\n */\n async submitAttestation(\n applicationId: string,\n data: AttestationSubmitRequest,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/applications/${applicationId}/attestations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Enhanced Due Diligence (EDD)\n // ==========================================================================\n\n /**\n * Get the EDD record for an application.\n *\n * @param applicationId - Application ID\n * @returns EDD record with application context\n */\n async getEDD(applicationId: string): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'GET',\n path: `/applications/${applicationId}/edd`,\n });\n }\n\n /**\n * Create or update the EDD record for an application.\n *\n * This endpoint is idempotent (uses PUT).\n *\n * @param applicationId - Application ID\n * @param data - EDD data\n * @returns Updated EDD record with application context\n */\n async createOrUpdateEDD(\n applicationId: string,\n data: EDDRequest,\n options?: RequestOptions\n ): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'PUT',\n path: `/applications/${applicationId}/edd`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Application Documents\n // ==========================================================================\n\n /**\n * Upload an application document using base64-encoded content.\n *\n * For files larger than 20MB, use {@link getDocumentUploadUrl} and upload\n * directly to cloud storage, then call {@link verifyDocument}.\n *\n * @param applicationId - Application ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async createDocument(\n applicationId: string,\n data: ApplicationDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List documents for an application.\n *\n * Supports filtering by category and document type.\n *\n * @param applicationId - Application ID\n * @param params - Pagination and filter parameters\n * @returns Paginated iterator of document metadata\n */\n listDocuments(\n applicationId: string,\n params?: DocumentListParams\n ): PaginatedIterator<UploadedDocumentMetadata> {\n return this.paginate<UploadedDocumentMetadata>(\n `/applications/${applicationId}/documents`,\n params\n );\n }\n\n /**\n * Download/get a document by ID.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n * @returns Document content (binary)\n */\n async getDocument(applicationId: string, documentId: string): Promise<unknown> {\n return this.transport.request<unknown>({\n method: 'GET',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Delete a document from a pending application.\n *\n * Only documents from applications in 'pending' status can be deleted.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n */\n async deleteDocument(applicationId: string, documentId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Verify a document uploaded via presigned URL.\n *\n * After uploading a file to the presigned URL from {@link getDocumentUploadUrl},\n * call this endpoint to register and verify the upload.\n *\n * @param applicationId - Application ID\n * @param documentId - The upload_id from the presigned URL response\n * @returns Document upload response with document_id\n */\n async verifyDocument(\n applicationId: string,\n documentId: string,\n _data?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents/${documentId}/verifications`,\n body: _data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an application document.\n *\n * Use this for files larger than 20MB. Upload the file directly to the\n * returned URL, then call {@link verifyDocument} to register it.\n *\n * @param applicationId - Application ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getDocumentUploadUrl(\n applicationId: string,\n data: ApplicationDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Documents\n // ==========================================================================\n\n /**\n * Upload a document for an associated individual using base64-encoded content.\n *\n * Supports identity documents (passport, driver's license, residence permit)\n * and EDD documents (bank statement, etc.). For files larger than 10MB, use\n * {@link getIndividualDocumentUploadUrl} instead.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async uploadIndividualDocument(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an individual document.\n *\n * Use this for files larger than 10MB. Upload the file directly to the\n * returned URL.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getIndividualDocumentUploadUrl(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Policies resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Policy,\n PolicyCreateRequest,\n PolicyRule,\n PolicyRuleCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Policies API resource.\n */\nexport class PoliciesResource extends BaseResource {\n /**\n * Create a new policy.\n *\n * @param data - Policy creation data\n * @returns Created policy\n */\n async create(data: PolicyCreateRequest, options?: RequestOptions): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'POST',\n path: '/policies',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List policies.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of policies\n */\n list(params?: ListParams): PaginatedIterator<Policy> {\n return this.paginate<Policy>('/policies', params);\n }\n\n /**\n * Get a policy by ID.\n *\n * @param policyId - Policy ID\n * @returns Policy record\n */\n async get(policyId: string): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'GET',\n path: `/policies/${policyId}`,\n });\n }\n\n /**\n * Delete a policy.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DeletePolicyIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param options - Request options (must include `endorsement`)\n */\n async delete(policyId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Add a rule to a policy.\n *\n * @param policyId - Policy ID\n * @param data - Rule creation data\n * @returns Created rule\n */\n async addRule(\n policyId: string,\n data: PolicyRuleCreateRequest,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'POST',\n path: `/policies/${policyId}/rules`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update a policy rule.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param data - Update data\n * @returns Updated rule\n */\n async updateRule(\n policyId: string,\n ruleId: string,\n data: Partial<PolicyRuleCreateRequest>,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'PATCH',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a policy rule.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `RemovePolicyRuleIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param options - Request options (must include `endorsement`)\n */\n async deleteRule(policyId: string, ruleId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a policy.\n *\n * Returns slim references (id + name + family) for the wallets the policy is currently attached to.\n *\n * @param policyId - Policy ID\n * @returns Array of attached wallets\n */\n async getWallets(policyId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/policies/${policyId}/wallets`,\n });\n }\n\n /**\n * Attach a policy to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachPolicyToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a policy from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachPolicyFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Signer Groups resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SignerGroup,\n SignerGroupCreateRequest,\n SignerGroupGetParams,\n SignerGroupSignerAddRequest,\n Signer,\n SignerCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Signer Groups API resource.\n */\nexport class SignerGroupsResource extends BaseResource {\n /**\n * Create a new signer group.\n *\n * @param data - Signer group creation data\n * @returns Created signer group\n */\n async create(data: SignerGroupCreateRequest, options?: RequestOptions): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: '/signer-groups',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n list(params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>('/signer-groups', params);\n }\n\n /**\n * Get a signer group by ID.\n *\n * Pass `{ include_removed: true }` to also get a `removed_members` array of\n * signers that were removed from this group, each carrying its `removed_at`\n * timestamp. Defaults to active members only.\n *\n * @param signerGroupId - Signer group ID\n * @param params - Optional `{ include_removed }`\n * @returns Signer group record\n *\n * @example\n * ```typescript\n * const group = await client.signerGroups.get(groupId, { include_removed: true });\n * for (const s of group.removed_members ?? []) {\n * console.log(s.name, 'removed at', s.removed_at);\n * }\n * ```\n */\n async get(signerGroupId: string, params?: SignerGroupGetParams): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}`,\n query: { ...params },\n });\n }\n\n /**\n * Add an existing signer's public key to a group.\n *\n * The endpoint takes `{ member_key }` — the base64 PKIX (SPKI) public\n * key of an existing signer resource — not a fresh signer definition.\n * Returns the updated group (with the new member included).\n *\n * @param signerGroupId - Signer group ID\n * @param data - `{ member_key }` (the signer's base64 PKIX public key)\n * @returns The updated signer group\n */\n async addSigner(\n signerGroupId: string,\n data: SignerGroupSignerAddRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: `/signer-groups/${signerGroupId}/signers`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove a signer from a group.\n *\n * @param signerGroupId - Signer group ID\n * @param signerId - The signer's KSUID `signer_id` — NOT its public key.\n * (The standalone `client.signers.delete()` takes the public key instead.)\n * @param options - Optional request options (e.g. an explicit idempotency\n * key — the platform requires one on this DELETE)\n */\n async removeSigner(\n signerGroupId: string,\n signerId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signer-groups/${signerGroupId}/signers/${signerId}`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a signer group.\n *\n * Returns slim references (id + name + family) for the wallets the signer group is currently attached to.\n *\n * @param signerGroupId - Signer group ID\n * @returns Array of attached wallets\n */\n async getWallets(signerGroupId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}/wallets`,\n });\n }\n\n /**\n * Attach a signer group to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachGroupToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a signer group from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachGroupFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups attached to a wallet.\n *\n * @param walletId - Wallet ID\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n listForWallet(walletId: string, params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>(`/wallets/${walletId}/signer-groups`, params);\n }\n}\n\n/**\n * Signers API resource.\n */\nexport class SignersResource extends BaseResource {\n /**\n * Create a new signer.\n *\n * @param data - Signer creation data (name, public_key, key_type)\n * @param options - Request options\n * @returns Created signer\n */\n async create(data: SignerCreateRequest, options?: RequestOptions): Promise<Signer> {\n return this.transport.request<Signer>({\n method: 'POST',\n path: '/signers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a signer by public key.\n *\n * Soft-deletes all signers with the given public key.\n *\n * @param publicKey - Signer public key\n */\n async delete(publicKey: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signers/${publicKey}`,\n });\n }\n}\n","/**\n * API Keys resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n ApiKey,\n ApiKeyResponse,\n ApiKeyCreateRequest,\n CreateApiKeyForClientRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * API Keys API resource.\n */\nexport class ApiKeysResource extends BaseResource {\n /**\n * Create a new API key.\n *\n * @param data - API key creation data\n * @returns Created API key (includes secret, only shown once)\n */\n async create(data: ApiKeyCreateRequest, options?: RequestOptions): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List API keys.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of API keys\n */\n list(params?: ListParams): PaginatedIterator<ApiKey> {\n return this.paginate<ApiKey>('/api-keys', params);\n }\n\n /**\n * Delete an API key.\n *\n * @param apiKeyId - API key ID\n */\n async delete(apiKeyId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/api-keys/${apiKeyId}`,\n });\n }\n\n /**\n * Delete all API keys.\n *\n * Intended for incident response only.\n */\n async deleteAll(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/api-keys',\n });\n }\n\n /**\n * Create an API key for a specific client (admin only).\n *\n * Requires admin access token.\n *\n * @param data - Request data containing `client_id`\n * @param options - Request options\n * @returns Created API key response (includes key, only shown once)\n */\n async createForClient(\n data: CreateApiKeyForClientRequest,\n options?: RequestOptions\n ): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys/admin',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Users resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n User,\n UserCreateRequest,\n UserUpdateRequest,\n UserListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Users API resource.\n */\nexport class UsersResource extends BaseResource {\n /**\n * Create a new user.\n *\n * @param data - User creation data\n * @returns Created user\n */\n async create(data: UserCreateRequest, options?: RequestOptions): Promise<User> {\n return this.transport.request<User>({\n method: 'POST',\n path: '/users',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List users.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of users\n */\n list(params?: UserListParams): PaginatedIterator<User> {\n return this.paginate<User>('/users', params);\n }\n\n /**\n * Update a user.\n *\n * @param userId - User ID\n * @param data - Update data (first_name, last_name, role)\n */\n async update(userId: string, data: UserUpdateRequest, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'PATCH',\n path: `/users/${userId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a user.\n *\n * @param userId - User ID\n */\n async delete(userId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/users/${userId}`,\n });\n }\n}\n","/**\n * Webhooks resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n WebhookTarget,\n WebhookTargetCreateRequest,\n WebhookTargetUpdateRequest,\n WebhookEvent,\n WebhookReplayResponse,\n WebhookHistoryListParams,\n WebhookHistoryResponse,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Webhooks API resource.\n */\nexport class WebhooksResource extends BaseResource {\n /**\n * Create a new webhook target.\n *\n * @param data - Webhook target creation data\n * @returns Created webhook target\n */\n async createTarget(\n data: WebhookTargetCreateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'POST',\n path: '/webhooks/targets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List webhook targets.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of webhook targets\n */\n listTargets(params?: ListParams): PaginatedIterator<WebhookTarget> {\n return this.paginate<WebhookTarget>('/webhooks/targets', params);\n }\n\n /**\n * Get a webhook target by ID.\n *\n * @param targetId - Webhook target ID\n * @returns Webhook target record\n */\n async getTarget(targetId: string): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'GET',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * Update a webhook target.\n *\n * @param targetId - Webhook target ID\n * @param data - Update data\n * @returns Updated webhook target\n */\n async updateTarget(\n targetId: string,\n data: WebhookTargetUpdateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'PATCH',\n path: `/webhooks/targets/${targetId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a webhook target.\n *\n * @param targetId - Webhook target ID\n */\n async deleteTarget(targetId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * List webhook delivery history.\n *\n * Note: This endpoint uses cursor-based pagination (`cursor`/`has_more`) instead\n * of the standard `starting_after`/`has_more_after` format. Because of this,\n * it returns the raw response rather than a `PaginatedIterator`. Use the `cursor`\n * field from the response to fetch subsequent pages.\n *\n * @param params - Webhook history query parameters\n * @returns Webhook history response with `data`, `has_more`, and `cursor`\n *\n * @example\n * ```typescript\n * let cursor: string | undefined;\n * do {\n * const page = await client.webhooks.listEvents({ limit: 50, cursor });\n * for (const event of page.data) {\n * console.log(event);\n * }\n * cursor = page.cursor ?? undefined;\n * } while (page.has_more);\n * ```\n */\n async listEvents(params?: WebhookHistoryListParams): Promise<WebhookHistoryResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n return this.transport.request<WebhookHistoryResponse>({\n method: 'GET',\n path: '/webhooks',\n query,\n });\n }\n\n /**\n * Get a webhook event by ID.\n *\n * @param eventId - Webhook event ID\n * @returns Webhook event record\n */\n async getEvent(eventId: string): Promise<WebhookEvent> {\n return this.transport.request<WebhookEvent>({\n method: 'GET',\n path: `/webhooks/${eventId}`,\n });\n }\n\n /**\n * Replay a webhook event.\n *\n * Re-queues the webhook for delivery to all configured targets.\n *\n * @param eventId - Webhook event ID\n * @param options - Request options\n * @returns Replay response with `webhook_id`, `status`, and `replayed_to_count`\n */\n async replayEvent(eventId: string, options?: RequestOptions): Promise<WebhookReplayResponse> {\n return this.transport.request<WebhookReplayResponse>({\n method: 'POST',\n path: `/webhooks/events/${eventId}/replay`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Info resource for platform capabilities.\n */\n\nimport { BaseResource } from './base.js';\nimport type { Country } from '../types.js';\n\n/**\n * Info API resource for platform capabilities.\n */\nexport class InfoResource extends BaseResource {\n /**\n * Get supported countries.\n *\n * @returns Array of supported countries\n *\n * @example\n * ```typescript\n * const countries = await client.info.getCountries();\n * ```\n */\n async getCountries(): Promise<Country[]> {\n // /capabilities/countries returns Country[] directly, not the\n // paginated { data, meta } envelope. Earlier versions read\n // response.data here and silently returned undefined.\n return this.transport.request<Country[]>({\n method: 'GET',\n path: '/capabilities/countries',\n });\n }\n\n /**\n * Get supported networks.\n *\n * @returns Array of supported networks\n *\n * @example\n * ```typescript\n * const networks = await client.info.getNetworks();\n * for (const network of networks) {\n * console.log(network.id, network.name);\n * }\n * ```\n */\n async getNetworks(): Promise<string[]> {\n // /capabilities/networks returns string[] (network IDs like\n // \"ethereum-mainnet\") directly, not the paginated { data, meta }\n // envelope. Earlier versions typed this as Network[] and read\n // response.data, which silently returned undefined.\n return this.transport.request<string[]>({\n method: 'GET',\n path: '/capabilities/networks',\n });\n }\n}\n","/**\n * Legal documents resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type { LegalDocument } from '../types.js';\n\n/**\n * Legal Documents API resource.\n *\n * The published terms a customer accepts during onboarding. **Unauthenticated**\n * — integrators need these before a customer relationship exists, so the\n * endpoints carry no credential and are safe to call from a signup page.\n */\nexport class LegalResource extends BaseResource {\n /**\n * List the revision of every legal document currently in force.\n *\n * An INDEX, not a bundle: each entry names a document and its in-force\n * revision, without the text. Fetch {@link get} for the one document you\n * are about to display — inlining every document would put the whole corpus\n * on every call.\n *\n * Not safe to cache indefinitely: it names whichever revision is in force\n * NOW, and that changes when a new one is published. A specific\n * `(key, version)` from {@link get} is a different matter — revisions are\n * immutable, so that text can be cached for as long as you like.\n *\n * @returns The in-force revision of each document, without its text\n *\n * @example\n * ```typescript\n * for (const doc of await client.legal.list()) {\n * console.log(doc.key, doc.version, doc.title);\n * }\n * ```\n */\n async list(): Promise<LegalDocument[]> {\n const response = await this.transport.request<{ data: LegalDocument[] }>({\n method: 'GET',\n path: '/legal/documents',\n });\n return response.data ?? [];\n }\n\n /**\n * Get one legal document — the revision in force, or a specific one.\n *\n * Pass the `version` you displayed back as `legal_document_version` when\n * submitting an attestation, so the acceptance record names the exact text\n * the customer saw rather than whichever revision happened to be current\n * when the request arrived.\n *\n * @param documentKey - Document identifier, e.g. `'dakota_tos'`\n * @param version - A specific published revision. Omit for the one in force\n * @returns The requested revision, including its text\n *\n * @example\n * ```typescript\n * const tos = await client.legal.get('dakota_tos');\n * render(tos.content);\n *\n * await client.applications.submitAttestation(applicationId, {\n * attestation_type: 'terms_of_service',\n * legal_document_version: tos.version, // records what they actually saw\n * // ...\n * });\n * ```\n */\n async get(documentKey: string, version?: string): Promise<LegalDocument> {\n return this.transport.request<LegalDocument>({\n method: 'GET',\n path: `/legal/documents/${documentKey}`,\n query: version !== undefined ? { version } : undefined,\n });\n }\n}\n","/**\n * Reserve-management marketing-fee statements resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type { RDMarketingFeeStatement } from '../types.js';\n\n/**\n * RD Marketing Fee API resource.\n *\n * The reserve-management statements for the calling client. The client comes\n * from the session and is never named in a request, so there is no id to pass\n * and no other client's statements to address.\n *\n * A client who has never had a rate gets a **404** from both methods: holding a\n * rate is what being in the programme means, and there is no separate\n * entitlement record to read.\n */\nexport class RDMarketingFeeResource extends BaseResource {\n /**\n * The months this client has a statement for, newest first.\n *\n * Runs from the start of their contract to the running month, and the\n * RUNNING month IS included. It cannot be priced yet — the bank's interest\n * posts in the month after it is earned — but the balance is real and\n * accruing, and a client checking mid-month has to be able to see it. Its\n * fee figures come back absent rather than zero.\n *\n * An EMPTY list means the contract is real but no month has started yet.\n * That is different from a 404, which means no contract at all.\n *\n * @returns Statement months as `YYYY-MM-DD` (first day of the month, UTC)\n *\n * @example\n * ```typescript\n * const months = await client.rdMarketingFee.listMonths();\n * if (months.length === 0) {\n * // Contract starts next month or later — \"starting soon\", not an error.\n * }\n * ```\n */\n async listMonths(): Promise<string[]> {\n const response = await this.transport.request<{ months?: string[] }>({\n method: 'GET',\n path: '/rd-marketing-fee/statements',\n });\n return response.months ?? [];\n }\n\n /**\n * One month's statement — one row per calendar day: the date, the RD\n * balance, and that day's fee.\n *\n * The rows are the STORED daily principals, read rather than recomputed, so\n * what the client reads and what Dakota priced cannot drift.\n *\n * Absent is not zero. A balance is absent when the day has not been derived\n * yet and `'0'` when the client genuinely held no RD; fees are absent for\n * every day of a month whose rate has not been derived. Neither unknown is\n * reported as a zero, so render an absent figure as unknown rather than\n * defaulting it.\n *\n * @param month - First day of the month, UTC, as `YYYY-MM-DD`\n * @returns The month's statement, one row per day\n *\n * @example\n * ```typescript\n * const statement = await client.rdMarketingFee.getStatement('2026-08-01');\n * for (const day of statement.daily) {\n * console.log(day.date, day.balance_minor ?? 'not yet derived');\n * }\n * ```\n */\n async getStatement(month: string): Promise<RDMarketingFeeStatement> {\n return this.transport.request<RDMarketingFeeStatement>({\n method: 'GET',\n path: `/rd-marketing-fee/statements/${month}`,\n });\n }\n}\n","/**\n * Sandbox resource for testing simulations.\n *\n * @remarks\n * These endpoints are only available in the Sandbox environment.\n * In sandbox, Dakota does NOT monitor testnet blockchains - you must\n * use these simulation endpoints to trigger payment events.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SimulateInboundRequest,\n SimulationResponse,\n SimulateOnboardingRequest,\n SimulateOnboardingResponse,\n AdvanceSimulationRequest,\n AdvanceSimulationResult,\n SimulationInspection,\n SandboxScenario,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Sandbox API resource for testing simulations.\n *\n * These endpoints are only available in the Sandbox environment.\n *\n * @remarks\n * **Important:** In sandbox, Dakota does NOT monitor testnet blockchains.\n * You must use these simulation endpoints to trigger payment events.\n *\n * @example\n * ```typescript\n * // Simulate ACH deposit to on-ramp account\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n *\n * // Simulate off-ramp ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * movement_id: 'tx_456',\n * amount: '500.00',\n * currency: 'USD',\n * });\n * ```\n */\nexport class SandboxResource extends BaseResource {\n /**\n * Simulate an inbound payment event.\n *\n * Triggers a simulated payment event through the mock banking provider.\n * The required fields depend on the simulation `type`:\n *\n * | Type | Required Fields |\n * |------|-----------------|\n * | `ach_inbound`, `wire_inbound` | `account_id` |\n * | `crypto_inbound` | `wallet_id` |\n * | `*_outbound_*`, `*_reversal` | `movement_id` |\n *\n * @param data - Simulation request data\n * @returns Simulation response with ID and state\n *\n * @example Simulate ACH deposit to on-ramp\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate off-ramp ACH settlement\n * ```typescript\n * // After creating a one-off transaction for off-ramp testing\n * const tx = await client.transactions.create({\n * customer_id: 'cust_123',\n * amount: '100.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-sepolia',\n * destination_id: 'dest_456',\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * });\n *\n * // Simulate the ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * movement_id: tx.id,\n * amount: '100.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate crypto deposit to wallet\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'crypto_inbound',\n * wallet_id: 'wallet_789',\n * amount: '500.00',\n * currency: 'USDC',\n * });\n * ```\n */\n async simulateInbound(\n data: SimulateInboundRequest,\n options?: RequestOptions\n ): Promise<SimulationResponse> {\n return this.transport.request<SimulationResponse>({\n method: 'POST',\n path: '/sandbox/simulate/inbound',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Simulate an onboarding state transition.\n *\n * Drives KYB, KYC, or applicant account status through a sandbox transition\n * without waiting for real compliance review.\n *\n * **Important:** Use `kyb_approve` to fully approve any customer type (individual or\n * business). This triggers the complete onboarding flow including endorsement and\n * recipient creation. The `kyc_*` types only update the individual applicant's KYC\n * application status without triggering the full onboarding flow.\n *\n * @param data - Simulation request data\n * @returns Simulation response with previous and new state\n *\n * @example Approve KYB and activate applicant\n * ```typescript\n * // Step 1: Approve the KYB application\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_approve',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_kyb_${Date.now()}`,\n * });\n *\n * // Step 2: Activate the applicant (triggers provisioning)\n * await client.sandbox.simulateOnboarding({\n * type: 'applicant_activate',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_activate_${Date.now()}`,\n * });\n * ```\n *\n * @example Reject a KYB application\n * ```typescript\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_reject',\n * applicant_id: applicationId,\n * simulation_id: `sim_${Date.now()}`,\n * reason_code: 'MISSING_DOCUMENTS',\n * });\n * ```\n */\n async simulateOnboarding(\n data: SimulateOnboardingRequest,\n options?: RequestOptions\n ): Promise<SimulateOnboardingResponse> {\n return this.transport.request<SimulateOnboardingResponse>({\n method: 'POST',\n path: '/sandbox/simulate/onboarding',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get detailed simulation status and callback history.\n *\n * Returns the current state and callback delivery history for a sandbox simulation.\n * Use this to debug async flows and see whether callbacks have been delivered.\n *\n * @param simulationId - Simulation ID returned from simulateInbound/simulateOnboarding\n * @returns Full simulation inspection including state and callbacks\n *\n * @example\n * ```typescript\n * const inspection = await client.sandbox.getSimulation('sim_123');\n * console.log('State:', inspection.state);\n * console.log('Callbacks:', inspection.callbacks);\n * ```\n */\n async getSimulation(simulationId: string): Promise<SimulationInspection> {\n return this.transport.request<SimulationInspection>({\n method: 'GET',\n path: `/sandbox/simulations/${simulationId}`,\n });\n }\n\n /**\n * Advance a stateful simulation to the next state.\n *\n * Some scenarios pause and wait for explicit advancement. Use this method\n * to continue a paused simulation with a specific action.\n *\n * @param simulationId - Simulation ID\n * @param data - Action to take (e.g., 'release', 'reject', 'confirm', 'expire')\n * @returns Updated simulation state\n *\n * @example\n * ```typescript\n * const result = await client.sandbox.advanceSimulation('sim_123', {\n * action: 'release',\n * });\n * console.log('New state:', result.new_state);\n * ```\n */\n async advanceSimulation(\n simulationId: string,\n data?: AdvanceSimulationRequest,\n options?: RequestOptions\n ): Promise<AdvanceSimulationResult> {\n return this.transport.request<AdvanceSimulationResult>({\n method: 'POST',\n path: `/sandbox/simulations/${simulationId}/advance`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List available sandbox scenarios.\n *\n * Returns all simulation scenarios supported by the platform.\n * Use these scenario names in the `scenario` field of simulateInbound.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of scenarios\n *\n * @example\n * ```typescript\n * const scenarios = await client.sandbox.listScenarios().toArray();\n * for (const scenario of scenarios) {\n * console.log(`${scenario.name}: ${scenario.description}`);\n * }\n * ```\n */\n listScenarios(params?: ListParams): PaginatedIterator<SandboxScenario> {\n return this.paginate<SandboxScenario>('/sandbox/scenarios', params);\n }\n}\n","/**\n * Self-Serve Credits resource for managing prepaid transfer credits.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n SelfServeCreditsPurchaseRequest,\n SelfServeCreditsPurchaseResponse,\n SelfServeCreditsBalanceResponse,\n SelfServeCreditsLedgerResponse,\n SelfServeCreditsLedgerParams,\n SelfServeCreditsPricingResponse,\n SelfServeCreditTiersResponse,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Self-Serve Credits API resource.\n *\n * Manage prepaid credits for self-serve transfer capacity.\n */\nexport class SelfServeResource extends BaseResource {\n /**\n * Purchase self-serve credits.\n *\n * Creates a Stripe checkout session for purchasing credits at the specified tier.\n *\n * @param data - Purchase request with the tier price\n * @param options - Optional request options (e.g., idempotency key)\n * @returns Response containing the Stripe checkout URL\n *\n * @example\n * ```typescript\n * const { checkout_url } = await client.selfServe.purchaseCredits({\n * tier_price_cents: 10000,\n * });\n * // Redirect user to checkout_url\n * ```\n */\n async purchaseCredits(\n data: SelfServeCreditsPurchaseRequest,\n options?: RequestOptions\n ): Promise<SelfServeCreditsPurchaseResponse> {\n return this.transport.request<SelfServeCreditsPurchaseResponse>({\n method: 'POST',\n path: '/self-serve/credits/purchase',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get current credits balance.\n *\n * @returns The current balance and transfer capacity in cents\n *\n * @example\n * ```typescript\n * const balance = await client.selfServe.getBalance();\n * console.log(`Balance: $${balance.balance_cents / 100}`);\n * console.log(`Transfer capacity: $${balance.transfer_capacity_cents / 100}`);\n * ```\n */\n async getBalance(): Promise<SelfServeCreditsBalanceResponse> {\n return this.transport.request<SelfServeCreditsBalanceResponse>({\n method: 'GET',\n path: '/self-serve/credits/balance',\n });\n }\n\n /**\n * List credits ledger entries.\n *\n * Returns a cursor-paginated list of ledger entries (purchases, deductions, refunds).\n *\n * @param params - Optional query parameters for filtering and pagination\n * @returns Ledger response with entries and has_more flag\n *\n * @example\n * ```typescript\n * // Get recent ledger entries\n * const ledger = await client.selfServe.listLedger();\n * for (const entry of ledger.entries) {\n * console.log(entry.entry_type, entry.amount_cents, entry.description);\n * }\n *\n * // Filter by type with pagination\n * const purchases = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * });\n *\n * // Paging: carry BOTH halves of the cursor. Entries written in one\n * // transaction share a created_at, so a page boundary inside such a\n * // group drops rows when only `cursor` is sent.\n * const last = purchases.entries[purchases.entries.length - 1];\n * const next = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * cursor: last.created_at,\n * cursor_id: last.id,\n * });\n * ```\n */\n async listLedger(params?: SelfServeCreditsLedgerParams): Promise<SelfServeCreditsLedgerResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params?.cursor !== undefined) query.cursor = params.cursor;\n // Ignored by the server without `cursor`, and the ordering it completes is\n // what stops a page boundary splitting one transaction's entries.\n if (params?.cursor_id !== undefined) query.cursor_id = params.cursor_id;\n if (params?.limit !== undefined) query.limit = params.limit;\n if (params?.type !== undefined) query.type = params.type;\n\n return this.transport.request<SelfServeCreditsLedgerResponse>({\n method: 'GET',\n path: '/self-serve/credits/ledger',\n query,\n });\n }\n\n /**\n * List available credit tiers.\n *\n * Returns all available pricing tiers for purchasing credits.\n *\n * @returns Response containing the list of available tiers\n *\n * @example\n * ```typescript\n * const { tiers } = await client.selfServe.listTiers();\n * for (const tier of tiers) {\n * console.log(`$${tier.price_cents / 100} → $${tier.transfer_capacity_cents / 100} capacity`);\n * }\n * ```\n */\n async listTiers(): Promise<SelfServeCreditTiersResponse> {\n return this.transport.request<SelfServeCreditTiersResponse>({\n method: 'GET',\n path: '/self-serve/credits/tiers',\n });\n }\n\n /**\n * Get the self-serve client's pricing config (fee schedule).\n *\n * Returns the caller's current `ClientPricingConfig` — transfer/ACH/wire/SEPA/SWIFT/KYC/KYB\n * fees plus the monthly minimum. Self-serve clients only.\n *\n * @returns The current pricing configuration\n *\n * @example\n * ```typescript\n * const pricing = await client.selfServe.getPricing();\n * console.log(`ACH fee: ${pricing.achFeeCents} cents`);\n * console.log(`Wire fee: ${pricing.wireFeeCents} cents`);\n * ```\n */\n async getPricing(): Promise<SelfServeCreditsPricingResponse> {\n return this.transport.request<SelfServeCreditsPricingResponse>({\n method: 'GET',\n path: '/self-serve/credits/pricing',\n });\n }\n}\n","/**\n * Fee Payout Destination resource.\n *\n * Where Dakota pays your accrued developer fees. Exactly ONE destination\n * exists per organization, and it is crypto-only — a USDC wallet on any\n * supported chain.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n FeePayoutDestination,\n PutFeePayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Fee Payout Destination API resource.\n */\nexport class FeePayoutDestinationResource extends BaseResource {\n /**\n * Get the destination registered to receive your developer-fee payouts.\n *\n * @returns The registered destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.get();\n * console.log(dest.chain, dest.wallet_address);\n * ```\n */\n async get(): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'GET',\n path: '/fee-payout-destination',\n });\n }\n\n /**\n * Register or replace your fee payout destination.\n *\n * There is exactly one destination per organization, so this REPLACES any\n * existing one. Emits `fee_payout_destination.updated`.\n *\n * `chain` is a CAIP-2 chain id (e.g. `eip155:8453`) from the supported\n * networks list — see `client.info.getNetworks()`.\n *\n * @param data - The USDC wallet to pay fees to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.set({\n * usdc_wallet: {\n * chain: 'eip155:8453',\n * address: '0x1234567890123456789012345678901234567890',\n * },\n * });\n * ```\n */\n async set(\n data: PutFeePayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'PUT',\n path: '/fee-payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove the registered fee payout destination, if one exists.\n *\n * Emits `fee_payout_destination.deleted`.\n *\n * @example\n * ```typescript\n * await client.feePayoutDestination.delete();\n * ```\n */\n async delete(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/fee-payout-destination',\n });\n }\n}\n","/**\n * Payment Agents resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { AGENTIC_MODEL_TIMEOUT_MS } from '../config.js';\nimport type {\n PaymentAgent,\n PaymentAgentCreateRequest,\n AgenticProposalsProgress,\n AgenticProposalsResult,\n CreateProposalsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Payment Agents API resource (ALPHA).\n */\nexport class PaymentAgentsResource extends BaseResource {\n /**\n * Create a hosted payment agent.\n *\n * @param data - Payment agent creation data (customer_id, name, hosted)\n * @returns The created payment agent (id, signer_id, signer_public_key, state)\n */\n async create(data: PaymentAgentCreateRequest, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: '/payment-agents',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a hosted payment agent.\n *\n * Returns the agent together with the wallets it can currently spend\n * from. `wallet_ids` are DERIVED at query time from the agent signer's\n * live signer-group membership, so they reflect the agent's access\n * right now — not just at creation time.\n *\n * @param paymentAgentId - Payment agent ID\n */\n async get(paymentAgentId: string): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}`,\n });\n }\n\n /**\n * Revoke a hosted payment agent.\n *\n * The agent can no longer be used, and its signing key is destroyed\n * in the isolated signer service (best-effort — the revoked state is\n * authoritative). Idempotent.\n *\n * The response's `signer_group_cleanup` names the signer groups the\n * (now-revoked) agent's signer still belongs to. A revoked signer can't\n * sign, but its group membership lingers — remove it with\n * `client.signerGroups.removeSigner(signer_group_id, signer_id)` to\n * finish de-provisioning.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The revoked payment agent (state=revoked, signer_group_cleanup?)\n */\n async revoke(paymentAgentId: string, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/revoke`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Draft payment proposals from a conversation.\n *\n * Pure cognition, no side effects: turn a customer's natural-language\n * request into reviewable proposals. Stateless — send the whole\n * conversation so far in `messages` on each call. Prefer\n * `AgentConversation` for multi-turn chat; use this directly only for\n * one-shot proposals.\n *\n * SLOW BY NATURE. A turn is a sequence of model calls — read the payees,\n * check balances, draft, revise — so a multi-payee request legitimately\n * runs minutes. It therefore defaults to {@link AGENTIC_MODEL_TIMEOUT_MS}\n * rather than the client's ordinary deadline. Pass `{ timeout }` to\n * change it for one call; an explicit client-wide `timeout` still wins.\n *\n * The result may carry `blockers` ALONGSIDE proposals — they are not\n * alternatives. Branch on `blocker.code`, not on `reply`, and ignore codes\n * you do not recognize.\n *\n * The vocabulary the agent drafts under is the one registered with\n * `client.agenticPolicy.set()`. It is not a property of this request —\n * a policy sent here is ignored, which is why the option to send one is\n * gone.\n *\n * @param paymentAgentId - Payment agent ID\n * @param data - Prompt and/or messages\n * @returns Proposals (at high confidence) and/or a conversational reply\n */\n async createProposals(\n paymentAgentId: string,\n data: CreateProposalsRequest,\n options?: RequestOptions\n ): Promise<AgenticProposalsResult> {\n return this.transport.request<AgenticProposalsResult>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/proposals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n endpointTimeout: AGENTIC_MODEL_TIMEOUT_MS,\n });\n }\n\n /**\n * Live progress of an in-flight drafting turn.\n *\n * A multi-payee drafting turn legitimately runs minutes (several sequential\n * model calls). While a `createProposals` call is in flight, poll this every\n * few seconds to show the customer what the agent is doing right now.\n *\n * Advisory display only. `active: false` means no turn is currently\n * publishing progress for this agent — idle, just finished, or served by\n * another instance — so fall back to a generic spinner. Never gate any\n * behaviour on this endpoint.\n *\n * The snapshot is coarse and customer-safe: a phase enum, one human\n * sentence, and the model round. Tool counts only — never payee names,\n * amounts, or addresses.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The current progress snapshot\n *\n * @example\n * ```typescript\n * const pending = client.paymentAgents.createProposals(agentId, { prompt });\n * const poll = setInterval(async () => {\n * const p = await client.paymentAgents.getProposalsProgress(agentId);\n * if (p.active) console.log(p.detail);\n * }, 3000);\n * const result = await pending.finally(() => clearInterval(poll));\n * ```\n */\n async getProposalsProgress(paymentAgentId: string): Promise<AgenticProposalsProgress> {\n return this.transport.request<AgenticProposalsProgress>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}/proposals/progress`,\n });\n }\n}\n","/**\n * Instructions resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticInstruction,\n AgenticInstructionsResult,\n CreateInstructionsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Instructions API resource (ALPHA).\n *\n * Each accepted proposal becomes one persisted instruction whose action\n * series is actuated deterministically.\n */\nexport class InstructionsResource extends BaseResource {\n /**\n * Accept proposals — actuate them into persisted instructions.\n *\n * One optional field shapes the actuation:\n *\n * - `developer_fee` declares your fee PER PAYOUT TYPE — `swap_bps` for a\n * crypto payout, `offramp_bps` for a bank payout. They are independent,\n * so one conversation can charge a swap and stay silent about a bank\n * payout in the same turn. Omit a rate (or send zero) and that payout\n * type carries no fee: nothing is charged, nothing is added to the\n * amount, and the agent is told nothing about a fee it could mention.\n * Both are DEFAULTS for the auto-accounts this request creates — an\n * action-level `fee_bps` still wins outright.\n *\n * The vocabulary the actuation is judged against comes from the policy\n * registered with `client.agenticPolicy.set()` — the same one the drafting\n * turn used, which is the point of registering it rather than sending it.\n *\n * @param data - The payment agent id and the proposals to accept\n * @returns instruction_ids + the mandates the batch drafted (in full\n * wire shape; sign the §8 approval immediately)\n */\n async create(\n data: CreateInstructionsRequest,\n options?: RequestOptions\n ): Promise<AgenticInstructionsResult> {\n return this.transport.request<AgenticInstructionsResult>({\n method: 'POST',\n path: '/instructions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get an accepted instruction — its action series and the per-action\n * downstream artifacts actuation produced.\n *\n * @param instructionId - Instruction ID\n */\n async get(instructionId: string): Promise<AgenticInstruction> {\n return this.transport.request<AgenticInstruction>({\n method: 'GET',\n path: `/instructions/${instructionId}`,\n });\n }\n}\n","/**\n * Mandates resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n AmendMandateRequest,\n ApproveMandateRequest,\n CancelMandateRequest,\n CreateMandateRequest,\n Mandate,\n MandateBudget,\n MandateListParams,\n MandateResponse,\n MandateVersion,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Mandates API resource (ALPHA).\n */\nexport class MandatesResource extends BaseResource {\n /**\n * List mandates (newest first), with the EFFECTIVE status — a pending or\n * active mandate past its valid_until reads \"expired\". Filter with\n * customer_id / signer_id / status; omit them all for the full collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of mandates\n */\n list(params?: MandateListParams): PaginatedIterator<Mandate> {\n return this.paginate<Mandate>('/mandates', params);\n }\n\n /**\n * Get a mandate — the signer it binds, its rule exactly as the customer\n * approves it, validity, and status.\n *\n * @param mandateId - Mandate ID\n */\n async get(mandateId: string): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'GET',\n path: `/mandates/${mandateId}`,\n });\n }\n\n /**\n * Create a mandate directly.\n *\n * Drafts a PENDING mandate from a direct user interaction — no instruction\n * back-link. Exactly one binding form names the signer the mandate binds:\n * `payment_agent_id` (hosted convenience — binds that agent's signer and\n * anchors to the agent's customer), or `signer_id` together with\n * `customer_id` (any of the client's signers, BYO keys included). The rule\n * is the one the customer will approve (via `approve`, a recognized signer\n * other than the bound one, §8).\n *\n * @param data - One binding form + rule + optional validity window\n * @returns The drafted (pending) mandate\n */\n async create(data: CreateMandateRequest, options?: RequestOptions): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: '/mandates',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Approve a mandate.\n *\n * A recognized signer OTHER than the bound one signs the mandate payload\n * (see `mandateSignPayload` + `MandateSigner`) to activate it; arms its\n * scheduled payments.\n *\n * @param mandateId - Mandate ID\n * @param data - Approver public key (base64 PKIX) + base64 ASN.1 signature\n */\n async approve(\n mandateId: string,\n data: ApproveMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/approve`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel a mandate.\n *\n * Revokes a pending or active mandate. The canceller must be a recognized\n * signer OTHER than the bound one, with a valid signature over the mandate\n * payload — the bound signer can never mutate its own mandate.\n *\n * @param mandateId - Mandate ID\n * @param data - Signer public key (base64 PKIX) + base64 ASN.1 signature\n */\n async cancel(\n mandateId: string,\n data: CancelMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/cancel`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Amend a mandate — append a new signed version of its rule.\n *\n * Carries a changed rule into force with ONE signature and WITHOUT resetting\n * the spend already made in the current window: usage accrues to the\n * MANDATE, so an agent that has spent 9,000 of a 10,000 monthly limit and is\n * amended to 20,000 has 11,000 left, not 20,000.\n *\n * The `rule` is stored and verified VERBATIM — this endpoint does not\n * normalize it. It must already be canonical: `window` present and non-empty\n * (send `'NONE'` for a lifetime window), `targets` as recipient ids rather\n * than payee names, and `asset` uppercase. `target_type`, `window`, `asset`\n * and `network_id` must also match the current version exactly; only the\n * amount fields and `targets` may differ. Anything else is a 400 naming the\n * offending field.\n *\n * Build `signature` from `mandateAmendSignPayload(mandate, version, rule)` —\n * the amend payload commits to the version being created, so a signature for\n * v2 can never be replayed to append v3.\n *\n * @param mandateId - Mandate ID\n * @param data - Amending signer public key + signature + the complete NEW rule\n * @returns The mandate at its new current version\n *\n * @example\n * ```typescript\n * const mandate = await client.mandates.get(mandateId);\n * const nextVersion = (mandate.version ?? 1) + 1;\n * const rule = { ...mandate.rule, max_amount_in_window: '20000' };\n * const payload = mandateAmendSignPayload(mandate, nextVersion, rule);\n *\n * const amended = await client.mandates.amend(mandateId, {\n * signer_public_key: signer.publicKeyBase64(),\n * signature: await signer.sign(payload),\n * rule,\n * });\n * ```\n */\n async amend(\n mandateId: string,\n data: AmendMandateRequest,\n options?: RequestOptions\n ): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: `/mandates/${mandateId}/amend`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List a mandate's versions, oldest first.\n *\n * The append-only history of every rule that was ever in force under this\n * mandate, and the §8 signer that put each one there. Versions are\n * immutable, so a rule listed here never changes — this is what makes an\n * executed payment's `mandate_version` audit stamp legible.\n *\n * @param mandateId - Mandate ID\n * @returns Every version, oldest first\n */\n async listVersions(mandateId: string): Promise<MandateVersion[]> {\n return this.transport.request<MandateVersion[]>({\n method: 'GET',\n path: `/mandates/${mandateId}/versions`,\n });\n }\n\n /**\n * Get a mandate's remaining budget right now.\n *\n * The mandate's `rule` gives the ceilings; this gives the CONSUMPTION — what\n * has already been spent, what is earmarked by scheduled payments that have\n * not fired yet, and therefore what is left. Read it before scheduling:\n * otherwise an over-budget payment is only discovered when the gate denies\n * it at its due date, days later, with the payee unpaid.\n *\n * Advisory — nothing here reserves budget, and the gate remains the\n * authority at fire time. Two things to honour when reading a line:\n * an ABSENT `remaining_amount` / `remaining_count` means \"not capped\", never\n * \"nothing left\"; a `remaining_amount` of `'?'` means the figure could not\n * be summed and MUST be treated as no headroom (the gate fails closed on the\n * same data).\n *\n * @param mandateId - Mandate ID\n * @returns Per-target and aggregate budget lines, as of a stated instant\n *\n * @example\n * ```typescript\n * const budget = await client.mandates.getBudget(mandateId);\n * for (const line of budget.aggregate) {\n * console.log(line.bucket, line.remaining_amount ?? 'uncapped');\n * }\n * ```\n */\n async getBudget(mandateId: string): Promise<MandateBudget> {\n return this.transport.request<MandateBudget>({\n method: 'GET',\n path: `/mandates/${mandateId}/budget`,\n });\n }\n}\n","/**\n * Scheduled Payments resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n CreateScheduledPaymentRequest,\n RequestOptions,\n ScheduledPayment,\n ScheduledPaymentListParams,\n} from '../types.js';\n\n/**\n * Scheduled Payments API resource (ALPHA).\n */\nexport class ScheduledPaymentsResource extends BaseResource {\n /**\n * List scheduled payments (oldest due first).\n *\n * Narrow the collection with the optional customer_id, signer_id,\n * wallet_id, mandate_id, and status filters; omit them all for the full\n * client collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of scheduled payments\n */\n list(params?: ScheduledPaymentListParams): PaginatedIterator<ScheduledPayment> {\n return this.paginate<ScheduledPayment>('/scheduled-payments', params);\n }\n\n /**\n * Schedule payments directly — bypass the proposal flow.\n *\n * Creates one or more scheduled payments for a signer under an existing\n * active mandate (coverage is matched at fire time, so no new signature\n * is needed here). The schedule is explicit `dates` OR `count` ×\n * `interval_seconds` from `start_at`.\n *\n * @param data - Signer + wallet + destination (or address+network_id) + schedule\n * @returns The rows that were created (one per date)\n */\n async create(\n data: CreateScheduledPaymentRequest,\n options?: RequestOptions\n ): Promise<ScheduledPayment[]> {\n return this.transport.request<ScheduledPayment[]>({\n method: 'POST',\n path: '/scheduled-payments',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel one still-scheduled payment.\n *\n * Finalizes the row as cancelled. No signature is required — schedule rows\n * are bookkeeping, not authorization; the signed grant is the MANDATE,\n * which this does not touch.\n *\n * @param scheduledPaymentId - Scheduled payment ID\n */\n async cancel(scheduledPaymentId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/scheduled-payments/${scheduledPaymentId}/cancel`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Insights resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type { InsightReport } from '../types.js';\n\n/**\n * Insights API resource (ALPHA).\n *\n * Read-only, advisory reporting over a customer's agentic activity. Nothing\n * here moves money or changes state.\n */\nexport class InsightsResource extends BaseResource {\n /**\n * Get the customer's account insight report.\n *\n * A deterministic, read-only report: a snapshot of typed facts\n * (funding-wallet balances, upcoming totals, open payments, active\n * mandates), observations (`insights`), and advisory recommendations\n * (`suggestions`). Every item carries `evidence` — typed references to\n * the platform objects it was computed from. `kind` is an OPEN set;\n * ignore kinds you do not recognize.\n *\n * @param customerId - Customer ID\n * @returns The customer's insight report\n */\n async get(customerId: string): Promise<InsightReport> {\n return this.transport.request<InsightReport>({\n method: 'GET',\n path: `/customers/${customerId}/insights`,\n });\n }\n}\n","/**\n * Agentic Client Policy resource (ALPHA).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticClientPolicy,\n RegisteredAgenticClientPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Agentic Client Policy API resource (ALPHA).\n *\n * The policy is per CLIENT — it belongs to the client behind your API key,\n * never to a key, since API keys are N:1 to clients and a per-key policy\n * would fragment for anyone running one service key per deployment.\n *\n * There is no client id to pass. The route resolves the client from the API\n * key, so you cannot address another client's policy even to be refused.\n */\nexport class AgenticPolicyResource extends BaseResource {\n /**\n * Get the policy registered for the client behind your API key.\n *\n * A 404 here is the DEFAULT, not an error condition: with no registration\n * and no per-request policy the agent drafts on platform defaults, exactly\n * as it did before registration existed.\n *\n * @returns The normalized registered policy + its timestamps\n *\n * @example\n * ```typescript\n * try {\n * const { policy } = await client.agenticPolicy.get();\n * console.log(policy.labels);\n * } catch (e) {\n * if (e instanceof APIError && e.statusCode === 404) {\n * // No registration — platform defaults apply.\n * }\n * }\n * ```\n */\n async get(): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'GET',\n path: '/agentic-policy',\n });\n }\n\n /**\n * Register — or fully replace — this client's agentic policy.\n *\n * Registration is the ONLY way to set a policy. A policy is a property of\n * the CLIENT, not of a request: carried per request, a drafting turn and\n * the accept that followed it could be judged by different rules. The\n * platform accordingly stopped reading `client_policy` from request bodies,\n * and one sent there is now ignored — silently, since the agent simply\n * narrates in the platform's nouns again (\"destination\", \"mandate\") with no\n * error anywhere. Registering once removes that failure mode.\n *\n * FULL REPLACE, not a merge — the registration IS your declared vocabulary,\n * so an omitted field means you no longer want it, and an empty body (`{}`)\n * clears the registration back to platform defaults.\n *\n * Validated exactly like the per-request copy, so an unknown key, an\n * unsupported value, or a label for an unimplemented concept is a 400 HERE,\n * at registration — not a surprise on a customer's first conversation.\n *\n * The client comes from your API key; there is no id to pass.\n *\n * @param policy - The complete policy (`{}` clears it)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The normalized stored policy + its timestamps\n *\n * @example\n * ```typescript\n * await client.agenticPolicy.set({\n * payee_model: 'flat',\n * payout_assets: ['USDC', 'USDT'],\n * labels: { limit: 'spending limit', payee: 'recipient', limit_unit: 'USD' },\n * payout_route: 'conversion_account_only',\n * mandate_strategy: 'external_only',\n * });\n * ```\n */\n async set(\n policy: AgenticClientPolicy,\n options?: RequestOptions\n ): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'PUT',\n path: '/agentic-policy',\n body: policy,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Multi-turn agent chat. The platform's proposals endpoint is STATELESS —\n * it holds no session and must be sent the whole transcript on every turn.\n * `AgentConversation` hides that bookkeeping so a caller just sends user\n * messages and reads the agent's clarifying questions / final proposals.\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport type { DakotaClient } from '../client/client.js';\nimport type {\n AgenticBlocker,\n AgenticProposal,\n AgenticProposalsResult,\n DeveloperFee,\n} from '../client/types.js';\n\n/**\n * MIME types the platform accepts for a document attachment.\n */\nexport type AttachmentMediaType =\n | 'application/pdf'\n | 'image/png'\n | 'image/jpeg'\n | 'image/webp'\n | 'image/gif';\n\n/**\n * An input artifact on a user turn for the agent to read — today a document\n * (a PDF or image, e.g. an invoice to draft a payment from). `data` is the\n * RAW document bytes; the SDK base64-encodes them on the wire.\n */\nexport interface Attachment {\n mediaType: AttachmentMediaType;\n /** raw document bytes (not base64) */\n data: Uint8Array;\n /** optional, for display/audit */\n filename?: string;\n}\n\n/**\n * One turn of an agent conversation.\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n /**\n * Input artifacts attached to this turn for the agent to investigate.\n * Attachments ride only on the turn they are passed; they are NOT\n * persisted in the transcript.\n */\n attachments?: Attachment[];\n}\n\n/**\n * The agent's response to one user message.\n */\nexport interface ConversationTurn {\n /**\n * The agent's conversational text — a clarifying question or a\n * confirmation. May be empty when only proposals are returned.\n */\n reply: string;\n /**\n * The reviewable action series, present once the agent reaches high\n * confidence. Accept it via the instructions flow.\n */\n proposals: AgenticProposal[];\n /** Whether the agent drafted proposals this turn. */\n hasProposals: boolean;\n /**\n * Machine-actionable reasons the turn could not complete — for YOUR\n * application, not the customer. `reply` says the same thing in prose,\n * which software cannot branch on: \"extend the limit to cover Priya\",\n * \"I need her bank details\" and \"that rail is not supported\" all arrive\n * as some text.\n *\n * These ACCOMPANY proposals rather than replacing them, and routinely do.\n * The common case is a payee who does not exist yet: the turn proposes\n * creating them AND reports that the limit will not reach them, because\n * you have to do both, in that order — accept the proposal so the payee\n * has an id, then amend the limit to include it. Never treat proposals\n * and blockers as alternatives.\n *\n * Empty when nothing blocked the turn. Always switch on `code` and ignore\n * codes you do not know; new ones are added over time.\n */\n blockers: AgenticBlocker[];\n /** Whether the turn reported any blocker. */\n hasBlockers: boolean;\n /**\n * The boundary screen's verdict for this turn:\n *\n * - `\"ok\"` — normal payments turn.\n * - `\"warned\"` — off-topic; the customer was warned but may continue.\n * - `\"blocked\"` — the chat is terminated; stop serving it and offer a fresh\n * conversation.\n * - `\"rejected_input\"` — this message was refused WHOLESALE (e.g. more\n * payees than one conversation supports). `reply` explains what to\n * resend; the conversation continues unaffected, and the SDK has already\n * dropped the refused message from the transcript for you.\n *\n * Empty when the platform sent none. Treat it as an OPEN set — new values\n * may be added.\n */\n conversationStatus: string;\n}\n\n/**\n * The boundary screen's verdict for a message refused wholesale. Its contract\n * is that the message must NOT be added to the conversation history — see\n * {@link ConversationTurn.conversationStatus}.\n */\nconst REJECTED_INPUT = 'rejected_input';\n\n/** Options for an {@link AgentConversation}. */\nexport interface AgentConversationOptions {\n /**\n * The customer's IANA timezone (e.g. `'America/Los_Angeles'`).\n *\n * When set, the agent resolves every relative date (\"tomorrow\", \"Friday\")\n * and clock time (\"10 am\") in THIS zone: a date without a time is drafted\n * for 10:00 local, and a time without a date means its next local\n * occurrence. Left unset, times resolve as UTC and the agent says so when a\n * specific clock time matters.\n *\n * The conversation resends it on every turn, since the endpoint is\n * stateless. Note the zone's UTC offset is captured at drafting time, so a\n * DST transition before a far-future fire date shifts it by the DST delta.\n */\n timezone?: string;\n\n /**\n * Deadline (ms) for each turn of this conversation.\n *\n * Turns default to {@link AGENTIC_MODEL_TIMEOUT_MS}, which is sized for a\n * multi-payee drafting turn. Set this when your own turns are longer (a\n * very large payee list) or shorter (you would rather show the customer a\n * failure than keep them waiting).\n *\n * Required if the client was built with an explicit `timeout`: that\n * choice wins over the endpoint default, so a client configured with a\n * short global deadline will cut turns off unless you raise it here.\n */\n timeout?: number;\n\n /**\n * Your developer fee, declared PER PAYOUT TYPE — `swap_bps` for a crypto\n * payout, `offramp_bps` for a bank one. The two are independent, so one\n * conversation can charge a swap and stay silent about a bank payout.\n *\n * Set it here as well as on `instructions.create()`, not instead of it.\n * The accept is what CHARGES the fee; declaring it on the drafting turn is\n * what lets the agent MENTION it — omit it and the agent is told nothing\n * about a fee it could name, so the customer approves a summary that never\n * disclosed one and then gets charged it.\n *\n * Resent on every turn, since the endpoint is stateless.\n */\n developerFee?: DeveloperFee;\n}\n\n/**\n * A stateful, multi-turn proposals chat with one agent.\n *\n * Keeps the running transcript, appends each user message and the agent's\n * reply, and resends the whole transcript on every {@link send} — so\n * callers never deal with the stateless endpoint's \"send all history each\n * time\" contract.\n *\n * For a stateless backend (one HTTP request per chat message), persist\n * {@link messages} between requests and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\nexport class AgentConversation {\n private readonly client: DakotaClient;\n private readonly paymentAgentId: string;\n private readonly timezone?: string;\n private readonly timeout?: number;\n private readonly developerFee?: DeveloperFee;\n private history: ChatMessage[] = [];\n\n constructor(\n client: DakotaClient,\n paymentAgentId: string,\n history?: ChatMessage[],\n options?: AgentConversationOptions\n ) {\n this.client = client;\n this.paymentAgentId = paymentAgentId;\n this.timezone = options?.timezone;\n this.timeout = options?.timeout;\n this.developerFee = options?.developerFee;\n if (history && history.length > 0) {\n this.history = history.map(cloneMessage);\n }\n }\n\n /**\n * Adds the user's message to the transcript, asks the agent, records the\n * agent's reply, and returns the turn. When `hasProposals` is true the\n * agent has drafted a reviewable action series; otherwise `reply` holds\n * its next question.\n *\n * On error the optimistic user turn is rolled back, so the caller may\n * retry the same call without duplicating it.\n */\n async send(userMessage: string): Promise<ConversationTurn> {\n return this.sendWithAttachments(userMessage);\n }\n\n /**\n * {@link send} with documents (e.g. an invoice PDF) attached to the user\n * turn for the agent to read and draft payments from. Same turn semantics\n * and rollback-on-error behavior as `send`. Attachments ride only on the\n * turn they are passed; the stateless transcript keeps the agent's text\n * reply, so a follow-up turn relies on that summary rather than re-sending\n * the document.\n */\n async sendWithAttachments(\n userMessage: string,\n attachments?: Attachment[]\n ): Promise<ConversationTurn> {\n const hasAttachments = attachments !== undefined && attachments.length > 0;\n this.history.push({\n role: 'user',\n content: userMessage,\n ...(hasAttachments ? { attachments } : {}),\n });\n\n const messages = this.history.map(serializeMessage);\n\n // Attachments ride only on THIS request: they are serialized into\n // `messages` above, then dropped from the stored transcript so they are\n // neither persisted via messages() / resumeAgentConversation nor\n // re-sent on later turns.\n if (hasAttachments) {\n const last = this.history[this.history.length - 1];\n if (last) {\n delete last.attachments;\n }\n }\n\n let result: AgenticProposalsResult;\n try {\n result = await this.client.paymentAgents.createProposals(\n this.paymentAgentId,\n {\n messages,\n // Resent on EVERY turn — the endpoint is stateless, so a value\n // given once would be forgotten on the next one.\n ...(this.timezone ? { timezone: this.timezone } : {}),\n ...(this.developerFee ? { developer_fee: this.developerFee } : {}),\n },\n this.timeout !== undefined ? { timeout: this.timeout } : undefined\n );\n } catch (err) {\n // Roll back the optimistic user turn so a retry does not duplicate it.\n this.history.pop();\n throw err;\n }\n\n const turn: ConversationTurn = {\n reply: result.reply ?? '',\n proposals: result.proposals ? [...result.proposals] : [],\n hasProposals: !!result.proposals && result.proposals.length > 0,\n blockers: result.blockers ? [...result.blockers] : [],\n hasBlockers: !!result.blockers && result.blockers.length > 0,\n conversationStatus: result.conversation_status ?? '',\n };\n\n // `rejected_input`: the server refused this message WHOLESALE and told us\n // not to keep it. Roll the optimistic user turn back and record no\n // assistant turn, so the transcript is identical to before this send. The\n // conversation itself continues unaffected — the caller still gets the\n // turn, whose `reply` explains what to resend.\n //\n // Without this the refused message stays in the transcript and is\n // re-transmitted on every later turn — the exact message the server asked\n // the client to drop — corrupting the conversation from here on. And\n // `messages()` returns a copy, so a caller could not repair it either.\n if (turn.conversationStatus === REJECTED_INPUT) {\n this.history.pop();\n return turn;\n }\n\n // Record an assistant turn so the transcript keeps alternating — the\n // platform (and the underlying model) reject two consecutive user\n // turns. Fall back to a placeholder when the agent returned only\n // proposals with no reply text.\n let assistant = turn.reply;\n if (!assistant) {\n assistant = turn.hasProposals ? '(drafted proposals for your review)' : '(no reply)';\n }\n this.history.push({ role: 'assistant', content: assistant });\n\n return turn;\n }\n\n /**\n * A copy of the full transcript so far. Persist this between requests in\n * a stateless backend and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\n messages(): ChatMessage[] {\n return this.history.map(cloneMessage);\n }\n}\n\nfunction cloneMessage(m: ChatMessage): ChatMessage {\n const out: ChatMessage = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => ({ ...a }));\n }\n return out;\n}\n\nfunction serializeMessage(m: ChatMessage): {\n role: 'user' | 'assistant';\n content: string;\n attachments?: {\n type: 'document';\n document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n };\n }[];\n} {\n const out: ReturnType<typeof serializeMessage> = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => {\n const document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n } = {\n media_type: a.mediaType,\n data: Buffer.from(a.data).toString('base64'),\n };\n if (a.filename) {\n document.filename = a.filename;\n }\n return { type: 'document' as const, document };\n });\n }\n return out;\n}\n","/**\n * High-level agentic helpers: collapse the multi-step, crypto-heavy hosted-\n * agent flows into single calls with good defaults, so a partner integration\n * stays short. The raw operations remain reachable via the resource classes\n * on `DakotaClient`.\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport type { DakotaClient } from '../client/client.js';\n\n/**\n * Grant a principal — a user OR an agent, both are just signers — permission\n * to spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet: the group whose attached policies should govern it.\n *\n * That membership change is the whole operation, and it is UNENDORSED: group\n * membership is a client-admin action, not a wallet endorsement, so it needs\n * NO signature — not from the wallet owner, not from the principal being\n * added. From then on the principal's transactions are subject to exactly\n * the policies bound to `spendingGroupId`, the same as any other member of\n * that group. The per-payment spend bound remains the agentic mandate gate,\n * not the policy.\n *\n * Deliberately reuses the wallet's pre-built policies and creates NO\n * per-signer policy. Two policy-engine realities make a per-signer policy\n * the wrong tool: a policy → wallet attach is endorsed by the policy's OWN\n * signer group (so only that group's key could attach it), and an\n * unconditional approval-threshold ALLOW policy inverts to a deny for any\n * transaction its group didn't sign, so a second signer's policy would veto\n * the first. Prepare the wallet's groups + policies in advance and point\n * each principal at the group whose constraints you want it to inherit.\n *\n * Idempotent: if the signer is already a member, returns\n * `alreadyMember: true` and makes no write. Rejects `spendingGroupId` if it\n * is not attached to `walletId`, so a wrong group fails loudly instead of\n * silently granting nothing.\n *\n * The key must already exist as a signer resource — the add endpoint takes\n * a `member_key` reference, it does not register keys. A hosted agent's key\n * is minted by `paymentAgents.create`; for a bare user key, register it\n * first (`POST /signers`) or the add fails with a signer-not-found error.\n *\n * @param client - Dakota client\n * @param walletId - The wallet the principal will spend from\n * @param signerPublicKey - The principal's registered signer public key\n * (base64 PKIX) — e.g. `signer_public_key` returned by\n * `paymentAgents.create` for a hosted agent\n * @param spendingGroupId - The signer group whose attached policies should\n * govern the principal; must already be attached to `walletId`\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID — the\n * platform rejects other formats with 400) to make the WHOLE helper\n * safely retryable — a crashed or partitioned call replayed with the\n * same key dedupes the underlying write server-side. Defaults to a\n * fresh random UUID per call.\n * @returns `{ alreadyMember }` — true when the signer was already a member\n * (no write performed)\n */\nexport async function attachUserToWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ alreadyMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Idempotency: skip the add if the signer's key is already a member.\n const group = await client.signerGroups.get(spendingGroupId);\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n return { alreadyMember: true };\n }\n }\n\n // Add the signer to the group (unendorsed). Granting spend permission is\n // security-relevant, so set an explicit idempotency key rather than depend\n // on transport config (`automaticIdempotency: false` would otherwise send\n // this POST without the required header and 400).\n await client.signerGroups.addSigner(\n spendingGroupId,\n { member_key: signerPublicKey },\n { idempotencyKey: options?.idempotencyKey ?? randomUUID() }\n );\n return { alreadyMember: false };\n}\n\n/**\n * Revoke a principal's spend permission by removing its signer from\n * `spendingGroupId` — the inverse of {@link attachUserToWallet}, and\n * likewise UNENDORSED (no signature).\n *\n * Deliberately SCOPED to the one group you pass, NOT a sweep across every\n * group on the wallet, for two reasons:\n * - signer groups are NOT wallet-exclusive — the same group can govern\n * multiple wallets — so removing a signer from a group revokes it on\n * EVERY wallet that group governs; passing one explicit group keeps\n * that blast radius known instead of multiplying it across all of the\n * wallet's groups;\n * - a sweep cannot tell \"added for this agent\" from \"belongs here for\n * another reason\" (e.g. the human owner sitting in the admin group),\n * so it can lock out a legitimate member.\n *\n * Pass the same group you used to attach. Idempotent: if the signer isn't\n * a member, it is a no-op (`wasMember: false`). Rejects `spendingGroupId`\n * if it is not attached to `walletId`.\n *\n * NOTE: this does not guard against removing a group's LAST member —\n * emptying the group that governs a wallet can leave it with no authorized\n * signer. The caller must avoid stranding the wallet. For a hosted agent,\n * prefer `paymentAgents.revoke` (it destroys the agent's key, so the signer\n * can authorize nothing even while still listed) and use this for\n * membership hygiene.\n *\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID) to\n * make the WHOLE helper safely retryable across crashes/partitions;\n * defaults to a fresh random UUID per call.\n */\nexport async function detachUserFromWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ wasMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Resolve the signer's public key → its resource id within the group: the\n // delete endpoint addresses members by id, not key. Absent ⇒ idempotent\n // no-op.\n const group = await client.signerGroups.get(spendingGroupId);\n let signerId = '';\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n signerId = member.id ?? '';\n break;\n }\n }\n if (!signerId) {\n return { wasMember: false };\n }\n\n // The platform requires an idempotency key on this DELETE. The transport\n // now injects one on DELETEs too, but revoking spend permission is\n // security-relevant, so we set one explicitly — this path must not depend\n // on transport configuration.\n await client.signerGroups.removeSigner(spendingGroupId, signerId, {\n idempotencyKey: options?.idempotencyKey ?? randomUUID(),\n });\n return { wasMember: true };\n}\n\n/**\n * Errors unless `spendingGroupId` is one of the signer groups attached to\n * `walletId` — so attach/detach can't silently operate on a group that has\n * nothing to do with the named wallet.\n *\n * Uses the symmetric group → wallets read (`GET /signer-groups/{id}/wallets`)\n * because it returns a bare array with a stable shape. Semantically\n * equivalent to `GET /wallets/{id}/signer-groups`; the check succeeds iff\n * the pair is attached.\n */\nasync function requireGroupOnWallet(\n client: DakotaClient,\n walletId: string,\n spendingGroupId: string\n): Promise<void> {\n const wallets = await client.signerGroups.getWallets(spendingGroupId);\n for (const w of wallets) {\n if (w.id === walletId) {\n return;\n }\n }\n throw new Error(`signer group ${spendingGroupId} is not attached to wallet ${walletId}`);\n}\n","/**\n * Dakota Platform API Client.\n */\n\nimport { DakotaClientConfig, ResolvedConfig, resolveConfig } from './config.js';\nimport { Transport } from './transport.js';\nimport {\n CustomersResource,\n RecipientsResource,\n DestinationsResource,\n AccountsResource,\n TransactionsResource,\n AutoTransactionsResource,\n WalletsResource,\n EventsResource,\n ApplicationsResource,\n PoliciesResource,\n SignerGroupsResource,\n SignersResource,\n ApiKeysResource,\n UsersResource,\n WebhooksResource,\n InfoResource,\n LegalResource,\n RDMarketingFeeResource,\n SandboxResource,\n SelfServeResource,\n FeePayoutDestinationResource,\n PaymentAgentsResource,\n InstructionsResource,\n MandatesResource,\n ScheduledPaymentsResource,\n InsightsResource,\n AgenticPolicyResource,\n} from './resources/index.js';\nimport {\n AgentConversation,\n type AgentConversationOptions,\n type ChatMessage,\n} from '../agentic/chat.js';\nimport {\n attachUserToWallet as attachUserToWalletHelper,\n detachUserFromWallet as detachUserFromWalletHelper,\n} from '../agentic/wallets.js';\n\n/**\n * Dakota Platform API Client.\n *\n * The main entry point for interacting with the Dakota Platform API.\n *\n * @example\n * ```typescript\n * import { DakotaClient, Environment } from 'dakota-ts-sdk';\n *\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * environment: Environment.Sandbox, // default\n * });\n *\n * // List customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // Create a customer\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customer_type: 'business',\n * });\n * ```\n */\nexport class DakotaClient {\n private readonly config: ResolvedConfig;\n private readonly transport: Transport;\n\n // API Resources\n /** Customers API - manage customer records and KYB */\n readonly customers: CustomersResource;\n /** Recipients API - manage payment recipients */\n readonly recipients: RecipientsResource;\n /** Destinations API - manage bank accounts and crypto wallets */\n readonly destinations: DestinationsResource;\n /** Accounts API - manage on-ramp, off-ramp, and swap accounts */\n readonly accounts: AccountsResource;\n /** Transactions API - manage one-off transactions */\n readonly transactions: TransactionsResource;\n /** Auto Transactions API - manage automated transactions */\n readonly autoTransactions: AutoTransactionsResource;\n /** Wallets API - manage non-custodial wallets */\n readonly wallets: WalletsResource;\n /** Events API - query platform events */\n readonly events: EventsResource;\n /** Applications API - manage KYB applications */\n readonly applications: ApplicationsResource;\n /** Policies API - manage transaction policies */\n readonly policies: PoliciesResource;\n /** Signer Groups API - manage multi-sig signer groups */\n readonly signerGroups: SignerGroupsResource;\n /** Signers API - manage individual signers */\n readonly signers: SignersResource;\n /** API Keys API - manage API keys */\n readonly apiKeys: ApiKeysResource;\n /** Users API - manage platform users */\n readonly users: UsersResource;\n /** Webhooks API - manage webhook targets and events */\n readonly webhooks: WebhooksResource;\n /** Info API - query platform capabilities */\n readonly info: InfoResource;\n /** Legal API - the published terms customers accept (unauthenticated) */\n readonly legal: LegalResource;\n /** RD Marketing Fee API - this client's reserve-management statements */\n readonly rdMarketingFee: RDMarketingFeeResource;\n /** Sandbox API - testing simulations (sandbox only) */\n readonly sandbox: SandboxResource;\n /** Self-Serve Credits API - manage prepaid transfer credits */\n readonly selfServe: SelfServeResource;\n /** Fee Payout Destination API - where Dakota pays your accrued developer fees */\n readonly feePayoutDestination: FeePayoutDestinationResource;\n /** Payment Agents API (ALPHA) - hosted signing agents that draft payments */\n readonly paymentAgents: PaymentAgentsResource;\n /** Instructions API (ALPHA) - accept and inspect actuated proposals */\n readonly instructions: InstructionsResource;\n /** Mandates API (ALPHA) - the §8 authorizations that arm scheduled payments */\n readonly mandates: MandatesResource;\n /** Scheduled Payments API (ALPHA) - schedule rows created from instructions */\n readonly scheduledPayments: ScheduledPaymentsResource;\n /** Insights API (ALPHA) - read-only advisory reporting over agentic activity */\n readonly insights: InsightsResource;\n /** Agentic Policy API (ALPHA) - register the vocabulary the agent speaks for your product */\n readonly agenticPolicy: AgenticPolicyResource;\n\n /**\n * Create a new Dakota client.\n *\n * @param config - Client configuration\n * @throws ConfigurationError if configuration is invalid\n *\n * @example\n * ```typescript\n * // Basic usage (sandbox)\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * });\n *\n * // Production\n * const client = new DakotaClient({\n * apiKey: 'your_production_api_key',\n * environment: Environment.Production,\n * });\n *\n * // With custom configuration\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * timeout: 30000,\n * retryPolicy: {\n * maxAttempts: 5,\n * initialBackoffMs: 100,\n * maxBackoffMs: 5000,\n * },\n * logger: console,\n * });\n * ```\n */\n constructor(config: DakotaClientConfig) {\n this.config = resolveConfig(config);\n this.transport = new Transport(this.config);\n\n // Initialize resources\n this.customers = new CustomersResource(this.transport);\n this.recipients = new RecipientsResource(this.transport);\n this.destinations = new DestinationsResource(this.transport);\n this.accounts = new AccountsResource(this.transport);\n this.transactions = new TransactionsResource(this.transport);\n this.autoTransactions = new AutoTransactionsResource(this.transport);\n this.wallets = new WalletsResource(this.transport);\n this.events = new EventsResource(this.transport);\n this.applications = new ApplicationsResource(this.transport);\n this.policies = new PoliciesResource(this.transport);\n this.signerGroups = new SignerGroupsResource(this.transport);\n this.signers = new SignersResource(this.transport);\n this.apiKeys = new ApiKeysResource(this.transport);\n this.users = new UsersResource(this.transport);\n this.webhooks = new WebhooksResource(this.transport);\n this.info = new InfoResource(this.transport);\n this.legal = new LegalResource(this.transport);\n this.rdMarketingFee = new RDMarketingFeeResource(this.transport);\n this.sandbox = new SandboxResource(this.transport);\n this.selfServe = new SelfServeResource(this.transport);\n this.feePayoutDestination = new FeePayoutDestinationResource(this.transport);\n this.paymentAgents = new PaymentAgentsResource(this.transport);\n this.instructions = new InstructionsResource(this.transport);\n this.mandates = new MandatesResource(this.transport);\n this.scheduledPayments = new ScheduledPaymentsResource(this.transport);\n this.insights = new InsightsResource(this.transport);\n this.agenticPolicy = new AgenticPolicyResource(this.transport);\n }\n\n // ==========================================================================\n // Agentic Payments high-level helpers (ALPHA)\n //\n // Collapse the multi-step, crypto-heavy hosted-agent flows into single\n // calls with good defaults. The raw operations remain reachable via\n // `signerGroups.addSigner` / `signerGroups.removeSigner` and friends.\n // ==========================================================================\n\n /**\n * Start a fresh multi-turn conversation with a payment agent.\n *\n * Pass `{ timezone }` (an IANA zone) so the agent resolves \"tomorrow\" and\n * \"10 am\" in the customer's local time rather than UTC. The conversation\n * resends it on every turn.\n *\n * @see AgentConversation\n */\n newAgentConversation(\n paymentAgentId: string,\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, undefined, options);\n }\n\n /**\n * Rebuild a conversation from a persisted transcript (oldest first) —\n * for backends that store the history between requests.\n *\n * A stateless backend must pass `{ timezone }` again here: the transcript\n * carries the messages, not the zone.\n */\n resumeAgentConversation(\n paymentAgentId: string,\n history: ChatMessage[],\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, history, options);\n }\n\n /**\n * Grant a principal (user or agent — both are just signers) permission to\n * spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet. Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see attachUserToWallet in `agentic/wallets.ts` for the full contract.\n */\n attachUserToWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ alreadyMember: boolean }> {\n return attachUserToWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Revoke a principal's spend permission by removing its signer from the\n * given signer group — the inverse of {@link attachUserToWallet}.\n * Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see detachUserFromWallet in `agentic/wallets.ts` for the full contract.\n */\n detachUserFromWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ wasMember: boolean }> {\n return detachUserFromWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Get the resolved base URL.\n */\n get baseURL(): string {\n return this.config.baseURL;\n }\n}\n","/**\n * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.\n *\n * A payload canonicalized here matches the platform's `enc.C14nJSON`\n * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a\n * signature produced from the result verifies server-side.\n *\n * This implementation covers the value shapes the SDK ever puts into a\n * signed payload: nulls, booleans, finite integers/floats, strings,\n * arrays, and plain object maps. It intentionally does NOT handle\n * non-integer numbers with fractional parts differently from\n * JSON.stringify, because every mandate/endorsement payload the SDK\n * produces uses only integers, strings, arrays, and object maps — decimal\n * amounts are always sent as strings.\n */\n\n/**\n * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.\n *\n * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a\n * circular reference — any of which cannot be encoded to canonical JSON.\n */\nexport function canonicalJSON(value: unknown): string {\n return canonicalize(value);\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonical JSON: non-finite number ${value}`);\n }\n // JSON.stringify already emits ES6 Number.prototype.toString() for\n // finite numbers, which is exactly what RFC 8785 § 3.2.2.3 mandates.\n return JSON.stringify(value);\n }\n if (typeof value === 'string') {\n // JSON.stringify handles JSON escape sequences per RFC 8259, matching\n // JCS's string-escape rules (§ 3.2.2.2).\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n // BigInts have no unambiguous number representation for JSON;\n // fail loudly rather than produce bytes that won't verify.\n throw new TypeError('canonical JSON: bigint values are not supported');\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => canonicalize(item));\n return `[${parts.join(',')}]`;\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // JCS sorts object member keys by their UTF-16 code-unit order,\n // which is exactly what a JavaScript `Array.prototype.sort()` on\n // strings produces (§ 3.2.3).\n const keys = Object.keys(obj).sort();\n const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);\n return `{${parts.join(',')}}`;\n }\n throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);\n}\n","/**\n * §8 mandate signing. Approving (or cancelling) a mandate is not a bare API\n * call: it requires a cryptographic signature over the mandate's canonical\n * bytes, proving the action came from a holder of the registered key. This\n * file reproduces the platform's exact signed payload (RFC 8785 / JCS\n * canonical JSON) and a P-256 signing/verification path, so partners never\n * hand-roll JCS + ECDSA.\n *\n * The canonical bytes a signature covers — matched byte-for-byte with the\n * platform's MandatePayload — are JCS JSON of:\n *\n * {action, id, bound_signer, rule, valid_from, valid_until}\n *\n * signed as base64( ASN.1( ECDSA-P256( SHA-256(payload) ))), with the public\n * key as base64 PKIX (SPKI).\n *\n * Agentic payments is an alpha surface (x-alpha, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n createSign,\n createVerify,\n generateKeyPairSync,\n KeyObject,\n} from 'node:crypto';\n\nimport type { Mandate, MandateRule } from '../client/types.js';\nimport { canonicalJSON } from './canonicalize.js';\n\n/**\n * The §8 verb a signature authorizes. It is part of the signed payload so\n * an approval and a cancellation can never be each other's replay: a signed\n * cancel must not be byte-identical to a signed approve.\n */\nexport type MandateAction = 'approve' | 'cancel';\n\n/**\n * Produces the §8 signature the platform verifies for a mandate\n * approve/cancel. The caller holds the private key; the SDK never sees it.\n *\n * Implement this over your own key custody (HSM/KMS) for production. For\n * sandbox and tests, `P256MandateSigner` is a ready in-memory implementation.\n */\nexport interface MandateSigner {\n /**\n * The base64 PKIX (SPKI) P-256 public key — the exact form the platform\n * registered for this signer and verifies signatures against.\n */\n publicKeyBase64(): string;\n\n /**\n * Returns a base64 ASN.1 ECDSA signature over SHA-256(payload).\n */\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform signs for one\n * §8 action on a mandate. Build it straight from the mandate as returned by\n * `mandates.get` / `mandates.list` — no server state is needed, and field\n * order is irrelevant (JCS sorts).\n *\n * `valid_from` / `valid_until` are always present in the signed payload\n * (even when zero); the wire omits a zero value, so a missing field\n * canonicalizes to 0 — matching the platform, which signs the int64\n * directly.\n */\nexport function mandateSignPayload(mandate: Mandate, action: MandateAction): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!mandate.rule) {\n throw new Error('mandate has no rule');\n }\n const encoded = canonicalJSON({\n action,\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule: mandate.rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n });\n return new TextEncoder().encode(encoded);\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform verifies for an\n * AMEND — appending version `version`, carrying `rule`, to `mandate`.\n *\n * The approve/cancel bytes are frozen, so amend gets its own payload rather\n * than an extra key on `mandateSignPayload`. It is the same JCS JSON plus one\n * key, `version`:\n *\n * {action: 'amend', id, bound_signer, rule, valid_from, valid_until, version}\n *\n * **`version` is what stops cross-version replay.** Without it, a signature\n * over `{amend, rule R}` would authorize \"make the current rule R\" forever: a\n * customer who signs v2 raising a limit to 20,000 and then v3 lowering it to\n * 5,000 could have the v2 signature replayed as a v4 — a rollback of their own\n * reduction, using their own signature. Binding the exact version number makes\n * each amend signature usable once, at one point in the mandate's history.\n *\n * `rule` is the NEW rule (what the signer is agreeing to), not the outgoing\n * one, and is taken verbatim — the amend endpoint never normalizes it, so the\n * bytes signed here are the bytes the server verifies. Pass the SAME rule\n * object to `mandates.amend`.\n *\n * @param mandate - The mandate as it is NOW (the amend is a compare-and-set on\n * its current version)\n * @param version - The version this amend creates — the mandate's current\n * `version` + 1\n * @param rule - The complete new rule, in canonical form\n */\nexport function mandateAmendSignPayload(\n mandate: Mandate,\n version: number,\n rule: MandateRule\n): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!Number.isInteger(version) || version < 2) {\n throw new Error('amend version must be an integer >= 2 (the version being created)');\n }\n const encoded = canonicalJSON({\n action: 'amend',\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n version,\n });\n return new TextEncoder().encode(encoded);\n}\n\n// ---------------------------------------------------------------------------\n// Endorsed-intent payload helpers.\n// ---------------------------------------------------------------------------\n//\n// Each reproduces, byte-for-byte, the canonical map the platform's policy\n// engine rebuilds to verify the endorsement (its intent reconstruction).\n// The idempotency_key is part of the signed bytes — reuse the SAME key on\n// the corresponding request.\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a signer\n * group to a wallet.\n */\nexport function attachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_group_to_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a policy to\n * a wallet.\n */\nexport function attachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_policy_to_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a signer\n * group from a wallet — the inverse of {@link attachGroupPayload}.\n */\nexport function detachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_group_from_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a policy\n * from a wallet — the inverse of {@link attachPolicyPayload}.\n */\nexport function detachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_policy_from_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to delete a policy.\n */\nexport function deletePolicyPayload(policyId: string, idempotencyKey: string): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'delete_policy',\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to remove a rule from a policy.\n */\nexport function removePolicyRulePayload(\n policyId: string,\n ruleId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'remove_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to update a rule's definition. `updatedDefinition` is the rule definition\n * as a JSON STRING; it is signed opaquely, exactly as sent on the update\n * request.\n */\nexport function updatePolicyRulePayload(\n policyId: string,\n ruleId: string,\n updatedDefinition: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'update_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n updated_definition: updatedDefinition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to add a rule to a policy. `action` (e.g. `\"allow\"`), `ruleType` (e.g.\n * `\"amount_threshold\"`), and `definition` (the rule-type-specific config,\n * in API format) must match the values sent on the add request, or the\n * endorsement won't verify against it.\n */\nexport function addPolicyRulePayload(\n policyId: string,\n action: string,\n ruleType: string,\n definition: Record<string, unknown>,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'add_policy_rule',\n action,\n rule_type: ruleType,\n policy_id: policyId,\n definition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\nfunction textBytes(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n// ---------------------------------------------------------------------------\n// P256MandateSigner — default in-memory signer (sandbox / tests)\n// ---------------------------------------------------------------------------\n\n/**\n * A {@link MandateSigner} holding a P-256 (ES256) private key in memory.\n *\n * Convenient for sandbox and tests; for production, implement\n * {@link MandateSigner} over your own key custody so the private key never\n * lives in the process.\n */\nexport class P256MandateSigner implements MandateSigner {\n private readonly privateKey: KeyObject;\n private readonly publicKey: KeyObject;\n\n private constructor(privateKey: KeyObject, publicKey: KeyObject) {\n this.privateKey = privateKey;\n this.publicKey = publicKey;\n }\n\n /**\n * Generate a fresh P-256 keypair.\n */\n static generate(): P256MandateSigner {\n const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a\n * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.\n */\n static fromPrivateKey(key: KeyObject | string | Uint8Array): P256MandateSigner {\n const privateKey =\n typeof key === 'string' || key instanceof Uint8Array\n ? createPrivateKey({\n key: key as string | Buffer,\n format: typeof key === 'string' ? 'pem' : 'der',\n type: 'pkcs8',\n })\n : key;\n if (privateKey.asymmetricKeyType !== 'ec') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const details = privateKey.asymmetricKeyDetails;\n if (details?.namedCurve !== 'prime256v1') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const publicKey = createPublicKey(privateKey);\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * base64 PKIX (SPKI) public key — pass this as the signer's registered\n * public key at agent creation / mandate approval.\n */\n publicKeyBase64(): string {\n const der = this.publicKey.export({ format: 'der', type: 'spki' });\n return Buffer.from(der).toString('base64');\n }\n\n /**\n * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).\n */\n sign(payload: Uint8Array): string {\n const signer = createSign('SHA256');\n signer.update(payload);\n const sig = signer.sign({ key: this.privateKey, dsaEncoding: 'der' });\n return Buffer.from(sig).toString('base64');\n }\n}\n\n/**\n * Check a base64 ASN.1 signature over SHA-256 of the canonical payload\n * against a base64 PKIX P-256 public key — the platform's exact\n * verification. Exposed so callers (and tests) can self-check a signature\n * before submitting it.\n *\n * @throws if the public key or signature can't be parsed, or the signature\n * does not verify against the payload.\n */\nexport function verifyMandateSignature(\n publicKeyBase64: string,\n payload: Uint8Array,\n signatureBase64: string\n): void {\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({\n key: Buffer.from(publicKeyBase64, 'base64'),\n format: 'der',\n type: 'spki',\n });\n } catch (err) {\n throw new Error(`parse public key: ${(err as Error).message}`);\n }\n if (publicKey.asymmetricKeyType !== 'ec') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n if (publicKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n const verifier = createVerify('SHA256');\n verifier.update(payload);\n const ok = verifier.verify(\n { key: publicKey, dsaEncoding: 'der' },\n Buffer.from(signatureBase64, 'base64')\n );\n if (!ok) {\n throw new Error('signature verification failed');\n }\n}\n"]}
|