keyring-agent-core 0.2.21 → 0.2.22

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,4 +1,4 @@
1
- "use strict";var dr=Object.create;var gn=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,gr=Object.prototype.hasOwnProperty;var fr=(c,e)=>{for(var t in e)gn(c,t,{get:e[t],enumerable:!0})},po=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pr(e))!gr.call(c,r)&&r!==t&&gn(c,r,{get:()=>e[r],enumerable:!(n=mr(e,r))||n.enumerable});return c};var yr=(c,e,t)=>(t=c!=null?dr(hr(c)):{},po(e||!c||!c.__esModule?gn(t,"default",{value:c,enumerable:!0}):t,c)),br=c=>po(gn({},"__esModule",{value:!0}),c);var Na={};fr(Na,{AI_AGENT_TOOL_NAMES:()=>Fn,AgentCore:()=>Yn,ApproveTokenTool:()=>Ft,BaseNftAiTool:()=>fe,BaseNftMessageTool:()=>ct,BaseSwapService:()=>Ue,BaseTool:()=>T,BaseWalletActionTool:()=>le,BuyTokenTool:()=>Ht,ChatHistory:()=>Kt,DEFAULT_CHAIN:()=>ge,DEFAULT_PROVIDER:()=>rn,DEFAULT_RPC_BY_CHAIN:()=>ie,DebridgeAdapter:()=>St,EstimatePoolYieldTool:()=>Ct,GeminiProvider:()=>ne,GeminiSearchAiTool:()=>pt,HEX_TO_PANTOGRAPH:()=>Uo,KnowledgeBase:()=>zt,MoralisService:()=>R,NFTContractInfoTool:()=>dt,NFTMetadataTool:()=>mt,NFT_AGENT_TOOL_NAMES:()=>qn,OpenAddLiquidityFormTool:()=>Pt,POOL_AGENT_TOOL_NAMES:()=>$n,PantographService:()=>te,PoolByAddressTool:()=>bt,PoolDetailTool:()=>ft,PoolFallbackAiTool:()=>ht,PoolSearchTool:()=>yt,PoolService:()=>Oe,PreviewAddLiquidityTool:()=>_t,RelayAdapter:()=>At,Router:()=>Qt,SUPPORTED_CHAINS:()=>$e,SUPPORTED_CHAINS_LABEL:()=>Ne,SWAP_PROVIDER_CONFIG:()=>Un,SendNativeTool:()=>Mt,SendNftTool:()=>Yt,SendTokenTool:()=>qt,Subagent:()=>j,SubgraphAddPoolTool:()=>Dt,SubgraphCoinPoolPairsTool:()=>Lt,SubgraphPoolByAddressTool:()=>Rt,SubgraphPoolByPositionIdTool:()=>Nt,SubgraphPoolSearchTool:()=>Et,SubgraphPositionDetailTool:()=>It,SubgraphTrendingPoolsTool:()=>Ut,Summarizer:()=>jt,SwapServiceFactory:()=>De,SwapTokenTool:()=>Gt,Synthesizer:()=>Xt,TOKEN_AGENT_TOOL_NAMES:()=>Mn,TRANSFER_TOPIC:()=>zo,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Ro,TokenAnalyticsTool:()=>je,TokenHoldersTool:()=>Ke,TokenInfoTool:()=>Ye,TokenScoreTool:()=>ze,ToolRegistry:()=>Fe,TopGainersTool:()=>Xe,TopPoolsTool:()=>gt,TransactionByHashTool:()=>lt,TrendingTokensTool:()=>Qe,UNISWAP_CHAIN_SLUG:()=>an,UpstashKnowledgeBase:()=>Re,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wn,WALLET_AGENT_TOOL_NAMES:()=>Bn,WalletApprovalsTool:()=>rt,WalletDefiPositionsTool:()=>at,WalletDefiProtocolPositionsTool:()=>it,WalletDefiSummaryTool:()=>st,WalletHistoryTool:()=>Ze,WalletNFTsTool:()=>ut,WalletNetWorthTool:()=>Tn,WalletNftTransfersTool:()=>tt,WalletPnlSummaryTool:()=>nt,WalletPnlTool:()=>ot,WalletTokenBalancesTool:()=>Je,WalletTokenTransfersTool:()=>et,ZERO_ADDRESS:()=>M,buildRangePresets:()=>lo,buildUniswapPoolUrl:()=>re,clampTick:()=>Te,configureSupportedChains:()=>bn,createAiAgent:()=>mn,createDefaultSubagents:()=>Vn,createNftAgent:()=>dn,createPoolAgent:()=>pn,createTokenAgent:()=>un,createWalletActionAgent:()=>hn,createWalletAgent:()=>cn,ethCallAt:()=>Yo,ethCallByChain:()=>io,getAffiliateFee:()=>vt,getChainMeta:()=>X,getDefaultRpcUrl:()=>Rs,getGatewayAddress:()=>Nn,getNativeTokenInfo:()=>xt,getPositionManagerAddress:()=>In,getProviderByChain:()=>En,ingestKnowledgeBase:()=>cr,priceToTick:()=>Le,resolveRpcUrl:()=>Tt,roundTickToSpacing:()=>ve,rpcCall:()=>Ae,setRpcOverrides:()=>ao,swapServiceFactory:()=>ye,tickToPrice:()=>ue,toPantographChain:()=>tn});module.exports=br(Na);var go=yr(require("axios"));var ho="0.2.21";var kr=`keyring-agent-core/${ho} (Keyring Chatbot Agent; +https://keyring.app)`,vr=3e4,Tr=typeof process<"u"&&process.versions?.node!=null,jn=class{instance;constructor(e={}){this.instance=go.default.create({baseURL:e.baseURL,timeout:e.timeout??vr,validateStatus:()=>!0,headers:{Accept:"application/json",...Tr?{"User-Agent":e.userAgent??kr}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[a,i]of Object.entries(o.headers??{}))i!=null&&(s[a.toLowerCase()]=String(i));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},_=new jn;function I(c){let{data:e,status:t,statusText:n}=c,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=i=>i&&typeof i=="object"?i.message:void 0,a=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let i of a)if(typeof i=="string"&&i.trim())return i.trim()}return r}var fo={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Sr="https://nft.keyring.app/api/gemini-stable",Ar=new Set([408,429,500,502,503,504]),yo=3e4,fn=c=>new Promise(e=>setTimeout(e,c));function yn(c,e,t){if(t!=null&&t>0)return Math.min(t,yo);let n=Math.min(e*2**(c-1),yo);return n/2+Math.random()*(n/2)}function xr(c){if(!c)return null;let e=Number(c);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(c);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ne=class{model;maxTokens;temperature;baseUrl;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??Sr}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:a=1e3}=n??{},i=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of i){let p=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${p}]`)}}let l={contents:i,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(l.systemInstruction=r),t?.length?(l.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(l.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(l.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,d="Unknown error";for(let m=1;m<=s;m++){let p;try{p=await _.post(u,l,{headers:{"Content-Type":"application/json"}})}catch(b){if(d=b instanceof Error?b.message:String(b),m>=s)break;await fn(yn(m,a));continue}if(!p.ok){let b=typeof p.data=="string"?p.data:JSON.stringify(p.data)||p.statusText;if(d=`Gemini proxy error ${p.status}: ${b}`,!Ar.has(p.status))throw new Error(d);if(m>=s)break;let v=xr(p.headers["retry-after"]??null);await fn(yn(m,a,v));continue}if(p.data==null||typeof p.data!="object"){if(d="Gemini proxy returned invalid JSON",m>=s)break;await fn(yn(m,a));continue}let h=p.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let f="",y=[],k=g.content?.parts;if(!Array.isArray(k)||k.length===0){let b=g.finishReason;if(!(b==="SAFETY"||b==="RECITATION")&&m<s){d=`Gemini returned an empty turn (finishReason=${b??"none"})`,await fn(yn(m,a));continue}return{text:"",toolCalls:[]}}for(let b of k)b.text&&(f+=b.text),b.functionCall&&y.push({toolName:b.functionCall.name,args:b.functionCall.args??{},callId:b.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let w=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:f,toolCalls:y,usage:w}}throw new Error(d)}toContents(e){let t=[],n=[];for(let a of e){if(a.role==="system"){t.push(a.content);continue}if(a.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:a.toolName??"unknown",response:{result:a.content},...a.toolCallId?{id:a.toolCallId}:{}}}]});continue}if(a.role==="assistant"&&a.toolCalls?.length){n.push({role:"model",parts:a.toolCalls.map(i=>({functionCall:{name:i.toolName,args:i.args,...i.callId?{id:i.callId}:{}}}))});continue}n.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let r=[];for(let a of n){let i=r[r.length-1],l=a.parts.some(d=>d.functionCall),u=i?.parts.some(d=>d.functionCall);i&&i.role===a.role&&!l&&!u?i.parts.push(...a.parts):r.push({...a,parts:[...a.parts]})}let o=[];for(let a=0;a<r.length;a++){let i=r[a],l=o[o.length-1];i.role==="function"&&!l?.parts.some(d=>d.functionCall)||i.role==="model"&&i.parts.some(d=>d.functionCall)&&!(r[a+1]?.role==="function")||o.push(i)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
1
+ "use strict";var dr=Object.create;var gn=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,gr=Object.prototype.hasOwnProperty;var fr=(c,e)=>{for(var t in e)gn(c,t,{get:e[t],enumerable:!0})},po=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pr(e))!gr.call(c,r)&&r!==t&&gn(c,r,{get:()=>e[r],enumerable:!(n=mr(e,r))||n.enumerable});return c};var yr=(c,e,t)=>(t=c!=null?dr(hr(c)):{},po(e||!c||!c.__esModule?gn(t,"default",{value:c,enumerable:!0}):t,c)),br=c=>po(gn({},"__esModule",{value:!0}),c);var Na={};fr(Na,{AI_AGENT_TOOL_NAMES:()=>Fn,AgentCore:()=>Yn,ApproveTokenTool:()=>Ft,BaseNftAiTool:()=>fe,BaseNftMessageTool:()=>ct,BaseSwapService:()=>Ue,BaseTool:()=>T,BaseWalletActionTool:()=>le,BuyTokenTool:()=>Ht,ChatHistory:()=>Kt,DEFAULT_CHAIN:()=>ge,DEFAULT_PROVIDER:()=>rn,DEFAULT_RPC_BY_CHAIN:()=>ie,DebridgeAdapter:()=>St,EstimatePoolYieldTool:()=>Ct,GeminiProvider:()=>ne,GeminiSearchAiTool:()=>pt,HEX_TO_PANTOGRAPH:()=>Uo,KnowledgeBase:()=>zt,MoralisService:()=>R,NFTContractInfoTool:()=>dt,NFTMetadataTool:()=>mt,NFT_AGENT_TOOL_NAMES:()=>qn,OpenAddLiquidityFormTool:()=>Pt,POOL_AGENT_TOOL_NAMES:()=>$n,PantographService:()=>te,PoolByAddressTool:()=>bt,PoolDetailTool:()=>ft,PoolFallbackAiTool:()=>ht,PoolSearchTool:()=>yt,PoolService:()=>Oe,PreviewAddLiquidityTool:()=>_t,RelayAdapter:()=>At,Router:()=>Qt,SUPPORTED_CHAINS:()=>$e,SUPPORTED_CHAINS_LABEL:()=>Ne,SWAP_PROVIDER_CONFIG:()=>Un,SendNativeTool:()=>Mt,SendNftTool:()=>Yt,SendTokenTool:()=>qt,Subagent:()=>j,SubgraphAddPoolTool:()=>Dt,SubgraphCoinPoolPairsTool:()=>Lt,SubgraphPoolByAddressTool:()=>Rt,SubgraphPoolByPositionIdTool:()=>Nt,SubgraphPoolSearchTool:()=>Et,SubgraphPositionDetailTool:()=>It,SubgraphTrendingPoolsTool:()=>Ut,Summarizer:()=>jt,SwapServiceFactory:()=>De,SwapTokenTool:()=>Gt,Synthesizer:()=>Xt,TOKEN_AGENT_TOOL_NAMES:()=>Mn,TRANSFER_TOPIC:()=>zo,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Ro,TokenAnalyticsTool:()=>je,TokenHoldersTool:()=>Ke,TokenInfoTool:()=>Ye,TokenScoreTool:()=>ze,ToolRegistry:()=>Fe,TopGainersTool:()=>Xe,TopPoolsTool:()=>gt,TransactionByHashTool:()=>lt,TrendingTokensTool:()=>Qe,UNISWAP_CHAIN_SLUG:()=>an,UpstashKnowledgeBase:()=>Re,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wn,WALLET_AGENT_TOOL_NAMES:()=>Bn,WalletApprovalsTool:()=>rt,WalletDefiPositionsTool:()=>at,WalletDefiProtocolPositionsTool:()=>it,WalletDefiSummaryTool:()=>st,WalletHistoryTool:()=>Ze,WalletNFTsTool:()=>ut,WalletNetWorthTool:()=>Tn,WalletNftTransfersTool:()=>tt,WalletPnlSummaryTool:()=>nt,WalletPnlTool:()=>ot,WalletTokenBalancesTool:()=>Je,WalletTokenTransfersTool:()=>et,ZERO_ADDRESS:()=>M,buildRangePresets:()=>lo,buildUniswapPoolUrl:()=>re,clampTick:()=>Te,configureSupportedChains:()=>bn,createAiAgent:()=>mn,createDefaultSubagents:()=>Vn,createNftAgent:()=>dn,createPoolAgent:()=>pn,createTokenAgent:()=>un,createWalletActionAgent:()=>hn,createWalletAgent:()=>cn,ethCallAt:()=>Yo,ethCallByChain:()=>io,getAffiliateFee:()=>vt,getChainMeta:()=>X,getDefaultRpcUrl:()=>Rs,getGatewayAddress:()=>Nn,getNativeTokenInfo:()=>xt,getPositionManagerAddress:()=>In,getProviderByChain:()=>En,ingestKnowledgeBase:()=>cr,priceToTick:()=>Le,resolveRpcUrl:()=>Tt,roundTickToSpacing:()=>ve,rpcCall:()=>Ae,setRpcOverrides:()=>ao,swapServiceFactory:()=>ye,tickToPrice:()=>ue,toPantographChain:()=>tn});module.exports=br(Na);var go=yr(require("axios"));var ho="0.2.22";var kr=`keyring-agent-core/${ho} (Keyring Chatbot Agent; +https://keyring.app)`,vr=3e4,Tr=typeof process<"u"&&process.versions?.node!=null,jn=class{instance;constructor(e={}){this.instance=go.default.create({baseURL:e.baseURL,timeout:e.timeout??vr,validateStatus:()=>!0,headers:{Accept:"application/json",...Tr?{"User-Agent":e.userAgent??kr}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[a,i]of Object.entries(o.headers??{}))i!=null&&(s[a.toLowerCase()]=String(i));return{ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,data:o.data,headers:s}}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},_=new jn;function I(c){let{data:e,status:t,statusText:n}=c,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=i=>i&&typeof i=="object"?i.message:void 0,a=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let i of a)if(typeof i=="string"&&i.trim())return i.trim()}return r}var fo={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Sr="https://nft.keyring.app/api/gemini-stable",Ar=new Set([408,429,500,502,503,504]),yo=3e4,fn=c=>new Promise(e=>setTimeout(e,c));function yn(c,e,t){if(t!=null&&t>0)return Math.min(t,yo);let n=Math.min(e*2**(c-1),yo);return n/2+Math.random()*(n/2)}function xr(c){if(!c)return null;let e=Number(c);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(c);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ne=class{model;maxTokens;temperature;baseUrl;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??Sr}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:a=1e3}=n??{},i=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of i){let p=m.parts.map(h=>h.functionCall?`fc:${h.functionCall.name}`:h.functionResponse?`fr:${h.functionResponse.name}`:`text:${(h.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${p}]`)}}let l={contents:i,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(l.systemInstruction=r),t?.length?(l.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(l.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(l.tools=[{googleSearch:{}}]);let u=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,d="Unknown error";for(let m=1;m<=s;m++){let p;try{p=await _.post(u,l,{headers:{"Content-Type":"application/json"}})}catch(b){if(d=b instanceof Error?b.message:String(b),m>=s)break;await fn(yn(m,a));continue}if(!p.ok){let b=typeof p.data=="string"?p.data:JSON.stringify(p.data)||p.statusText;if(d=`Gemini proxy error ${p.status}: ${b}`,!Ar.has(p.status))throw new Error(d);if(m>=s)break;let v=xr(p.headers["retry-after"]??null);await fn(yn(m,a,v));continue}if(p.data==null||typeof p.data!="object"){if(d="Gemini proxy returned invalid JSON",m>=s)break;await fn(yn(m,a));continue}let h=p.data,g=h.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let f="",y=[],k=g.content?.parts;if(!Array.isArray(k)||k.length===0){let b=g.finishReason;if(!(b==="SAFETY"||b==="RECITATION")&&m<s){d=`Gemini returned an empty turn (finishReason=${b??"none"})`,await fn(yn(m,a));continue}return{text:"",toolCalls:[]}}for(let b of k)b.text&&(f+=b.text),b.functionCall&&y.push({toolName:b.functionCall.name,args:b.functionCall.args??{},callId:b.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let w=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:f,toolCalls:y,usage:w}}throw new Error(d)}toContents(e){let t=[],n=[];for(let a of e){if(a.role==="system"){t.push(a.content);continue}if(a.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:a.toolName??"unknown",response:{result:a.content},...a.toolCallId?{id:a.toolCallId}:{}}}]});continue}if(a.role==="assistant"&&a.toolCalls?.length){n.push({role:"model",parts:a.toolCalls.map(i=>({functionCall:{name:i.toolName,args:i.args,...i.callId?{id:i.callId}:{}}}))});continue}n.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let r=[];for(let a of n){let i=r[r.length-1],l=a.parts.some(d=>d.functionCall),u=i?.parts.some(d=>d.functionCall);i&&i.role===a.role&&!l&&!u?i.parts.push(...a.parts):r.push({...a,parts:[...a.parts]})}let o=[];for(let a=0;a<r.length;a++){let i=r[a],l=o[o.length-1];i.role==="function"&&!l?.parts.some(d=>d.functionCall)||i.role==="model"&&i.parts.some(d=>d.functionCall)&&!(r[a+1]?.role==="function")||o.push(i)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
2
2
  `)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let s={type:fo[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:fo[o.items?.type??"string"]??"STRING"}),n[o.name]=s,o.required&&r.push(o.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var Fe=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-o}}catch(s){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var $e=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],Pr=new Set($e),_e=[...$e],bo=new Set(_e),ge="0x1",Ne="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function _r(c){return c.map(e=>Ve[e]??e).join(", ")}function bn(c){let e=new Set;if(c)for(let n of c){let r=zn(n);r&&e.add(r)}let t=$e.filter(n=>!e.has(n));_e=t.length>0?[...t]:[...$e],bo=new Set(_e),ge=_e.includes("0x1")?"0x1":_e[0],Ne=_r(_e)}var Cr={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function he(c){let e=zn(c);return e&&bo.has(e)?e:null}function zn(c){if(typeof c!="string")return null;let e=c.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Cr[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&Pr.has(n)?n:null}function wn(c){return he(c)!==null}function wo(){return[..._e]}var We=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ne}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ce=c=>typeof c=="string"&&c.trim()!=="";function kn(c,e){if(Ce(c)){let t=he(c);if(t)return t;throw new We(c.trim())}if(Ce(e?.chain)){let t=he(e.chain);if(t)return t;throw new We(e.chain.trim())}return null}function vn(c,e){return he(c)??he(e?.chain)??void 0}var Ve={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function N(c){let e=zn(c);return e&&Ve[e]?Ve[e]:typeof c=="string"&&c.trim()?c.trim():"the requested chain"}var Er={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function ko(c){if(typeof c!="string")return null;let e=c.trim().toLowerCase();return e?Er[e]??null:null}var Ur={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function vo(c){let e=he(c);return e?Ur[e]??null:null}function He(c,e){if(!Ce(c))return null;let t=he(c),n=he(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:Ve[t]??t,connectedLabel:Ve[n]??n}}function Rr(){return _e.map(c=>{let e=Ve[c]??c;return{label:e,prompt:e}})}var K=class extends Error{code="needs_chain_selection";buttons;constructor(e){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=e??Rr()}},Jt=class extends Error{code="no_wallet_connected";constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one."),this.name="NoWalletConnectedError"}};function Y(c,e){if(Ce(c))return c.trim();if(Ce(e?.walletAddress))return e.walletAddress.trim();throw new Jt}function U(c,e){if(Ce(c)){let t=he(c);if(t)return t;throw new We(c.trim())}if(Ce(e?.chain)){let t=he(e.chain);if(t)return t;throw new We(e.chain.trim())}if(Ce(e?.walletAddress))throw new K;return ge}var T=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),s=Nr(o);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-r,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(o){return o instanceof K?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof Jt?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-r}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}};function Nr(c){if(!c||typeof c!="object")return{data:c};let e=c,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:c};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var To=require("js-sha3");function B(c){return typeof c=="string"&&/^0x[0-9a-fA-F]{40}$/.test(c)}function Ir(c){return new Uint8Array(To.keccak256.arrayBuffer(c))}function Zt(c){let e=c.startsWith("0x")?c.slice(2):c,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function So(c){return"0x"+Array.from(c).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ao(c){return new TextEncoder().encode(c)}function Ie(...c){let e=c.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of c)t.set(r,n),n+=r.length;return t}function Lr(c,e=32){let t=new Uint8Array(e);return t.set(c,e-c.length),t}function Dr(c,e=32){let t=new Uint8Array(e);return t.set(c),t}function xo(c){let e=((c%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Zt(e)}function en(c){return xo(BigInt(c))}function Po(c){return c==="uint"?"uint256":c==="int"?"int256":c.match(/^uint$/)?"uint256":c.match(/^int$/)?"int256":c.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function _o(c){let e=Po(c.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(c.components??[]).map(_o).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Or(c){let e=(c.inputs??[]).map(_o).join(",");return`${c.name??""}(${e})`}function Qn(c,e){let t=qr(c.type);if(t){let[r,o]=t;return Br({...c,type:o},e,r)}if(c.type==="tuple")return Mr(c,e);if(c.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Lr(Zt(o.toLowerCase()))}}if(c.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Po(c.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:en(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:xo(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Zt(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Dr(o)}}if(n==="bytes"){let r=typeof e=="string"?Zt(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ie(en(r.length),s)}}if(n==="string"){let r=typeof e=="string"?Ao(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:Ie(en(r.length),s)}}throw new Error(`Unsupported ABI type: ${c.type}`)}function Xn(c){let e=0;for(let{dynamic:o,encoded:s}of c)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of c)o?(t.push(en(e+r)),n.push(s),r+=s.length):t.push(s);return Ie(...t,...n)}function Br(c,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let s of e){let a=Qn(c,s);a.dynamic&&(r=!0),o.push(a)}if(n||r){let s=Xn(o);if(n){let a=en(o.length);return{dynamic:!0,encoded:o.length>0?Ie(a,s):a}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Ie(...o.map(s=>s.encoded))}}function Mr(c,e){let t=c.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],a=Array.isArray(e)?e[o]:e[s.name??""],i=Qn(s,a);i.dynamic&&(n=!0),r.push(i)}return{dynamic:n,encoded:n?Xn(r):Ie(...r.map(o=>o.encoded))}}function qr(c){let e=c.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Fr(c,e){if(c.length!==e.length)throw new Error(`Expected ${c.length} values, got ${e.length}`);if(c.length===0)return"0x";let t=c.map((r,o)=>Qn(r,e[o])),n=Xn(t);return So(n)}function Ge({abi:c,functionName:e,args:t=[]}){let n=c.find(i=>(i.type==="function"||i.type===void 0)&&i.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Or(n),o=Ir(Ao(r)).slice(0,4),s=n.inputs??[],a=s.length===0||t.length===0?new Uint8Array(0):Zt(Fr(s,t).slice(2));return So(Ie(o,a))}var $r="https://wallet-api.pantograph.app",Wr="0x0000000000000000000000000000000000000000",Uo={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Ro={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"]};function tn(c){return Uo[c.toLowerCase()]||c}function Co(c){let e=[];for(let[t,n]of Object.entries(c))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Jn(c){let e=c,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function ee(c){if(c==null)return null;let e=typeof c=="number"?c:parseFloat(String(c));return Number.isFinite(e)?e:null}function Eo(c,e){let t=c.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ee(c.price_change_percentage_24h)??ee(c.priceChange24h)??ee(c.usd_price_24hr_percent_change)??ee(c.price_change_24h)??ee(c.priceChange);return{chainId:e,tokenAddress:c.address??c.token_address??"",name:c.name??null,symbol:c.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:c.logoURI??c.icon_image??c.logo??null,usdPrice:ee(c.price)??ee(c.usd_price),marketCap:ee(c.market_cap)??ee(c.marketCap),totalVolume:{"24h":ee(c.total_volume)??ee(c.volume24h)},pricePercentChange:{"24h":r}}}var te=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??$r).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=tn(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await _.get(o);if(!s.ok)return;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=new Map;for(let u of i)u.address&&l.set(u.address.toLowerCase(),{price:u.price!=null?parseFloat(String(u.price)):NaN,icon_image:u.icon_image});for(let u=0;u<e.length;u++){let d=l.get(e[u].token_address.toLowerCase());d&&(d.icon_image&&(e[u].logo=d.icon_image,e[u].thumbnail=d.icon_image),isNaN(d.price)||(e[u].usd_price=d.price,e[u].usd_value=parseFloat(e[u].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,t){try{let n=tn(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await _.get(r);if(!o.ok)return null;let s=o.data,a=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],i=e.toLowerCase()===Wr,l=a.find(u=>u.address?.toLowerCase()===e.toLowerCase()||i&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||i&&u.token_address==="");return l?Jn(l):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=tn(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await _.get(o);if(!s.ok)return n;let a=s.data,i=Array.isArray(a)?a:Array.isArray(a.data)?a.data:[],l=new Set(e.map(u=>u.toLowerCase()));for(let u of i){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&l.has(d)&&(n[d]=Jn(u))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||ge,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=Co({chainId:o,key:t}),a=`${this.baseUrl}/token-list?${s}`,i=await _.get(a);if(!i.ok)throw new Error(I(i));let l=i.data,u=[];return l?.data?u=Array.isArray(l.data)?l.data:Object.values(l.data).flat():typeof l=="object"&&!Array.isArray(l)&&(u=Object.values(l).flat()),{success:!0,data:u.map(Jn)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||ge,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=Ro[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[a,i]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),l=a.status==="fulfilled"?a.value:[],u=i.status==="fulfilled"?o.map(g=>i.value[g.toLowerCase()]).filter(g=>g!=null).map(g=>Eo(g,t)):[],d=new Set,m=[];for(let g of u){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(g))}let p=[];for(let g of l){let f=g.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(g))}let h=r!=null?[...m,...p].slice(0,r):[...m,...p.slice(0,n)];return await this.enrichTrendingMarketData(h,t),{success:!0,data:h}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let s=r[o.tokenAddress.toLowerCase()];s&&(o.marketCap==null&&(o.marketCap=ee(s.market_cap)??ee(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ee(s.total_volume)??ee(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=tn(e),o=Co({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,a=[];for(let i=0;i<5;i++){let l=await _.get(s);if(!l.ok)throw new Error(I(l));let u=l.data;if(a=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],a.length>0)break;i<4&&await new Promise(d=>setTimeout(d,2e3))}return a.map(i=>Eo(i,e))}async getTopGainers(e){let t=e?.chain||ge,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Vr="https://nft.keyring.app",Hr="https://nft.keyring.app",Gr=.01,E=5,F=1e3,Yr="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Kr="0x0000000000000000000000000000000000000000";function V(c){return c||ge}function $(c){let e=[];for(let[t,n]of Object.entries(c))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function W(c){return new Promise(e=>setTimeout(e,c))}function jr(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){let e=c;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Zn(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){let e=c;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var R=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Vr).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Hr).replace(/\/+$/,""),this.pantograph=new te({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:s=!1}=e;if(!t)return{success:!1,error:"Address is required"};let a=V(n),i="Unknown error";for(let l=1;l<=E;l++)try{let u={chain:a,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],m=null;do{m&&(u.cursor=m);let h=$(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,f=await _.get(g);if(!f.ok)throw new Error(I(f));let y=f.data,k=y?.data??y;k?.result?.length>0&&d.push(...k.result),m=k?.cursor??null}while(m);let p={result:d};return p?.result?.length>0&&(p.result=p.result.filter(h=>parseFloat(h.balance||"0")>0),p.result=p.result.map(h=>({...h,token_address:h.token_address.toLowerCase()===Yr?Kr:h.token_address})),await this.enrichTokenPrices(p.result,a),p.result=p.result.filter(h=>h.usd_value==null||h.usd_value>=Gr)),{success:!0,data:p}}catch(u){i=u instanceof Error?u.message:"Unknown error",l<E&&await W(F)}return{success:!1,error:i}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=V(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let a=1;a<=E;a++)try{let[i,l]=await Promise.allSettled([_.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${$({chain:r,addresses:[t]})}`),_.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${$({chain:r,include:"percent_change"})}`)]),u=null;if(i.status==="fulfilled"&&i.value.ok){let m=i.value.data;u=(Array.isArray(m)?m:Array.isArray(m?.data)?m.data:[])[0]??null}if(!u){o="Token metadata not found",a<E&&await W(F);continue}let d=null;if(l.status==="fulfilled"&&l.value.ok){let m=l.value.data;d=m?.data??m}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(i){o=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:a,includePrices:i,format:l="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=V(n),d="Unknown error";for(let m=1;m<=E;m++)try{let p={chain:u,format:l,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(p.cursor=s),i&&(p.include_prices=!0),a&&a.length>0&&(p.token_addresses=a);let h=$(p),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,f=await _.get(g);if(!f.ok)throw new Error(I(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(p){d=p instanceof Error?p.message:"Unknown error",m<E&&await W(F)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:a=!0,include:i}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!B(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let l=V(r),u="Unknown error";for(let d=1;d<=E;d++)try{let m={chain:l,format:o,normalizeMetadata:s,media_items:a};i&&(m.include=i);let p=$(m),h=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${p}`,g=await _.get(h);if(!g.ok)throw new Error(I(g));let f=g.data;return{success:!0,data:f?.data??f}}catch(m){u=m instanceof Error?m.message:"Unknown error",d<E&&await W(F)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:a,toBlock:i,cursor:l,order:u="DESC",includeInternalTransactions:d,nftMetadata:m}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let p=V(n),h=Math.max(1,Math.min(100,Math.floor(r))),g="Unknown error";for(let f=1;f<=E;f++)try{let y={chain:p,limit:h,order:u};o&&(y.from_date=o),s&&(y.to_date=s),a!=null&&(y.from_block=a),i!=null&&(y.to_block=i),l&&(y.cursor=l),d!=null&&(y.include_internal_transactions=d),m!=null&&(y.nft_metadata=m);let k=$(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${k}`,b=await _.get(w);if(!b.ok)throw new Error(I(b));let v=b.data;return{success:!0,data:v?.data??v}}catch(y){g=y instanceof Error?y.message:"Unknown error",f<E&&await W(F)}return{success:!1,error:g}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let m=V(n),p=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=E;g++)try{let f={chain:m,limit:p,order:d};s&&(f.from_date=s),a&&(f.to_date=a),i!=null&&(f.from_block=i),l!=null&&(f.to_block=l),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=$(f),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await _.get(k);if(!w.ok)throw new Error(I(w));let b=w.data;return{success:!0,data:b?.data??b}}catch(f){h=f instanceof Error?f.message:"Unknown error",g<E&&await W(F)}return{success:!1,error:h}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:u,order:d="DESC",includePrices:m,format:p="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let h=V(n),g=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=E;y++)try{let k={chain:h,limit:g,order:d,format:p};s&&(k.from_date=s),a&&(k.to_date=a),i!=null&&(k.from_block=i),l!=null&&(k.to_block=l),u&&(k.cursor=u),r?.length&&(k.contract_addresses=r),m!=null&&(k.include_prices=m);let w=$(k),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await _.get(b);if(!v.ok)throw new Error(I(v));let A=v.data;return{success:!0,data:A?.data??A}}catch(k){f=k instanceof Error?k.message:"Unknown error",y<E&&await W(F)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!B(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletNetWorth(e){let{address:t,chains:n,excludeSpam:r,excludeUnverifiedContracts:o,maxTokenInactivity:s,minPairSideLiquidityUsd:a}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet net worth is only supported for EVM addresses"};let i="Unknown error";for(let l=1;l<=E;l++)try{let u={};n&&n.length>0&&(u.chains=n.map(y=>V(y))),r!=null&&(u.exclude_spam=r),o!=null&&(u.exclude_unverified_contracts=o),s!=null&&(u.max_token_inactivity=s),a!=null&&(u.min_pair_side_liquidity_usd=a);let d=$(u),m=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/net-worth${d?`?${d}`:""}`,p=await _.get(m);if(!p.ok)throw new Error(I(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(u){i=u instanceof Error?u.message:"Unknown error",l<E&&await W(F)}return{success:!1,error:i}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=V(n),s="Unknown error";for(let a=1;a<=E;a++)try{let i={chain:o};r&&(i.days=r);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${l}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data;return{success:!0,data:m?.data??m}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=V(n),a="Unknown error";for(let i=1;i<=E;i++)try{let l={chain:s};r&&(l.days=r),o&&o.length>0&&(l.token_addresses=o.slice(0,25));let u=$(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,m=await _.get(d);if(!m.ok)throw new Error(I(m));let p=m.data;return{success:!0,data:p?.data??p}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<E&&await W(F)}return{success:!1,error:a}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=V(n),a="Unknown error";for(let i=1;i<=E;i++)try{let l={chain:s};r!=null&&(l.limit=r),o&&(l.cursor=o);let u=$(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,m=await _.get(d);if(!m.ok)throw new Error(I(m));let p=m.data;return{success:!0,data:p?.data??p}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<E&&await W(F)}return{success:!1,error:a}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!B(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chains:r}),i=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data,d=u?.data??u;return{success:!0,data:jr(d)}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!B(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=V(r),s="Unknown error";for(let a=1;a<=E;a++)try{let i=$({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${i}`,u=await _.get(l);if(!u.ok)throw new Error(I(u));let p=u.data.result;return{success:!0,data:{protocol_id:p.protocolId,protocol_name:p.protocolName,protocol_url:p.protocolUrl??"",protocol_logo:p.protocolLogo??"",total_usd_value:p.totalUsd??0,total_unclaimed_usd_value:p.totalUnclaimedUsd??null,positions:p.positions.map(g=>({label:g.label,address:g.address,balance_usd:g.balanceUsd??0,total_unclaimed_usd_value:g.unclaimedUsd??0,position_details:g.details,tokens:g.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!B(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!B(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=V(n),o="Unknown error";for(let s=1;s<=E;s++)try{let a=$({chain:r}),i=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${a}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data;return{success:!0,data:u?.data??u}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<E&&await W(F)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=E;o++)try{let s={};t&&(s.chain=V(t)),n!=null&&(s.limit=n);let a=$(s),i=`${this.baseUrl}/api/moralis/proxy/tokens/trending${a?`?${a}`:""}`,l=await _.get(i);if(!l.ok)throw new Error(I(l));let u=l.data,d=u?.data??u;return{success:!0,data:Zn(d)}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<E&&await W(F)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=E;a++)try{let i={};t&&(i.chain=V(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${l?`?${l}`:""}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data,p=m?.data??m;return{success:!0,data:Zn(p)}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let a=1;a<=E;a++)try{let i={};t&&(i.chain=V(t)),n&&(i.time_frame=n),r!=null&&(i.min_market_cap=r),o!=null&&(i.security_score=o);let l=$(i),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${l?`?${l}`:""}`,d=await _.get(u);if(!d.ok)throw new Error(I(d));let m=d.data,p=m?.data??m;return{success:!0,data:Zn(p)}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<E&&await W(F)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var Ye=class extends T{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days, (4) on-chain activity signals (holders, liquidity, unusual flows), (5) team/protocol updates or roadmap items, (6) key risks, red flags, or controversies, (7) sentiment and notable community discussion. When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. Aim for 3-6 sentences. Be specific to the token. Do not use generic filler. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;llm;constructor(e){super(),this.service=new R(e),this.llm=new ne({})}async run(e,t){let n=e.keyword||"",r=U(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",a=e.buy_prompt_template||"",i=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,a,i):{error:"Missing required parameter: keyword"}}async execute(e,t){let n=await super.execute(e,t),r=n.data;return n.success&&r&&Array.isArray(r.actionButtons)&&r.actionButtons.length>0&&(n.actionButtons=r.actionButtons),n}async searchToken(e,t,n,r,o,s){let a=[s?`User's connected wallet address: ${s}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
3
3
  `),[i,l,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,a):Promise.resolve(null)]),d=i.success&&i.data?Array.isArray(i.data)?i.data:[]:[],m=e.toLowerCase(),p=b=>b.symbol?.toLowerCase()===m||b.token_address?.toLowerCase()===m,h=[...d].sort((b,v)=>(p(b)?0:1)-(p(v)?0:1)),g=null,f=h[0];if(f?.token_address){let b=await this.service.getTokenMetadata({address:f.token_address,chain:t});b.success&&b.data&&(g=b.data)}!g&&f&&(g={...f});let y=g?.symbol?.trim(),k=y?[{label:this.fillTemplate(r,y,"Buy {token}"),prompt:this.fillTemplate(o,y,"buy {token}")}]:[];return{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:t,userHoldsToken:!!l,walletBalance:l,token:g,...d.length>1?{searchResults:h.slice(0,10)}:{},research:u,...k.length>0?{actionButtons:k}:{}}}fillTemplate(e,t,n){return(e&&e.includes("{token}")?e:n).replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),s=r.data.result.find(a=>a.token_address.toLowerCase()===o||a.symbol?.toLowerCase()===o||a.name?.toLowerCase().includes(o));return s||null}};var Ke=class extends T{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new R(e)}async run(e,t){let n=U(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let l=await this.service.getTokenHolders({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token holder stats"};let u=l.data;return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var je=class extends T{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new R(e)}async run(e,t){let n=U(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,a=d.symbol,i=d.name}let l=await this.service.getTokenAnalytics({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token analytics"};let u=l.data??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var ze=class extends T{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new R(e)}async run(e,t){let n=U(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,s=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!s)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let a,i;if(o){let m=await this.resolveContractAddress(o,n,r);if(!m)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?N(n):"the selected chain"}. Try passing contractAddress directly.`};s=m.address,a=m.symbol,i=m.name}let l=await this.service.getTokenScore({address:s,chain:n});if(!l.success)return{error:l.error||"Failed to fetch token score"};let u=l.data??{},d=u.metrics??{};return{token:{symbol:a??o??null,name:i??null,contractAddress:s,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let s=await this.service.getWalletTokenBalances({address:n,chain:t});if(s.success&&s.data?.result?.length){let a=s.data.result.find(i=>(i.symbol??"").toLowerCase()===r);if(a)return{address:a.token_address,symbol:a.symbol,name:a.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let a=o.data.find(i=>(i.symbol??"").toLowerCase()===r)??o.data[0];if(a?.token_address)return{address:a.token_address,symbol:a.symbol,name:a.name}}}};var Qe=class extends T{name="get-trending-tokens";description='List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}];service;constructor(e){super(),this.service=new te({baseUrl:e?.pantographUrl})}async run(e,t){let n=vn(e.chain,t),r=e.buy_button_label||"",o=e.buy_prompt_template||"",s=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,a=await this.service.getTrendingTokens({chain:n,limit:s});if(!a.success)return{error:a.error||"Failed to fetch trending tokens"};let i=a.data??[],l=new Set,u=[];for(let d of i){let m=d.symbol?.trim();!m||l.has(m.toLowerCase())||(l.add(m.toLowerCase()),u.push({label:this.fillTemplate(r,m,"Buy {token}"),prompt:this.fillTemplate(o,m,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
4
4
  <rank>. <name> (<symbol>)
@@ -916,7 +916,7 @@ ${e}${l}
916
916
  Return JSON only.`,timestamp:Date.now()}],m=[{role:"system",content:_a,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[p,h]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(m)]),g={};if(p.status==="fulfilled")try{g=this.parseJSON(p.value.text)}catch(k){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${k}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${p.reason}`);let f="";if(h.status==="fulfilled")try{let k=this.parseJSON(h.value.text);typeof k.language=="string"&&(f=k.language.trim().toLowerCase())}catch(k){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${k}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${h.reason}`);let y={isFollowUp:r&&typeof g.isFollowUp=="boolean"?g.isFollowUp:!1,rewrittenQuery:typeof g.rewrittenQuery=="string"&&g.rewrittenQuery.trim()?g.rewrittenQuery.trim():e,topicChanged:r&&typeof g.topicChanged=="boolean"?g.topicChanged:!1,reasoning:typeof g.reasoning=="string"?g.reasoning:"",language:f,mentionedChain:typeof g.mentionedChain=="string"?g.mentionedChain.trim():"",needsWebSearch:g.needsWebSearch===!0,aboutAssistant:g.aboutAssistant===!0};if(this.debug){let k=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
917
917
  [QueryRewriter] (${k}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${w?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp} topicChanged: ${y.topicChanged}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var O=require("@langchain/langgraph");var se=c=>({reducer:(e,t)=>t,default:c}),Ca=O.Annotation.Root({userMessage:(0,O.Annotation)(),doSuggest:(0,O.Annotation)(se(()=>!0)),overrideLang:(0,O.Annotation)(se(()=>"")),conversationMessages:(0,O.Annotation)(se(()=>[])),lastSubagents:(0,O.Annotation)(se(()=>[])),messageId:(0,O.Annotation)(se(()=>"")),rewrite:(0,O.Annotation)(se(()=>null)),effectiveQuery:(0,O.Annotation)(se(()=>"")),turnLanguage:(0,O.Annotation)(se(()=>"")),kbContext:(0,O.Annotation)(se(()=>"")),decision:(0,O.Annotation)(se(()=>null)),assignment:(0,O.Annotation)(se(()=>null)),assignmentIndex:(0,O.Annotation)(se(()=>0)),subResults:(0,O.Annotation)({reducer:(c,e)=>c.concat(e),default:()=>[]}),response:(0,O.Annotation)(se(()=>null))});function ir(c){let e=async d=>{c.addUserMessage(d.userMessage),c.needsSummary()&&await c.compactHistory();let m=c.conversationForTurn(),p=c.lastAssistantSubagents(m);return c.debug&&p.length>0&&console.log(`[AgentCore] previous turn handled by: ${p.join(", ")}`),{conversationMessages:m,lastSubagents:p,messageId:c.generateMessageId()}},t=async d=>{let m=await c.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),p=d.overrideLang||m.language||"";return{rewrite:m,effectiveQuery:m.rewrittenQuery,turnLanguage:p}},n=async d=>{let m=d.rewrite,p=m.isFollowUp?d.effectiveQuery:d.userMessage,h=await c.searchKB(p),g=c.formatKBContext(h),f=await c.tryAnswerFromKB(d.userMessage,h,g,d.messageId);return f?{kbContext:g,response:{...f,messageId:d.messageId,rewrite:m}}:{kbContext:g}},r=async d=>({decision:await c.route(d.effectiveQuery,d.conversationMessages,c.subagentCards(),d.lastSubagents)}),o=async d=>{let m=await c.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,d.messageId,d.rewrite?.needsWebSearch??!1),p=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...m,messageId:d.messageId,routerDecision:p,rewrite:d.rewrite}}},s=async d=>{let m=await c.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:m}]}},a=async d=>{let m=d.subResults.slice().sort((b,v)=>b.i-v.i).map(b=>b.result);c.persistToolMessages(m);let p=c.mergeTrace(m),h=await c.synthesise(d.userMessage,p,c.synthesiserHistory(),d.turnLanguage||void 0),g=m.map(b=>b.subagentName),f=c.collectUiActions(m,d.turnLanguage||null),y=c.collectActionButtons(m,d.turnLanguage||null),k=c.subResultsTriggerNoSuggestions(m);return{response:{...await c.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:g,uiActions:f,actionButtons:y,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!k&&y.length===0}),messageId:d.messageId,trace:p,routerDecision:d.decision,subagentResults:m,rewrite:d.rewrite,...f.length>0?{uiActions:f}:{},...y.length>0?{actionButtons:y}:{}}}},i=async d=>{let m=(d.rewrite?.mentionedChain||String(c.connectedChain()??"")).trim();return{response:{...await c.answerUnsupportedChain(m,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},l=d=>d.response?O.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let m=d.decision?.assignments??[];if(m.length===0)return"direct";let p=m.some(g=>g.subagent!=="ai-agent"),h=(d.rewrite?.mentionedChain||c.connectedChain()||"").trim();return p&&h!==""&&!wn(h)?"unsupportedChain":m.map((g,f)=>new O.Send("subagent",{...d,assignment:g,assignmentIndex:f}))};return new O.StateGraph(Ca).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",a).addNode("unsupportedChain",i).addEdge(O.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",l,["route","direct",O.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",O.END).addEdge("direct",O.END).addEdge("subagent","synthesize").addEdge("synthesize",O.END).compile()}var lr=require("js-sha3");function Gn(){let c=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(c+e).slice(-8)}var Ea="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Ua=`
918
918
 
919
- IDENTITY: If the user asks who or what you are, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline and steer back to how you can help.`,Yn=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;suggestionsEnabled;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;historyReady;constructor(e){this.secretKey=e.secretKey,ao(e.rpcUrls),bn(e.excludeChains),this.llm=new ne(e.llm),this.registry=new Fe,this.history=new Kt(e.maxHistoryMessages??50),this.summarizer=new jt(this.llm),this.synthesizer=new Xt(this.llm),this.systemPrompt=(e.systemPrompt??Ea)+Ua,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new zt(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Re({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let u=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Je(u)),this.registry.register(new Ye(u)),this.registry.register(new Ze(u)),this.registry.register(new et(u)),this.registry.register(new tt(u)),this.registry.register(new Ke(u)),this.registry.register(new nt(u)),this.registry.register(new ot(u)),this.registry.register(new lt(u)),this.registry.register(new st(u)),this.registry.register(new at(u)),this.registry.register(new it(u)),this.registry.register(new rt(u)),this.registry.register(new Qe(u)),this.registry.register(new Xe(u)),this.registry.register(new je(u)),this.registry.register(new ze(u))}let r=e.nftLink;this.registry.register(new ut({url:r})),this.registry.register(new dt),this.registry.register(new mt),this.registry.register(new pt(e.llm));let o=e.subagents?.["pool-subgraph"]===!0;if((o?e.subagents?.pool===!0:e.subagents?.pool!==!1)&&e.uniswap!==!1){let u=typeof e.uniswap=="object"?e.uniswap:void 0;this.registry.register(new gt(u)),this.registry.register(new ft(u)),this.registry.register(new yt(u)),this.registry.register(new bt(u)),this.registry.register(new Ct(u));let d=u?{isProduction:u.isProduction}:void 0;this.registry.register(new Pt({baseUrl:u?.baseUrl,pool:d,minProvideUsd:u?.minProvideUsd})),this.registry.register(new _t({pool:d}))}if(o&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Et(u)),this.registry.register(new Ut(u)),this.registry.register(new Rt(u)),this.registry.register(new Nt(u)),this.registry.register(new It(u)),this.registry.register(new Lt(u)),this.registry.register(new Dt(u)),this.registry.register(new ht(e.llm))}if(e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Mt(u)),this.registry.register(new qt(u)),this.registry.register(new Yt(u,{url:r})),this.registry.register(new Ft(u)),this.registry.register(new Ht(u,{debug:this.debug})),this.registry.register(new Gt(u,{debug:this.debug}))}this.router=new Qt(this.llm,{debug:this.debug}),this.rewriter=new Hn(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=Vn(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},e.subagents);this.subagents=new Map(l.map(u=>[u.name,u])),this.chatGraph=ir(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:Gn()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),a=s.data,i=s.success?a?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,l=Gn(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:i,timestamp:Date.now(),subagents:["direct-invoke"],messageId:l};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:i,messageId:l,...u.length>0?{uiActions:u}:{}}}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;let e="";if(e&&(!this.secretKey||(0,lr.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=t?.generateSuggestions??this.suggestionsEnabled,r=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let o=Date.now();this.debug&&(console.log(`
919
+ IDENTITY: If the user asks who or what you are, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline and steer back to how you can help.`,Yn=class{llm;registry;history;summarizer;router;rewriter;subagents;synthesizer;chatGraph;systemPrompt;debug;secretKey;licenseChecked=!1;userContext={};storage;storageKey;persistHistoryEnabled;kb;kbEntries;vectorKB=null;vectorKBAutoIngested=!1;vectorKBAutoIngestPromise=null;autoIngestEnabled=!1;kbAnswerThreshold;suggestionsEnabled;historyLoaded=!1;historyLoadingPromise=null;inFlightTurn=null;historyReady;constructor(e){this.secretKey=e.secretKey,ao(e.rpcUrls),bn(e.excludeChains),this.llm=new ne(e.llm),this.registry=new Fe,this.history=new Kt(e.maxHistoryMessages??50),this.summarizer=new jt(this.llm),this.synthesizer=new Xt(this.llm),this.systemPrompt=(e.systemPrompt??Ea)+Ua,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new zt(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Re({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let u=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Je(u)),this.registry.register(new Ye(u)),this.registry.register(new Ze(u)),this.registry.register(new et(u)),this.registry.register(new tt(u)),this.registry.register(new Ke(u)),this.registry.register(new nt(u)),this.registry.register(new ot(u)),this.registry.register(new lt(u)),this.registry.register(new st(u)),this.registry.register(new at(u)),this.registry.register(new it(u)),this.registry.register(new rt(u)),this.registry.register(new Qe(u)),this.registry.register(new Xe(u)),this.registry.register(new je(u)),this.registry.register(new ze(u))}let r=e.nftLink;this.registry.register(new ut({url:r})),this.registry.register(new dt),this.registry.register(new mt),this.registry.register(new pt(e.llm));let o=e.subagents?.["pool-subgraph"]===!0;if((o?e.subagents?.pool===!0:e.subagents?.pool!==!1)&&e.uniswap!==!1){let u=typeof e.uniswap=="object"?e.uniswap:void 0;this.registry.register(new gt(u)),this.registry.register(new ft(u)),this.registry.register(new yt(u)),this.registry.register(new bt(u)),this.registry.register(new Ct(u));let d=u?{isProduction:u.isProduction}:void 0;this.registry.register(new Pt({baseUrl:u?.baseUrl,pool:d,minProvideUsd:u?.minProvideUsd})),this.registry.register(new _t({pool:d}))}if(o&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Et(u)),this.registry.register(new Ut(u)),this.registry.register(new Rt(u)),this.registry.register(new Nt(u)),this.registry.register(new It(u)),this.registry.register(new Lt(u)),this.registry.register(new Dt(u)),this.registry.register(new ht(e.llm))}if(e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Mt(u)),this.registry.register(new qt(u)),this.registry.register(new Yt(u,{url:r})),this.registry.register(new Ft(u)),this.registry.register(new Ht(u,{debug:this.debug})),this.registry.register(new Gt(u,{debug:this.debug}))}this.router=new Qt(this.llm,{debug:this.debug}),this.rewriter=new Hn(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=Vn(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},e.subagents);this.subagents=new Map(l.map(u=>[u.name,u])),this.chatGraph=ir(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:Gn()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,timestamp:Date.now()});let s=await this.registry.execute(e,t,this.userContext),a=s.data,i=s.success?a?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,l=Gn(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:i,timestamp:Date.now(),subagents:["direct-invoke"],messageId:l};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:i,messageId:l,...u.length>0?{uiActions:u}:{}}}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,lr.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=t?.generateSuggestions??this.suggestionsEnabled,r=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let o=Date.now();this.debug&&(console.log(`
920
920
  ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=this.chatGraph.invoke({userMessage:e,doSuggest:n,overrideLang:r});this.inFlightTurn=s;let a;try{a=await s}finally{this.inFlightTurn===s&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-o}ms total`),console.log(`${"\u2500".repeat(60)}
921
921
  `)),a.response??{answer:"",messageId:Gn()}}createGraphHost(){return{debug:this.debug,addUserMessage:e=>this.addUserMessage(e),needsSummary:()=>this.history.needsSummary(),compactHistory:()=>this.compactHistory(),conversationForTurn:()=>{let e=this.history.getConversation();return e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e},lastAssistantSubagents:e=>or(e),generateMessageId:()=>Gn(),rewrite:(e,t,n)=>this.rewriter.rewrite(e,t,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,n,r)=>this.tryAnswerFromKB(e,t,n,r),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,n,r)=>this.router.route(e,t,n,this.userContext,r),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,n)=>this.answerUnsupportedChain(e,t,n),answerDirectly:(e,t,n,r,o,s)=>this.answerDirectly(e,t,n,r,o,s),runSubagent:async(e,t,n)=>{let r=this.subagents.get(e.subagent);if(!r)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let o=Date.now(),s=await r.run({query:e.query,reasoning:e.reasoning,language:n},t,this.userContext);if(this.debug){let a=s.toolResults.map(i=>i.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${a}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>{let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return we(t)},mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,n,r)=>this.synthesizer.synthesise(e,t,n,r),collectUiActions:(e,t)=>this.collectUiActions(e,t),collectActionButtons:(e,t)=>this.collectActionButtons(e,t),subResultsTriggerNoSuggestions:e=>this.subResultsTriggerNoSuggestions(e),finaliseAnswer:(e,t)=>this.finaliseAnswer(e,t)}}subResultsTriggerNoSuggestions(e){for(let t of e)for(let n of t.toolResults){if(!n.success)continue;if(this.registry.get(n.toolName)?.noSuggestions===!0)return!0}return!1}capitalizeFirst(e){if(!e)return e;let t=Array.from(e);return t[0]=t[0].toLocaleUpperCase(),t.join("")}collectActionButtons(e,t){let n=new Map,r=[];for(let o of e)for(let s of o.toolResults)if(!(!s.success||!Array.isArray(s.actionButtons)))for(let a of s.actionButtons){if(!a||typeof a!="object"||typeof a.label!="string"||!a.label.trim()||typeof a.prompt!="string"||!a.prompt.trim())continue;let i=this.capitalizeFirst(a.prompt),l={label:a.label,prompt:i,...t?{language:t}:{}},u=n.get(i);u?l.label.length>u.label.length&&n.set(i,l):(n.set(i,l),r.push(i))}return r.map(o=>n.get(o))}collectUiActions(e,t){let n=[];for(let r of e)for(let o of r.toolResults)o.success&&o.ui&&typeof o.ui=="object"&&typeof o.ui.component=="string"&&n.push(this.stampLanguage(o.ui,t));if(this.debug&&n.length>0){let r=n.map(o=>`${o.component}=${o.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${r}`)}return n}stampLanguage(e,t){return!t||e.language?e:{...e,language:t}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let t=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(t.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=t.slice(0,3).map(r=>`${r.score.toFixed(3)} ${this.snippet(r.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${n}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(n=>n.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((n,r)=>`[Reference ${r+1}]
922
922
  Q: ${n.entry.question}
@@ -436,7 +436,7 @@ NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}
436
436
  `);return s===-1?"":i.stack.slice(s+1)})();try{if(!n.stack)n.stack=a;else if(a){let s=a.indexOf(`
437
437
  `),o=s===-1?-1:a.indexOf(`
438
438
  `,s+1),l=o===-1?"":a.slice(o+1);String(n.stack).endsWith(l)||(n.stack+=`
439
- `+a)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Ri(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:a}=r;n!==void 0&&wf.assertOptions(n,{silentJSONParsing:ii.transitional(ii.boolean),forcedJSONParsing:ii.transitional(ii.boolean),clarifyTimeoutError:ii.transitional(ii.boolean),legacyInterceptorReqResOrdering:ii.transitional(ii.boolean)},!1),i!=null&&(D.isFunction(i)?r.paramsSerializer={serialize:i}:wf.assertOptions(i,{encode:ii.function,serialize:ii.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),wf.assertOptions(r,{baseUrl:ii.spelling("baseURL"),withXsrfToken:ii.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=a&&D.merge(a.common,a[r.method]);a&&D.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete a[m]}),r.headers=lr.concat(s,a);let o=[],l=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(r)===!1)return;l=l&&g.synchronous;let y=r.transitional||Zu;y&&y.legacyInterceptorReqResOrdering?o.unshift(g.fulfilled,g.rejected):o.push(g.fulfilled,g.rejected)});let u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let c,d=0,f;if(!l){let m=[Ay.bind(this),void 0];for(m.unshift(...o),m.push(...u),f=m.length,c=Promise.resolve(r);d<f;)c=c.then(m[d++],m[d++]);return c}f=o.length;let h=r;for(;d<f;){let m=o[d++],g=o[d++];try{h=m(h)}catch(y){g.call(this,y);break}}try{c=Ay.call(this,h)}catch(m){return Promise.reject(m)}for(d=0,f=u.length;d<f;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=Ri(this.defaults,e);let r=vf(e.baseURL,e.url,e.allowAbsoluteUrls);return gf(r,e.params,e.paramsSerializer)}};D.forEach(["delete","get","head","options"],function(e){Ju.prototype[e]=function(r,n){return this.request(Ri(n||{},{method:e,url:r,data:(n||{}).data}))}});D.forEach(["post","put","patch","query"],function(e){function r(n){return function(a,s,o){return this.request(Ri(o||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:a,data:s}))}}Ju.prototype[e]=r(),e!=="query"&&(Ju.prototype[e+"Form"]=r(!0))});var Sf=Ju;var qT=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(a){r=a});let n=this;this.promise.then(i=>{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](i);n._listeners=null}),this.promise.then=i=>{let a,s=new Promise(o=>{n.subscribe(o),a=o}).then(i);return s.cancel=function(){n.unsubscribe(a)},s},e(function(a,s,o){n.reason||(n.reason=new Yi(a,s,o),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},X$=qT;function jT(t){return function(r){return t.apply(null,r)}}function LT(t){return D.isObject(t)&&t.isAxiosError===!0}var BT={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(BT).forEach(([t,e])=>{BT[e]=t});var Q$=BT;function eR(t){let e=new Sf(t),r=df(Sf.prototype.request,e);return D.extend(r,Sf.prototype,e,{allOwnKeys:!0}),D.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return eR(Ri(t,i))},r}var hr=eR(Gu);hr.Axios=Sf;hr.CanceledError=Yi;hr.CancelToken=X$;hr.isCancel=_f;hr.VERSION=Ku;hr.toFormData=_o;hr.AxiosError=$e;hr.Cancel=hr.CanceledError;hr.all=function(e){return Promise.all(e)};hr.spread=jT;hr.isAxiosError=LT;hr.mergeConfig=Ri;hr.AxiosHeaders=lr;hr.formToJSON=t=>Py(D.isHTMLForm(t)?new FormData(t):t);hr.getAdapter=xy.getAdapter;hr.HttpStatusCode=Q$;hr.default=hr;var Oy=hr;var{Axios:vje,AxiosError:wje,CanceledError:Sje,isCancel:Tje,CancelToken:kje,VERSION:Pje,all:Eje,Cancel:Cje,isAxiosError:xje,spread:Aje,toFormData:Ije,AxiosHeaders:Oje,HttpStatusCode:$je,formToJSON:Rje,getAdapter:Nje,mergeConfig:Mje,create:Dje}=Oy;var tR="0.2.21";var tW=`keyring-agent-core/${tR} (Keyring Chatbot Agent; +https://keyring.app)`,rW=3e4,nW=typeof process<"u"&&process.versions?.node!=null,FT=class{constructor(e={}){p(this,"instance");this.instance=Oy.create({baseURL:e.baseURL,timeout:e.timeout??rW,validateStatus:()=>!0,headers:{Accept:"application/json",...nW?{"User-Agent":e.userAgent??tW}:{},...e.headers}})}async request(e,r,n,i={}){let a=await this.instance.request({...i,method:e,url:r,data:n}),s={};for(let[o,l]of Object.entries(a.headers??{}))l!=null&&(s[o.toLowerCase()]=String(l));return{ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Be=new FT;function ct(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let a=e,s=l=>l&&typeof l=="object"?l.message:void 0,o=[a.message,a.errorMessage,a.error,a.error_description,a.detail,s(a.error),s(a.data)];for(let l of o)if(typeof l=="string"&&l.trim())return l.trim()}return i}var rR={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},iW="https://nft.keyring.app/api/gemini-stable",aW=new Set([408,429,500,502,503,504]),nR=3e4,$y=t=>new Promise(e=>setTimeout(e,t));function Ry(t,e,r){if(r!=null&&r>0)return Math.min(r,nR);let n=Math.min(e*2**(t-1),nR);return n/2+Math.random()*(n/2)}function sW(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pn=class{constructor(e){p(this,"model");p(this,"maxTokens");p(this,"temperature");p(this,"baseUrl");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??iW}async chat(e,r,n){let{systemInstruction:i,contents:a}=this.toContents(e),{maxRetries:s=5,retryDelayMs:o=1e3}=n??{},l=a.length>0?a:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let f of l){let h=f.parts.map(m=>m.functionCall?`fc:${m.functionCall.name}`:m.functionResponse?`fr:${m.functionResponse.name}`:`text:${(m.text??"").slice(0,40)}`).join(", ");console.log(` ${f.role}: [${h}]`)}}let u={contents:l,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(u.systemInstruction=i),r?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let c=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,d="Unknown error";for(let f=1;f<=s;f++){let h;try{h=await Be.post(c,u,{headers:{"Content-Type":"application/json"}})}catch(P){if(d=P instanceof Error?P.message:String(P),f>=s)break;await $y(Ry(f,o));continue}if(!h.ok){let P=typeof h.data=="string"?h.data:JSON.stringify(h.data)||h.statusText;if(d=`Gemini proxy error ${h.status}: ${P}`,!aW.has(h.status))throw new Error(d);if(f>=s)break;let A=sW(h.headers["retry-after"]??null);await $y(Ry(f,o,A));continue}if(h.data==null||typeof h.data!="object"){if(d="Gemini proxy returned invalid JSON",f>=s)break;await $y(Ry(f,o));continue}let m=h.data,g=m.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",_=[],S=g.content?.parts;if(!Array.isArray(S)||S.length===0){let P=g.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&f<s){d=`Gemini returned an empty turn (finishReason=${P??"none"})`,await $y(Ry(f,o));continue}return{text:"",toolCalls:[]}}for(let P of S)P.text&&(y+=P.text),P.functionCall&&_.push({toolName:P.functionCall.name,args:P.functionCall.args??{},callId:P.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=m.usageMetadata?{promptTokens:m.usageMetadata.promptTokenCount??0,completionTokens:m.usageMetadata.candidatesTokenCount??0,totalTokens:m.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:_,usage:k}}throw new Error(d)}toContents(e){let r=[],n=[];for(let o of e){if(o.role==="system"){r.push(o.content);continue}if(o.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:o.toolName??"unknown",response:{result:o.content},...o.toolCallId?{id:o.toolCallId}:{}}}]});continue}if(o.role==="assistant"&&o.toolCalls?.length){n.push({role:"model",parts:o.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:o.role==="assistant"?"model":"user",parts:[{text:o.content}]})}let i=[];for(let o of n){let l=i[i.length-1],u=o.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===o.role&&!u&&!c?l.parts.push(...o.parts):i.push({...o,parts:[...o.parts]})}let a=[];for(let o=0;o<i.length;o++){let l=i[o],u=a[a.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[o+1]?.role==="function")||a.push(l)}for(;a.length>0&&a[0].role!=="user";)a.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
439
+ `+a)}}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Ri(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:a}=r;n!==void 0&&wf.assertOptions(n,{silentJSONParsing:ii.transitional(ii.boolean),forcedJSONParsing:ii.transitional(ii.boolean),clarifyTimeoutError:ii.transitional(ii.boolean),legacyInterceptorReqResOrdering:ii.transitional(ii.boolean)},!1),i!=null&&(D.isFunction(i)?r.paramsSerializer={serialize:i}:wf.assertOptions(i,{encode:ii.function,serialize:ii.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),wf.assertOptions(r,{baseUrl:ii.spelling("baseURL"),withXsrfToken:ii.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=a&&D.merge(a.common,a[r.method]);a&&D.forEach(["delete","get","head","post","put","patch","query","common"],m=>{delete a[m]}),r.headers=lr.concat(s,a);let o=[],l=!0;this.interceptors.request.forEach(function(g){if(typeof g.runWhen=="function"&&g.runWhen(r)===!1)return;l=l&&g.synchronous;let y=r.transitional||Zu;y&&y.legacyInterceptorReqResOrdering?o.unshift(g.fulfilled,g.rejected):o.push(g.fulfilled,g.rejected)});let u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let c,d=0,f;if(!l){let m=[Ay.bind(this),void 0];for(m.unshift(...o),m.push(...u),f=m.length,c=Promise.resolve(r);d<f;)c=c.then(m[d++],m[d++]);return c}f=o.length;let h=r;for(;d<f;){let m=o[d++],g=o[d++];try{h=m(h)}catch(y){g.call(this,y);break}}try{c=Ay.call(this,h)}catch(m){return Promise.reject(m)}for(d=0,f=u.length;d<f;)c=c.then(u[d++],u[d++]);return c}getUri(e){e=Ri(this.defaults,e);let r=vf(e.baseURL,e.url,e.allowAbsoluteUrls);return gf(r,e.params,e.paramsSerializer)}};D.forEach(["delete","get","head","options"],function(e){Ju.prototype[e]=function(r,n){return this.request(Ri(n||{},{method:e,url:r,data:(n||{}).data}))}});D.forEach(["post","put","patch","query"],function(e){function r(n){return function(a,s,o){return this.request(Ri(o||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:a,data:s}))}}Ju.prototype[e]=r(),e!=="query"&&(Ju.prototype[e+"Form"]=r(!0))});var Sf=Ju;var qT=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(a){r=a});let n=this;this.promise.then(i=>{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](i);n._listeners=null}),this.promise.then=i=>{let a,s=new Promise(o=>{n.subscribe(o),a=o}).then(i);return s.cancel=function(){n.unsubscribe(a)},s},e(function(a,s,o){n.reason||(n.reason=new Yi(a,s,o),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},X$=qT;function jT(t){return function(r){return t.apply(null,r)}}function LT(t){return D.isObject(t)&&t.isAxiosError===!0}var BT={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(BT).forEach(([t,e])=>{BT[e]=t});var Q$=BT;function eR(t){let e=new Sf(t),r=df(Sf.prototype.request,e);return D.extend(r,Sf.prototype,e,{allOwnKeys:!0}),D.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return eR(Ri(t,i))},r}var hr=eR(Gu);hr.Axios=Sf;hr.CanceledError=Yi;hr.CancelToken=X$;hr.isCancel=_f;hr.VERSION=Ku;hr.toFormData=_o;hr.AxiosError=$e;hr.Cancel=hr.CanceledError;hr.all=function(e){return Promise.all(e)};hr.spread=jT;hr.isAxiosError=LT;hr.mergeConfig=Ri;hr.AxiosHeaders=lr;hr.formToJSON=t=>Py(D.isHTMLForm(t)?new FormData(t):t);hr.getAdapter=xy.getAdapter;hr.HttpStatusCode=Q$;hr.default=hr;var Oy=hr;var{Axios:vje,AxiosError:wje,CanceledError:Sje,isCancel:Tje,CancelToken:kje,VERSION:Pje,all:Eje,Cancel:Cje,isAxiosError:xje,spread:Aje,toFormData:Ije,AxiosHeaders:Oje,HttpStatusCode:$je,formToJSON:Rje,getAdapter:Nje,mergeConfig:Mje,create:Dje}=Oy;var tR="0.2.22";var tW=`keyring-agent-core/${tR} (Keyring Chatbot Agent; +https://keyring.app)`,rW=3e4,nW=typeof process<"u"&&process.versions?.node!=null,FT=class{constructor(e={}){p(this,"instance");this.instance=Oy.create({baseURL:e.baseURL,timeout:e.timeout??rW,validateStatus:()=>!0,headers:{Accept:"application/json",...nW?{"User-Agent":e.userAgent??tW}:{},...e.headers}})}async request(e,r,n,i={}){let a=await this.instance.request({...i,method:e,url:r,data:n}),s={};for(let[o,l]of Object.entries(a.headers??{}))l!=null&&(s[o.toLowerCase()]=String(l));return{ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:s}}get(e,r){return this.request("GET",e,void 0,r)}post(e,r,n){return this.request("POST",e,r,n)}put(e,r,n){return this.request("PUT",e,r,n)}patch(e,r,n){return this.request("PATCH",e,r,n)}delete(e,r){return this.request("DELETE",e,void 0,r)}},Be=new FT;function ct(t){let{data:e,status:r,statusText:n}=t,i=n?`HTTP ${r} ${n}`:`HTTP ${r}`;if(typeof e=="string")return e.trim()||i;if(e&&typeof e=="object"){let a=e,s=l=>l&&typeof l=="object"?l.message:void 0,o=[a.message,a.errorMessage,a.error,a.error_description,a.detail,s(a.error),s(a.data)];for(let l of o)if(typeof l=="string"&&l.trim())return l.trim()}return i}var rR={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},iW="https://nft.keyring.app/api/gemini-stable",aW=new Set([408,429,500,502,503,504]),nR=3e4,$y=t=>new Promise(e=>setTimeout(e,t));function Ry(t,e,r){if(r!=null&&r>0)return Math.min(r,nR);let n=Math.min(e*2**(t-1),nR);return n/2+Math.random()*(n/2)}function sW(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pn=class{constructor(e){p(this,"model");p(this,"maxTokens");p(this,"temperature");p(this,"baseUrl");this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??1,this.baseUrl=e.baseUrl??iW}async chat(e,r,n){let{systemInstruction:i,contents:a}=this.toContents(e),{maxRetries:s=5,retryDelayMs:o=1e3}=n??{},l=a.length>0?a:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let f of l){let h=f.parts.map(m=>m.functionCall?`fc:${m.functionCall.name}`:m.functionResponse?`fr:${m.functionResponse.name}`:`text:${(m.text??"").slice(0,40)}`).join(", ");console.log(` ${f.role}: [${h}]`)}}let u={contents:l,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};i&&(u.systemInstruction=i),r?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(r)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let c=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,d="Unknown error";for(let f=1;f<=s;f++){let h;try{h=await Be.post(c,u,{headers:{"Content-Type":"application/json"}})}catch(P){if(d=P instanceof Error?P.message:String(P),f>=s)break;await $y(Ry(f,o));continue}if(!h.ok){let P=typeof h.data=="string"?h.data:JSON.stringify(h.data)||h.statusText;if(d=`Gemini proxy error ${h.status}: ${P}`,!aW.has(h.status))throw new Error(d);if(f>=s)break;let A=sW(h.headers["retry-after"]??null);await $y(Ry(f,o,A));continue}if(h.data==null||typeof h.data!="object"){if(d="Gemini proxy returned invalid JSON",f>=s)break;await $y(Ry(f,o));continue}let m=h.data,g=m.candidates?.[0];if(!g)return{text:"",toolCalls:[]};let y="",_=[],S=g.content?.parts;if(!Array.isArray(S)||S.length===0){let P=g.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&f<s){d=`Gemini returned an empty turn (finishReason=${P??"none"})`,await $y(Ry(f,o));continue}return{text:"",toolCalls:[]}}for(let P of S)P.text&&(y+=P.text),P.functionCall&&_.push({toolName:P.functionCall.name,args:P.functionCall.args??{},callId:P.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let k=m.usageMetadata?{promptTokens:m.usageMetadata.promptTokenCount??0,completionTokens:m.usageMetadata.candidatesTokenCount??0,totalTokens:m.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:_,usage:k}}throw new Error(d)}toContents(e){let r=[],n=[];for(let o of e){if(o.role==="system"){r.push(o.content);continue}if(o.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:o.toolName??"unknown",response:{result:o.content},...o.toolCallId?{id:o.toolCallId}:{}}}]});continue}if(o.role==="assistant"&&o.toolCalls?.length){n.push({role:"model",parts:o.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:o.role==="assistant"?"model":"user",parts:[{text:o.content}]})}let i=[];for(let o of n){let l=i[i.length-1],u=o.parts.some(d=>d.functionCall),c=l?.parts.some(d=>d.functionCall);l&&l.role===o.role&&!u&&!c?l.parts.push(...o.parts):i.push({...o,parts:[...o.parts]})}let a=[];for(let o=0;o<i.length;o++){let l=i[o],u=a[a.length-1];l.role==="function"&&!u?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(i[o+1]?.role==="function")||a.push(l)}for(;a.length>0&&a[0].role!=="user";)a.shift();return{systemInstruction:r.length?{role:"user",parts:[{text:r.join(`
440
440
  `)}]}:null,contents:a}}toFunctionDeclarations(e){return e.map(r=>{let n={},i=[];for(let a of r.parameters){let s={type:rR[a.type]??"STRING",description:a.description};a.type==="array"&&(s.items={type:rR[a.items?.type??"string"]??"STRING"}),n[a.name]=s,a.required&&i.push(a.name)}return{name:r.name,description:r.description,parameters:{type:"OBJECT",properties:n,required:i}}})}};var Yu=class{constructor(){p(this,"tools",new Map)}register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(r=>r.category===e)}async execute(e,r,n){let i=this.tools.get(e);if(!i)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let a=Date.now();try{return{...await i.execute(r,n),duration:Date.now()-a}}catch(s){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-a}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Xu=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],oW=new Set(Xu),bo=[...Xu],iR=new Set(bo),Qi="0x1",Al="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function lW(t){return t.map(e=>ec[e]??e).join(", ")}function Ny(t){let e=new Set;if(t)for(let n of t){let i=zT(n);i&&e.add(i)}let r=Xu.filter(n=>!e.has(n));bo=r.length>0?[...r]:[...Xu],iR=new Set(bo),Qi=bo.includes("0x1")?"0x1":bo[0],Al=lW(bo)}var uW={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708"};function Xi(t){let e=zT(t);return e&&iR.has(e)?e:null}function zT(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let r=uW[e];if(r)return r;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&oW.has(n)?n:null}function My(t){return Xi(t)!==null}function aR(){return[...bo]}var Qu=class extends Error{constructor(r){super(`Chain "${r}" is not supported. Supported chains: ${Al}.`);p(this,"requested",r);p(this,"code","unsupported_chain");this.name="UnsupportedChainError"}},vo=t=>typeof t=="string"&&t.trim()!=="";function Dy(t,e){if(vo(t)){let r=Xi(t);if(r)return r;throw new Qu(t.trim())}if(vo(e?.chain)){let r=Xi(e.chain);if(r)return r;throw new Qu(e.chain.trim())}return null}function Uy(t,e){return Xi(t)??Xi(e?.chain)??void 0}var ec={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function ut(t){let e=zT(t);return e&&ec[e]?ec[e]:typeof t=="string"&&t.trim()?t.trim():"the requested chain"}var cW={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function sR(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?cW[e]??null:null}var dW={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function oR(t){let e=Xi(t);return e?dW[e]??null:null}function tc(t,e){if(!vo(t))return null;let r=Xi(t),n=Xi(e?.chain);return!r||!n||r===n?null:{requested:r,connected:n,requestedLabel:ec[r]??r,connectedLabel:ec[n]??n}}function pW(){return bo.map(t=>{let e=ec[t]??t;return{label:e,prompt:e}})}var vr=class extends Error{constructor(r){super("Wallet is connected but no chain is set \u2014 ask the user to pick one.");p(this,"code","needs_chain_selection");p(this,"buttons");this.name="NeedsChainSelectionError",this.buttons=r??pW()}},Tf=class extends Error{constructor(){super("No wallet address available \u2014 ask the user to connect a wallet or supply one.");p(this,"code","no_wallet_connected");this.name="NoWalletConnectedError"}};function mr(t,e){if(vo(t))return t.trim();if(vo(e?.walletAddress))return e.walletAddress.trim();throw new Tf}function Qe(t,e){if(vo(t)){let r=Xi(t);if(r)return r;throw new Qu(t.trim())}if(vo(e?.chain)){let r=Xi(e.chain);if(r)return r;throw new Qu(e.chain.trim())}if(vo(e?.walletAddress))throw new vr;return Qi}var ue=class{constructor(){p(this,"category")}async execute(e,r){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=Date.now();try{let a=await this.run(e,r),s=fW(a);return{toolName:this.name,callId:n,success:!0,data:s.data,duration:Date.now()-i,...s.actionButtons?{actionButtons:s.actionButtons}:{}}}catch(a){return a instanceof vr?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-i,actionButtons:a.buttons}:a instanceof Tf?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-i}:{toolName:this.name,callId:n,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-i}}}};function fW(t){if(!t||typeof t!="object")return{data:t};let e=t,r=e.actionButtons;if(!Array.isArray(r)||r.length===0)return{data:t};let{actionButtons:n,...i}=e;return{data:i,actionButtons:r}}var lR=hy(jy());function Ut(t){return typeof t=="string"&&/^0x[0-9a-fA-F]{40}$/.test(t)}function hW(t){return new Uint8Array(lR.keccak256.arrayBuffer(t))}function kf(t){let e=t.startsWith("0x")?t.slice(2):t,r=e.length%2?"0"+e:e,n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*2,i*2+2),16);return n}function uR(t){return"0x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function cR(t){return new TextEncoder().encode(t)}function Il(...t){let e=t.reduce((i,a)=>i+a.length,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function mW(t,e=32){let r=new Uint8Array(e);return r.set(t,e-t.length),r}function gW(t,e=32){let r=new Uint8Array(e);return r.set(t),r}function dR(t){let e=((t%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return kf(e)}function Pf(t){return dR(BigInt(t))}function pR(t){return t==="uint"?"uint256":t==="int"?"int256":t.match(/^uint$/)?"uint256":t.match(/^int$/)?"int256":t.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function fR(t){let e=pR(t.type);if(e==="tuple"||e.startsWith("tuple[")){let r=(t.components??[]).map(fR).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${r})${n}`}return e}function yW(t){let e=(t.inputs??[]).map(fR).join(",");return`${t.name??""}(${e})`}function VT(t,e){let r=vW(t.type);if(r){let[i,a]=r;return _W({...t,type:a},e,i)}if(t.type==="tuple")return bW(t,e);if(t.type==="address"){let i=String(e),a=i.startsWith("0x")?i.slice(2):i;return{dynamic:!1,encoded:mW(kf(a.toLowerCase()))}}if(t.type==="bool"){let i=new Uint8Array(32);return i[31]=e?1:0,{dynamic:!1,encoded:i}}let n=pR(t.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Pf(BigInt(e))};if(/^int\d*$/.test(n)){let i=BigInt(e);return i<0n&&(i=i+(1n<<256n)),{dynamic:!1,encoded:dR(i)}}if(/^bytes(\d+)$/.test(n)){let i=parseInt(n.slice(5),10),a=typeof e=="string"?kf(e):e;if(a.length!==i)throw new Error(`bytes${i} expects exactly ${i} bytes, got ${a.length}`);return{dynamic:!1,encoded:gW(a)}}if(n==="bytes"){let i=typeof e=="string"?kf(e):e,a=Math.ceil(i.length/32)*32,s=new Uint8Array(a);return s.set(i),{dynamic:!0,encoded:Il(Pf(i.length),s)}}if(n==="string"){let i=typeof e=="string"?cR(e):e,a=Math.ceil(i.length/32)*32,s=new Uint8Array(a);return s.set(i),{dynamic:!0,encoded:Il(Pf(i.length),s)}}throw new Error(`Unsupported ABI type: ${t.type}`)}function ZT(t){let e=0;for(let{dynamic:a,encoded:s}of t)e+=a?32:s.length;let r=[],n=[],i=0;for(let{dynamic:a,encoded:s}of t)a?(r.push(Pf(e+i)),n.push(s),i+=s.length):r.push(s);return Il(...r,...n)}function _W(t,e,r){let n=r===null;if(!n&&e.length!==r)throw new Error(`Array length mismatch: expected ${r}, got ${e.length}`);let i=!1,a=[];for(let s of e){let o=VT(t,s);o.dynamic&&(i=!0),a.push(o)}if(n||i){let s=ZT(a);if(n){let o=Pf(a.length);return{dynamic:!0,encoded:a.length>0?Il(o,s):o}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Il(...a.map(s=>s.encoded))}}function bW(t,e){let r=t.components??[],n=!1,i=[];for(let a=0;a<r.length;a++){let s=r[a],o=Array.isArray(e)?e[a]:e[s.name??""],l=VT(s,o);l.dynamic&&(n=!0),i.push(l)}return{dynamic:n,encoded:n?ZT(i):Il(...i.map(a=>a.encoded))}}function vW(t){let e=t.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function wW(t,e){if(t.length!==e.length)throw new Error(`Expected ${t.length} values, got ${e.length}`);if(t.length===0)return"0x";let r=t.map((i,a)=>VT(i,e[a])),n=ZT(r);return uR(n)}function rc({abi:t,functionName:e,args:r=[]}){let n=t.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let i=yW(n),a=hW(cR(i)).slice(0,4),s=n.inputs??[],o=s.length===0||r.length===0?new Uint8Array(0):kf(wW(s,r).slice(2));return uR(Il(a,o))}var SW="https://wallet-api.pantograph.app",TW="0x0000000000000000000000000000000000000000",gR={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},yR={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"]};function Ef(t){return gR[t.toLowerCase()]||t}function hR(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function HT(t){let e=t,r=e.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN,i=e.price,a=i!=null?parseFloat(String(i)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(a)?{usd_price:a}:{}}}function un(t){if(t==null)return null;let e=typeof t=="number"?t:parseFloat(String(t));return Number.isFinite(e)?e:null}function mR(t,e){let r=t.decimals,n=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,i=un(t.price_change_percentage_24h)??un(t.priceChange24h)??un(t.usd_price_24hr_percent_change)??un(t.price_change_24h)??un(t.priceChange);return{chainId:e,tokenAddress:t.address??t.token_address??"",name:t.name??null,symbol:t.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:t.logoURI??t.icon_image??t.logo??null,usdPrice:un(t.price)??un(t.usd_price),marketCap:un(t.market_cap)??un(t.marketCap),totalVolume:{"24h":un(t.total_volume)??un(t.volume24h)},pricePercentChange:{"24h":i}}}var cn=class{constructor(e){p(this,"baseUrl");this.baseUrl=(e?.baseUrl??SW).replace(/\/+$/,"")}async enrichTokenPrices(e,r){if(e.length!==0)try{let n=Ef(r),i=e.map(c=>c.token_address).join(","),a=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(i)}`,s=await Be.get(a);if(!s.ok)return;let o=s.data,l=Array.isArray(o)?o:Array.isArray(o.data)?o.data:[],u=new Map;for(let c of l)c.address&&u.set(c.address.toLowerCase(),{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image});for(let c=0;c<e.length;c++){let d=u.get(e[c].token_address.toLowerCase());d&&(d.icon_image&&(e[c].logo=d.icon_image,e[c].thumbnail=d.icon_image),isNaN(d.price)||(e[c].usd_price=d.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*d.price))}}catch{}}async getTokenMetadata(e,r){try{let n=Ef(r),i=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,a=await Be.get(i);if(!a.ok)return null;let s=a.data,o=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],l=e.toLowerCase()===TW,u=o.find(c=>c.address?.toLowerCase()===e.toLowerCase()||l&&c.address===""||c.token_address?.toLowerCase()===e.toLowerCase()||l&&c.token_address==="");return u?HT(u):null}catch{return null}}async getTokensMetadata(e,r){let n={};if(e.length===0)return n;try{let i=Ef(r),a=`${this.baseUrl}/keyrings/tokens/${i}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await Be.get(a);if(!s.ok)return n;let o=s.data,l=Array.isArray(o)?o:Array.isArray(o.data)?o.data:[],u=new Set(e.map(c=>c.toLowerCase()));for(let c of l){let d=c.address?.toLowerCase()||c.token_address?.toLowerCase()||(c.address===""?"":null);d&&u.has(d)&&(n[d]=HT(c))}}catch{}return n}async searchTokensByKey(e){let{key:r,chain:n}=e;if(!r)return{success:!1,error:"Search key is required"};let a=parseInt(n||Qi,16);if(isNaN(a))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=hR({chainId:a,key:r}),o=`${this.baseUrl}/token-list?${s}`,l=await Be.get(o);if(!l.ok)throw new Error(ct(l));let u=l.data,c=[];return u?.data?c=Array.isArray(u.data)?u.data:Object.values(u.data).flat():typeof u=="object"&&!Array.isArray(u)&&(c=Object.values(u).flat()),{success:!0,data:c.map(HT)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let r=e?.chain||Qi,n=5,i=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let a=yR[r.toLowerCase()]??[],s=i!=null?i+a.length:n+a.length,[o,l]=await Promise.allSettled([this.fetchTopGainers(r,s),a.length>0?this.getTokensMetadata(a,r):Promise.resolve({})]),u=o.status==="fulfilled"?o.value:[],c=l.status==="fulfilled"?a.map(g=>l.value[g.toLowerCase()]).filter(g=>g!=null).map(g=>mR(g,r)):[],d=new Set,f=[];for(let g of c){let y=g.tokenAddress?.toLowerCase();!y||d.has(y)||(d.add(y),f.push(g))}let h=[];for(let g of u){let y=g.tokenAddress?.toLowerCase();!y||d.has(y)||(d.add(y),h.push(g))}let m=i!=null?[...f,...h].slice(0,i):[...f,...h.slice(0,n)];return await this.enrichTrendingMarketData(m,r),{success:!0,data:m}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async enrichTrendingMarketData(e,r){let n=e.filter(a=>a.tokenAddress&&(a.marketCap==null||a.totalVolume?.["24h"]==null));if(n.length===0)return;let i=await this.getTokensMetadata(n.map(a=>a.tokenAddress),r);for(let a of n){let s=i[a.tokenAddress.toLowerCase()];s&&(a.marketCap==null&&(a.marketCap=un(s.market_cap)??un(s.marketCap)),a.totalVolume?.["24h"]==null&&(a.totalVolume={"24h":un(s.total_volume)??un(s.volume24h)}))}}async fetchTopGainers(e,r,n="24h"){let i=Ef(e),a=hR({duration:n,limit:r}),s=`${this.baseUrl}/token-list/top-gainers/${i}${a?`?${a}`:""}`,o=[];for(let l=0;l<5;l++){let u=await Be.get(s);if(!u.ok)throw new Error(ct(u));let c=u.data;if(o=Array.isArray(c)?c:Array.isArray(c.data)?c.data:[],o.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return o.map(l=>mR(l,e))}async getTopGainers(e){let r=e?.chain||Qi,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,i=e?.duration||"24h";try{let a=await this.fetchTopGainers(r,n,i);return await this.enrichTrendingMarketData(a,r),{success:!0,data:a}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}};var kW="https://nft.keyring.app",PW="https://nft.keyring.app",EW=.01,Xe=5,Yt=1e3,CW="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",xW="0x0000000000000000000000000000000000000000";function rr(t){return t||Qi}function Xt(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let i of n)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`);else e.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Qt(t){return new Promise(e=>setTimeout(e,t))}function AW(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result.map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",position:{label:r.position.label,address:r.position.address,balance_usd:r.position.balanceUsd??0,total_unclaimed_usd_value:r.position.unclaimedUsd??0,position_details:r.position.details,tokens:r.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}function GT(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){let e=t;return Array.isArray(e.result)?e.result:Object.keys(e).filter(r=>/^\d+$/.test(r)).sort((r,n)=>Number(r)-Number(n)).map(r=>e[r]).filter(r=>!!r&&typeof r=="object")}return[]}var it=class{constructor(e){p(this,"baseUrl");p(this,"v1BaseUrl");p(this,"pantograph");this.baseUrl=(e?.baseUrl??kW).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??PW).replace(/\/+$/,""),this.pantograph=new cn({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:r,chain:n,tokenAddresses:i,excludeSpam:a=!1,excludeUnverifiedContracts:s=!1}=e;if(!r)return{success:!1,error:"Address is required"};let o=rr(n),l="Unknown error";for(let u=1;u<=Xe;u++)try{let c={chain:o,exclude_spam:a,exclude_unverified_contracts:s,limit:100};i&&(c.token_addresses=i);let d=[],f=null;do{f&&(c.cursor=f);let m=Xt(c),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/tokens?${m}`,y=await Be.get(g);if(!y.ok)throw new Error(ct(y));let _=y.data,S=_?.data??_;S?.result?.length>0&&d.push(...S.result),f=S?.cursor??null}while(f);let h={result:d};return h?.result?.length>0&&(h.result=h.result.filter(m=>parseFloat(m.balance||"0")>0),h.result=h.result.map(m=>({...m,token_address:m.token_address.toLowerCase()===CW?xW:m.token_address})),await this.enrichTokenPrices(h.result,o),h.result=h.result.filter(m=>m.usd_value==null||m.usd_value>=EW)),{success:!0,data:h}}catch(c){l=c instanceof Error?c.message:"Unknown error",u<Xe&&await Qt(Yt)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token address is required"};let i=rr(n),a="Unknown error",s=await this.pantograph.getTokenMetadata(r,i);if(s)return{success:!0,data:s};for(let o=1;o<=Xe;o++)try{let[l,u]=await Promise.allSettled([Be.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${Xt({chain:i,addresses:[r]})}`),Be.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/price?${Xt({chain:i,include:"percent_change"})}`)]),c=null;if(l.status==="fulfilled"&&l.value.ok){let f=l.value.data;c=(Array.isArray(f)?f:Array.isArray(f?.data)?f.data:[])[0]??null}if(!c){a="Token metadata not found",o<Xe&&await Qt(Yt);continue}let d=null;if(u.status==="fulfilled"&&u.value.ok){let f=u.value.data;d=f?.data??f}return{success:!0,data:{...c,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){a=l instanceof Error?l.message:"Unknown error",o<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletNFTs(e){let{address:r,chain:n,limit:i=10,excludeSpam:a=!0,cursor:s,tokenAddresses:o,includePrices:l,format:u="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};let c=rr(n),d="Unknown error";for(let f=1;f<=Xe;f++)try{let h={chain:c,format:u,limit:i,exclude_spam:a,media_items:!0,normalizeMetadata:!0};s&&(h.cursor=s),l&&(h.include_prices=!0),o&&o.length>0&&(h.token_addresses=o);let m=Xt(h),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft?${m}`,y=await Be.get(g);if(!y.ok)throw new Error(ct(y));let _=y.data;return{success:!0,data:_?.data??_}}catch(h){d=h instanceof Error?h.message:"Unknown error",f<Xe&&await Qt(Yt)}return{success:!1,error:d}}async getNftMetadata(e){let{address:r,tokenId:n,chain:i,format:a="decimal",normalizeMetadata:s=!0,mediaItems:o=!0,include:l}=e;if(!r)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!Ut(r))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let u=rr(i),c="Unknown error";for(let d=1;d<=Xe;d++)try{let f={chain:u,format:a,normalizeMetadata:s,media_items:o};l&&(f.include=l);let h=Xt(f),m=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/${encodeURIComponent(n)}?${h}`,g=await Be.get(m);if(!g.ok)throw new Error(ct(g));let y=g.data;return{success:!0,data:y?.data??y}}catch(f){c=f instanceof Error?f.message:"Unknown error",d<Xe&&await Qt(Yt)}return{success:!1,error:c}}async getNftContractMetadata(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(r)}/metadata?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletHistory(e){let{address:r,chain:n,limit:i=25,fromDate:a,toDate:s,fromBlock:o,toBlock:l,cursor:u,order:c="DESC",includeInternalTransactions:d,nftMetadata:f}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let h=rr(n),m=Math.max(1,Math.min(100,Math.floor(i))),g="Unknown error";for(let y=1;y<=Xe;y++)try{let _={chain:h,limit:m,order:c};a&&(_.from_date=a),s&&(_.to_date=s),o!=null&&(_.from_block=o),l!=null&&(_.to_block=l),u&&(_.cursor=u),d!=null&&(_.include_internal_transactions=d),f!=null&&(_.nft_metadata=f);let S=Xt(_),k=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/history?${S}`,P=await Be.get(k);if(!P.ok)throw new Error(ct(P));let A=P.data;return{success:!0,data:A?.data??A}}catch(_){g=_ instanceof Error?_.message:"Unknown error",y<Xe&&await Qt(Yt)}return{success:!1,error:g}}async getWalletTokenTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:a=25,fromDate:s,toDate:o,fromBlock:l,toBlock:u,cursor:c,order:d="DESC"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let f=rr(n),h=Math.max(1,Math.min(100,Math.floor(a))),m="Unknown error";for(let g=1;g<=Xe;g++)try{let y={chain:f,limit:h,order:d};s&&(y.from_date=s),o&&(y.to_date=o),l!=null&&(y.from_block=l),u!=null&&(y.to_block=u),c&&(y.cursor=c),i?.length&&(y.contract_addresses=i);let _=Xt(y),S=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/erc20/transfers?${_}`,k=await Be.get(S);if(!k.ok)throw new Error(ct(k));let P=k.data;return{success:!0,data:P?.data??P}}catch(y){m=y instanceof Error?y.message:"Unknown error",g<Xe&&await Qt(Yt)}return{success:!1,error:m}}async getWalletNftTransfers(e){let{address:r,chain:n,contractAddresses:i,limit:a=25,fromDate:s,toDate:o,fromBlock:l,toBlock:u,cursor:c,order:d="DESC",includePrices:f,format:h="decimal"}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let m=rr(n),g=Math.max(1,Math.min(100,Math.floor(a))),y="Unknown error";for(let _=1;_<=Xe;_++)try{let S={chain:m,limit:g,order:d,format:h};s&&(S.from_date=s),o&&(S.to_date=o),l!=null&&(S.from_block=l),u!=null&&(S.to_block=u),c&&(S.cursor=c),i?.length&&(S.contract_addresses=i),f!=null&&(S.include_prices=f);let k=Xt(S),P=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(r)}/nft/transfers?${k}`,A=await Be.get(P);if(!A.ok)throw new Error(ct(A));let R=A.data;return{success:!0,data:R?.data??R}}catch(S){y=S instanceof Error?S.message:"Unknown error",_<Xe&&await Qt(Yt)}return{success:!1,error:y}}async getTokenHolders(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Contract address is required"};if(!Ut(r))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(r)}/holders?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletNetWorth(e){let{address:r,chains:n,excludeSpam:i,excludeUnverifiedContracts:a,maxTokenInactivity:s,minPairSideLiquidityUsd:o}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet net worth is only supported for EVM addresses"};let l="Unknown error";for(let u=1;u<=Xe;u++)try{let c={};n&&n.length>0&&(c.chains=n.map(_=>rr(_))),i!=null&&(c.exclude_spam=i),a!=null&&(c.exclude_unverified_contracts=a),s!=null&&(c.max_token_inactivity=s),o!=null&&(c.min_pair_side_liquidity_usd=o);let d=Xt(c),f=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/net-worth${d?`?${d}`:""}`,h=await Be.get(f);if(!h.ok)throw new Error(ct(h));let m=h.data;return{success:!0,data:m?.data??m}}catch(c){l=c instanceof Error?c.message:"Unknown error",u<Xe&&await Qt(Yt)}return{success:!1,error:l}}async getWalletPnlSummary(e){let{address:r,chain:n,days:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let a=rr(n),s="Unknown error";for(let o=1;o<=Xe;o++)try{let l={chain:a};i&&(l.days=i);let u=Xt(l),c=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability/summary?${u}`,d=await Be.get(c);if(!d.ok)throw new Error(ct(d));let f=d.data;return{success:!0,data:f?.data??f}}catch(l){s=l instanceof Error?l.message:"Unknown error",o<Xe&&await Qt(Yt)}return{success:!1,error:s}}async getWalletPnl(e){let{address:r,chain:n,days:i,tokenAddresses:a}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=rr(n),o="Unknown error";for(let l=1;l<=Xe;l++)try{let u={chain:s};i&&(u.days=i),a&&a.length>0&&(u.token_addresses=a.slice(0,25));let c=Xt(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/profitability?${c}`,f=await Be.get(d);if(!f.ok)throw new Error(ct(f));let h=f.data;return{success:!0,data:h?.data??h}}catch(u){o=u instanceof Error?u.message:"Unknown error",l<Xe&&await Qt(Yt)}return{success:!1,error:o}}async getTransactionByHash(e){let{transactionHash:r,chain:n}=e;if(!r)return{success:!1,error:"Transaction hash is required"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(r)}/verbose?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletApprovals(e){let{address:r,chain:n,limit:i,cursor:a}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=rr(n),o="Unknown error";for(let l=1;l<=Xe;l++)try{let u={chain:s};i!=null&&(u.limit=i),a&&(u.cursor=a);let c=Xt(u),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(r)}/approvals?${c}`,f=await Be.get(d);if(!f.ok)throw new Error(ct(f));let h=f.data;return{success:!0,data:h?.data??h}}catch(u){o=u instanceof Error?u.message:"Unknown error",l<Xe&&await Qt(Yt)}return{success:!1,error:o}}async getWalletDefiSummary(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/summary?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletDefiPositions(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Address is required"};if(!Ut(r))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chains:i}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/positions?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data,d=c?.data??c;return{success:!0,data:AW(d)}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getWalletDefiProtocolPositions(e){let{address:r,protocol:n,chain:i}=e;if(!r)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!Ut(r))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let a=rr(i),s="Unknown error";for(let o=1;o<=Xe;o++)try{let l=Xt({chains:a}),u=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(r)}/defi/${encodeURIComponent(n)}/positions?${l}`,c=await Be.get(u);if(!c.ok)throw new Error(ct(c));let h=c.data.result;return{success:!0,data:{protocol_id:h.protocolId,protocol_name:h.protocolName,protocol_url:h.protocolUrl??"",protocol_logo:h.protocolLogo??"",total_usd_value:h.totalUsd??0,total_unclaimed_usd_value:h.totalUnclaimedUsd??null,positions:h.positions.map(g=>({label:g.label,address:g.address,balance_usd:g.balanceUsd??0,total_unclaimed_usd_value:g.unclaimedUsd??0,position_details:g.details,tokens:g.tokens.map(y=>({token_type:y.tokenType,address:y.address,contract_address:y.address,name:y.name??"",symbol:y.symbol??"",decimals:y.decimals??18,logo:y.logo,balance:y.balance??"0",balance_formatted:y.balanceFormatted??"0",usd_price:y.usdPrice,usd_value:y.usdValue}))}))}}}catch(l){s=l instanceof Error?l.message:"Unknown error",o<Xe&&await Qt(Yt)}return{success:!1,error:s}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Ut(r))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/analytics?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getTokenScore(e){let{address:r,chain:n}=e;if(!r)return{success:!1,error:"Token contract address is required"};if(!Ut(r))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let i=rr(n),a="Unknown error";for(let s=1;s<=Xe;s++)try{let o=Xt({chain:i}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(r)}/score?${o}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data;return{success:!0,data:c?.data??c}}catch(o){a=o instanceof Error?o.message:"Unknown error",s<Xe&&await Qt(Yt)}return{success:!1,error:a}}async getTrendingTokens(e){let r=e?.chain,n=e?.limit,i="Unknown error";for(let a=1;a<=Xe;a++)try{let s={};r&&(s.chain=rr(r)),n!=null&&(s.limit=n);let o=Xt(s),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${o?`?${o}`:""}`,u=await Be.get(l);if(!u.ok)throw new Error(ct(u));let c=u.data,d=c?.data??c;return{success:!0,data:GT(d)}}catch(s){i=s instanceof Error?s.message:"Unknown error",a<Xe&&await Qt(Yt)}return{success:!1,error:i}}async getTopGainers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:a}=e??{},s="Unknown error";for(let o=1;o<=Xe;o++)try{let l={};r&&(l.chain=rr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),a!=null&&(l.security_score=a);let u=Xt(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${u?`?${u}`:""}`,d=await Be.get(c);if(!d.ok)throw new Error(ct(d));let f=d.data,h=f?.data??f;return{success:!0,data:GT(h)}}catch(l){s=l instanceof Error?l.message:"Unknown error",o<Xe&&await Qt(Yt)}return{success:!1,error:s}}async getTopLosers(e){let{chain:r,timeFrame:n,minMarketCap:i,securityScore:a}=e??{},s="Unknown error";for(let o=1;o<=Xe;o++)try{let l={};r&&(l.chain=rr(r)),n&&(l.time_frame=n),i!=null&&(l.min_market_cap=i),a!=null&&(l.security_score=a);let u=Xt(l),c=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${u?`?${u}`:""}`,d=await Be.get(c);if(!d.ok)throw new Error(ct(d));let f=d.data,h=f?.data??f;return{success:!0,data:GT(h)}}catch(l){s=l instanceof Error?l.message:"Unknown error",o<Xe&&await Qt(Yt)}return{success:!1,error:s}}async enrichTokenPrices(e,r){return this.pantograph.enrichTokenPrices(e,r)}};var nc=class extends ue{constructor(r){super();p(this,"name","get-token-info");p(this,"description",'Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea');p(this,"category","blockchain-data");p(this,"parameters",[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days, (4) on-chain activity signals (holders, liquidity, unusual flows), (5) team/protocol updates or roadmap items, (6) key risks, red flags, or controversies, (7) sentiment and notable community discussion. When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. Aim for 3-6 sentences. Be specific to the token. Do not use generic filler. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment."`,required:!0},{name:"buy_button_label",type:"string",description:`Label for the "Buy" suggestion button shown under the token info, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the Buy button is clicked. Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}]);p(this,"service");p(this,"llm");this.service=new it(r),this.llm=new Pn({})}async run(r,n){let i=r.keyword||"",a=Qe(r.chain,n),s=r.prompt||"",o=r.buy_button_label||"",l=r.buy_prompt_template||"",u=n?.walletAddress||void 0;return i?await this.searchToken(i,a,s,o,l,u):{error:"Missing required parameter: keyword"}}async execute(r,n){let i=await super.execute(r,n),a=i.data;return i.success&&a&&Array.isArray(a.actionButtons)&&a.actionButtons.length>0&&(i.actionButtons=a.actionButtons),i}async searchToken(r,n,i,a,s,o){let l=[o?`User's connected wallet address: ${o}`:null,n?`Current chain (hex chain ID): ${n}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
441
441
  `),[u,c,d]=await Promise.all([this.service.searchTokensByKey({key:r,chain:n}),o?this.findTokenInWallet(o,n,r):Promise.resolve(null),i?this.askGeminiWithSearch(i,l):Promise.resolve(null)]),f=u.success&&u.data?Array.isArray(u.data)?u.data:[]:[],h=r.toLowerCase(),m=A=>A.symbol?.toLowerCase()===h||A.token_address?.toLowerCase()===h,g=[...f].sort((A,R)=>(m(A)?0:1)-(m(R)?0:1)),y=null,_=g[0];if(_?.token_address){let A=await this.service.getTokenMetadata({address:_.token_address,chain:n});A.success&&A.data&&(y=A.data)}!y&&_&&(y={..._});let S=y?.symbol?.trim(),k=S?[{label:this.fillTemplate(a,S,"Buy {token}"),prompt:this.fillTemplate(s,S,"buy {token}")}]:[];return{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it. A "Buy" button is shown below your reply automatically \u2014 do NOT mention it, list it, or repeat its text.',chain:n,userHoldsToken:!!c,walletBalance:c,token:y,...f.length>1?{searchResults:g.slice(0,10)}:{},research:d,...k.length>0?{actionButtons:k}:{}}}fillTemplate(r,n,i){return(r&&r.includes("{token}")?r:i).replace(/\{token\}/g,n).replace(/\s+/g," ").trim()}async askGeminiWithSearch(r,n){let i=Date.now();try{return(await this.llm.chat([...n?[{role:"system",content:n,timestamp:i}]:[],{role:"user",content:r,timestamp:i}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(r,n,i){if(!i)return null;let a=await this.service.getWalletTokenBalances({address:r,chain:n,excludeSpam:!0,excludeUnverifiedContracts:!0});if(!a.success||!a.data?.result)return null;let s=i.toLowerCase(),o=a.data.result.find(l=>l.token_address.toLowerCase()===s||l.symbol?.toLowerCase()===s||l.name?.toLowerCase().includes(s));return o||null}};var ic=class extends ue{constructor(r){super();p(this,"name","get-token-holders");p(this,"description",'Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea. ');p(this,"category","blockchain-data");p(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);p(this,"service");this.service=new it(r)}async run(r,n){let i=Qe(r.chain,n),a=n?.walletAddress||void 0,s=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,o=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!s&&!o)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let l,u;if(s){let f=await this.resolveContractAddress(s,i,a);if(!f)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${i?ut(i):"the selected chain"}. Try passing contractAddress directly.`};o=f.address,l=f.symbol,u=f.name}let c=await this.service.getTokenHolders({address:o,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:l??s??null,name:u??null,contractAddress:o,chain:i||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(r,n,i){let a=r.toLowerCase();if(i){let o=await this.service.getWalletTokenBalances({address:i,chain:n});if(o.success&&o.data?.result?.length){let l=o.data.result.find(u=>(u.symbol??"").toLowerCase()===a);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let s=await this.service.searchTokensByKey({key:r,chain:n});if(s.success&&s.data?.length){let l=s.data.find(u=>(u.symbol??"").toLowerCase()===a)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};var ac=class extends ue{constructor(r){super();p(this,"name","get-token-analytics");p(this,"description",`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);p(this,"category","blockchain-data");p(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);p(this,"service");this.service=new it(r)}async run(r,n){let i=Qe(r.chain,n),a=n?.walletAddress||void 0,s=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,o=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!s&&!o)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(s){let f=await this.resolveContractAddress(s,i,a);if(!f)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${i?ut(i):"the selected chain"}. Try passing contractAddress directly.`};o=f.address,l=f.symbol,u=f.name}let c=await this.service.getTokenAnalytics({address:o,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:l??s??null,name:u??null,contractAddress:o,chain:i||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(r,n,i){let a=r.toLowerCase();if(i){let o=await this.service.getWalletTokenBalances({address:i,chain:n});if(o.success&&o.data?.result?.length){let l=o.data.result.find(u=>(u.symbol??"").toLowerCase()===a);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let s=await this.service.searchTokensByKey({key:r,chain:n});if(s.success&&s.data?.length){let l=s.data.find(u=>(u.symbol??"").toLowerCase()===a)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};var sc=class extends ue{constructor(r){super();p(this,"name","get-token-score");p(this,"description",`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea.`);p(this,"category","blockchain-data");p(this,"parameters",[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}]);p(this,"service");this.service=new it(r)}async run(r,n){let i=Qe(r.chain,n),a=n?.walletAddress||void 0,s=typeof r.tokenSymbol=="string"&&r.tokenSymbol?r.tokenSymbol.trim():void 0,o=typeof r.contractAddress=="string"&&r.contractAddress?r.contractAddress.trim():void 0;if(!s&&!o)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let l,u;if(s){let h=await this.resolveContractAddress(s,i,a);if(!h)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${i?ut(i):"the selected chain"}. Try passing contractAddress directly.`};o=h.address,l=h.symbol,u=h.name}let c=await this.service.getTokenScore({address:o,chain:i});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},f=d.metrics??{};return{token:{symbol:l??s??null,name:u??null,contractAddress:o,chain:i||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:f.usdPrice??null,liquidityUsd:f.liquidityUsd??null,volumeUsd:f.volumeUsd??null,transactions:f.transactions??null,supply:f.supply??null}}}async resolveContractAddress(r,n,i){let a=r.toLowerCase();if(i){let o=await this.service.getWalletTokenBalances({address:i,chain:n});if(o.success&&o.data?.result?.length){let l=o.data.result.find(u=>(u.symbol??"").toLowerCase()===a);if(l)return{address:l.token_address,symbol:l.symbol,name:l.name}}}let s=await this.service.searchTokensByKey({key:r,chain:n});if(s.success&&s.data?.length){let l=s.data.find(u=>(u.symbol??"").toLowerCase()===a)??s.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}};var oc=class extends ue{constructor(r){super();p(this,"name","get-trending-tokens");p(this,"description",'List tokens trending on-chain right now, ranked by trading activity, volume, liquidity and holder growth. Returns price, market cap, liquidity, holder count, and multi-timeframe buckets (1h / 4h / 12h / 24h) of price change, volume, transaction counts, and unique buyers/sellers. Cross-chain by default \u2014 omit `chain` for a global ranking, or pass it to filter to one network. Use this tool for questions like: "What tokens are trending right now?", "Show me hot tokens", "What\'s popular on Base today?", "Which tokens have the highest 24h volume?", "Biggest movers in the last hour?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, and more.');p(this,"category","blockchain-data");p(this,"parameters",[{name:"chain",type:"string",description:'Optional hex chain ID to scope results to a single network: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user names a chain. Omit to return cross-chain trending results.',required:!1},{name:"limit",type:"number",description:'Total number of trending tokens to return (chain default tokens + top gainers combined). Only set this when the user asks for a specific count (e.g. "show 20 trending tokens" \u2192 20). Omit otherwise \u2014 when omitted, returns all default tokens plus 5 top gainers.',required:!1},{name:"buy_button_label",type:"string",description:`Label template for the per-token "Buy" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. One button is rendered per trending token, with "{token}" replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "Buy {token}". Vietnamese example: "Mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_prompt_template",type:"string",description:`A short "buy" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a token's Buy button is clicked. "{token}" is replaced by that token's symbol. Use the exact placeholder "{token}" (do not translate the braces); put the localized verb in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0}]);p(this,"service");this.service=new cn({baseUrl:r?.pantographUrl})}async run(r,n){let i=Uy(r.chain,n),a=r.buy_button_label||"",s=r.buy_prompt_template||"",o=typeof r.limit=="number"&&Number.isFinite(r.limit)&&r.limit>0?Math.floor(r.limit):void 0,l=await this.service.getTrendingTokens({chain:i,limit:o});if(!l.success)return{error:l.error||"Failed to fetch trending tokens"};let u=l.data??[],c=new Set,d=[];for(let f of u){let h=f.symbol?.trim();!h||c.has(h.toLowerCase())||(c.add(h.toLowerCase()),d.push({label:this.fillTemplate(a,h,"Buy {token}"),prompt:this.fillTemplate(s,h,"buy {token}")}))}return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
442
442
  <rank>. <name> (<symbol>)
@@ -1354,7 +1354,7 @@ ${e}${u}
1354
1354
  Return JSON only.`,timestamp:Date.now()}],f=[{role:"system",content:y7,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[h,m]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(f)]),g={};if(h.status==="fulfilled")try{g=this.parseJSON(h.value.text)}catch(S){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${S}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${h.reason}`);let y="";if(m.status==="fulfilled")try{let S=this.parseJSON(m.value.text);typeof S.language=="string"&&(y=S.language.trim().toLowerCase())}catch(S){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${S}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${m.reason}`);let _={isFollowUp:i&&typeof g.isFollowUp=="boolean"?g.isFollowUp:!1,rewrittenQuery:typeof g.rewrittenQuery=="string"&&g.rewrittenQuery.trim()?g.rewrittenQuery.trim():e,topicChanged:i&&typeof g.topicChanged=="boolean"?g.topicChanged:!1,reasoning:typeof g.reasoning=="string"?g.reasoning:"",language:y,mentionedChain:typeof g.mentionedChain=="string"?g.mentionedChain.trim():"",needsWebSearch:g.needsWebSearch===!0,aboutAssistant:g.aboutAssistant===!0};if(this.debug){let S=Date.now()-c,k=_.rewrittenQuery!==e;console.log(`
1355
1355
  [QueryRewriter] (${S}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${_.rewrittenQuery}"${k?"":" (unchanged)"}`),console.log(` followUp : ${_.isFollowUp} topicChanged: ${_.topicChanged}`),_.reasoning&&console.log(` reasoning : ${_.reasoning}`),console.log(` language : ${_.language}`),console.log(` webSearch : ${_.needsWebSearch}`),console.log(` aboutSelf : ${_.aboutAssistant}`)}return _}parseJSON(e){let r=e.trim();r.startsWith("```")&&(r=r.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=r.match(/\{[\s\S]*\}/);return n&&(r=n[0]),JSON.parse(r)}};var Rt=hy(gG());var ri=t=>({reducer:(e,r)=>r,default:t}),aDe=Rt.Annotation.Root({userMessage:(0,Rt.Annotation)(),doSuggest:(0,Rt.Annotation)(ri(()=>!0)),overrideLang:(0,Rt.Annotation)(ri(()=>"")),conversationMessages:(0,Rt.Annotation)(ri(()=>[])),lastSubagents:(0,Rt.Annotation)(ri(()=>[])),messageId:(0,Rt.Annotation)(ri(()=>"")),rewrite:(0,Rt.Annotation)(ri(()=>null)),effectiveQuery:(0,Rt.Annotation)(ri(()=>"")),turnLanguage:(0,Rt.Annotation)(ri(()=>"")),kbContext:(0,Rt.Annotation)(ri(()=>"")),decision:(0,Rt.Annotation)(ri(()=>null)),assignment:(0,Rt.Annotation)(ri(()=>null)),assignmentIndex:(0,Rt.Annotation)(ri(()=>0)),subResults:(0,Rt.Annotation)({reducer:(t,e)=>t.concat(e),default:()=>[]}),response:(0,Rt.Annotation)(ri(()=>null))});function yG(t){let e=async d=>{t.addUserMessage(d.userMessage),t.needsSummary()&&await t.compactHistory();let f=t.conversationForTurn(),h=t.lastAssistantSubagents(f);return t.debug&&h.length>0&&console.log(`[AgentCore] previous turn handled by: ${h.join(", ")}`),{conversationMessages:f,lastSubagents:h,messageId:t.generateMessageId()}},r=async d=>{let f=await t.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),h=d.overrideLang||f.language||"";return{rewrite:f,effectiveQuery:f.rewrittenQuery,turnLanguage:h}},n=async d=>{let f=d.rewrite,h=f.isFollowUp?d.effectiveQuery:d.userMessage,m=await t.searchKB(h),g=t.formatKBContext(m),y=await t.tryAnswerFromKB(d.userMessage,m,g,d.messageId);return y?{kbContext:g,response:{...y,messageId:d.messageId,rewrite:f}}:{kbContext:g}},i=async d=>({decision:await t.route(d.effectiveQuery,d.conversationMessages,t.subagentCards(),d.lastSubagents)}),a=async d=>{let f=await t.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,d.messageId,d.rewrite?.needsWebSearch??!1),h=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...f,messageId:d.messageId,routerDecision:h,rewrite:d.rewrite}}},s=async d=>{let f=await t.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:f}]}},o=async d=>{let f=d.subResults.slice().sort((P,A)=>P.i-A.i).map(P=>P.result);t.persistToolMessages(f);let h=t.mergeTrace(f),m=await t.synthesise(d.userMessage,h,t.synthesiserHistory(),d.turnLanguage||void 0),g=f.map(P=>P.subagentName),y=t.collectUiActions(f,d.turnLanguage||null),_=t.collectActionButtons(f,d.turnLanguage||null),S=t.subResultsTriggerNoSuggestions(f);return{response:{...await t.finaliseAnswer({userMessage:d.userMessage,answer:m,subagents:g,uiActions:y,actionButtons:_,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!S&&_.length===0}),messageId:d.messageId,trace:h,routerDecision:d.decision,subagentResults:f,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},..._.length>0?{actionButtons:_}:{}}}},l=async d=>{let f=(d.rewrite?.mentionedChain||String(t.connectedChain()??"")).trim();return{response:{...await t.answerUnsupportedChain(f,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},u=d=>d.response?Rt.END:d.rewrite?.aboutAssistant?"direct":"route",c=d=>{let f=d.decision?.assignments??[];if(f.length===0)return"direct";let h=f.some(g=>g.subagent!=="ai-agent"),m=(d.rewrite?.mentionedChain||t.connectedChain()||"").trim();return h&&m!==""&&!My(m)?"unsupportedChain":f.map((g,y)=>new Rt.Send("subagent",{...d,assignment:g,assignmentIndex:y}))};return new Rt.StateGraph(aDe).addNode("setup",e).addNode("contextualize",r).addNode("kb",n).addNode("route",i).addNode("direct",a).addNode("subagent",s).addNode("synthesize",o).addNode("unsupportedChain",l).addEdge(Rt.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",u,["route","direct",Rt.END]).addConditionalEdges("route",c,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",Rt.END).addEdge("direct",Rt.END).addEdge("subagent","synthesize").addEdge("synthesize",Rt.END).compile()}var _G=hy(jy());function dT(){let t=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(t+e).slice(-8)}var sDe="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",oDe=`
1356
1356
 
1357
- IDENTITY: If the user asks who or what you are, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline and steer back to how you can help.`,pT=class{constructor(e){p(this,"llm");p(this,"registry");p(this,"history");p(this,"summarizer");p(this,"router");p(this,"rewriter");p(this,"subagents");p(this,"synthesizer");p(this,"chatGraph");p(this,"systemPrompt");p(this,"debug");p(this,"secretKey");p(this,"licenseChecked",!1);p(this,"userContext",{});p(this,"storage");p(this,"storageKey");p(this,"persistHistoryEnabled");p(this,"kb");p(this,"kbEntries");p(this,"vectorKB",null);p(this,"vectorKBAutoIngested",!1);p(this,"vectorKBAutoIngestPromise",null);p(this,"autoIngestEnabled",!1);p(this,"kbAnswerThreshold");p(this,"suggestionsEnabled");p(this,"historyLoaded",!1);p(this,"historyLoadingPromise",null);p(this,"inFlightTurn",null);p(this,"historyReady");this.secretKey=e.secretKey,ek(e.rpcUrls),Ny(e.excludeChains),this.llm=new Pn(e.llm),this.registry=new Yu,this.history=new id(e.maxHistoryMessages??50),this.summarizer=new ad(this.llm),this.synthesizer=new ld(this.llm),this.systemPrompt=(e.systemPrompt??sDe)+oDe,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new sd(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let r=e.vectorKB;r?.enabled?(r.provider?this.kb=r.provider:(this.vectorKB=new To({url:r.url,token:r.token,namespace:r.namespace,minScore:r.minScore,defaultTopK:r.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=r.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${r.provider?"custom provider":"Upstash"}`+(r.namespace?`, ns=${r.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:r?.enabled&&!r.provider?this.kbAnswerThreshold=r.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let c=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new uc(c)),this.registry.register(new nc(c)),this.registry.register(new cc(c)),this.registry.register(new dc(c)),this.registry.register(new pc(c)),this.registry.register(new ic(c)),this.registry.register(new fc(c)),this.registry.register(new hc(c)),this.registry.register(new bc(c)),this.registry.register(new gc(c)),this.registry.register(new yc(c)),this.registry.register(new _c(c)),this.registry.register(new mc(c)),this.registry.register(new oc(c)),this.registry.register(new lc(c)),this.registry.register(new ac(c)),this.registry.register(new sc(c))}let i=e.nftLink;this.registry.register(new wc({url:i})),this.registry.register(new Sc),this.registry.register(new Tc),this.registry.register(new kc(e.llm));let a=e.subagents?.["pool-subgraph"]===!0;if((a?e.subagents?.pool===!0:e.subagents?.pool!==!1)&&e.uniswap!==!1){let c=typeof e.uniswap=="object"?e.uniswap:void 0;this.registry.register(new Ec(c)),this.registry.register(new Cc(c)),this.registry.register(new xc(c)),this.registry.register(new Ac(c)),this.registry.register(new jc(c));let d=c?{isProduction:c.isProduction}:void 0;this.registry.register(new Uc({baseUrl:c?.baseUrl,pool:d,minProvideUsd:c?.minProvideUsd})),this.registry.register(new qc({pool:d}))}if(a&&e.subgraph!==!1){let c=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Lc(c)),this.registry.register(new Bc(c)),this.registry.register(new Fc(c)),this.registry.register(new zc(c)),this.registry.register(new Vc(c)),this.registry.register(new Zc(c)),this.registry.register(new Hc(c)),this.registry.register(new Pc(e.llm))}if(e.subagents?.["wallet-action"]!==!1){let c=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Kc(c)),this.registry.register(new Jc(c)),this.registry.register(new nd(c,{url:i})),this.registry.register(new Yc(c)),this.registry.register(new td(c,{debug:this.debug})),this.registry.register(new rd(c,{debug:this.debug}))}this.router=new od(this.llm,{debug:this.debug}),this.rewriter=new l_(this.llm,{debug:this.debug});let l=typeof e.subgraph=="object"?e.subgraph:void 0,u=o_(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:l?.linkAddLiquidity},e.subagents);this.subagents=new Map(u.map(c=>[c.name,c])),this.chatGraph=yG(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let r of e)this.registry.register(r)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,r,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:dT()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(r)}`);let a=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:a,timestamp:Date.now()});let s=await this.registry.execute(e,r,this.userContext),o=s.data,l=s.success?o?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,u=dT(),c=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:u};return c.length>0&&(d.uiActions=c),this.history.add(d),await this.persistHistory(),{answer:l,messageId:u,...c.length>0?{uiActions:c}:{}}}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let r=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,r}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:r}=await this.ingestKnowledgeBase();this.debug&&r>0&&console.log(`[AgentCore] auto-ingested ${r} KB entr${r===1?"y":"ies"} to vector store`)}catch(r){this.debug&&console.warn("[AgentCore] auto-ingest failed:",r)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let r=JSON.parse(e);this.history.restore(r),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;let e="";if(e&&(!this.secretKey||(0,_G.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,r){this.assertLicense();let n=r?.generateSuggestions??this.suggestionsEnabled,i=typeof r?.language=="string"&&r.language.trim()?r.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let a=Date.now();this.debug&&(console.log(`
1357
+ IDENTITY: If the user asks who or what you are, say only that you are an AI assistant here to help with crypto and DeFi questions. NEVER claim to be, or to be made / trained / powered by, any specific company or model (e.g. Google, Gemini, OpenAI, GPT, Anthropic, Claude). Do NOT reveal or speculate about the underlying model, provider, or training. If pressed for those details, politely decline and steer back to how you can help.`,pT=class{constructor(e){p(this,"llm");p(this,"registry");p(this,"history");p(this,"summarizer");p(this,"router");p(this,"rewriter");p(this,"subagents");p(this,"synthesizer");p(this,"chatGraph");p(this,"systemPrompt");p(this,"debug");p(this,"secretKey");p(this,"licenseChecked",!1);p(this,"userContext",{});p(this,"storage");p(this,"storageKey");p(this,"persistHistoryEnabled");p(this,"kb");p(this,"kbEntries");p(this,"vectorKB",null);p(this,"vectorKBAutoIngested",!1);p(this,"vectorKBAutoIngestPromise",null);p(this,"autoIngestEnabled",!1);p(this,"kbAnswerThreshold");p(this,"suggestionsEnabled");p(this,"historyLoaded",!1);p(this,"historyLoadingPromise",null);p(this,"inFlightTurn",null);p(this,"historyReady");this.secretKey=e.secretKey,ek(e.rpcUrls),Ny(e.excludeChains),this.llm=new Pn(e.llm),this.registry=new Yu,this.history=new id(e.maxHistoryMessages??50),this.summarizer=new ad(this.llm),this.synthesizer=new ld(this.llm),this.systemPrompt=(e.systemPrompt??sDe)+oDe,this.debug=e.debug??!1,this.suggestionsEnabled=e.generateSuggestions??!0,this.storage=e.storage??null,this.storageKey=e.storageKey??"keyring-agent-history",this.persistHistoryEnabled=e.persistHistory??!1,this.kbEntries=new sd(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let r=e.vectorKB;r?.enabled?(r.provider?this.kb=r.provider:(this.vectorKB=new To({url:r.url,token:r.token,namespace:r.namespace,minScore:r.minScore,defaultTopK:r.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=r.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${r.provider?"custom provider":"Upstash"}`+(r.namespace?`, ns=${r.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:r?.enabled&&!r.provider?this.kbAnswerThreshold=r.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let c=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new uc(c)),this.registry.register(new nc(c)),this.registry.register(new cc(c)),this.registry.register(new dc(c)),this.registry.register(new pc(c)),this.registry.register(new ic(c)),this.registry.register(new fc(c)),this.registry.register(new hc(c)),this.registry.register(new bc(c)),this.registry.register(new gc(c)),this.registry.register(new yc(c)),this.registry.register(new _c(c)),this.registry.register(new mc(c)),this.registry.register(new oc(c)),this.registry.register(new lc(c)),this.registry.register(new ac(c)),this.registry.register(new sc(c))}let i=e.nftLink;this.registry.register(new wc({url:i})),this.registry.register(new Sc),this.registry.register(new Tc),this.registry.register(new kc(e.llm));let a=e.subagents?.["pool-subgraph"]===!0;if((a?e.subagents?.pool===!0:e.subagents?.pool!==!1)&&e.uniswap!==!1){let c=typeof e.uniswap=="object"?e.uniswap:void 0;this.registry.register(new Ec(c)),this.registry.register(new Cc(c)),this.registry.register(new xc(c)),this.registry.register(new Ac(c)),this.registry.register(new jc(c));let d=c?{isProduction:c.isProduction}:void 0;this.registry.register(new Uc({baseUrl:c?.baseUrl,pool:d,minProvideUsd:c?.minProvideUsd})),this.registry.register(new qc({pool:d}))}if(a&&e.subgraph!==!1){let c=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Lc(c)),this.registry.register(new Bc(c)),this.registry.register(new Fc(c)),this.registry.register(new zc(c)),this.registry.register(new Vc(c)),this.registry.register(new Zc(c)),this.registry.register(new Hc(c)),this.registry.register(new Pc(e.llm))}if(e.subagents?.["wallet-action"]!==!1){let c=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new Kc(c)),this.registry.register(new Jc(c)),this.registry.register(new nd(c,{url:i})),this.registry.register(new Yc(c)),this.registry.register(new td(c,{debug:this.debug})),this.registry.register(new rd(c,{debug:this.debug}))}this.router=new od(this.llm,{debug:this.debug}),this.rewriter=new l_(this.llm,{debug:this.debug});let l=typeof e.subgraph=="object"?e.subgraph:void 0,u=o_(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:l?.linkAddLiquidity},e.subagents);this.subagents=new Map(u.map(c=>[c.name,c])),this.chatGraph=yG(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let r of e)this.registry.register(r)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,r,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:dT()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(r)}`);let a=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:a,timestamp:Date.now()});let s=await this.registry.execute(e,r,this.userContext),o=s.data,l=s.success?o?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,u=dT(),c=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:u};return c.length>0&&(d.uiActions=c),this.history.add(d),await this.persistHistory(),{answer:l,messageId:u,...c.length>0?{uiActions:c}:{}}}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let r=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,r}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:r}=await this.ingestKnowledgeBase();this.debug&&r>0&&console.log(`[AgentCore] auto-ingested ${r} KB entr${r===1?"y":"ies"} to vector store`)}catch(r){this.debug&&console.warn("[AgentCore] auto-ingest failed:",r)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let r=JSON.parse(e);this.history.restore(r),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,_G.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey.");this.licenseChecked=!0}async chat(e,r){this.assertLicense();let n=r?.generateSuggestions??this.suggestionsEnabled,i=typeof r?.language=="string"&&r.language.trim()?r.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let a=Date.now();this.debug&&(console.log(`
1358
1358
  ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=this.chatGraph.invoke({userMessage:e,doSuggest:n,overrideLang:i});this.inFlightTurn=s;let o;try{o=await s}finally{this.inFlightTurn===s&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-a}ms total`),console.log(`${"\u2500".repeat(60)}
1359
1359
  `)),o.response??{answer:"",messageId:dT()}}createGraphHost(){return{debug:this.debug,addUserMessage:e=>this.addUserMessage(e),needsSummary:()=>this.history.needsSummary(),compactHistory:()=>this.compactHistory(),conversationForTurn:()=>{let e=this.history.getConversation();return e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e},lastAssistantSubagents:e=>nN(e),generateMessageId:()=>dT(),rewrite:(e,r,n)=>this.rewriter.rewrite(e,r,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,r,n,i)=>this.tryAnswerFromKB(e,r,n,i),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,r,n,i)=>this.router.route(e,r,n,this.userContext,i),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,r,n)=>this.answerUnsupportedChain(e,r,n),answerDirectly:(e,r,n,i,a,s)=>this.answerDirectly(e,r,n,i,a,s),runSubagent:async(e,r,n)=>{let i=this.subagents.get(e.subagent);if(!i)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let a=Date.now(),s=await i.run({query:e.query,reasoning:e.reasoning,language:n},r,this.userContext);if(this.debug){let o=s.toolResults.map(l=>l.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-a}ms | tools: ${o}`)}return s},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>{let e=this.history.getConversation(),r=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return na(r)},mergeTrace:e=>this.mergeTrace(e),synthesise:(e,r,n,i)=>this.synthesizer.synthesise(e,r,n,i),collectUiActions:(e,r)=>this.collectUiActions(e,r),collectActionButtons:(e,r)=>this.collectActionButtons(e,r),subResultsTriggerNoSuggestions:e=>this.subResultsTriggerNoSuggestions(e),finaliseAnswer:(e,r)=>this.finaliseAnswer(e,r)}}subResultsTriggerNoSuggestions(e){for(let r of e)for(let n of r.toolResults){if(!n.success)continue;if(this.registry.get(n.toolName)?.noSuggestions===!0)return!0}return!1}capitalizeFirst(e){if(!e)return e;let r=Array.from(e);return r[0]=r[0].toLocaleUpperCase(),r.join("")}collectActionButtons(e,r){let n=new Map,i=[];for(let a of e)for(let s of a.toolResults)if(!(!s.success||!Array.isArray(s.actionButtons)))for(let o of s.actionButtons){if(!o||typeof o!="object"||typeof o.label!="string"||!o.label.trim()||typeof o.prompt!="string"||!o.prompt.trim())continue;let l=this.capitalizeFirst(o.prompt),u={label:o.label,prompt:l,...r?{language:r}:{}},c=n.get(l);c?u.label.length>c.label.length&&n.set(l,u):(n.set(l,u),i.push(l))}return i.map(a=>n.get(a))}collectUiActions(e,r){let n=[];for(let i of e)for(let a of i.toolResults)a.success&&a.ui&&typeof a.ui=="object"&&typeof a.ui.component=="string"&&n.push(this.stampLanguage(a.ui,r));if(this.debug&&n.length>0){let i=n.map(a=>`${a.component}=${a.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${r??""}"): ${i}`)}return n}stampLanguage(e,r){return!r||e.language?e:{...e,language:r}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let r=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(r.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=r.slice(0,3).map(i=>`${i.score.toFixed(3)} ${this.snippet(i.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${r.length}): ${n}`)}return r}snippet(e,r){return e.length<=r?e:e.slice(0,r-1)+"\u2026"}formatKBContext(e){let r=e.filter(n=>n.score>=this.kbAnswerThreshold);return r.length===0?"":r.map((n,i)=>`[Reference ${i+1}]
1360
1360
  Q: ${n.entry.question}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keyring-agent-core",
3
- "version": "0.2.21",
3
+ "version": "0.2.22",
4
4
  "description": "Core AI chat agent with multi-agent architecture, ReAct pattern, and modular tool system powered by Gemini",
5
5
  "main": "dist/index.js",
6
6
  "react-native": "dist/index.native.js",