@mixrpay/agent-sdk 0.8.8 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4365 +1,31 @@
1
- // src/session-key.ts
2
- import {
3
- privateKeyToAccount,
4
- signTypedData,
5
- signMessage as viemSignMessage
6
- } from "viem/accounts";
1
+ export{c as deleteCredentials,e as getCredentialsFilePath,d as hasCredentials,b as loadCredentials,a as saveCredentials}from'./chunk-IBXQMJ7G.js';import {fileURLToPath}from'url';import {join,dirname}from'path';import {privateKeyToAccount,signMessage,generatePrivateKey,signTypedData}from'viem/accounts';import {createWalletClient,http,parseUnits,encodeFunctionData}from'viem';import {base}from'viem/chains';import {existsSync,mkdirSync,writeFileSync,chmodSync,readFileSync}from'fs';import {homedir}from'os';var l=class extends Error{code;retryAfterMs;constructor(e,t="MIXRPAY_ERROR",s){super(e),this.name="MixrPayError",this.code=t,this.retryAfterMs=s,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}isRetryable(){return false}},S=class extends l{required;available;topUpUrl;constructor(e,t){let s=e-t;super(`Insufficient balance: need $${e.toFixed(2)}, have $${t.toFixed(2)} (short $${s.toFixed(2)}). Top up your wallet to continue.`,"INSUFFICIENT_BALANCE"),this.name="InsufficientBalanceError",this.required=e,this.available=t,this.topUpUrl="https://mixrpay.com/manage/wallet";}},$=class extends l{expiredAt;constructor(e){super(`Session key expired at ${e}. Request a new session key from the wallet owner at https://mixrpay.com/manage/invites`,"SESSION_KEY_EXPIRED"),this.name="SessionKeyExpiredError",this.expiredAt=e;}},v=class extends l{limitType;limit;attempted;constructor(e,t,s){let a={per_tx:"Per-transaction",daily:"Daily",total:"Total",client_max:"Client-side"}[e]||e,r=e==="daily"?"Wait until tomorrow or request a higher limit.":e==="client_max"?"Increase maxPaymentUsd in your AgentWallet configuration.":"Request a new session key with a higher limit.";super(`${a} spending limit exceeded: limit is $${t.toFixed(2)}, attempted $${s.toFixed(2)}. ${r}`,"SPENDING_LIMIT_EXCEEDED"),this.name="SpendingLimitExceededError",this.limitType=e,this.limit=t,this.attempted=s;}isRetryable(){return this.limitType==="daily"}},A=class extends l{reason;txHash;constructor(e,t){let s=`Payment failed: ${e}`;t&&(s+=` (tx: ${t} - check on basescan.org)`),super(s,"PAYMENT_FAILED"),this.name="PaymentFailedError",this.reason=e,this.txHash=t;}isRetryable(){return true}},_=class extends l{reason;constructor(e="Invalid session key format"){super(`${e}. Session keys should be in format: sk_live_<64 hex chars> or sk_test_<64 hex chars>. Get one from https://mixrpay.com/manage/invites`,"INVALID_SESSION_KEY"),this.name="InvalidSessionKeyError",this.reason=e;}},k=class extends l{reason;constructor(e){super(`x402 protocol error: ${e}. This may indicate a server configuration issue. If the problem persists, contact the API provider.`,"X402_PROTOCOL_ERROR"),this.name="X402ProtocolError",this.reason=e;}isRetryable(){return true}},C=class extends l{sessionId;expiredAt;constructor(e,t){super(`Session ${e} has expired${t?` at ${t}`:""}. A new session will be created automatically on your next request.`,"SESSION_EXPIRED"),this.name="SessionExpiredError",this.sessionId=e,this.expiredAt=t;}},U=class extends l{sessionId;limit;requested;remaining;constructor(e,t,s,n){super(`Session spending limit exceeded: limit is $${e.toFixed(2)}, requested $${t.toFixed(2)}, remaining $${s.toFixed(2)}. Create a new session with a higher limit to continue.`,"SESSION_LIMIT_EXCEEDED"),this.name="SessionLimitExceededError",this.sessionId=n,this.limit=e,this.requested=t,this.remaining=s;}},P=class extends l{sessionId;constructor(e){super(`Session ${e} not found. It may have been deleted or never existed. Create a new session with getOrCreateSession().`,"SESSION_NOT_FOUND"),this.name="SessionNotFoundError",this.sessionId=e;}},I=class extends l{sessionId;reason;constructor(e,t){super(`Session ${e} has been revoked${t?`: ${t}`:""}. Create a new session with getOrCreateSession().`,"SESSION_REVOKED"),this.name="SessionRevokedError",this.sessionId=e,this.reason=t;}},D=class extends l{attempted;allowedPatterns;constructor(e,t){let s=t.slice(0,3).join(", "),n=t.length>3?"...":"";super(`Payment to "${e}" not allowed. Session allowlist: ${s}${n}. Update the session allowlist or create a new session.`,"MERCHANT_NOT_ALLOWED"),this.name="MerchantNotAllowedError",this.attempted=e,this.allowedPatterns=t;}},M=class extends l{constructor(e=6e4,t){super(t||`Rate limit exceeded. Please wait ${Math.ceil(e/1e3)} seconds before retrying.`,"RATE_LIMIT_EXCEEDED",e),this.name="RateLimitError";}isRetryable(){return true}},N=class extends l{reason;constructor(e,t){super(`Network error: ${e}. Check your connection and try again.`,"NETWORK_ERROR",5e3),this.name="NetworkError",this.reason=e,t?.stack&&(this.stack=t.stack);}isRetryable(){return true}},L=class extends l{reason;statusCode;constructor(e,t=401){super(`Authentication failed: ${e}`,t===401?"UNAUTHORIZED":"FORBIDDEN"),this.name="AuthenticationError",this.reason=e,this.statusCode=t;}isRetryable(){return false}};function ue(d){return d instanceof l}function ge(d){return d instanceof l||d instanceof Error?d.message:String(d)}var ye={8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",84532:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"},fe={name:"USD Coin",version:"2"},we={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},O=class d{privateKey;account;address;isTest;constructor(e,t){this.privateKey=e,this.account=privateKeyToAccount(e),this.address=this.account.address,this.isTest=t;}toString(){return `${this.isTest?"sk_test_":"sk_live_"}${this.privateKey.slice(2)}`}get privateKeyHex(){return this.privateKey.slice(2)}get rawPrivateKey(){return this.privateKey}static fromString(e){let t=/^sk_(live|test)_([a-fA-F0-9]{64})$/,s=e.match(t);if(!s)throw new _("Session key must be in format sk_live_{64_hex} or sk_test_{64_hex}");let n=s[1],a=s[2];try{let r=`0x${a}`;return new d(r,n==="test")}catch(r){throw new _(`Failed to decode session key: ${r}`)}}async signTransferAuthorization(e,t){return signTypedData({privateKey:this.privateKey,domain:e,types:we,primaryType:"TransferWithAuthorization",message:t})}async signMessage(e){return signMessage({privateKey:this.privateKey,message:e})}getDefaultChainId(){return this.isTest?84532:8453}};function X(d){let e=ye[d.chainId];if(!e)throw new Error(`USDC not supported on chain ${d.chainId}`);let t={...fe,chainId:d.chainId,verifyingContract:e},s={from:d.fromAddress,to:d.toAddress,value:d.value,validAfter:d.validAfter,validBefore:d.validBefore,nonce:d.nonce};return {domain:t,message:s}}function F(){let d=new Uint8Array(32);return crypto.getRandomValues(d),`0x${Array.from(d).map(e=>e.toString(16).padStart(2,"0")).join("")}`}function be(d,e){return `MixrPay:${d}:${e.toLowerCase()}`}async function Y(d){let e=Date.now(),t=be(e,d.address),s=await d.signMessage(t);return {address:d.address,timestamp:e,signature:s}}var ve="0.9.2",z=".config/mixrpay",ke="wallet.json";function Z(){let d=process.env.MIXRPAY_WORKSPACE_DIR||process.env.OPENCLAW_WORKSPACE_DIR;return d?join(d,z):join(homedir(),z)}function R(){return join(Z(),ke)}async function W(d,e){let t=Z(),s=R();existsSync(t)||mkdirSync(t,{recursive:true,mode:448});let n={address:e.toLowerCase(),privateKey:d,createdAt:new Date().toISOString(),sdkVersion:ve};writeFileSync(s,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384});try{chmodSync(s,384);}catch{}}async function K(){let d=process.env.MIXRPAY_WALLET_KEY;if(d){if(d.startsWith("0x")&&d.length===66)return d;if(d.length===64)return `0x${d}`;console.warn("[MixrPay] MIXRPAY_WALLET_KEY has invalid format, ignoring");}let e=R();if(!existsSync(e))return null;try{let t=readFileSync(e,"utf-8"),s=JSON.parse(t);return !s.privateKey||!s.privateKey.startsWith("0x")?(console.warn("[MixrPay] Wallet file has invalid format"),null):s.privateKey}catch(t){return console.warn("[MixrPay] Failed to read wallet file:",t),null}}async function Te(){let d=R();if(!existsSync(d)){let e=process.env.MIXRPAY_WALLET_KEY;return e&&(e.startsWith("0x")?e:`0x${e}`).length===66,null}try{let e=readFileSync(d,"utf-8");return JSON.parse(e)}catch{return null}}async function q(){let d=process.env.MIXRPAY_WALLET_KEY;return d&&(d.length===64||d.startsWith("0x")&&d.length===66)?true:existsSync(R())}function Ue(){return R()}async function Pe(){let d=R();if(!existsSync(d))return false;try{let{unlinkSync:e}=await import('fs');return e(d),!0}catch{return false}}async function Q(d){let e=null,t=d.headers.get("X-Payment-Required");if(t)try{e=JSON.parse(t);}catch{}if(!e){let n=d.headers.get("WWW-Authenticate");if(n?.startsWith("X-402 "))try{let a=n.slice(6);e=JSON.parse(atob(a));}catch{}}if(!e)try{e=await d.json();}catch{}if(!e)throw new k("Could not parse payment requirements from 402 response");if(!e.recipient)throw new k("Missing recipient in payment requirements");if(!e.amount)throw new k("Missing amount in payment requirements");let s=Math.floor(Date.now()/1e3);return {recipient:e.recipient,amount:BigInt(e.amount),currency:e.currency||"USDC",chainId:e.chainId||e.chain_id||8453,facilitatorUrl:e.facilitatorUrl||e.facilitator_url||"https://x402.org/facilitator",nonce:e.nonce||F().slice(2),expiresAt:e.expiresAt||e.expires_at||s+300,description:e.description}}async function ee(d,e,t){let s=d.nonce.length===64?`0x${d.nonce}`:F(),a=BigInt(Math.floor(Date.now()/1e3))-60n,r=BigInt(d.expiresAt),{domain:i,message:o}=X({fromAddress:t,toAddress:d.recipient,value:d.amount,validAfter:a,validBefore:r,nonce:s,chainId:d.chainId}),c=await e.signTransferAuthorization(i,o),p={x402Version:1,scheme:"exact",network:d.chainId===8453?"base":"base-sepolia",payload:{signature:c,authorization:{from:t,to:d.recipient,value:d.amount.toString(),validAfter:a.toString(),validBefore:r.toString(),nonce:s}}};return btoa(JSON.stringify(p))}function te(d){return Date.now()/1e3>d.expiresAt}function B(d){return Number(d.amount)/1e6}var re="0.9.4",b=process.env.MIXRPAY_BASE_URL||"https://www.mixrpay.com";var je=3e4,ne={BASE_MAINNET:{chainId:8453,name:"Base",isTestnet:false},BASE_SEPOLIA:{chainId:84532,name:"Base Sepolia",isTestnet:true}},ae={debug:0,info:1,warn:2,error:3,none:4},J=class{level;prefix;constructor(e="none",t="[MixrPay]"){this.level=e,this.prefix=t;}setLevel(e){this.level=e;}shouldLog(e){return ae[e]>=ae[this.level]}debug(...e){this.shouldLog("debug")&&console.log(`${this.prefix} \u{1F50D}`,...e);}info(...e){this.shouldLog("info")&&console.log(`${this.prefix} \u2139\uFE0F`,...e);}warn(...e){this.shouldLog("warn")&&console.warn(`${this.prefix} \u26A0\uFE0F`,...e);}error(...e){this.shouldLog("error")&&console.error(`${this.prefix} \u274C`,...e);}payment(e,t,s){if(this.shouldLog("info")){let n=s?` for "${s}"`:"";console.log(`${this.prefix} \u{1F4B8} Paid $${e.toFixed(4)} to ${t.slice(0,10)}...${n}`);}}},G=class d{sessionKey;walletAddress;maxPaymentUsd;onPayment;baseUrl;timeout;logger;payments=[];totalSpentUsd=0;sessionKeyInfo;sessionKeyInfoFetchedAt;allowlist;allowlistFetchedAt;selfCustodyAddress;selfCustodyKey;agentInstanceId;apiKey;constructor(e){this.validateConfig(e),this.sessionKey=O.fromString(e.sessionKey),this.walletAddress=e.walletAddress||this.sessionKey.address,this.maxPaymentUsd=e.maxPaymentUsd,this.onPayment=e.onPayment,this.baseUrl=(e.baseUrl||b).replace(/\/$/,""),this.timeout=e.timeout||je,e.apiKey&&(this.apiKey=e.apiKey),this.logger=new J(e.logLevel||"none"),this.logger.debug("AgentWallet initialized",{walletAddress:this.walletAddress,isTestnet:this.isTestnet(),maxPaymentUsd:this.maxPaymentUsd,hasApiKey:!!this.apiKey});}validateConfig(e){if(!e.sessionKey)throw new _("Session key is required. Get one from the wallet owner at https://mixrpay.com/manage/invites");let t=e.sessionKey.trim();if(!t.startsWith("sk_live_")&&!t.startsWith("sk_test_")){let a=t.slice(0,8);throw new _(`Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${a}'`)}let s=72;if(t.length!==s)throw new _(`Invalid session key length. Expected ${s} characters, got ${t.length}. Make sure you copied the complete key.`);let n=t.slice(8);if(!/^[0-9a-fA-F]+$/.test(n))throw new _("Invalid session key format. The key should contain only hexadecimal characters after the prefix.");if(e.maxPaymentUsd!==void 0){if(e.maxPaymentUsd<=0)throw new l("maxPaymentUsd must be a positive number");e.maxPaymentUsd>1e4&&this.logger?.warn("maxPaymentUsd is very high ($"+e.maxPaymentUsd+"). Consider using a lower limit for safety.");}}async fetchAllowlist(){if(this.allowlist!==void 0&&this.allowlistFetchedAt&&Date.now()-this.allowlistFetchedAt<3e5)return this.allowlist;try{let t=await this.getSessionKeyInfo();return this.allowlist=t.allowedMerchants||[],this.allowlistFetchedAt=Date.now(),this.logger.debug("Fetched allowlist",{patterns:this.allowlist.length,allowAll:this.allowlist.length===0}),this.allowlist}catch(t){return this.logger.warn("Failed to fetch allowlist, allowing all merchants",{error:t}),this.allowlist=[],this.allowlistFetchedAt=Date.now(),this.allowlist}}async validateMerchantAllowed(e,t){let s=await this.fetchAllowlist();if(s.length===0)return;if(!this.matchesAllowlist(e,s,t))throw new D(e,s)}matchesAllowlist(e,t,s){for(let n of t)if(this.matchPattern(e,n,s))return true;return false}matchPattern(e,t,s){return s==="url"?this.matchUrlPattern(e,t):this.matchToolPattern(e,t)}matchUrlPattern(e,t){let s;try{e.includes("://")?s=new URL(e).hostname.toLowerCase():s=e.toLowerCase();}catch{return false}let a=t.toLowerCase().trim();if(a.includes("://"))try{a=new URL(a).hostname;}catch{}if(s===a)return true;if(a.startsWith("*.")){let r=a.substring(2);if(s.endsWith(`.${r}`)&&s!==r)return true}return false}matchToolPattern(e,t){let s=e.toLowerCase().trim(),n=t.toLowerCase().trim();if(s===n)return true;if(n.endsWith("/*")){let a=n.substring(0,n.length-2);if(s.startsWith(`${a}/`))return true}return false}static async register(e){let{privateKey:t,name:s}=e,n=(e.baseUrl||b).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=register`);if(!i.ok){let h=await i.json().catch(()=>({}));throw new l(h.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:c}=await i.json(),p=await signMessage({message:c,privateKey:t}),u=await fetch(`${n}/api/v1/agent/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:o,external_wallet:r,signature:p,name:s})});if(!u.ok){let h=await u.json().catch(()=>({})),y=h.error||`Registration failed with status ${u.status}`,m=h.request_id,f=(h.code||"").toLowerCase(),w="";u.status===503?w=" The service may be temporarily unavailable. Please try again later.":u.status===500?w=" This is a server error. Please contact support with the request ID.":(f==="missing_challenge"||f==="missing_signature")&&(w=" This may indicate an SDK bug. Please update to the latest version.");let j=m?`${y} (request_id: ${m})${w}`:`${y}${w}`;throw new l(j)}let g=await u.json();return {userId:g.user_id,depositAddress:g.deposit_address}}static async checkServerHealth(e){let t=(e||b).replace(/\/$/,"");try{let s=await fetch(`${t}/api/health/ready?details=true`);if(!s.ok)return {healthy:!1,database:"unknown",agentRegistrationAvailable:!1,walletServiceConfigured:!1,error:`Health check failed with status ${s.status}`};let n=await s.json();return {healthy:n.status==="ready",database:n.database||"unknown",agentRegistrationAvailable:n.services?.agentRegistration?.available??!1,walletServiceConfigured:n.services?.wallet?.configured??!1}}catch(s){return {healthy:false,database:"unreachable",agentRegistrationAvailable:false,walletServiceConfigured:false,error:s instanceof Error?s.message:"Failed to reach server"}}}static async getSessionKey(e){let{privateKey:t,spendingLimitUsd:s,maxPerTxUsd:n,maxDailyUsd:a,durationDays:r}=e,i=(e.baseUrl||b).replace(/\/$/,""),c=privateKeyToAccount(t).address,p=await fetch(`${i}/api/v1/agent/challenge?wallet=${c}&action=session-key`);if(!p.ok){let f=await p.json().catch(()=>({}));throw new l(f.error||`Failed to get challenge: ${p.status}`)}let{challenge:u,message:g}=await p.json(),h=await signMessage({message:g,privateKey:t}),y=await fetch(`${i}/api/v1/agent/session-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:u,external_wallet:c,signature:h,spending_limit_usd:s,max_per_tx_usd:n,max_daily_usd:a,duration_days:r})});if(!y.ok){let f=await y.json().catch(()=>({}));throw new l(f.error||`Session key creation failed: ${y.status}`)}let m=await y.json();return {sessionKey:m.session_key,address:m.address,sessionKeyId:m.session_key_id,expiresAt:new Date(m.expires_at),limits:{maxTotalUsd:m.limits.max_total_usd,maxPerTxUsd:m.limits.max_per_tx_usd,maxDailyUsd:m.limits.max_daily_usd}}}static async getStatus(e){let{privateKey:t}=e,s=(e.baseUrl||b).replace(/\/$/,""),a=privateKeyToAccount(t).address,r=await fetch(`${s}/api/v1/agent/challenge?wallet=${a}&action=status`);if(!r.ok){let g=await r.json().catch(()=>({}));throw new l(g.error||`Failed to get challenge: ${r.status}`)}let{challenge:i,message:o}=await r.json(),c=await signMessage({message:o,privateKey:t}),p=await fetch(`${s}/api/v1/agent/status?challenge=${i}&external_wallet=${a}&signature=${encodeURIComponent(c)}`);if(!p.ok){let g=await p.json().catch(()=>({}));throw new l(g.error||`Failed to get status: ${p.status}`)}let u=await p.json();return {depositAddress:u.deposit_address,balanceUsd:u.balance_usd,activeSessions:u.active_sessions.map(g=>({id:g.id,expiresAt:new Date(g.expires_at),totalSpentUsd:g.total_spent_usd,remainingUsd:g.remaining_usd,maxTotalUsd:g.max_total_usd})),totalSpentUsd:u.total_spent_usd}}static async revokeSessionKey(e){let{privateKey:t,sessionKeyId:s}=e,n=(e.baseUrl||b).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=revoke`);if(!i.ok){let g=await i.json().catch(()=>({}));throw new l(g.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:c}=await i.json(),p=await signMessage({message:c,privateKey:t}),u=await fetch(`${n}/api/v1/agent/session-key/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:o,external_wallet:r,signature:p,session_key_id:s})});if(!u.ok){let g=await u.json().catch(()=>({}));throw new l(g.error||`Revocation failed: ${u.status}`)}return true}static async withdraw(e){let{privateKey:t,amountUsd:s}=e,n=(e.baseUrl||b).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=withdraw`);if(!i.ok){let h=await i.json().catch(()=>({}));throw new l(h.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:c}=await i.json(),p=await signMessage({message:c,privateKey:t}),u=await fetch(`${n}/api/v1/agent/withdraw`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:o,external_wallet:r,signature:p,to_address:r,amount_usd:s})});if(!u.ok){let h=await u.json().catch(()=>({}));throw new l(h.error||`Withdrawal failed: ${u.status}`)}let g=await u.json();return {txHash:g.tx_hash,amountUsd:g.amount_usd,remainingBalanceUsd:g.remaining_balance_usd}}static async claimInvite(e){let{inviteCode:t,privateKey:s}=e,n=(e.baseUrl||b).replace(/\/$/,""),r=privateKeyToAccount(s).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=claim-invite`);if(!i.ok){let h=await i.json().catch(()=>({}));throw new l(h.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:c}=await i.json(),p=await signMessage({message:c,privateKey:s}),u=await fetch(`${n}/api/v1/agent/claim-invite`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite_code:t,challenge:o,agent_wallet_address:r,signature:p})});if(!u.ok){let y=(await u.json().catch(()=>({}))).error||`Failed to claim invite: ${u.status}`,m="";throw u.status===404?m=" The invite code may be invalid or misspelled.":u.status===400&&(y.includes("already claimed")?m=" This invite has already been used by another agent.":y.includes("expired")?m=" Ask the wallet owner to create a new invite.":y.includes("revoked")&&(m=" The wallet owner has revoked this invite.")),new l(`${y}${m}`)}let g=await u.json();return {sessionKey:g.session_key,address:g.address,sessionKeyId:g.session_key_id,expiresAt:new Date(g.expires_at),limits:{budgetUsd:g.limits.budget_usd,budgetPeriod:g.limits.budget_period,maxPerTxUsd:g.limits.max_per_tx_usd},allowedMerchants:g.allowed_merchants||[],inviterName:g.inviter_name||"Anonymous"}}static async activate(e,t){let s=(t?.baseUrl||b).replace(/\/$/,""),n=new d({sessionKey:e,baseUrl:s}),a=await n.getSessionAuthHeaders(),r=await fetch(`${s}/api/v2/agent/activate`,{method:"POST",headers:{"Content-Type":"application/json",...a}});if(!r.ok){let o=await r.json().catch(()=>({}));throw new l(o.error||`Activation failed: ${r.status}`)}let i=await r.json();return {wallet:n,budget:{maxTotalUsd:i.budget.max_total_usd,maxDailyUsd:i.budget.max_daily_usd,maxPerTxUsd:i.budget.max_per_tx_usd,spentUsd:i.budget.spent_usd,remainingUsd:i.budget.remaining_usd},capabilities:{executeTransactions:i.capabilities.execute_transactions,gasSponsored:i.capabilities.gas_sponsored,batchedTx:i.capabilities.batched_tx},skills:i.skills||[],tools:i.tools||[],gatewayProviders:i.gateway_providers||[]}}static async connect(e){let t=(e?.baseUrl||process.env.MIXRPAY_BASE_URL||b).replace(/\/$/,""),s=e?.logLevel||"none",n=process.env.MIXRPAY_INSTANCE_ID;if(e?.sessionKey){let p=new d({sessionKey:e.sessionKey,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&p.setAgentInstanceId(n),p}let a=process.env.MIXRPAY_SESSION_KEY;if(a){let p=new d({sessionKey:a,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&p.setAgentInstanceId(n),p}let r=process.env.MIXRPAY_API_KEY||process.env.MIXRPAY_AGENT_TOKEN;if(r&&(r.startsWith("agt_live_")||r.startsWith("agt_test_")))return d.fromApiKey(r,{baseUrl:t,logLevel:s});let i=e?.accessCode||process.env.MIXRPAY_ACCESS_CODE;if(i)return d.fromAccessCode(i,{baseUrl:t,logLevel:s});let o=e?.masterKey||process.env.MIXRPAY_MASTER_KEY,c=e?.agentName||process.env.MIXRPAY_AGENT_NAME;if(o&&c)return d.fromMasterKey(o,c,{baseUrl:t,logLevel:s});try{let{loadCredentials:p}=await import('./credentials-Z4HQDXFU.js'),u=p();if(u.success&&u.credentials.sessionKey){let g=new d({sessionKey:u.credentials.sessionKey,baseUrl:u.credentials.baseUrl||t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment,apiKey:u.credentials.apiToken});return n&&g.setAgentInstanceId(n),g}if(u.success&&u.credentials.apiToken)return d.fromApiKey(u.credentials.apiToken,{baseUrl:t,logLevel:s});if(u.success&&u.credentials.masterKey&&u.credentials.defaultAgentName)return d.fromMasterKey(u.credentials.masterKey,u.credentials.defaultAgentName,{baseUrl:t,logLevel:s})}catch{}if(e?.interactive)return d.deviceFlowLogin({baseUrl:t,logLevel:s});throw new l(`No MixrPay credentials found. Options:
2
+ 1. Set MIXRPAY_SESSION_KEY environment variable
3
+ 2. Set MIXRPAY_API_KEY or MIXRPAY_AGENT_TOKEN environment variable (agt_live_xxx)
4
+ 3. Set MIXRPAY_ACCESS_CODE environment variable (mixr-xxx)
5
+ 4. Pass sessionKey or accessCode to connect()
6
+ 5. Run \`npx mixrpay login\` to cache credentials
7
+ 6. Use connect({ interactive: true }) for browser login`)}static async fromApiKey(e,t){let s=(t?.baseUrl||b).replace(/\/$/,"");if(!e.startsWith("agt_live_")&&!e.startsWith("agt_test_"))throw new l(`Invalid API key format. Expected 'agt_live_' or 'agt_test_' prefix, got '${e.slice(0,9)}...'`);let n=await fetch(`${s}/api/v2/agent/session-from-token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(!n.ok){let o=await n.json().catch(()=>({}));throw new l(o.error||`Failed to exchange API key for session: ${n.status}`)}let a=await n.json(),r=a.session_key;if(!r)throw new l("No session_key in API response");let i=new d({sessionKey:r,baseUrl:s,logLevel:t?.logLevel});return i.setApiKey(e),a.agent_instance_id&&i.setAgentInstanceId(a.agent_instance_id),i}static async fromAccessCode(e,t){let s=(t?.baseUrl||b).replace(/\/$/,"");if(!e.startsWith("mixr-"))throw new l(`Invalid access code format. Expected 'mixr-' prefix, got '${e.slice(0,5)}...'`);let n=await fetch(`${s}/api/v2/agent/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!n.ok){let p=await n.json().catch(()=>({})),u=(p.code||"").toLowerCase(),g="";throw n.status===404||u==="invalid_code"?g=" Check the code for typos or get a new one from the MixrPay dashboard.":n.status===400&&(u==="code_claimed"?g=" This code has already been used. Get a new code from the dashboard.":u==="code_expired"?g=" This code has expired. Get a new code from the dashboard.":u==="code_revoked"&&(g=" This code has been revoked by the owner.")),new l((p.error||`Failed to activate access code: ${n.status}`)+g)}let a=await n.json(),r=a.session_key,i=a.token,o=a.agent_id;if(!r)throw new l("No session_key in access code response");try{let{saveCredentials:p}=await import('./credentials-Z4HQDXFU.js');p({sessionKey:r,apiToken:i,baseUrl:s});}catch{}let c=new d({sessionKey:r,baseUrl:s,logLevel:t?.logLevel});return i&&(c.apiKey=i),o&&(c.agentInstanceId=o),c}static async fromMasterKey(e,t,s){let n=(s?.baseUrl||b).replace(/\/$/,"");if(!e.startsWith("mk_live_")&&!e.startsWith("mk_test_"))throw new l("Invalid master key format. Expected 'mk_live_' or 'mk_test_' prefix.");let a=await fetch(`${n}/api/v2/master-keys/session`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({agent_name:t})});if(!a.ok){let c=await a.json().catch(()=>({}));throw a.status===404?new l(`Agent '${t}' not found. Use the MixrPay dashboard to create it.`):new l(c.error||`Failed to get session from master key: ${a.status}`)}let r=await a.json(),i=r.session_key;if(!i)throw new l("No session_key in master key response");let o=new d({sessionKey:i,baseUrl:n,logLevel:s?.logLevel});return r.agent?.id&&(o.agentInstanceId=r.agent.id),o}static async deviceFlowLogin(e){let t=(e?.baseUrl||b).replace(/\/$/,""),s=await fetch(`${t}/api/v2/auth/device/authorize`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok){let h=await s.json().catch(()=>({}));throw new l(h.error||`Device flow initiation failed: ${s.status}`)}let n=await s.json(),{device_code:a,user_code:r,verification_uri:i,verification_uri_complete:o,expires_in:c,interval:p}=n;console.log(`
8
+ \u{1F510} MixrPay Login
9
+ `),console.log(`Visit: ${o||i}`),console.log(`Enter code: ${r}
10
+ `),console.log(`Waiting for authentication...
11
+ `);let u=(p||5)*1e3,g=Date.now()+(c||300)*1e3;for(;Date.now()<g;){await new Promise(f=>setTimeout(f,u));let h=await fetch(`${t}/api/v2/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:a})});if(h.ok){let w=(await h.json()).session_key;if(w){console.log(`\u2705 Authenticated successfully!
12
+ `);try{let{saveCredentials:j}=await import('./credentials-Z4HQDXFU.js');j({sessionKey:w,baseUrl:t});}catch{}return new d({sessionKey:w,baseUrl:t,logLevel:e?.logLevel})}}let m=(await h.json().catch(()=>({}))).error;if(m!=="authorization_pending")if(m==="slow_down"){await new Promise(f=>setTimeout(f,u));continue}else {if(m==="expired_token")throw new l("Device code expired. Please try again.");if(m==="access_denied")throw new l("Authentication was denied by the user.");if(m)throw new l(`Device flow error: ${m}`)}}throw new l("Device flow timed out. Please try again.")}async spawnChildInvite(e){let{budgetUsd:t,name:s,allowedMerchants:n,expiresInDays:a}=e,r=await this.getSessionAuthHeaders(),i=await fetch(`${this.baseUrl}/api/v1/agent/spawn`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify({budget_usd:t,name:s,allowed_merchants:n,expires_in_days:a})});if(!i.ok){let c=await i.json().catch(()=>({}));throw i.status===409?new l("Concurrent modification - please retry"):i.status===429?new l("Rate limited - too many spawn attempts"):new l(c.error||`Failed to spawn child: ${i.status}`)}let o=await i.json();return {inviteCode:o.invite_code,inviteId:o.invite_id,budgetUsd:o.budget_usd,expiresAt:new Date(o.expires_at),depth:o.depth,maxSpawnBudget:o.max_spawn_budget,allowedMerchants:o.allowed_merchants||[]}}async getAvailableBudget(){let e=await this.getSessionAuthHeaders(),t=await fetch(`${this.baseUrl}/api/v1/agent/descendants`,{method:"GET",headers:e});if(!t.ok){let n=await t.json().catch(()=>({}));throw new l(n.error||`Failed to get budget: ${t.status}`)}let s=await t.json();return {totalBudget:s.budget.total_usd,spent:s.budget.spent_usd,allocatedToChildren:s.budget.allocated_to_children_usd,available:s.budget.available_usd,maxSpawnBudget:s.max_spawn_budget,canSpawn:s.can_spawn}}async getChildSessions(){let e=await this.getSessionAuthHeaders(),t=await fetch(`${this.baseUrl}/api/v1/agent/descendants`,{method:"GET",headers:e});if(!t.ok){let n=await t.json().catch(()=>({}));throw new l(n.error||`Failed to get children: ${t.status}`)}return (await t.json()).children||[]}async listChildSessions(){return this.getChildSessions()}async fetch(e,t){this.logger.debug(`Fetching ${t?.method||"GET"} ${e}`),await this.validateMerchantAllowed(e,"url");let s=crypto.randomUUID(),n=this.extractCorrelationId(t?.headers),a=new AbortController,r=setTimeout(()=>a.abort(),this.timeout);try{let i=await fetch(e,{...t,signal:a.signal});return this.logger.debug(`Initial response: ${i.status}`),i.status===402&&(this.logger.info(`Payment required for ${e}`),i=await this.handlePaymentRequired(e,t,i,s,n)),i}catch(i){throw i instanceof Error&&i.name==="AbortError"?new l(`Request timeout after ${this.timeout}ms`):i}finally{clearTimeout(r);}}extractCorrelationId(e){if(!e)return;if(e instanceof Headers)return e.get("X-Correlation-Id")||e.get("x-correlation-id")||void 0;if(Array.isArray(e)){let s=e.find(([n])=>n.toLowerCase()==="x-correlation-id");return s?s[1]:void 0}let t=e;return t["X-Correlation-Id"]||t["x-correlation-id"]||void 0}async handlePaymentRequired(e,t,s,n,a){let r;try{r=await Q(s),this.logger.debug("Payment requirements:",{amount:`$${B(r).toFixed(4)}`,recipient:r.recipient,description:r.description});}catch(u){throw this.logger.error("Failed to parse payment requirements:",u),new A(`Failed to parse payment requirements: ${u}. The server may not be properly configured for x402 payments.`)}if(te(r))throw new A("Payment requirements have expired. This usually means the request took too long. Try again.");let i=B(r);if(this.maxPaymentUsd!==void 0&&i>this.maxPaymentUsd)throw new v("client_max",this.maxPaymentUsd,i);let o;try{this.logger.debug("Signing payment authorization..."),o=await ee(r,this.sessionKey,this.walletAddress);}catch(u){throw this.logger.error("Failed to sign payment:",u),new A(`Failed to sign payment: ${u}. This may indicate an issue with the session key.`)}this.logger.debug("Retrying request with payment...");let c=new Headers(t?.headers);c.set("X-PAYMENT",o);let p=await fetch(e,{...t,headers:c});if(p.status!==402){let u={amountUsd:i,recipient:r.recipient,txHash:p.headers.get("X-Payment-TxHash"),timestamp:new Date,description:r.description,url:e,requestId:n,correlationId:a};this.payments.push(u),this.totalSpentUsd+=i,this.logger.payment(i,r.recipient,r.description),this.onPayment&&this.onPayment(u);}else await this.handlePaymentError(p);return p}async handlePaymentError(e){let t={};try{t=await e.json();}catch{}let s=(t.error_code||"").toLowerCase(),n=t.error||t.message||"Payment required";if(this.logger.error("Payment failed:",{errorCode:s,errorMessage:n,errorData:t}),s==="insufficient_balance"){let a=t.required||0,r=t.available||0;throw new S(a,r)}else throw s==="session_key_expired"?new $(t.expired_at||"unknown"):s==="spending_limit_exceeded"?new v(t.limit_type||"unknown",t.limit||0,t.attempted||0):new A(n)}getWalletAddress(){return this.walletAddress}isTestnet(){return this.sessionKey.isTest}getNetwork(){return this.isTestnet()?ne.BASE_SEPOLIA:ne.BASE_MAINNET}async getBalance(){this.logger.debug("Fetching wallet balance...");try{let e=await fetch(`${this.baseUrl}/api/v1/session-key/info`,{headers:{"X-Session-Key":this.sessionKey.address.toLowerCase()}});if(!e.ok)throw new Error("Failed to get session key info");let t=await e.json(),s=t.wallet_address||t.walletAddress;if(!s)throw new Error("No wallet address in session key info");let n=await fetch(`${this.baseUrl}/api/wallet/balance?address=${s}&chain=base`);if(n.ok){let a=await n.json(),r=a.balance_usdc||a.balance_usd||0;return this.logger.debug(`Balance: $${r}`),r}}catch(e){this.logger.warn("Failed to fetch balance:",e);}return this.logger.debug("Using estimated balance based on tracking"),Math.max(0,100-this.totalSpentUsd)}async canAfford(e){let t=await this.getBalance(),s=t>=e;return {canAfford:s,balance:t,shortfall:s?0:e-t,remainingAfter:s?t-e:0}}async getSessionKeyInfo(e=false){let t=this.sessionKeyInfoFetchedAt?Date.now()-this.sessionKeyInfoFetchedAt:1/0;if(!e&&this.sessionKeyInfo&&t<6e4)return this.sessionKeyInfo;this.logger.debug("Fetching session key info...");try{let s=await fetch(`${this.baseUrl}/api/v1/session-key/info`,{headers:{"X-Session-Key":this.sessionKey.address.toLowerCase()}});if(s.ok){let n=await s.json();return this.sessionKeyInfo={address:this.sessionKey.address,walletAddress:n.wallet_address??n.walletAddress??null,isValid:n.is_valid??n.isValid??!0,limits:{perTxUsd:n.per_tx_limit_usd??n.perTxLimitUsd??null,dailyUsd:n.daily_limit_usd??n.dailyLimitUsd??null,totalUsd:n.total_limit_usd??n.totalLimitUsd??null},usage:{todayUsd:n.today_spent_usd??n.todaySpentUsd??0,totalUsd:n.total_spent_usd??n.totalSpentUsd??0,txCount:n.tx_count??n.txCount??0},expiresAt:n.expires_at?new Date(n.expires_at):null,createdAt:n.created_at?new Date(n.created_at):null,name:n.name,allowedMerchants:n.allowed_merchants??n.allowedMerchants??[]},this.sessionKeyInfoFetchedAt=Date.now(),this.sessionKeyInfo}}catch(s){this.logger.warn("Failed to fetch session key info:",s);}return {address:this.sessionKey.address,walletAddress:null,isValid:true,limits:{perTxUsd:null,dailyUsd:null,totalUsd:null},usage:{todayUsd:this.totalSpentUsd,totalUsd:this.totalSpentUsd,txCount:this.payments.length},expiresAt:null,createdAt:null}}async getSpendingStats(){this.logger.debug("Fetching spending stats...");try{let e=await fetch(`${this.baseUrl}/api/v1/session-key/stats`,{headers:{"X-Session-Key":this.sessionKey.address.toLowerCase()}});if(e.ok){let t=await e.json();return {totalSpentUsd:t.total_spent_usd||t.totalSpentUsd||this.totalSpentUsd,txCount:t.tx_count||t.txCount||this.payments.length,remainingDailyUsd:t.remaining_daily_usd||t.remainingDailyUsd||null,remainingTotalUsd:t.remaining_total_usd||t.remainingTotalUsd||null,expiresAt:t.expires_at?new Date(t.expires_at):null}}}catch(e){this.logger.warn("Failed to fetch spending stats:",e);}return {totalSpentUsd:this.totalSpentUsd,txCount:this.payments.length,remainingDailyUsd:null,remainingTotalUsd:null,expiresAt:null}}getPaymentHistory(){return [...this.payments]}getTotalSpent(){return this.totalSpentUsd}async createSelfCustodyWallet(){if(!this.agentInstanceId)throw new l("Agent instance ID is required for self-custody wallet. Use AgentWallet.fromApiKey() or set MIXRPAY_INSTANCE_ID environment variable.","NO_AGENT_INSTANCE_ID");let e=await K();if(e){let i=privateKeyToAccount(e);return this.selfCustodyAddress=i.address,this.selfCustodyKey=e,this.logger.info("Loaded existing self-custody wallet",{address:i.address}),{address:i.address,privateKey:e}}let t=generatePrivateKey(),s=privateKeyToAccount(t),n=Date.now(),a=`MixrPay Wallet Registration
13
+ Address: ${s.address}
14
+ Timestamp: ${n}`,r=await s.signMessage({message:a});return await this.registerWalletAddress(s.address,r,n),await W(t,s.address),this.selfCustodyAddress=s.address,this.selfCustodyKey=t,this.logger.info("Created self-custody wallet",{address:s.address}),{address:s.address,privateKey:t}}async registerWalletAddress(e,t,s){if(!this.apiKey)throw new l("API key is required for wallet registration. Use AgentWallet.fromApiKey() to initialize.","NO_API_KEY");let n=await fetch(`${this.baseUrl}/api/v2/agent/wallet/register`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({address:e,signature:t,timestamp:s})});if(!n.ok){let a=await n.json().catch(()=>({}));throw new l(a.error||`Failed to register wallet: ${n.status}`,"WALLET_REGISTRATION_FAILED")}}async loadSelfCustodyWallet(){let e=await K();if(!e)return false;let t=privateKeyToAccount(e);return this.selfCustodyAddress=t.address,this.selfCustodyKey=e,this.logger.debug("Loaded self-custody wallet",{address:t.address}),true}async hasSelfCustodyWallet(){return await q()}getSelfCustodyAddress(){return this.selfCustodyAddress||null}async executeFromOwnWallet(e){if(!this.selfCustodyKey||!this.selfCustodyAddress)throw new l("Self-custody wallet not loaded. Call loadSelfCustodyWallet() or createSelfCustodyWallet() first.","WALLET_NOT_LOADED");let{to:t,value:s,data:n,gasLimit:a}=e,r=privateKeyToAccount(this.selfCustodyKey),i=createWalletClient({account:r,chain:base,transport:http()});this.logger.debug("Executing transaction from self-custody wallet",{from:this.selfCustodyAddress,to:t,value:s?.toString()});try{let o=await i.sendTransaction({to:t,value:s??BigInt(0),data:n,gas:a});this.logger.info("Transaction submitted",{txHash:o});let c=!1;try{await this.reportTransaction(o,t,s??BigInt(0)),c=!0;}catch(p){this.logger.warn("Failed to report transaction to MixrPay",{txHash:o,error:p instanceof Error?p.message:p});}return {txHash:o,reportedToMixrPay:c}}catch(o){throw this.logger.error("Transaction failed",{error:o instanceof Error?o.message:o}),new l(`Transaction failed: ${o instanceof Error?o.message:"Unknown error"}`,"TRANSACTION_FAILED")}}async transferUSDC(e){if(!this.selfCustodyKey||!this.selfCustodyAddress)throw new l("Self-custody wallet not loaded. Call loadSelfCustodyWallet() or createSelfCustodyWallet() first.","WALLET_NOT_LOADED");let{to:t,amountUsdc:s}=e,n="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",a=6,r=parseUnits(s.toFixed(a),a),i=encodeFunctionData({abi:[{name:"transfer",type:"function",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],functionName:"transfer",args:[t,r]});return this.logger.debug("Transferring USDC",{from:this.selfCustodyAddress,to:t,amountUsdc:s,amountMinorUnits:r.toString()}),(await this.executeFromOwnWallet({to:n,data:i})).txHash}async reportTransaction(e,t,s){if(!this.apiKey){this.logger.warn("Cannot report transaction - no API key set");return}let n=await fetch(`${this.baseUrl}/api/v2/agent/tx/report`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({tx_hash:e,to_address:t,value:s.toString(),chain_id:base.id})});if(!n.ok){let a=await n.json().catch(()=>({}));throw new l(a.error||`Failed to report transaction: ${n.status}`,"TX_REPORT_FAILED")}}getAgentInstanceId(){return this.agentInstanceId}setAgentInstanceId(e){this.agentInstanceId=e;}setApiKey(e){this.apiKey=e;}mcp(){let e=join(dirname(fileURLToPath(import.meta.url)),"mcp-server.js"),t={MIXRPAY_SESSION_KEY:this.sessionKey.toString(),MIXRPAY_BASE_URL:this.baseUrl};return this.apiKey&&(t.MIXRPAY_API_KEY=this.apiKey),this.agentInstanceId&&(t.MIXRPAY_INSTANCE_ID=this.agentInstanceId),this.selfCustodyKey&&(t.AGENT_WALLET_KEY=this.selfCustodyKey),this.maxPaymentUsd&&(t.MIXRPAY_MAX_PAYMENT_USD=String(this.maxPaymentUsd)),{command:"node",args:[e],env:t}}async runDiagnostics(){this.logger.info("Running diagnostics...");let e=[],t=[],s={},n,a;s.sessionKeyFormat=true;try{let o=Date.now(),c=await fetch(`${this.baseUrl}/health`,{method:"GET",signal:AbortSignal.timeout(5e3)});n=Date.now()-o,s.apiConnectivity=c.ok,c.ok||(e.push(`API server returned ${c.status}. Check baseUrl configuration.`),t.push("Verify the baseUrl configuration points to a valid MixrPay server.")),n>2e3&&(e.push(`High API latency: ${n}ms. This may cause timeouts.`),t.push("Consider using a server closer to your region or check network connectivity."));}catch{s.apiConnectivity=false,e.push("Cannot connect to MixrPay API. Check your network connection and baseUrl."),t.push("Verify network connectivity and that the MixrPay server is running.");}try{let o=await this.getSessionKeyInfo(!0);s.sessionKeyValid=o.isValid,o.isValid||(e.push("Session key is invalid or has been revoked."),t.push("Request a new session key from the wallet owner at https://mixrpay.com/manage/invites"));let c=new Date,p=null;o.expiresAt&&(p=(o.expiresAt.getTime()-c.getTime())/(1e3*60*60),o.expiresAt<c?(s.sessionKeyValid=!1,e.push(`Session key expired on ${o.expiresAt.toISOString()}`),t.push("Create a new session key to continue making payments.")):p<24&&(e.push(`Session key expires in ${p.toFixed(1)} hours.`),t.push("Consider creating a new session key before the current one expires.")));let u=await this.getSpendingStats();a={remainingDailyUsd:u.remainingDailyUsd,remainingTotalUsd:u.remainingTotalUsd,expiresAt:o.expiresAt,expiresInHours:p},u.remainingDailyUsd!==null&&u.remainingDailyUsd<1&&(e.push(`Daily limit nearly exhausted: $${u.remainingDailyUsd.toFixed(2)} remaining.`),t.push("Wait until tomorrow for daily limit to reset, or request a higher daily limit.")),u.remainingTotalUsd!==null&&u.remainingTotalUsd<1&&(e.push(`Total limit nearly exhausted: $${u.remainingTotalUsd.toFixed(2)} remaining.`),t.push("Request a new session key with a higher total limit."));}catch{s.sessionKeyValid=false,e.push("Could not verify session key validity."),t.push("Check network connectivity and try again.");}let r=0;try{r=await this.getBalance(),s.hasBalance=r>0,r<=0?(e.push("Wallet has no USDC balance. Top up at https://mixrpay.com/manage/wallet"),t.push("Deposit USDC to your wallet address to enable payments.")):r<1&&(e.push(`Low balance: $${r.toFixed(2)}. Consider topping up.`),t.push("Top up your wallet balance to avoid payment failures."));}catch{s.hasBalance=false,e.push("Could not fetch wallet balance."),t.push("Check network connectivity and try again.");}let i=e.length===0;return this.logger.info("Diagnostics complete:",{healthy:i,issues:e,latencyMs:n}),{healthy:i,issues:e,checks:s,sdkVersion:re,network:this.getNetwork().name,walletAddress:this.walletAddress,sessionLimits:a,latencyMs:n,recommendations:t}}async generateSiwe(e){let{domain:t,uri:s,statement:n,nonce:a=crypto.randomUUID(),issuedAt:r=new Date,expirationTime:i,notBefore:o,requestId:c,resources:p}=e,u=this.sessionKey.address,g=this.getNetwork().chainId,h="1",y=`${t} wants you to sign in with your Ethereum account:
15
+ `;if(y+=`${u}
7
16
 
8
- // src/errors.ts
9
- var MixrPayError = class extends Error {
10
- /** Error code for programmatic handling */
11
- code;
12
- /** Optional hint for how long to wait before retrying (in milliseconds) */
13
- retryAfterMs;
14
- constructor(message, code = "MIXRPAY_ERROR", retryAfterMs) {
15
- super(message);
16
- this.name = "MixrPayError";
17
- this.code = code;
18
- this.retryAfterMs = retryAfterMs;
19
- if (Error.captureStackTrace) {
20
- Error.captureStackTrace(this, this.constructor);
21
- }
22
- }
23
- /**
24
- * Check if this error is retryable.
25
- *
26
- * Returns true if the operation might succeed on retry (e.g., transient network issues).
27
- * Returns false if the error requires user action to resolve (e.g., insufficient balance).
28
- *
29
- * @returns true if the operation should be retried, false otherwise
30
- *
31
- * @example
32
- * ```typescript
33
- * try {
34
- * await wallet.fetch(...);
35
- * } catch (error) {
36
- * if (error instanceof MixrPayError && error.isRetryable()) {
37
- * // Retry the operation
38
- * await retry();
39
- * } else {
40
- * // Handle permanent failure
41
- * throw error;
42
- * }
43
- * }
44
- * ```
45
- */
46
- isRetryable() {
47
- return false;
48
- }
49
- };
50
- var InsufficientBalanceError = class extends MixrPayError {
51
- /** Amount required for the payment in USD */
52
- required;
53
- /** Current available balance in USD */
54
- available;
55
- /** URL where the user can top up their wallet */
56
- topUpUrl;
57
- constructor(required, available) {
58
- const shortage = required - available;
59
- super(
60
- `Insufficient balance: need $${required.toFixed(2)}, have $${available.toFixed(2)} (short $${shortage.toFixed(2)}). Top up your wallet to continue.`,
61
- "INSUFFICIENT_BALANCE"
62
- );
63
- this.name = "InsufficientBalanceError";
64
- this.required = required;
65
- this.available = available;
66
- this.topUpUrl = "https://mixrpay.com/manage/wallet";
67
- }
68
- };
69
- var SessionKeyExpiredError = class extends MixrPayError {
70
- /** When the session key expired */
71
- expiredAt;
72
- constructor(expiredAt) {
73
- super(
74
- `Session key expired at ${expiredAt}. Request a new session key from the wallet owner at https://mixrpay.com/manage/invites`,
75
- "SESSION_KEY_EXPIRED"
76
- );
77
- this.name = "SessionKeyExpiredError";
78
- this.expiredAt = expiredAt;
79
- }
80
- };
81
- var SpendingLimitExceededError = class extends MixrPayError {
82
- /** Type of limit that was exceeded */
83
- limitType;
84
- /** The limit amount in USD */
85
- limit;
86
- /** The amount that was attempted in USD */
87
- attempted;
88
- constructor(limitType, limit, attempted) {
89
- const limitNames = {
90
- per_tx: "Per-transaction",
91
- daily: "Daily",
92
- total: "Total",
93
- client_max: "Client-side"
94
- };
95
- const limitName = limitNames[limitType] || limitType;
96
- const suggestion = limitType === "daily" ? "Wait until tomorrow or request a higher limit." : limitType === "client_max" ? "Increase maxPaymentUsd in your AgentWallet configuration." : "Request a new session key with a higher limit.";
97
- super(
98
- `${limitName} spending limit exceeded: limit is $${limit.toFixed(2)}, attempted $${attempted.toFixed(2)}. ${suggestion}`,
99
- "SPENDING_LIMIT_EXCEEDED"
100
- );
101
- this.name = "SpendingLimitExceededError";
102
- this.limitType = limitType;
103
- this.limit = limit;
104
- this.attempted = attempted;
105
- }
106
- /**
107
- * Daily limits reset at midnight, so those are retryable (after waiting).
108
- * Other limit types require user action (new session key, config change).
109
- * @returns true only for daily limits
110
- */
111
- isRetryable() {
112
- return this.limitType === "daily";
113
- }
114
- };
115
- var PaymentFailedError = class extends MixrPayError {
116
- /** Detailed reason for the failure */
117
- reason;
118
- /** Transaction hash if the tx was submitted (for debugging) */
119
- txHash;
120
- constructor(reason, txHash) {
121
- let message = `Payment failed: ${reason}`;
122
- if (txHash) {
123
- message += ` (tx: ${txHash} - check on basescan.org)`;
124
- }
125
- super(message, "PAYMENT_FAILED");
126
- this.name = "PaymentFailedError";
127
- this.reason = reason;
128
- this.txHash = txHash;
129
- }
130
- /**
131
- * Payment failures are often transient (network issues, temporary server errors).
132
- * @returns true - payment failures should generally be retried
133
- */
134
- isRetryable() {
135
- return true;
136
- }
137
- };
138
- var InvalidSessionKeyError = class extends MixrPayError {
139
- /** Detailed reason why the key is invalid */
140
- reason;
141
- constructor(reason = "Invalid session key format") {
142
- super(
143
- `${reason}. Session keys should be in format: sk_live_<64 hex chars> or sk_test_<64 hex chars>. Get one from https://mixrpay.com/manage/invites`,
144
- "INVALID_SESSION_KEY"
145
- );
146
- this.name = "InvalidSessionKeyError";
147
- this.reason = reason;
148
- }
149
- };
150
- var X402ProtocolError = class extends MixrPayError {
151
- /** Detailed reason for the protocol error */
152
- reason;
153
- constructor(reason) {
154
- super(
155
- `x402 protocol error: ${reason}. This may indicate a server configuration issue. If the problem persists, contact the API provider.`,
156
- "X402_PROTOCOL_ERROR"
157
- );
158
- this.name = "X402ProtocolError";
159
- this.reason = reason;
160
- }
161
- /**
162
- * Protocol errors may be caused by temporary server issues.
163
- * @returns true - worth retrying in case server recovers
164
- */
165
- isRetryable() {
166
- return true;
167
- }
168
- };
169
- var SessionExpiredError = class extends MixrPayError {
170
- /** ID of the expired session */
171
- sessionId;
172
- /** When the session expired (ISO string or Date) */
173
- expiredAt;
174
- constructor(sessionId, expiredAt) {
175
- super(
176
- `Session ${sessionId} has expired${expiredAt ? ` at ${expiredAt}` : ""}. A new session will be created automatically on your next request.`,
177
- "SESSION_EXPIRED"
178
- );
179
- this.name = "SessionExpiredError";
180
- this.sessionId = sessionId;
181
- this.expiredAt = expiredAt;
182
- }
183
- };
184
- var SessionLimitExceededError = class extends MixrPayError {
185
- /** ID of the session */
186
- sessionId;
187
- /** The session's spending limit in USD */
188
- limit;
189
- /** The amount requested in USD */
190
- requested;
191
- /** Remaining balance in the session (limit - used) */
192
- remaining;
193
- constructor(limit, requested, remaining, sessionId) {
194
- super(
195
- `Session spending limit exceeded: limit is $${limit.toFixed(2)}, requested $${requested.toFixed(2)}, remaining $${remaining.toFixed(2)}. Create a new session with a higher limit to continue.`,
196
- "SESSION_LIMIT_EXCEEDED"
197
- );
198
- this.name = "SessionLimitExceededError";
199
- this.sessionId = sessionId;
200
- this.limit = limit;
201
- this.requested = requested;
202
- this.remaining = remaining;
203
- }
204
- };
205
- var SessionNotFoundError = class extends MixrPayError {
206
- /** The session ID that was not found */
207
- sessionId;
208
- constructor(sessionId) {
209
- super(
210
- `Session ${sessionId} not found. It may have been deleted or never existed. Create a new session with getOrCreateSession().`,
211
- "SESSION_NOT_FOUND"
212
- );
213
- this.name = "SessionNotFoundError";
214
- this.sessionId = sessionId;
215
- }
216
- };
217
- var SessionRevokedError = class extends MixrPayError {
218
- /** The session ID that was revoked */
219
- sessionId;
220
- /** Optional reason for revocation */
221
- reason;
222
- constructor(sessionId, reason) {
223
- super(
224
- `Session ${sessionId} has been revoked${reason ? `: ${reason}` : ""}. Create a new session with getOrCreateSession().`,
225
- "SESSION_REVOKED"
226
- );
227
- this.name = "SessionRevokedError";
228
- this.sessionId = sessionId;
229
- this.reason = reason;
230
- }
231
- };
232
- var MerchantNotAllowedError = class extends MixrPayError {
233
- /** The merchant/tool that was attempted */
234
- attempted;
235
- /** The patterns that are allowed by the session */
236
- allowedPatterns;
237
- constructor(attempted, allowedPatterns) {
238
- const patternsPreview = allowedPatterns.slice(0, 3).join(", ");
239
- const suffix = allowedPatterns.length > 3 ? "..." : "";
240
- super(
241
- `Payment to "${attempted}" not allowed. Session allowlist: ${patternsPreview}${suffix}. Update the session allowlist or create a new session.`,
242
- "MERCHANT_NOT_ALLOWED"
243
- );
244
- this.name = "MerchantNotAllowedError";
245
- this.attempted = attempted;
246
- this.allowedPatterns = allowedPatterns;
247
- }
248
- };
249
- function isMixrPayError(error) {
250
- return error instanceof MixrPayError;
251
- }
252
- function getErrorMessage(error) {
253
- if (error instanceof MixrPayError) {
254
- return error.message;
255
- }
256
- if (error instanceof Error) {
257
- return error.message;
258
- }
259
- return String(error);
260
- }
17
+ `,n&&(y+=`${n}
261
18
 
262
- // src/session-key.ts
263
- var USDC_ADDRESSES = {
264
- 8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
265
- // Base Mainnet
266
- 84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
267
- // Base Sepolia
268
- };
269
- var USDC_EIP712_DOMAIN_BASE = {
270
- name: "USD Coin",
271
- version: "2"
272
- };
273
- var TRANSFER_WITH_AUTHORIZATION_TYPES = {
274
- TransferWithAuthorization: [
275
- { name: "from", type: "address" },
276
- { name: "to", type: "address" },
277
- { name: "value", type: "uint256" },
278
- { name: "validAfter", type: "uint256" },
279
- { name: "validBefore", type: "uint256" },
280
- { name: "nonce", type: "bytes32" }
281
- ]
282
- };
283
- var SessionKey = class _SessionKey {
284
- privateKey;
285
- account;
286
- address;
287
- isTest;
288
- constructor(privateKey, isTest) {
289
- this.privateKey = privateKey;
290
- this.account = privateKeyToAccount(privateKey);
291
- this.address = this.account.address;
292
- this.isTest = isTest;
293
- }
294
- /**
295
- * Get the private key as hex string (without 0x prefix).
296
- * Used for API authentication headers.
297
- */
298
- get privateKeyHex() {
299
- return this.privateKey.slice(2);
300
- }
301
- /**
302
- * Get the raw private key with 0x prefix.
303
- * Used internally for signing operations.
304
- */
305
- get rawPrivateKey() {
306
- return this.privateKey;
307
- }
308
- /**
309
- * Parse a session key string into a SessionKey object.
310
- *
311
- * @param sessionKey - Session key in format sk_live_... or sk_test_...
312
- * @returns SessionKey object
313
- * @throws InvalidSessionKeyError if the format is invalid
314
- */
315
- static fromString(sessionKey) {
316
- const pattern = /^sk_(live|test)_([a-fA-F0-9]{64})$/;
317
- const match = sessionKey.match(pattern);
318
- if (!match) {
319
- throw new InvalidSessionKeyError(
320
- "Session key must be in format sk_live_{64_hex} or sk_test_{64_hex}"
321
- );
322
- }
323
- const env = match[1];
324
- const hexKey = match[2];
325
- try {
326
- const privateKey = `0x${hexKey}`;
327
- return new _SessionKey(privateKey, env === "test");
328
- } catch (e) {
329
- throw new InvalidSessionKeyError(`Failed to decode session key: ${e}`);
330
- }
331
- }
332
- /**
333
- * Sign EIP-712 typed data for TransferWithAuthorization.
334
- *
335
- * @param domain - EIP-712 domain
336
- * @param message - Transfer authorization message
337
- * @returns Hex-encoded signature
338
- */
339
- async signTransferAuthorization(domain, message) {
340
- return signTypedData({
341
- privateKey: this.privateKey,
342
- domain,
343
- types: TRANSFER_WITH_AUTHORIZATION_TYPES,
344
- primaryType: "TransferWithAuthorization",
345
- message
346
- });
347
- }
348
- /**
349
- * Sign a plain message (EIP-191 personal sign).
350
- *
351
- * @param message - Message to sign
352
- * @returns Hex-encoded signature
353
- */
354
- async signMessage(message) {
355
- return viemSignMessage({
356
- privateKey: this.privateKey,
357
- message
358
- });
359
- }
360
- /**
361
- * Get the chain ID based on whether this is a test key.
362
- */
363
- getDefaultChainId() {
364
- return this.isTest ? 84532 : 8453;
365
- }
366
- };
367
- function buildTransferAuthorizationData(params) {
368
- const usdcAddress = USDC_ADDRESSES[params.chainId];
369
- if (!usdcAddress) {
370
- throw new Error(`USDC not supported on chain ${params.chainId}`);
371
- }
372
- const domain = {
373
- ...USDC_EIP712_DOMAIN_BASE,
374
- chainId: params.chainId,
375
- verifyingContract: usdcAddress
376
- };
377
- const message = {
378
- from: params.fromAddress,
379
- to: params.toAddress,
380
- value: params.value,
381
- validAfter: params.validAfter,
382
- validBefore: params.validBefore,
383
- nonce: params.nonce
384
- };
385
- return { domain, message };
386
- }
387
- function generateNonce() {
388
- const bytes = new Uint8Array(32);
389
- crypto.getRandomValues(bytes);
390
- return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
391
- }
392
- function buildSessionAuthMessage(timestamp, address) {
393
- return `MixrPay:${timestamp}:${address.toLowerCase()}`;
394
- }
395
- async function createSessionAuthPayload(sessionKey) {
396
- const timestamp = Date.now();
397
- const message = buildSessionAuthMessage(timestamp, sessionKey.address);
398
- const signature = await sessionKey.signMessage(message);
399
- return {
400
- address: sessionKey.address,
401
- timestamp,
402
- signature
403
- };
404
- }
405
-
406
- // src/agent-wallet.ts
407
- import { privateKeyToAccount as privateKeyToAccount2, signMessage } from "viem/accounts";
408
-
409
- // src/x402.ts
410
- async function parse402Response(response) {
411
- let paymentData = null;
412
- const paymentHeader = response.headers.get("X-Payment-Required");
413
- if (paymentHeader) {
414
- try {
415
- paymentData = JSON.parse(paymentHeader);
416
- } catch {
417
- }
418
- }
419
- if (!paymentData) {
420
- const authHeader = response.headers.get("WWW-Authenticate");
421
- if (authHeader?.startsWith("X-402 ")) {
422
- try {
423
- const encoded = authHeader.slice(6);
424
- paymentData = JSON.parse(atob(encoded));
425
- } catch {
426
- }
427
- }
428
- }
429
- if (!paymentData) {
430
- try {
431
- paymentData = await response.json();
432
- } catch {
433
- }
434
- }
435
- if (!paymentData) {
436
- throw new X402ProtocolError("Could not parse payment requirements from 402 response");
437
- }
438
- if (!paymentData.recipient) {
439
- throw new X402ProtocolError("Missing recipient in payment requirements");
440
- }
441
- if (!paymentData.amount) {
442
- throw new X402ProtocolError("Missing amount in payment requirements");
443
- }
444
- const now = Math.floor(Date.now() / 1e3);
445
- return {
446
- recipient: paymentData.recipient,
447
- amount: BigInt(paymentData.amount),
448
- currency: paymentData.currency || "USDC",
449
- chainId: paymentData.chainId || paymentData.chain_id || 8453,
450
- facilitatorUrl: paymentData.facilitatorUrl || paymentData.facilitator_url || "https://x402.org/facilitator",
451
- nonce: paymentData.nonce || generateNonce().slice(2),
452
- // Remove 0x prefix for storage
453
- expiresAt: paymentData.expiresAt || paymentData.expires_at || now + 300,
454
- description: paymentData.description
455
- };
456
- }
457
- async function buildXPaymentHeader(requirements, sessionKey, walletAddress) {
458
- const nonceHex = requirements.nonce.length === 64 ? `0x${requirements.nonce}` : generateNonce();
459
- const now = BigInt(Math.floor(Date.now() / 1e3));
460
- const validAfter = now - 60n;
461
- const validBefore = BigInt(requirements.expiresAt);
462
- const { domain, message } = buildTransferAuthorizationData({
463
- fromAddress: walletAddress,
464
- toAddress: requirements.recipient,
465
- value: requirements.amount,
466
- validAfter,
467
- validBefore,
468
- nonce: nonceHex,
469
- chainId: requirements.chainId
470
- });
471
- const signature = await sessionKey.signTransferAuthorization(domain, message);
472
- const paymentPayload = {
473
- x402Version: 1,
474
- scheme: "exact",
475
- network: requirements.chainId === 8453 ? "base" : "base-sepolia",
476
- payload: {
477
- signature,
478
- authorization: {
479
- from: walletAddress,
480
- to: requirements.recipient,
481
- value: requirements.amount.toString(),
482
- validAfter: validAfter.toString(),
483
- validBefore: validBefore.toString(),
484
- nonce: nonceHex
485
- }
486
- }
487
- };
488
- return btoa(JSON.stringify(paymentPayload));
489
- }
490
- function isPaymentExpired(requirements) {
491
- return Date.now() / 1e3 > requirements.expiresAt;
492
- }
493
- function getAmountUsd(requirements) {
494
- return Number(requirements.amount) / 1e6;
495
- }
496
-
497
- // src/agent-wallet.ts
498
- var SDK_VERSION = "0.8.7";
499
- var DEFAULT_BASE_URL = process.env.MIXRPAY_BASE_URL || "https://www.mixrpay.com";
500
- var DEFAULT_TIMEOUT = 3e4;
501
- var NETWORKS = {
502
- BASE_MAINNET: { chainId: 8453, name: "Base", isTestnet: false },
503
- BASE_SEPOLIA: { chainId: 84532, name: "Base Sepolia", isTestnet: true }
504
- };
505
- var LOG_LEVELS = {
506
- debug: 0,
507
- info: 1,
508
- warn: 2,
509
- error: 3,
510
- none: 4
511
- };
512
- var Logger = class {
513
- level;
514
- prefix;
515
- constructor(level = "none", prefix = "[MixrPay]") {
516
- this.level = level;
517
- this.prefix = prefix;
518
- }
519
- setLevel(level) {
520
- this.level = level;
521
- }
522
- shouldLog(level) {
523
- return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
524
- }
525
- debug(...args) {
526
- if (this.shouldLog("debug")) {
527
- console.log(`${this.prefix} \u{1F50D}`, ...args);
528
- }
529
- }
530
- info(...args) {
531
- if (this.shouldLog("info")) {
532
- console.log(`${this.prefix} \u2139\uFE0F`, ...args);
533
- }
534
- }
535
- warn(...args) {
536
- if (this.shouldLog("warn")) {
537
- console.warn(`${this.prefix} \u26A0\uFE0F`, ...args);
538
- }
539
- }
540
- error(...args) {
541
- if (this.shouldLog("error")) {
542
- console.error(`${this.prefix} \u274C`, ...args);
543
- }
544
- }
545
- payment(amount, recipient, description) {
546
- if (this.shouldLog("info")) {
547
- const desc = description ? ` for "${description}"` : "";
548
- console.log(`${this.prefix} \u{1F4B8} Paid $${amount.toFixed(4)} to ${recipient.slice(0, 10)}...${desc}`);
549
- }
550
- }
551
- };
552
- var AgentWallet = class {
553
- sessionKey;
554
- walletAddress;
555
- maxPaymentUsd;
556
- onPayment;
557
- baseUrl;
558
- timeout;
559
- logger;
560
- // Payment tracking
561
- payments = [];
562
- totalSpentUsd = 0;
563
- // Session key info cache
564
- sessionKeyInfo;
565
- sessionKeyInfoFetchedAt;
566
- // Merchant allowlist (fetched from server)
567
- allowlist;
568
- allowlistFetchedAt;
569
- /**
570
- * Create a new AgentWallet instance.
571
- *
572
- * @param config - Configuration options
573
- * @throws {InvalidSessionKeyError} If the session key format is invalid
574
- *
575
- * @example Basic initialization
576
- * ```typescript
577
- * const wallet = new AgentWallet({
578
- * sessionKey: 'sk_live_abc123...'
579
- * });
580
- * ```
581
- *
582
- * @example With all options
583
- * ```typescript
584
- * const wallet = new AgentWallet({
585
- * sessionKey: 'sk_live_abc123...',
586
- * maxPaymentUsd: 5.0, // Client-side safety limit
587
- * onPayment: (p) => log(p), // Track payments
588
- * logLevel: 'info', // Enable logging
589
- * timeout: 60000, // 60s timeout
590
- * });
591
- * ```
592
- */
593
- constructor(config) {
594
- this.validateConfig(config);
595
- this.sessionKey = SessionKey.fromString(config.sessionKey);
596
- this.walletAddress = config.walletAddress || this.sessionKey.address;
597
- this.maxPaymentUsd = config.maxPaymentUsd;
598
- this.onPayment = config.onPayment;
599
- this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
600
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
601
- this.logger = new Logger(config.logLevel || "none");
602
- this.logger.debug("AgentWallet initialized", {
603
- walletAddress: this.walletAddress,
604
- isTestnet: this.isTestnet(),
605
- maxPaymentUsd: this.maxPaymentUsd
606
- });
607
- }
608
- /**
609
- * Validate the configuration before initialization.
610
- */
611
- validateConfig(config) {
612
- if (!config.sessionKey) {
613
- throw new InvalidSessionKeyError(
614
- "Session key is required. Get one from the wallet owner at https://mixrpay.com/manage/invites"
615
- );
616
- }
617
- const key = config.sessionKey.trim();
618
- if (!key.startsWith("sk_live_") && !key.startsWith("sk_test_")) {
619
- throw new InvalidSessionKeyError(
620
- `Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${key.slice(0, 10)}...'`
621
- );
622
- }
623
- const expectedLength = 8 + 64;
624
- if (key.length !== expectedLength) {
625
- throw new InvalidSessionKeyError(
626
- `Invalid session key length. Expected ${expectedLength} characters, got ${key.length}. Make sure you copied the complete key.`
627
- );
628
- }
629
- const hexPortion = key.slice(8);
630
- if (!/^[0-9a-fA-F]+$/.test(hexPortion)) {
631
- throw new InvalidSessionKeyError(
632
- "Invalid session key format. The key should contain only hexadecimal characters after the prefix."
633
- );
634
- }
635
- if (config.maxPaymentUsd !== void 0) {
636
- if (config.maxPaymentUsd <= 0) {
637
- throw new MixrPayError("maxPaymentUsd must be a positive number");
638
- }
639
- if (config.maxPaymentUsd > 1e4) {
640
- this.logger?.warn("maxPaymentUsd is very high ($" + config.maxPaymentUsd + "). Consider using a lower limit for safety.");
641
- }
642
- }
643
- }
644
- // ===========================================================================
645
- // Merchant Allowlist Validation
646
- // ===========================================================================
647
- /**
648
- * Fetch the merchant allowlist from the server.
649
- * Caches the result for 5 minutes to avoid excessive API calls.
650
- */
651
- async fetchAllowlist() {
652
- const CACHE_TTL_MS = 5 * 60 * 1e3;
653
- if (this.allowlist !== void 0 && this.allowlistFetchedAt) {
654
- const age = Date.now() - this.allowlistFetchedAt;
655
- if (age < CACHE_TTL_MS) {
656
- return this.allowlist;
657
- }
658
- }
659
- try {
660
- const info = await this.getSessionKeyInfo();
661
- this.allowlist = info.allowedMerchants || [];
662
- this.allowlistFetchedAt = Date.now();
663
- this.logger.debug("Fetched allowlist", {
664
- patterns: this.allowlist.length,
665
- allowAll: this.allowlist.length === 0
666
- });
667
- return this.allowlist;
668
- } catch (error) {
669
- this.logger.warn("Failed to fetch allowlist, allowing all merchants", { error });
670
- this.allowlist = [];
671
- this.allowlistFetchedAt = Date.now();
672
- return this.allowlist;
673
- }
674
- }
675
- /**
676
- * Validate that a target is allowed by the session's allowlist.
677
- *
678
- * @param target - URL, domain, or tool name to check
679
- * @param type - Type of target: 'url' for HTTP requests, 'tool' for MCP tools
680
- * @throws {MerchantNotAllowedError} If target is not in allowlist
681
- */
682
- async validateMerchantAllowed(target, type) {
683
- const allowlist = await this.fetchAllowlist();
684
- if (allowlist.length === 0) {
685
- return;
686
- }
687
- const isAllowed = this.matchesAllowlist(target, allowlist, type);
688
- if (!isAllowed) {
689
- throw new MerchantNotAllowedError(target, allowlist);
690
- }
691
- }
692
- /**
693
- * Check if a target matches any pattern in the allowlist.
694
- */
695
- matchesAllowlist(target, allowlist, type) {
696
- for (const pattern of allowlist) {
697
- if (this.matchPattern(target, pattern, type)) {
698
- return true;
699
- }
700
- }
701
- return false;
702
- }
703
- /**
704
- * Check if a target matches a single pattern.
705
- */
706
- matchPattern(target, pattern, type) {
707
- if (type === "url") {
708
- return this.matchUrlPattern(target, pattern);
709
- } else {
710
- return this.matchToolPattern(target, pattern);
711
- }
712
- }
713
- /**
714
- * Match a URL or domain against a pattern.
715
- */
716
- matchUrlPattern(target, pattern) {
717
- let hostname;
718
- try {
719
- if (target.includes("://")) {
720
- const url = new URL(target);
721
- hostname = url.hostname.toLowerCase();
722
- } else {
723
- hostname = target.toLowerCase();
724
- }
725
- } catch {
726
- return false;
727
- }
728
- const normalizedPattern = pattern.toLowerCase().trim();
729
- let patternDomain = normalizedPattern;
730
- if (patternDomain.includes("://")) {
731
- try {
732
- patternDomain = new URL(patternDomain).hostname;
733
- } catch {
734
- }
735
- }
736
- if (hostname === patternDomain) {
737
- return true;
738
- }
739
- if (patternDomain.startsWith("*.")) {
740
- const baseDomain = patternDomain.substring(2);
741
- if (hostname.endsWith(`.${baseDomain}`) && hostname !== baseDomain) {
742
- return true;
743
- }
744
- }
745
- return false;
746
- }
747
- /**
748
- * Match an MCP tool name against a pattern.
749
- */
750
- matchToolPattern(toolName, pattern) {
751
- const normalizedTool = toolName.toLowerCase().trim();
752
- const normalizedPattern = pattern.toLowerCase().trim();
753
- if (normalizedTool === normalizedPattern) {
754
- return true;
755
- }
756
- if (normalizedPattern.endsWith("/*")) {
757
- const baseProvider = normalizedPattern.substring(0, normalizedPattern.length - 2);
758
- if (normalizedTool.startsWith(`${baseProvider}/`)) {
759
- return true;
760
- }
761
- }
762
- return false;
763
- }
764
- // ===========================================================================
765
- // Static Agent Registration Methods
766
- // ===========================================================================
767
- /**
768
- * Register a new agent with MixrPay.
769
- *
770
- * This creates a Privy-managed embedded wallet for the agent's payments.
771
- * The agent proves ownership of their external wallet by signing a challenge.
772
- *
773
- * @param options - Registration options including the private key
774
- * @returns Registration result with deposit address
775
- * @throws {MixrPayError} If registration fails
776
- *
777
- * @example
778
- * ```typescript
779
- * const { depositAddress, userId } = await AgentWallet.register({
780
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
781
- * name: 'My Trading Agent',
782
- * });
783
- *
784
- * console.log(`Fund your agent at: ${depositAddress}`);
785
- * ```
786
- */
787
- static async register(options) {
788
- const { privateKey, name } = options;
789
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
790
- const account = privateKeyToAccount2(privateKey);
791
- const walletAddress = account.address;
792
- const challengeResponse = await fetch(
793
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=register`
794
- );
795
- if (!challengeResponse.ok) {
796
- const error = await challengeResponse.json().catch(() => ({}));
797
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
798
- }
799
- const { challenge, message } = await challengeResponse.json();
800
- const signature = await signMessage({ message, privateKey });
801
- const registerResponse = await fetch(`${baseUrl}/api/v1/agent/register`, {
802
- method: "POST",
803
- headers: { "Content-Type": "application/json" },
804
- body: JSON.stringify({
805
- challenge,
806
- external_wallet: walletAddress,
807
- signature,
808
- name
809
- })
810
- });
811
- if (!registerResponse.ok) {
812
- const error = await registerResponse.json().catch(() => ({}));
813
- const errorMessage = error.error || `Registration failed with status ${registerResponse.status}`;
814
- const requestId = error.request_id;
815
- const errorCode = error.code;
816
- let helpText = "";
817
- if (registerResponse.status === 503) {
818
- helpText = " The service may be temporarily unavailable. Please try again later.";
819
- } else if (registerResponse.status === 500) {
820
- helpText = " This is a server error. Please contact support with the request ID.";
821
- } else if (errorCode === "MISSING_CHALLENGE" || errorCode === "MISSING_SIGNATURE") {
822
- helpText = " This may indicate an SDK bug. Please update to the latest version.";
823
- }
824
- const fullMessage = requestId ? `${errorMessage} (request_id: ${requestId})${helpText}` : `${errorMessage}${helpText}`;
825
- throw new MixrPayError(fullMessage);
826
- }
827
- const data = await registerResponse.json();
828
- return {
829
- userId: data.user_id,
830
- depositAddress: data.deposit_address
831
- };
832
- }
833
- /**
834
- * Check if the MixrPay server is properly configured for agent registration.
835
- *
836
- * Use this to diagnose registration issues before attempting to register.
837
- *
838
- * @param baseUrl - MixrPay API base URL (default: https://www.mixrpay.com)
839
- * @returns Server health status including agent registration availability
840
- *
841
- * @example
842
- * ```typescript
843
- * const status = await AgentWallet.checkServerHealth();
844
- * if (!status.agentRegistrationAvailable) {
845
- * console.error('Agent registration is not available:', status);
846
- * }
847
- * ```
848
- */
849
- static async checkServerHealth(baseUrl) {
850
- const url = (baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
851
- try {
852
- const response = await fetch(`${url}/api/health/ready?details=true`);
853
- if (!response.ok) {
854
- return {
855
- healthy: false,
856
- database: "unknown",
857
- agentRegistrationAvailable: false,
858
- privyConfigured: false,
859
- error: `Health check failed with status ${response.status}`
860
- };
861
- }
862
- const data = await response.json();
863
- return {
864
- healthy: data.status === "ready",
865
- database: data.database || "unknown",
866
- agentRegistrationAvailable: data.services?.agentRegistration?.available ?? false,
867
- privyConfigured: data.services?.privy?.configured ?? false
868
- };
869
- } catch (error) {
870
- return {
871
- healthy: false,
872
- database: "unreachable",
873
- agentRegistrationAvailable: false,
874
- privyConfigured: false,
875
- error: error instanceof Error ? error.message : "Failed to reach server"
876
- };
877
- }
878
- }
879
- /**
880
- * Get a session key for an already-registered agent.
881
- *
882
- * Session keys allow the agent to make payments within the specified limits.
883
- * The private key is returned ONCE - store it securely!
884
- *
885
- * @param options - Session key options
886
- * @returns Session key result with the sk_live_ format key
887
- * @throws {MixrPayError} If session key creation fails
888
- *
889
- * @example
890
- * ```typescript
891
- * const result = await AgentWallet.getSessionKey({
892
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
893
- * spendingLimitUsd: 100,
894
- * durationDays: 30,
895
- * });
896
- *
897
- * // Store this securely - it's your payment key!
898
- * console.log(`Session key: ${result.sessionKey}`);
899
- *
900
- * // Use it to create an AgentWallet
901
- * const wallet = new AgentWallet({ sessionKey: result.sessionKey });
902
- * ```
903
- */
904
- static async getSessionKey(options) {
905
- const { privateKey, spendingLimitUsd, maxPerTxUsd, maxDailyUsd, durationDays } = options;
906
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
907
- const account = privateKeyToAccount2(privateKey);
908
- const walletAddress = account.address;
909
- const challengeResponse = await fetch(
910
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=session-key`
911
- );
912
- if (!challengeResponse.ok) {
913
- const error = await challengeResponse.json().catch(() => ({}));
914
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
915
- }
916
- const { challenge, message } = await challengeResponse.json();
917
- const signature = await signMessage({ message, privateKey });
918
- const sessionKeyResponse = await fetch(`${baseUrl}/api/v1/agent/session-key`, {
919
- method: "POST",
920
- headers: { "Content-Type": "application/json" },
921
- body: JSON.stringify({
922
- challenge,
923
- external_wallet: walletAddress,
924
- signature,
925
- spending_limit_usd: spendingLimitUsd,
926
- max_per_tx_usd: maxPerTxUsd,
927
- max_daily_usd: maxDailyUsd,
928
- duration_days: durationDays
929
- })
930
- });
931
- if (!sessionKeyResponse.ok) {
932
- const error = await sessionKeyResponse.json().catch(() => ({}));
933
- throw new MixrPayError(error.error || `Session key creation failed: ${sessionKeyResponse.status}`);
934
- }
935
- const data = await sessionKeyResponse.json();
936
- return {
937
- sessionKey: data.session_key,
938
- address: data.address,
939
- sessionKeyId: data.session_key_id,
940
- expiresAt: new Date(data.expires_at),
941
- limits: {
942
- maxTotalUsd: data.limits.max_total_usd,
943
- maxPerTxUsd: data.limits.max_per_tx_usd,
944
- maxDailyUsd: data.limits.max_daily_usd
945
- }
946
- };
947
- }
948
- /**
949
- * Get the status of a registered agent.
950
- *
951
- * Returns balance, active sessions, and spending information.
952
- *
953
- * @param options - Status options
954
- * @returns Agent status
955
- * @throws {MixrPayError} If status fetch fails
956
- *
957
- * @example
958
- * ```typescript
959
- * const status = await AgentWallet.getStatus({
960
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
961
- * });
962
- *
963
- * console.log(`Balance: $${status.balanceUsd}`);
964
- * console.log(`Active sessions: ${status.activeSessions.length}`);
965
- * ```
966
- */
967
- static async getStatus(options) {
968
- const { privateKey } = options;
969
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
970
- const account = privateKeyToAccount2(privateKey);
971
- const walletAddress = account.address;
972
- const challengeResponse = await fetch(
973
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=status`
974
- );
975
- if (!challengeResponse.ok) {
976
- const error = await challengeResponse.json().catch(() => ({}));
977
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
978
- }
979
- const { challenge, message } = await challengeResponse.json();
980
- const signature = await signMessage({ message, privateKey });
981
- const statusResponse = await fetch(
982
- `${baseUrl}/api/v1/agent/status?challenge=${challenge}&external_wallet=${walletAddress}&signature=${encodeURIComponent(signature)}`
983
- );
984
- if (!statusResponse.ok) {
985
- const error = await statusResponse.json().catch(() => ({}));
986
- throw new MixrPayError(error.error || `Failed to get status: ${statusResponse.status}`);
987
- }
988
- const data = await statusResponse.json();
989
- return {
990
- depositAddress: data.deposit_address,
991
- balanceUsd: data.balance_usd,
992
- activeSessions: data.active_sessions.map((s) => ({
993
- id: s.id,
994
- expiresAt: new Date(s.expires_at),
995
- totalSpentUsd: s.total_spent_usd,
996
- remainingUsd: s.remaining_usd,
997
- maxTotalUsd: s.max_total_usd
998
- })),
999
- totalSpentUsd: data.total_spent_usd
1000
- };
1001
- }
1002
- /**
1003
- * Revoke a session key.
1004
- *
1005
- * After revocation, the session key can no longer be used for payments.
1006
- *
1007
- * @param options - Revoke options
1008
- * @returns true if revoked successfully
1009
- * @throws {MixrPayError} If revocation fails
1010
- *
1011
- * @example
1012
- * ```typescript
1013
- * const success = await AgentWallet.revokeSessionKey({
1014
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
1015
- * sessionKeyId: 'session-key-uuid',
1016
- * });
1017
- *
1018
- * if (success) {
1019
- * console.log('Session key revoked');
1020
- * }
1021
- * ```
1022
- */
1023
- static async revokeSessionKey(options) {
1024
- const { privateKey, sessionKeyId } = options;
1025
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
1026
- const account = privateKeyToAccount2(privateKey);
1027
- const walletAddress = account.address;
1028
- const challengeResponse = await fetch(
1029
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=revoke`
1030
- );
1031
- if (!challengeResponse.ok) {
1032
- const error = await challengeResponse.json().catch(() => ({}));
1033
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
1034
- }
1035
- const { challenge, message } = await challengeResponse.json();
1036
- const signature = await signMessage({ message, privateKey });
1037
- const revokeResponse = await fetch(`${baseUrl}/api/v1/agent/session-key/revoke`, {
1038
- method: "POST",
1039
- headers: { "Content-Type": "application/json" },
1040
- body: JSON.stringify({
1041
- challenge,
1042
- external_wallet: walletAddress,
1043
- signature,
1044
- session_key_id: sessionKeyId
1045
- })
1046
- });
1047
- if (!revokeResponse.ok) {
1048
- const error = await revokeResponse.json().catch(() => ({}));
1049
- throw new MixrPayError(error.error || `Revocation failed: ${revokeResponse.status}`);
1050
- }
1051
- return true;
1052
- }
1053
- /**
1054
- * Withdraw USDC from agent's MixrPay wallet to their external wallet.
1055
- *
1056
- * SECURITY: Withdrawals can ONLY go to the agent's own registration wallet
1057
- * (the wallet used during `register()`). This prevents prompt injection
1058
- * attacks where a compromised agent might be tricked into withdrawing
1059
- * to an attacker's address.
1060
- *
1061
- * @param options - Withdrawal options
1062
- * @returns Withdrawal result with transaction hash
1063
- * @throws {MixrPayError} If withdrawal fails
1064
- *
1065
- * @example
1066
- * ```typescript
1067
- * const result = await AgentWallet.withdraw({
1068
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
1069
- * amountUsd: 50.00,
1070
- * });
1071
- *
1072
- * console.log(`Withdrew $${result.amountUsd}`);
1073
- * console.log(`Transaction: ${result.txHash}`);
1074
- * console.log(`Remaining balance: $${result.remainingBalanceUsd}`);
1075
- * ```
1076
- */
1077
- static async withdraw(options) {
1078
- const { privateKey, amountUsd } = options;
1079
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
1080
- const account = privateKeyToAccount2(privateKey);
1081
- const walletAddress = account.address;
1082
- const challengeResponse = await fetch(
1083
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=withdraw`
1084
- );
1085
- if (!challengeResponse.ok) {
1086
- const error = await challengeResponse.json().catch(() => ({}));
1087
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
1088
- }
1089
- const { challenge, message } = await challengeResponse.json();
1090
- const signature = await signMessage({ message, privateKey });
1091
- const withdrawResponse = await fetch(`${baseUrl}/api/v1/agent/withdraw`, {
1092
- method: "POST",
1093
- headers: { "Content-Type": "application/json" },
1094
- body: JSON.stringify({
1095
- challenge,
1096
- external_wallet: walletAddress,
1097
- signature,
1098
- to_address: walletAddress,
1099
- // Always withdraw to self
1100
- amount_usd: amountUsd
1101
- })
1102
- });
1103
- if (!withdrawResponse.ok) {
1104
- const error = await withdrawResponse.json().catch(() => ({}));
1105
- throw new MixrPayError(error.error || `Withdrawal failed: ${withdrawResponse.status}`);
1106
- }
1107
- const data = await withdrawResponse.json();
1108
- return {
1109
- txHash: data.tx_hash,
1110
- amountUsd: data.amount_usd,
1111
- remainingBalanceUsd: data.remaining_balance_usd
1112
- };
1113
- }
1114
- /**
1115
- * Claim an agent invite code to receive a session key for the inviter's wallet.
1116
- *
1117
- * This allows an agent to get a pre-configured session key from a human wallet owner
1118
- * without needing to register their own wallet or fund it. The human sets the budget
1119
- * limits and merchant whitelist when creating the invite.
1120
- *
1121
- * @param options - Claim invite options including the invite code and agent's private key
1122
- * @returns Claim result with the new session key
1123
- * @throws {MixrPayError} If claiming fails (e.g., invalid code, already claimed, expired)
1124
- *
1125
- * @example
1126
- * ```typescript
1127
- * // Human creates invite at https://mixrpay.com/manage/invites, shares code "mixr-abc123"
1128
- *
1129
- * const result = await AgentWallet.claimInvite({
1130
- * inviteCode: 'mixr-abc123',
1131
- * privateKey: process.env.AGENT_WALLET_KEY as `0x${string}`,
1132
- * });
1133
- *
1134
- * console.log(`Got session key: ${result.sessionKey}`);
1135
- * console.log(`Budget: $${result.limits.budgetUsd}/${result.limits.budgetPeriod}`);
1136
- * console.log(`Invited by: ${result.inviterName}`);
1137
- *
1138
- * // Use the session key to make payments
1139
- * const wallet = new AgentWallet({ sessionKey: result.sessionKey });
1140
- * const response = await wallet.fetch('https://api.example.com/endpoint');
1141
- * ```
1142
- */
1143
- static async claimInvite(options) {
1144
- const { inviteCode, privateKey } = options;
1145
- const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
1146
- const account = privateKeyToAccount2(privateKey);
1147
- const walletAddress = account.address;
1148
- const challengeResponse = await fetch(
1149
- `${baseUrl}/api/v1/agent/challenge?wallet=${walletAddress}&action=claim-invite`
1150
- );
1151
- if (!challengeResponse.ok) {
1152
- const error = await challengeResponse.json().catch(() => ({}));
1153
- throw new MixrPayError(error.error || `Failed to get challenge: ${challengeResponse.status}`);
1154
- }
1155
- const { challenge, message } = await challengeResponse.json();
1156
- const signature = await signMessage({ message, privateKey });
1157
- const claimResponse = await fetch(`${baseUrl}/api/v1/agent/claim-invite`, {
1158
- method: "POST",
1159
- headers: { "Content-Type": "application/json" },
1160
- body: JSON.stringify({
1161
- invite_code: inviteCode,
1162
- challenge,
1163
- agent_wallet_address: walletAddress,
1164
- signature
1165
- })
1166
- });
1167
- if (!claimResponse.ok) {
1168
- const error = await claimResponse.json().catch(() => ({}));
1169
- const errorMessage = error.error || `Failed to claim invite: ${claimResponse.status}`;
1170
- let helpText = "";
1171
- if (claimResponse.status === 404) {
1172
- helpText = " The invite code may be invalid or misspelled.";
1173
- } else if (claimResponse.status === 400) {
1174
- if (errorMessage.includes("already claimed")) {
1175
- helpText = " This invite has already been used by another agent.";
1176
- } else if (errorMessage.includes("expired")) {
1177
- helpText = " Ask the wallet owner to create a new invite.";
1178
- } else if (errorMessage.includes("revoked")) {
1179
- helpText = " The wallet owner has revoked this invite.";
1180
- }
1181
- }
1182
- throw new MixrPayError(`${errorMessage}${helpText}`);
1183
- }
1184
- const data = await claimResponse.json();
1185
- return {
1186
- sessionKey: data.session_key,
1187
- address: data.address,
1188
- sessionKeyId: data.session_key_id,
1189
- expiresAt: new Date(data.expires_at),
1190
- limits: {
1191
- budgetUsd: data.limits.budget_usd,
1192
- budgetPeriod: data.limits.budget_period,
1193
- maxPerTxUsd: data.limits.max_per_tx_usd
1194
- },
1195
- allowedMerchants: data.allowed_merchants || [],
1196
- inviterName: data.inviter_name || "Anonymous"
1197
- };
1198
- }
1199
- // ===========================================================================
1200
- // Nested Budget Delegation Methods
1201
- // ===========================================================================
1202
- /**
1203
- * Spawn a child invite for sub-agents.
1204
- *
1205
- * Allows an agent to create an invite code for a sub-agent with a portion
1206
- * of their remaining budget (max 20%). The child inherits merchant restrictions
1207
- * and cannot outlive the parent session.
1208
- *
1209
- * @param options - Spawn options
1210
- * @returns The created child invite details
1211
- *
1212
- * @throws {MixrPayError} If spawning fails (insufficient budget, depth limit, etc.)
1213
- *
1214
- * @example
1215
- * ```typescript
1216
- * const wallet = new AgentWallet({ sessionKey: 'sk_live_...' });
1217
- *
1218
- * // Spawn a child invite for a sub-agent
1219
- * const childInvite = await wallet.spawnChildInvite({
1220
- * budgetUsd: 10.00, // Max 20% of available budget
1221
- * name: 'Research Sub-Agent',
1222
- * allowedMerchants: ['firecrawl.dev'], // Must be subset of parent
1223
- * expiresInDays: 7, // Will be capped to parent's expiry
1224
- * });
1225
- *
1226
- * console.log(`Share with sub-agent: ${childInvite.inviteCode}`);
1227
- * console.log(`Child can spawn up to: $${childInvite.maxSpawnBudget}`);
1228
- * ```
1229
- */
1230
- async spawnChildInvite(options) {
1231
- const { budgetUsd, name, allowedMerchants, expiresInDays } = options;
1232
- const timestamp = Date.now();
1233
- const nonce = crypto.randomUUID();
1234
- const message = `spawn:${timestamp}:${nonce}`;
1235
- const signature = await signMessage({
1236
- message,
1237
- privateKey: this.sessionKey.rawPrivateKey
1238
- });
1239
- const response = await fetch(`${this.baseUrl}/api/v1/agent/spawn`, {
1240
- method: "POST",
1241
- headers: { "Content-Type": "application/json" },
1242
- body: JSON.stringify({
1243
- session_key: this.sessionKey.toString(),
1244
- signature,
1245
- message,
1246
- budget_usd: budgetUsd,
1247
- name,
1248
- allowed_merchants: allowedMerchants,
1249
- expires_in_days: expiresInDays
1250
- })
1251
- });
1252
- if (!response.ok) {
1253
- const error = await response.json().catch(() => ({}));
1254
- if (response.status === 409) {
1255
- throw new MixrPayError("Concurrent modification - please retry");
1256
- }
1257
- if (response.status === 429) {
1258
- throw new MixrPayError("Rate limited - too many spawn attempts");
1259
- }
1260
- throw new MixrPayError(error.error || `Failed to spawn child: ${response.status}`);
1261
- }
1262
- const data = await response.json();
1263
- return {
1264
- inviteCode: data.invite_code,
1265
- inviteId: data.invite_id,
1266
- budgetUsd: data.budget_usd,
1267
- expiresAt: new Date(data.expires_at),
1268
- depth: data.depth,
1269
- maxSpawnBudget: data.max_spawn_budget,
1270
- allowedMerchants: data.allowed_merchants || []
1271
- };
1272
- }
1273
- /**
1274
- * Get available budget information for spawning.
1275
- *
1276
- * Returns the current budget status including how much can be spawned
1277
- * to child agents (20% of available).
1278
- *
1279
- * @returns Budget information
1280
- *
1281
- * @example
1282
- * ```typescript
1283
- * const budget = await wallet.getAvailableBudget();
1284
- *
1285
- * console.log(`Total budget: $${budget.totalBudget}`);
1286
- * console.log(`Spent: $${budget.spent}`);
1287
- * console.log(`Allocated to children: $${budget.allocatedToChildren}`);
1288
- * console.log(`Available: $${budget.available}`);
1289
- * console.log(`Max spawn budget: $${budget.maxSpawnBudget}`);
1290
- *
1291
- * if (budget.canSpawn && budget.maxSpawnBudget >= 5.00) {
1292
- * // Safe to spawn a $5 child
1293
- * }
1294
- * ```
1295
- */
1296
- async getAvailableBudget() {
1297
- const response = await fetch(`${this.baseUrl}/api/v1/agent/descendants`, {
1298
- method: "GET",
1299
- headers: {
1300
- "Authorization": `Bearer ${this.sessionKey.toString()}`
1301
- }
1302
- });
1303
- if (!response.ok) {
1304
- const error = await response.json().catch(() => ({}));
1305
- throw new MixrPayError(error.error || `Failed to get budget: ${response.status}`);
1306
- }
1307
- const data = await response.json();
1308
- return {
1309
- totalBudget: data.budget.total_usd,
1310
- spent: data.budget.spent_usd,
1311
- allocatedToChildren: data.budget.allocated_to_children_usd,
1312
- available: data.budget.available_usd,
1313
- maxSpawnBudget: data.max_spawn_budget,
1314
- canSpawn: data.can_spawn
1315
- };
1316
- }
1317
- /**
1318
- * Get all child sessions spawned by this session.
1319
- *
1320
- * Returns a tree of child invites/sessions including their spending status.
1321
- *
1322
- * @returns Array of child sessions
1323
- *
1324
- * @example
1325
- * ```typescript
1326
- * const children = await wallet.getChildSessions();
1327
- *
1328
- * for (const child of children) {
1329
- * console.log(`${child.name}: $${child.spentUsd}/$${child.budgetUsd}`);
1330
- * console.log(` Status: ${child.status}`);
1331
- * console.log(` Depth: ${child.depth}`);
1332
- *
1333
- * if (child.children) {
1334
- * console.log(` Has ${child.children.length} grandchildren`);
1335
- * }
1336
- * }
1337
- * ```
1338
- */
1339
- async getChildSessions() {
1340
- const response = await fetch(`${this.baseUrl}/api/v1/agent/descendants`, {
1341
- method: "GET",
1342
- headers: {
1343
- "Authorization": `Bearer ${this.sessionKey.toString()}`
1344
- }
1345
- });
1346
- if (!response.ok) {
1347
- const error = await response.json().catch(() => ({}));
1348
- throw new MixrPayError(error.error || `Failed to get children: ${response.status}`);
1349
- }
1350
- const data = await response.json();
1351
- return data.children || [];
1352
- }
1353
- /**
1354
- * List child sessions spawned by this agent.
1355
- *
1356
- * Alias for `getChildSessions()` for naming consistency.
1357
- *
1358
- * @returns Array of child session info
1359
- */
1360
- async listChildSessions() {
1361
- return this.getChildSessions();
1362
- }
1363
- // ===========================================================================
1364
- // Core Methods
1365
- // ===========================================================================
1366
- /**
1367
- * Make an HTTP request, automatically handling x402 payment if required.
1368
- *
1369
- * This is a drop-in replacement for the native `fetch()` function.
1370
- * If the server returns 402 Payment Required:
1371
- * 1. Parse payment requirements from response
1372
- * 2. Sign transferWithAuthorization using session key
1373
- * 3. Retry request with X-PAYMENT header
1374
- *
1375
- * @param url - Request URL
1376
- * @param init - Request options (same as native fetch)
1377
- * @returns Response from the server
1378
- *
1379
- * @throws {InsufficientBalanceError} If wallet doesn't have enough USDC
1380
- * @throws {SessionKeyExpiredError} If session key has expired
1381
- * @throws {SpendingLimitExceededError} If payment would exceed limits
1382
- * @throws {PaymentFailedError} If payment transaction failed
1383
- *
1384
- * @example GET request
1385
- * ```typescript
1386
- * const response = await wallet.fetch('https://api.example.com/data');
1387
- * const data = await response.json();
1388
- * ```
1389
- *
1390
- * @example POST request with JSON
1391
- * ```typescript
1392
- * const response = await wallet.fetch('https://api.example.com/generate', {
1393
- * method: 'POST',
1394
- * headers: { 'Content-Type': 'application/json' },
1395
- * body: JSON.stringify({ prompt: 'Hello world' })
1396
- * });
1397
- * ```
1398
- */
1399
- async fetch(url, init) {
1400
- this.logger.debug(`Fetching ${init?.method || "GET"} ${url}`);
1401
- await this.validateMerchantAllowed(url, "url");
1402
- const requestId = crypto.randomUUID();
1403
- const correlationId = this.extractCorrelationId(init?.headers);
1404
- const controller = new AbortController();
1405
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1406
- try {
1407
- let response = await fetch(url, {
1408
- ...init,
1409
- signal: controller.signal
1410
- });
1411
- this.logger.debug(`Initial response: ${response.status}`);
1412
- if (response.status === 402) {
1413
- this.logger.info(`Payment required for ${url}`);
1414
- response = await this.handlePaymentRequired(url, init, response, requestId, correlationId);
1415
- }
1416
- return response;
1417
- } catch (error) {
1418
- if (error instanceof Error && error.name === "AbortError") {
1419
- throw new MixrPayError(`Request timeout after ${this.timeout}ms`);
1420
- }
1421
- throw error;
1422
- } finally {
1423
- clearTimeout(timeoutId);
1424
- }
1425
- }
1426
- /**
1427
- * Extract correlation ID from request headers.
1428
- */
1429
- extractCorrelationId(headers) {
1430
- if (!headers) return void 0;
1431
- if (headers instanceof Headers) {
1432
- return headers.get("X-Correlation-Id") || headers.get("x-correlation-id") || void 0;
1433
- }
1434
- if (Array.isArray(headers)) {
1435
- const entry = headers.find(
1436
- ([key]) => key.toLowerCase() === "x-correlation-id"
1437
- );
1438
- return entry ? entry[1] : void 0;
1439
- }
1440
- const record = headers;
1441
- return record["X-Correlation-Id"] || record["x-correlation-id"] || void 0;
1442
- }
1443
- /**
1444
- * Handle a 402 Payment Required response.
1445
- */
1446
- async handlePaymentRequired(url, init, response, requestId, correlationId) {
1447
- let requirements;
1448
- try {
1449
- requirements = await parse402Response(response);
1450
- this.logger.debug("Payment requirements:", {
1451
- amount: `$${getAmountUsd(requirements).toFixed(4)}`,
1452
- recipient: requirements.recipient,
1453
- description: requirements.description
1454
- });
1455
- } catch (e) {
1456
- this.logger.error("Failed to parse payment requirements:", e);
1457
- throw new PaymentFailedError(
1458
- `Failed to parse payment requirements: ${e}. The server may not be properly configured for x402 payments.`
1459
- );
1460
- }
1461
- if (isPaymentExpired(requirements)) {
1462
- throw new PaymentFailedError(
1463
- "Payment requirements have expired. This usually means the request took too long. Try again."
1464
- );
1465
- }
1466
- const amountUsd = getAmountUsd(requirements);
1467
- if (this.maxPaymentUsd !== void 0 && amountUsd > this.maxPaymentUsd) {
1468
- throw new SpendingLimitExceededError(
1469
- "client_max",
1470
- this.maxPaymentUsd,
1471
- amountUsd
1472
- );
1473
- }
1474
- let xPayment;
1475
- try {
1476
- this.logger.debug("Signing payment authorization...");
1477
- xPayment = await buildXPaymentHeader(
1478
- requirements,
1479
- this.sessionKey,
1480
- this.walletAddress
1481
- );
1482
- } catch (e) {
1483
- this.logger.error("Failed to sign payment:", e);
1484
- throw new PaymentFailedError(
1485
- `Failed to sign payment: ${e}. This may indicate an issue with the session key.`
1486
- );
1487
- }
1488
- this.logger.debug("Retrying request with payment...");
1489
- const headers = new Headers(init?.headers);
1490
- headers.set("X-PAYMENT", xPayment);
1491
- const retryResponse = await fetch(url, {
1492
- ...init,
1493
- headers
1494
- });
1495
- if (retryResponse.status !== 402) {
1496
- const payment = {
1497
- amountUsd,
1498
- recipient: requirements.recipient,
1499
- txHash: retryResponse.headers.get("X-Payment-TxHash"),
1500
- timestamp: /* @__PURE__ */ new Date(),
1501
- description: requirements.description,
1502
- url,
1503
- requestId,
1504
- correlationId
1505
- };
1506
- this.payments.push(payment);
1507
- this.totalSpentUsd += amountUsd;
1508
- this.logger.payment(amountUsd, requirements.recipient, requirements.description);
1509
- if (this.onPayment) {
1510
- this.onPayment(payment);
1511
- }
1512
- } else {
1513
- await this.handlePaymentError(retryResponse);
1514
- }
1515
- return retryResponse;
1516
- }
1517
- /**
1518
- * Handle payment-specific errors from the response.
1519
- */
1520
- async handlePaymentError(response) {
1521
- let errorData = {};
1522
- try {
1523
- errorData = await response.json();
1524
- } catch {
1525
- }
1526
- const errorCode = errorData.error_code || "";
1527
- const errorMessage = errorData.error || errorData.message || "Payment required";
1528
- this.logger.error("Payment failed:", { errorCode, errorMessage, errorData });
1529
- if (errorCode === "insufficient_balance") {
1530
- const required = errorData.required || 0;
1531
- const available = errorData.available || 0;
1532
- throw new InsufficientBalanceError(required, available);
1533
- } else if (errorCode === "session_key_expired") {
1534
- throw new SessionKeyExpiredError(errorData.expired_at || "unknown");
1535
- } else if (errorCode === "spending_limit_exceeded") {
1536
- throw new SpendingLimitExceededError(
1537
- errorData.limit_type || "unknown",
1538
- errorData.limit || 0,
1539
- errorData.attempted || 0
1540
- );
1541
- } else {
1542
- throw new PaymentFailedError(errorMessage);
1543
- }
1544
- }
1545
- // ===========================================================================
1546
- // Wallet Information
1547
- // ===========================================================================
1548
- /**
1549
- * Get the wallet address.
1550
- *
1551
- * @returns The Ethereum address of the smart wallet
1552
- */
1553
- getWalletAddress() {
1554
- return this.walletAddress;
1555
- }
1556
- /**
1557
- * Check if using testnet session key.
1558
- *
1559
- * @returns true if using Base Sepolia (testnet), false if using Base Mainnet
1560
- */
1561
- isTestnet() {
1562
- return this.sessionKey.isTest;
1563
- }
1564
- /**
1565
- * Get the network information.
1566
- *
1567
- * @returns Network details including chain ID and name
1568
- */
1569
- getNetwork() {
1570
- return this.isTestnet() ? NETWORKS.BASE_SEPOLIA : NETWORKS.BASE_MAINNET;
1571
- }
1572
- /**
1573
- * Get current USDC balance of the wallet.
1574
- *
1575
- * @returns USDC balance in USD
1576
- *
1577
- * @example
1578
- * ```typescript
1579
- * const balance = await wallet.getBalance();
1580
- * console.log(`Balance: $${balance.toFixed(2)}`);
1581
- * ```
1582
- */
1583
- async getBalance() {
1584
- this.logger.debug("Fetching wallet balance...");
1585
- try {
1586
- const infoResponse = await fetch(`${this.baseUrl}/api/v1/session-key/info`, {
1587
- headers: {
1588
- "X-Session-Key": this.sessionKey.address.toLowerCase()
1589
- }
1590
- });
1591
- if (!infoResponse.ok) {
1592
- throw new Error("Failed to get session key info");
1593
- }
1594
- const info = await infoResponse.json();
1595
- const walletAddress = info.wallet_address || info.walletAddress;
1596
- if (!walletAddress) {
1597
- throw new Error("No wallet address in session key info");
1598
- }
1599
- const response = await fetch(
1600
- `${this.baseUrl}/api/wallet/balance?address=${walletAddress}&chain=base`
1601
- );
1602
- if (response.ok) {
1603
- const data = await response.json();
1604
- const balance = data.balance_usdc || data.balance_usd || 0;
1605
- this.logger.debug(`Balance: $${balance}`);
1606
- return balance;
1607
- }
1608
- } catch (error) {
1609
- this.logger.warn("Failed to fetch balance:", error);
1610
- }
1611
- this.logger.debug("Using estimated balance based on tracking");
1612
- return Math.max(0, 100 - this.totalSpentUsd);
1613
- }
1614
- /**
1615
- * Check if the wallet can afford a specific amount.
1616
- *
1617
- * This is a convenience method to check balance before making a request
1618
- * when you know the expected cost.
1619
- *
1620
- * @param amountUsd - Amount to check in USD
1621
- * @returns Object with affordability information
1622
- *
1623
- * @example
1624
- * ```typescript
1625
- * const check = await wallet.canAfford(5.00);
1626
- * if (check.canAfford) {
1627
- * console.log(`Can afford! Will have $${check.remainingAfter.toFixed(2)} left`);
1628
- * await wallet.fetch(url);
1629
- * } else {
1630
- * console.log(`Need $${check.shortfall.toFixed(2)} more`);
1631
- * }
1632
- * ```
1633
- */
1634
- async canAfford(amountUsd) {
1635
- const balance = await this.getBalance();
1636
- const canAfford = balance >= amountUsd;
1637
- return {
1638
- canAfford,
1639
- balance,
1640
- shortfall: canAfford ? 0 : amountUsd - balance,
1641
- remainingAfter: canAfford ? balance - amountUsd : 0
1642
- };
1643
- }
1644
- /**
1645
- * Get information about the session key.
1646
- *
1647
- * @param refresh - Force refresh from server (default: use cache if < 60s old)
1648
- * @returns Session key details including limits and expiration
1649
- *
1650
- * @example
1651
- * ```typescript
1652
- * const info = await wallet.getSessionKeyInfo();
1653
- * console.log(`Daily limit: $${info.limits.dailyUsd}`);
1654
- * console.log(`Expires: ${info.expiresAt}`);
1655
- * ```
1656
- */
1657
- async getSessionKeyInfo(refresh = false) {
1658
- const cacheAge = this.sessionKeyInfoFetchedAt ? Date.now() - this.sessionKeyInfoFetchedAt : Infinity;
1659
- if (!refresh && this.sessionKeyInfo && cacheAge < 6e4) {
1660
- return this.sessionKeyInfo;
1661
- }
1662
- this.logger.debug("Fetching session key info...");
1663
- try {
1664
- const response = await fetch(`${this.baseUrl}/api/v1/session-key/info`, {
1665
- headers: {
1666
- "X-Session-Key": this.sessionKey.address.toLowerCase()
1667
- }
1668
- });
1669
- if (response.ok) {
1670
- const data = await response.json();
1671
- this.sessionKeyInfo = {
1672
- address: this.sessionKey.address,
1673
- walletAddress: data.wallet_address ?? data.walletAddress ?? null,
1674
- isValid: data.is_valid ?? data.isValid ?? true,
1675
- limits: {
1676
- perTxUsd: data.per_tx_limit_usd ?? data.perTxLimitUsd ?? null,
1677
- dailyUsd: data.daily_limit_usd ?? data.dailyLimitUsd ?? null,
1678
- totalUsd: data.total_limit_usd ?? data.totalLimitUsd ?? null
1679
- },
1680
- usage: {
1681
- todayUsd: data.today_spent_usd ?? data.todaySpentUsd ?? 0,
1682
- totalUsd: data.total_spent_usd ?? data.totalSpentUsd ?? 0,
1683
- txCount: data.tx_count ?? data.txCount ?? 0
1684
- },
1685
- expiresAt: data.expires_at ? new Date(data.expires_at) : null,
1686
- createdAt: data.created_at ? new Date(data.created_at) : null,
1687
- name: data.name,
1688
- allowedMerchants: data.allowed_merchants ?? data.allowedMerchants ?? []
1689
- };
1690
- this.sessionKeyInfoFetchedAt = Date.now();
1691
- return this.sessionKeyInfo;
1692
- }
1693
- } catch (error) {
1694
- this.logger.warn("Failed to fetch session key info:", error);
1695
- }
1696
- return {
1697
- address: this.sessionKey.address,
1698
- walletAddress: null,
1699
- isValid: true,
1700
- limits: { perTxUsd: null, dailyUsd: null, totalUsd: null },
1701
- usage: { todayUsd: this.totalSpentUsd, totalUsd: this.totalSpentUsd, txCount: this.payments.length },
1702
- expiresAt: null,
1703
- createdAt: null
1704
- };
1705
- }
1706
- /**
1707
- * Get spending stats for this session key.
1708
- *
1709
- * @returns Spending statistics
1710
- *
1711
- * @example
1712
- * ```typescript
1713
- * const stats = await wallet.getSpendingStats();
1714
- * console.log(`Spent: $${stats.totalSpentUsd.toFixed(2)}`);
1715
- * console.log(`Remaining daily: $${stats.remainingDailyUsd?.toFixed(2) ?? 'unlimited'}`);
1716
- * ```
1717
- */
1718
- async getSpendingStats() {
1719
- this.logger.debug("Fetching spending stats...");
1720
- try {
1721
- const response = await fetch(`${this.baseUrl}/api/v1/session-key/stats`, {
1722
- headers: {
1723
- "X-Session-Key": this.sessionKey.address.toLowerCase()
1724
- }
1725
- });
1726
- if (response.ok) {
1727
- const data = await response.json();
1728
- return {
1729
- totalSpentUsd: data.total_spent_usd || data.totalSpentUsd || this.totalSpentUsd,
1730
- txCount: data.tx_count || data.txCount || this.payments.length,
1731
- remainingDailyUsd: data.remaining_daily_usd || data.remainingDailyUsd || null,
1732
- remainingTotalUsd: data.remaining_total_usd || data.remainingTotalUsd || null,
1733
- expiresAt: data.expires_at ? new Date(data.expires_at) : null
1734
- };
1735
- }
1736
- } catch (error) {
1737
- this.logger.warn("Failed to fetch spending stats:", error);
1738
- }
1739
- return {
1740
- totalSpentUsd: this.totalSpentUsd,
1741
- txCount: this.payments.length,
1742
- remainingDailyUsd: null,
1743
- remainingTotalUsd: null,
1744
- expiresAt: null
1745
- };
1746
- }
1747
- /**
1748
- * Get list of payments made in this session.
1749
- *
1750
- * @returns Array of payment events
1751
- */
1752
- getPaymentHistory() {
1753
- return [...this.payments];
1754
- }
1755
- /**
1756
- * Get the total amount spent in this session.
1757
- *
1758
- * @returns Total spent in USD
1759
- */
1760
- getTotalSpent() {
1761
- return this.totalSpentUsd;
1762
- }
1763
- // ===========================================================================
1764
- // Diagnostics
1765
- // ===========================================================================
1766
- /**
1767
- * Run diagnostics to verify the wallet is properly configured.
1768
- *
1769
- * This is useful for debugging integration issues.
1770
- *
1771
- * @returns Diagnostic results with status and any issues found
1772
- *
1773
- * @example
1774
- * ```typescript
1775
- * const diagnostics = await wallet.runDiagnostics();
1776
- * if (diagnostics.healthy) {
1777
- * console.log('✅ Wallet is ready to use');
1778
- * } else {
1779
- * console.log('❌ Issues found:');
1780
- * diagnostics.issues.forEach(issue => console.log(` - ${issue}`));
1781
- * }
1782
- * ```
1783
- */
1784
- async runDiagnostics() {
1785
- this.logger.info("Running diagnostics...");
1786
- const issues = [];
1787
- const recommendations = [];
1788
- const checks = {};
1789
- let latencyMs;
1790
- let sessionLimits;
1791
- checks.sessionKeyFormat = true;
1792
- try {
1793
- const startTime = Date.now();
1794
- const response = await fetch(`${this.baseUrl}/health`, {
1795
- method: "GET",
1796
- signal: AbortSignal.timeout(5e3)
1797
- });
1798
- latencyMs = Date.now() - startTime;
1799
- checks.apiConnectivity = response.ok;
1800
- if (!response.ok) {
1801
- issues.push(`API server returned ${response.status}. Check baseUrl configuration.`);
1802
- recommendations.push("Verify the baseUrl configuration points to a valid MixrPay server.");
1803
- }
1804
- if (latencyMs > 2e3) {
1805
- issues.push(`High API latency: ${latencyMs}ms. This may cause timeouts.`);
1806
- recommendations.push("Consider using a server closer to your region or check network connectivity.");
1807
- }
1808
- } catch {
1809
- checks.apiConnectivity = false;
1810
- issues.push("Cannot connect to MixrPay API. Check your network connection and baseUrl.");
1811
- recommendations.push("Verify network connectivity and that the MixrPay server is running.");
1812
- }
1813
- try {
1814
- const info = await this.getSessionKeyInfo(true);
1815
- checks.sessionKeyValid = info.isValid;
1816
- if (!info.isValid) {
1817
- issues.push("Session key is invalid or has been revoked.");
1818
- recommendations.push("Request a new session key from the wallet owner at https://mixrpay.com/manage/invites");
1819
- }
1820
- const now = /* @__PURE__ */ new Date();
1821
- let expiresInHours = null;
1822
- if (info.expiresAt) {
1823
- expiresInHours = (info.expiresAt.getTime() - now.getTime()) / (1e3 * 60 * 60);
1824
- if (info.expiresAt < now) {
1825
- checks.sessionKeyValid = false;
1826
- issues.push(`Session key expired on ${info.expiresAt.toISOString()}`);
1827
- recommendations.push("Create a new session key to continue making payments.");
1828
- } else if (expiresInHours < 24) {
1829
- issues.push(`Session key expires in ${expiresInHours.toFixed(1)} hours.`);
1830
- recommendations.push("Consider creating a new session key before the current one expires.");
1831
- }
1832
- }
1833
- const stats = await this.getSpendingStats();
1834
- sessionLimits = {
1835
- remainingDailyUsd: stats.remainingDailyUsd,
1836
- remainingTotalUsd: stats.remainingTotalUsd,
1837
- expiresAt: info.expiresAt,
1838
- expiresInHours
1839
- };
1840
- if (stats.remainingDailyUsd !== null && stats.remainingDailyUsd < 1) {
1841
- issues.push(`Daily limit nearly exhausted: $${stats.remainingDailyUsd.toFixed(2)} remaining.`);
1842
- recommendations.push("Wait until tomorrow for daily limit to reset, or request a higher daily limit.");
1843
- }
1844
- if (stats.remainingTotalUsd !== null && stats.remainingTotalUsd < 1) {
1845
- issues.push(`Total limit nearly exhausted: $${stats.remainingTotalUsd.toFixed(2)} remaining.`);
1846
- recommendations.push("Request a new session key with a higher total limit.");
1847
- }
1848
- } catch {
1849
- checks.sessionKeyValid = false;
1850
- issues.push("Could not verify session key validity.");
1851
- recommendations.push("Check network connectivity and try again.");
1852
- }
1853
- let balance = 0;
1854
- try {
1855
- balance = await this.getBalance();
1856
- checks.hasBalance = balance > 0;
1857
- if (balance <= 0) {
1858
- issues.push("Wallet has no USDC balance. Top up at https://mixrpay.com/manage/wallet");
1859
- recommendations.push("Deposit USDC to your wallet address to enable payments.");
1860
- } else if (balance < 1) {
1861
- issues.push(`Low balance: $${balance.toFixed(2)}. Consider topping up.`);
1862
- recommendations.push("Top up your wallet balance to avoid payment failures.");
1863
- }
1864
- } catch {
1865
- checks.hasBalance = false;
1866
- issues.push("Could not fetch wallet balance.");
1867
- recommendations.push("Check network connectivity and try again.");
1868
- }
1869
- const healthy = issues.length === 0;
1870
- this.logger.info("Diagnostics complete:", { healthy, issues, latencyMs });
1871
- return {
1872
- healthy,
1873
- issues,
1874
- checks,
1875
- sdkVersion: SDK_VERSION,
1876
- network: this.getNetwork().name,
1877
- walletAddress: this.walletAddress,
1878
- sessionLimits,
1879
- latencyMs,
1880
- recommendations
1881
- };
1882
- }
1883
- /**
1884
- * Enable or disable debug logging.
1885
- *
1886
- * @param enable - true to enable debug logging, false to disable
1887
- *
1888
- * @example
1889
- * ```typescript
1890
- * wallet.setDebug(true); // Enable detailed logs
1891
- * await wallet.fetch(...);
1892
- * wallet.setDebug(false); // Disable logs
1893
- * ```
1894
- */
1895
- setDebug(enable) {
1896
- this.logger.setLevel(enable ? "debug" : "none");
1897
- }
1898
- /**
1899
- * Set the log level.
1900
- *
1901
- * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
1902
- */
1903
- setLogLevel(level) {
1904
- this.logger.setLevel(level);
1905
- }
1906
- // ===========================================================================
1907
- // Session Authorization Methods (for MixrPay Merchants)
1908
- // ===========================================================================
1909
- /**
1910
- * Create the X-Session-Auth header for secure API authentication.
1911
- * Uses signature-based authentication - private key is NEVER transmitted.
1912
- *
1913
- * @returns Headers object with X-Session-Auth
1914
- */
1915
- async getSessionAuthHeaders() {
1916
- const payload = await createSessionAuthPayload(this.sessionKey);
1917
- return {
1918
- "X-Session-Auth": JSON.stringify(payload)
1919
- };
1920
- }
1921
- /**
1922
- * Get an existing session or create a new one with a MixrPay merchant.
1923
- *
1924
- * This is the recommended way to interact with MixrPay-enabled APIs.
1925
- * If an active session exists, it will be returned. Otherwise, a new
1926
- * session authorization request will be created and confirmed.
1927
- *
1928
- * @param options - Session creation options
1929
- * @returns Active session authorization
1930
- *
1931
- * @throws {MixrPayError} If merchant is not found or session creation fails
1932
- *
1933
- * @example
1934
- * ```typescript
1935
- * const session = await wallet.getOrCreateSession({
1936
- * merchantPublicKey: 'pk_live_abc123...',
1937
- * spendingLimitUsd: 25.00,
1938
- * durationDays: 7,
1939
- * });
1940
- *
1941
- * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
1942
- * ```
1943
- */
1944
- async getOrCreateSession(options) {
1945
- this.logger.debug("getOrCreateSession called", options);
1946
- const { merchantPublicKey, spendingLimitUsd = 25, durationDays = 7 } = options;
1947
- try {
1948
- const existingSession = await this.getSessionByMerchant(merchantPublicKey);
1949
- if (existingSession && existingSession.status === "active") {
1950
- this.logger.debug("Found existing active session", existingSession.id);
1951
- return existingSession;
1952
- }
1953
- } catch {
1954
- }
1955
- this.logger.info(`Creating new session with merchant ${merchantPublicKey.slice(0, 20)}...`);
1956
- const authHeaders = await this.getSessionAuthHeaders();
1957
- const authorizeResponse = await fetch(`${this.baseUrl}/api/v2/session/authorize`, {
1958
- method: "POST",
1959
- headers: {
1960
- "Content-Type": "application/json",
1961
- ...authHeaders
1962
- },
1963
- body: JSON.stringify({
1964
- merchant_public_key: merchantPublicKey,
1965
- spending_limit_usd: spendingLimitUsd,
1966
- duration_days: durationDays
1967
- })
1968
- });
1969
- if (!authorizeResponse.ok) {
1970
- const error = await authorizeResponse.json().catch(() => ({}));
1971
- throw new MixrPayError(
1972
- error.message || error.error || `Failed to create session: ${authorizeResponse.status}`
1973
- );
1974
- }
1975
- const authorizeData = await authorizeResponse.json();
1976
- const sessionId = authorizeData.session_id;
1977
- const messageToSign = authorizeData.message_to_sign;
1978
- if (!sessionId || !messageToSign) {
1979
- throw new MixrPayError("Invalid authorize response: missing session_id or message_to_sign");
1980
- }
1981
- this.logger.debug("Signing session authorization message...");
1982
- const signature = await this.sessionKey.signMessage(messageToSign);
1983
- const confirmResponse = await fetch(`${this.baseUrl}/api/v2/session/confirm`, {
1984
- method: "POST",
1985
- headers: {
1986
- "Content-Type": "application/json"
1987
- },
1988
- body: JSON.stringify({
1989
- session_id: sessionId,
1990
- signature,
1991
- wallet_address: this.walletAddress
1992
- })
1993
- });
1994
- if (!confirmResponse.ok) {
1995
- const error = await confirmResponse.json().catch(() => ({}));
1996
- throw new MixrPayError(
1997
- error.message || `Failed to confirm session: ${confirmResponse.status}`
1998
- );
1999
- }
2000
- const confirmData = await confirmResponse.json();
2001
- this.logger.info(`Session created: ${confirmData.session?.id || sessionId}`);
2002
- return this.parseSessionResponse(confirmData.session || confirmData);
2003
- }
2004
- /**
2005
- * Get session status for a specific merchant.
2006
- *
2007
- * @param merchantPublicKey - The merchant's public key
2008
- * @returns Session authorization or null if not found
2009
- */
2010
- async getSessionByMerchant(merchantPublicKey) {
2011
- this.logger.debug("getSessionByMerchant", merchantPublicKey);
2012
- const authHeaders = await this.getSessionAuthHeaders();
2013
- const response = await fetch(`${this.baseUrl}/api/v2/session/status?merchant_public_key=${encodeURIComponent(merchantPublicKey)}`, {
2014
- headers: authHeaders
2015
- });
2016
- if (response.status === 404) {
2017
- return null;
2018
- }
2019
- if (!response.ok) {
2020
- const error = await response.json().catch(() => ({}));
2021
- throw new MixrPayError(error.message || `Failed to get session: ${response.status}`);
2022
- }
2023
- const data = await response.json();
2024
- return data.session ? this.parseSessionResponse(data.session) : null;
2025
- }
2026
- /**
2027
- * List all session authorizations for this wallet.
2028
- *
2029
- * @returns Array of session authorizations
2030
- *
2031
- * @example
2032
- * ```typescript
2033
- * const sessions = await wallet.listSessions();
2034
- * for (const session of sessions) {
2035
- * console.log(`${session.merchantName}: $${session.remainingLimitUsd} remaining`);
2036
- * }
2037
- * ```
2038
- */
2039
- async listSessions() {
2040
- this.logger.debug("listSessions");
2041
- const authHeaders = await this.getSessionAuthHeaders();
2042
- const response = await fetch(`${this.baseUrl}/api/v2/session/list`, {
2043
- headers: authHeaders
2044
- });
2045
- if (!response.ok) {
2046
- const error = await response.json().catch(() => ({}));
2047
- throw new MixrPayError(error.message || `Failed to list sessions: ${response.status}`);
2048
- }
2049
- const data = await response.json();
2050
- return (data.sessions || []).map((s) => this.parseSessionResponse(s));
2051
- }
2052
- /**
2053
- * Revoke a session authorization.
2054
- *
2055
- * After revocation, no further charges can be made against this session.
2056
- *
2057
- * @param sessionId - The session ID to revoke
2058
- * @returns true if revoked successfully
2059
- *
2060
- * @example
2061
- * ```typescript
2062
- * const revoked = await wallet.revokeSession('sess_abc123');
2063
- * if (revoked) {
2064
- * console.log('Session revoked successfully');
2065
- * }
2066
- * ```
2067
- */
2068
- async revokeSession(sessionId) {
2069
- this.logger.debug("revokeSession", sessionId);
2070
- const authHeaders = await this.getSessionAuthHeaders();
2071
- const response = await fetch(`${this.baseUrl}/api/v2/session/revoke`, {
2072
- method: "POST",
2073
- headers: {
2074
- "Content-Type": "application/json",
2075
- ...authHeaders
2076
- },
2077
- body: JSON.stringify({ session_id: sessionId })
2078
- });
2079
- if (!response.ok) {
2080
- const error = await response.json().catch(() => ({}));
2081
- this.logger.error("Failed to revoke session:", error);
2082
- return false;
2083
- }
2084
- this.logger.info(`Session ${sessionId} revoked`);
2085
- return true;
2086
- }
2087
- /**
2088
- * Get statistics about all session authorizations.
2089
- *
2090
- * This provides an overview of active, expired, and revoked sessions,
2091
- * along with aggregate spending information.
2092
- *
2093
- * @returns Session statistics
2094
- *
2095
- * @example
2096
- * ```typescript
2097
- * const stats = await wallet.getSessionStats();
2098
- * console.log(`Active sessions: ${stats.activeCount}`);
2099
- * console.log(`Total authorized: $${stats.totalAuthorizedUsd.toFixed(2)}`);
2100
- * console.log(`Total remaining: $${stats.totalRemainingUsd.toFixed(2)}`);
2101
- *
2102
- * for (const session of stats.activeSessions) {
2103
- * console.log(`${session.merchantName}: $${session.remainingUsd} remaining`);
2104
- * }
2105
- * ```
2106
- */
2107
- async getSessionStats() {
2108
- this.logger.debug("getSessionStats");
2109
- const sessions = await this.listSessions();
2110
- const now = /* @__PURE__ */ new Date();
2111
- const active = [];
2112
- const expired = [];
2113
- const revoked = [];
2114
- for (const session of sessions) {
2115
- if (session.status === "revoked") {
2116
- revoked.push(session);
2117
- } else if (session.status === "expired" || session.expiresAt && session.expiresAt < now) {
2118
- expired.push(session);
2119
- } else if (session.status === "active") {
2120
- active.push(session);
2121
- }
2122
- }
2123
- const totalAuthorizedUsd = active.reduce((sum, s) => sum + s.spendingLimitUsd, 0);
2124
- const totalSpentUsd = sessions.reduce((sum, s) => sum + s.amountUsedUsd, 0);
2125
- const totalRemainingUsd = active.reduce((sum, s) => sum + s.remainingLimitUsd, 0);
2126
- return {
2127
- activeCount: active.length,
2128
- expiredCount: expired.length,
2129
- revokedCount: revoked.length,
2130
- totalAuthorizedUsd,
2131
- totalSpentUsd,
2132
- totalRemainingUsd,
2133
- activeSessions: active.map((s) => ({
2134
- id: s.id,
2135
- merchantName: s.merchantName,
2136
- merchantPublicKey: s.merchantId,
2137
- // merchantId is the public key in this context
2138
- spendingLimitUsd: s.spendingLimitUsd,
2139
- remainingUsd: s.remainingLimitUsd,
2140
- expiresAt: s.expiresAt
2141
- }))
2142
- };
2143
- }
2144
- /**
2145
- * Charge against an active session authorization.
2146
- *
2147
- * This is useful when you need to manually charge a session outside of
2148
- * the `callMerchantApi()` flow.
2149
- *
2150
- * @param sessionId - The session ID to charge
2151
- * @param amountUsd - Amount to charge in USD
2152
- * @param options - Additional charge options
2153
- * @returns Charge result
2154
- *
2155
- * @example
2156
- * ```typescript
2157
- * const result = await wallet.chargeSession('sess_abc123', 0.05, {
2158
- * feature: 'ai-generation',
2159
- * idempotencyKey: 'unique-key-123',
2160
- * });
2161
- *
2162
- * console.log(`Charged $${result.amountUsd}, remaining: $${result.remainingSessionBalanceUsd}`);
2163
- * ```
2164
- */
2165
- async chargeSession(sessionId, amountUsd, options = {}) {
2166
- this.logger.debug("chargeSession", { sessionId, amountUsd, options });
2167
- const authHeaders = await this.getSessionAuthHeaders();
2168
- const response = await fetch(`${this.baseUrl}/api/v2/charge`, {
2169
- method: "POST",
2170
- headers: {
2171
- "Content-Type": "application/json",
2172
- ...authHeaders
2173
- },
2174
- body: JSON.stringify({
2175
- session_id: sessionId,
2176
- price_usd: amountUsd,
2177
- feature: options.feature,
2178
- idempotency_key: options.idempotencyKey,
2179
- metadata: options.metadata
2180
- })
2181
- });
2182
- if (!response.ok) {
2183
- const error = await response.json().catch(() => ({}));
2184
- const errorCode = error.error || error.error_code || "";
2185
- if (response.status === 402) {
2186
- if (errorCode === "session_limit_exceeded") {
2187
- const limit = error.sessionLimitUsd || error.session_limit_usd || 0;
2188
- const remaining = error.remainingUsd || error.remaining_usd || 0;
2189
- throw new SessionLimitExceededError(limit, amountUsd, remaining, sessionId);
2190
- }
2191
- if (errorCode === "insufficient_balance") {
2192
- throw new InsufficientBalanceError(
2193
- amountUsd,
2194
- error.availableUsd || error.available_usd || 0
2195
- );
2196
- }
2197
- }
2198
- if (response.status === 404 || errorCode === "session_not_found") {
2199
- throw new SessionNotFoundError(sessionId);
2200
- }
2201
- if (errorCode === "session_expired") {
2202
- throw new SessionExpiredError(sessionId, error.expiredAt || error.expires_at);
2203
- }
2204
- if (errorCode === "session_revoked") {
2205
- throw new SessionRevokedError(sessionId, error.reason);
2206
- }
2207
- throw new MixrPayError(error.message || `Charge failed: ${response.status}`);
2208
- }
2209
- const data = await response.json();
2210
- this.logger.payment(amountUsd, sessionId, options.feature);
2211
- return {
2212
- success: true,
2213
- chargeId: data.chargeId || data.charge_id,
2214
- amountUsd: data.amountUsd || data.amount_usd || amountUsd,
2215
- txHash: data.txHash || data.tx_hash,
2216
- remainingSessionBalanceUsd: data.remainingSessionBalanceUsd || data.remaining_session_balance_usd || 0
2217
- };
2218
- }
2219
- /**
2220
- * Call a MixrPay merchant's API with automatic session management.
2221
- *
2222
- * This is the recommended way to interact with MixrPay-enabled APIs.
2223
- * It automatically:
2224
- * 1. Gets or creates a session authorization
2225
- * 2. Adds the `X-Mixr-Session` header to the request
2226
- * 3. Handles payment errors and session expiration
2227
- *
2228
- * @param options - API call options
2229
- * @returns Response from the merchant API
2230
- *
2231
- * @example
2232
- * ```typescript
2233
- * const response = await wallet.callMerchantApi({
2234
- * url: 'https://api.merchant.com/generate',
2235
- * merchantPublicKey: 'pk_live_abc123...',
2236
- * method: 'POST',
2237
- * body: { prompt: 'Hello world' },
2238
- * priceUsd: 0.05,
2239
- * });
2240
- *
2241
- * const data = await response.json();
2242
- * ```
2243
- */
2244
- async callMerchantApi(options) {
2245
- const {
2246
- url,
2247
- method = "POST",
2248
- body,
2249
- headers: customHeaders = {},
2250
- merchantPublicKey,
2251
- priceUsd,
2252
- feature
2253
- } = options;
2254
- this.logger.debug("callMerchantApi", { url, method, merchantPublicKey, priceUsd });
2255
- await this.validateMerchantAllowed(url, "url");
2256
- if (priceUsd !== void 0 && this.maxPaymentUsd !== void 0 && priceUsd > this.maxPaymentUsd) {
2257
- throw new SpendingLimitExceededError("client_max", this.maxPaymentUsd, priceUsd);
2258
- }
2259
- const session = await this.getOrCreateSession({
2260
- merchantPublicKey,
2261
- spendingLimitUsd: 25,
2262
- // Default limit
2263
- durationDays: 7
2264
- });
2265
- const headers = {
2266
- "Content-Type": "application/json",
2267
- "X-Mixr-Session": session.id,
2268
- ...customHeaders
2269
- };
2270
- if (feature) {
2271
- headers["X-Mixr-Feature"] = feature;
2272
- }
2273
- const requestBody = body !== void 0 ? typeof body === "string" ? body : JSON.stringify(body) : void 0;
2274
- const response = await fetch(url, {
2275
- method,
2276
- headers,
2277
- body: requestBody,
2278
- signal: AbortSignal.timeout(this.timeout)
2279
- });
2280
- const chargedAmount = response.headers.get("X-Mixr-Charged");
2281
- if (chargedAmount) {
2282
- const amountUsd = parseFloat(chargedAmount);
2283
- if (!isNaN(amountUsd)) {
2284
- const payment = {
2285
- amountUsd,
2286
- recipient: merchantPublicKey,
2287
- txHash: response.headers.get("X-Payment-TxHash"),
2288
- timestamp: /* @__PURE__ */ new Date(),
2289
- description: feature || "API call",
2290
- url,
2291
- requestId: crypto.randomUUID(),
2292
- correlationId: this.extractCorrelationId(customHeaders)
2293
- };
2294
- this.payments.push(payment);
2295
- this.totalSpentUsd += amountUsd;
2296
- this.logger.payment(amountUsd, merchantPublicKey, feature);
2297
- if (this.onPayment) {
2298
- this.onPayment(payment);
2299
- }
2300
- }
2301
- }
2302
- if (response.status === 402) {
2303
- const errorData = await response.json().catch(() => ({}));
2304
- const errorCode = errorData.error || errorData.error_code || "";
2305
- if (errorCode === "session_expired") {
2306
- this.logger.info("Session expired, creating new one...");
2307
- const newSession = await this.getOrCreateSession({
2308
- merchantPublicKey,
2309
- spendingLimitUsd: 25,
2310
- durationDays: 7
2311
- });
2312
- headers["X-Mixr-Session"] = newSession.id;
2313
- return fetch(url, {
2314
- method,
2315
- headers,
2316
- body: requestBody,
2317
- signal: AbortSignal.timeout(this.timeout)
2318
- });
2319
- }
2320
- if (errorCode === "session_limit_exceeded") {
2321
- const limit = errorData.sessionLimitUsd || errorData.session_limit_usd || 0;
2322
- const remaining = errorData.remainingUsd || errorData.remaining_usd || 0;
2323
- throw new SessionLimitExceededError(limit, priceUsd || 0, remaining, session.id);
2324
- }
2325
- if (errorCode === "session_revoked") {
2326
- throw new SessionRevokedError(session.id, errorData.reason);
2327
- }
2328
- if (errorCode === "session_not_found") {
2329
- throw new SessionNotFoundError(session.id);
2330
- }
2331
- if (errorCode === "insufficient_balance") {
2332
- throw new InsufficientBalanceError(
2333
- priceUsd || 0,
2334
- errorData.availableUsd || errorData.available_usd || 0
2335
- );
2336
- }
2337
- }
2338
- return response;
2339
- }
2340
- /**
2341
- * Parse session response data into SessionAuthorization object.
2342
- */
2343
- parseSessionResponse(data) {
2344
- return {
2345
- id: data.id || data.session_id || data.sessionId,
2346
- merchantId: data.merchantId || data.merchant_id,
2347
- merchantName: data.merchantName || data.merchant_name || "Unknown",
2348
- status: data.status || "active",
2349
- spendingLimitUsd: Number(data.spendingLimitUsd || data.spending_limit_usd || data.spendingLimit || 0),
2350
- amountUsedUsd: Number(data.amountUsedUsd || data.amount_used_usd || data.amountUsed || 0),
2351
- remainingLimitUsd: Number(
2352
- data.remainingLimitUsd || data.remaining_limit_usd || data.remainingLimit || Number(data.spendingLimitUsd || data.spending_limit_usd || 0) - Number(data.amountUsedUsd || data.amount_used_usd || 0)
2353
- ),
2354
- expiresAt: new Date(data.expiresAt || data.expires_at),
2355
- createdAt: new Date(data.createdAt || data.created_at)
2356
- };
2357
- }
2358
- // ===========================================================================
2359
- // MCP (Model Context Protocol) Methods
2360
- // ===========================================================================
2361
- /**
2362
- * Get authentication headers for MCP wallet-based authentication.
2363
- *
2364
- * These headers prove wallet ownership without transmitting the private key.
2365
- * Use for direct pay-per-call mode (no session needed).
2366
- *
2367
- * @returns Headers object with X-Mixr-Wallet, X-Mixr-Signature, X-Mixr-Timestamp
2368
- *
2369
- * @example
2370
- * ```typescript
2371
- * const headers = await wallet.getMCPAuthHeaders();
2372
- * const response = await fetch('https://mixrpay.com/api/mcp', {
2373
- * method: 'POST',
2374
- * headers: {
2375
- * 'Content-Type': 'application/json',
2376
- * ...headers,
2377
- * },
2378
- * body: JSON.stringify({
2379
- * jsonrpc: '2.0',
2380
- * method: 'tools/list',
2381
- * id: 1,
2382
- * }),
2383
- * });
2384
- * ```
2385
- */
2386
- async getMCPAuthHeaders() {
2387
- const timestamp = Date.now().toString();
2388
- const message = `MixrPay MCP Auth
19
+ `),y+=`URI: ${s}
20
+ `,y+=`Version: ${h}
21
+ `,y+=`Chain ID: ${g}
22
+ `,y+=`Nonce: ${a}
23
+ `,y+=`Issued At: ${r.toISOString()}`,i&&(y+=`
24
+ Expiration Time: ${i.toISOString()}`),o&&(y+=`
25
+ Not Before: ${o.toISOString()}`),c&&(y+=`
26
+ Request ID: ${c}`),p&&p.length>0){y+=`
27
+ Resources:`;for(let f of p)y+=`
28
+ - ${f}`;}let m=await this.sessionKey.signMessage(y);return {message:y,signature:m,address:u,chainId:g,nonce:a,issuedAt:r,expirationTime:i}}setDebug(e){this.logger.setLevel(e?"debug":"none");}setLogLevel(e){this.logger.setLevel(e);}async getSessionAuthHeaders(){let e=await Y(this.sessionKey);return {"X-Session-Auth":JSON.stringify(e)}}async getOrCreateSession(e){this.logger.debug("getOrCreateSession called",e);let{merchantPublicKey:t,spendingLimitUsd:s,durationDays:n}=e;try{let h=await this.getSessionByMerchant(t);if(h&&h.status==="active")return this.logger.debug("Found existing active session",h.id),h}catch{}this.logger.info(`Creating new session with merchant ${t.slice(0,20)}...`);let a=await this.getSessionAuthHeaders(),r=await fetch(`${this.baseUrl}/api/v2/session/authorize`,{method:"POST",headers:{"Content-Type":"application/json",...a},body:JSON.stringify({merchant_public_key:t,spending_limit_usd:s,duration_days:n})});if(!r.ok){let h=await r.json().catch(()=>({}));throw new l(h.message||h.error||`Failed to create session: ${r.status}`)}let i=await r.json(),o=i.session_id,c=i.message_to_sign;if(!o||!c)throw new l("Invalid authorize response: missing session_id or message_to_sign");this.logger.debug("Signing session authorization message...");let p=await this.sessionKey.signMessage(c),u=await fetch(`${this.baseUrl}/api/v2/session/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:o,signature:p,wallet_address:this.walletAddress})});if(!u.ok){let h=await u.json().catch(()=>({}));throw new l(h.message||`Failed to confirm session: ${u.status}`)}let g=await u.json();return this.logger.info(`Session created: ${g.session?.id||o}`),this.parseSessionResponse(g.session||g)}async getSessionByMerchant(e){this.logger.debug("getSessionByMerchant",e);let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/session/status?merchant_public_key=${encodeURIComponent(e)}`,{headers:t});if(s.status===404)return null;if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.message||`Failed to get session: ${s.status}`)}let n=await s.json();return n.session?this.parseSessionResponse(n.session):null}async listSessions(){this.logger.debug("listSessions");let e=await this.getSessionAuthHeaders(),t=await fetch(`${this.baseUrl}/api/v2/session/list`,{headers:e});if(!t.ok){let n=await t.json().catch(()=>({}));throw new l(n.message||`Failed to list sessions: ${t.status}`)}return ((await t.json()).sessions||[]).map(n=>this.parseSessionResponse(n))}async revokeSession(e){this.logger.debug("revokeSession",e);let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/session/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify({session_id:e})});if(!s.ok){let n=await s.json().catch(()=>({}));return this.logger.error("Failed to revoke session:",n),false}return this.logger.info(`Session ${e} revoked`),true}async getSessionStats(){this.logger.debug("getSessionStats");let e=await this.listSessions(),t=new Date,s=[],n=[],a=[];for(let c of e)c.status==="revoked"?a.push(c):c.status==="expired"||c.expiresAt&&c.expiresAt<t?n.push(c):c.status==="active"&&s.push(c);let r=s.reduce((c,p)=>c+p.spendingLimitUsd,0),i=e.reduce((c,p)=>c+p.amountUsedUsd,0),o=s.reduce((c,p)=>c+p.remainingLimitUsd,0);return {activeCount:s.length,expiredCount:n.length,revokedCount:a.length,totalAuthorizedUsd:r,totalSpentUsd:i,totalRemainingUsd:o,activeSessions:s.map(c=>({id:c.id,merchantName:c.merchantName,merchantPublicKey:c.merchantId,spendingLimitUsd:c.spendingLimitUsd,remainingUsd:c.remainingLimitUsd,expiresAt:c.expiresAt}))}}async chargeSession(e,t,s={}){this.logger.debug("chargeSession",{sessionId:e,amountUsd:t,options:s});let n=await this.getSessionAuthHeaders(),a=await fetch(`${this.baseUrl}/api/v2/charge`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify({session_id:e,price_usd:t,feature:s.feature,idempotency_key:s.idempotencyKey,metadata:s.metadata})});if(!a.ok){let i=await a.json().catch(()=>({})),o=(i.error||i.error_code||"").toLowerCase();if(a.status===402){if(o==="session_limit_exceeded"){let c=i.sessionLimitUsd||i.session_limit_usd||0,p=i.remainingUsd||i.remaining_usd||0;throw new U(c,t,p,e)}if(o==="insufficient_balance")throw new S(t,i.availableUsd||i.available_usd||0)}throw a.status===404||o==="session_not_found"?new P(e):o==="session_expired"?new C(e,i.expiredAt||i.expires_at):o==="session_revoked"?new I(e,i.reason):new l(i.message||`Charge failed: ${a.status}`)}let r=await a.json();return this.logger.payment(t,e,s.feature),{success:true,chargeId:r.chargeId||r.charge_id,amountUsd:r.amountUsd||r.amount_usd||t,txHash:r.txHash||r.tx_hash,remainingSessionBalanceUsd:r.remainingSessionBalanceUsd||r.remaining_session_balance_usd||0}}async callMerchantApi(e){let{url:t,method:s="POST",body:n,headers:a={},merchantPublicKey:r,priceUsd:i,feature:o}=e;if(this.logger.debug("callMerchantApi",{url:t,method:s,merchantPublicKey:r,priceUsd:i}),await this.validateMerchantAllowed(t,"url"),i!==void 0&&this.maxPaymentUsd!==void 0&&i>this.maxPaymentUsd)throw new v("client_max",this.maxPaymentUsd,i);let c=await this.getOrCreateSession({merchantPublicKey:r}),p={"Content-Type":"application/json","X-Mixr-Session":c.id,...a};o&&(p["X-Mixr-Feature"]=o);let u=n!==void 0?typeof n=="string"?n:JSON.stringify(n):void 0,g=await fetch(t,{method:s,headers:p,body:u,signal:AbortSignal.timeout(this.timeout)}),h=g.headers.get("X-Mixr-Charged");if(h){let y=parseFloat(h);if(!isNaN(y)){let m={amountUsd:y,recipient:r,txHash:g.headers.get("X-Payment-TxHash"),timestamp:new Date,description:o||"API call",url:t,requestId:crypto.randomUUID(),correlationId:this.extractCorrelationId(a)};this.payments.push(m),this.totalSpentUsd+=y,this.logger.payment(y,r,o),this.onPayment&&this.onPayment(m);}}if(g.status===402){let y=await g.json().catch(()=>({})),m=(y.error||y.error_code||"").toLowerCase();if(m==="session_expired"){this.logger.info("Session expired, creating new one...");let f=await this.getOrCreateSession({merchantPublicKey:r});return p["X-Mixr-Session"]=f.id,fetch(t,{method:s,headers:p,body:u,signal:AbortSignal.timeout(this.timeout)})}if(m==="session_limit_exceeded"){let f=y.sessionLimitUsd||y.session_limit_usd||0,w=y.remainingUsd||y.remaining_usd||0;throw new U(f,i||0,w,c.id)}if(m==="session_revoked")throw new I(c.id,y.reason);if(m==="session_not_found")throw new P(c.id);if(m==="insufficient_balance")throw new S(i||0,y.availableUsd||y.available_usd||0)}return g}parseSessionResponse(e){return {id:e.id||e.session_id||e.sessionId,merchantId:e.merchantId||e.merchant_id,merchantName:e.merchantName||e.merchant_name||"Unknown",status:e.status||"active",spendingLimitUsd:Number(e.spendingLimitUsd||e.spending_limit_usd||e.spendingLimit||0),amountUsedUsd:Number(e.amountUsedUsd||e.amount_used_usd||e.amountUsed||0),remainingLimitUsd:Number(e.remainingLimitUsd||e.remaining_limit_usd||e.remainingLimit||Number(e.spendingLimitUsd||e.spending_limit_usd||0)-Number(e.amountUsedUsd||e.amount_used_usd||0)),expiresAt:new Date(e.expiresAt||e.expires_at),createdAt:new Date(e.createdAt||e.created_at)}}async getMCPAuthHeaders(){let e=Date.now().toString(),t=`MixrPay MCP Auth
2389
29
  Wallet: ${this.walletAddress}
2390
- Timestamp: ${timestamp}`;
2391
- const signature = await this.sessionKey.signMessage(message);
2392
- return {
2393
- "X-Mixr-Wallet": this.walletAddress,
2394
- "X-Mixr-Signature": signature,
2395
- "X-Mixr-Timestamp": timestamp
2396
- };
2397
- }
2398
- /**
2399
- * List available MCP tools from the MixrPay gateway.
2400
- *
2401
- * Returns all tools exposed by MCP providers on the MixrPay marketplace.
2402
- * Each tool includes pricing information.
2403
- *
2404
- * @returns Array of MCP tools with pricing and metadata
2405
- *
2406
- * @example
2407
- * ```typescript
2408
- * const tools = await wallet.listMCPTools();
2409
- * for (const tool of tools) {
2410
- * console.log(`${tool.name}: $${tool.priceUsd} - ${tool.description}`);
2411
- * }
2412
- * ```
2413
- */
2414
- async listMCPTools() {
2415
- this.logger.debug("listMCPTools");
2416
- const response = await fetch(`${this.baseUrl}/api/mcp`, {
2417
- method: "POST",
2418
- headers: { "Content-Type": "application/json" },
2419
- body: JSON.stringify({
2420
- jsonrpc: "2.0",
2421
- method: "tools/list",
2422
- id: Date.now()
2423
- })
2424
- });
2425
- if (!response.ok) {
2426
- throw new MixrPayError(`Failed to list MCP tools: ${response.status}`);
2427
- }
2428
- const result = await response.json();
2429
- if (result.error) {
2430
- throw new MixrPayError(result.error.message || "Failed to list MCP tools");
2431
- }
2432
- return (result.result?.tools || []).map((tool) => ({
2433
- name: tool.name,
2434
- description: tool.description,
2435
- inputSchema: tool.inputSchema,
2436
- priceUsd: tool["x-mixrpay"]?.priceUsd || 0,
2437
- merchantName: tool["x-mixrpay"]?.merchantName,
2438
- merchantSlug: tool["x-mixrpay"]?.merchantSlug,
2439
- verified: tool["x-mixrpay"]?.verified || false
2440
- }));
2441
- }
2442
- /**
2443
- * Call an MCP tool with wallet authentication (direct pay per call).
2444
- *
2445
- * This method signs a fresh auth message for each call, charging
2446
- * directly from your wallet balance without needing a session.
2447
- *
2448
- * @param toolName - The tool name in format "merchant/tool"
2449
- * @param args - Arguments to pass to the tool
2450
- * @returns Tool execution result
2451
- *
2452
- * @example
2453
- * ```typescript
2454
- * const result = await wallet.callMCPTool('firecrawl/scrape', {
2455
- * url: 'https://example.com',
2456
- * });
2457
- * console.log(result.data);
2458
- * console.log(`Charged: $${result.chargedUsd}`);
2459
- * ```
2460
- */
2461
- async callMCPTool(toolName, args = {}) {
2462
- this.logger.debug("callMCPTool", { toolName, args });
2463
- await this.validateMerchantAllowed(toolName, "tool");
2464
- const authHeaders = await this.getMCPAuthHeaders();
2465
- const response = await fetch(`${this.baseUrl}/api/mcp`, {
2466
- method: "POST",
2467
- headers: {
2468
- "Content-Type": "application/json",
2469
- ...authHeaders
2470
- },
2471
- body: JSON.stringify({
2472
- jsonrpc: "2.0",
2473
- method: "tools/call",
2474
- params: { name: toolName, arguments: args },
2475
- id: Date.now()
2476
- })
2477
- });
2478
- const result = await response.json();
2479
- if (result.error) {
2480
- throw new MixrPayError(result.error.message || "MCP tool call failed");
2481
- }
2482
- const content = result.result?.content?.[0];
2483
- const data = content?.text ? JSON.parse(content.text) : null;
2484
- const mixrpay = result.result?._mixrpay || {};
2485
- if (mixrpay.chargedUsd) {
2486
- const payment = {
2487
- amountUsd: mixrpay.chargedUsd,
2488
- recipient: toolName.split("/")[0] || toolName,
2489
- txHash: mixrpay.txHash,
2490
- timestamp: /* @__PURE__ */ new Date(),
2491
- description: `MCP: ${toolName}`,
2492
- url: `${this.baseUrl}/api/mcp`,
2493
- requestId: crypto.randomUUID()
2494
- };
2495
- this.payments.push(payment);
2496
- this.totalSpentUsd += mixrpay.chargedUsd;
2497
- this.logger.payment(mixrpay.chargedUsd, toolName, "MCP call");
2498
- if (this.onPayment) {
2499
- this.onPayment(payment);
2500
- }
2501
- }
2502
- return {
2503
- data,
2504
- chargedUsd: mixrpay.chargedUsd || 0,
2505
- txHash: mixrpay.txHash,
2506
- latencyMs: mixrpay.latencyMs
2507
- };
2508
- }
2509
- // ===========================================================================
2510
- // JIT MCP Server Methods
2511
- // ===========================================================================
2512
- /**
2513
- * Deploy a JIT MCP server from the Glama directory.
2514
- *
2515
- * Deploys any remote-capable MCP server to Cloudflare Workers.
2516
- * Charges $1 from your session budget.
2517
- *
2518
- * @param options - Deployment options including Glama server details and env vars
2519
- * @returns Deployed instance with private endpoint URL
2520
- *
2521
- * @example
2522
- * ```typescript
2523
- * const result = await wallet.deployJitMcp({
2524
- * glamaId: 'notion-mcp',
2525
- * glamaNamespace: 'notion',
2526
- * glamaSlug: 'notion-mcp',
2527
- * toolName: 'My Notion Server',
2528
- * envVars: { NOTION_API_KEY: 'secret_...' },
2529
- * ttlHours: 24,
2530
- * });
2531
- *
2532
- * console.log('Endpoint:', result.instance.endpointUrl);
2533
- * console.log('Expires:', result.instance.expiresAt);
2534
- * ```
2535
- */
2536
- async deployJitMcp(options) {
2537
- this.logger.debug("deployJitMcp", { glamaId: options.glamaId, toolName: options.toolName });
2538
- const authHeaders = await this.getSessionAuthHeaders();
2539
- const response = await fetch(`${this.baseUrl}/api/v2/jit/deploy`, {
2540
- method: "POST",
2541
- headers: {
2542
- "Content-Type": "application/json",
2543
- ...authHeaders
2544
- },
2545
- body: JSON.stringify({
2546
- glama_id: options.glamaId,
2547
- glama_namespace: options.glamaNamespace,
2548
- glama_slug: options.glamaSlug,
2549
- tool_name: options.toolName,
2550
- tool_description: options.toolDescription,
2551
- env_vars: options.envVars,
2552
- ttl_hours: options.ttlHours || 24
2553
- // session_id not needed - derived from X-Session-Auth
2554
- })
2555
- });
2556
- if (!response.ok) {
2557
- const error = await response.json().catch(() => ({}));
2558
- throw new MixrPayError(error.error || `JIT deploy failed: ${response.status}`);
2559
- }
2560
- const data = await response.json();
2561
- if (data.payment?.amount_usd > 0) {
2562
- const payment = {
2563
- amountUsd: data.payment.amount_usd,
2564
- recipient: "mixrpay-jit-deploy",
2565
- txHash: data.payment.tx_hash,
2566
- timestamp: /* @__PURE__ */ new Date(),
2567
- description: `JIT Deploy: ${options.toolName}`,
2568
- url: `${this.baseUrl}/api/v2/jit/deploy`,
2569
- requestId: data.request_id || crypto.randomUUID()
2570
- };
2571
- this.payments.push(payment);
2572
- this.totalSpentUsd += data.payment.amount_usd;
2573
- this.logger.payment(data.payment.amount_usd, "jit-deploy", options.toolName);
2574
- if (this.onPayment) {
2575
- this.onPayment(payment);
2576
- }
2577
- }
2578
- return {
2579
- instance: this.parseJitInstance(data.instance),
2580
- payment: {
2581
- method: data.payment.method,
2582
- amountUsd: data.payment.amount_usd,
2583
- txHash: data.payment.tx_hash
2584
- }
2585
- };
2586
- }
2587
- /**
2588
- * List your deployed JIT MCP server instances.
2589
- *
2590
- * @param options - Optional filters
2591
- * @returns Array of JIT instances
2592
- *
2593
- * @example
2594
- * ```typescript
2595
- * const instances = await wallet.listJitInstances({ status: 'active' });
2596
- * for (const inst of instances) {
2597
- * console.log(`${inst.toolName}: ${inst.endpointUrl}`);
2598
- * }
2599
- * ```
2600
- */
2601
- async listJitInstances(options) {
2602
- this.logger.debug("listJitInstances", options);
2603
- const authHeaders = await this.getSessionAuthHeaders();
2604
- const params = new URLSearchParams();
2605
- if (options?.status) params.set("status", options.status);
2606
- const response = await fetch(
2607
- `${this.baseUrl}/api/v2/jit/instances?${params}`,
2608
- { headers: authHeaders }
2609
- );
2610
- if (!response.ok) {
2611
- const error = await response.json().catch(() => ({}));
2612
- throw new MixrPayError(error.error || `Failed to list JIT instances: ${response.status}`);
2613
- }
2614
- const data = await response.json();
2615
- return (data.instances || []).map((i) => this.parseJitInstance(i));
2616
- }
2617
- /**
2618
- * Stop a running JIT MCP server instance.
2619
- *
2620
- * Instance will be marked as stopped and Worker cleaned up.
2621
- * No refund is given - instances are billed at deploy time.
2622
- *
2623
- * @param instanceId - The instance ID to stop
2624
- *
2625
- * @example
2626
- * ```typescript
2627
- * await wallet.stopJitInstance('inst_abc123');
2628
- * console.log('Instance stopped');
2629
- * ```
2630
- */
2631
- async stopJitInstance(instanceId) {
2632
- this.logger.debug("stopJitInstance", { instanceId });
2633
- const authHeaders = await this.getSessionAuthHeaders();
2634
- const response = await fetch(
2635
- `${this.baseUrl}/api/v2/jit/instances/${instanceId}`,
2636
- { method: "DELETE", headers: authHeaders }
2637
- );
2638
- if (!response.ok) {
2639
- const error = await response.json().catch(() => ({}));
2640
- throw new MixrPayError(error.error || `Failed to stop JIT instance: ${response.status}`);
2641
- }
2642
- }
2643
- /**
2644
- * Parse JIT instance response data.
2645
- */
2646
- parseJitInstance(data) {
2647
- return {
2648
- id: data.id,
2649
- endpointUrl: data.endpoint_url,
2650
- toolName: data.tool_name,
2651
- glamaId: data.glama_id,
2652
- glamaNamespace: data.glama_namespace,
2653
- glamaSlug: data.glama_slug,
2654
- status: data.status,
2655
- mode: data.mode,
2656
- ttlHours: data.ttl_hours,
2657
- expiresAt: new Date(data.expires_at),
2658
- createdAt: new Date(data.created_at)
2659
- };
2660
- }
2661
- /**
2662
- * Get details of a specific JIT MCP server instance.
2663
- *
2664
- * @param instanceId - The instance ID to retrieve
2665
- * @returns Full instance details including endpoint URL
2666
- *
2667
- * @example
2668
- * ```typescript
2669
- * const instance = await wallet.getJitInstance('inst_abc123');
2670
- * console.log('Endpoint:', instance.endpointUrl);
2671
- * console.log('Expires:', instance.expiresAt);
2672
- * ```
2673
- */
2674
- async getJitInstance(instanceId) {
2675
- this.logger.debug("getJitInstance", { instanceId });
2676
- const authHeaders = await this.getSessionAuthHeaders();
2677
- const response = await fetch(
2678
- `${this.baseUrl}/api/v2/jit/instances/${instanceId}`,
2679
- { headers: authHeaders }
2680
- );
2681
- if (!response.ok) {
2682
- const error = await response.json().catch(() => ({}));
2683
- throw new MixrPayError(error.error || `Failed to get JIT instance: ${response.status}`);
2684
- }
2685
- const data = await response.json();
2686
- return this.parseJitInstance(data.instance);
2687
- }
2688
- // ===========================================================================
2689
- // Glama MCP Directory Methods
2690
- // ===========================================================================
2691
- /**
2692
- * Search the Glama MCP server directory.
2693
- *
2694
- * Glama indexes 15,000+ MCP servers. Use this to discover tools
2695
- * that can be deployed as JIT servers.
2696
- *
2697
- * Note: This is a public API and does not require authentication.
2698
- *
2699
- * @param query - Search query (e.g., "notion", "github", "database")
2700
- * @returns Array of matching servers with hosting info
2701
- *
2702
- * @example
2703
- * ```typescript
2704
- * const results = await wallet.searchGlamaDirectory('notion');
2705
- *
2706
- * // Filter to only hostable servers
2707
- * const hostable = results.servers.filter(s => s.canHost);
2708
- * console.log(`Found ${hostable.length} deployable servers`);
2709
- *
2710
- * // Deploy one
2711
- * if (hostable.length > 0) {
2712
- * const server = hostable[0];
2713
- * await wallet.deployJitMcp({
2714
- * glamaId: server.id,
2715
- * glamaNamespace: server.namespace,
2716
- * glamaSlug: server.slug,
2717
- * toolName: server.name,
2718
- * envVars: { API_KEY: '...' },
2719
- * });
2720
- * }
2721
- * ```
2722
- */
2723
- async searchGlamaDirectory(query) {
2724
- this.logger.debug("searchGlamaDirectory", { query });
2725
- const params = new URLSearchParams({ q: query });
2726
- const response = await fetch(`${this.baseUrl}/api/mcp/glama?${params}`);
2727
- if (!response.ok) {
2728
- const error = await response.json().catch(() => ({}));
2729
- throw new MixrPayError(error.error || `Glama search failed: ${response.status}`);
2730
- }
2731
- const data = await response.json();
2732
- return {
2733
- servers: (data.servers || []).map((s) => this.parseGlamaServer(s)),
2734
- pageInfo: data.pageInfo,
2735
- query: data.query
2736
- };
2737
- }
2738
- /**
2739
- * Get featured/popular MCP servers from the Glama directory.
2740
- *
2741
- * Returns curated list of popular servers when you don't have
2742
- * a specific search query.
2743
- *
2744
- * Note: This is a public API and does not require authentication.
2745
- *
2746
- * @returns Array of featured servers with hosting info
2747
- *
2748
- * @example
2749
- * ```typescript
2750
- * const { servers } = await wallet.getFeaturedGlamaServers();
2751
- * console.log('Featured servers:', servers.map(s => s.name));
2752
- * ```
2753
- */
2754
- async getFeaturedGlamaServers() {
2755
- this.logger.debug("getFeaturedGlamaServers");
2756
- const response = await fetch(`${this.baseUrl}/api/mcp/glama`);
2757
- if (!response.ok) {
2758
- const error = await response.json().catch(() => ({}));
2759
- throw new MixrPayError(error.error || `Failed to get featured servers: ${response.status}`);
2760
- }
2761
- const data = await response.json();
2762
- return {
2763
- servers: (data.servers || []).map((s) => this.parseGlamaServer(s)),
2764
- featured: data.featured
2765
- };
2766
- }
2767
- /**
2768
- * Parse Glama server response data.
2769
- */
2770
- parseGlamaServer(data) {
2771
- const importData = data.importData;
2772
- return {
2773
- id: data.id,
2774
- name: data.name,
2775
- namespace: data.namespace,
2776
- slug: data.slug,
2777
- description: data.description,
2778
- url: data.url,
2779
- attributes: data.attributes,
2780
- canHost: data.canHost,
2781
- tools: data.tools || [],
2782
- repository: data.repository,
2783
- license: data.spdxLicense?.name,
2784
- importData: importData ? {
2785
- glamaId: importData.glamaId,
2786
- glamaNamespace: importData.glamaNamespace,
2787
- glamaSlug: importData.glamaSlug,
2788
- suggestedName: importData.suggestedName,
2789
- suggestedDescription: importData.suggestedDescription,
2790
- hostingType: importData.hostingType,
2791
- requiredEnvVars: importData.requiredEnvVars,
2792
- optionalEnvVars: importData.optionalEnvVars
2793
- } : void 0
2794
- };
2795
- }
2796
- // ===========================================================================
2797
- // JIT Task Agent Methods
2798
- // ===========================================================================
2799
- /**
2800
- * Deploy a JIT Task Agent - a serverless agent that executes a specific task.
2801
- *
2802
- * JIT Task Agents run on Cloudflare Workers and execute an agentic loop
2803
- * (LLM + tools) within a budget cap. They self-destruct when complete.
2804
- *
2805
- * @param options - Task agent deployment options
2806
- * @returns Deployed task agent instance with endpoints
2807
- *
2808
- * @example Basic usage
2809
- * ```typescript
2810
- * const result = await wallet.deployTaskAgent({
2811
- * name: 'Research Agent',
2812
- * prompt: 'Research the top 5 AI startups in San Francisco',
2813
- * budgetUsd: 5.00,
2814
- * tools: ['platform/exa-search', 'platform/firecrawl-scrape'],
2815
- * });
2816
- *
2817
- * console.log('Task ID:', result.instance.id);
2818
- * console.log('Status URL:', result.instance.statusUrl);
2819
- * ```
2820
- *
2821
- * @example With auto-run
2822
- * ```typescript
2823
- * const result = await wallet.deployTaskAgent({
2824
- * name: 'Data Collector',
2825
- * prompt: 'Collect pricing data from competitor websites',
2826
- * budgetUsd: 10.00,
2827
- * tools: ['platform/firecrawl-scrape'],
2828
- * autoRun: true, // Start immediately
2829
- * });
2830
- *
2831
- * // Wait for completion
2832
- * const finalResult = await wallet.waitForTaskAgent(result.instance.id);
2833
- * console.log('Result:', finalResult.result);
2834
- * ```
2835
- */
2836
- async deployTaskAgent(options) {
2837
- this.logger.debug("deployTaskAgent", { name: options.name, budgetUsd: options.budgetUsd });
2838
- const authHeaders = await this.getSessionAuthHeaders();
2839
- const response = await fetch(`${this.baseUrl}/api/v2/jit-task/deploy`, {
2840
- method: "POST",
2841
- headers: {
2842
- "Content-Type": "application/json",
2843
- ...authHeaders
2844
- },
2845
- body: JSON.stringify({
2846
- name: options.name,
2847
- prompt: options.prompt,
2848
- system_prompt: options.systemPrompt,
2849
- model: options.model || "claude-sonnet-4-5",
2850
- tools: options.tools || [],
2851
- budget_usd: options.budgetUsd,
2852
- ttl_hours: options.ttlHours || 24,
2853
- max_iterations: options.maxIterations || 10,
2854
- plan_id: options.planId,
2855
- task_id: options.taskId,
2856
- idempotency_key: options.idempotencyKey,
2857
- auto_run: options.autoRun || false
2858
- })
2859
- });
2860
- if (!response.ok) {
2861
- const error = await response.json().catch(() => ({}));
2862
- throw new MixrPayError(error.error || `Task agent deploy failed: ${response.status}`);
2863
- }
2864
- const data = await response.json();
2865
- return {
2866
- instance: this.parseTaskAgentInstance(data.instance),
2867
- idempotent: data.idempotent || false,
2868
- requestId: data.request_id
2869
- };
2870
- }
2871
- /**
2872
- * Get the status of a JIT Task Agent.
2873
- *
2874
- * @param instanceId - The task agent instance ID
2875
- * @returns Current status and details
2876
- *
2877
- * @example
2878
- * ```typescript
2879
- * const status = await wallet.getTaskAgentStatus('cuid_abc123');
2880
- * console.log('Status:', status.status);
2881
- * console.log('Iterations:', status.iterations.current, '/', status.iterations.max);
2882
- * console.log('Spent:', status.budget.spentUsd, '/', status.budget.totalUsd);
2883
- * ```
2884
- */
2885
- async getTaskAgentStatus(instanceId) {
2886
- this.logger.debug("getTaskAgentStatus", { instanceId });
2887
- const authHeaders = await this.getSessionAuthHeaders();
2888
- const response = await fetch(`${this.baseUrl}/api/v2/jit-task/${instanceId}`, {
2889
- method: "GET",
2890
- headers: authHeaders
2891
- });
2892
- if (!response.ok) {
2893
- const error = await response.json().catch(() => ({}));
2894
- throw new MixrPayError(error.error || `Failed to get task status: ${response.status}`);
2895
- }
2896
- const data = await response.json();
2897
- return this.parseTaskAgentStatus(data);
2898
- }
2899
- /**
2900
- * Trigger execution of a JIT Task Agent.
2901
- *
2902
- * Only works for agents in 'active' status (not yet started).
2903
- *
2904
- * @param instanceId - The task agent instance ID
2905
- * @returns Trigger result
2906
- *
2907
- * @example
2908
- * ```typescript
2909
- * // Deploy without auto-run
2910
- * const { instance } = await wallet.deployTaskAgent({
2911
- * name: 'Research',
2912
- * prompt: 'Research AI trends',
2913
- * budgetUsd: 5.00,
2914
- * });
2915
- *
2916
- * // Later, trigger execution
2917
- * await wallet.triggerTaskAgent(instance.id);
2918
- * ```
2919
- */
2920
- async triggerTaskAgent(instanceId) {
2921
- this.logger.debug("triggerTaskAgent", { instanceId });
2922
- const authHeaders = await this.getSessionAuthHeaders();
2923
- const response = await fetch(`${this.baseUrl}/api/v2/jit-task/${instanceId}`, {
2924
- method: "POST",
2925
- headers: {
2926
- "Content-Type": "application/json",
2927
- ...authHeaders
2928
- }
2929
- });
2930
- if (!response.ok) {
2931
- const error = await response.json().catch(() => ({}));
2932
- throw new MixrPayError(error.error || `Failed to trigger task: ${response.status}`);
2933
- }
2934
- const data = await response.json();
2935
- return {
2936
- success: data.success,
2937
- status: data.status
2938
- };
2939
- }
2940
- /**
2941
- * Cancel a JIT Task Agent.
2942
- *
2943
- * Stops execution and marks the task as cancelled.
2944
- * Cannot cancel tasks that are already completed/failed.
2945
- *
2946
- * @param instanceId - The task agent instance ID
2947
- * @returns Cancel result
2948
- *
2949
- * @example
2950
- * ```typescript
2951
- * await wallet.cancelTaskAgent('cuid_abc123');
2952
- * console.log('Task cancelled');
2953
- * ```
2954
- */
2955
- async cancelTaskAgent(instanceId) {
2956
- this.logger.debug("cancelTaskAgent", { instanceId });
2957
- const authHeaders = await this.getSessionAuthHeaders();
2958
- const response = await fetch(`${this.baseUrl}/api/v2/jit-task/${instanceId}`, {
2959
- method: "DELETE",
2960
- headers: authHeaders
2961
- });
2962
- if (!response.ok) {
2963
- const error = await response.json().catch(() => ({}));
2964
- throw new MixrPayError(error.error || `Failed to cancel task: ${response.status}`);
2965
- }
2966
- const data = await response.json();
2967
- return {
2968
- success: data.success,
2969
- status: data.status
2970
- };
2971
- }
2972
- /**
2973
- * List JIT Task Agents for the authenticated user.
2974
- *
2975
- * Returns deployed task agents with optional filtering by status,
2976
- * plan, or task. Includes pagination and summary statistics.
2977
- *
2978
- * @param options - Optional filter and pagination parameters
2979
- * @returns List of task agents with pagination and stats
2980
- *
2981
- * @example List all task agents
2982
- * ```typescript
2983
- * const { taskAgents, pagination, stats } = await wallet.listTaskAgents();
2984
- * console.log(`${pagination.total} total agents, ${stats.active} active`);
2985
- * ```
2986
- *
2987
- * @example Filter by status
2988
- * ```typescript
2989
- * const { taskAgents } = await wallet.listTaskAgents({ status: 'running' });
2990
- * for (const agent of taskAgents) {
2991
- * console.log(`${agent.name}: $${agent.budget.spentUsd}/$${agent.budget.totalUsd}`);
2992
- * }
2993
- * ```
2994
- *
2995
- * @example Filter by plan
2996
- * ```typescript
2997
- * const { taskAgents } = await wallet.listTaskAgents({ planId: 'plan_abc' });
2998
- * ```
2999
- */
3000
- async listTaskAgents(options) {
3001
- this.logger.debug("listTaskAgents", { options });
3002
- const authHeaders = await this.getSessionAuthHeaders();
3003
- const searchParams = new URLSearchParams();
3004
- if (options?.status) searchParams.set("status", options.status);
3005
- if (options?.planId) searchParams.set("plan_id", options.planId);
3006
- if (options?.taskId) searchParams.set("task_id", options.taskId);
3007
- if (options?.limit !== void 0) searchParams.set("limit", String(options.limit));
3008
- if (options?.offset !== void 0) searchParams.set("offset", String(options.offset));
3009
- const qs = searchParams.toString();
3010
- const url = `${this.baseUrl}/api/v2/jit-task${qs ? `?${qs}` : ""}`;
3011
- const response = await fetch(url, {
3012
- method: "GET",
3013
- headers: authHeaders
3014
- });
3015
- if (!response.ok) {
3016
- const error = await response.json().catch(() => ({}));
3017
- throw new MixrPayError(error.error || `Failed to list task agents: ${response.status}`);
3018
- }
3019
- const data = await response.json();
3020
- return {
3021
- taskAgents: (data.task_agents || []).map((agent) => {
3022
- const budget = agent.budget;
3023
- const iterations = agent.iterations;
3024
- const usage = agent.usage;
3025
- const plan = agent.plan;
3026
- const task = agent.task;
3027
- return {
3028
- id: agent.id,
3029
- name: agent.name,
3030
- prompt: agent.prompt,
3031
- model: agent.model,
3032
- tools: agent.tools,
3033
- status: agent.status,
3034
- budget: {
3035
- totalUsd: budget.total_usd,
3036
- spentUsd: budget.spent_usd,
3037
- remainingUsd: budget.remaining_usd
3038
- },
3039
- iterations: {
3040
- current: iterations.current,
3041
- max: iterations.max
3042
- },
3043
- usage: {
3044
- toolCalls: usage.tool_calls,
3045
- inputTokens: usage.input_tokens,
3046
- outputTokens: usage.output_tokens
3047
- },
3048
- result: agent.result,
3049
- error: agent.error,
3050
- depth: agent.depth,
3051
- plan: plan ? { id: plan.id, title: plan.title } : null,
3052
- task: task ? { id: task.id, title: task.title } : null,
3053
- ttlHours: agent.ttl_hours,
3054
- expiresAt: new Date(agent.expires_at),
3055
- createdAt: new Date(agent.created_at),
3056
- startedAt: agent.started_at ? new Date(agent.started_at) : void 0,
3057
- completedAt: agent.completed_at ? new Date(agent.completed_at) : void 0
3058
- };
3059
- }),
3060
- pagination: {
3061
- total: data.pagination.total,
3062
- limit: data.pagination.limit,
3063
- offset: data.pagination.offset,
3064
- hasMore: data.pagination.has_more
3065
- },
3066
- stats: {
3067
- active: data.stats.active ?? 0,
3068
- completed: data.stats.completed ?? 0,
3069
- failed: data.stats.failed ?? 0,
3070
- totalSpentUsd: data.stats.total_spent_usd ?? 0
3071
- }
3072
- };
3073
- }
3074
- /**
3075
- * Wait for a JIT Task Agent to complete.
3076
- *
3077
- * Polls the status until the task reaches a terminal state
3078
- * (completed, failed, cancelled, budget_exceeded, expired).
3079
- *
3080
- * @param instanceId - The task agent instance ID
3081
- * @param options - Wait options
3082
- * @returns Final task result
3083
- *
3084
- * @example
3085
- * ```typescript
3086
- * const result = await wallet.waitForTaskAgent('cuid_abc123', {
3087
- * pollIntervalMs: 2000,
3088
- * timeoutMs: 300000, // 5 minutes
3089
- * });
3090
- *
3091
- * if (result.status === 'completed') {
3092
- * console.log('Result:', result.result);
3093
- * } else {
3094
- * console.log('Failed:', result.error);
3095
- * }
3096
- * ```
3097
- */
3098
- async waitForTaskAgent(instanceId, options) {
3099
- const pollIntervalMs = options?.pollIntervalMs || 2e3;
3100
- const timeoutMs = options?.timeoutMs || 3e5;
3101
- const startTime = Date.now();
3102
- this.logger.debug("waitForTaskAgent", { instanceId, pollIntervalMs, timeoutMs });
3103
- while (true) {
3104
- const status = await this.getTaskAgentStatus(instanceId);
3105
- if (["completed", "failed", "cancelled", "budget_exceeded", "expired"].includes(status.status)) {
3106
- return {
3107
- id: status.id,
3108
- status: status.status,
3109
- result: status.result,
3110
- error: status.error,
3111
- spentUsd: status.budget.spentUsd,
3112
- iterations: status.iterations.current,
3113
- toolCalls: status.usage.toolCalls,
3114
- completedAt: status.completedAt
3115
- };
3116
- }
3117
- if (Date.now() - startTime > timeoutMs) {
3118
- throw new MixrPayError(`Task agent wait timeout after ${timeoutMs}ms`);
3119
- }
3120
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
3121
- }
3122
- }
3123
- /**
3124
- * Parse task agent instance from API response.
3125
- */
3126
- parseTaskAgentInstance(data) {
3127
- return {
3128
- id: data.id,
3129
- name: data.name,
3130
- endpointUrl: data.endpoint_url,
3131
- statusUrl: data.status_url,
3132
- triggerUrl: data.trigger_url,
3133
- cancelUrl: data.cancel_url,
3134
- resultUrl: data.result_url,
3135
- status: data.status,
3136
- budgetUsd: data.budget_usd,
3137
- expiresAt: new Date(data.expires_at),
3138
- depth: data.depth,
3139
- maxIterations: data.max_iterations
3140
- };
3141
- }
3142
- /**
3143
- * Parse task agent status from API response.
3144
- */
3145
- parseTaskAgentStatus(data) {
3146
- const budget = data.budget;
3147
- const iterations = data.iterations;
3148
- const usage = data.usage;
3149
- const endpoints = data.endpoints;
3150
- return {
3151
- id: data.id,
3152
- name: data.name,
3153
- prompt: data.prompt,
3154
- model: data.model,
3155
- tools: data.tools,
3156
- status: data.status,
3157
- budget: {
3158
- totalUsd: budget?.total_usd ?? 0,
3159
- spentUsd: budget?.spent_usd ?? 0,
3160
- remainingUsd: budget?.remaining_usd ?? 0
3161
- },
3162
- iterations: {
3163
- current: iterations?.current ?? 0,
3164
- max: iterations?.max ?? 0
3165
- },
3166
- usage: {
3167
- toolCalls: usage?.tool_calls ?? 0,
3168
- inputTokens: usage?.input_tokens ?? 0,
3169
- outputTokens: usage?.output_tokens ?? 0
3170
- },
3171
- result: data.result,
3172
- error: data.error,
3173
- depth: data.depth,
3174
- planId: data.plan_id,
3175
- taskId: data.task_id,
3176
- endpoints: {
3177
- statusUrl: endpoints?.status_url ?? "",
3178
- triggerUrl: endpoints?.trigger_url ?? "",
3179
- cancelUrl: endpoints?.cancel_url ?? "",
3180
- resultUrl: endpoints?.result_url ?? ""
3181
- },
3182
- ttlHours: data.ttl_hours,
3183
- expiresAt: new Date(data.expires_at),
3184
- createdAt: new Date(data.created_at),
3185
- startedAt: data.started_at ? new Date(data.started_at) : void 0,
3186
- completedAt: data.completed_at ? new Date(data.completed_at) : void 0
3187
- };
3188
- }
3189
- // ===========================================================================
3190
- // LLM Completion Methods
3191
- // ===========================================================================
3192
- /**
3193
- * Simple LLM completion - single-turn, no tools.
3194
- *
3195
- * This is a convenience method for agents that just need to call an LLM
3196
- * without the full agentic loop. Useful when Clawdbot spawns agents
3197
- * that need to make their own LLM calls through MixrPay.
3198
- *
3199
- * @param prompt - The user prompt to send
3200
- * @param options - Optional configuration
3201
- * @returns The LLM response text and cost
3202
- *
3203
- * @example Basic usage
3204
- * ```typescript
3205
- * const result = await wallet.complete('Summarize this text: ...');
3206
- * console.log(result.text);
3207
- * console.log(`Cost: $${result.costUsd.toFixed(4)}`);
3208
- * ```
3209
- *
3210
- * @example With custom model
3211
- * ```typescript
3212
- * const result = await wallet.complete(
3213
- * 'Write a haiku about coding',
3214
- * { model: 'gpt-4o', systemPrompt: 'You are a poet.' }
3215
- * );
3216
- * ```
3217
- */
3218
- async complete(prompt, options) {
3219
- this.logger.debug("complete", { promptLength: prompt.length, model: options?.model });
3220
- const result = await this.runAgent({
3221
- messages: [{ role: "user", content: prompt }],
3222
- config: {
3223
- model: options?.model || "gpt-4o-mini",
3224
- maxIterations: 1,
3225
- tools: [],
3226
- // No tools - pure LLM completion
3227
- systemPrompt: options?.systemPrompt
3228
- }
3229
- });
3230
- return {
3231
- text: result.response,
3232
- costUsd: result.cost.totalUsd,
3233
- tokens: result.tokens,
3234
- model: options?.model || "gpt-4o-mini"
3235
- };
3236
- }
3237
- // ===========================================================================
3238
- // Agent Runtime API
3239
- // ===========================================================================
3240
- /**
3241
- * Run an AI agent with LLM and tool execution.
3242
- *
3243
- * This method orchestrates a full agentic loop:
3244
- * - Multi-turn reasoning with LLM
3245
- * - Automatic tool execution
3246
- * - Bundled billing (single charge at end)
3247
- * - Optional streaming via SSE
3248
- *
3249
- * @param options - Agent run options
3250
- * @returns Agent run result with response and cost breakdown
3251
- *
3252
- * @example Basic usage
3253
- * ```typescript
3254
- * const result = await wallet.runAgent({
3255
- * sessionId: 'sess_abc123',
3256
- * messages: [{ role: 'user', content: 'Find AI startups in SF' }],
3257
- * });
3258
- *
3259
- * console.log(result.response);
3260
- * console.log(`Cost: $${result.cost.totalUsd.toFixed(4)}`);
3261
- * ```
3262
- *
3263
- * @example With custom config
3264
- * ```typescript
3265
- * const result = await wallet.runAgent({
3266
- * sessionId: 'sess_abc123',
3267
- * messages: [{ role: 'user', content: 'Research quantum computing' }],
3268
- * config: {
3269
- * model: 'gpt-4o',
3270
- * maxIterations: 15,
3271
- * tools: ['platform/exa-search', 'platform/firecrawl-scrape'],
3272
- * systemPrompt: 'You are a research assistant.',
3273
- * },
3274
- * });
3275
- * ```
3276
- *
3277
- * @example With streaming
3278
- * ```typescript
3279
- * await wallet.runAgent({
3280
- * sessionId: 'sess_abc123',
3281
- * messages: [{ role: 'user', content: 'Analyze this company' }],
3282
- * stream: true,
3283
- * onEvent: (event) => {
3284
- * if (event.type === 'llm_chunk') {
3285
- * process.stdout.write(event.delta);
3286
- * } else if (event.type === 'tool_call') {
3287
- * console.log(`Calling tool: ${event.tool}`);
3288
- * }
3289
- * },
3290
- * });
3291
- * ```
3292
- */
3293
- async runAgent(options) {
3294
- const {
3295
- sessionId,
3296
- messages,
3297
- config = {},
3298
- stream = false,
3299
- idempotencyKey,
3300
- onEvent
3301
- } = options;
3302
- this.logger.debug("runAgent", { sessionId: sessionId || "(from signature)", messageCount: messages.length, config, stream });
3303
- const body = {
3304
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
3305
- config: {
3306
- model: config.model,
3307
- max_iterations: config.maxIterations,
3308
- tools: config.tools,
3309
- system_prompt: config.systemPrompt
3310
- },
3311
- stream,
3312
- idempotency_key: idempotencyKey
3313
- };
3314
- if (sessionId) {
3315
- body.session_id = sessionId;
3316
- }
3317
- const AGENT_RUN_TIMEOUT = 18e4;
3318
- if (!stream) {
3319
- const authHeaders = await this.getSessionAuthHeaders();
3320
- const response = await fetch(`${this.baseUrl}/api/v2/agent/run`, {
3321
- method: "POST",
3322
- headers: {
3323
- "Content-Type": "application/json",
3324
- ...authHeaders
3325
- },
3326
- body: JSON.stringify(body),
3327
- signal: AbortSignal.timeout(AGENT_RUN_TIMEOUT)
3328
- });
3329
- if (!response.ok) {
3330
- const error = await response.json().catch(() => ({}));
3331
- throw new MixrPayError(error.error || `Agent run failed: ${response.status}`);
3332
- }
3333
- const data = await response.json();
3334
- if (data.cost?.total_usd > 0) {
3335
- const payment = {
3336
- amountUsd: data.cost.total_usd,
3337
- recipient: "mixrpay-agent-run",
3338
- txHash: data.tx_hash,
3339
- timestamp: /* @__PURE__ */ new Date(),
3340
- description: `Agent run: ${data.run_id}`,
3341
- url: `${this.baseUrl}/api/v2/agent/run`,
3342
- requestId: idempotencyKey || crypto.randomUUID()
3343
- };
3344
- this.payments.push(payment);
3345
- this.totalSpentUsd += data.cost.total_usd;
3346
- this.logger.payment(data.cost.total_usd, "agent-run", data.run_id);
3347
- if (this.onPayment) {
3348
- this.onPayment(payment);
3349
- }
3350
- }
3351
- return {
3352
- runId: data.run_id,
3353
- status: data.status,
3354
- response: data.response,
3355
- iterations: data.iterations,
3356
- toolsUsed: data.tools_used,
3357
- cost: {
3358
- llmUsd: data.cost.llm_usd,
3359
- toolsUsd: data.cost.tools_usd,
3360
- totalUsd: data.cost.total_usd
3361
- },
3362
- tokens: data.tokens,
3363
- sessionRemainingUsd: data.session_remaining_usd,
3364
- txHash: data.tx_hash
3365
- };
3366
- }
3367
- return this.runAgentStreaming(body, onEvent);
3368
- }
3369
- /**
3370
- * Internal: Handle streaming agent run via SSE
3371
- */
3372
- async runAgentStreaming(body, onEvent) {
3373
- const STREAMING_TIMEOUT = 3e5;
3374
- const authHeaders = await this.getSessionAuthHeaders();
3375
- const response = await fetch(`${this.baseUrl}/api/v2/agent/run`, {
3376
- method: "POST",
3377
- headers: {
3378
- "Content-Type": "application/json",
3379
- ...authHeaders
3380
- },
3381
- body: JSON.stringify(body),
3382
- signal: AbortSignal.timeout(STREAMING_TIMEOUT)
3383
- });
3384
- if (!response.ok) {
3385
- const error = await response.json().catch(() => ({}));
3386
- throw new MixrPayError(error.error || `Agent run failed: ${response.status}`);
3387
- }
3388
- const reader = response.body?.getReader();
3389
- if (!reader) {
3390
- throw new MixrPayError("No response body for streaming");
3391
- }
3392
- const decoder = new TextDecoder();
3393
- let buffer = "";
3394
- let result = null;
3395
- while (true) {
3396
- const { done, value } = await reader.read();
3397
- if (done) break;
3398
- buffer += decoder.decode(value, { stream: true });
3399
- const lines = buffer.split("\n");
3400
- buffer = lines.pop() || "";
3401
- let currentEvent = "";
3402
- for (const line of lines) {
3403
- if (line.startsWith("event: ")) {
3404
- currentEvent = line.slice(7).trim();
3405
- } else if (line.startsWith("data: ") && currentEvent) {
3406
- try {
3407
- const data = JSON.parse(line.slice(6));
3408
- const event = this.parseSSEEvent(currentEvent, data);
3409
- if (event) {
3410
- onEvent?.(event);
3411
- if (currentEvent === "complete") {
3412
- result = {
3413
- runId: data.run_id,
3414
- status: "completed",
3415
- response: data.response,
3416
- iterations: data.iterations,
3417
- toolsUsed: data.tools_used,
3418
- cost: {
3419
- llmUsd: 0,
3420
- // Not provided in streaming complete
3421
- toolsUsd: 0,
3422
- totalUsd: data.total_cost_usd
3423
- },
3424
- tokens: { prompt: 0, completion: 0 },
3425
- sessionRemainingUsd: 0,
3426
- txHash: data.tx_hash
3427
- };
3428
- if (data.total_cost_usd > 0) {
3429
- const payment = {
3430
- amountUsd: data.total_cost_usd,
3431
- recipient: "mixrpay-agent-run",
3432
- txHash: data.tx_hash,
3433
- timestamp: /* @__PURE__ */ new Date(),
3434
- description: `Agent run: ${data.run_id}`,
3435
- url: `${this.baseUrl}/api/v2/agent/run`,
3436
- requestId: body.idempotency_key || crypto.randomUUID()
3437
- };
3438
- this.payments.push(payment);
3439
- this.totalSpentUsd += data.total_cost_usd;
3440
- if (this.onPayment) {
3441
- this.onPayment(payment);
3442
- }
3443
- }
3444
- }
3445
- if (currentEvent === "error") {
3446
- throw new MixrPayError(data.error || "Agent run failed");
3447
- }
3448
- }
3449
- } catch (e) {
3450
- if (e instanceof MixrPayError) throw e;
3451
- this.logger.warn("Failed to parse SSE event:", e);
3452
- }
3453
- currentEvent = "";
3454
- }
3455
- }
3456
- }
3457
- if (!result) {
3458
- throw new MixrPayError("Agent run completed without final result");
3459
- }
3460
- return result;
3461
- }
3462
- /**
3463
- * Internal: Parse SSE event into typed event object
3464
- */
3465
- parseSSEEvent(eventType, data) {
3466
- switch (eventType) {
3467
- case "run_start":
3468
- return { type: "run_start", runId: data.run_id };
3469
- case "iteration_start":
3470
- return { type: "iteration_start", iteration: data.iteration };
3471
- case "llm_chunk":
3472
- return { type: "llm_chunk", delta: data.delta };
3473
- case "tool_call":
3474
- return { type: "tool_call", tool: data.tool, arguments: data.arguments };
3475
- case "tool_result":
3476
- return {
3477
- type: "tool_result",
3478
- tool: data.tool,
3479
- success: data.success,
3480
- costUsd: data.cost_usd,
3481
- error: data.error
3482
- };
3483
- case "iteration_complete":
3484
- return {
3485
- type: "iteration_complete",
3486
- iteration: data.iteration,
3487
- tokens: data.tokens,
3488
- costUsd: data.cost_usd
3489
- };
3490
- case "complete":
3491
- return {
3492
- type: "complete",
3493
- runId: data.run_id,
3494
- response: data.response,
3495
- totalCostUsd: data.total_cost_usd,
3496
- txHash: data.tx_hash,
3497
- iterations: data.iterations,
3498
- toolsUsed: data.tools_used
3499
- };
3500
- case "error":
3501
- return {
3502
- type: "error",
3503
- error: data.error,
3504
- partialCostUsd: data.partial_cost_usd
3505
- };
3506
- default:
3507
- return null;
3508
- }
3509
- }
3510
- /**
3511
- * Get the status of an agent run by ID.
3512
- *
3513
- * @param runId - The agent run ID
3514
- * @param sessionId - The session ID (for authentication)
3515
- * @returns Agent run status and results
3516
- *
3517
- * @example
3518
- * ```typescript
3519
- * const status = await wallet.getAgentRunStatus('run_abc123', 'sess_xyz789');
3520
- * console.log(`Status: ${status.status}`);
3521
- * if (status.status === 'completed') {
3522
- * console.log(status.response);
3523
- * }
3524
- * ```
3525
- */
3526
- async getAgentRunStatus(runId, _sessionId) {
3527
- this.logger.debug("getAgentRunStatus", { runId });
3528
- const authHeaders = await this.getSessionAuthHeaders();
3529
- const response = await fetch(`${this.baseUrl}/api/v2/agent/run/${runId}`, {
3530
- headers: authHeaders
3531
- });
3532
- if (!response.ok) {
3533
- const error = await response.json().catch(() => ({}));
3534
- throw new MixrPayError(error.error || `Failed to get run status: ${response.status}`);
3535
- }
3536
- const data = await response.json();
3537
- return {
3538
- runId: data.run_id,
3539
- status: data.status,
3540
- response: data.response,
3541
- iterations: data.iterations,
3542
- toolsUsed: data.tools_used,
3543
- cost: {
3544
- llmUsd: data.cost.llm_usd,
3545
- toolsUsd: data.cost.tools_usd,
3546
- totalUsd: data.cost.total_usd
3547
- },
3548
- tokens: data.tokens,
3549
- txHash: data.tx_hash,
3550
- error: data.error,
3551
- startedAt: new Date(data.started_at),
3552
- completedAt: data.completed_at ? new Date(data.completed_at) : void 0
3553
- };
3554
- }
3555
- /**
3556
- * Call an MCP tool using session authorization (pre-authorized spending limit).
3557
- *
3558
- * Use this when you've already created a session with the tool provider
3559
- * and want to use that spending limit instead of direct wallet charges.
3560
- *
3561
- * @param sessionId - The session ID for the tool provider
3562
- * @param toolName - The tool name in format "merchant/tool"
3563
- * @param args - Arguments to pass to the tool
3564
- * @returns Tool execution result
3565
- *
3566
- * @example
3567
- * ```typescript
3568
- * // Create session with provider first
3569
- * const session = await wallet.getOrCreateSession({
3570
- * merchantPublicKey: 'pk_live_firecrawl_...',
3571
- * spendingLimitUsd: 50,
3572
- * });
3573
- *
3574
- * // Use session for multiple calls
3575
- * const result = await wallet.callMCPToolWithSession(
3576
- * session.id,
3577
- * 'firecrawl/scrape',
3578
- * { url: 'https://example.com' }
3579
- * );
3580
- * ```
3581
- */
3582
- async callMCPToolWithSession(sessionId, toolName, args = {}) {
3583
- this.logger.debug("callMCPToolWithSession", { sessionId, toolName, args });
3584
- await this.validateMerchantAllowed(toolName, "tool");
3585
- const response = await fetch(`${this.baseUrl}/api/mcp`, {
3586
- method: "POST",
3587
- headers: {
3588
- "Content-Type": "application/json",
3589
- "X-Mixr-Session": sessionId
3590
- },
3591
- body: JSON.stringify({
3592
- jsonrpc: "2.0",
3593
- method: "tools/call",
3594
- params: { name: toolName, arguments: args },
3595
- id: Date.now()
3596
- })
3597
- });
3598
- const result = await response.json();
3599
- if (result.error) {
3600
- throw new MixrPayError(result.error.message || "MCP tool call failed");
3601
- }
3602
- const content = result.result?.content?.[0];
3603
- const data = content?.text ? JSON.parse(content.text) : null;
3604
- const mixrpay = result.result?._mixrpay || {};
3605
- if (mixrpay.chargedUsd) {
3606
- const payment = {
3607
- amountUsd: mixrpay.chargedUsd,
3608
- recipient: toolName.split("/")[0] || toolName,
3609
- txHash: mixrpay.txHash,
3610
- timestamp: /* @__PURE__ */ new Date(),
3611
- description: `MCP: ${toolName}`,
3612
- url: `${this.baseUrl}/api/mcp`,
3613
- requestId: crypto.randomUUID()
3614
- };
3615
- this.payments.push(payment);
3616
- this.totalSpentUsd += mixrpay.chargedUsd;
3617
- this.logger.payment(mixrpay.chargedUsd, toolName, "MCP call (session)");
3618
- if (this.onPayment) {
3619
- this.onPayment(payment);
3620
- }
3621
- }
3622
- return {
3623
- data,
3624
- chargedUsd: mixrpay.chargedUsd || 0,
3625
- txHash: mixrpay.txHash,
3626
- latencyMs: mixrpay.latencyMs
3627
- };
3628
- }
3629
- // ===========================================================================
3630
- // Task Board Methods
3631
- // ===========================================================================
3632
- /**
3633
- * Create a new task on the Task Board.
3634
- *
3635
- * Users (human or agent) can post tasks with budgets for other agents to complete.
3636
- * The listing fee is charged when an agent is accepted, not at creation time.
3637
- *
3638
- * @param params - Task creation parameters
3639
- * @returns The created task
3640
- *
3641
- * @example
3642
- * ```typescript
3643
- * const task = await wallet.createTask({
3644
- * title: 'Research crypto regulations',
3645
- * description: 'Research and summarize crypto regulations in the EU...',
3646
- * budgetUsd: 100,
3647
- * deliverables: ['PDF report', 'Summary document'],
3648
- * category: 'research',
3649
- * });
3650
- * console.log(`Task created: ${task.id}`);
3651
- * ```
3652
- */
3653
- async createTask(params) {
3654
- this.logger.info(`Creating task: ${params.title}`);
3655
- const response = await this.callApi("/api/v2/tasks", {
3656
- method: "POST",
3657
- headers: { "Content-Type": "application/json" },
3658
- body: JSON.stringify({
3659
- title: params.title,
3660
- description: params.description,
3661
- budget_usd: params.budgetUsd,
3662
- deliverables: params.deliverables,
3663
- category: params.category,
3664
- expires_in_days: params.expiresInDays
3665
- })
3666
- });
3667
- const result = await response.json();
3668
- if (!response.ok) {
3669
- throw new MixrPayError(result.error || "Failed to create task");
3670
- }
3671
- return this.parseTask(result.task);
3672
- }
3673
- /**
3674
- * List open tasks on the Task Board.
3675
- *
3676
- * Browse available tasks that agents can request to work on.
3677
- *
3678
- * @param params - Optional filter parameters
3679
- * @returns List of tasks with pagination
3680
- *
3681
- * @example
3682
- * ```typescript
3683
- * const { tasks, pagination } = await wallet.listTasks({
3684
- * minBudget: 50,
3685
- * category: 'research',
3686
- * });
3687
- * console.log(`Found ${pagination.total} matching tasks`);
3688
- * ```
3689
- */
3690
- async listTasks(params) {
3691
- const searchParams = new URLSearchParams();
3692
- if (params?.status) searchParams.set("status", params.status);
3693
- if (params?.category) searchParams.set("category", params.category);
3694
- if (params?.minBudget !== void 0) searchParams.set("min_budget", String(params.minBudget));
3695
- if (params?.maxBudget !== void 0) searchParams.set("max_budget", String(params.maxBudget));
3696
- if (params?.limit !== void 0) searchParams.set("limit", String(params.limit));
3697
- if (params?.offset !== void 0) searchParams.set("offset", String(params.offset));
3698
- const url = `/api/v2/tasks${searchParams.toString() ? `?${searchParams}` : ""}`;
3699
- const response = await this.callApi(url, { method: "GET" });
3700
- const result = await response.json();
3701
- if (!response.ok) {
3702
- throw new MixrPayError(result.error || "Failed to list tasks");
3703
- }
3704
- return {
3705
- tasks: result.tasks.map((t) => this.parseTask(t)),
3706
- pagination: result.pagination
3707
- };
3708
- }
3709
- /**
3710
- * Get details for a specific task.
3711
- *
3712
- * @param taskId - The task ID
3713
- * @returns Task details
3714
- */
3715
- async getTask(taskId) {
3716
- const response = await this.callApi(`/api/v2/tasks/${taskId}`, { method: "GET" });
3717
- const result = await response.json();
3718
- if (!response.ok) {
3719
- throw new MixrPayError(result.error || "Failed to get task");
3720
- }
3721
- return this.parseTask(result.task);
3722
- }
3723
- /**
3724
- * Get tasks created by or assigned to the authenticated user.
3725
- *
3726
- * @param options - Filter and pagination options
3727
- * @returns List of tasks with pagination info
3728
- *
3729
- * @example
3730
- * ```typescript
3731
- * // Get all my tasks
3732
- * const { tasks, pagination } = await wallet.getMyTasks();
3733
- *
3734
- * // Get only tasks I created
3735
- * const created = await wallet.getMyTasks({ role: 'creator' });
3736
- *
3737
- * // Get only tasks assigned to me
3738
- * const assigned = await wallet.getMyTasks({ role: 'agent' });
3739
- *
3740
- * // Filter by status
3741
- * const pending = await wallet.getMyTasks({ status: 'submitted' });
3742
- * ```
3743
- */
3744
- async getMyTasks(options = {}) {
3745
- const params = new URLSearchParams();
3746
- if (options.role) params.set("role", options.role);
3747
- if (options.status) params.set("status", options.status);
3748
- if (options.page) params.set("page", options.page.toString());
3749
- if (options.limit) params.set("limit", options.limit.toString());
3750
- const queryString = params.toString();
3751
- const url = `/api/v2/tasks/my${queryString ? `?${queryString}` : ""}`;
3752
- const response = await this.callApi(url, { method: "GET" });
3753
- const result = await response.json();
3754
- if (!response.ok) {
3755
- throw new MixrPayError(result.error || "Failed to get tasks");
3756
- }
3757
- return {
3758
- tasks: result.tasks.map((t) => ({
3759
- ...this.parseTask(t),
3760
- isCreator: t.is_creator,
3761
- isAgent: t.is_agent
3762
- })),
3763
- pagination: {
3764
- page: result.pagination.page,
3765
- limit: result.pagination.limit,
3766
- total: result.pagination.total,
3767
- totalPages: result.pagination.total_pages
3768
- }
3769
- };
3770
- }
3771
- /**
3772
- * Request to claim a task.
3773
- *
3774
- * Agents use this to express interest in completing a task.
3775
- * The task creator will review requests and accept one agent.
3776
- *
3777
- * @param taskId - The task ID to request
3778
- * @param message - Optional pitch/message to the task creator
3779
- * @returns The created request
3780
- *
3781
- * @example
3782
- * ```typescript
3783
- * const request = await wallet.requestTask('task_123',
3784
- * 'I have experience with crypto research and can deliver within 24 hours.'
3785
- * );
3786
- * console.log(`Request submitted: ${request.id}`);
3787
- * ```
3788
- */
3789
- async requestTask(taskId, message) {
3790
- this.logger.info(`Requesting task: ${taskId}`);
3791
- const response = await this.callApi(`/api/v2/tasks/${taskId}/request`, {
3792
- method: "POST",
3793
- headers: { "Content-Type": "application/json" },
3794
- body: message ? JSON.stringify({ message }) : "{}"
3795
- });
3796
- const result = await response.json();
3797
- if (!response.ok) {
3798
- throw new MixrPayError(result.error || "Failed to request task");
3799
- }
3800
- return {
3801
- id: result.request.id,
3802
- taskId: result.request.task_id,
3803
- status: result.request.status,
3804
- message: result.request.message,
3805
- createdAt: new Date(result.request.created_at)
3806
- };
3807
- }
3808
- /**
3809
- * Get requests for a task you created.
3810
- *
3811
- * @param taskId - The task ID
3812
- * @returns List of agent requests
3813
- */
3814
- async getTaskRequests(taskId) {
3815
- const response = await this.callApi(`/api/v2/tasks/${taskId}/requests`, { method: "GET" });
3816
- const result = await response.json();
3817
- if (!response.ok) {
3818
- throw new MixrPayError(result.error || "Failed to get task requests");
3819
- }
3820
- return result.requests.map((r) => ({
3821
- id: r.id,
3822
- status: r.status,
3823
- message: r.message,
3824
- createdAt: new Date(r.created_at),
3825
- reviewedAt: r.reviewed_at ? new Date(r.reviewed_at) : void 0,
3826
- agent: r.agent
3827
- }));
3828
- }
3829
- /**
3830
- * Accept an agent's request to work on your task.
3831
- *
3832
- * This will:
3833
- * - Charge the listing fee from your wallet
3834
- * - Create a session for the agent with your task budget
3835
- * - Mark the task as claimed
3836
- * - Reject all other pending requests
3837
- *
3838
- * @param taskId - The task ID
3839
- * @param requestId - The request ID to accept
3840
- * @returns Acceptance result with session info
3841
- *
3842
- * @example
3843
- * ```typescript
3844
- * const result = await wallet.acceptTaskRequest('task_123', 'req_456');
3845
- * console.log(`Agent accepted! Session budget: $${result.session.budgetUsd}`);
3846
- * ```
3847
- */
3848
- async acceptTaskRequest(taskId, requestId) {
3849
- this.logger.info(`Accepting request ${requestId} for task ${taskId}`);
3850
- const response = await this.callApi(`/api/v2/tasks/${taskId}/requests/${requestId}/accept`, {
3851
- method: "POST"
3852
- });
3853
- const result = await response.json();
3854
- if (!response.ok) {
3855
- throw new MixrPayError(result.error || "Failed to accept request");
3856
- }
3857
- return {
3858
- success: result.success,
3859
- task: {
3860
- id: result.task.id,
3861
- status: result.task.status,
3862
- agentUserId: result.task.agent_user_id
3863
- },
3864
- session: {
3865
- id: result.session.id,
3866
- sessionKey: result.session.session_key,
3867
- // Agent needs this to authenticate API calls
3868
- address: result.session.address,
3869
- expiresAt: new Date(result.session.expires_at),
3870
- budgetUsd: result.session.budget_usd,
3871
- allowedMerchants: result.session.allowed_merchants || []
3872
- },
3873
- invite: {
3874
- id: result.invite.id,
3875
- code: result.invite.code
3876
- },
3877
- listingFeeTxHash: result.listing_fee_tx_hash
3878
- };
3879
- }
3880
- /**
3881
- * Reject an agent's request.
3882
- *
3883
- * @param taskId - The task ID
3884
- * @param requestId - The request ID to reject
3885
- */
3886
- async rejectTaskRequest(taskId, requestId) {
3887
- const response = await this.callApi(`/api/v2/tasks/${taskId}/requests/${requestId}/reject`, {
3888
- method: "POST"
3889
- });
3890
- const result = await response.json();
3891
- if (!response.ok) {
3892
- throw new MixrPayError(result.error || "Failed to reject request");
3893
- }
3894
- }
3895
- /**
3896
- * Submit deliverables for a task you're working on.
3897
- *
3898
- * After being accepted to work on a task, use this to submit your work
3899
- * for the task creator's review.
3900
- *
3901
- * @param taskId - The task ID
3902
- * @param output - The deliverables (text and/or URL)
3903
- *
3904
- * @example
3905
- * ```typescript
3906
- * await wallet.submitTask('task_123', {
3907
- * text: 'Here is my research report...',
3908
- * url: 'https://docs.google.com/document/d/...',
3909
- * });
3910
- * ```
3911
- */
3912
- async submitTask(taskId, output) {
3913
- this.logger.info(`Submitting task: ${taskId}`);
3914
- const response = await this.callApi(`/api/v2/tasks/${taskId}/submit`, {
3915
- method: "POST",
3916
- headers: { "Content-Type": "application/json" },
3917
- body: JSON.stringify({
3918
- output_text: output.text,
3919
- output_url: output.url
3920
- })
3921
- });
3922
- const result = await response.json();
3923
- if (!response.ok) {
3924
- throw new MixrPayError(result.error || "Failed to submit task");
3925
- }
3926
- }
3927
- /**
3928
- * Approve a submitted task and pay the agent.
3929
- *
3930
- * This will:
3931
- * - Calculate remaining budget (budget - spent on tools)
3932
- * - Transfer remaining budget to the agent's wallet
3933
- * - Mark the task as completed
3934
- * - Revoke the agent's session
3935
- *
3936
- * @param taskId - The task ID
3937
- * @returns Payout details
3938
- *
3939
- * @example
3940
- * ```typescript
3941
- * const result = await wallet.approveTask('task_123');
3942
- * console.log(`Paid agent $${result.payout.amountUsd}`);
3943
- * ```
3944
- */
3945
- async approveTask(taskId) {
3946
- this.logger.info(`Approving task: ${taskId}`);
3947
- const response = await this.callApi(`/api/v2/tasks/${taskId}/approve`, {
3948
- method: "POST"
3949
- });
3950
- const result = await response.json();
3951
- if (!response.ok) {
3952
- throw new MixrPayError(result.error || "Failed to approve task");
3953
- }
3954
- return {
3955
- success: result.success,
3956
- task: {
3957
- id: result.task.id,
3958
- status: result.task.status,
3959
- completedAt: new Date(result.task.completed_at)
3960
- },
3961
- payout: {
3962
- status: result.payout.status,
3963
- amountUsd: result.payout.amount_usd,
3964
- txHash: result.payout.tx_hash
3965
- }
3966
- };
3967
- }
3968
- /**
3969
- * Reject a task submission and send it back for revision.
3970
- *
3971
- * @param taskId - The task ID
3972
- * @param feedback - Optional feedback for the agent
3973
- */
3974
- async rejectTaskSubmission(taskId, feedback) {
3975
- const response = await this.callApi(`/api/v2/tasks/${taskId}/reject`, {
3976
- method: "POST",
3977
- headers: { "Content-Type": "application/json" },
3978
- body: feedback ? JSON.stringify({ feedback }) : "{}"
3979
- });
3980
- const result = await response.json();
3981
- if (!response.ok) {
3982
- throw new MixrPayError(result.error || "Failed to reject task");
3983
- }
3984
- }
3985
- /**
3986
- * Cancel a task you created.
3987
- *
3988
- * Can only cancel tasks in 'open' or 'claimed' status.
3989
- * If the task was claimed, the agent's session will be revoked.
3990
- *
3991
- * @param taskId - The task ID
3992
- */
3993
- async cancelTask(taskId) {
3994
- const response = await this.callApi(`/api/v2/tasks/${taskId}`, {
3995
- method: "DELETE"
3996
- });
3997
- const result = await response.json();
3998
- if (!response.ok) {
3999
- throw new MixrPayError(result.error || "Failed to cancel task");
4000
- }
4001
- }
4002
- // ===========================================================================
4003
- // Mission Control: Subtask Management
4004
- // ===========================================================================
4005
- /**
4006
- * Create a subtask under an existing task.
4007
- * Requires session key authentication.
4008
- * Budget is allocated from the parent task's remaining budget.
4009
- *
4010
- * @param options - Subtask creation options
4011
- * @returns The created subtask
4012
- *
4013
- * @example
4014
- * ```typescript
4015
- * const subtask = await wallet.createSubtask({
4016
- * parentTaskId: 'task_123',
4017
- * title: 'Research competitor pricing',
4018
- * description: 'Find pricing info for top 5 competitors',
4019
- * budgetUsd: 10,
4020
- * });
4021
- * ```
4022
- */
4023
- async createSubtask(options) {
4024
- this.logger.info(`Creating subtask: ${options.title}`);
4025
- const response = await this.callApi("/api/v2/tasks/create-subtask", {
4026
- method: "POST",
4027
- headers: { "Content-Type": "application/json" },
4028
- body: JSON.stringify({
4029
- parent_task_id: options.parentTaskId,
4030
- title: options.title,
4031
- description: options.description,
4032
- deliverables: options.deliverables,
4033
- category: options.category,
4034
- budget_usd: options.budgetUsd,
4035
- allow_sub_agents: options.allowSubAgents,
4036
- expires_in_days: options.expiresInDays,
4037
- idempotency_key: options.idempotencyKey
4038
- })
4039
- });
4040
- const result = await response.json();
4041
- if (!response.ok) {
4042
- throw new MixrPayError(result.error || "Failed to create subtask");
4043
- }
4044
- return this.parseTask(result.task);
4045
- }
4046
- /**
4047
- * Update the status of a task.
4048
- * Requires session key authentication.
4049
- * Creates an audit trail via TaskStatusUpdate records.
4050
- *
4051
- * @param taskId - The task ID
4052
- * @param status - New status
4053
- * @param note - Optional note explaining the status change
4054
- * @returns The updated task
4055
- *
4056
- * @example
4057
- * ```typescript
4058
- * await wallet.updateTaskStatus('task_123', 'submitted', 'All deliverables completed');
4059
- * ```
4060
- */
4061
- async updateTaskStatus(taskId, status, note, idempotencyKey) {
4062
- this.logger.info(`Updating task ${taskId} status to ${status}`);
4063
- const response = await this.callApi(`/api/v2/tasks/${taskId}/status`, {
4064
- method: "PATCH",
4065
- headers: { "Content-Type": "application/json" },
4066
- body: JSON.stringify({
4067
- status,
4068
- note,
4069
- idempotency_key: idempotencyKey
4070
- })
4071
- });
4072
- const result = await response.json();
4073
- if (!response.ok) {
4074
- throw new MixrPayError(result.error || "Failed to update task status");
4075
- }
4076
- return this.parseTask(result.task);
4077
- }
4078
- /**
4079
- * Get subtasks of a task.
4080
- * Requires session key authentication.
4081
- *
4082
- * @param taskId - The parent task ID
4083
- * @returns List of subtasks
4084
- *
4085
- * @example
4086
- * ```typescript
4087
- * const subtasks = await wallet.getSubtasks('task_123');
4088
- * console.log(`Found ${subtasks.length} subtasks`);
4089
- * ```
4090
- */
4091
- async getSubtasks(taskId) {
4092
- const response = await this.callApi(`/api/v2/tasks/${taskId}/subtasks`, {
4093
- method: "GET"
4094
- });
4095
- const result = await response.json();
4096
- if (!response.ok) {
4097
- throw new MixrPayError(result.error || "Failed to get subtasks");
4098
- }
4099
- return (result.subtasks || []).map((t) => this.parseTask(t));
4100
- }
4101
- /**
4102
- * Get the status history of a task.
4103
- * Requires session key authentication.
4104
- *
4105
- * @param taskId - The task ID
4106
- * @returns Status history with audit trail
4107
- *
4108
- * @example
4109
- * ```typescript
4110
- * const history = await wallet.getTaskStatusHistory('task_123');
4111
- * for (const entry of history.history) {
4112
- * console.log(`${entry.oldStatus} -> ${entry.newStatus}: ${entry.note}`);
4113
- * }
4114
- * ```
4115
- */
4116
- async getTaskStatusHistory(taskId) {
4117
- const response = await this.callApi(`/api/v2/tasks/${taskId}/status`, {
4118
- method: "GET"
4119
- });
4120
- const result = await response.json();
4121
- if (!response.ok) {
4122
- throw new MixrPayError(result.error || "Failed to get task status history");
4123
- }
4124
- return {
4125
- taskId: result.task_id,
4126
- currentStatus: result.current_status,
4127
- history: (result.history || []).map((h) => ({
4128
- id: h.id,
4129
- oldStatus: h.old_status,
4130
- newStatus: h.new_status,
4131
- note: h.note,
4132
- createdAt: new Date(h.created_at)
4133
- }))
4134
- };
4135
- }
4136
- // ===========================================================================
4137
- // Mission Control: Approval System
4138
- // ===========================================================================
4139
- /**
4140
- * Request approval from a human user for an action.
4141
- * Returns immediately if the action is auto-approved.
4142
- *
4143
- * @param options - Approval request options
4144
- * @returns Approval request or auto-approval result
4145
- *
4146
- * @example
4147
- * ```typescript
4148
- * const result = await wallet.requestApproval({
4149
- * actionType: 'external_communication',
4150
- * actionPayload: { recipient: 'user@example.com', message: 'Hello!' },
4151
- * context: 'Sending welcome email to new customer',
4152
- * });
4153
- *
4154
- * if ('autoApproved' in result) {
4155
- * console.log('Auto-approved:', result.reason);
4156
- * } else {
4157
- * console.log('Waiting for approval:', result.id);
4158
- * }
4159
- * ```
4160
- */
4161
- async requestApproval(options) {
4162
- this.logger.info(`Requesting approval for: ${options.actionType}`);
4163
- const response = await this.callApi("/api/v2/approvals/request", {
4164
- method: "POST",
4165
- headers: { "Content-Type": "application/json" },
4166
- body: JSON.stringify({
4167
- action_type: options.actionType,
4168
- action_payload: options.actionPayload,
4169
- context: options.context,
4170
- expires_in_hours: options.expiresInHours,
4171
- idempotency_key: options.idempotencyKey
4172
- })
4173
- });
4174
- const result = await response.json();
4175
- if (!response.ok) {
4176
- throw new MixrPayError(result.error || "Failed to request approval");
4177
- }
4178
- if (result.auto_approved) {
4179
- return {
4180
- autoApproved: true,
4181
- reason: result.reason
4182
- };
4183
- }
4184
- return this.parseApprovalRequest(result.approval_request);
4185
- }
4186
- /**
4187
- * Check the status of an approval request.
4188
- *
4189
- * @param requestId - The approval request ID
4190
- * @returns Current status of the request
4191
- *
4192
- * @example
4193
- * ```typescript
4194
- * const status = await wallet.checkApprovalStatus('req_123');
4195
- * if (status.status === 'approved') {
4196
- * console.log('Approved! Proceeding with action...');
4197
- * }
4198
- * ```
4199
- */
4200
- async checkApprovalStatus(requestId) {
4201
- const response = await this.callApi(`/api/v2/approvals/check?request_id=${requestId}`, {
4202
- method: "GET"
4203
- });
4204
- const result = await response.json();
4205
- if (!response.ok) {
4206
- throw new MixrPayError(result.error || "Failed to check approval status");
4207
- }
4208
- return {
4209
- requestId: result.request_id,
4210
- status: result.status,
4211
- responseNote: result.response_note,
4212
- approvalScope: result.approval_scope,
4213
- respondedAt: result.responded_at ? new Date(result.responded_at) : void 0
4214
- };
4215
- }
4216
- /**
4217
- * Check if an action type needs approval before execution.
4218
- *
4219
- * @param actionType - The type of action to check
4220
- * @param amountUsd - Optional amount for spend actions
4221
- * @returns Whether approval is needed
4222
- *
4223
- * @example
4224
- * ```typescript
4225
- * const check = await wallet.checkActionPermission('external_communication');
4226
- * if (check.needsApproval) {
4227
- * const approval = await wallet.requestApproval({ ... });
4228
- * }
4229
- * ```
4230
- */
4231
- async checkActionPermission(actionType, amountUsd) {
4232
- let url = `/api/v2/approvals/check?action_type=${encodeURIComponent(actionType)}`;
4233
- if (amountUsd !== void 0) {
4234
- url += `&amount_usd=${amountUsd}`;
4235
- }
4236
- const response = await this.callApi(url, { method: "GET" });
4237
- const result = await response.json();
4238
- if (!response.ok) {
4239
- throw new MixrPayError(result.error || "Failed to check action permission");
4240
- }
4241
- return {
4242
- actionType: result.action_type,
4243
- needsApproval: result.needs_approval,
4244
- reason: result.reason
4245
- };
4246
- }
4247
- /**
4248
- * Wait for an approval request to be resolved.
4249
- * Polls the status until approved, rejected, or expired.
4250
- *
4251
- * @param requestId - The approval request ID
4252
- * @param options - Polling options
4253
- * @returns Final status of the request
4254
- *
4255
- * @example
4256
- * ```typescript
4257
- * const approval = await wallet.requestApproval({ ... });
4258
- * if (!('autoApproved' in approval)) {
4259
- * const result = await wallet.waitForApproval(approval.id, { timeoutMs: 60000 });
4260
- * if (result.status === 'approved') {
4261
- * // Proceed with action
4262
- * }
4263
- * }
4264
- * ```
4265
- */
4266
- async waitForApproval(requestId, options = {}) {
4267
- const pollInterval = options.pollIntervalMs || 5e3;
4268
- const timeout = options.timeoutMs || 3e5;
4269
- const startTime = Date.now();
4270
- while (Date.now() - startTime < timeout) {
4271
- const status = await this.checkApprovalStatus(requestId);
4272
- if (status.status !== "pending") {
4273
- return status;
4274
- }
4275
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
4276
- }
4277
- return {
4278
- requestId,
4279
- status: "expired"
4280
- };
4281
- }
4282
- /** Helper to parse approval request from API response */
4283
- parseApprovalRequest(r) {
4284
- return {
4285
- id: r.id,
4286
- actionType: r.action_type,
4287
- actionPayload: r.action_payload,
4288
- context: r.context,
4289
- status: r.status,
4290
- responseNote: r.response_note,
4291
- approvalScope: r.approval_scope,
4292
- createdAt: new Date(r.created_at),
4293
- expiresAt: new Date(r.expires_at),
4294
- respondedAt: r.responded_at ? new Date(r.responded_at) : void 0
4295
- };
4296
- }
4297
- /** Helper to parse task from API response */
4298
- parseTask(t) {
4299
- return {
4300
- id: t.id,
4301
- title: t.title,
4302
- description: t.description,
4303
- deliverables: t.deliverables || [],
4304
- category: t.category,
4305
- budgetUsd: t.budget_usd,
4306
- listingFeeUsd: t.listing_fee_usd,
4307
- status: t.status,
4308
- createdAt: new Date(t.created_at),
4309
- updatedAt: t.updated_at ? new Date(t.updated_at) : void 0,
4310
- expiresAt: t.expires_at ? new Date(t.expires_at) : void 0,
4311
- claimedAt: t.claimed_at ? new Date(t.claimed_at) : void 0,
4312
- submittedAt: t.submitted_at ? new Date(t.submitted_at) : void 0,
4313
- completedAt: t.completed_at ? new Date(t.completed_at) : void 0,
4314
- creator: t.creator,
4315
- assignedAgent: t.assigned_agent,
4316
- requestCount: t.request_count,
4317
- output: t.output,
4318
- payment: t.payment
4319
- };
4320
- }
4321
- /** Helper to call our API with auth */
4322
- async callApi(path, init = {}) {
4323
- const url = `${this.baseUrl}${path}`;
4324
- const headers = {
4325
- ...init.headers
4326
- };
4327
- if (this.sessionKey) {
4328
- const account = privateKeyToAccount2(this.sessionKey.rawPrivateKey);
4329
- const address = account.address.toLowerCase();
4330
- const timestamp = Date.now();
4331
- const message = `MixrPay:${timestamp}:${address}`;
4332
- const signature = await signMessage({
4333
- message,
4334
- privateKey: this.sessionKey.rawPrivateKey
4335
- });
4336
- headers["X-Session-Auth"] = JSON.stringify({
4337
- address,
4338
- timestamp,
4339
- signature
4340
- });
4341
- }
4342
- return fetch(url, {
4343
- ...init,
4344
- headers
4345
- });
4346
- }
4347
- };
4348
- export {
4349
- AgentWallet,
4350
- InsufficientBalanceError,
4351
- InvalidSessionKeyError,
4352
- MerchantNotAllowedError,
4353
- MixrPayError,
4354
- PaymentFailedError,
4355
- SDK_VERSION,
4356
- SessionExpiredError,
4357
- SessionKeyExpiredError,
4358
- SessionLimitExceededError,
4359
- SessionNotFoundError,
4360
- SessionRevokedError,
4361
- SpendingLimitExceededError,
4362
- X402ProtocolError,
4363
- getErrorMessage,
4364
- isMixrPayError
4365
- };
30
+ Timestamp: ${e}`,s=await this.sessionKey.signMessage(t);return {"X-Mixr-Wallet":this.walletAddress,"X-Mixr-Signature":s,"X-Mixr-Timestamp":e}}async listTools(){this.logger.debug("listTools");let e=await fetch(`${this.baseUrl}/api/mcp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"tools/list",id:Date.now()})});if(!e.ok)throw new l(`Failed to list MCP tools: ${e.status}`);let t=await e.json();if(t.error)throw new l(t.error.message||"Failed to list MCP tools");return (t.result?.tools||[]).map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema,priceUsd:s["x-mixrpay"]?.priceUsd||0,merchantName:s["x-mixrpay"]?.merchantName,merchantSlug:s["x-mixrpay"]?.merchantSlug,verified:s["x-mixrpay"]?.verified||false}))}async listMCPTools(){return this.listTools()}async callTool(e,t={}){this.logger.debug("callTool",{toolName:e,args:t}),await this.validateMerchantAllowed(e,"tool");let s=await this.getMCPAuthHeaders(),a=await(await fetch(`${this.baseUrl}/api/mcp`,{method:"POST",headers:{"Content-Type":"application/json",...s},body:JSON.stringify({jsonrpc:"2.0",method:"tools/call",params:{name:e,arguments:t},id:Date.now()})})).json();if(a.error)throw new l(a.error.message||"MCP tool call failed");let r=a.result?.content?.[0],i=r?.text?JSON.parse(r.text):null,o=a.result?._mixrpay||{};if(o.chargedUsd){let c={amountUsd:o.chargedUsd,recipient:e.split("/")[0]||e,txHash:o.txHash,timestamp:new Date,description:`MCP: ${e}`,url:`${this.baseUrl}/api/mcp`,requestId:crypto.randomUUID()};this.payments.push(c),this.totalSpentUsd+=o.chargedUsd,this.logger.payment(o.chargedUsd,e,"MCP call"),this.onPayment&&this.onPayment(c);}return {data:i,chargedUsd:o.chargedUsd||0,txHash:o.txHash,latencyMs:o.latencyMs}}async callMCPTool(e,t={}){return this.callTool(e,t)}async deployJitMcp(e){this.logger.debug("deployJitMcp",{glamaId:e.glamaId,toolName:e.toolName});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit/deploy`,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify({glama_id:e.glamaId,glama_namespace:e.glamaNamespace,glama_slug:e.glamaSlug,tool_name:e.toolName,tool_description:e.toolDescription,env_vars:e.envVars,ttl_hours:e.ttlHours||24})});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`JIT deploy failed: ${s.status}`)}let n=await s.json();if(n.payment?.amount_usd>0){let a={amountUsd:n.payment.amount_usd,recipient:"mixrpay-jit-deploy",txHash:n.payment.tx_hash,timestamp:new Date,description:`JIT Deploy: ${e.toolName}`,url:`${this.baseUrl}/api/v2/jit/deploy`,requestId:n.request_id||crypto.randomUUID()};this.payments.push(a),this.totalSpentUsd+=n.payment.amount_usd,this.logger.payment(n.payment.amount_usd,"jit-deploy",e.toolName),this.onPayment&&this.onPayment(a);}return {instance:this.parseJitInstance(n.instance),payment:{method:n.payment.method,amountUsd:n.payment.amount_usd,txHash:n.payment.tx_hash}}}async listJitInstances(e){this.logger.debug("listJitInstances",e);let t=await this.getSessionAuthHeaders(),s=new URLSearchParams;e?.status&&s.set("status",e.status);let n=await fetch(`${this.baseUrl}/api/v2/jit/instances?${s}`,{headers:t});if(!n.ok){let r=await n.json().catch(()=>({}));throw new l(r.error||`Failed to list JIT instances: ${n.status}`)}return ((await n.json()).instances||[]).map(r=>this.parseJitInstance(r))}async stopJitInstance(e){this.logger.debug("stopJitInstance",{instanceId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit/instances/${e}`,{method:"DELETE",headers:t});if(!s.ok){let n=await s.json().catch(()=>({}));throw new l(n.error||`Failed to stop JIT instance: ${s.status}`)}}parseJitInstance(e){return {id:e.id,endpointUrl:e.endpoint_url,toolName:e.tool_name,glamaId:e.glama_id,glamaNamespace:e.glama_namespace,glamaSlug:e.glama_slug,status:e.status,mode:e.mode,ttlHours:e.ttl_hours,expiresAt:new Date(e.expires_at),createdAt:new Date(e.created_at)}}async getJitInstance(e){this.logger.debug("getJitInstance",{instanceId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit/instances/${e}`,{headers:t});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Failed to get JIT instance: ${s.status}`)}let n=await s.json();return this.parseJitInstance(n.instance)}async executeTransaction(e){this.logger.debug("executeTransaction",{to:e.to,estimatedCostUsd:e.estimatedCostUsd});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/tx/execute`,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify({to:e.to,data:e.data,value:e.value?.toString()??"0",chain_id:e.chainId,estimated_cost_usd:e.estimatedCostUsd,description:e.description,idempotency_key:e.idempotencyKey})}),n=await s.json().catch(()=>({}));if(!s.ok){let a=(n.error_code||"tx_failed").toLowerCase(),r=n.error||`Transaction execution failed: ${s.status}`;throw a==="budget_exceeded"?new l(r,"SPENDING_LIMIT_EXCEEDED"):new l(r,a)}return this.logger.info("Transaction executed",{txHash:n.tx_hash,estimatedCostUsd:e.estimatedCostUsd,remainingBudgetUsd:n.remaining_budget_usd}),{success:true,txHash:n.tx_hash,chargeId:n.charge_id,estimatedCostUsd:n.estimated_cost_usd,remainingBudgetUsd:n.remaining_budget_usd}}async useSkill(e,t){this.logger.debug("useSkill",{skillId:e,options:t});let s=await this.getSessionAuthHeaders(),n=await fetch(`${this.baseUrl}/api/v2/skills/${e}/use`,{method:"POST",headers:{"Content-Type":"application/json",...s},body:JSON.stringify({ttl_hours:t?.ttlHours||24})});if(!n.ok){let r=await n.json().catch(()=>({}));throw r.configure_url?new l(`${r.error||"Skill not configured"}. Configure at: ${this.baseUrl}${r.configure_url}`,"SKILL_NOT_CONFIGURED"):new l(r.error||`Failed to use skill: ${n.status}`)}let a=await n.json();return {skillId:a.skill_id,endpoint:a.endpoint,tools:a.tools||[],expiresAt:new Date(a.expires_at),instanceId:a.instance_id}}async listSkills(){this.logger.debug("listSkills");let e=await this.getSessionAuthHeaders(),t=await fetch(`${this.baseUrl}/api/v2/skills`,{headers:e});if(!t.ok){let n=await t.json().catch(()=>({}));throw new l(n.error||`Failed to list skills: ${t.status}`)}return (await t.json()).skills||[]}async getConnectedApps(){this.logger.debug("getConnectedApps");let e=await this.getSessionAuthHeaders(),t=await fetch(`${this.baseUrl}/api/v2/skills/composio/connections`,{headers:e});if(!t.ok){let a=await t.json().catch(()=>({}));throw new l(a.error||`Failed to get connected apps: ${t.status}`,"CONNECTED_APPS_FAILED")}let s=await t.json();return {connected:(s.connections||[]).filter(a=>a.status==="connected").map(a=>a.app.toLowerCase()),connections:s.connections||[],oauthConnections:s.oauth_connections||[],apiKeyConnections:s.api_key_connections||[]}}async getSkillStatus(e){this.logger.debug("getSkillStatus",{skillId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/skills/${e}/configure`,{headers:t});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Failed to get skill status: ${s.status}`)}let n=await s.json();return {skillId:n.skill_id,status:n.status,configuredVars:n.configured_vars||[],lastUsedAt:n.last_used_at?new Date(n.last_used_at):void 0,errorMessage:n.error_message}}async configureSkill(e,t){this.logger.debug("configureSkill",{skillId:e,varNames:Object.keys(t)});let s=await this.getSessionAuthHeaders(),n=await fetch(`${this.baseUrl}/api/v2/skills/${e}/configure`,{method:"POST",headers:{"Content-Type":"application/json",...s},body:JSON.stringify({env_vars:t})});if(!n.ok){let r=await n.json().catch(()=>({}));throw new l(r.error||`Failed to configure skill: ${n.status}`,r.error_code)}let a=await n.json();return {success:true,skillId:a.skill_id,configuredVars:a.configured_vars||[]}}async searchGlamaDirectory(e){this.logger.debug("searchGlamaDirectory",{query:e});let t=new URLSearchParams({q:e}),s=await fetch(`${this.baseUrl}/api/mcp/glama?${t}`);if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Glama search failed: ${s.status}`)}let n=await s.json();return {servers:(n.servers||[]).map(a=>this.parseGlamaServer(a)),pageInfo:n.pageInfo,query:n.query}}async getFeaturedGlamaServers(){this.logger.debug("getFeaturedGlamaServers");let e=await fetch(`${this.baseUrl}/api/mcp/glama`);if(!e.ok){let s=await e.json().catch(()=>({}));throw new l(s.error||`Failed to get featured servers: ${e.status}`)}let t=await e.json();return {servers:(t.servers||[]).map(s=>this.parseGlamaServer(s)),featured:t.featured}}parseGlamaServer(e){let t=e.importData;return {id:e.id,name:e.name,namespace:e.namespace,slug:e.slug,description:e.description,url:e.url,attributes:e.attributes,canHost:e.canHost,tools:e.tools||[],repository:e.repository,license:e.spdxLicense?.name,importData:t?{glamaId:t.glamaId,glamaNamespace:t.glamaNamespace,glamaSlug:t.glamaSlug,suggestedName:t.suggestedName,suggestedDescription:t.suggestedDescription,hostingType:t.hostingType,requiredEnvVars:t.requiredEnvVars,optionalEnvVars:t.optionalEnvVars}:void 0}}async deployTaskAgent(e){this.logger.debug("deployTaskAgent",{name:e.name,budgetUsd:e.budgetUsd});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit-task/deploy`,{method:"POST",headers:{"Content-Type":"application/json",...t},body:JSON.stringify({name:e.name,prompt:e.prompt,system_prompt:e.systemPrompt,model:e.model||"claude-sonnet-4-5",tools:e.tools||[],budget_usd:e.budgetUsd,ttl_hours:e.ttlHours||24,max_iterations:e.maxIterations||10,plan_id:e.planId,task_id:e.taskId,idempotency_key:e.idempotencyKey,auto_run:e.autoRun||false})});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Task agent deploy failed: ${s.status}`)}let n=await s.json();return {instance:this.parseTaskAgentInstance(n.instance),idempotent:n.idempotent||false,requestId:n.request_id}}async getTaskAgentStatus(e){this.logger.debug("getTaskAgentStatus",{instanceId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit-task/${e}`,{method:"GET",headers:t});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Failed to get task status: ${s.status}`)}let n=await s.json();return this.parseTaskAgentStatus(n)}async triggerTaskAgent(e){this.logger.debug("triggerTaskAgent",{instanceId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit-task/${e}`,{method:"POST",headers:{"Content-Type":"application/json",...t}});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Failed to trigger task: ${s.status}`)}let n=await s.json();return {success:n.success,status:n.status}}async cancelTaskAgent(e){this.logger.debug("cancelTaskAgent",{instanceId:e});let t=await this.getSessionAuthHeaders(),s=await fetch(`${this.baseUrl}/api/v2/jit-task/${e}`,{method:"DELETE",headers:t});if(!s.ok){let a=await s.json().catch(()=>({}));throw new l(a.error||`Failed to cancel task: ${s.status}`)}let n=await s.json();return {success:n.success,status:n.status}}async listTaskAgents(e){this.logger.debug("listTaskAgents",{options:e});let t=await this.getSessionAuthHeaders(),s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.planId&&s.set("plan_id",e.planId),e?.taskId&&s.set("task_id",e.taskId),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));let n=s.toString(),a=`${this.baseUrl}/api/v2/jit-task${n?`?${n}`:""}`,r=await fetch(a,{method:"GET",headers:t});if(!r.ok){let o=await r.json().catch(()=>({}));throw new l(o.error||`Failed to list task agents: ${r.status}`)}let i=await r.json();return {taskAgents:(i.task_agents||[]).map(o=>{let c=o.budget,p=o.iterations,u=o.usage,g=o.plan,h=o.task;return {id:o.id,name:o.name,prompt:o.prompt,model:o.model,tools:o.tools,status:o.status,budget:{totalUsd:c.total_usd,spentUsd:c.spent_usd,remainingUsd:c.remaining_usd},iterations:{current:p.current,max:p.max},usage:{toolCalls:u.tool_calls,inputTokens:u.input_tokens,outputTokens:u.output_tokens},result:o.result,error:o.error,depth:o.depth,plan:g?{id:g.id,title:g.title}:null,task:h?{id:h.id,title:h.title}:null,ttlHours:o.ttl_hours,expiresAt:new Date(o.expires_at),createdAt:new Date(o.created_at),startedAt:o.started_at?new Date(o.started_at):void 0,completedAt:o.completed_at?new Date(o.completed_at):void 0}}),pagination:{total:i.pagination.total,limit:i.pagination.limit,offset:i.pagination.offset,hasMore:i.pagination.has_more},stats:{active:i.stats.active??0,completed:i.stats.completed??0,failed:i.stats.failed??0,totalSpentUsd:i.stats.total_spent_usd??0}}}async waitForTaskAgent(e,t){let s=t?.pollIntervalMs||2e3,n=t?.timeoutMs||3e5,a=Date.now();for(this.logger.debug("waitForTaskAgent",{instanceId:e,pollIntervalMs:s,timeoutMs:n});;){let r=await this.getTaskAgentStatus(e);if(["completed","failed","cancelled","budget_exceeded","expired"].includes(r.status))return {id:r.id,status:r.status,result:r.result,error:r.error,spentUsd:r.budget.spentUsd,iterations:r.iterations.current,toolCalls:r.usage.toolCalls,completedAt:r.completedAt};if(Date.now()-a>n)throw new l(`Task agent wait timeout after ${n}ms`);await new Promise(i=>setTimeout(i,s));}}parseTaskAgentInstance(e){return {id:e.id,name:e.name,endpointUrl:e.endpoint_url,statusUrl:e.status_url,triggerUrl:e.trigger_url,cancelUrl:e.cancel_url,resultUrl:e.result_url,status:e.status,budgetUsd:e.budget_usd,expiresAt:new Date(e.expires_at),depth:e.depth,maxIterations:e.max_iterations}}parseTaskAgentStatus(e){let t=e.budget,s=e.iterations,n=e.usage,a=e.endpoints;return {id:e.id,name:e.name,prompt:e.prompt,model:e.model,tools:e.tools,status:e.status,budget:{totalUsd:t?.total_usd??0,spentUsd:t?.spent_usd??0,remainingUsd:t?.remaining_usd??0},iterations:{current:s?.current??0,max:s?.max??0},usage:{toolCalls:n?.tool_calls??0,inputTokens:n?.input_tokens??0,outputTokens:n?.output_tokens??0},result:e.result,error:e.error,depth:e.depth,planId:e.plan_id,taskId:e.task_id,endpoints:{statusUrl:a?.status_url??"",triggerUrl:a?.trigger_url??"",cancelUrl:a?.cancel_url??"",resultUrl:a?.result_url??""},ttlHours:e.ttl_hours,expiresAt:new Date(e.expires_at),createdAt:new Date(e.created_at),startedAt:e.started_at?new Date(e.started_at):void 0,completedAt:e.completed_at?new Date(e.completed_at):void 0}}async complete(e,t){this.logger.debug("complete",{promptLength:e.length,model:t?.model});let s=await this.runAgent({messages:[{role:"user",content:e}],config:{model:t?.model||"gpt-4o-mini",maxIterations:1,tools:[],systemPrompt:t?.systemPrompt}});return {text:s.response,costUsd:s.cost.totalUsd,tokens:s.tokens,model:t?.model||"gpt-4o-mini"}}async runAgent(e){let{sessionId:t,messages:s,config:n={},stream:a=false,idempotencyKey:r,onEvent:i}=e;this.logger.debug("runAgent",{sessionId:t||"(from signature)",messageCount:s.length,config:n,stream:a});let o={messages:s.map(p=>({role:p.role,content:p.content})),config:{model:n.model,max_iterations:n.maxIterations,tools:n.tools,system_prompt:n.systemPrompt},stream:a,idempotency_key:r};t&&(o.session_id=t);let c=18e4;if(!a){let p=await this.getSessionAuthHeaders(),u=await fetch(`${this.baseUrl}/api/v2/agent/run`,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(o),signal:AbortSignal.timeout(c)});if(!u.ok){let h=await u.json().catch(()=>({}));throw new l(h.error||`Agent run failed: ${u.status}`)}let g=await u.json();if(g.cost?.total_usd>0){let h={amountUsd:g.cost.total_usd,recipient:"mixrpay-agent-run",txHash:g.tx_hash,timestamp:new Date,description:`Agent run: ${g.run_id}`,url:`${this.baseUrl}/api/v2/agent/run`,requestId:r||crypto.randomUUID()};this.payments.push(h),this.totalSpentUsd+=g.cost.total_usd,this.logger.payment(g.cost.total_usd,"agent-run",g.run_id),this.onPayment&&this.onPayment(h);}return {runId:g.run_id,status:g.status,response:g.response,iterations:g.iterations,toolsUsed:g.tools_used,cost:{llmUsd:g.cost.llm_usd,toolsUsd:g.cost.tools_usd,totalUsd:g.cost.total_usd},tokens:g.tokens,sessionRemainingUsd:g.session_remaining_usd,txHash:g.tx_hash}}return this.runAgentStreaming(o,i)}async runAgentStreaming(e,t){let n=await this.getSessionAuthHeaders(),a=await fetch(`${this.baseUrl}/api/v2/agent/run`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(e),signal:AbortSignal.timeout(3e5)});if(!a.ok){let p=await a.json().catch(()=>({}));throw new l(p.error||`Agent run failed: ${a.status}`)}let r=a.body?.getReader();if(!r)throw new l("No response body for streaming");let i=new TextDecoder,o="",c=null;for(;;){let{done:p,value:u}=await r.read();if(p)break;o+=i.decode(u,{stream:true});let g=o.split(`
31
+ `);o=g.pop()||"";let h="";for(let y of g)if(y.startsWith("event: "))h=y.slice(7).trim();else if(y.startsWith("data: ")&&h){try{let m=JSON.parse(y.slice(6)),f=this.parseSSEEvent(h,m);if(f){if(t?.(f),h==="complete"&&(c={runId:m.run_id,status:"completed",response:m.response,iterations:m.iterations,toolsUsed:m.tools_used,cost:{llmUsd:0,toolsUsd:0,totalUsd:m.total_cost_usd},tokens:{prompt:0,completion:0},sessionRemainingUsd:0,txHash:m.tx_hash},m.total_cost_usd>0)){let w={amountUsd:m.total_cost_usd,recipient:"mixrpay-agent-run",txHash:m.tx_hash,timestamp:new Date,description:`Agent run: ${m.run_id}`,url:`${this.baseUrl}/api/v2/agent/run`,requestId:e.idempotency_key||crypto.randomUUID()};this.payments.push(w),this.totalSpentUsd+=m.total_cost_usd,this.onPayment&&this.onPayment(w);}if(h==="error")throw new l(m.error||"Agent run failed")}}catch(m){if(m instanceof l)throw m;this.logger.warn("Failed to parse SSE event:",m);}h="";}}if(!c)throw new l("Agent run completed without final result");return c}parseSSEEvent(e,t){switch(e){case "run_start":return {type:"run_start",runId:t.run_id};case "iteration_start":return {type:"iteration_start",iteration:t.iteration};case "llm_chunk":return {type:"llm_chunk",delta:t.delta};case "tool_call":return {type:"tool_call",tool:t.tool,arguments:t.arguments};case "tool_result":return {type:"tool_result",tool:t.tool,success:t.success,costUsd:t.cost_usd,error:t.error};case "iteration_complete":return {type:"iteration_complete",iteration:t.iteration,tokens:t.tokens,costUsd:t.cost_usd};case "complete":return {type:"complete",runId:t.run_id,response:t.response,totalCostUsd:t.total_cost_usd,txHash:t.tx_hash,iterations:t.iterations,toolsUsed:t.tools_used};case "error":return {type:"error",error:t.error,partialCostUsd:t.partial_cost_usd};default:return null}}async getAgentRunStatus(e,t){this.logger.debug("getAgentRunStatus",{runId:e});let s=await this.getSessionAuthHeaders(),n=await fetch(`${this.baseUrl}/api/v2/agent/run/${e}`,{headers:s});if(!n.ok){let r=await n.json().catch(()=>({}));throw new l(r.error||`Failed to get run status: ${n.status}`)}let a=await n.json();return {runId:a.run_id,status:a.status,response:a.response,iterations:a.iterations,toolsUsed:a.tools_used,cost:{llmUsd:a.cost.llm_usd,toolsUsd:a.cost.tools_usd,totalUsd:a.cost.total_usd},tokens:a.tokens,txHash:a.tx_hash,error:a.error,startedAt:new Date(a.started_at),completedAt:a.completed_at?new Date(a.completed_at):void 0}}async callToolWithSession(e,t,s={}){this.logger.debug("callToolWithSession",{sessionId:e,toolName:t,args:s}),await this.validateMerchantAllowed(t,"tool");let a=await(await fetch(`${this.baseUrl}/api/mcp`,{method:"POST",headers:{"Content-Type":"application/json","X-Mixr-Session":e},body:JSON.stringify({jsonrpc:"2.0",method:"tools/call",params:{name:t,arguments:s},id:Date.now()})})).json();if(a.error)throw new l(a.error.message||"MCP tool call failed");let r=a.result?.content?.[0],i=r?.text?JSON.parse(r.text):null,o=a.result?._mixrpay||{};if(o.chargedUsd){let c={amountUsd:o.chargedUsd,recipient:t.split("/")[0]||t,txHash:o.txHash,timestamp:new Date,description:`MCP: ${t}`,url:`${this.baseUrl}/api/mcp`,requestId:crypto.randomUUID()};this.payments.push(c),this.totalSpentUsd+=o.chargedUsd,this.logger.payment(o.chargedUsd,t,"MCP call (session)"),this.onPayment&&this.onPayment(c);}return {data:i,chargedUsd:o.chargedUsd||0,txHash:o.txHash,latencyMs:o.latencyMs}}async callMCPToolWithSession(e,t,s={}){return this.callToolWithSession(e,t,s)}async createTask(e){this.logger.info(`Creating task: ${e.title}`);let t=await this.callApi("/api/v2/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e.title,description:e.description,budget_usd:e.budgetUsd,deliverables:e.deliverables,category:e.category,expires_in_days:e.expiresInDays})}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to create task");return this.parseTask(s.task)}async listTasks(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.category&&t.set("category",e.category),e?.minBudget!==void 0&&t.set("min_budget",String(e.minBudget)),e?.maxBudget!==void 0&&t.set("max_budget",String(e.maxBudget)),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let s=`/api/v2/tasks${t.toString()?`?${t}`:""}`,n=await this.callApi(s,{method:"GET"}),a=await n.json();if(!n.ok)throw new l(a.error||"Failed to list tasks");return {tasks:a.tasks.map(r=>this.parseTask(r)),pagination:a.pagination}}async getTask(e){let t=await this.callApi(`/api/v2/tasks/${e}`,{method:"GET"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to get task");return this.parseTask(s.task)}async getMyTasks(e={}){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.page&&t.set("page",e.page.toString()),e.limit&&t.set("limit",e.limit.toString());let s=t.toString(),n=`/api/v2/tasks/my${s?`?${s}`:""}`,a=await this.callApi(n,{method:"GET"}),r=await a.json();if(!a.ok)throw new l(r.error||"Failed to get tasks");return {tasks:r.tasks.map(i=>({...this.parseTask(i),isCreator:i.is_creator,isAgent:i.is_agent})),pagination:{page:r.pagination.page,limit:r.pagination.limit,total:r.pagination.total,totalPages:r.pagination.total_pages}}}async requestTask(e,t){this.logger.info(`Requesting task: ${e}`);let s=await this.callApi(`/api/v2/tasks/${e}/request`,{method:"POST",headers:{"Content-Type":"application/json"},body:t?JSON.stringify({message:t}):"{}"}),n=await s.json();if(!s.ok)throw new l(n.error||"Failed to request task");return {id:n.request.id,taskId:n.request.task_id,status:n.request.status,message:n.request.message,createdAt:new Date(n.request.created_at)}}async getTaskRequests(e){let t=await this.callApi(`/api/v2/tasks/${e}/requests`,{method:"GET"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to get task requests");return s.requests.map(n=>({id:n.id,status:n.status,message:n.message,createdAt:new Date(n.created_at),reviewedAt:n.reviewed_at?new Date(n.reviewed_at):void 0,agent:n.agent}))}async acceptTaskRequest(e,t){this.logger.info(`Accepting request ${t} for task ${e}`);let s=await this.callApi(`/api/v2/tasks/${e}/requests/${t}/accept`,{method:"POST"}),n=await s.json();if(!s.ok)throw new l(n.error||"Failed to accept request");return {success:n.success,task:{id:n.task.id,status:n.task.status,agentUserId:n.task.agent_user_id},session:{id:n.session.id,sessionKey:n.session.session_key,address:n.session.address,expiresAt:new Date(n.session.expires_at),budgetUsd:n.session.budget_usd,allowedMerchants:n.session.allowed_merchants||[]},invite:{id:n.invite.id,code:n.invite.code},listingFeeTxHash:n.listing_fee_tx_hash}}async rejectTaskRequest(e,t){let s=await this.callApi(`/api/v2/tasks/${e}/requests/${t}/reject`,{method:"POST"}),n=await s.json();if(!s.ok)throw new l(n.error||"Failed to reject request")}async submitTask(e,t){this.logger.info(`Submitting task: ${e}`);let s=await this.callApi(`/api/v2/tasks/${e}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({output_text:t.text,output_url:t.url})}),n=await s.json();if(!s.ok)throw new l(n.error||"Failed to submit task")}async approveTask(e){this.logger.info(`Approving task: ${e}`);let t=await this.callApi(`/api/v2/tasks/${e}/approve`,{method:"POST"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to approve task");return {success:s.success,task:{id:s.task.id,status:s.task.status,completedAt:new Date(s.task.completed_at)},payout:{status:s.payout.status,amountUsd:s.payout.amount_usd,txHash:s.payout.tx_hash}}}async rejectTaskSubmission(e,t){let s=await this.callApi(`/api/v2/tasks/${e}/reject`,{method:"POST",headers:{"Content-Type":"application/json"},body:t?JSON.stringify({feedback:t}):"{}"}),n=await s.json();if(!s.ok)throw new l(n.error||"Failed to reject task")}async cancelTask(e){let t=await this.callApi(`/api/v2/tasks/${e}`,{method:"DELETE"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to cancel task")}async createSubtask(e){this.logger.info(`Creating subtask: ${e.title}`);let t=await this.callApi("/api/v2/tasks/create-subtask",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_task_id:e.parentTaskId,title:e.title,description:e.description,deliverables:e.deliverables,category:e.category,budget_usd:e.budgetUsd,allow_sub_agents:e.allowSubAgents,expires_in_days:e.expiresInDays,idempotency_key:e.idempotencyKey})}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to create subtask");return this.parseTask(s.task)}async updateTaskStatus(e,t,s,n){this.logger.info(`Updating task ${e} status to ${t}`);let a=await this.callApi(`/api/v2/tasks/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t,note:s,idempotency_key:n})}),r=await a.json();if(!a.ok)throw new l(r.error||"Failed to update task status");return this.parseTask(r.task)}async getSubtasks(e){let t=await this.callApi(`/api/v2/tasks/${e}/subtasks`,{method:"GET"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to get subtasks");return (s.subtasks||[]).map(n=>this.parseTask(n))}async getTaskStatusHistory(e){let t=await this.callApi(`/api/v2/tasks/${e}/status`,{method:"GET"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to get task status history");return {taskId:s.task_id,currentStatus:s.current_status,history:(s.history||[]).map(n=>({id:n.id,oldStatus:n.old_status,newStatus:n.new_status,note:n.note,createdAt:new Date(n.created_at)}))}}async requestApproval(e){this.logger.info(`Requesting approval for: ${e.actionType}`);let t=await this.callApi("/api/v2/approvals/request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action_type:e.actionType,action_payload:e.actionPayload,context:e.context,expires_in_hours:e.expiresInHours,idempotency_key:e.idempotencyKey})}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to request approval");return s.auto_approved?{autoApproved:true,reason:s.reason}:this.parseApprovalRequest(s.approval_request)}async checkApprovalStatus(e){let t=await this.callApi(`/api/v2/approvals/check?request_id=${e}`,{method:"GET"}),s=await t.json();if(!t.ok)throw new l(s.error||"Failed to check approval status");return {requestId:s.request_id,status:s.status,responseNote:s.response_note,approvalScope:s.approval_scope,respondedAt:s.responded_at?new Date(s.responded_at):void 0}}async checkActionPermission(e,t){let s=`/api/v2/approvals/check?action_type=${encodeURIComponent(e)}`;t!==void 0&&(s+=`&amount_usd=${t}`);let n=await this.callApi(s,{method:"GET"}),a=await n.json();if(!n.ok)throw new l(a.error||"Failed to check action permission");return {actionType:a.action_type,needsApproval:a.needs_approval,reason:a.reason}}async waitForApproval(e,t={}){let s=t.pollIntervalMs||5e3,n=t.timeoutMs||3e5,a=Date.now();for(;Date.now()-a<n;){let r=await this.checkApprovalStatus(e);if(r.status!=="pending")return r;await new Promise(i=>setTimeout(i,s));}return {requestId:e,status:"expired"}}parseApprovalRequest(e){return {id:e.id,actionType:e.action_type,actionPayload:e.action_payload,context:e.context,status:e.status,responseNote:e.response_note,approvalScope:e.approval_scope,createdAt:new Date(e.created_at),expiresAt:new Date(e.expires_at),respondedAt:e.responded_at?new Date(e.responded_at):void 0}}parseTask(e){return {id:e.id,title:e.title,description:e.description,deliverables:e.deliverables||[],category:e.category,budgetUsd:e.budget_usd,listingFeeUsd:e.listing_fee_usd,status:e.status,createdAt:new Date(e.created_at),updatedAt:e.updated_at?new Date(e.updated_at):void 0,expiresAt:e.expires_at?new Date(e.expires_at):void 0,claimedAt:e.claimed_at?new Date(e.claimed_at):void 0,submittedAt:e.submitted_at?new Date(e.submitted_at):void 0,completedAt:e.completed_at?new Date(e.completed_at):void 0,creator:e.creator,assignedAgent:e.assigned_agent,requestCount:e.request_count,output:e.output,payment:e.payment}}async getBalances(){let e=await this.callApiWithAuth("/api/v2/agent/balances",{method:"GET"});if(!e.ok){let t=await e.json().catch(()=>({}));throw new l(t.error||`Failed to get balances: ${e.status}`)}return e.json()}async transfer(e,t,s="USDC"){let n=await this.callApiWithAuth("/api/v2/agent/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({to:e,amount:t,currency:s})});if(!n.ok){let a=await n.json().catch(()=>({}));throw new l(a.error||`Transfer failed: ${n.status}`)}return n.json()}async swap(e,t,s,n=100){let a=await this.callApiWithAuth("/api/v2/agent/swap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sell_token:e,buy_token:t,sell_amount:s,slippage_bps:n})});if(!a.ok){let r=await a.json().catch(()=>({}));throw new l(r.error||`Swap failed: ${a.status}`)}return a.json()}async bridge(e,t,s,n){let a=await this.callApiWithAuth("/api/v2/agent/bridge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,amount:t,dest_chain:s,dest_address:n})});if(!a.ok){let r=await a.json().catch(()=>({}));throw new l(r.error||`Bridge failed: ${a.status}`)}return a.json()}async getBridgeStatus(e){let t=await this.callApiWithAuth(`/api/v2/agent/bridge/status?order_id=${encodeURIComponent(e)}`,{method:"GET"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new l(s.error||`Bridge status check failed: ${t.status}`)}return t.json()}async fetchPaid(e,t){let s=await this.callApiWithAuth("/api/v2/agent/fetch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e,method:t?.method||"GET",headers:t?.headers,body:t?.body,max_payment_usd:t?.maxPaymentUsd})});if(!s.ok){let n=await s.json().catch(()=>({}));throw new l(n.error||`Fetch failed: ${s.status}`)}return s.json()}async callApiWithAuth(e,t={}){let s=`${this.baseUrl}${e}`,n={...t.headers};if(this.apiKey)n.Authorization=`Bearer ${this.apiKey}`;else {let a=await this.getSessionAuthHeaders();Object.assign(n,a);}return fetch(s,{...t,headers:n})}async callApi(e,t={}){let s=`${this.baseUrl}${e}`,n={...t.headers};if(this.sessionKey){let r=privateKeyToAccount(this.sessionKey.rawPrivateKey).address.toLowerCase(),i=Date.now(),o=`MixrPay:${i}:${r}`,c=await signMessage({message:o,privateKey:this.sessionKey.rawPrivateKey});n["X-Session-Auth"]=JSON.stringify({address:r,timestamp:i,signature:c});}return fetch(s,{...t,headers:n})}};export{G as AgentWallet,L as AuthenticationError,S as InsufficientBalanceError,_ as InvalidSessionKeyError,D as MerchantNotAllowedError,l as MixrPayError,N as NetworkError,A as PaymentFailedError,M as RateLimitError,re as SDK_VERSION,C as SessionExpiredError,$ as SessionKeyExpiredError,U as SessionLimitExceededError,P as SessionNotFoundError,I as SessionRevokedError,v as SpendingLimitExceededError,k as X402ProtocolError,Pe as deleteWalletKey,ge as getErrorMessage,Ue as getWalletStoragePath,q as hasWalletKey,ue as isMixrPayError,Te as loadWalletData,K as loadWalletKey,W as saveWalletKey};