@mixrpay/agent-sdk 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,10 +68,10 @@ const balances = await wallet.getBalances();
68
68
  // Transfer USDC
69
69
  await wallet.transfer('0x...', '10.00');
70
70
 
71
- // Swap tokens via 0x
71
+ // Swap tokens
72
72
  await wallet.swap('ETH', 'USDC', '0.1');
73
73
 
74
- // Bridge cross-chain via deBridge
74
+ // Bridge cross-chain
75
75
  const bridge = await wallet.bridge('USDC', '100', 'ethereum');
76
76
  await wallet.waitForBridgeCompletion(bridge.order_id);
77
77
 
@@ -216,7 +216,7 @@ try {
216
216
  ## Features
217
217
 
218
218
  - Non-custodial agent wallets (keys stay local)
219
- - DeFi primitives: swap (0x), bridge (deBridge), transfer
219
+ - DeFi primitives: swap, bridge, transfer
220
220
  - 20+ gateway tools (Firecrawl, Exa, Tavily, and more)
221
221
  - x402 auto-pay proxy for paid APIs
222
222
  - MCP server for Claude Agent SDK
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{g as AgentWallet,c as DEFAULT_BASE_URL,d as DEFAULT_FACILITATOR_URL,e as DEFAULT_TIMEOUT,f as NETWORKS,b as SDK_VERSION}from'./chunk-UED36HQN.js';
2
+ export{g as AgentWallet,c as DEFAULT_BASE_URL,d as DEFAULT_FACILITATOR_URL,e as DEFAULT_TIMEOUT,f as NETWORKS,b as SDK_VERSION}from'./chunk-4WCYTILC.js';
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {fileURLToPath}from'url';import {join,dirname}from'path';import {privateKeyToAccount,signMessage,generatePrivateKey,signTypedData}from'viem/accounts';import {z as z$1}from'zod';import {createWalletClient,http,parseUnits,encodeFunctionData}from'viem';import {base}from'viem/chains';import {existsSync,readFileSync,mkdirSync,writeFileSync,chmodSync}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}},v=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;}},T=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}},S=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;}},P=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;}},I=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;}},R=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;}};var _e={8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",84532:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"},xe={name:"USD Coin",version:"2"},Se={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"}]},E=class c{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 S("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 c(r,n==="test")}catch(r){throw new S(`Failed to decode session key: ${r}`)}}async signTransferAuthorization(e,t){return signTypedData({privateKey:this.privateKey,domain:e,types:Se,primaryType:"TransferWithAuthorization",message:t})}async signMessage(e){return signMessage({privateKey:this.privateKey,message:e})}getDefaultChainId(){return this.isTest?84532:8453}};function q(c){let e=_e[c.chainId];if(!e)throw new Error(`USDC not supported on chain ${c.chainId}`);let t={...xe,chainId:c.chainId,verifyingContract:e},s={from:c.fromAddress,to:c.toAddress,value:c.value,validAfter:c.validAfter,validBefore:c.validBefore,nonce:c.nonce};return {domain:t,message:s}}function K(){let c=new Uint8Array(32);return crypto.getRandomValues(c),`0x${Array.from(c).map(e=>e.toString(16).padStart(2,"0")).join("")}`}function Ae(c,e){return `MixrPay:${c}:${e.toLowerCase()}`}async function B(c){let e=Date.now(),t=Ae(e,c.address),s=await c.signMessage(t);return {address:c.address,timestamp:e,signature:s}}var J=z$1.object({query:z$1.string().describe('Search query (e.g. "web scraping", "email", "database")')}),G=z$1.object({tool_name:z$1.string().describe('Tool name in "merchant/tool" format'),arguments:z$1.record(z$1.unknown()).optional().describe("Arguments to pass to the tool")}),X=z$1.object({url:z$1.string().url().describe("The merchant API URL to call"),merchant_public_key:z$1.string().describe("The merchant's MixrPay public key (pk_live_... or pk_test_...)"),method:z$1.enum(["GET","POST","PUT","PATCH","DELETE"]).default("POST").describe("HTTP method"),body:z$1.unknown().optional().describe("Request body (will be JSON-serialized)"),price_usd:z$1.number().optional().describe("Expected price in USD for client-side validation")}),z=z$1.object({skill_id:z$1.string().describe("The skill ID to execute"),input:z$1.record(z$1.unknown()).optional().describe("Input parameters for the skill")}),Y=z$1.object({skill_id:z$1.string().describe("The skill ID to check")}),V=z$1.object({glama_id:z$1.string().describe('Glama server ID (e.g. "notion-mcp")'),glama_namespace:z$1.string().describe('Glama namespace (e.g. "notion")'),glama_slug:z$1.string().describe('Glama slug (e.g. "notion-mcp")'),tool_name:z$1.string().describe("Human-readable name for the tool"),tool_description:z$1.string().optional().describe("Optional description"),env_vars:z$1.record(z$1.string()).optional().describe("Environment variables for the MCP server (e.g. API keys)"),ttl_hours:z$1.number().min(1).max(168).optional().describe("Time-to-live in hours (default: 24, max: 168)")}),Z=z$1.object({status:z$1.enum(["provisioning","active","stopped","expired"]).optional().describe("Filter by status")}),Q=z$1.object({instance_id:z$1.string().describe("The instance ID to stop")}),ee=z$1.object({to:z$1.string().describe("Recipient address (0x...)"),amount_usdc:z$1.number().positive().describe("Amount in USDC (e.g. 10.5)")}),te=z$1.object({name:z$1.string().describe("Name for the child agent"),budget_usd:z$1.number().positive().describe("Budget to delegate in USD"),budget_period:z$1.enum(["daily","monthly","total"]).default("total").describe("Budget period"),max_per_tx_usd:z$1.number().positive().optional().describe("Max per-transaction limit in USD"),expires_in_days:z$1.number().min(1).max(365).optional().describe("Expiry in days (default: 30)")}),se=z$1.object({title:z$1.string().describe("Task title"),description:z$1.string().describe("Detailed task description"),budget_usd:z$1.number().positive().describe("Budget for the task in USD"),skills_required:z$1.array(z$1.string()).optional().describe("Required skill IDs")}),ne=z$1.object({status:z$1.string().optional().describe('Filter by status (e.g. "open", "in_progress")'),limit:z$1.number().min(1).max(100).optional().describe("Number of results (default: 20)")});function ae(c){let e=[{name:"check_balance",title:"Check Balance",description:"Get the USDC balance of the wallet on Base.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>({balanceUsd:await c.getBalance(),network:c.isTestnet()?"base-sepolia":"base"})},{name:"get_spending_stats",title:"Get Spending Stats",description:"Get session key spending limits and current usage (total spent, remaining daily/total limits, expiry).",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getSpendingStats()},{name:"get_session_info",title:"Get Session Info",description:"Get detailed session key information including limits, usage, expiry, and allowed merchants.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getSessionKeyInfo(true)},{name:"run_diagnostics",title:"Run Diagnostics",description:"Run a full health check on the wallet: API connectivity, session key validity, balance, and latency.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.runDiagnostics()},{name:"list_tools",title:"List Marketplace Tools",description:"Browse all available paid API tools on the MixrPay marketplace. Each tool includes pricing and description.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.listTools()},{name:"search_tools",title:"Search Tools",description:"Search the Glama MCP server directory for tools by keyword.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:J,handler:async s=>{let{query:n}=J.parse(s);return c.searchGlamaDirectory(n)}},{name:"call_tool",title:"Call Marketplace Tool",description:'Call a paid API tool on the MixrPay marketplace. Payment is automatic from the wallet. Tool names are in "merchant/tool" format (e.g. "firecrawl/scrape").',annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:G,handler:async s=>{let{tool_name:n,arguments:a}=G.parse(s);return c.callTool(n,a||{})}},{name:"call_merchant_api",title:"Call Merchant API",description:"Call any merchant API endpoint with x402 payment. The wallet handles authentication and payment automatically.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:X,handler:async s=>{let{url:n,merchant_public_key:a,method:r,body:i,price_usd:o}=X.parse(s),d=await c.callMerchantApi({url:n,merchantPublicKey:a,method:r,body:i,priceUsd:o}),g=await d.json().catch(()=>d.text());return {status:d.status,data:g}}},{name:"list_skills",title:"List Skills",description:"List all available skills (pre-built integrations) that the wallet can use.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.listSkills()},{name:"use_skill",title:"Use Skill",description:"Execute a skill by ID. Skills are pre-built integrations (e.g. web scraping, email sending).",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:z,handler:async s=>{let{skill_id:n,input:a}=z.parse(s);return c.useSkill(n,{input:a})}},{name:"get_skill_status",title:"Get Skill Status",description:"Check the status and configuration of a specific skill.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:Y,handler:async s=>{let{skill_id:n}=Y.parse(s);return c.getSkillStatus(n)}},{name:"deploy_jit_mcp",title:"Deploy JIT MCP Server",description:"Deploy a just-in-time MCP server from the Glama directory. Creates a temporary hosted MCP server instance.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:V,handler:async s=>{let{glama_id:n,glama_namespace:a,glama_slug:r,tool_name:i,tool_description:o,env_vars:d,ttl_hours:g}=V.parse(s);return c.deployJitMcp({glamaId:n,glamaNamespace:a,glamaSlug:r,toolName:i,toolDescription:o,envVars:d,ttlHours:g})}},{name:"list_jit_instances",title:"List JIT Instances",description:"List all deployed JIT MCP server instances.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:Z,handler:async s=>{let{status:n}=Z.parse(s);return c.listJitInstances(n?{status:n}:void 0)}},{name:"stop_jit_instance",title:"Stop JIT Instance",description:"Stop a running JIT MCP server instance.",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:false},inputSchema:Q,handler:async s=>{let{instance_id:n}=Q.parse(s);return await c.stopJitInstance(n),{success:true,instance_id:n}}},{name:"transfer_usdc",title:"Transfer USDC",description:"Transfer USDC from the self-custody wallet to another address on Base. Only available when the wallet has a self-custody wallet (AGENT_WALLET_KEY set).",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},inputSchema:ee,handler:async s=>{let{to:n,amount_usdc:a}=ee.parse(s);if(!await c.hasSelfCustodyWallet())throw new Error("No self-custody wallet configured. Set AGENT_WALLET_KEY to enable transfers.");return {success:true,txHash:await c.transferUSDC({to:n,amountUsdc:a}),to:n,amountUsdc:a}}},{name:"get_budget",title:"Get Available Budget",description:"Get the available delegation budget including remaining amount, whether spawning children is possible, and budget limits.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getAvailableBudget()},{name:"spawn_child",title:"Spawn Child Session",description:"Create a child invite with a delegated budget from this wallet. Returns an invite code that another agent can claim.",annotations:{readOnlyHint:false,openWorldHint:false},inputSchema:te,handler:async s=>{let{name:n,budget_usd:a,budget_period:r,max_per_tx_usd:i,expires_in_days:o}=te.parse(s);return c.spawnChildInvite({name:n,budgetUsd:a,budgetPeriod:r,maxPerTxUsd:i,expiresInDays:o})}},{name:"list_children",title:"List Child Sessions",description:"List all child sessions (agents) spawned from this wallet.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.listChildSessions()},{name:"create_task",title:"Create Task",description:"Create a new task on the MixrPay marketplace for other agents to complete.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:se,handler:async s=>{let{title:n,description:a,budget_usd:r,skills_required:i}=se.parse(s);return c.createTask({title:n,description:a,budgetUsd:r,skillsRequired:i})}},{name:"list_tasks",title:"List Tasks",description:"Browse available tasks on the MixrPay marketplace.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:ne,handler:async s=>{let{status:n,limit:a}=ne.parse(s);return c.listTasks({status:n,limit:a})}}];return {definitions:e,execute:async(s,n)=>{let a=e.find(r=>r.name===s);if(!a)throw new Error(`Unknown tool: ${s}`);try{let r=await a.handler(n);return JSON.stringify(r,null,2)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i)}}}}function re(c){if(c instanceof z$1.ZodObject){let e=c._def.shape(),t={},s=[];for(let[n,a]of Object.entries(e)){let r=a;t[n]=O(r),!(r instanceof z$1.ZodOptional)&&!(r instanceof z$1.ZodDefault)&&s.push(n);}return {type:"object",properties:t,...s.length>0?{required:s}:{}}}return {type:"object",properties:{}}}function O(c){let e=c;e instanceof z$1.ZodOptional&&(e=e._def.innerType),e instanceof z$1.ZodDefault&&(e=e._def.innerType);let t=c._def.description;if(e instanceof z$1.ZodString)return {type:"string",...t&&{description:t}};if(e instanceof z$1.ZodNumber)return {type:"number",...t&&{description:t}};if(e instanceof z$1.ZodBoolean)return {type:"boolean",...t&&{description:t}};if(e instanceof z$1.ZodEnum)return {type:"string",enum:e._def.values,...t&&{description:t}};if(e instanceof z$1.ZodArray)return {type:"array",items:O(e._def.type),...t&&{description:t}};if(e instanceof z$1.ZodRecord)return {type:"object",additionalProperties:O(e._def.valueType),...t&&{description:t}};if(e instanceof z$1.ZodObject){let s=e._def.shape(),n={};for(let[a,r]of Object.entries(s))n[a]=O(r);return {type:"object",properties:n,...t&&{description:t}}}return e instanceof z$1.ZodUnknown?{...t&&{description:t}}:{...t&&{description:t}}}var Ie="0.9.5",ie=".config/mixrpay",Re="wallet.json";function oe(){let c=process.env.MIXRPAY_WORKSPACE_DIR||process.env.OPENCLAW_WORKSPACE_DIR;return c?join(c,ie):join(homedir(),ie)}function N(){return join(oe(),Re)}async function le(c,e){let t=oe(),s=N();existsSync(t)||mkdirSync(t,{recursive:true,mode:448});let n={address:e.toLowerCase(),privateKey:c,createdAt:new Date().toISOString(),sdkVersion:Ie};writeFileSync(s,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384});try{chmodSync(s,384);}catch{}}async function L(){let c=process.env.MIXRPAY_WALLET_KEY;if(c){if(c.startsWith("0x")&&c.length===66)return c;if(c.length===64)return `0x${c}`;console.warn("[MixrPay] MIXRPAY_WALLET_KEY has invalid format, ignoring");}let e=N();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 ce(){let c=process.env.MIXRPAY_WALLET_KEY;return c&&(c.length===64||c.startsWith("0x")&&c.length===66)?true:existsSync(N())}async function de(c){let e=null,t=c.headers.get("X-Payment-Required");if(t)try{e=JSON.parse(t);}catch{}if(!e){let n=c.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 c.json();}catch{}if(!e)throw new P("Could not parse payment requirements from 402 response");if(!e.recipient)throw new P("Missing recipient in payment requirements");if(!e.amount)throw new P("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||K().slice(2),expiresAt:e.expiresAt||e.expires_at||s+300,description:e.description}}async function ue(c,e,t){let s=c.nonce.length===64?`0x${c.nonce}`:K(),a=BigInt(Math.floor(Date.now()/1e3))-60n,r=BigInt(c.expiresAt),{domain:i,message:o}=q({fromAddress:t,toAddress:c.recipient,value:c.amount,validAfter:a,validBefore:r,nonce:s,chainId:c.chainId}),d=await e.signTransferAuthorization(i,o),g={x402Version:1,scheme:"exact",network:c.chainId===8453?"base":"base-sepolia",payload:{signature:d,authorization:{from:t,to:c.recipient,value:c.amount.toString(),validAfter:a.toString(),validBefore:r.toString(),nonce:s}}};return btoa(JSON.stringify(g))}function ge(c){return Date.now()/1e3>c.expiresAt}function F(c){return Number(c.amount)/1e6}var He="0.11.0",_=process.env.MIXRPAY_BASE_URL||"https://www.mixrpay.com",ut="https://x402.org/facilitator",Ne=3e4,me={BASE_MAINNET:{chainId:8453,name:"Base",isTestnet:false},BASE_SEPOLIA:{chainId:84532,name:"Base Sepolia",isTestnet:true}},he={debug:0,info:1,warn:2,error:3,none:4},W=class{level;prefix;constructor(e="none",t="[MixrPay]"){this.level=e,this.prefix=t;}setLevel(e){this.level=e;}shouldLog(e){return he[e]>=he[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}`);}}},ye=class c{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=E.fromString(e.sessionKey),this.walletAddress=e.walletAddress||this.sessionKey.address,this.maxPaymentUsd=e.maxPaymentUsd,this.onPayment=e.onPayment,this.baseUrl=(e.baseUrl||_).replace(/\/$/,""),this.timeout=e.timeout||Ne,e.apiKey&&(this.apiKey=e.apiKey),this.logger=new W(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 S("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 S(`Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${a}'`)}let s=72;if(t.length!==s)throw new S(`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 S("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||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=register`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,name:s})});if(!u.ok){let y=await u.json().catch(()=>({})),f=y.error||`Registration failed with status ${u.status}`,h=y.request_id,w=(y.code||"").toLowerCase(),b="";u.status===503?b=" The service may be temporarily unavailable. Please try again later.":u.status===500?b=" This is a server error. Please contact support with the request ID.":(w==="missing_challenge"||w==="missing_signature")&&(b=" This may indicate an SDK bug. Please update to the latest version.");let j=h?`${f} (request_id: ${h})${b}`:`${f}${b}`;throw new l(j)}let p=await u.json();return {userId:p.user_id,depositAddress:p.deposit_address}}static async checkServerHealth(e){let t=(e||_).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||_).replace(/\/$/,""),d=privateKeyToAccount(t).address,g=await fetch(`${i}/api/v1/agent/challenge?wallet=${d}&action=session-key`);if(!g.ok){let w=await g.json().catch(()=>({}));throw new l(w.error||`Failed to get challenge: ${g.status}`)}let{challenge:u,message:p}=await g.json(),y=await signMessage({message:p,privateKey:t}),f=await fetch(`${i}/api/v1/agent/session-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:u,external_wallet:d,signature:y,spending_limit_usd:s,max_per_tx_usd:n,max_daily_usd:a,duration_days:r})});if(!f.ok){let w=await f.json().catch(()=>({}));throw new l(w.error||`Session key creation failed: ${f.status}`)}let h=await f.json();return {sessionKey:h.session_key,address:h.address,sessionKeyId:h.session_key_id,expiresAt:new Date(h.expires_at),limits:{maxTotalUsd:h.limits.max_total_usd,maxPerTxUsd:h.limits.max_per_tx_usd,maxDailyUsd:h.limits.max_daily_usd}}}static async getStatus(e){let{privateKey:t}=e,s=(e.baseUrl||_).replace(/\/$/,""),a=privateKeyToAccount(t).address,r=await fetch(`${s}/api/v1/agent/challenge?wallet=${a}&action=status`);if(!r.ok){let p=await r.json().catch(()=>({}));throw new l(p.error||`Failed to get challenge: ${r.status}`)}let{challenge:i,message:o}=await r.json(),d=await signMessage({message:o,privateKey:t}),g=await fetch(`${s}/api/v1/agent/status?challenge=${i}&external_wallet=${a}&signature=${encodeURIComponent(d)}`);if(!g.ok){let p=await g.json().catch(()=>({}));throw new l(p.error||`Failed to get status: ${g.status}`)}let u=await g.json();return {depositAddress:u.deposit_address,balanceUsd:u.balance_usd,activeSessions:u.active_sessions.map(p=>({id:p.id,expiresAt:new Date(p.expires_at),totalSpentUsd:p.total_spent_usd,remainingUsd:p.remaining_usd,maxTotalUsd:p.max_total_usd})),totalSpentUsd:u.total_spent_usd}}static async revokeSessionKey(e){let{privateKey:t,sessionKeyId:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=revoke`);if(!i.ok){let p=await i.json().catch(()=>({}));throw new l(p.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,session_key_id:s})});if(!u.ok){let p=await u.json().catch(()=>({}));throw new l(p.error||`Revocation failed: ${u.status}`)}return true}static async withdraw(e){let{privateKey:t,amountUsd:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=withdraw`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,to_address:r,amount_usd:s})});if(!u.ok){let y=await u.json().catch(()=>({}));throw new l(y.error||`Withdrawal failed: ${u.status}`)}let p=await u.json();return {txHash:p.tx_hash,amountUsd:p.amount_usd,remainingBalanceUsd:p.remaining_balance_usd}}static async claimInvite(e){let{inviteCode:t,privateKey:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(s).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=claim-invite`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g})});if(!u.ok){let f=(await u.json().catch(()=>({}))).error||`Failed to claim invite: ${u.status}`,h="";throw u.status===404?h=" The invite code may be invalid or misspelled.":u.status===400&&(f.includes("already claimed")?h=" This invite has already been used by another agent.":f.includes("expired")?h=" Ask the wallet owner to create a new invite.":f.includes("revoked")&&(h=" The wallet owner has revoked this invite.")),new l(`${f}${h}`)}let p=await u.json();return {sessionKey:p.session_key,address:p.address,sessionKeyId:p.session_key_id,expiresAt:new Date(p.expires_at),limits:{budgetUsd:p.limits.budget_usd,budgetPeriod:p.limits.budget_period,maxPerTxUsd:p.limits.max_per_tx_usd},allowedMerchants:p.allowed_merchants||[],inviterName:p.inviter_name||"Anonymous"}}static async activate(e,t){let s=(t?.baseUrl||_).replace(/\/$/,""),n=new c({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||_).replace(/\/$/,""),s=e?.logLevel||"none",n=process.env.MIXRPAY_INSTANCE_ID;if(e?.sessionKey){let g=new c({sessionKey:e.sessionKey,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&g.setAgentInstanceId(n),g}let a=process.env.MIXRPAY_SESSION_KEY;if(a){let g=new c({sessionKey:a,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&g.setAgentInstanceId(n),g}let r=process.env.MIXRPAY_API_KEY||process.env.MIXRPAY_AGENT_TOKEN;if(r&&(r.startsWith("agt_live_")||r.startsWith("agt_test_")))return c.fromApiKey(r,{baseUrl:t,logLevel:s});let i=e?.accessCode||process.env.MIXRPAY_ACCESS_CODE;if(i)return c.fromAccessCode(i,{baseUrl:t,logLevel:s});let o=e?.masterKey||process.env.MIXRPAY_MASTER_KEY,d=e?.agentName||process.env.MIXRPAY_AGENT_NAME;if(o&&d)return c.fromMasterKey(o,d,{baseUrl:t,logLevel:s});try{let{loadCredentials:g}=await import('./credentials-XJV2ESBQ.js'),u=g();if(u.success&&u.credentials.sessionKey){let p=new c({sessionKey:u.credentials.sessionKey,baseUrl:u.credentials.baseUrl||t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment,apiKey:u.credentials.apiToken});return n&&p.setAgentInstanceId(n),p}if(u.success&&u.credentials.apiToken)return c.fromApiKey(u.credentials.apiToken,{baseUrl:t,logLevel:s});if(u.success&&u.credentials.masterKey&&u.credentials.defaultAgentName)return c.fromMasterKey(u.credentials.masterKey,u.credentials.defaultAgentName,{baseUrl:t,logLevel:s})}catch{}if(e?.interactive)return c.deviceFlowLogin({baseUrl:t,logLevel:s});throw new l(`No MixrPay credentials found. Options:
2
+ import {fileURLToPath}from'url';import {join,dirname}from'path';import {privateKeyToAccount,signMessage,generatePrivateKey,signTypedData}from'viem/accounts';import {z as z$1}from'zod';import {createWalletClient,http,parseUnits,encodeFunctionData}from'viem';import {base}from'viem/chains';import {existsSync,readFileSync,mkdirSync,writeFileSync,chmodSync}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}},v=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://mixr.network/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;}},T=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}},S=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;}},P=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;}},I=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;}},R=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;}};var _e={8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",84532:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"},xe={name:"USD Coin",version:"2"},Se={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"}]},E=class c{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 S("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 c(r,n==="test")}catch(r){throw new S(`Failed to decode session key: ${r}`)}}async signTransferAuthorization(e,t){return signTypedData({privateKey:this.privateKey,domain:e,types:Se,primaryType:"TransferWithAuthorization",message:t})}async signMessage(e){return signMessage({privateKey:this.privateKey,message:e})}getDefaultChainId(){return this.isTest?84532:8453}};function q(c){let e=_e[c.chainId];if(!e)throw new Error(`USDC not supported on chain ${c.chainId}`);let t={...xe,chainId:c.chainId,verifyingContract:e},s={from:c.fromAddress,to:c.toAddress,value:c.value,validAfter:c.validAfter,validBefore:c.validBefore,nonce:c.nonce};return {domain:t,message:s}}function K(){let c=new Uint8Array(32);return crypto.getRandomValues(c),`0x${Array.from(c).map(e=>e.toString(16).padStart(2,"0")).join("")}`}function Ae(c,e){return `MixrPay:${c}:${e.toLowerCase()}`}async function B(c){let e=Date.now(),t=Ae(e,c.address),s=await c.signMessage(t);return {address:c.address,timestamp:e,signature:s}}var J=z$1.object({query:z$1.string().describe('Search query (e.g. "web scraping", "email", "database")')}),G=z$1.object({tool_name:z$1.string().describe('Tool name in "merchant/tool" format'),arguments:z$1.record(z$1.unknown()).optional().describe("Arguments to pass to the tool")}),X=z$1.object({url:z$1.string().url().describe("The merchant API URL to call"),merchant_public_key:z$1.string().describe("The merchant's MixrPay public key (pk_live_... or pk_test_...)"),method:z$1.enum(["GET","POST","PUT","PATCH","DELETE"]).default("POST").describe("HTTP method"),body:z$1.unknown().optional().describe("Request body (will be JSON-serialized)"),price_usd:z$1.number().optional().describe("Expected price in USD for client-side validation")}),z=z$1.object({skill_id:z$1.string().describe("The skill ID to execute"),input:z$1.record(z$1.unknown()).optional().describe("Input parameters for the skill")}),Y=z$1.object({skill_id:z$1.string().describe("The skill ID to check")}),V=z$1.object({glama_id:z$1.string().describe('Glama server ID (e.g. "notion-mcp")'),glama_namespace:z$1.string().describe('Glama namespace (e.g. "notion")'),glama_slug:z$1.string().describe('Glama slug (e.g. "notion-mcp")'),tool_name:z$1.string().describe("Human-readable name for the tool"),tool_description:z$1.string().optional().describe("Optional description"),env_vars:z$1.record(z$1.string()).optional().describe("Environment variables for the MCP server (e.g. API keys)"),ttl_hours:z$1.number().min(1).max(168).optional().describe("Time-to-live in hours (default: 24, max: 168)")}),Z=z$1.object({status:z$1.enum(["provisioning","active","stopped","expired"]).optional().describe("Filter by status")}),Q=z$1.object({instance_id:z$1.string().describe("The instance ID to stop")}),ee=z$1.object({to:z$1.string().describe("Recipient address (0x...)"),amount_usdc:z$1.number().positive().describe("Amount in USDC (e.g. 10.5)")}),te=z$1.object({name:z$1.string().describe("Name for the child agent"),budget_usd:z$1.number().positive().describe("Budget to delegate in USD"),budget_period:z$1.enum(["daily","monthly","total"]).default("total").describe("Budget period"),max_per_tx_usd:z$1.number().positive().optional().describe("Max per-transaction limit in USD"),expires_in_days:z$1.number().min(1).max(365).optional().describe("Expiry in days (default: 30)")}),se=z$1.object({title:z$1.string().describe("Task title"),description:z$1.string().describe("Detailed task description"),budget_usd:z$1.number().positive().describe("Budget for the task in USD"),skills_required:z$1.array(z$1.string()).optional().describe("Required skill IDs")}),ne=z$1.object({status:z$1.string().optional().describe('Filter by status (e.g. "open", "in_progress")'),limit:z$1.number().min(1).max(100).optional().describe("Number of results (default: 20)")});function ae(c){let e=[{name:"check_balance",title:"Check Balance",description:"Get the USDC balance of the wallet on Base.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>({balanceUsd:await c.getBalance(),network:c.isTestnet()?"base-sepolia":"base"})},{name:"get_spending_stats",title:"Get Spending Stats",description:"Get session key spending limits and current usage (total spent, remaining daily/total limits, expiry).",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getSpendingStats()},{name:"get_session_info",title:"Get Session Info",description:"Get detailed session key information including limits, usage, expiry, and allowed merchants.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getSessionKeyInfo(true)},{name:"run_diagnostics",title:"Run Diagnostics",description:"Run a full health check on the wallet: API connectivity, session key validity, balance, and latency.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.runDiagnostics()},{name:"list_tools",title:"List Marketplace Tools",description:"Browse all available paid API tools on the MixrPay marketplace. Each tool includes pricing and description.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.listTools()},{name:"search_tools",title:"Search Tools",description:"Search the Glama MCP server directory for tools by keyword.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:J,handler:async s=>{let{query:n}=J.parse(s);return c.searchGlamaDirectory(n)}},{name:"call_tool",title:"Call Marketplace Tool",description:'Call a paid API tool on the MixrPay marketplace. Payment is automatic from the wallet. Tool names are in "merchant/tool" format (e.g. "firecrawl/scrape").',annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:G,handler:async s=>{let{tool_name:n,arguments:a}=G.parse(s);return c.callTool(n,a||{})}},{name:"call_merchant_api",title:"Call Merchant API",description:"Call any merchant API endpoint with x402 payment. The wallet handles authentication and payment automatically.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:X,handler:async s=>{let{url:n,merchant_public_key:a,method:r,body:i,price_usd:o}=X.parse(s),d=await c.callMerchantApi({url:n,merchantPublicKey:a,method:r,body:i,priceUsd:o}),g=await d.json().catch(()=>d.text());return {status:d.status,data:g}}},{name:"list_skills",title:"List Skills",description:"List all available skills (pre-built integrations) that the wallet can use.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:null,handler:async()=>c.listSkills()},{name:"use_skill",title:"Use Skill",description:"Execute a skill by ID. Skills are pre-built integrations (e.g. web scraping, email sending).",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:z,handler:async s=>{let{skill_id:n,input:a}=z.parse(s);return c.useSkill(n,{input:a})}},{name:"get_skill_status",title:"Get Skill Status",description:"Check the status and configuration of a specific skill.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:Y,handler:async s=>{let{skill_id:n}=Y.parse(s);return c.getSkillStatus(n)}},{name:"deploy_jit_mcp",title:"Deploy JIT MCP Server",description:"Deploy a just-in-time MCP server from the Glama directory. Creates a temporary hosted MCP server instance.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:V,handler:async s=>{let{glama_id:n,glama_namespace:a,glama_slug:r,tool_name:i,tool_description:o,env_vars:d,ttl_hours:g}=V.parse(s);return c.deployJitMcp({glamaId:n,glamaNamespace:a,glamaSlug:r,toolName:i,toolDescription:o,envVars:d,ttlHours:g})}},{name:"list_jit_instances",title:"List JIT Instances",description:"List all deployed JIT MCP server instances.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:Z,handler:async s=>{let{status:n}=Z.parse(s);return c.listJitInstances(n?{status:n}:void 0)}},{name:"stop_jit_instance",title:"Stop JIT Instance",description:"Stop a running JIT MCP server instance.",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:false},inputSchema:Q,handler:async s=>{let{instance_id:n}=Q.parse(s);return await c.stopJitInstance(n),{success:true,instance_id:n}}},{name:"transfer_usdc",title:"Transfer USDC",description:"Transfer USDC from the self-custody wallet to another address on Base. Only available when the wallet has a self-custody wallet (AGENT_WALLET_KEY set).",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},inputSchema:ee,handler:async s=>{let{to:n,amount_usdc:a}=ee.parse(s);if(!await c.hasSelfCustodyWallet())throw new Error("No self-custody wallet configured. Set AGENT_WALLET_KEY to enable transfers.");return {success:true,txHash:await c.transferUSDC({to:n,amountUsdc:a}),to:n,amountUsdc:a}}},{name:"get_budget",title:"Get Available Budget",description:"Get the available delegation budget including remaining amount, whether spawning children is possible, and budget limits.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.getAvailableBudget()},{name:"spawn_child",title:"Spawn Child Session",description:"Create a child invite with a delegated budget from this wallet. Returns an invite code that another agent can claim.",annotations:{readOnlyHint:false,openWorldHint:false},inputSchema:te,handler:async s=>{let{name:n,budget_usd:a,budget_period:r,max_per_tx_usd:i,expires_in_days:o}=te.parse(s);return c.spawnChildInvite({name:n,budgetUsd:a,budgetPeriod:r,maxPerTxUsd:i,expiresInDays:o})}},{name:"list_children",title:"List Child Sessions",description:"List all child sessions (agents) spawned from this wallet.",annotations:{readOnlyHint:true,openWorldHint:false},inputSchema:null,handler:async()=>c.listChildSessions()},{name:"create_task",title:"Create Task",description:"Create a new task on the MixrPay marketplace for other agents to complete.",annotations:{readOnlyHint:false,openWorldHint:true},inputSchema:se,handler:async s=>{let{title:n,description:a,budget_usd:r,skills_required:i}=se.parse(s);return c.createTask({title:n,description:a,budgetUsd:r,skillsRequired:i})}},{name:"list_tasks",title:"List Tasks",description:"Browse available tasks on the MixrPay marketplace.",annotations:{readOnlyHint:true,openWorldHint:true},inputSchema:ne,handler:async s=>{let{status:n,limit:a}=ne.parse(s);return c.listTasks({status:n,limit:a})}}];return {definitions:e,execute:async(s,n)=>{let a=e.find(r=>r.name===s);if(!a)throw new Error(`Unknown tool: ${s}`);try{let r=await a.handler(n);return JSON.stringify(r,null,2)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i)}}}}function re(c){if(c instanceof z$1.ZodObject){let e=c._def.shape(),t={},s=[];for(let[n,a]of Object.entries(e)){let r=a;t[n]=O(r),!(r instanceof z$1.ZodOptional)&&!(r instanceof z$1.ZodDefault)&&s.push(n);}return {type:"object",properties:t,...s.length>0?{required:s}:{}}}return {type:"object",properties:{}}}function O(c){let e=c;e instanceof z$1.ZodOptional&&(e=e._def.innerType),e instanceof z$1.ZodDefault&&(e=e._def.innerType);let t=c._def.description;if(e instanceof z$1.ZodString)return {type:"string",...t&&{description:t}};if(e instanceof z$1.ZodNumber)return {type:"number",...t&&{description:t}};if(e instanceof z$1.ZodBoolean)return {type:"boolean",...t&&{description:t}};if(e instanceof z$1.ZodEnum)return {type:"string",enum:e._def.values,...t&&{description:t}};if(e instanceof z$1.ZodArray)return {type:"array",items:O(e._def.type),...t&&{description:t}};if(e instanceof z$1.ZodRecord)return {type:"object",additionalProperties:O(e._def.valueType),...t&&{description:t}};if(e instanceof z$1.ZodObject){let s=e._def.shape(),n={};for(let[a,r]of Object.entries(s))n[a]=O(r);return {type:"object",properties:n,...t&&{description:t}}}return e instanceof z$1.ZodUnknown?{...t&&{description:t}}:{...t&&{description:t}}}var Ie="0.9.5",ie=".config/mixrpay",Re="wallet.json";function oe(){let c=process.env.MIXRPAY_WORKSPACE_DIR||process.env.OPENCLAW_WORKSPACE_DIR;return c?join(c,ie):join(homedir(),ie)}function N(){return join(oe(),Re)}async function le(c,e){let t=oe(),s=N();existsSync(t)||mkdirSync(t,{recursive:true,mode:448});let n={address:e.toLowerCase(),privateKey:c,createdAt:new Date().toISOString(),sdkVersion:Ie};writeFileSync(s,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384});try{chmodSync(s,384);}catch{}}async function L(){let c=process.env.MIXRPAY_WALLET_KEY;if(c){if(c.startsWith("0x")&&c.length===66)return c;if(c.length===64)return `0x${c}`;console.warn("[MixrPay] MIXRPAY_WALLET_KEY has invalid format, ignoring");}let e=N();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 ce(){let c=process.env.MIXRPAY_WALLET_KEY;return c&&(c.length===64||c.startsWith("0x")&&c.length===66)?true:existsSync(N())}async function de(c){let e=null,t=c.headers.get("X-Payment-Required");if(t)try{e=JSON.parse(t);}catch{}if(!e){let n=c.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 c.json();}catch{}if(!e)throw new P("Could not parse payment requirements from 402 response");if(!e.recipient)throw new P("Missing recipient in payment requirements");if(!e.amount)throw new P("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||K().slice(2),expiresAt:e.expiresAt||e.expires_at||s+300,description:e.description}}async function ue(c,e,t){let s=c.nonce.length===64?`0x${c.nonce}`:K(),a=BigInt(Math.floor(Date.now()/1e3))-60n,r=BigInt(c.expiresAt),{domain:i,message:o}=q({fromAddress:t,toAddress:c.recipient,value:c.amount,validAfter:a,validBefore:r,nonce:s,chainId:c.chainId}),d=await e.signTransferAuthorization(i,o),g={x402Version:1,scheme:"exact",network:c.chainId===8453?"base":"base-sepolia",payload:{signature:d,authorization:{from:t,to:c.recipient,value:c.amount.toString(),validAfter:a.toString(),validBefore:r.toString(),nonce:s}}};return btoa(JSON.stringify(g))}function ge(c){return Date.now()/1e3>c.expiresAt}function F(c){return Number(c.amount)/1e6}var He="0.11.0",_=process.env.MIXRPAY_BASE_URL||"https://mixr.network",ut="https://x402.org/facilitator",Ne=3e4,me={BASE_MAINNET:{chainId:8453,name:"Base",isTestnet:false},BASE_SEPOLIA:{chainId:84532,name:"Base Sepolia",isTestnet:true}},he={debug:0,info:1,warn:2,error:3,none:4},W=class{level;prefix;constructor(e="none",t="[MixrPay]"){this.level=e,this.prefix=t;}setLevel(e){this.level=e;}shouldLog(e){return he[e]>=he[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}`);}}},ye=class c{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=E.fromString(e.sessionKey),this.walletAddress=e.walletAddress||this.sessionKey.address,this.maxPaymentUsd=e.maxPaymentUsd,this.onPayment=e.onPayment,this.baseUrl=(e.baseUrl||_).replace(/\/$/,""),this.timeout=e.timeout||Ne,e.apiKey&&(this.apiKey=e.apiKey),this.logger=new W(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 S("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 S(`Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${a}'`)}let s=72;if(t.length!==s)throw new S(`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 S("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||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=register`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,name:s})});if(!u.ok){let y=await u.json().catch(()=>({})),f=y.error||`Registration failed with status ${u.status}`,h=y.request_id,w=(y.code||"").toLowerCase(),b="";u.status===503?b=" The service may be temporarily unavailable. Please try again later.":u.status===500?b=" This is a server error. Please contact support with the request ID.":(w==="missing_challenge"||w==="missing_signature")&&(b=" This may indicate an SDK bug. Please update to the latest version.");let j=h?`${f} (request_id: ${h})${b}`:`${f}${b}`;throw new l(j)}let p=await u.json();return {userId:p.user_id,depositAddress:p.deposit_address}}static async checkServerHealth(e){let t=(e||_).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||_).replace(/\/$/,""),d=privateKeyToAccount(t).address,g=await fetch(`${i}/api/v1/agent/challenge?wallet=${d}&action=session-key`);if(!g.ok){let w=await g.json().catch(()=>({}));throw new l(w.error||`Failed to get challenge: ${g.status}`)}let{challenge:u,message:p}=await g.json(),y=await signMessage({message:p,privateKey:t}),f=await fetch(`${i}/api/v1/agent/session-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:u,external_wallet:d,signature:y,spending_limit_usd:s,max_per_tx_usd:n,max_daily_usd:a,duration_days:r})});if(!f.ok){let w=await f.json().catch(()=>({}));throw new l(w.error||`Session key creation failed: ${f.status}`)}let h=await f.json();return {sessionKey:h.session_key,address:h.address,sessionKeyId:h.session_key_id,expiresAt:new Date(h.expires_at),limits:{maxTotalUsd:h.limits.max_total_usd,maxPerTxUsd:h.limits.max_per_tx_usd,maxDailyUsd:h.limits.max_daily_usd}}}static async getStatus(e){let{privateKey:t}=e,s=(e.baseUrl||_).replace(/\/$/,""),a=privateKeyToAccount(t).address,r=await fetch(`${s}/api/v1/agent/challenge?wallet=${a}&action=status`);if(!r.ok){let p=await r.json().catch(()=>({}));throw new l(p.error||`Failed to get challenge: ${r.status}`)}let{challenge:i,message:o}=await r.json(),d=await signMessage({message:o,privateKey:t}),g=await fetch(`${s}/api/v1/agent/status?challenge=${i}&external_wallet=${a}&signature=${encodeURIComponent(d)}`);if(!g.ok){let p=await g.json().catch(()=>({}));throw new l(p.error||`Failed to get status: ${g.status}`)}let u=await g.json();return {depositAddress:u.deposit_address,balanceUsd:u.balance_usd,activeSessions:u.active_sessions.map(p=>({id:p.id,expiresAt:new Date(p.expires_at),totalSpentUsd:p.total_spent_usd,remainingUsd:p.remaining_usd,maxTotalUsd:p.max_total_usd})),totalSpentUsd:u.total_spent_usd}}static async revokeSessionKey(e){let{privateKey:t,sessionKeyId:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=revoke`);if(!i.ok){let p=await i.json().catch(()=>({}));throw new l(p.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,session_key_id:s})});if(!u.ok){let p=await u.json().catch(()=>({}));throw new l(p.error||`Revocation failed: ${u.status}`)}return true}static async withdraw(e){let{privateKey:t,amountUsd:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(t).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=withdraw`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g,to_address:r,amount_usd:s})});if(!u.ok){let y=await u.json().catch(()=>({}));throw new l(y.error||`Withdrawal failed: ${u.status}`)}let p=await u.json();return {txHash:p.tx_hash,amountUsd:p.amount_usd,remainingBalanceUsd:p.remaining_balance_usd}}static async claimInvite(e){let{inviteCode:t,privateKey:s}=e,n=(e.baseUrl||_).replace(/\/$/,""),r=privateKeyToAccount(s).address,i=await fetch(`${n}/api/v1/agent/challenge?wallet=${r}&action=claim-invite`);if(!i.ok){let y=await i.json().catch(()=>({}));throw new l(y.error||`Failed to get challenge: ${i.status}`)}let{challenge:o,message:d}=await i.json(),g=await signMessage({message:d,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:g})});if(!u.ok){let f=(await u.json().catch(()=>({}))).error||`Failed to claim invite: ${u.status}`,h="";throw u.status===404?h=" The invite code may be invalid or misspelled.":u.status===400&&(f.includes("already claimed")?h=" This invite has already been used by another agent.":f.includes("expired")?h=" Ask the wallet owner to create a new invite.":f.includes("revoked")&&(h=" The wallet owner has revoked this invite.")),new l(`${f}${h}`)}let p=await u.json();return {sessionKey:p.session_key,address:p.address,sessionKeyId:p.session_key_id,expiresAt:new Date(p.expires_at),limits:{budgetUsd:p.limits.budget_usd,budgetPeriod:p.limits.budget_period,maxPerTxUsd:p.limits.max_per_tx_usd},allowedMerchants:p.allowed_merchants||[],inviterName:p.inviter_name||"Anonymous"}}static async activate(e,t){let s=(t?.baseUrl||_).replace(/\/$/,""),n=new c({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||_).replace(/\/$/,""),s=e?.logLevel||"none",n=process.env.MIXRPAY_INSTANCE_ID;if(e?.sessionKey){let g=new c({sessionKey:e.sessionKey,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&g.setAgentInstanceId(n),g}let a=process.env.MIXRPAY_SESSION_KEY;if(a){let g=new c({sessionKey:a,baseUrl:t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment});return n&&g.setAgentInstanceId(n),g}let r=process.env.MIXRPAY_API_KEY||process.env.MIXRPAY_AGENT_TOKEN;if(r&&(r.startsWith("agt_live_")||r.startsWith("agt_test_")))return c.fromApiKey(r,{baseUrl:t,logLevel:s});let i=e?.accessCode||process.env.MIXRPAY_ACCESS_CODE;if(i)return c.fromAccessCode(i,{baseUrl:t,logLevel:s});let o=e?.masterKey||process.env.MIXRPAY_MASTER_KEY,d=e?.agentName||process.env.MIXRPAY_AGENT_NAME;if(o&&d)return c.fromMasterKey(o,d,{baseUrl:t,logLevel:s});try{let{loadCredentials:g}=await import('./credentials-XJV2ESBQ.js'),u=g();if(u.success&&u.credentials.sessionKey){let p=new c({sessionKey:u.credentials.sessionKey,baseUrl:u.credentials.baseUrl||t,logLevel:s,maxPaymentUsd:e?.maxPaymentUsd,onPayment:e?.onPayment,apiKey:u.credentials.apiToken});return n&&p.setAgentInstanceId(n),p}if(u.success&&u.credentials.apiToken)return c.fromApiKey(u.credentials.apiToken,{baseUrl:t,logLevel:s});if(u.success&&u.credentials.masterKey&&u.credentials.defaultAgentName)return c.fromMasterKey(u.credentials.masterKey,u.credentials.defaultAgentName,{baseUrl:t,logLevel:s})}catch{}if(e?.interactive)return c.deviceFlowLogin({baseUrl:t,logLevel:s});throw new l(`No MixrPay credentials found. Options:
3
3
  1. Set MIXRPAY_SESSION_KEY environment variable
4
4
  2. Set MIXRPAY_API_KEY or MIXRPAY_AGENT_TOKEN environment variable (agt_live_xxx)
5
5
  3. Set MIXRPAY_ACCESS_CODE environment variable (mixr-xxx)