@useagentpay/sdk 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/cjs_shims.js","../src/errors.ts","../src/transactions/poller.ts","../src/index.ts","../src/utils/ids.ts","../src/utils/display.ts","../src/utils/paths.ts","../src/vault/vault.ts","../src/auth/keypair.ts","../src/auth/mandate.ts","../src/budget/budget.ts","../src/transactions/manager.ts","../src/audit/logger.ts","../src/executor/executor.ts","../src/executor/placeholder.ts","../src/agentpay.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","export class NotSetupError extends Error {\n readonly code = 'NOT_SETUP';\n constructor(message = 'AgentPay has not been set up yet. Run `agentpay setup` first.') {\n super(message);\n this.name = 'NotSetupError';\n }\n}\n\nexport class DecryptError extends Error {\n readonly code = 'DECRYPT_FAILED';\n constructor(message = 'Failed to decrypt credentials. Wrong passphrase or corrupted file.') {\n super(message);\n this.name = 'DecryptError';\n }\n}\n\nexport class InsufficientBalanceError extends Error {\n readonly code = 'INSUFFICIENT_BALANCE';\n constructor(amount?: number, balance?: number) {\n const msg = amount !== undefined && balance !== undefined\n ? `Insufficient balance: requested $${amount.toFixed(2)} but only $${balance.toFixed(2)} available.`\n : 'Insufficient balance for this transaction.';\n super(msg);\n this.name = 'InsufficientBalanceError';\n }\n}\n\nexport class ExceedsTxLimitError extends Error {\n readonly code = 'EXCEEDS_TX_LIMIT';\n constructor(amount?: number, limit?: number) {\n const msg = amount !== undefined && limit !== undefined\n ? `Amount $${amount.toFixed(2)} exceeds per-transaction limit of $${limit.toFixed(2)}.`\n : 'Amount exceeds per-transaction limit.';\n super(msg);\n this.name = 'ExceedsTxLimitError';\n }\n}\n\nexport class NotApprovedError extends Error {\n readonly code = 'NOT_APPROVED';\n constructor(txId?: string) {\n super(txId ? `Transaction ${txId} has not been approved.` : 'Transaction has not been approved.');\n this.name = 'NotApprovedError';\n }\n}\n\nexport class InvalidMandateError extends Error {\n readonly code = 'INVALID_MANDATE';\n constructor(message = 'Purchase mandate signature verification failed.') {\n super(message);\n this.name = 'InvalidMandateError';\n }\n}\n\nexport class AlreadyExecutedError extends Error {\n readonly code = 'ALREADY_EXECUTED';\n constructor(txId?: string) {\n super(txId ? `Transaction ${txId} has already been executed.` : 'Transaction has already been executed.');\n this.name = 'AlreadyExecutedError';\n }\n}\n\nexport class CheckoutFailedError extends Error {\n readonly code = 'CHECKOUT_FAILED';\n constructor(message = 'Failed to complete checkout.') {\n super(message);\n this.name = 'CheckoutFailedError';\n }\n}\n\nexport class TimeoutError extends Error {\n readonly code = 'TIMEOUT';\n constructor(message = 'Operation timed out.') {\n super(message);\n this.name = 'TimeoutError';\n }\n}\n","import type { Transaction } from './types.js';\nimport type { TransactionManager } from './manager.js';\nimport { TimeoutError } from '../errors.js';\n\nexport interface PollOptions {\n pollInterval?: number;\n timeout?: number;\n}\n\nexport async function waitForApproval(\n txId: string,\n manager: TransactionManager,\n options?: PollOptions,\n): Promise<{ status: 'approved' | 'rejected'; reason?: string }> {\n const interval = options?.pollInterval ?? 2000;\n const timeout = options?.timeout ?? 300_000;\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const tx = manager.get(txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n\n if (tx.status === 'approved') return { status: 'approved' };\n if (tx.status === 'rejected') return { status: 'rejected', reason: tx.rejectionReason };\n\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n\n throw new TimeoutError(`Timed out waiting for approval of ${txId}`);\n}\n","export const VERSION = '0.1.0';\n\n// Types\nexport type { BillingCredentials, EncryptedVault } from './vault/types.js';\nexport type { KeyPair, PurchaseMandate, TransactionDetails } from './auth/types.js';\nexport type { Wallet } from './budget/types.js';\nexport type { Transaction, TransactionStatus, Receipt, ProposeOptions } from './transactions/types.js';\nexport type { CheckoutResult, ExecutorConfig } from './executor/types.js';\n\n// Errors\nexport {\n NotSetupError,\n DecryptError,\n InsufficientBalanceError,\n ExceedsTxLimitError,\n NotApprovedError,\n InvalidMandateError,\n AlreadyExecutedError,\n CheckoutFailedError,\n TimeoutError,\n} from './errors.js';\n\n// Utilities\nexport { generateTxId } from './utils/ids.js';\nexport { formatCurrency, formatTimestamp, formatTable, formatStatus } from './utils/display.js';\nexport { getHomePath, getCredentialsPath, getKeysPath, getWalletPath, getTransactionsPath, getAuditPath } from './utils/paths.js';\n\n// Vault\nexport { encrypt, decrypt, saveVault, loadVault } from './vault/vault.js';\n\n// Auth\nexport { generateKeyPair, saveKeyPair, loadPublicKey, loadPrivateKey } from './auth/keypair.js';\nexport { createMandate, verifyMandate } from './auth/mandate.js';\n\n// Budget\nexport { BudgetManager } from './budget/budget.js';\n\n// Transactions\nexport { TransactionManager } from './transactions/manager.js';\nexport { waitForApproval } from './transactions/poller.js';\n\n// Audit\nexport { AuditLogger } from './audit/logger.js';\n\n// Executor\nexport { PurchaseExecutor } from './executor/executor.js';\nexport { PLACEHOLDER_MAP, getPlaceholderVariables, credentialsToSwapMap } from './executor/placeholder.js';\n\n// AgentPay\nexport { AgentPay } from './agentpay.js';\nexport type { AgentPayOptions } from './agentpay.js';\n","import { randomBytes } from 'node:crypto';\n\nexport function generateTxId(): string {\n return `tx_${randomBytes(4).toString('hex')}`;\n}\n","import type { Transaction } from '../transactions/types.js';\n\nexport function formatCurrency(amount: number): string {\n return `$${amount.toFixed(2)}`;\n}\n\nexport function formatTimestamp(iso: string): string {\n const d = new Date(iso);\n return d.toLocaleString('en-US', {\n month: 'short',\n day: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n });\n}\n\nexport function formatTable(transactions: Transaction[]): string {\n if (transactions.length === 0) return 'No transactions.';\n\n const header = 'TX_ID MERCHANT AMOUNT DESCRIPTION';\n const separator = '─'.repeat(header.length);\n const rows = transactions.map((tx) => {\n const id = tx.id.padEnd(14);\n const merchant = tx.merchant.padEnd(16);\n const amount = formatCurrency(tx.amount).padStart(9);\n return `${id}${merchant}${amount} ${tx.description}`;\n });\n\n return [header, separator, ...rows].join('\\n');\n}\n\nexport function formatStatus(data: {\n balance: number;\n budget: number;\n limitPerTx: number;\n pending: Transaction[];\n recent: Transaction[];\n}): string {\n const lines = [\n 'AgentPay Status',\n '───────────────',\n `Balance: ${formatCurrency(data.balance)} / ${formatCurrency(data.budget)}`,\n `Per-tx limit: ${formatCurrency(data.limitPerTx)}`,\n `Pending purchases: ${data.pending.length}`,\n ];\n\n if (data.recent.length > 0) {\n lines.push('', 'Recent:');\n for (const tx of data.recent) {\n const status = `[${tx.status}]`.padEnd(12);\n lines.push(` ${status} ${tx.id} ${tx.merchant.padEnd(12)} ${formatCurrency(tx.amount).padStart(8)} ${tx.description}`);\n }\n }\n\n return lines.join('\\n');\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport function getHomePath(): string {\n return process.env.AGENTPAY_HOME || join(homedir(), '.agentpay');\n}\n\nexport function getCredentialsPath(): string {\n return join(getHomePath(), 'credentials.enc');\n}\n\nexport function getKeysPath(): string {\n return join(getHomePath(), 'keys');\n}\n\nexport function getPublicKeyPath(): string {\n return join(getKeysPath(), 'public.pem');\n}\n\nexport function getPrivateKeyPath(): string {\n return join(getKeysPath(), 'private.pem');\n}\n\nexport function getWalletPath(): string {\n return join(getHomePath(), 'wallet.json');\n}\n\nexport function getTransactionsPath(): string {\n return join(getHomePath(), 'transactions.json');\n}\n\nexport function getAuditPath(): string {\n return join(getHomePath(), 'audit.log');\n}\n","import { pbkdf2Sync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';\nimport { readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { BillingCredentials, EncryptedVault } from './types.js';\nimport { DecryptError, NotSetupError } from '../errors.js';\nimport { getCredentialsPath } from '../utils/paths.js';\n\nconst ALGORITHM = 'aes-256-gcm';\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_DIGEST = 'sha512';\nconst KEY_LENGTH = 32;\nconst SALT_LENGTH = 32;\nconst IV_LENGTH = 16;\n\nexport function deriveKey(passphrase: string, salt: Buffer): Buffer {\n return pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);\n}\n\nexport function encrypt(credentials: BillingCredentials, passphrase: string): EncryptedVault {\n const salt = randomBytes(SALT_LENGTH);\n const iv = randomBytes(IV_LENGTH);\n const key = deriveKey(passphrase, salt);\n\n const cipher = createCipheriv(ALGORITHM, key, iv);\n const plaintext = JSON.stringify(credentials);\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n const authTag = cipher.getAuthTag();\n\n return {\n ciphertext: Buffer.concat([encrypted, authTag]).toString('base64'),\n salt: salt.toString('base64'),\n iv: iv.toString('base64'),\n };\n}\n\nexport function decrypt(vault: EncryptedVault, passphrase: string): BillingCredentials {\n try {\n const salt = Buffer.from(vault.salt, 'base64');\n const iv = Buffer.from(vault.iv, 'base64');\n const data = Buffer.from(vault.ciphertext, 'base64');\n const key = deriveKey(passphrase, salt);\n\n const authTag = data.subarray(data.length - 16);\n const ciphertext = data.subarray(0, data.length - 16);\n\n const decipher = createDecipheriv(ALGORITHM, key, iv);\n decipher.setAuthTag(authTag);\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n\n return JSON.parse(decrypted.toString('utf8')) as BillingCredentials;\n } catch {\n throw new DecryptError();\n }\n}\n\nexport function saveVault(vault: EncryptedVault, path?: string): void {\n const filePath = path ?? getCredentialsPath();\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, JSON.stringify(vault, null, 2), { mode: 0o600 });\n}\n\nexport function loadVault(path?: string): EncryptedVault {\n const filePath = path ?? getCredentialsPath();\n try {\n const data = readFileSync(filePath, 'utf8');\n return JSON.parse(data) as EncryptedVault;\n } catch {\n throw new NotSetupError();\n }\n}\n","import { generateKeyPairSync, createPublicKey } from 'node:crypto';\nimport { readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { KeyPair } from './types.js';\nimport { getPublicKeyPath, getPrivateKeyPath } from '../utils/paths.js';\n\nexport function generateKeyPair(passphrase: string): KeyPair {\n const { publicKey, privateKey } = generateKeyPairSync('ed25519', {\n publicKeyEncoding: { type: 'spki', format: 'pem' },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase,\n },\n });\n\n return { publicKey, privateKey };\n}\n\nexport function saveKeyPair(keys: KeyPair, publicPath?: string, privatePath?: string): void {\n const pubPath = publicPath ?? getPublicKeyPath();\n const privPath = privatePath ?? getPrivateKeyPath();\n\n mkdirSync(dirname(pubPath), { recursive: true });\n writeFileSync(pubPath, keys.publicKey, { mode: 0o644 });\n writeFileSync(privPath, keys.privateKey, { mode: 0o600 });\n}\n\nexport function loadPublicKey(path?: string): string {\n return readFileSync(path ?? getPublicKeyPath(), 'utf8');\n}\n\nexport function loadPrivateKey(path?: string): string {\n return readFileSync(path ?? getPrivateKeyPath(), 'utf8');\n}\n","import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';\nimport type { PurchaseMandate, TransactionDetails } from './types.js';\nimport { InvalidMandateError } from '../errors.js';\n\nfunction hashTransactionDetails(details: TransactionDetails): string {\n const canonical = JSON.stringify({\n txId: details.txId,\n merchant: details.merchant,\n amount: details.amount,\n description: details.description,\n timestamp: details.timestamp,\n });\n return createHash('sha256').update(canonical).digest('hex');\n}\n\nexport function createMandate(\n txDetails: TransactionDetails,\n privateKeyPem: string,\n passphrase: string,\n): PurchaseMandate {\n const txHash = hashTransactionDetails(txDetails);\n const data = Buffer.from(txHash);\n\n const privateKey = createPrivateKey({\n key: privateKeyPem,\n format: 'pem',\n type: 'pkcs8',\n passphrase,\n });\n\n const signature = sign(null, data, privateKey);\n\n const publicKey = createPublicKey(privateKey);\n const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }) as string;\n\n return {\n txId: txDetails.txId,\n txHash,\n signature: signature.toString('base64'),\n publicKey: publicKeyPem,\n timestamp: new Date().toISOString(),\n };\n}\n\nexport function verifyMandate(mandate: PurchaseMandate, txDetails: TransactionDetails): boolean {\n try {\n const txHash = hashTransactionDetails(txDetails);\n if (txHash !== mandate.txHash) return false;\n\n const data = Buffer.from(txHash);\n const signature = Buffer.from(mandate.signature, 'base64');\n const publicKey = createPublicKey({\n key: mandate.publicKey,\n format: 'pem',\n type: 'spki',\n });\n\n return verify(null, data, publicKey, signature);\n } catch {\n return false;\n }\n}\n","import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { Wallet } from './types.js';\nimport { NotSetupError, InsufficientBalanceError, ExceedsTxLimitError } from '../errors.js';\nimport { getWalletPath } from '../utils/paths.js';\n\nexport class BudgetManager {\n private walletPath: string;\n\n constructor(walletPath?: string) {\n this.walletPath = walletPath ?? getWalletPath();\n }\n\n getWallet(): Wallet {\n try {\n const data = readFileSync(this.walletPath, 'utf8');\n return JSON.parse(data) as Wallet;\n } catch {\n throw new NotSetupError();\n }\n }\n\n private saveWallet(wallet: Wallet): void {\n mkdirSync(dirname(this.walletPath), { recursive: true });\n writeFileSync(this.walletPath, JSON.stringify(wallet, null, 2), { mode: 0o600 });\n }\n\n setBudget(amount: number): void {\n let wallet: Wallet;\n try {\n wallet = this.getWallet();\n } catch {\n wallet = { budget: 0, balance: 0, limitPerTx: 0, spent: 0 };\n }\n wallet.budget = amount;\n wallet.balance = amount - wallet.spent;\n this.saveWallet(wallet);\n }\n\n setLimitPerTx(limit: number): void {\n const wallet = this.getWallet();\n wallet.limitPerTx = limit;\n this.saveWallet(wallet);\n }\n\n deductBalance(amount: number): void {\n const wallet = this.getWallet();\n if (amount > wallet.balance) {\n throw new InsufficientBalanceError(amount, wallet.balance);\n }\n wallet.balance -= amount;\n wallet.spent += amount;\n this.saveWallet(wallet);\n }\n\n checkProposal(amount: number): void {\n const wallet = this.getWallet();\n if (amount > wallet.balance) {\n throw new InsufficientBalanceError(amount, wallet.balance);\n }\n if (wallet.limitPerTx > 0 && amount > wallet.limitPerTx) {\n throw new ExceedsTxLimitError(amount, wallet.limitPerTx);\n }\n }\n\n addFunds(amount: number): Wallet {\n const wallet = this.getWallet();\n wallet.budget += amount;\n wallet.balance += amount;\n this.saveWallet(wallet);\n return wallet;\n }\n\n getBalance(): { budget: number; balance: number; limitPerTx: number; spent: number } {\n const wallet = this.getWallet();\n return {\n budget: wallet.budget,\n balance: wallet.balance,\n limitPerTx: wallet.limitPerTx,\n spent: wallet.spent,\n };\n }\n\n initWallet(budget: number, limitPerTx: number = 0): void {\n const wallet: Wallet = { budget, balance: budget, limitPerTx, spent: 0 };\n this.saveWallet(wallet);\n }\n}\n","import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { Transaction, Receipt, ProposeOptions } from './types.js';\nimport type { PurchaseMandate } from '../auth/types.js';\nimport { generateTxId } from '../utils/ids.js';\nimport { getTransactionsPath } from '../utils/paths.js';\n\nexport class TransactionManager {\n private txPath: string;\n\n constructor(txPath?: string) {\n this.txPath = txPath ?? getTransactionsPath();\n }\n\n private loadAll(): Transaction[] {\n try {\n const data = readFileSync(this.txPath, 'utf8');\n return JSON.parse(data) as Transaction[];\n } catch {\n return [];\n }\n }\n\n private saveAll(transactions: Transaction[]): void {\n mkdirSync(dirname(this.txPath), { recursive: true });\n writeFileSync(this.txPath, JSON.stringify(transactions, null, 2), { mode: 0o600 });\n }\n\n propose(options: ProposeOptions): Transaction {\n const transactions = this.loadAll();\n const tx: Transaction = {\n id: generateTxId(),\n status: 'pending',\n merchant: options.merchant,\n amount: options.amount,\n description: options.description,\n url: options.url,\n createdAt: new Date().toISOString(),\n };\n transactions.push(tx);\n this.saveAll(transactions);\n return tx;\n }\n\n get(txId: string): Transaction | undefined {\n return this.loadAll().find((tx) => tx.id === txId);\n }\n\n approve(txId: string, mandate: PurchaseMandate): void {\n const transactions = this.loadAll();\n const tx = transactions.find((t) => t.id === txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n if (tx.status !== 'pending') throw new Error(`Cannot approve transaction in '${tx.status}' state.`);\n tx.status = 'approved';\n tx.mandate = mandate;\n this.saveAll(transactions);\n }\n\n reject(txId: string, reason?: string): void {\n const transactions = this.loadAll();\n const tx = transactions.find((t) => t.id === txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n if (tx.status !== 'pending') throw new Error(`Cannot reject transaction in '${tx.status}' state.`);\n tx.status = 'rejected';\n tx.rejectionReason = reason;\n this.saveAll(transactions);\n }\n\n markExecuting(txId: string): void {\n const transactions = this.loadAll();\n const tx = transactions.find((t) => t.id === txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n if (tx.status !== 'approved') throw new Error(`Cannot execute transaction in '${tx.status}' state.`);\n tx.status = 'executing';\n this.saveAll(transactions);\n }\n\n markCompleted(txId: string, receipt: Receipt): void {\n const transactions = this.loadAll();\n const tx = transactions.find((t) => t.id === txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n if (tx.status !== 'executing') throw new Error(`Cannot complete transaction in '${tx.status}' state.`);\n tx.status = 'completed';\n tx.receipt = receipt;\n this.saveAll(transactions);\n }\n\n markFailed(txId: string, error: string): void {\n const transactions = this.loadAll();\n const tx = transactions.find((t) => t.id === txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n if (tx.status !== 'executing') throw new Error(`Cannot fail transaction in '${tx.status}' state.`);\n tx.status = 'failed';\n tx.error = error;\n this.saveAll(transactions);\n }\n\n list(): Transaction[] {\n return this.loadAll();\n }\n\n getPending(): Transaction[] {\n return this.loadAll().filter((tx) => tx.status === 'pending');\n }\n\n getHistory(): Transaction[] {\n return this.loadAll().filter((tx) => tx.status !== 'pending');\n }\n}\n","import { appendFileSync, readFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { getAuditPath } from '../utils/paths.js';\n\nexport class AuditLogger {\n private logPath: string;\n\n constructor(logPath?: string) {\n this.logPath = logPath ?? getAuditPath();\n }\n\n log(action: string, details: Record<string, unknown>): void {\n const timestamp = new Date().toISOString();\n const detailsStr = JSON.stringify(details);\n const entry = `${timestamp}\\t${action}\\t${detailsStr}\\n`;\n mkdirSync(dirname(this.logPath), { recursive: true });\n appendFileSync(this.logPath, entry, { mode: 0o600 });\n }\n\n getLog(): string[] {\n try {\n const data = readFileSync(this.logPath, 'utf8');\n return data.trim().split('\\n').filter(Boolean);\n } catch {\n return [];\n }\n }\n}\n","import { Stagehand } from '@browserbasehq/stagehand';\nimport type { BillingCredentials } from '../vault/types.js';\nimport type { Transaction } from '../transactions/types.js';\nimport type { CheckoutResult, ExecutorConfig } from './types.js';\nimport { CheckoutFailedError } from '../errors.js';\nimport { credentialsToSwapMap, getPlaceholderVariables } from './placeholder.js';\n\nexport interface DiscoverResult {\n price: number;\n productName: string;\n}\n\nexport class PurchaseExecutor {\n private config: ExecutorConfig;\n private stagehand: Stagehand | null = null;\n\n constructor(config?: ExecutorConfig) {\n this.config = {\n browserbaseApiKey: config?.browserbaseApiKey ?? process.env.BROWSERBASE_API_KEY,\n browserbaseProjectId: config?.browserbaseProjectId ?? process.env.BROWSERBASE_PROJECT_ID,\n modelApiKey: config?.modelApiKey ?? process.env.ANTHROPIC_API_KEY,\n };\n }\n\n private createStagehand(): Stagehand {\n return new Stagehand({\n env: 'BROWSERBASE',\n apiKey: this.config.browserbaseApiKey,\n projectId: this.config.browserbaseProjectId,\n model: this.config.modelApiKey\n ? { modelName: 'claude-3-7-sonnet-latest', apiKey: this.config.modelApiKey }\n : undefined,\n browserbaseSessionCreateParams: {\n browserSettings: {\n recordSession: false,\n },\n },\n });\n }\n\n /**\n * Phase 1: Open browser, navigate to URL, extract price and product info.\n * Keeps the session alive for fillAndComplete().\n */\n async openAndDiscover(url: string, instructions?: string): Promise<DiscoverResult> {\n this.stagehand = this.createStagehand();\n await this.stagehand.init();\n const page = this.stagehand.context.activePage()!;\n\n await page.goto(url);\n\n // Let Stagehand find the product and add to cart with optional extra instructions\n const addToCartInstructions = instructions\n ? `On this product page: ${instructions}. Then add the item to the cart.`\n : 'Add this product to the cart.';\n await this.stagehand.act(addToCartInstructions);\n\n // Extract price and product name\n const extracted = await this.stagehand.extract(\n 'Extract the product name and the price (as a number without $ sign) from the page or cart. Return JSON: { \"price\": <number>, \"productName\": \"<string>\" }',\n ) as any;\n\n const price = parseFloat(extracted?.price ?? extracted?.extraction?.price ?? '0');\n const productName = extracted?.productName ?? extracted?.extraction?.productName ?? 'Unknown Product';\n\n return { price, productName };\n }\n\n /**\n * Phase 2: Proceed to checkout, fill forms, swap credentials, and submit.\n * Must be called after openAndDiscover().\n */\n async fillAndComplete(credentials: BillingCredentials): Promise<CheckoutResult> {\n if (!this.stagehand) {\n throw new CheckoutFailedError('No active session. Call openAndDiscover() first.');\n }\n\n try {\n // Proceed to checkout\n await this.stagehand.act('Proceed to checkout from the cart.');\n\n // Fill checkout form with placeholders\n const variables = getPlaceholderVariables();\n await this.stagehand.act(\n `Fill in the checkout form with these values:\n Name: ${variables.cardholder_name}\n Card Number: ${variables.card_number}\n Expiry: ${variables.card_expiry}\n CVV: ${variables.card_cvv}\n Email: ${variables.email}\n Phone: ${variables.phone}\n Billing Street: ${variables.billing_street}\n Billing City: ${variables.billing_city}\n Billing State: ${variables.billing_state}\n Billing ZIP: ${variables.billing_zip}\n Billing Country: ${variables.billing_country}\n Shipping Street: ${variables.shipping_street}\n Shipping City: ${variables.shipping_city}\n Shipping State: ${variables.shipping_state}\n Shipping ZIP: ${variables.shipping_zip}\n Shipping Country: ${variables.shipping_country}`,\n { variables },\n );\n\n // Atomic swap: replace placeholders with real credentials and submit\n const swapMap = credentialsToSwapMap(credentials);\n const page = this.stagehand.context.activePage()!;\n\n await page.evaluate((map: Record<string, string>) => {\n const inputs = document.querySelectorAll('input, textarea, select');\n for (const input of inputs) {\n const el = input as HTMLInputElement;\n for (const [placeholder, value] of Object.entries(map)) {\n if (el.value === placeholder) {\n el.value = value;\n el.dispatchEvent(new Event('input', { bubbles: true }));\n el.dispatchEvent(new Event('change', { bubbles: true }));\n }\n }\n }\n const submitBtn = document.querySelector('button[type=\"submit\"], input[type=\"submit\"]') as HTMLElement | null;\n if (submitBtn) submitBtn.click();\n }, swapMap);\n\n // Wait for confirmation page\n await page.waitForTimeout(5000);\n\n // Try to extract confirmation\n const result = await this.stagehand.extract(\n 'Extract the order confirmation number or ID from the page',\n );\n\n const confirmationId = (result as any)?.extraction;\n if (!confirmationId || confirmationId === 'null' || confirmationId === 'UNKNOWN') {\n throw new CheckoutFailedError('No order confirmation found. Checkout may not have completed.');\n }\n\n return {\n success: true,\n confirmationId,\n };\n } catch (err) {\n if (err instanceof CheckoutFailedError) throw err;\n const message = err instanceof Error ? err.message : 'Unknown checkout error';\n throw new CheckoutFailedError(message);\n }\n }\n\n /**\n * Convenience: single-shot execute (navigate + checkout in one call).\n * Used by AgentPay facade when amount is already known.\n */\n async execute(tx: Transaction, credentials: BillingCredentials): Promise<CheckoutResult> {\n this.stagehand = this.createStagehand();\n\n try {\n await this.stagehand.init();\n const page = this.stagehand.context.activePage()!;\n\n await page.goto(tx.url);\n\n const variables = getPlaceholderVariables();\n await this.stagehand.act(\n `Find the product and proceed to checkout. Fill in the checkout form with these values:\n Name: ${variables.cardholder_name}\n Card Number: ${variables.card_number}\n Expiry: ${variables.card_expiry}\n CVV: ${variables.card_cvv}\n Email: ${variables.email}\n Phone: ${variables.phone}\n Billing Street: ${variables.billing_street}\n Billing City: ${variables.billing_city}\n Billing State: ${variables.billing_state}\n Billing ZIP: ${variables.billing_zip}\n Billing Country: ${variables.billing_country}\n Shipping Street: ${variables.shipping_street}\n Shipping City: ${variables.shipping_city}\n Shipping State: ${variables.shipping_state}\n Shipping ZIP: ${variables.shipping_zip}\n Shipping Country: ${variables.shipping_country}`,\n { variables },\n );\n\n const swapMap = credentialsToSwapMap(credentials);\n await page.evaluate((map: Record<string, string>) => {\n const inputs = document.querySelectorAll('input, textarea, select');\n for (const input of inputs) {\n const el = input as HTMLInputElement;\n for (const [placeholder, value] of Object.entries(map)) {\n if (el.value === placeholder) {\n el.value = value;\n el.dispatchEvent(new Event('input', { bubbles: true }));\n el.dispatchEvent(new Event('change', { bubbles: true }));\n }\n }\n }\n const submitBtn = document.querySelector('button[type=\"submit\"], input[type=\"submit\"]') as HTMLElement | null;\n if (submitBtn) submitBtn.click();\n }, swapMap);\n\n await page.waitForTimeout(5000);\n\n const result = await this.stagehand.extract(\n 'Extract the order confirmation number or ID from the page',\n );\n\n const confirmationId = (result as any)?.extraction;\n if (!confirmationId || confirmationId === 'null' || confirmationId === 'UNKNOWN') {\n throw new CheckoutFailedError('No order confirmation found. Checkout may not have completed.');\n }\n\n return {\n success: true,\n confirmationId,\n };\n } catch (err) {\n if (err instanceof CheckoutFailedError) throw err;\n const message = err instanceof Error ? err.message : 'Unknown checkout error';\n throw new CheckoutFailedError(message);\n } finally {\n await this.close();\n }\n }\n\n async close(): Promise<void> {\n try {\n if (this.stagehand) {\n await this.stagehand.close();\n this.stagehand = null;\n }\n } catch {\n // Ignore cleanup errors\n }\n }\n}\n","import type { BillingCredentials } from '../vault/types.js';\n\nexport const PLACEHOLDER_MAP = {\n card_number: '{{card_number}}',\n cardholder_name: '{{cardholder_name}}',\n card_expiry: '{{card_expiry}}',\n card_cvv: '{{card_cvv}}',\n billing_street: '{{billing_street}}',\n billing_city: '{{billing_city}}',\n billing_state: '{{billing_state}}',\n billing_zip: '{{billing_zip}}',\n billing_country: '{{billing_country}}',\n shipping_street: '{{shipping_street}}',\n shipping_city: '{{shipping_city}}',\n shipping_state: '{{shipping_state}}',\n shipping_zip: '{{shipping_zip}}',\n shipping_country: '{{shipping_country}}',\n email: '{{email}}',\n phone: '{{phone}}',\n} as const;\n\nexport function getPlaceholderVariables(): Record<string, string> {\n // These are the %var% placeholders used with Stagehand act() variables\n // The AI never sees the real values — only these placeholders\n return {\n card_number: '%card_number%',\n cardholder_name: '%cardholder_name%',\n card_expiry: '%card_expiry%',\n card_cvv: '%card_cvv%',\n billing_street: '%billing_street%',\n billing_city: '%billing_city%',\n billing_state: '%billing_state%',\n billing_zip: '%billing_zip%',\n billing_country: '%billing_country%',\n shipping_street: '%shipping_street%',\n shipping_city: '%shipping_city%',\n shipping_state: '%shipping_state%',\n shipping_zip: '%shipping_zip%',\n shipping_country: '%shipping_country%',\n email: '%email%',\n phone: '%phone%',\n };\n}\n\nexport function credentialsToSwapMap(creds: BillingCredentials): Record<string, string> {\n return {\n [PLACEHOLDER_MAP.card_number]: creds.card.number,\n [PLACEHOLDER_MAP.cardholder_name]: creds.name,\n [PLACEHOLDER_MAP.card_expiry]: creds.card.expiry,\n [PLACEHOLDER_MAP.card_cvv]: creds.card.cvv,\n [PLACEHOLDER_MAP.billing_street]: creds.billingAddress.street,\n [PLACEHOLDER_MAP.billing_city]: creds.billingAddress.city,\n [PLACEHOLDER_MAP.billing_state]: creds.billingAddress.state,\n [PLACEHOLDER_MAP.billing_zip]: creds.billingAddress.zip,\n [PLACEHOLDER_MAP.billing_country]: creds.billingAddress.country,\n [PLACEHOLDER_MAP.shipping_street]: creds.shippingAddress.street,\n [PLACEHOLDER_MAP.shipping_city]: creds.shippingAddress.city,\n [PLACEHOLDER_MAP.shipping_state]: creds.shippingAddress.state,\n [PLACEHOLDER_MAP.shipping_zip]: creds.shippingAddress.zip,\n [PLACEHOLDER_MAP.shipping_country]: creds.shippingAddress.country,\n [PLACEHOLDER_MAP.email]: creds.email,\n [PLACEHOLDER_MAP.phone]: creds.phone,\n };\n}\n\n/**\n * Atomically swap placeholders with real credentials in the DOM and submit.\n * This is called via page.evaluate() — credentials exist in the DOM only for milliseconds.\n */\nexport function getAtomicSwapScript(): string {\n return `\n (swapMap) => {\n const inputs = document.querySelectorAll('input, textarea, select');\n for (const input of inputs) {\n const el = input;\n for (const [placeholder, value] of Object.entries(swapMap)) {\n if (el.value === placeholder) {\n el.value = value;\n el.dispatchEvent(new Event('input', { bubbles: true }));\n el.dispatchEvent(new Event('change', { bubbles: true }));\n }\n }\n }\n // Submit the form\n const submitBtn = document.querySelector('button[type=\"submit\"], input[type=\"submit\"]');\n if (submitBtn) submitBtn.click();\n }\n `;\n}\n","import { join } from 'node:path';\nimport { BudgetManager } from './budget/budget.js';\nimport { TransactionManager } from './transactions/manager.js';\nimport { AuditLogger } from './audit/logger.js';\nimport { PurchaseExecutor } from './executor/executor.js';\nimport { verifyMandate } from './auth/mandate.js';\nimport { decrypt, loadVault } from './vault/vault.js';\nimport { getHomePath } from './utils/paths.js';\nimport {\n NotApprovedError,\n InvalidMandateError,\n InsufficientBalanceError,\n AlreadyExecutedError,\n} from './errors.js';\nimport type { Transaction, Receipt, ProposeOptions } from './transactions/types.js';\nimport type { TransactionDetails } from './auth/types.js';\nimport type { ExecutorConfig } from './executor/types.js';\n\nexport interface AgentPayOptions {\n home?: string;\n passphrase?: string;\n executor?: ExecutorConfig;\n}\n\nexport class AgentPay {\n public readonly home: string;\n private passphrase?: string;\n private budgetManager: BudgetManager;\n private txManager: TransactionManager;\n private auditLogger: AuditLogger;\n private executor: PurchaseExecutor;\n\n constructor(options?: AgentPayOptions) {\n this.home = options?.home ?? getHomePath();\n this.passphrase = options?.passphrase;\n this.budgetManager = new BudgetManager(join(this.home, 'wallet.json'));\n this.txManager = new TransactionManager(join(this.home, 'transactions.json'));\n this.auditLogger = new AuditLogger(join(this.home, 'audit.log'));\n this.executor = new PurchaseExecutor(options?.executor);\n }\n\n get wallet() {\n const bm = this.budgetManager;\n return {\n getBalance: () => bm.getBalance(),\n getHistory: () => this.txManager.getHistory(),\n getLimits: () => {\n const w = bm.getBalance();\n return { budget: w.budget, limitPerTx: w.limitPerTx, remaining: w.balance };\n },\n generateFundingQR: async (options?: { suggestedBudget?: number; message?: string }) => {\n const QRCode = await import('qrcode');\n const params = new URLSearchParams();\n if (options?.suggestedBudget) params.set('budget', String(options.suggestedBudget));\n if (options?.message) params.set('msg', options.message);\n const baseUrl = process.env.AGENTPAY_WEB_URL ?? 'http://localhost:3000';\n const url = `${baseUrl}/setup${params.toString() ? `?${params.toString()}` : ''}`;\n const qrDataUrl = await QRCode.toDataURL(url);\n return { url, qrDataUrl };\n },\n };\n }\n\n get transactions() {\n return {\n propose: (options: ProposeOptions): Transaction => {\n this.budgetManager.checkProposal(options.amount);\n const tx = this.txManager.propose(options);\n this.auditLogger.log('PROPOSE', { txId: tx.id, merchant: tx.merchant, amount: tx.amount });\n return tx;\n },\n get: (txId: string) => this.txManager.get(txId),\n waitForApproval: async (txId: string, options?: { pollInterval?: number; timeout?: number }) => {\n const { waitForApproval } = await import('./transactions/poller.js');\n return waitForApproval(txId, this.txManager, options);\n },\n execute: async (txId: string): Promise<Receipt> => {\n const tx = this.txManager.get(txId);\n if (!tx) throw new Error(`Transaction ${txId} not found.`);\n\n // Validate state\n if (tx.status === 'completed' || tx.status === 'failed') {\n throw new AlreadyExecutedError(txId);\n }\n if (tx.status !== 'approved') {\n throw new NotApprovedError(txId);\n }\n if (!tx.mandate) {\n throw new InvalidMandateError('No mandate found on approved transaction.');\n }\n\n // Verify mandate\n const txDetails: TransactionDetails = {\n txId: tx.id,\n merchant: tx.merchant,\n amount: tx.amount,\n description: tx.description,\n timestamp: tx.createdAt,\n };\n if (!verifyMandate(tx.mandate, txDetails)) {\n throw new InvalidMandateError();\n }\n\n // Check balance\n this.budgetManager.checkProposal(tx.amount);\n\n // Mark executing\n this.txManager.markExecuting(txId);\n this.auditLogger.log('EXECUTE', { txId, browserbaseSessionStarted: true });\n\n try {\n // Decrypt credentials\n if (!this.passphrase) {\n throw new Error('Passphrase required for execution. Pass it to AgentPay constructor.');\n }\n const vaultPath = join(this.home, 'credentials.enc');\n const vault = loadVault(vaultPath);\n const credentials = decrypt(vault, this.passphrase);\n\n // Execute checkout\n const result = await this.executor.execute(tx, credentials);\n\n // Mark completed and deduct balance\n const receipt: Receipt = {\n id: `rcpt_${txId.replace('tx_', '')}`,\n merchant: tx.merchant,\n amount: tx.amount,\n confirmationId: result.confirmationId ?? 'UNKNOWN',\n completedAt: new Date().toISOString(),\n };\n\n this.txManager.markCompleted(txId, receipt);\n this.budgetManager.deductBalance(tx.amount);\n this.auditLogger.log('COMPLETE', { txId, confirmationId: receipt.confirmationId });\n\n return receipt;\n } catch (err) {\n this.txManager.markFailed(txId, err instanceof Error ? err.message : 'Unknown error');\n this.auditLogger.log('FAILED', { txId, error: err instanceof Error ? err.message : 'Unknown' });\n throw err;\n }\n },\n getReceipt: (txId: string): Receipt | undefined => {\n const tx = this.txManager.get(txId);\n return tx?.receipt;\n },\n };\n }\n\n get audit() {\n return { getLog: () => this.auditLogger.getLog() };\n }\n\n status(): {\n balance: number;\n budget: number;\n limitPerTx: number;\n pending: Transaction[];\n recent: Transaction[];\n isSetup: boolean;\n } {\n try {\n const wallet = this.budgetManager.getBalance();\n const pending = this.txManager.getPending();\n const recent = this.txManager.list().slice(-5);\n return {\n balance: wallet.balance,\n budget: wallet.budget,\n limitPerTx: wallet.limitPerTx,\n pending,\n recent,\n isSetup: true,\n };\n } catch {\n return {\n balance: 0,\n budget: 0,\n limitPerTx: 0,\n pending: [],\n recent: [],\n isSetup: false,\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAa,eAQA,cAQA,0BAWA,qBAWA,kBAQA,qBAQA,sBAQA,qB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,KAAK,YAAY,OAAO,EAAE;AAAA,EACnD;AAAA,EAEA,SAOE;AACA,QAAI;AACF,YAAM,SAAS,KAAK,cAAc,WAAW;AAC7C,YAAM,UAAU,KAAK,UAAU,WAAW;AAC1C,YAAM,SAAS,KAAK,UAAU,KAAK,EAAE,MAAM,EAAE;AAC7C,aAAO;AAAA,QACL,SAAS,OAAO;AAAA,QAChB,QAAQ,OAAO;AAAA,QACf,YAAY,OAAO;AAAA,QACnB;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX;AAAA,IACF,QAAQ;AACN,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,YAAY;AAAA,QACZ,SAAS,CAAC;AAAA,QACV,QAAQ,CAAC;AAAA,QACT,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AACF;;;AZxLO,IAAM,UAAU;","names":["import_node_crypto","import_node_path","import_node_crypto","import_node_fs","import_node_path","import_node_crypto","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_path","waitForApproval"]}
@@ -0,0 +1,328 @@
1
+ interface BillingCredentials {
2
+ card: {
3
+ number: string;
4
+ expiry: string;
5
+ cvv: string;
6
+ };
7
+ name: string;
8
+ billingAddress: {
9
+ street: string;
10
+ city: string;
11
+ state: string;
12
+ zip: string;
13
+ country: string;
14
+ };
15
+ shippingAddress: {
16
+ street: string;
17
+ city: string;
18
+ state: string;
19
+ zip: string;
20
+ country: string;
21
+ };
22
+ email: string;
23
+ phone: string;
24
+ }
25
+ interface EncryptedVault {
26
+ ciphertext: string;
27
+ salt: string;
28
+ iv: string;
29
+ }
30
+
31
+ interface KeyPair {
32
+ publicKey: string;
33
+ privateKey: string;
34
+ }
35
+ interface PurchaseMandate {
36
+ txId: string;
37
+ txHash: string;
38
+ signature: string;
39
+ publicKey: string;
40
+ timestamp: string;
41
+ }
42
+ interface TransactionDetails {
43
+ txId: string;
44
+ merchant: string;
45
+ amount: number;
46
+ description: string;
47
+ timestamp: string;
48
+ }
49
+
50
+ interface Wallet {
51
+ budget: number;
52
+ balance: number;
53
+ limitPerTx: number;
54
+ spent: number;
55
+ }
56
+
57
+ type TransactionStatus = 'pending' | 'approved' | 'rejected' | 'executing' | 'completed' | 'failed';
58
+ interface Transaction {
59
+ id: string;
60
+ status: TransactionStatus;
61
+ merchant: string;
62
+ amount: number;
63
+ description: string;
64
+ url: string;
65
+ createdAt: string;
66
+ mandate?: PurchaseMandate;
67
+ receipt?: Receipt;
68
+ rejectionReason?: string;
69
+ error?: string;
70
+ }
71
+ interface Receipt {
72
+ id: string;
73
+ merchant: string;
74
+ amount: number;
75
+ confirmationId: string;
76
+ completedAt: string;
77
+ }
78
+ interface ProposeOptions {
79
+ merchant: string;
80
+ amount: number;
81
+ description: string;
82
+ url: string;
83
+ }
84
+
85
+ interface CheckoutResult {
86
+ success: boolean;
87
+ confirmationId?: string;
88
+ error?: string;
89
+ }
90
+ interface ExecutorConfig {
91
+ browserbaseApiKey?: string;
92
+ browserbaseProjectId?: string;
93
+ modelApiKey?: string;
94
+ }
95
+
96
+ declare class NotSetupError extends Error {
97
+ readonly code = "NOT_SETUP";
98
+ constructor(message?: string);
99
+ }
100
+ declare class DecryptError extends Error {
101
+ readonly code = "DECRYPT_FAILED";
102
+ constructor(message?: string);
103
+ }
104
+ declare class InsufficientBalanceError extends Error {
105
+ readonly code = "INSUFFICIENT_BALANCE";
106
+ constructor(amount?: number, balance?: number);
107
+ }
108
+ declare class ExceedsTxLimitError extends Error {
109
+ readonly code = "EXCEEDS_TX_LIMIT";
110
+ constructor(amount?: number, limit?: number);
111
+ }
112
+ declare class NotApprovedError extends Error {
113
+ readonly code = "NOT_APPROVED";
114
+ constructor(txId?: string);
115
+ }
116
+ declare class InvalidMandateError extends Error {
117
+ readonly code = "INVALID_MANDATE";
118
+ constructor(message?: string);
119
+ }
120
+ declare class AlreadyExecutedError extends Error {
121
+ readonly code = "ALREADY_EXECUTED";
122
+ constructor(txId?: string);
123
+ }
124
+ declare class CheckoutFailedError extends Error {
125
+ readonly code = "CHECKOUT_FAILED";
126
+ constructor(message?: string);
127
+ }
128
+ declare class TimeoutError extends Error {
129
+ readonly code = "TIMEOUT";
130
+ constructor(message?: string);
131
+ }
132
+
133
+ declare function generateTxId(): string;
134
+
135
+ declare function formatCurrency(amount: number): string;
136
+ declare function formatTimestamp(iso: string): string;
137
+ declare function formatTable(transactions: Transaction[]): string;
138
+ declare function formatStatus(data: {
139
+ balance: number;
140
+ budget: number;
141
+ limitPerTx: number;
142
+ pending: Transaction[];
143
+ recent: Transaction[];
144
+ }): string;
145
+
146
+ declare function getHomePath(): string;
147
+ declare function getCredentialsPath(): string;
148
+ declare function getKeysPath(): string;
149
+ declare function getWalletPath(): string;
150
+ declare function getTransactionsPath(): string;
151
+ declare function getAuditPath(): string;
152
+
153
+ declare function encrypt(credentials: BillingCredentials, passphrase: string): EncryptedVault;
154
+ declare function decrypt(vault: EncryptedVault, passphrase: string): BillingCredentials;
155
+ declare function saveVault(vault: EncryptedVault, path?: string): void;
156
+ declare function loadVault(path?: string): EncryptedVault;
157
+
158
+ declare function generateKeyPair(passphrase: string): KeyPair;
159
+ declare function saveKeyPair(keys: KeyPair, publicPath?: string, privatePath?: string): void;
160
+ declare function loadPublicKey(path?: string): string;
161
+ declare function loadPrivateKey(path?: string): string;
162
+
163
+ declare function createMandate(txDetails: TransactionDetails, privateKeyPem: string, passphrase: string): PurchaseMandate;
164
+ declare function verifyMandate(mandate: PurchaseMandate, txDetails: TransactionDetails): boolean;
165
+
166
+ declare class BudgetManager {
167
+ private walletPath;
168
+ constructor(walletPath?: string);
169
+ getWallet(): Wallet;
170
+ private saveWallet;
171
+ setBudget(amount: number): void;
172
+ setLimitPerTx(limit: number): void;
173
+ deductBalance(amount: number): void;
174
+ checkProposal(amount: number): void;
175
+ addFunds(amount: number): Wallet;
176
+ getBalance(): {
177
+ budget: number;
178
+ balance: number;
179
+ limitPerTx: number;
180
+ spent: number;
181
+ };
182
+ initWallet(budget: number, limitPerTx?: number): void;
183
+ }
184
+
185
+ declare class TransactionManager {
186
+ private txPath;
187
+ constructor(txPath?: string);
188
+ private loadAll;
189
+ private saveAll;
190
+ propose(options: ProposeOptions): Transaction;
191
+ get(txId: string): Transaction | undefined;
192
+ approve(txId: string, mandate: PurchaseMandate): void;
193
+ reject(txId: string, reason?: string): void;
194
+ markExecuting(txId: string): void;
195
+ markCompleted(txId: string, receipt: Receipt): void;
196
+ markFailed(txId: string, error: string): void;
197
+ list(): Transaction[];
198
+ getPending(): Transaction[];
199
+ getHistory(): Transaction[];
200
+ }
201
+
202
+ interface PollOptions {
203
+ pollInterval?: number;
204
+ timeout?: number;
205
+ }
206
+ declare function waitForApproval(txId: string, manager: TransactionManager, options?: PollOptions): Promise<{
207
+ status: 'approved' | 'rejected';
208
+ reason?: string;
209
+ }>;
210
+
211
+ declare class AuditLogger {
212
+ private logPath;
213
+ constructor(logPath?: string);
214
+ log(action: string, details: Record<string, unknown>): void;
215
+ getLog(): string[];
216
+ }
217
+
218
+ interface DiscoverResult {
219
+ price: number;
220
+ productName: string;
221
+ }
222
+ declare class PurchaseExecutor {
223
+ private config;
224
+ private stagehand;
225
+ constructor(config?: ExecutorConfig);
226
+ private createStagehand;
227
+ /**
228
+ * Phase 1: Open browser, navigate to URL, extract price and product info.
229
+ * Keeps the session alive for fillAndComplete().
230
+ */
231
+ openAndDiscover(url: string, instructions?: string): Promise<DiscoverResult>;
232
+ /**
233
+ * Phase 2: Proceed to checkout, fill forms, swap credentials, and submit.
234
+ * Must be called after openAndDiscover().
235
+ */
236
+ fillAndComplete(credentials: BillingCredentials): Promise<CheckoutResult>;
237
+ /**
238
+ * Convenience: single-shot execute (navigate + checkout in one call).
239
+ * Used by AgentPay facade when amount is already known.
240
+ */
241
+ execute(tx: Transaction, credentials: BillingCredentials): Promise<CheckoutResult>;
242
+ close(): Promise<void>;
243
+ }
244
+
245
+ declare const PLACEHOLDER_MAP: {
246
+ readonly card_number: "{{card_number}}";
247
+ readonly cardholder_name: "{{cardholder_name}}";
248
+ readonly card_expiry: "{{card_expiry}}";
249
+ readonly card_cvv: "{{card_cvv}}";
250
+ readonly billing_street: "{{billing_street}}";
251
+ readonly billing_city: "{{billing_city}}";
252
+ readonly billing_state: "{{billing_state}}";
253
+ readonly billing_zip: "{{billing_zip}}";
254
+ readonly billing_country: "{{billing_country}}";
255
+ readonly shipping_street: "{{shipping_street}}";
256
+ readonly shipping_city: "{{shipping_city}}";
257
+ readonly shipping_state: "{{shipping_state}}";
258
+ readonly shipping_zip: "{{shipping_zip}}";
259
+ readonly shipping_country: "{{shipping_country}}";
260
+ readonly email: "{{email}}";
261
+ readonly phone: "{{phone}}";
262
+ };
263
+ declare function getPlaceholderVariables(): Record<string, string>;
264
+ declare function credentialsToSwapMap(creds: BillingCredentials): Record<string, string>;
265
+
266
+ interface AgentPayOptions {
267
+ home?: string;
268
+ passphrase?: string;
269
+ executor?: ExecutorConfig;
270
+ }
271
+ declare class AgentPay {
272
+ readonly home: string;
273
+ private passphrase?;
274
+ private budgetManager;
275
+ private txManager;
276
+ private auditLogger;
277
+ private executor;
278
+ constructor(options?: AgentPayOptions);
279
+ get wallet(): {
280
+ getBalance: () => {
281
+ budget: number;
282
+ balance: number;
283
+ limitPerTx: number;
284
+ spent: number;
285
+ };
286
+ getHistory: () => Transaction[];
287
+ getLimits: () => {
288
+ budget: number;
289
+ limitPerTx: number;
290
+ remaining: number;
291
+ };
292
+ generateFundingQR: (options?: {
293
+ suggestedBudget?: number;
294
+ message?: string;
295
+ }) => Promise<{
296
+ url: string;
297
+ qrDataUrl: string;
298
+ }>;
299
+ };
300
+ get transactions(): {
301
+ propose: (options: ProposeOptions) => Transaction;
302
+ get: (txId: string) => Transaction | undefined;
303
+ waitForApproval: (txId: string, options?: {
304
+ pollInterval?: number;
305
+ timeout?: number;
306
+ }) => Promise<{
307
+ status: "approved" | "rejected";
308
+ reason?: string;
309
+ }>;
310
+ execute: (txId: string) => Promise<Receipt>;
311
+ getReceipt: (txId: string) => Receipt | undefined;
312
+ };
313
+ get audit(): {
314
+ getLog: () => string[];
315
+ };
316
+ status(): {
317
+ balance: number;
318
+ budget: number;
319
+ limitPerTx: number;
320
+ pending: Transaction[];
321
+ recent: Transaction[];
322
+ isSetup: boolean;
323
+ };
324
+ }
325
+
326
+ declare const VERSION = "0.1.0";
327
+
328
+ export { AgentPay, type AgentPayOptions, AlreadyExecutedError, AuditLogger, type BillingCredentials, BudgetManager, CheckoutFailedError, type CheckoutResult, DecryptError, type EncryptedVault, ExceedsTxLimitError, type ExecutorConfig, InsufficientBalanceError, InvalidMandateError, type KeyPair, NotApprovedError, NotSetupError, PLACEHOLDER_MAP, type ProposeOptions, PurchaseExecutor, type PurchaseMandate, type Receipt, TimeoutError, type Transaction, type TransactionDetails, TransactionManager, type TransactionStatus, VERSION, type Wallet, createMandate, credentialsToSwapMap, decrypt, encrypt, formatCurrency, formatStatus, formatTable, formatTimestamp, generateKeyPair, generateTxId, getAuditPath, getCredentialsPath, getHomePath, getKeysPath, getPlaceholderVariables, getTransactionsPath, getWalletPath, loadPrivateKey, loadPublicKey, loadVault, saveKeyPair, saveVault, verifyMandate, waitForApproval };