keyring-agent-core 0.2.27 → 0.2.29

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 Qr=Object.create;var qn=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(l,e)=>{for(var t in e)qn(l,t,{get:e[t],enumerable:!0})},Wo=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jr(e))!es.call(l,r)&&r!==t&&qn(l,r,{get:()=>e[r],enumerable:!(n=Xr(e,r))||n.enumerable});return l};var ns=(l,e,t)=>(t=l!=null?Qr(Zr(l)):{},Wo(e||!l||!l.__esModule?qn(t,"default",{value:l,enumerable:!0}):t,l)),os=l=>Wo(qn({},"__esModule",{value:!0}),l);var Ea={};ts(Ea,{AI_AGENT_TOOL_NAMES:()=>uo,AbortError:()=>Ye,AgentCore:()=>yo,ApproveTokenTool:()=>rn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>T,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>cn,ChatHistory:()=>pn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>xn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>qt,EstimatePoolYieldTool:()=>Ht,GeminiProvider:()=>J,GeminiSearchAiTool:()=>Et,HEX_TO_PANTOGRAPH:()=>lr,KnowledgeBase:()=>hn,ManageLiquidityRedirectTool:()=>Yt,MoralisService:()=>D,NFTContractInfoTool:()=>_t,NFTMetadataTool:()=>Ct,NFT_AGENT_TOOL_NAMES:()=>co,OpenAddLiquidityFormTool:()=>Vt,POOL_AGENT_TOOL_NAMES:()=>po,PantographService:()=>ne,PoolByAddressTool:()=>Ot,PoolDetailTool:()=>Lt,PoolFallbackAiTool:()=>Rt,PoolPriceRangesTool:()=>Gt,PoolSearchTool:()=>Dt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Wt,RelayAdapter:()=>Ft,Router:()=>gn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>Zn,SendNativeTool:()=>nn,SendNftTool:()=>dn,SendTokenTool:()=>on,Subagent:()=>j,SubgraphAddPoolTool:()=>Zt,SubgraphCoinPoolPairsTool:()=>Jt,SubgraphPoolByAddressTool:()=>zt,SubgraphPoolByPositionIdTool:()=>Qt,SubgraphPoolSearchTool:()=>Kt,SubgraphPositionDetailTool:()=>Xt,SubgraphTrendingPoolsTool:()=>jt,Summarizer:()=>mn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>un,Synthesizer:()=>fn,TOKEN_AGENT_TOOL_NAMES:()=>lo,TRANSFER_TOPIC:()=>Nr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>cr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>It,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Cn,UpstashKnowledgeBase:()=>Ve,WALLET_ACTION_AGENT_TOOL_NAMES:()=>mo,WALLET_AGENT_TOOL_NAMES:()=>ao,WalletActionAppTool:()=>En,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>Tt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>vt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustAgent:()=>bo,ZERO_ADDRESS:()=>$,buildRangePresets:()=>Lo,buildUniswapPoolUrl:()=>pe,clampTick:()=>_e,configureSupportedChains:()=>Vn,createAiAgent:()=>Ln,createDefaultSubagents:()=>ho,createNftAgent:()=>In,createPoolAgent:()=>Dn,createTokenAgent:()=>Un,createWalletActionAgent:()=>On,createWalletActionAppTools:()=>io,createWalletAgent:()=>Nn,ethCallAt:()=>Cr,ethCallByChain:()=>Io,getAffiliateFee:()=>Mt,getChainMeta:()=>ee,getDefaultRpcUrl:()=>Si,getGatewayAddress:()=>to,getNativeTokenInfo:()=>$t,getPositionManagerAddress:()=>no,getProviderByChain:()=>Jn,ingestKnowledgeBase:()=>zr,isAbortError:()=>et,normalizePriceRangeToPool:()=>Ut,priceToTick:()=>ze,resolveRpcUrl:()=>Bt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Uo,swapServiceFactory:()=>Ce,tickToPrice:()=>be,toPantographChain:()=>An});module.exports=os(Ea);var Go=ns(require("axios"));var Ho="0.2.27";var ss=`keyring-agent-core/${Ho} (Keyring Chatbot Agent; +https://keyring.app)`,is=3e4,as=typeof process<"u"&&process.versions?.node!=null,wo=class{instance;constructor(e={}){this.instance=Go.default.create({baseURL:e.baseURL,timeout:e.timeout??is,validateStatus:()=>!0,headers:{Accept:"application/json",...as?{"User-Agent":e.userAgent??ss}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[i,a]of Object.entries(o.headers??{}))a!=null&&(s[i.toLowerCase()]=String(a));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)}},P=new wo;function L(l){let{data:e,status:t,statusText:n}=l,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=a=>a&&typeof a=="object"?a.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let a of i)if(typeof a=="string"&&a.trim())return a.trim()}return r}var Ye=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function et(l){if(!l||typeof l!="object")return!1;let e=l;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function ko(l){if(l?.aborted)throw new Ye}function Yo(l,e){if(!e)return{signal:l.signal,cleanup:()=>{}};if(e.aborted)return l.abort(),{signal:l.signal,cleanup:()=>{}};let t=()=>l.abort();return e.addEventListener("abort",t),{signal:l.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Ko={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ls="https://nft.keyring.app/api/gemini-stable",cs=new Set([408,429,500,502,503,504]),jo=3e4,Fn=l=>new Promise(e=>setTimeout(e,l));function $n(l,e,t){if(t!=null&&t>0)return Math.min(t,jo);let n=Math.min(e*2**(l-1),jo);return n/2+Math.random()*(n/2)}function us(l){if(!l)return null;let e=Number(l);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(l);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var J=class{model;maxTokens;temperature;baseUrl;requestSignal;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??ls}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},a=n?.signal??this.requestSignal;ko(a);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=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}: [${g}]`)}}let u={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(u.systemInstruction=r),t?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){ko(a);let g;try{g=await P.post(d,u,{headers:{"Content-Type":"application/json"},signal:a})}catch(k){if(et(k))throw k;if(p=k instanceof Error?k.message:String(k),m>=s)break;await Fn($n(m,i));continue}if(!g.ok){let k=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(p=`Gemini proxy error ${g.status}: ${k}`,!cs.has(g.status))throw new Error(p);if(m>=s)break;let A=us(g.headers["retry-after"]??null);await Fn($n(m,i,A));continue}if(g.data==null||typeof g.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await Fn($n(m,i));continue}let h=g.data,f=h.candidates?.[0];if(!f)return{text:"",toolCalls:[]};let y="",b=[],w=f.content?.parts;if(!Array.isArray(w)||w.length===0){let k=f.finishReason;if(!(k==="SAFETY"||k==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${k??"none"})`,await Fn($n(m,i));continue}return{text:"",toolCalls:[]}}for(let k of w)k.text&&(y+=k.text),k.functionCall&&b.push({toolName:k.functionCall.name,args:k.functionCall.args??{},callId:k.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let v=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:v}}throw new Error(p)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(a=>({functionCall:{name:a.toolName,args:a.args,...a.callId?{id:a.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let a=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=a?.parts.some(d=>d.functionCall);a&&a.role===i.role&&!c&&!u?a.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let a=r[i],c=o[o.length-1];a.role==="function"&&!c?.parts.some(d=>d.functionCall)||a.role==="model"&&a.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(a)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
1
+ "use strict";var Qr=Object.create;var qn=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(l,e)=>{for(var t in e)qn(l,t,{get:e[t],enumerable:!0})},Wo=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Jr(e))!es.call(l,r)&&r!==t&&qn(l,r,{get:()=>e[r],enumerable:!(n=Xr(e,r))||n.enumerable});return l};var ns=(l,e,t)=>(t=l!=null?Qr(Zr(l)):{},Wo(e||!l||!l.__esModule?qn(t,"default",{value:l,enumerable:!0}):t,l)),os=l=>Wo(qn({},"__esModule",{value:!0}),l);var Ra={};ts(Ra,{AI_AGENT_TOOL_NAMES:()=>uo,AbortError:()=>Ye,AgentCore:()=>yo,ApproveTokenTool:()=>rn,BaseNftAiTool:()=>Pe,BaseNftMessageTool:()=>Pt,BaseSwapService:()=>$e,BaseTool:()=>T,BaseWalletActionTool:()=>ye,BuyTokenTool:()=>cn,ChatHistory:()=>pn,DEFAULT_CHAIN:()=>Se,DEFAULT_PROVIDER:()=>xn,DEFAULT_RPC_BY_CHAIN:()=>fe,DebridgeAdapter:()=>qt,EstimatePoolYieldTool:()=>Ht,GeminiProvider:()=>J,GeminiSearchAiTool:()=>Et,HEX_TO_PANTOGRAPH:()=>lr,KnowledgeBase:()=>hn,ManageLiquidityRedirectTool:()=>Yt,MoralisService:()=>D,NFTContractInfoTool:()=>_t,NFTMetadataTool:()=>Ct,NFT_AGENT_TOOL_NAMES:()=>co,OpenAddLiquidityFormTool:()=>Vt,POOL_AGENT_TOOL_NAMES:()=>po,PantographService:()=>ne,PoolByAddressTool:()=>Ot,PoolDetailTool:()=>Lt,PoolFallbackAiTool:()=>Rt,PoolPriceRangesTool:()=>Gt,PoolSearchTool:()=>Dt,PoolService:()=>Xe,PreviewAddLiquidityTool:()=>Wt,RelayAdapter:()=>Ft,Router:()=>gn,SUPPORTED_CHAINS:()=>nt,SUPPORTED_CHAINS_LABEL:()=>Ke,SWAP_PROVIDER_CONFIG:()=>Zn,SendNativeTool:()=>nn,SendNftTool:()=>dn,SendTokenTool:()=>on,Subagent:()=>j,SubgraphAddPoolTool:()=>Zt,SubgraphCoinPoolPairsTool:()=>Jt,SubgraphPoolByAddressTool:()=>zt,SubgraphPoolByPositionIdTool:()=>Qt,SubgraphPoolSearchTool:()=>Kt,SubgraphPositionDetailTool:()=>Xt,SubgraphTrendingPoolsTool:()=>jt,Summarizer:()=>mn,SwapServiceFactory:()=>Qe,SwapTokenTool:()=>un,Synthesizer:()=>fn,TOKEN_AGENT_TOOL_NAMES:()=>lo,TRANSFER_TOPIC:()=>Nr,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>cr,TokenAnalyticsTool:()=>ut,TokenHoldersTool:()=>ct,TokenInfoTool:()=>lt,TokenScoreTool:()=>dt,ToolRegistry:()=>tt,TopGainersTool:()=>mt,TopPoolsTool:()=>It,TransactionByHashTool:()=>St,TrendingTokensTool:()=>pt,UNISWAP_CHAIN_SLUG:()=>Cn,UpstashKnowledgeBase:()=>Ve,WALLET_ACTION_AGENT_TOOL_NAMES:()=>mo,WALLET_AGENT_TOOL_NAMES:()=>ao,WalletActionAppTool:()=>En,WalletApprovalsTool:()=>kt,WalletDefiPositionsTool:()=>Tt,WalletDefiProtocolPositionsTool:()=>At,WalletDefiSummaryTool:()=>vt,WalletHistoryTool:()=>gt,WalletNFTsTool:()=>xt,WalletNftTransfersTool:()=>yt,WalletPnlSummaryTool:()=>bt,WalletPnlTool:()=>wt,WalletTokenBalancesTool:()=>ht,WalletTokenTransfersTool:()=>ft,WebsiteTrustKeyringAgent:()=>bo,ZERO_ADDRESS:()=>$,buildRangePresets:()=>Lo,buildUniswapPoolUrl:()=>pe,clampTick:()=>_e,configureSupportedChains:()=>Vn,createAiAgent:()=>Ln,createDefaultSubagents:()=>ho,createNftAgent:()=>In,createPoolAgent:()=>Dn,createTokenAgent:()=>Un,createWalletActionAgent:()=>On,createWalletActionAppTools:()=>io,createWalletAgent:()=>Nn,ethCallAt:()=>Cr,ethCallByChain:()=>Io,getAffiliateFee:()=>Mt,getChainMeta:()=>ee,getDefaultRpcUrl:()=>Si,getGatewayAddress:()=>to,getNativeTokenInfo:()=>$t,getPositionManagerAddress:()=>no,getProviderByChain:()=>Jn,ingestKnowledgeBase:()=>zr,isAbortError:()=>et,normalizePriceRangeToPool:()=>Ut,priceToTick:()=>ze,resolveRpcUrl:()=>Bt,roundTickToSpacing:()=>xe,rpcCall:()=>Ie,setRpcOverrides:()=>Uo,swapServiceFactory:()=>Ce,tickToPrice:()=>be,toPantographChain:()=>An});module.exports=os(Ra);var Go=ns(require("axios"));var Ho="0.2.29";var ss=`keyring-agent-core/${Ho} (Keyring Chatbot Agent; +https://keyring.app)`,is=3e4,as=typeof process<"u"&&process.versions?.node!=null,wo=class{instance;constructor(e={}){this.instance=Go.default.create({baseURL:e.baseURL,timeout:e.timeout??is,validateStatus:()=>!0,headers:{Accept:"application/json",...as?{"User-Agent":e.userAgent??ss}:{},...e.headers}})}async request(e,t,n,r={}){let o=await this.instance.request({...r,method:e,url:t,data:n}),s={};for(let[i,a]of Object.entries(o.headers??{}))a!=null&&(s[i.toLowerCase()]=String(a));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)}},P=new wo;function L(l){let{data:e,status:t,statusText:n}=l,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,s=a=>a&&typeof a=="object"?a.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,s(o.error),s(o.data)];for(let a of i)if(typeof a=="string"&&a.trim())return a.trim()}return r}var Ye=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function et(l){if(!l||typeof l!="object")return!1;let e=l;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function ko(l){if(l?.aborted)throw new Ye}function Yo(l,e){if(!e)return{signal:l.signal,cleanup:()=>{}};if(e.aborted)return l.abort(),{signal:l.signal,cleanup:()=>{}};let t=()=>l.abort();return e.addEventListener("abort",t),{signal:l.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Ko={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},ls="https://nft.keyring.app/api/gemini-stable",cs=new Set([408,429,500,502,503,504]),jo=3e4,Fn=l=>new Promise(e=>setTimeout(e,l));function $n(l,e,t){if(t!=null&&t>0)return Math.min(t,jo);let n=Math.min(e*2**(l-1),jo);return n/2+Math.random()*(n/2)}function us(l){if(!l)return null;let e=Number(l);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(l);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var J=class{model;maxTokens;temperature;baseUrl;requestSignal;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??ls}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:s=5,retryDelayMs:i=1e3}=n??{},a=n?.signal??this.requestSignal;ko(a);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=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}: [${g}]`)}}let u={contents:c,generationConfig:{maxOutputTokens:this.maxTokens,temperature:this.temperature}};r&&(u.systemInstruction=r),t?.length?(u.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(u.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(u.tools=[{googleSearch:{}}]);let d=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,p="Unknown error";for(let m=1;m<=s;m++){ko(a);let g;try{g=await P.post(d,u,{headers:{"Content-Type":"application/json"},signal:a})}catch(k){if(et(k))throw k;if(p=k instanceof Error?k.message:String(k),m>=s)break;await Fn($n(m,i));continue}if(!g.ok){let k=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(p=`Gemini proxy error ${g.status}: ${k}`,!cs.has(g.status))throw new Error(p);if(m>=s)break;let A=us(g.headers["retry-after"]??null);await Fn($n(m,i,A));continue}if(g.data==null||typeof g.data!="object"){if(p="Gemini proxy returned invalid JSON",m>=s)break;await Fn($n(m,i));continue}let h=g.data,f=h.candidates?.[0];if(!f)return{text:"",toolCalls:[]};let y="",b=[],w=f.content?.parts;if(!Array.isArray(w)||w.length===0){let k=f.finishReason;if(!(k==="SAFETY"||k==="RECITATION")&&m<s){p=`Gemini returned an empty turn (finishReason=${k??"none"})`,await Fn($n(m,i));continue}return{text:"",toolCalls:[]}}for(let k of w)k.text&&(y+=k.text),k.functionCall&&b.push({toolName:k.functionCall.name,args:k.functionCall.args??{},callId:k.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let v=h.usageMetadata?{promptTokens:h.usageMetadata.promptTokenCount??0,completionTokens:h.usageMetadata.candidatesTokenCount??0,totalTokens:h.usageMetadata.totalTokenCount??0}:void 0;return{text:y,toolCalls:b,usage:v}}throw new Error(p)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(a=>({functionCall:{name:a.toolName,args:a.args,...a.callId?{id:a.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let a=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=a?.parts.some(d=>d.functionCall);a&&a.role===i.role&&!c&&!u?a.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let a=r[i],c=o[o.length-1];a.role==="function"&&!c?.parts.some(d=>d.functionCall)||a.role==="model"&&a.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(a)}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:Ko[o.type]??"STRING",description:o.description};o.type==="array"&&(s.items={type:Ko[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 tt=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 nt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708"],ds=new Set(nt),Oe=[...nt],zo=new Set(Oe),Se="0x1",Ke="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea";function ps(l){return l.map(e=>rt[e]??e).join(", ")}function Vn(l){let e=new Set;if(l)for(let n of l){let r=Wn(n);r&&e.add(r)}let t=nt.filter(n=>!e.has(n));Oe=t.length>0?[...t]:[...nt],zo=new Set(Oe),Se=Oe.includes("0x1")?"0x1":Oe[0],Ke=ps(Oe)}var ms={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"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 ie(l){let e=Wn(l);return e&&zo.has(e)?e:null}function Wn(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=ms[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&&ds.has(n)?n:null}function Hn(l){return ie(l)!==null}function he(){return[...Oe]}var ot=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Ke}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Me=l=>typeof l=="string"&&l.trim()!=="";function ae(l,e){if(Me(l)){let t=ie(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ie(e.chain);if(t)return t;throw new ot(e.chain.trim())}return null}function Gn(l,e){return ie(l)??ie(e?.chain)??void 0}var rt={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea"};function E(l){let e=Wn(l);return e&&rt[e]?rt[e]:typeof l=="string"&&l.trim()?l.trim():"the requested chain"}var hs={"0x1":"https://etherscan.io","0xa":"https://optimistic.etherscan.io","0x38":"https://bscscan.com","0x89":"https://polygonscan.com","0x2105":"https://basescan.org","0xa4b1":"https://arbiscan.io","0xa86a":"https://snowtrace.io","0xe708":"https://lineascan.build"};function Qo(l,e){let t=Wn(l),n=t?hs[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var gs={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a"};function Xo(l){if(typeof l!="string")return null;let e=l.trim().toLowerCase();return e?gs[e]??null:null}var fs={"0x1":"ETH","0xa":"ETH","0x38":"BNB","0x89":"POL","0x2105":"ETH","0xa4b1":"ETH","0xa86a":"AVAX","0xe708":"ETH"};function Jo(l){let e=ie(l);return e?fs[e]??null:null}function st(l,e){if(!Me(l))return null;let t=ie(l),n=ie(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:rt[t]??t,connectedLabel:rt[n]??n}}function Zo(l){let e=typeof l=="string"?l.trim():"";return Oe.map(t=>{let n=rt[t]??t;return{label:n,prompt:e?`${e} (${n})`:n}})}function it(l,e){return{actionButtons:Zo(e),_instructions:`The user wants to ${l} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var z=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=Zo(e)}},kn=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 K(l,e){if(Me(l))return l.trim();if(Me(e?.walletAddress))return e.walletAddress.trim();throw new kn}function M(l,e){if(Me(l)){let t=ie(l);if(t)return t;throw new ot(l.trim())}if(Me(e?.chain)){let t=ie(e.chain);if(t)return t;throw new ot(e.chain.trim())}if(Me(e?.walletAddress))throw new z(typeof e?.query=="string"?e.query:void 0);return Se}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=ys(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 z?{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 kn?{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 ys(l){if(!l||typeof l!="object")return{data:l};let e=l,t=e.actionButtons;if(!Array.isArray(t)||t.length===0)return{data:l};let{actionButtons:n,...r}=e;return{data:r,actionButtons:t}}var er=require("js-sha3");function F(l){return typeof l=="string"&&/^0x[0-9a-fA-F]{40}$/.test(l)}function bs(l){return new Uint8Array(er.keccak256.arrayBuffer(l))}function vn(l){let e=l.startsWith("0x")?l.slice(2):l,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 tr(l){return"0x"+Array.from(l).map(e=>e.toString(16).padStart(2,"0")).join("")}function nr(l){return new TextEncoder().encode(l)}function je(...l){let e=l.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of l)t.set(r,n),n+=r.length;return t}function ws(l,e=32){let t=new Uint8Array(e);return t.set(l,e-l.length),t}function ks(l,e=32){let t=new Uint8Array(e);return t.set(l),t}function or(l){let e=((l%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return vn(e)}function Tn(l){return or(BigInt(l))}function rr(l){return l==="uint"?"uint256":l==="int"?"int256":l.match(/^uint$/)?"uint256":l.match(/^int$/)?"int256":l.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function sr(l){let e=rr(l.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(l.components??[]).map(sr).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function vs(l){let e=(l.inputs??[]).map(sr).join(",");return`${l.name??""}(${e})`}function vo(l,e){let t=Ss(l.type);if(t){let[r,o]=t;return Ts({...l,type:o},e,r)}if(l.type==="tuple")return As(l,e);if(l.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:ws(vn(o.toLowerCase()))}}if(l.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=rr(l.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Tn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:or(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?vn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:ks(o)}}if(n==="bytes"){let r=typeof e=="string"?vn(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(Tn(r.length),s)}}if(n==="string"){let r=typeof e=="string"?nr(e):e,o=Math.ceil(r.length/32)*32,s=new Uint8Array(o);return s.set(r),{dynamic:!0,encoded:je(Tn(r.length),s)}}throw new Error(`Unsupported ABI type: ${l.type}`)}function To(l){let e=0;for(let{dynamic:o,encoded:s}of l)e+=o?32:s.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:s}of l)o?(t.push(Tn(e+r)),n.push(s),r+=s.length):t.push(s);return je(...t,...n)}function Ts(l,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 i=vo(l,s);i.dynamic&&(r=!0),o.push(i)}if(n||r){let s=To(o);if(n){let i=Tn(o.length);return{dynamic:!0,encoded:o.length>0?je(i,s):i}}return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:je(...o.map(s=>s.encoded))}}function As(l,e){let t=l.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let s=t[o],i=Array.isArray(e)?e[o]:e[s.name??""],a=vo(s,i);a.dynamic&&(n=!0),r.push(a)}return{dynamic:n,encoded:n?To(r):je(...r.map(o=>o.encoded))}}function Ss(l){let e=l.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function Ps(l,e){if(l.length!==e.length)throw new Error(`Expected ${l.length} values, got ${e.length}`);if(l.length===0)return"0x";let t=l.map((r,o)=>vo(r,e[o])),n=To(t);return tr(n)}function at({abi:l,functionName:e,args:t=[]}){let n=l.find(a=>(a.type==="function"||a.type===void 0)&&a.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=vs(n),o=bs(nr(r)).slice(0,4),s=n.inputs??[],i=s.length===0||t.length===0?new Uint8Array(0):vn(Ps(s,t).slice(2));return tr(je(o,i))}var xs="https://wallet-api.pantograph.app",_s="0x0000000000000000000000000000000000000000",lr={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},cr={"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 An(l){return lr[l.toLowerCase()]||l}function ir(l){let e=[];for(let[t,n]of Object.entries(l))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 Ao(l){let e=l,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 te(l){if(l==null)return null;let e=typeof l=="number"?l:parseFloat(String(l));return Number.isFinite(e)?e:null}function ar(l,e){let t=l.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=te(l.price_change_percentage_24h)??te(l.priceChange24h)??te(l.usd_price_24hr_percent_change)??te(l.price_change_24h)??te(l.priceChange);return{chainId:e,tokenAddress:l.address??l.token_address??"",name:l.name??null,symbol:l.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:l.logoURI??l.icon_image??l.logo??null,usdPrice:te(l.price)??te(l.usd_price),marketCap:te(l.market_cap)??te(l.marketCap),totalVolume:{"24h":te(l.total_volume)??te(l.volume24h)},pricePercentChange:{"24h":r}}}var ne=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??xs).replace(/\/+$/,"")}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=An(t),r=e.map(u=>u.token_address).join(","),o=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(r)}`,s=await P.get(o);if(!s.ok)return;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Map;for(let u of a)u.address&&c.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=c.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=An(t),r=`${this.baseUrl}/keyrings/tokens/${n}/v2?addresses=${encodeURIComponent(e)}`,o=await P.get(r);if(!o.ok)return null;let s=o.data,i=Array.isArray(s)?s:Array.isArray(s.data)?s.data:[],a=e.toLowerCase()===_s,c=i.find(u=>u.address?.toLowerCase()===e.toLowerCase()||a&&u.address===""||u.token_address?.toLowerCase()===e.toLowerCase()||a&&u.token_address==="");return c?Ao(c):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=An(t),o=`${this.baseUrl}/keyrings/tokens/${r}/v2?addresses=${encodeURIComponent(e.join(","))}`,s=await P.get(o);if(!s.ok)return n;let i=s.data,a=Array.isArray(i)?i:Array.isArray(i.data)?i.data:[],c=new Set(e.map(u=>u.toLowerCase()));for(let u of a){let d=u.address?.toLowerCase()||u.token_address?.toLowerCase()||(u.address===""?"":null);d&&c.has(d)&&(n[d]=Ao(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||Se,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let s=ir({chainId:o,key:t}),i=`${this.baseUrl}/token-list?${s}`,a=await P.get(i);if(!a.ok)throw new Error(L(a));let c=a.data,u=[];return c?.data?u=Array.isArray(c.data)?c.data:Object.values(c.data).flat():typeof c=="object"&&!Array.isArray(c)&&(u=Object.values(c).flat()),{success:!0,data:u.map(Ao)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Se,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=cr[t.toLowerCase()]??[],s=r!=null?r+o.length:n+o.length,[i,a]=await Promise.allSettled([this.fetchTopGainers(t,s),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=a.status==="fulfilled"?o.map(h=>a.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>ar(h,t)):[],d=new Set,p=[];for(let h of u){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(h))}let m=[];for(let h of c){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(h))}let g=r!=null?[...p,...m].slice(0,r):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,t),{success:!0,data:g}}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=te(s.market_cap)??te(s.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":te(s.total_volume)??te(s.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=An(e),o=ir({duration:n,limit:t}),s=`${this.baseUrl}/token-list/top-gainers/${r}${o?`?${o}`:""}`,i=[];for(let a=0;a<5;a++){let c=await P.get(s);if(!c.ok)throw new Error(L(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;a<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(a=>ar(a,e))}async getTopGainers(e){let t=e?.chain||Se,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 Cs="https://nft.keyring.app",Es="https://nft.keyring.app",Rs=.01,R=5,W=1e3,Ns="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Us="0x0000000000000000000000000000000000000000",N=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function Y(l){return l||Se}function H(l){let e=[];for(let[t,n]of Object.entries(l))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 G(l){return new Promise(e=>setTimeout(e,l))}function Is(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;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 So(l){if(Array.isArray(l))return l;if(l&&typeof l=="object"){let e=l;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 D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Cs).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Es).replace(/\/+$/,""),this.pantograph=new ne({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 i=Y(n),a="Unknown error";for(let c=1;c<=R;c++)try{let u={chain:i,exclude_spam:o,exclude_unverified_contracts:s,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let g=H(u),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${g}`,f=await P.get(h);if(!f.ok)throw new N(f.status,L(f));let y=f.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Ns?Us:g.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Rs)),{success:!0,data:m}}catch(u){if(a=u instanceof Error?u.message:"Unknown error",u instanceof N&&u.status===400)break;c<R&&await G(W)}return{success:!1,error:a}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=Y(n),o="Unknown error",s=await this.pantograph.getTokenMetadata(t,r);if(s)return{success:!0,data:s};for(let i=1;i<=R;i++)try{let[a,c]=await Promise.allSettled([P.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${H({chain:r,addresses:[t]})}`),P.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${H({chain:r,include:"percent_change"})}`)]),u=null;if(a.status==="fulfilled"&&a.value.ok){let p=a.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<R&&await G(W);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}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(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=10,excludeSpam:o=!0,cursor:s,tokenAddresses:i,includePrices:a,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=Y(n),d="Unknown error";for(let p=1;p<=R;p++)try{let m={chain:u,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};s&&(m.cursor=s),a&&(m.include_prices=!0),i&&i.length>0&&(m.token_addresses=i);let g=H(m),h=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${g}`,f=await P.get(h);if(!f.ok)throw new N(f.status,L(f));let y=f.data;return{success:!0,data:y?.data??y}}catch(m){if(d=m instanceof Error?m.message:"Unknown error",m instanceof N&&m.status===400)break;p<R&&await G(W)}return{success:!1,error:d}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:s=!0,mediaItems:i=!0,include:a}=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(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=Y(r),u="Unknown error";for(let d=1;d<=R;d++)try{let p={chain:c,format:o,normalizeMetadata:s,media_items:i};a&&(p.include=a);let m=H(p),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await P.get(g);if(!h.ok)throw new N(h.status,L(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof N&&p.status===400)break;d<R&&await G(W)}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=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:s,fromBlock:i,toBlock:a,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=Y(n),g=Math.max(1,Math.min(100,Math.floor(r))),h="Unknown error";for(let f=1;f<=R;f++)try{let y={chain:m,limit:g,order:u};o&&(y.from_date=o),s&&(y.to_date=s),i!=null&&(y.from_block=i),a!=null&&(y.to_block=a),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=H(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,v=await P.get(w);if(!v.ok)throw new N(v.status,L(v));let k=v.data;return{success:!0,data:k?.data??k}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof N&&y.status===400)break;f<R&&await G(W)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=Y(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let h=1;h<=R;h++)try{let f={chain:p,limit:m,order:d};s&&(f.from_date=s),i&&(f.to_date=i),a!=null&&(f.from_block=a),c!=null&&(f.to_block=c),u&&(f.cursor=u),r?.length&&(f.contract_addresses=r);let y=H(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await P.get(b);if(!w.ok)throw new N(w.status,L(w));let v=w.data;return{success:!0,data:v?.data??v}}catch(f){if(g=f instanceof Error?f.message:"Unknown error",f instanceof N&&f.status===400)break;h<R&&await G(W)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:s,toDate:i,fromBlock:a,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=Y(n),h=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let y=1;y<=R;y++)try{let b={chain:g,limit:h,order:d,format:m};s&&(b.from_date=s),i&&(b.to_date=i),a!=null&&(b.from_block=a),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=H(b),v=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,k=await P.get(v);if(!k.ok)throw new N(k.status,L(k));let A=k.data;return{success:!0,data:A?.data??A}}catch(b){if(f=b instanceof Error?b.message:"Unknown error",b instanceof N&&b.status===400)break;y<R&&await G(W)}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(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=Y(n),s="Unknown error";for(let i=1;i<=R;i++)try{let a={chain:o};r&&(a.days=r);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;a<R&&await G(W)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let s=Y(n),i="Unknown error";for(let a=1;a<=R;a++)try{let c={chain:s};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=H(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await P.get(d);if(!p.ok)throw new N(p.status,L(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof N&&c.status===400)break;a<R&&await G(W)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chains:r}),a=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:Is(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}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(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=Y(r),s="Unknown error";for(let i=1;i<=R;i++)try{let a=H({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${a}`,u=await P.get(c);if(!u.ok)throw new N(u.status,L(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.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(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}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(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}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(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=Y(n),o="Unknown error";for(let s=1;s<=R;s++)try{let i=H({chain:r}),a=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof N&&i.status===400)break;s<R&&await G(W)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=R;o++)try{let s={};t&&(s.chain=Y(t)),n!=null&&(s.limit=n);let i=H(s),a=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await P.get(a);if(!c.ok)throw new N(c.status,L(c));let u=c.data,d=u?.data??u;return{success:!0,data:So(d)}}catch(s){if(r=s instanceof Error?s.message:"Unknown error",s instanceof N&&s.status===400)break;o<R&&await G(W)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:So(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},s="Unknown error";for(let i=1;i<=R;i++)try{let a={};t&&(a.chain=Y(t)),n&&(a.time_frame=n),r!=null&&(a.min_market_cap=r),o!=null&&(a.security_score=o);let c=H(a),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await P.get(u);if(!d.ok)throw new N(d.status,L(d));let p=d.data,m=p?.data??p;return{success:!0,data:So(m)}}catch(a){if(s=a instanceof Error?a.message:"Unknown error",a instanceof N&&a.status===400)break;i<R&&await G(W)}return{success:!1,error:s}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var lt=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 \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. 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 with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,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 D(e),this.llm=new J({})}async run(e,t){let n=e.keyword||"",r=M(e.chain,t),o=e.prompt||"",s=e.buy_button_label||"",i=e.buy_prompt_template||"",a=t?.walletAddress||void 0;return n?await this.searchToken(n,r,o,s,i,a):{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 i=[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
  `),[a,c,u]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),s?this.findTokenInWallet(s,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,i):Promise.resolve(null)]),d=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],p=e.toLowerCase(),m=v=>v.symbol?.toLowerCase()===p||v.token_address?.toLowerCase()===p,g=[...d].sort((v,k)=>(m(v)?0:1)-(m(k)?0:1)),h=null,f=g[0];if(f?.token_address){let v=await this.service.getTokenMetadata({address:f.token_address,chain:t});v.success&&v.data&&(h=v.data)}!h&&f&&(h={...f});let y=h?.symbol?.trim(),b=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. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). 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:!!c,walletBalance:c,token:h,...d.length>1?{searchResults:g.slice(0,10)}:{},research:u,...b.length>0?{actionButtons:b}:{}}}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(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return s||null}};var ct=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 D(e)}async run(e,t){let n=M(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 i,a;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?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=d.name}let c=await this.service.getTokenHolders({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??o??null,name:a??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 i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var ut=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 D(e)}async run(e,t){let n=M(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 i,a;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?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=d.address,i=d.symbol,a=d.name}let c=await this.service.getTokenAnalytics({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??o??null,name:a??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 i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var dt=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 D(e)}async run(e,t){let n=M(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 i,a;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?E(n):"the selected chain"}. Try passing contractAddress directly.`};s=p.address,i=p.symbol,a=p.name}let c=await this.service.getTokenScore({address:s,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??o??null,name:a??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 i=s.data.result.find(a=>(a.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(a=>(a.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var pt=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 ne({baseUrl:e?.pantographUrl})}async run(e,t){let n=Gn(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,i=await this.service.getTrendingTokens({chain:n,limit:s});if(!i.success)return{error:i.error||"Failed to fetch trending tokens"};let a=i.data??[],c=new Set,u=[];for(let d of a){let p=d.symbol?.trim();!p||c.has(p.toLowerCase())||(c.add(p.toLowerCase()),u.push({label:this.fillTemplate(r,p,"Buy {token}"),prompt:this.fillTemplate(o,p,"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>)
@@ -278,12 +278,14 @@ User query: ${e}`,timestamp:Date.now()}],m=Date.now(),g=null,h="",f=null;for(let
278
278
  [Router] (${y}ms)`),console.log(` analysis : ${g.analysis??""}`),console.log(` dispatch : ${v}`),w.length>0)for(let k of w)console.log(` \u2192 ${k.subagent}: "${k.query}"`),console.log(` reason: ${k.reasoning}`)}return{analysis:typeof g.analysis=="string"?g.analysis:"",assignments:w}}async dispatch(e,t,n,r){if(e.assignments.length===0)return[];this.debug&&console.log(`
279
279
  [Router] dispatching ${e.assignments.length} subagent(s) in parallel\u2026`);let o=Date.now(),s=e.assignments.map(async a=>{let c=t.get(a.subagent);if(!c)return this.debug&&console.log(`[Router] WARN: subagent "${a.subagent}" not registered`),{subagentName:a.subagent,steps:[],finalAnswer:`Subagent "${a.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let u=Date.now(),d=await c.run({query:a.query,reasoning:a.reasoning},n,r);if(this.debug){let p=d.toolResults.map(m=>m.toolName).join(", ")||"\u2014";console.log(`[Router] ${a.subagent} done in ${Date.now()-u}ms | tools: ${p}`)}return d}),i=await Promise.all(s);return this.debug&&console.log(`[Router] all subagents done in ${Date.now()-o}ms total`),i}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,"").trim());try{return JSON.parse(t)}catch(n){let r=t.match(/\{[\s\S]*\}/);if(r)return JSON.parse(r[0]);throw n}}};var aa=`
280
280
 
281
- LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chinese, Thai, Spanish, Arabic, \u2026). Every intent\u2192tool mapping, verb, and example phrase in this prompt is ILLUSTRATIVE ONLY \u2014 written mostly in English for brevity, NOT a list of accepted words. Always pick the tool by the MEANING of the request, treating translated, transliterated, or mixed-language equivalents exactly like the English example (buy / send / swap / approve / show / search / trending / balance, etc. are the same intent in every language). Token symbols, contract addresses, and numbers are language-neutral \u2014 extract them verbatim. Never refuse, misroute, or fall back to plain text merely because the wording is not in English.`,j=class{name;description;domain;capability;toolNames;systemPrompt;cortexFallbackTool;mustCallTool;llm;registry;maxToolCalls;historyMessages;debug;constructor(e){if(this.name=e.name,this.description=e.description,this.domain=e.domain,this.capability=e.capability,this.toolNames=new Set(e.toolNames),this.systemPrompt=e.systemPrompt+aa,this.cortexFallbackTool=e.cortexFallbackTool,this.mustCallTool=e.mustCallTool??!1,this.cortexFallbackTool&&!this.toolNames.has(this.cortexFallbackTool))throw new Error(`Subagent "${e.name}": cortexFallbackTool "${this.cortexFallbackTool}" must be in toolNames.`);this.llm=e.llm,this.registry=e.registry,this.maxToolCalls=e.options?.maxToolCalls??5,this.historyMessages=e.options?.historyMessages??10,this.debug=e.options?.debug??!1}getCard(){return{name:this.name,description:this.description,domain:this.domain}}getTools(){return this.registry.getDefinitions().filter(e=>this.toolNames.has(e.name))}async run(e,t,n){let r=this.getTools();if(this.debug&&(console.log(`
281
+ LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (English, Vietnamese, Japanese, Korean, Chinese, Thai, Spanish, Arabic, \u2026). Every intent\u2192tool mapping, verb, and example phrase in this prompt is ILLUSTRATIVE ONLY \u2014 written mostly in English for brevity, NOT a list of accepted words. Always pick the tool by the MEANING of the request, treating translated, transliterated, or mixed-language equivalents exactly like the English example (buy / send / swap / approve / show / search / trending / balance, etc. are the same intent in every language). Token symbols, contract addresses, and numbers are language-neutral \u2014 extract them verbatim. Never refuse, misroute, or fall back to plain text merely because the wording is not in English.`,la=`
282
+
283
+ OUTPUT FORMAT: Reply in plain text. NEVER draw tables or any column/pipe layout. When presenting multiple items, use a simple bullet or numbered list; otherwise just write short sentences.`,j=class{name;description;domain;capability;toolNames;systemPrompt;cortexFallbackTool;mustCallTool;llm;registry;maxToolCalls;historyMessages;debug;constructor(e){if(this.name=e.name,this.description=e.description,this.domain=e.domain,this.capability=e.capability,this.toolNames=new Set(e.toolNames),this.systemPrompt=e.systemPrompt+aa+la,this.cortexFallbackTool=e.cortexFallbackTool,this.mustCallTool=e.mustCallTool??!1,this.cortexFallbackTool&&!this.toolNames.has(this.cortexFallbackTool))throw new Error(`Subagent "${e.name}": cortexFallbackTool "${this.cortexFallbackTool}" must be in toolNames.`);this.llm=e.llm,this.registry=e.registry,this.maxToolCalls=e.options?.maxToolCalls??5,this.historyMessages=e.options?.historyMessages??10,this.debug=e.options?.debug??!1}getCard(){return{name:this.name,description:this.description,domain:this.domain}}getTools(){return this.registry.getDefinitions().filter(e=>this.toolNames.has(e.name))}async run(e,t,n){let r=this.getTools();if(this.debug&&(console.log(`
282
284
  [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${r.map(k=>k.name).join(", ")}`)),r.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let o=[],s=[],i=[],a=new Set,c=0,u=!1,d=[];if(n?.walletAddress&&d.push(`Connected wallet: ${n.walletAddress}`),n?.chain){let k=E(n.chain),A=Jo(n.chain),x=A?`; native coin: ${A}`:"";d.push(`Current chain: ${k} (${n.chain})${x}`)}let p=d.length>0?`User context:
283
285
  ${d.join(`
284
286
  `)}`:"",m=e.language?`The user's current language is "${e.language}" (BCP-47). Write every user-facing string you produce \u2014 replies AND any localized tool arguments \u2014 in this language.`:"",g=[p,m,`Routed query: ${e.query}`,e.reasoning?`Router reasoning: ${e.reasoning}`:"","Use only the tools you own. If you already have enough information, respond directly in the user's language."].filter(Boolean).join(`
285
287
 
286
- `),h=Or(t,this.toolNames),f=Le(h,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...f,{role:"user",content:g,timestamp:Date.now()}],b=6e3,w=this.maxToolCalls+2;for(let k=0;k<w;k++){let A=c<this.maxToolCalls,x=A?r:void 0,S=A&&this.mustCallTool&&c===0,O=await this.llm.chat(y,x,S?{forceToolUse:!0}:void 0);if(O.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&A){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),y.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; chain = the connected chain, else Ethereum) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&A&&!u){u=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),y.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${O.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:O.text,toolResults:s,toolMessages:i}}let C={role:"assistant",content:O.text||"",toolCalls:O.toolCalls,timestamp:Date.now()};y.push(C);let B=[];for(let _ of O.toolCalls){if(!this.toolNames.has(_.toolName)){let re=`Tool "${_.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${re}`),o.push({phase:"observe",content:re,timestamp:Date.now()}),y.push({role:"tool",content:re,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}let U=`${_.toolName}::${JSON.stringify(_.args)}`;if(a.has(U)){let re=`Skipped duplicate call: ${_.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${_.toolName}`),o.push({phase:"observe",content:re,timestamp:Date.now()}),y.push({role:"tool",content:re,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}a.add(U),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${_.toolName} ${JSON.stringify(_.args)}`),o.push({phase:"think",content:O.text||`Calling ${_.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${_.toolName}`,toolCall:{toolName:_.toolName,args:_.args},timestamp:Date.now()});let Te=Date.now(),De={...n,query:e.query},V=await this.registry.execute(_.toolName,_.args,De);s.push(V);let oe=V.success?JSON.stringify(V.data):`Error: ${V.error}`;if(this.debug){let re=V.success?"OK":"ERR",Ae=V.success?`${oe.slice(0,120)}${oe.length>120?"\u2026":""}`:V.error;console.log(` [${this.name}] ${re} (${Date.now()-Te}ms): ${Ae}`)}o.push({phase:"observe",content:oe,toolResult:V,timestamp:Date.now()});let Ne={role:"tool",content:oe,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()};y.push(Ne),B.push({...Ne,content:oe.length>b?oe.slice(0,b)+"\u2026[truncated]":oe})}B.length>0&&(i.push(C),i.push(...B))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),y.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let v=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:v.text,toolResults:s,toolMessages:i}}};var la=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
288
+ `),h=Or(t,this.toolNames),f=Le(h,this.historyMessages),y=[{role:"system",content:this.systemPrompt,timestamp:0},...f,{role:"user",content:g,timestamp:Date.now()}],b=6e3,w=this.maxToolCalls+2;for(let k=0;k<w;k++){let A=c<this.maxToolCalls,x=A?r:void 0,S=A&&this.mustCallTool&&c===0,O=await this.llm.chat(y,x,S?{forceToolUse:!0}:void 0);if(O.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&A){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),y.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; chain = the connected chain, else Ethereum) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&A&&!u){u=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),y.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${O.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:o,finalAnswer:O.text,toolResults:s,toolMessages:i}}let C={role:"assistant",content:O.text||"",toolCalls:O.toolCalls,timestamp:Date.now()};y.push(C);let B=[];for(let _ of O.toolCalls){if(!this.toolNames.has(_.toolName)){let re=`Tool "${_.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${re}`),o.push({phase:"observe",content:re,timestamp:Date.now()}),y.push({role:"tool",content:re,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}let U=`${_.toolName}::${JSON.stringify(_.args)}`;if(a.has(U)){let re=`Skipped duplicate call: ${_.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${_.toolName}`),o.push({phase:"observe",content:re,timestamp:Date.now()}),y.push({role:"tool",content:re,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()});continue}a.add(U),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${_.toolName} ${JSON.stringify(_.args)}`),o.push({phase:"think",content:O.text||`Calling ${_.toolName}`,timestamp:Date.now()}),o.push({phase:"act",content:`Calling tool: ${_.toolName}`,toolCall:{toolName:_.toolName,args:_.args},timestamp:Date.now()});let Te=Date.now(),De={...n,query:e.query},V=await this.registry.execute(_.toolName,_.args,De);s.push(V);let oe=V.success?JSON.stringify(V.data):`Error: ${V.error}`;if(this.debug){let re=V.success?"OK":"ERR",Ae=V.success?`${oe.slice(0,120)}${oe.length>120?"\u2026":""}`:V.error;console.log(` [${this.name}] ${re} (${Date.now()-Te}ms): ${Ae}`)}o.push({phase:"observe",content:oe,toolResult:V,timestamp:Date.now()});let Ne={role:"tool",content:oe,toolName:_.toolName,toolCallId:_.callId,timestamp:Date.now()};y.push(Ne),B.push({...Ne,content:oe.length>b?oe.slice(0,b)+"\u2026[truncated]":oe})}B.length>0&&(i.push(C),i.push(...B))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),y.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let v=await this.llm.chat(y);return{subagentName:this.name,steps:o,finalAnswer:v.text,toolResults:s,toolMessages:i}}};var ca=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
287
289
 
288
290
  SPECIALISED TOOLS (prefer these when intent matches):
289
291
  - get-wallet-token-balances: token + native coin balances
@@ -333,7 +335,7 @@ PAGINATION:
333
335
  pass the cursor from the LAST history response in conversation. Always tell the user
334
336
  how many results were returned and whether more pages exist.
335
337
 
336
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,ao=["get-wallet-token-balances","get-wallet-history","get-wallet-token-transfers","get-wallet-nft-transfers","get-wallet-pnl-summary","get-wallet-pnl","get-wallet-approvals","get-wallet-defi-summary","get-wallet-defi-positions","get-wallet-defi-protocol-positions","get-transaction-by-hash","gemini-search-ai"];function Nn(l,e,t){return new j({name:"wallet-agent",domain:"wallet",capability:"check a wallet's token balances, portfolio, transaction history, PnL, DeFi positions and token approvals",description:["Wallet-scoped on-chain state. Specialised tools cover balances, net worth, transaction history,","single-tx lookup, ERC-20 / NFT transfers, PnL, DeFi positions, and approvals.","Owns READ-ONLY queries about a WALLET'S OWN DeFi/LP/staking/lending positions \u2014 both across all protocols",'AND within a specific NAMED protocol: "my positions", "my LP positions", "my position on Uniswap",','"my Uniswap positions", "what I have on Aave", "my Lido staking", "my Pendle positions". The "my/their"',"(or connected-wallet) framing makes it wallet-scoped \u2014 route it here even when a protocol like Uniswap is named.","This is VIEWING only. An explicit request to ACT on an LP position \u2014 close / remove / withdraw the pair, or",'collect / claim earned fees ("close my pool", "remove liquidity", "collect my fees", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2014 is NOT in scope (\u2192 pool-agent).',"For wallet queries without a direct tool , this agent falls","back to a search-grounded Gemini model internally \u2014 it never refuses a wallet-scoped query","and always calls a tool.","NOT in scope: market-wide token data (\u2192 token-agent), NFT current holdings (\u2192 nft-agent),","pool analytics or a position looked up by its NUMERIC NFT id with no wallet (\u2192 pool-subgraph/pool-agent)."].join(" "),toolNames:[...ao],systemPrompt:la,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ca=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
338
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,ao=["get-wallet-token-balances","get-wallet-history","get-wallet-token-transfers","get-wallet-nft-transfers","get-wallet-pnl-summary","get-wallet-pnl","get-wallet-approvals","get-wallet-defi-summary","get-wallet-defi-positions","get-wallet-defi-protocol-positions","get-transaction-by-hash","gemini-search-ai"];function Nn(l,e,t){return new j({name:"wallet-agent",domain:"wallet",capability:"check a wallet's token balances, portfolio, transaction history, PnL, DeFi positions and token approvals",description:["Wallet-scoped on-chain state. Specialised tools cover balances, net worth, transaction history,","single-tx lookup, ERC-20 / NFT transfers, PnL, DeFi positions, and approvals.","Owns READ-ONLY queries about a WALLET'S OWN DeFi/LP/staking/lending positions \u2014 both across all protocols",'AND within a specific NAMED protocol: "my positions", "my LP positions", "my position on Uniswap",','"my Uniswap positions", "what I have on Aave", "my Lido staking", "my Pendle positions". The "my/their"',"(or connected-wallet) framing makes it wallet-scoped \u2014 route it here even when a protocol like Uniswap is named.","This is VIEWING only. An explicit request to ACT on an LP position \u2014 close / remove / withdraw the pair, or",'collect / claim earned fees ("close my pool", "remove liquidity", "collect my fees", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n") \u2014 is NOT in scope (\u2192 pool-agent).',"For wallet queries without a direct tool , this agent falls","back to a search-grounded Gemini model internally \u2014 it never refuses a wallet-scoped query","and always calls a tool.","NOT in scope: market-wide token data (\u2192 token-agent), NFT current holdings (\u2192 nft-agent),","pool analytics or a position looked up by its NUMERIC NFT id with no wallet (\u2192 pool-subgraph/pool-agent)."].join(" "),toolNames:[...ao],systemPrompt:ca,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ua=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
337
339
 
338
340
  SPECIALISED TOOLS (prefer these when intent matches):
339
341
  - get-token-info: metadata (name, symbol, decimals, address, logo)
@@ -374,7 +376,7 @@ GENERAL RULES:
374
376
  - Never repeat a tool call with identical arguments.
375
377
  - Answer in the user's language. Do not mention tool names.
376
378
 
377
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea. `,lo=["get-token-info","get-token-holders","get-token-analytics","get-token-score","get-trending-tokens","get-top-gainers","gemini-search-ai"];function Un(l,e,t){return new j({name:"token-agent",domain:"token",capability:"look up token info, prices, analytics, holders, trending tokens and top gainers",description:["Market data for a SPECIFIC named token (by symbol or address): metadata, price, holders, analytics,","and risk score \u2014 plus market-wide RANKINGS: trending tokens and top gainers. For a token question","without a direct structured tool, this agent falls back to a search-grounded Gemini model internally \u2014","it never refuses a single-token query and always calls a tool.","NOT in scope: wallet balances or transfer history (\u2192 wallet-agent), NFT data (\u2192 nft-agent),",'broad CATEGORY / THEME discovery lists \u2014 "meme tokens", "AI tokens", "gaming / L2 / RWA tokens" (\u2192 ai-agent).'].join(" "),toolNames:[...lo],systemPrompt:ca,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ua=`You are the NFT domain expert. You answer questions about NFT holdings and metadata, not transfer history.
379
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea. `,lo=["get-token-info","get-token-holders","get-token-analytics","get-token-score","get-trending-tokens","get-top-gainers","gemini-search-ai"];function Un(l,e,t){return new j({name:"token-agent",domain:"token",capability:"look up token info, prices, analytics, holders, trending tokens and top gainers",description:["Market data for a SPECIFIC named token (by symbol or address): metadata, price, holders, analytics,","and risk score \u2014 plus market-wide RANKINGS: trending tokens and top gainers. For a token question","without a direct structured tool, this agent falls back to a search-grounded Gemini model internally \u2014","it never refuses a single-token query and always calls a tool.","NOT in scope: wallet balances or transfer history (\u2192 wallet-agent), NFT data (\u2192 nft-agent),",'broad CATEGORY / THEME discovery lists \u2014 "meme tokens", "AI tokens", "gaming / L2 / RWA tokens" (\u2192 ai-agent).'].join(" "),toolNames:[...lo],systemPrompt:ua,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var da=`You are the NFT domain expert. You answer questions about NFT holdings and metadata, not transfer history.
378
380
 
379
381
  SPECIALISED TOOLS (prefer these when intent matches):
380
382
  - get-wallet-nfts: user wants to view / browse their OWN NFTs / holdings \u2014 returns a fixed website notice
@@ -421,7 +423,7 @@ GENERAL RULES:
421
423
  - get-wallet-nfts takes no arguments; get-nft-metadata / get-nft-contract-info take only a \`prompt\` (no chain) \u2014 never pass chain to any tool.
422
424
  - For a specific NFT, use get-nft-metadata and build a prompt embedding its contract address + token id.
423
425
  - One tool per turn. Never repeat a tool call with identical arguments.
424
- - Answer in the user's language. Do not mention tool names.`,co=["get-wallet-nfts","get-nft-metadata","get-nft-contract-info","gemini-search-ai"];function In(l,e,t){return new j({name:"nft-agent",domain:"nft",capability:"look up NFT holdings, metadata and collection info",description:["Read-only NFT lookups: holdings, single-NFT metadata, and collection / contract info.","For NFT category, theme, or market-wide questions without a direct tool, this agent falls back to a","search-grounded Gemini model internally \u2014 it never refuses an NFT query and always calls a tool.","NOT in scope: SENDING / transferring an NFT (the action \u2192 wallet-action-agent);","past NFT transfer history / events (\u2192 wallet-agent)."].join(" "),toolNames:[...co],systemPrompt:ua,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var da=`You are the Crypto AI fallback expert powered by a search-grounded Gemini model.
426
+ - Answer in the user's language. Do not mention tool names.`,co=["get-wallet-nfts","get-nft-metadata","get-nft-contract-info","gemini-search-ai"];function In(l,e,t){return new j({name:"nft-agent",domain:"nft",capability:"look up NFT holdings, metadata and collection info",description:["Read-only NFT lookups: holdings, single-NFT metadata, and collection / contract info.","For NFT category, theme, or market-wide questions without a direct tool, this agent falls back to a","search-grounded Gemini model internally \u2014 it never refuses an NFT query and always calls a tool.","NOT in scope: SENDING / transferring an NFT (the action \u2192 wallet-action-agent);","past NFT transfer history / events (\u2192 wallet-agent)."].join(" "),toolNames:[...co],systemPrompt:da,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var pa=`You are the Crypto AI fallback expert powered by a search-grounded Gemini model.
425
427
 
426
428
  You answer ANY blockchain / crypto / token / NFT / DeFi / on-chain question that does not have a
427
429
  direct structured tool in the other agents. The underlying model has live web-search grounding \u2014
@@ -440,7 +442,7 @@ ROUTING:
440
442
  RULES:
441
443
  - ALWAYS call the tool \u2014 NEVER refuse, NEVER answer without calling it.
442
444
  - NEVER retry with the same prompt if the call fails \u2014 return what you have.
443
- - Answer in the user's language. Do NOT mention tool names.`,uo=["gemini-search-ai"];function Ln(l,e,t){return new j({name:"ai-agent",domain:"ai",capability:"answer general crypto, blockchain and DeFi questions, using up-to-date web search when needed",description:["Catch-all crypto / blockchain expert powered by a search-grounded Gemini model (live Google","Search). USE THIS AGENT whenever the query is about blockchain, crypto, tokens, NFTs, DeFi,","wallets, on-chain data, smart contracts, or any supported EVM chain BUT no other agent","(wallet-agent, token-agent, nft-agent, pool-agent) has a direct structured tool for it.","Scope examples: (1) token categories or themes \u2014 meme tokens, AI tokens, gaming tokens, L2 tokens, RWA;",'(2) protocol-specific questions \u2014 "how does X protocol work", "what happened to Y";',"(3) cross-contract or exploratory EVM analysis spanning many contracts;","(4) any open-ended on-chain question without a direct structured tool.","Prefer the specific agents when they clearly match (wallet balances \u2192 wallet-agent,","single-token info/analytics \u2192 token-agent, NFT holdings/metadata \u2192 nft-agent, DEX pools \u2192 pool-agent).","But for anything crypto-related that falls outside those, route HERE \u2014 do not return empty."].join(" "),toolNames:[...uo],systemPrompt:da,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var pa=`You are the Pool / DEX Liquidity domain expert.
445
+ - Answer in the user's language. Do NOT mention tool names.`,uo=["gemini-search-ai"];function Ln(l,e,t){return new j({name:"ai-agent",domain:"ai",capability:"answer general crypto, blockchain and DeFi questions, using up-to-date web search when needed",description:["Catch-all crypto / blockchain expert powered by a search-grounded Gemini model (live Google","Search). USE THIS AGENT whenever the query is about blockchain, crypto, tokens, NFTs, DeFi,","wallets, on-chain data, smart contracts, or any supported EVM chain BUT no other agent","(wallet-agent, token-agent, nft-agent, pool-agent) has a direct structured tool for it.","Scope examples: (1) token categories or themes \u2014 meme tokens, AI tokens, gaming tokens, L2 tokens, RWA;",'(2) protocol-specific questions \u2014 "how does X protocol work", "what happened to Y";',"(3) cross-contract or exploratory EVM analysis spanning many contracts;","(4) any open-ended on-chain question without a direct structured tool.","Prefer the specific agents when they clearly match (wallet balances \u2192 wallet-agent,","single-token info/analytics \u2192 token-agent, NFT holdings/metadata \u2192 nft-agent, DEX pools \u2192 pool-agent).","But for anything crypto-related that falls outside those, route HERE \u2014 do not return empty."].join(" "),toolNames:[...uo],systemPrompt:pa,cortexFallbackTool:"gemini-search-ai",llm:l,registry:e,options:t})}var ma=`You are the Pool / DEX Liquidity domain expert.
444
446
 
445
447
  You answer questions about decentralized exchange liquidity pools \u2014 specifically Uniswap V2/V3/V4 pools across EVM chains \u2014 AND you guide the user through providing liquidity to a pool.
446
448
 
@@ -608,7 +610,7 @@ State awareness:
608
610
 
609
611
  Never fabricate pool addresses, tick numbers, prices, or NFT ids. Every value must come from a tool call this turn or the immediately preceding turn.
610
612
 
611
- Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,po=["get-top-pools","get-pool-detail","search-pools","lookup-pool-by-address","open-add-liquidity-form","preview-add-liquidity","estimate-pool-yield","get-pool-price-ranges","manage-liquidity-redirect","pool-fallback-ai"];function Dn(l,e,t){return new j({name:"pool-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or transaction count;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/1w/30d), tx count, both tokens;","(4) pool detail by token pair (and optional fee tier) \u2014 full stats for a single pool including TVL, 24h volume, fees, APR estimate, token reserves, and weekly volume history;","(5) pool search \u2014 find pools that match a free-text query (token symbol, token name, or pool address) on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token, resolve both;",'(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool ("if I put $1000 into USDC/WETH 0.05%, how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?");',"(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction once the user confirms amount and price range.","(9) MANAGE / ACT ON AN EXISTING POSITION \u2014 closing / removing / withdrawing the pair OR collecting / claiming earned fees on the user's OWN position",'("close my pool", "close my position", "remove liquidity", "withdraw liquidity", "collect my fees", "claim earnings", "\u0111\xF3ng pool", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "thu ph\xED") \u2014 handled HERE (returns the CoinPool management link).',`NOT in scope: VIEWING a wallet's OWN LP / DeFi position DATA \u2014 "my positions", "my position on Uniswap", "my Uniswap positions",`,'"what I have on Aave", any read-only "my/their positions" query (with or without a protocol named) (\u2192 wallet-agent).',`IMPORTANT distinction: VIEWING / listing one's own positions \u2192 wallet-agent; ACTING on one (close / remove / withdraw / collect fees) \u2192 pool-agent (here), even when phrased as "my pool" / "my position".`,"token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).",'Key distinction from token-agent: pool-agent answers "which POOLS are biggest / most active" and handles "I want to add LP",','while token-agent answers "what is this TOKEN" and "what is the market doing for this TOKEN".'].join(" "),toolNames:[...po],systemPrompt:pa,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var ma=`You are the Uniswap V3 Subgraph DEX-pool expert.
613
+ Chain ids: 0x1 Ethereum \xB7 0xa Optimism \xB7 0x38 BSC \xB7 0x89 Polygon \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum \xB7 0xa86a Avalanche \xB7 0xe708 Linea .`,po=["get-top-pools","get-pool-detail","search-pools","lookup-pool-by-address","open-add-liquidity-form","preview-add-liquidity","estimate-pool-yield","get-pool-price-ranges","manage-liquidity-redirect","pool-fallback-ai"];function Dn(l,e,t){return new j({name:"pool-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Handles questions about decentralized exchange liquidity pools \u2014 Uniswap V2/V3/V4 across EVM chains \u2014","AND walks the user through ADDING LIQUIDITY to a pool (provide LP / farm / stake / deposit / cung c\u1EA5p thanh kho\u1EA3n).","Scope: (1) top pools by chain \u2014 biggest pools ranked by TVL, volume, or transaction count;","(2) pool composition \u2014 which token pairs dominate liquidity on a given network;","(3) pool-level analytics \u2014 fee tier, rolling volume buckets (1d/1w/30d), tx count, both tokens;","(4) pool detail by token pair (and optional fee tier) \u2014 full stats for a single pool including TVL, 24h volume, fees, APR estimate, token reserves, and weekly volume history;","(5) pool search \u2014 find pools that match a free-text query (token symbol, token name, or pool address) on a given chain;","(6) single-address lookup \u2014 when the user pastes one 0x address without saying whether it is a pool or a token, resolve both;",'(7) YIELD ESTIMATION \u2014 estimate daily/weekly/monthly/yearly fee income for a given USD deposit into a specific pool ("if I put $1000 into USDC/WETH 0.05%, how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?");',"(8) ADD LIQUIDITY \u2014 open the AddLiquidityForm UI for a chosen pool, then build the unsigned mint transaction once the user confirms amount and price range.","(9) MANAGE / ACT ON AN EXISTING POSITION \u2014 closing / removing / withdrawing the pair OR collecting / claiming earned fees on the user's OWN position",'("close my pool", "close my position", "remove liquidity", "withdraw liquidity", "collect my fees", "claim earnings", "\u0111\xF3ng pool", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "thu ph\xED") \u2014 handled HERE (returns the CoinPool management link).',`NOT in scope: VIEWING a wallet's OWN LP / DeFi position DATA \u2014 "my positions", "my position on Uniswap", "my Uniswap positions",`,'"what I have on Aave", any read-only "my/their positions" query (with or without a protocol named) (\u2192 wallet-agent).',`IMPORTANT distinction: VIEWING / listing one's own positions \u2192 wallet-agent; ACTING on one (close / remove / withdraw / collect fees) \u2192 pool-agent (here), even when phrased as "my pool" / "my position".`,"token metadata or token-level market data (\u2192 token-agent), NFT data (\u2192 nft-agent).",'Key distinction from token-agent: pool-agent answers "which POOLS are biggest / most active" and handles "I want to add LP",','while token-agent answers "what is this TOKEN" and "what is the market doing for this TOKEN".'].join(" "),toolNames:[...po],systemPrompt:ma,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var ha=`You are the Uniswap V3 Subgraph DEX-pool expert.
612
614
 
613
615
  You answer questions about Uniswap V3 liquidity pools using The Graph subgraphs. APR values are enriched from DefiLlama Yields. Concentrated-liquidity price-range data comes from the CoinPool platform.
614
616
 
@@ -698,7 +700,7 @@ YIELD / EARNINGS PROJECTION ("how much would I earn"):
698
700
  FOLLOW-UPS / CONTINUATIONS:
699
701
  - Short replies like "yes", "tell me more", "the first one", "show ranges" refer back to the previous turn. Extract tokens/chains/pool addresses from the prior assistant message and call the appropriate tool. NEVER ask for clarification when history clearly shows what was discussed.
700
702
 
701
- NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,Fr=["subgraph-search-pools","subgraph-trending-pools","subgraph-pool-by-address","subgraph-pool-by-position-id","subgraph-position-detail","subgraph-coinpool-pairs","subgraph-add-pool","pool-fallback-ai"];function Oo(l,e,t){return new j({name:"pool-subgraph-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Answers questions about Uniswap V3 liquidity pools using The Graph subgraphs as the primary source","(APR is enriched from DefiLlama Yields; concentrated-liquidity price ranges come from CoinPool).","Scope: (1) pool search by token symbols on one or more EVM chains, with TVL/APR/fee filters and sort by tvl/volume/apr/fee/liquidity;","(2) trending pools ranked by volume past day on a chain;","(3) pool detail for a specific 0x pool address;","(4) lookup the underlying pool for a Uniswap V3 NFT position id (numeric, e.g. 962961);","(5) full position detail (deposits, withdrawals, collected fees) for a numeric position id;","(6) CoinPool concentrated-liquidity price-range candidates with per-range APR for a token pair;","(7) the add-liquidity / add-pool / create-pair INTENT \u2014 resolves the pool (by address or token pair) and surfaces the add-liquidity website link.","Handles a position ONLY by its NUMERIC NFT id (e.g. 962961) \u2014 NEVER a wallet's own holdings.",'NOT in scope: ANY wallet-scoped LP/DeFi holdings \u2014 "my positions", "my Uniswap positions", "my position on Uniswap",','"what I have on Aave" and every "my/their" positions query (with or without a protocol named) belong to wallet-agent;',"also out of scope: sending/transferring LP NFTs, building/signing the add-liquidity transaction itself,","token metadata (\u2192 token-agent), NFT data (\u2192 nft-agent).","Prefer this subagent over pool-agent when the deployment is configured to use Subgraph data (the two are mutually exclusive at config time)."].join(" "),toolNames:[...Fr],systemPrompt:ma,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var ha=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "approve"). Never reply in text and never ask the user for missing fields (token, NFT, amount, recipient): the tool opens a picker/form that collects them.
703
+ NEVER fabricate pool addresses, token prices, APRs, or position ids. Every value must come from a tool call this turn or the immediately preceding turn.`,Fr=["subgraph-search-pools","subgraph-trending-pools","subgraph-pool-by-address","subgraph-pool-by-position-id","subgraph-position-detail","subgraph-coinpool-pairs","subgraph-add-pool","pool-fallback-ai"];function Oo(l,e,t){return new j({name:"pool-subgraph-agent",domain:"pool",capability:"analyze DEX liquidity pools and concentrated-liquidity positions",description:["Answers questions about Uniswap V3 liquidity pools using The Graph subgraphs as the primary source","(APR is enriched from DefiLlama Yields; concentrated-liquidity price ranges come from CoinPool).","Scope: (1) pool search by token symbols on one or more EVM chains, with TVL/APR/fee filters and sort by tvl/volume/apr/fee/liquidity;","(2) trending pools ranked by volume past day on a chain;","(3) pool detail for a specific 0x pool address;","(4) lookup the underlying pool for a Uniswap V3 NFT position id (numeric, e.g. 962961);","(5) full position detail (deposits, withdrawals, collected fees) for a numeric position id;","(6) CoinPool concentrated-liquidity price-range candidates with per-range APR for a token pair;","(7) the add-liquidity / add-pool / create-pair INTENT \u2014 resolves the pool (by address or token pair) and surfaces the add-liquidity website link.","Handles a position ONLY by its NUMERIC NFT id (e.g. 962961) \u2014 NEVER a wallet's own holdings.",'NOT in scope: ANY wallet-scoped LP/DeFi holdings \u2014 "my positions", "my Uniswap positions", "my position on Uniswap",','"what I have on Aave" and every "my/their" positions query (with or without a protocol named) belong to wallet-agent;',"also out of scope: sending/transferring LP NFTs, building/signing the add-liquidity transaction itself,","token metadata (\u2192 token-agent), NFT data (\u2192 nft-agent).","Prefer this subagent over pool-agent when the deployment is configured to use Subgraph data (the two are mutually exclusive at config time)."].join(" "),toolNames:[...Fr],systemPrompt:ha,cortexFallbackTool:"pool-fallback-ai",llm:l,registry:e,options:t})}var ga=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "approve"). Never reply in text and never ask the user for missing fields (token, NFT, amount, recipient): the tool opens a picker/form that collects them.
702
704
 
703
705
  Tools:
704
706
  - open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
@@ -726,7 +728,7 @@ SEND NFT (open-send-nft-form) specifics:
726
728
 
727
729
  Skip the tool ONLY if: walletAddress missing (ask to connect) \xB7 user explicitly names a chain different from userContext.chain (ask to switch).
728
730
 
729
- After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,mo=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function On(l,e,t){return new j({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","This agent picks the matching open-*-form tool which emits a pre-filled form (or, for buy/swap, a confirm panel) for the FE to render.",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft") via the NFT send form.',"The FE \u2014 not this agent \u2014 builds and submits the tx after the user confirms.","NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...mo],systemPrompt:ha,mustCallTool:!0,llm:l,registry:e,options:t})}var ga=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "swap", "approve"). Never reply in text first and never ask the user for any details (token, NFT, amount, recipient): these actions are NOT performed in chat \u2014 the tool just tells the user they can do it directly in the app.
731
+ After the tool returns: 1 short sentence in the user's language. Don't list missing fields. Don't mention tool names.`,mo=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function On(l,e,t){return new j({name:"wallet-action-agent",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","This agent picks the matching open-*-form tool which emits a pre-filled form (or, for buy/swap, a confirm panel) for the FE to render.",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft") via the NFT send form.',"The FE \u2014 not this agent \u2014 builds and submits the tx after the user confirms.","NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...mo],systemPrompt:ga,mustCallTool:!0,llm:l,registry:e,options:t})}var fa=`Call exactly ONE tool every turn \u2014 ALWAYS, even for a bare verb with no details ("send token", "send nft", "buy", "swap", "approve"). Never reply in text first and never ask the user for any details (token, NFT, amount, recipient): these actions are NOT performed in chat \u2014 the tool just tells the user they can do it directly in the app.
730
732
 
731
733
  Tools (each only points the user to the app \u2014 none performs the action):
732
734
  - open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
@@ -746,22 +748,22 @@ Intent \u2192 tool:
746
748
 
747
749
  These tools take NO arguments and do NOT collect any data \u2014 they only return guidance pointing the user to the app. Just pick the tool matching the intent.
748
750
 
749
- After the tool returns: reply in 1 short sentence in the user's language, telling the user they can do it in the app (include the link if one was given). Don't ask for details. Don't mention tool names, forms, or UI.`,$r=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function Mo(l,e,t){return new j({name:"wallet-action-app",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","In this deployment the action is NOT performed in chat \u2014 this agent picks the matching tool, which only","tells the user they can do the action directly in the app (with a link when configured).",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft").',"NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...$r],systemPrompt:ga,mustCallTool:!0,llm:l,registry:e,options:t})}function ho(l,e,t,n){let r=(d,p)=>{let m=n?.[d];return m===void 0?p:m},o=r("pool-subgraph",!1),s=n?.pool===!0,i=o?s:r("pool",!0),a=r("wallet-action-app",!1),c=a?!1:r("wallet-action",!0),u=[];return r("wallet",!0)&&u.push(Nn(l,e,t)),c&&u.push(On(l,e,t)),a&&u.push(Mo(l,e,t)),r("token",!0)&&u.push(Un(l,e,t)),r("nft",!0)&&u.push(In(l,e,t)),i&&u.push(Dn(l,e,t)),o&&u.push(Oo(l,e,t)),r("ai",!0)&&u.push(Ln(l,e,t)),u}var fa=`You are a response synthesizer. Given the user's question and tool execution results, produce a clear, helpful final answer.
751
+ After the tool returns: reply in 1 short sentence in the user's language, telling the user they can do it in the app (include the link if one was given). Don't ask for details. Don't mention tool names, forms, or UI.`,$r=["open-send-native-form","open-send-token-form","open-send-nft-form","open-buy-token-form","open-swap-token-form","open-approve-token-form"];function Mo(l,e,t){return new j({name:"wallet-action-app",domain:"wallet-action",capability:"help with wallet actions such as sending tokens or NFTs, buying or swapping tokens",description:["User wants to PERFORM an on-chain action (send a token or NFT, buy, swap, approve).","In this deployment the action is NOT performed in chat \u2014 this agent picks the matching tool, which only","tells the user they can do the action directly in the app (with a link when configured).",'Includes sending / transferring an NFT ("send nft", "g\u1EEDi nft", "transfer nft").',"NOT in scope: read-only wallet/token/NFT queries, past NFT transfer history / events (\u2192 wallet-agent), liquidity provisioning."].join(" "),toolNames:[...$r],systemPrompt:fa,mustCallTool:!0,llm:l,registry:e,options:t})}function ho(l,e,t,n){let r=(d,p)=>{let m=n?.[d];return m===void 0?p:m},o=r("pool-subgraph",!1),s=n?.pool===!0,i=o?s:r("pool",!0),a=r("wallet-action-app",!1),c=a?!1:r("wallet-action",!0),u=[];return r("wallet",!0)&&u.push(Nn(l,e,t)),c&&u.push(On(l,e,t)),a&&u.push(Mo(l,e,t)),r("token",!0)&&u.push(Un(l,e,t)),r("nft",!0)&&u.push(In(l,e,t)),i&&u.push(Dn(l,e,t)),o&&u.push(Oo(l,e,t)),r("ai",!0)&&u.push(Ln(l,e,t)),u}var ya=`You are a response synthesizer. Given the user's question and tool execution results, produce a clear, helpful final answer.
750
752
 
751
753
  Rules:
752
754
  - Be concise but complete.
753
- - Present data in a readable format (use lists, tables, or bullet points when appropriate).
755
+ - Reply in plain text. NEVER draw tables or any column/pipe layout. When there are multiple items, use a simple bullet or numbered list; otherwise just write short sentences.
754
756
  - If tool data contains the answer, cite the relevant facts and numbers.
755
757
  - If tools returned errors, explain honestly what happened.
756
758
  - Preserve any markdown links exactly as they appear in the agent reasoning or tool results \u2014 keep clickable links like [label](https://...) verbatim, including the full URL. NEVER strip a link down to plain text, drop its URL, or invent a URL that was not provided.
757
759
  - Respond in the same language as the user's message.
758
760
  - Do NOT mention internal tool names, JSON structures, or technical implementation details.
759
761
  `,fn=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return Vr(t.finalAnswer);let s=t.steps.filter(m=>m.phase==="observe").map((m,g)=>`[Result ${g+1}]: ${m.content}`).join(`
760
- `),i=Re(n),a=Le(i,8),c=(r||"").trim().toLowerCase(),u=c?`IMPORTANT: Reply in BCP-47 language "${c}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${c}".`:`IMPORTANT: The user wrote in the language of this message: "${e}". Reply in that exact language, ignoring any other languages that appear inside tool results.`,d=[{role:"system",content:fa,timestamp:0},...a,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
762
+ `),i=Re(n),a=Le(i,8),c=(r||"").trim().toLowerCase(),u=c?`IMPORTANT: Reply in BCP-47 language "${c}" (the language the user actually typed). Tool results may contain text in other languages \u2014 ignore that and reply ONLY in "${c}".`:`IMPORTANT: The user wrote in the language of this message: "${e}". Reply in that exact language, ignoring any other languages that appear inside tool results.`,d=[{role:"system",content:ya,timestamp:0},...a,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",s?`Tool results:
761
763
  ${s}`:"","",u].filter(Boolean).join(`
762
764
  `),timestamp:Date.now()}],p=await this.llm.chat(d);return Vr(p.text)}};function Vr(l){return l&&l.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
763
765
 
764
- `)}var ya=`You are a CONTEXTUALIZER.
766
+ `)}var ba=`You are a CONTEXTUALIZER.
765
767
 
766
768
  Your ONLY job: read the conversation history + the user's latest message,
767
769
  and produce a SELF-CONTAINED version of that message.
@@ -936,7 +938,7 @@ When the user references "this transaction", "that tx", "the transaction above",
936
938
  - Scan the conversation history for tool results (role: "tool") that contain transaction data.
937
939
  - Extract the EXACT hash value (starts with "0x", 66 chars) from the most recent such result.
938
940
  - Include it verbatim in rewrittenQuery. NEVER invent or modify a hash.
939
- - If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,ba=`You detect the language of a single user message.
941
+ - If no hash is found in history, set rewrittenQuery to the original message verbatim so the subagent knows to fetch it.`,wa=`You detect the language of a single user message.
940
942
 
941
943
  Output STRICT JSON, no prose, no code fences:
942
944
  {"language": "<BCP-47 tag>"}
@@ -968,13 +970,13 @@ Examples:
968
970
 
969
971
  ${a.join(`
970
972
 
971
- `)}`:"",u=Date.now(),d=[{role:"system",content:ya,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
973
+ `)}`:"",u=Date.now(),d=[{role:"system",content:ba,timestamp:0},...i,{role:"user",content:`Latest user message to contextualize:
972
974
  ${e}${c}
973
975
 
974
- Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:ba,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,g]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(p)]),h={};if(m.status==="fulfilled")try{h=this.parseJSON(m.value.text)}catch(b){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let f="";if(g.status==="fulfilled")try{let b=this.parseJSON(g.value.text);typeof b.language=="string"&&(f=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${g.reason}`);let y={isFollowUp:r&&typeof h.isFollowUp=="boolean"?h.isFollowUp:!1,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:r&&typeof h.topicChanged=="boolean"?h.topicChanged:!1,reasoning:typeof h.reasoning=="string"?h.reasoning:"",language:f,mentionedChain:typeof h.mentionedChain=="string"?h.mentionedChain.trim():"",needsWebSearch:h.needsWebSearch===!0,aboutAssistant:h.aboutAssistant===!0};if(this.debug){let b=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
975
- [QueryRewriter] (${b}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 q=require("@langchain/langgraph");function qo(l){return l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Wr="\\s*/\\s*";function Bo(l){return[l.symA.toLowerCase(),l.symB.toLowerCase()].sort().join("|")}function Hr(l){return`(${l.symA}${Wr}${l.symB}|${l.symB}${Wr}${l.symA})`}function wa(l){let e=qo(String(l));return`(?<![\\d.])${Number.isInteger(l)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Gr(l,e,t,n){return`${l.slice(0,e)}[${t}](${n})${l.slice(e+t.length)}`}function ka(l,e){let n=new RegExp(`(?<!\\[)\\b${Hr(e)}\\b`,"i").exec(l);return n?Gr(l,n.index,n[1]??n[0],e.url):null}function va(l,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${Hr(e)}\\b[^\\n\\]]{0,16}?${wa(e.feePercent)}\\s*%`,"i").exec(l);return n?Gr(l,n.index,n[1]??"",e.url):null}var Ta=l=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,s=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof s=="string"&&s&&typeof i=="string"&&i){let a=r.feeTierPercent;e.push({url:o,symA:qo(s),symB:qo(i),feePercent:typeof a=="number"&&Number.isFinite(a)?a:void 0})}};t(l),t(l.pool);for(let n of["pools","candidates"]){let r=l[n];Array.isArray(r)&&r.forEach(t)}return e},Aa=[Ta];function Yr(l,e){if(!l)return l;let t=[];for(let s of e)for(let i of s.toolResults){if(!i.success||!i.data||typeof i.data!="object")continue;let a=i.data;for(let c of Aa)t.push(...c(a))}if(t.length===0)return l;let n=new Map;for(let s of t)n.set(Bo(s),(n.get(Bo(s))??0)+1);let r=l,o=new Set;for(let s of t){if(o.has(s.url))continue;if(r.includes(s.url)){o.add(s.url);continue}let a=(n.get(Bo(s))??0)>1?va(r,s):ka(r,s);a&&(r=a,o.add(s.url))}return r}var me=l=>({reducer:(e,t)=>t,default:l}),Sa=q.Annotation.Root({userMessage:(0,q.Annotation)(),doSuggest:(0,q.Annotation)(me(()=>!0)),overrideLang:(0,q.Annotation)(me(()=>"")),conversationMessages:(0,q.Annotation)(me(()=>[])),lastSubagents:(0,q.Annotation)(me(()=>[])),messageId:(0,q.Annotation)(me(()=>"")),rewrite:(0,q.Annotation)(me(()=>null)),effectiveQuery:(0,q.Annotation)(me(()=>"")),turnLanguage:(0,q.Annotation)(me(()=>"")),kbContext:(0,q.Annotation)(me(()=>"")),decision:(0,q.Annotation)(me(()=>null)),assignment:(0,q.Annotation)(me(()=>null)),assignmentIndex:(0,q.Annotation)(me(()=>0)),subResults:(0,q.Annotation)({reducer:(l,e)=>l.concat(e),default:()=>[]}),response:(0,q.Annotation)(me(()=>null))});function Kr(l){let e=async d=>{l.addUserMessage(d.userMessage),l.needsSummary()&&await l.compactHistory();let p=l.conversationForTurn(),m=l.lastAssistantSubagents(p);return l.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:l.generateMessageId()}},t=async d=>{let p=await l.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),m=d.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},n=async d=>{let p=d.rewrite,m=p.isFollowUp?d.effectiveQuery:d.userMessage,g=await l.searchKB(m),h=l.formatKBContext(g),f=await l.tryAnswerFromKB(d.userMessage,g,h,d.messageId);return f?{kbContext:h,response:{...f,messageId:d.messageId,rewrite:p}}:{kbContext:h}},r=async d=>({decision:await l.route(d.effectiveQuery,d.conversationMessages,l.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await l.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,d.messageId,d.rewrite?.needsWebSearch??!1),m=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:m,rewrite:d.rewrite}}},s=async d=>{let p=await l.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,A)=>k.i-A.i).map(k=>k.result);l.persistToolMessages(p);let m=l.mergeTrace(p),g=await l.synthesise(d.userMessage,m,l.synthesiserHistory(),d.turnLanguage||void 0),h=Yr(g,p),f=p.map(k=>k.subagentName),y=l.collectUiActions(p,d.turnLanguage||null),b=l.collectActionButtons(p,d.turnLanguage||null),w=l.subResultsTriggerNoSuggestions(p);return{response:{...await l.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:f,uiActions:y,actionButtons:b,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!w&&b.length===0}),messageId:d.messageId,trace:m,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},a=async d=>{let p=(d.rewrite?.mentionedChain||String(l.connectedChain()??"")).trim();return{response:{...await l.answerUnsupportedChain(p,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?q.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(h=>h.subagent!=="ai-agent"),g=(d.rewrite?.mentionedChain||l.connectedChain()||"").trim();return m&&g!==""&&!Hn(g)?"unsupportedChain":p.map((h,f)=>new q.Send("subagent",{...d,assignment:h,assignmentIndex:f}))};return new q.StateGraph(Sa).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",i).addNode("unsupportedChain",a).addEdge(q.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",q.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",q.END).addEdge("direct",q.END).addEdge("subagent","synthesize").addEdge("synthesize",q.END).compile()}var jr=require("js-sha3");function fo(){let l=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(l+e).slice(-8)}var Pa="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",xa=`
976
+ Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:wa,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[m,g]=await Promise.allSettled([this.llm.chat(d),this.llm.chat(p)]),h={};if(m.status==="fulfilled")try{h=this.parseJSON(m.value.text)}catch(b){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${m.reason}`);let f="";if(g.status==="fulfilled")try{let b=this.parseJSON(g.value.text);typeof b.language=="string"&&(f=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${g.reason}`);let y={isFollowUp:r&&typeof h.isFollowUp=="boolean"?h.isFollowUp:!1,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:r&&typeof h.topicChanged=="boolean"?h.topicChanged:!1,reasoning:typeof h.reasoning=="string"?h.reasoning:"",language:f,mentionedChain:typeof h.mentionedChain=="string"?h.mentionedChain.trim():"",needsWebSearch:h.needsWebSearch===!0,aboutAssistant:h.aboutAssistant===!0};if(this.debug){let b=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
977
+ [QueryRewriter] (${b}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 q=require("@langchain/langgraph");function qo(l){return l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Wr="\\s*/\\s*";function Bo(l){return[l.symA.toLowerCase(),l.symB.toLowerCase()].sort().join("|")}function Hr(l){return`(${l.symA}${Wr}${l.symB}|${l.symB}${Wr}${l.symA})`}function ka(l){let e=qo(String(l));return`(?<![\\d.])${Number.isInteger(l)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Gr(l,e,t,n){return`${l.slice(0,e)}[${t}](${n})${l.slice(e+t.length)}`}function va(l,e){let n=new RegExp(`(?<!\\[)\\b${Hr(e)}\\b`,"i").exec(l);return n?Gr(l,n.index,n[1]??n[0],e.url):null}function Ta(l,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${Hr(e)}\\b[^\\n\\]]{0,16}?${ka(e.feePercent)}\\s*%`,"i").exec(l);return n?Gr(l,n.index,n[1]??"",e.url):null}var Aa=l=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,s=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof s=="string"&&s&&typeof i=="string"&&i){let a=r.feeTierPercent;e.push({url:o,symA:qo(s),symB:qo(i),feePercent:typeof a=="number"&&Number.isFinite(a)?a:void 0})}};t(l),t(l.pool);for(let n of["pools","candidates"]){let r=l[n];Array.isArray(r)&&r.forEach(t)}return e},Sa=[Aa];function Yr(l,e){if(!l)return l;let t=[];for(let s of e)for(let i of s.toolResults){if(!i.success||!i.data||typeof i.data!="object")continue;let a=i.data;for(let c of Sa)t.push(...c(a))}if(t.length===0)return l;let n=new Map;for(let s of t)n.set(Bo(s),(n.get(Bo(s))??0)+1);let r=l,o=new Set;for(let s of t){if(o.has(s.url))continue;if(r.includes(s.url)){o.add(s.url);continue}let a=(n.get(Bo(s))??0)>1?Ta(r,s):va(r,s);a&&(r=a,o.add(s.url))}return r}var me=l=>({reducer:(e,t)=>t,default:l}),Pa=q.Annotation.Root({userMessage:(0,q.Annotation)(),doSuggest:(0,q.Annotation)(me(()=>!0)),overrideLang:(0,q.Annotation)(me(()=>"")),conversationMessages:(0,q.Annotation)(me(()=>[])),lastSubagents:(0,q.Annotation)(me(()=>[])),messageId:(0,q.Annotation)(me(()=>"")),rewrite:(0,q.Annotation)(me(()=>null)),effectiveQuery:(0,q.Annotation)(me(()=>"")),turnLanguage:(0,q.Annotation)(me(()=>"")),kbContext:(0,q.Annotation)(me(()=>"")),decision:(0,q.Annotation)(me(()=>null)),assignment:(0,q.Annotation)(me(()=>null)),assignmentIndex:(0,q.Annotation)(me(()=>0)),subResults:(0,q.Annotation)({reducer:(l,e)=>l.concat(e),default:()=>[]}),response:(0,q.Annotation)(me(()=>null))});function Kr(l){let e=async d=>{l.addUserMessage(d.userMessage),l.needsSummary()&&await l.compactHistory();let p=l.conversationForTurn(),m=l.lastAssistantSubagents(p);return l.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:l.generateMessageId()}},t=async d=>{let p=await l.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),m=d.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},n=async d=>{let p=d.rewrite,m=p.isFollowUp?d.effectiveQuery:d.userMessage,g=await l.searchKB(m),h=l.formatKBContext(g),f=await l.tryAnswerFromKB(d.userMessage,g,h,d.messageId);return f?{kbContext:h,response:{...f,messageId:d.messageId,rewrite:p}}:{kbContext:h}},r=async d=>({decision:await l.route(d.effectiveQuery,d.conversationMessages,l.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await l.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.doSuggest,d.messageId,d.rewrite?.needsWebSearch??!1),m=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:m,rewrite:d.rewrite}}},s=async d=>{let p=await l.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,A)=>k.i-A.i).map(k=>k.result);l.persistToolMessages(p);let m=l.mergeTrace(p),g=await l.synthesise(d.userMessage,m,l.synthesiserHistory(),d.turnLanguage||void 0),h=Yr(g,p),f=p.map(k=>k.subagentName),y=l.collectUiActions(p,d.turnLanguage||null),b=l.collectActionButtons(p,d.turnLanguage||null),w=l.subResultsTriggerNoSuggestions(p);return{response:{...await l.finaliseAnswer({userMessage:d.userMessage,answer:h,subagents:f,uiActions:y,actionButtons:b,messageId:d.messageId},{generateSuggestions:d.doSuggest&&!w&&b.length===0}),messageId:d.messageId,trace:m,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},a=async d=>{let p=(d.rewrite?.mentionedChain||String(l.connectedChain()??"")).trim();return{response:{...await l.answerUnsupportedChain(p,d.turnLanguage,d.messageId),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?q.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let m=p.some(h=>h.subagent!=="ai-agent"),g=(d.rewrite?.mentionedChain||l.connectedChain()||"").trim();return m&&g!==""&&!Hn(g)?"unsupportedChain":p.map((h,f)=>new q.Send("subagent",{...d,assignment:h,assignmentIndex:f}))};return new q.StateGraph(Pa).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",s).addNode("synthesize",i).addNode("unsupportedChain",a).addEdge(q.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",q.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",q.END).addEdge("direct",q.END).addEdge("subagent","synthesize").addEdge("synthesize",q.END).compile()}var jr=require("js-sha3");function fo(){let l=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(l+e).slice(-8)}var xa="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",_a=`
976
978
 
977
- 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.`,yo=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;currentAbortController=null;historyReady;constructor(e){this.secretKey=e.secretKey,Uo(e.rpcUrls),Vn(e.excludeChains),this.llm=new J(e.llm),this.registry=new tt,this.history=new pn(e.maxHistoryMessages??50),this.summarizer=new mn(this.llm),this.synthesizer=new fn(this.llm),this.systemPrompt=(e.systemPrompt??Pa)+xa,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 hn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Ve({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 d=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new ht(d)),this.registry.register(new lt(d)),this.registry.register(new gt(d)),this.registry.register(new ft(d)),this.registry.register(new yt(d)),this.registry.register(new ct(d)),this.registry.register(new bt(d)),this.registry.register(new wt(d)),this.registry.register(new St(d)),this.registry.register(new vt(d)),this.registry.register(new Tt(d)),this.registry.register(new At(d)),this.registry.register(new kt(d)),this.registry.register(new pt(d)),this.registry.register(new mt(d)),this.registry.register(new ut(d)),this.registry.register(new dt(d))}let r=e.nftLink;this.registry.register(new xt({url:r})),this.registry.register(new _t),this.registry.register(new Ct),this.registry.register(new Et(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,s=o?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(s&&e.uniswap!==!1){let d=typeof e.uniswap=="object"?e.uniswap:void 0,p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new It(d,p)),this.registry.register(new Lt(d)),this.registry.register(new Dt(d)),this.registry.register(new Ot(d)),this.registry.register(new Ht(d));let m=d?{isProduction:d.isProduction}:void 0;this.registry.register(new Vt({baseUrl:d?.baseUrl,pool:m,minProvideUsd:d?.minProvideUsd})),this.registry.register(new Wt({pool:m})),this.registry.register(new Gt),this.registry.register(new Yt)}if((s||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Rt(e.llm)),o&&e.subgraph!==!1){let d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Kt(d)),this.registry.register(new jt(d)),this.registry.register(new zt(d)),this.registry.register(new Qt(d)),this.registry.register(new Xt(d)),this.registry.register(new Jt(d)),this.registry.register(new Zt(d))}let i=e.subagents?.["wallet-action-app"]===!0;if(i?!1:e.subagents?.["wallet-action"]!==!1){let d=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new nn(d)),this.registry.register(new on(d)),this.registry.register(new dn(d,{url:r})),this.registry.register(new rn(d)),this.registry.register(new cn(d,{debug:this.debug})),this.registry.register(new un(d,{debug:this.debug}))}if(i)for(let d of io({appLink:e.walletActionAppLink,nftLink:r}))this.registry.register(d);this.router=new gn(this.llm,{debug:this.debug}),this.rewriter=new go(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,u=ho(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},e.subagents);this.subagents=new Map(u.map(d=>[d.name,d])),this.chatGraph=Kr(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:fo()};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),i=s.data,a=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=fo(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:a,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:a,messageId:c,...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,jr.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(`
979
+ 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.`,yo=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;currentAbortController=null;historyReady;constructor(e){this.secretKey=e.secretKey,Uo(e.rpcUrls),Vn(e.excludeChains),this.llm=new J(e.llm),this.registry=new tt,this.history=new pn(e.maxHistoryMessages??50),this.summarizer=new mn(this.llm),this.synthesizer=new fn(this.llm),this.systemPrompt=(e.systemPrompt??xa)+_a,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 hn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Ve({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 d=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new ht(d)),this.registry.register(new lt(d)),this.registry.register(new gt(d)),this.registry.register(new ft(d)),this.registry.register(new yt(d)),this.registry.register(new ct(d)),this.registry.register(new bt(d)),this.registry.register(new wt(d)),this.registry.register(new St(d)),this.registry.register(new vt(d)),this.registry.register(new Tt(d)),this.registry.register(new At(d)),this.registry.register(new kt(d)),this.registry.register(new pt(d)),this.registry.register(new mt(d)),this.registry.register(new ut(d)),this.registry.register(new dt(d))}let r=e.nftLink;this.registry.register(new xt({url:r})),this.registry.register(new _t),this.registry.register(new Ct),this.registry.register(new Et(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,s=o?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(s&&e.uniswap!==!1){let d=typeof e.uniswap=="object"?e.uniswap:void 0,p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new It(d,p)),this.registry.register(new Lt(d)),this.registry.register(new Dt(d)),this.registry.register(new Ot(d)),this.registry.register(new Ht(d));let m=d?{isProduction:d.isProduction}:void 0;this.registry.register(new Vt({baseUrl:d?.baseUrl,pool:m,minProvideUsd:d?.minProvideUsd})),this.registry.register(new Wt({pool:m})),this.registry.register(new Gt),this.registry.register(new Yt)}if((s||o)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Rt(e.llm)),o&&e.subgraph!==!1){let d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Kt(d)),this.registry.register(new jt(d)),this.registry.register(new zt(d)),this.registry.register(new Qt(d)),this.registry.register(new Xt(d)),this.registry.register(new Jt(d)),this.registry.register(new Zt(d))}let i=e.subagents?.["wallet-action-app"]===!0;if(i?!1:e.subagents?.["wallet-action"]!==!1){let d=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{};this.registry.register(new nn(d)),this.registry.register(new on(d)),this.registry.register(new dn(d,{url:r})),this.registry.register(new rn(d)),this.registry.register(new cn(d,{debug:this.debug})),this.registry.register(new un(d,{debug:this.debug}))}if(i)for(let d of io({appLink:e.walletActionAppLink,nftLink:r}))this.registry.register(d);this.router=new gn(this.llm,{debug:this.debug}),this.rewriter=new go(this.llm,{debug:this.debug});let c=typeof e.subgraph=="object"?e.subgraph:void 0,u=ho(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:c?.linkAddLiquidity},e.subagents);this.subagents=new Map(u.map(d=>[d.name,d])),this.chatGraph=Kr(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:fo()};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),i=s.data,a=s.success?i?.summary??"Done.":`Action failed: ${s.error??"unknown error"}`,c=fo(),u=s.success&&s.ui?[this.stampLanguage(s.ui,null)]:[],d={role:"assistant",content:a,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:a,messageId:c,...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,jr.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(`
978
980
  ${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:i,cleanup:a}=Yo(s,t?.signal);this.llm.setRequestSignal?.(i);let c=this.history.serialise(),u=this.chatGraph.invoke({userMessage:e,doSuggest:n,overrideLang:r},{signal:i});this.inFlightTurn=u;let d;try{d=await u}catch(p){throw et(p)||i.aborted?(this.history.restore(c),new Ye):p}finally{a(),this.llm.setRequestSignal?.(void 0),this.currentAbortController===s&&(this.currentAbortController=null),this.inFlightTurn===u&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-o}ms total`),console.log(`${"\u2500".repeat(60)}
979
981
  `)),d.response??{answer:"",messageId:fo()}}stop(){this.currentAbortController?.abort()}isBusy(){return this.inFlightTurn!==null}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=>Br(e),generateMessageId:()=>fo(),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 i=s.toolResults.map(a=>a.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${i}`)}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 Re(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 i of s.actionButtons){if(!i||typeof i!="object"||typeof i.label!="string"||!i.label.trim()||typeof i.prompt!="string"||!i.prompt.trim())continue;let a=this.capitalizeFirst(i.prompt),c={label:i.label,prompt:a,...t?{language:t}:{}},u=n.get(a);u?c.label.length>u.label.length&&n.set(a,c):(n.set(a,c),r.push(a))}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}]
980
982
  Q: ${n.entry.question}
@@ -1040,12 +1042,12 @@ RULES:
1040
1042
  - Suggestions must be diverse \u2014 do not repeat the same intent in different words.
1041
1043
  - Use the same language as the user.
1042
1044
  - Good example (pool): ["Add liquidity to USDC/WETH 0.05%", "Estimate yield for $1000 here", "Compare with 0.3% fee tier"]
1043
- - Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return i?JSON.parse(i[0]).filter(c=>typeof c=="string"&&c.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=Mr(o,o.length),i=e.length-s.length,a=Re(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...a);let d=await this.summarizer.summarize(u);this.history.compactWith(d,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var _a='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',bo=class{llm;debug;constructor(e={}){this.llm=e.provider??new J({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(t,o),{answer:p}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},r,o);return{answer:p,extraData:{currentSite:n,isPhishing:!1}}}let s=await this.investigate(t,n,o),i=this.buildVerdict(n,s);this.debug&&(console.log("[WebsiteTrustAgent] domain:",n),console.log("[WebsiteTrustAgent] investigation:",s),console.log("[WebsiteTrustAgent] verdict:",i));let{answer:a,reasons:c}=await this.present(n,{isPhishing:i.isPhishing,description:s.description,copiedSite:i.copiedSite,reasons:i.reasons},r,o),u={currentSite:n,isPhishing:i.isPhishing};return i.copiedSite&&(u.copiedSite=i.copiedSite),i.isPhishing&&c.length>0&&(u.reasons=c),{answer:a,extraData:u}}catch(s){throw new Error(`WebsiteTrustAgent.chat failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}buildVerdict(e,t){let n=[t.officialDomain,...t.affiliatedDomains].filter(p=>!!p),r=n.length>0?n.some(p=>this.isSameRegistrableDomain(e,p)):t.exactMatchOfficial,s=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!r&&t.brandIsWellKnown&&(n.length>0||!t.hasOwnLegitPresence),a=!(r||t.hasOwnLegitPresence&&!s)&&t.scamReports.length>0,c=s||a;if(!c)return{isPhishing:!1,reasons:[]};let u=[];if(s){let p=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;p&&u.push(p),t.impersonationEvidence.length>0?u.push(...t.impersonationEvidence):p||u.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}a&&u.push(...t.scamReports);let d=s?t.officialDomain??t.brand:void 0;return{isPhishing:c,copiedSite:d,reasons:this.dedupe(u)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
1045
+ - Bad example: ["What is a pool?", "How do pools work?", "Tell me more"] (generic, no action, no specifics)`,timestamp:0}])).text.match(/\[[\s\S]*\]/);return i?JSON.parse(i[0]).filter(c=>typeof c=="string"&&c.length>0).slice(0,3):[]}catch{return[]}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}getLastSuggestions(){let e=this.getDisplayHistory();for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="assistant")return n.suggestedPrompts??[]}return[]}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),s=Mr(o,o.length),i=e.length-s.length,a=Re(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...a);let d=await this.summarizer.summarize(u);this.history.compactWith(d,s)}persistToolMessages(e){for(let t of e)t.toolMessages.length>0&&(this.history.addMany(t.toolMessages),this.history.add({role:"assistant",content:t.finalAnswer,_intermediate:!0,timestamp:Date.now()}),this.debug&&console.log(`[AgentCore] stored ${t.toolMessages.length} tool message(s) + finalAnswer from ${t.subagentName}`))}getLLMProvider(){return this.llm}getToolRegistry(){return this.registry}};var Ca='You are a precise web-security analyst with live web search. You analyze the EXACT domain string given, character-for-character \u2014 you NEVER mentally autocorrect a typo or assume a similar real domain is "meant". You are aware that search engines silently "did you mean"-correct misspelled domains and return pages for a DIFFERENT real domain; such results never prove the domain under test is legitimate. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.',bo=class{llm;debug;constructor(e={}){this.llm=e.provider??new J({temperature:.8,...e.llm}),this.debug=e.debug??!1}async chat(e){let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let d=await this.describeOfficial(t,o),{answer:p}=await this.present(n,{isPhishing:!1,description:d,reasons:[]},r,o);return{answer:p,extraData:{currentSite:t,isPhishing:!1}}}let s=await this.investigate(t,n,o),i=this.buildVerdict(n,s);this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",s),console.log("[WebsiteTrustKeyringAgent] verdict:",i));let{answer:a,reasons:c}=await this.present(n,{isPhishing:i.isPhishing,description:s.description,copiedSite:i.copiedSite,reasons:i.reasons},r,o),u={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(u.copiedSite=i.copiedSite),i.isPhishing&&c.length>0&&(u.reasons=c),{answer:a,extraData:u}}catch(s){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}buildVerdict(e,t){let n=[t.officialDomain,...t.affiliatedDomains].filter(p=>!!p),r=n.length>0?n.some(p=>this.isSameRegistrableDomain(e,p)):t.exactMatchOfficial,s=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!r&&t.brandIsWellKnown&&(n.length>0||!t.hasOwnLegitPresence),a=!(r||t.hasOwnLegitPresence&&!s)&&t.scamReports.length>0,c=s||a;if(!c)return{isPhishing:!1,reasons:[]};let u=[];if(s){let p=t.officialDomain?this.describeLookAlike(e,t.officialDomain):void 0;p&&u.push(p),t.impersonationEvidence.length>0?u.push(...t.impersonationEvidence):p||u.push(t.officialDomain?`This address (${e}) is not the official ${t.brand??"brand"} domain \u2014 the real one is ${t.officialDomain}; the look-alike is easy to miss at a glance.`:`This domain (${e}) imitates ${t.brand??"a known brand"} but is not its official site and has no legitimate presence of its own.`)}a&&u.push(...t.scamReports);let d=s?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:c,copiedSite:d,reasons:this.dedupe(u)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
1044
1046
  URL: ${e}
1045
1047
 
1046
1048
  Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
1047
1049
  A. Describe what this site is or claims to be for the user: the product/service it offers, what it does, and who appears to operate it. This is the main information the user wants about the site \u2014 be concrete.
1048
- B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
1050
+ B. Does the domain carry or RESEMBLE a recognizable brand / product / service \u2014 exactly, or via a typo, an extra/missing/swapped letter, a homoglyph, an ADDED WORD or hyphen (e.g. brand+"rpc"/"wallet"/"app"/"pro"/"support"/"finance"), or the brand placed on a different TLD or in a subdomain/path? Treat "the official name with extra text bolted on" as RESEMBLING the brand \u2014 set resemblesBrand=true. If it references ANY identifiable brand/product, you MUST search for and return that brand's OFFICIAL canonical domain in \`officialDomain\` (do not leave it null when the brand is identifiable). Also return that brand's full official site URL \u2014 including the real scheme (https:// or http://) you confirm via search \u2014 in \`officialUrl\`. A "did you mean" correction to the REAL domain helps you learn the official domain but does NOT make the domain under test legitimate.
1049
1051
  A name within 1-2 letters of a well-known domain (missing / doubled / swapped letter, e.g. "opensee" for "opensea", "binanse" for "binance") is a TYPOSQUAT: set resemblesBrand=true, name the intended brand, and return its official domain. Identifying the brand it MIMICS is REQUIRED; it never makes the typo legitimate.
1050
1052
  B2. Is that brand a WELL-KNOWN, established project \u2014 prominent in crypto, blockchain, NFT, DeFi or Web3 (or otherwise a major, widely-recognized brand)? A scammer only bothers faking a name people trust, so set brandIsWellKnown=true only for a genuinely recognized project; for an obscure or no-name brand set false.
1051
1053
  C. Compare the FULL registrable domain + TLD of the domain under test against that official domain \u2014 they match ONLY if identical in BOTH the name AND the TLD. Reusing the brand name with anything added or changed is NOT a match and is NOT the official site.
@@ -1062,12 +1064,13 @@ Return ONLY this JSON:
1062
1064
  "brand": string | null, // the brand it resembles, or null
1063
1065
  "brandIsWellKnown": boolean, // is that brand a well-known crypto/web3 (or major) project worth faking?
1064
1066
  "officialDomain": string | null, // that brand's real official domain (e.g. "relay.link"), or null if unknown
1067
+ "officialUrl": string | null, // that brand's official site URL WITH scheme (e.g. "https://relay.link"), or null if unknown
1065
1068
  "exactMatchOfficial": boolean, // is the domain under test EXACTLY the official domain (name AND TLD)?
1066
1069
  "affiliatedDomains": string[], // ALL verified official/authorized domains of the brand (canonical + regional); [] if unsure
1067
1070
  "hasOwnLegitPresence": boolean, // does THIS exact domain have its own legitimate presence?
1068
1071
  "impersonationEvidence": string[], // >=3 specific points if impersonating; [] otherwise
1069
1072
  "scamReports": string[] // SOURCED findings (each with a markdown-link source) accusing THIS exact domain; [] if none/unsourced
1070
- }`,o=await this.askJson(r,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,t){let n=`This website is officially verified as legitimate: ${e}
1073
+ }`,o=await this.askJson(r,{signal:n,maxRetries:3});return{description:this.cleanStr(o?.description)??"",resemblesBrand:o?.resemblesBrand===!0,brand:this.cleanStr(o?.brand),brandIsWellKnown:o?.brandIsWellKnown===!0,officialDomain:this.cleanStr(o?.officialDomain),officialUrl:this.cleanStr(o?.officialUrl),exactMatchOfficial:o?.exactMatchOfficial===!0,affiliatedDomains:this.cleanStrArray(o?.affiliatedDomains),hasOwnLegitPresence:o?.hasOwnLegitPresence===!0,impersonationEvidence:this.cleanStrArray(o?.impersonationEvidence),scamReports:this.cleanStrArray(o?.scamReports)}}async describeOfficial(e,t){let n=`This website is officially verified as legitimate: ${e}
1071
1074
  Using web search, describe what this website / platform is and what it does (its purpose, who runs it).
1072
1075
 
1073
1076
  Return ONLY this JSON: { "description": string } // 1-3 concise sentences`,r=await this.askJson(n,{signal:t,maxRetries:3});return this.cleanStr(r?.description)??""}async present(e,t,n,r){let o=this.languageLabel(n),i=`Here is a COMPLETED web-security assessment (facts only \u2014 do not re-investigate):
@@ -1085,4 +1088,4 @@ Write the user-facing result for a NON-TECHNICAL user:
1085
1088
 
1086
1089
  LANGUAGE (MANDATORY): write "answer" AND every "reasons" item ENTIRELY in ${o}. The facts above are in English ONLY as source material \u2014 your output prose MUST be in ${o}, not English (unless ${o} itself is English). Only domain names, URLs, markdown links and brand names stay verbatim.
1087
1090
 
1088
- Return ONLY this JSON: { "answer": string, "reasons": string[] }`,a=await this.askJson(i,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2}),c=this.cleanStr(a?.answer)??(t.description||e),u=this.cleanStrArray(a?.reasons);return{answer:c,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5)}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=_a,maxRetries:s=2}=t,i=Date.now(),a=[{role:"system",content:o,timestamp:i},{role:"user",content:e,timestamp:i}],c=await this.llm.chat(a,void 0,{googleSearch:r,maxRetries:s,signal:n}),u=this.parseJson(c.text?.trim()??"");return this.debug&&!u&&console.log("[WebsiteTrustAgent] unparseable step reply:",(c.text??"").slice(0,200)),u}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`;return new URL(t).hostname||e}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}registrableName(e){let t=this.toHost(e).split(".");return this.alnum(t.length>=2?t[t.length-2]:t[0])}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let a=1;a<=r;a++){let c=e[s-1]===t[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.registrableName(e);return[t?this.toHost(t).split(".")[0]:"",n??""].map(i=>this.alnum(i)).filter(i=>i.length>=4).some(i=>r.includes(i)||this.isNearMiss(o,i))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),u=r.slice(0,s),d=n.slice(o+1),p=r.slice(s+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.alnum(r.split(".")[0]),a=this.registrableName(n);if(this.isNearMiss(a,i)){let c=this.editDistance(a,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${a}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.cleanStr(r);o&&n.push(o)}return n}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var Ca=l=>{let e=JSON.parse(l),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function zr(l,e){let t=l.entries??(l.json?Ca(l.json):[]);return t.length===0?{count:0}:new Ve(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletActionAppTool,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustAgent,ZERO_ADDRESS,buildRangePresets,buildUniswapPoolUrl,clampTick,configureSupportedChains,createAiAgent,createDefaultSubagents,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletActionAppTools,createWalletAgent,ethCallAt,ethCallByChain,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,normalizePriceRangeToPool,priceToTick,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
1091
+ Return ONLY this JSON: { "answer": string, "reasons": string[] }`,a=await this.askJson(i,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2}),c=this.cleanStr(a?.answer)??(t.description||e),u=this.cleanStrArray(a?.reasons);return{answer:c,reasons:u.length>0?u.slice(0,5):t.reasons.slice(0,5)}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=Ca,maxRetries:s=2}=t,i=Date.now(),a=[{role:"system",content:o,timestamp:i},{role:"user",content:e,timestamp:i}],c=await this.llm.chat(a,void 0,{googleSearch:r,maxRetries:s,signal:n}),u=this.parseJson(c.text?.trim()??"");return this.debug&&!u&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(c.text??"").slice(0,200)),u}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`;return new URL(t).hostname||e}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}registrableName(e){let t=this.toHost(e).split(".");return this.alnum(t.length>=2?t[t.length-2]:t[0])}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(s,i)=>i);for(let s=1;s<=n;s++){let i=[s];for(let a=1;a<=r;a++){let c=e[s-1]===t[a-1]?0:1;i[a]=Math.min(o[a]+1,i[a-1]+1,o[a-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.registrableName(e);return[t?this.toHost(t).split(".")[0]:"",n??""].map(i=>this.alnum(i)).filter(i=>i.length>=4).some(i=>r.includes(i)||this.isNearMiss(o,i))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),s=r.lastIndexOf(".");if(o>0&&s>0){let c=n.slice(0,o),u=r.slice(0,s),d=n.slice(o+1),p=r.slice(s+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.alnum(r.split(".")[0]),a=this.registrableName(n);if(this.isNearMiss(a,i)){let c=this.editDistance(a,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${a}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.cleanStr(r);o&&n.push(o)}return n}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var Ea=l=>{let e=JSON.parse(l),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function zr(l,e){let t=l.entries??(l.json?Ea(l.json):[]);return t.length===0?{count:0}:new Ve(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseNftMessageTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,ManageLiquidityRedirectTool,MoralisService,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,OpenAddLiquidityFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,SwapTokenTool,Synthesizer,TOKEN_AGENT_TOOL_NAMES,TRANSFER_TOPIC,TRENDING_DEFAULT_BY_HEX_CHAIN,TokenAnalyticsTool,TokenHoldersTool,TokenInfoTool,TokenScoreTool,ToolRegistry,TopGainersTool,TopPoolsTool,TransactionByHashTool,TrendingTokensTool,UNISWAP_CHAIN_SLUG,UpstashKnowledgeBase,WALLET_ACTION_AGENT_TOOL_NAMES,WALLET_AGENT_TOOL_NAMES,WalletActionAppTool,WalletApprovalsTool,WalletDefiPositionsTool,WalletDefiProtocolPositionsTool,WalletDefiSummaryTool,WalletHistoryTool,WalletNFTsTool,WalletNftTransfersTool,WalletPnlSummaryTool,WalletPnlTool,WalletTokenBalancesTool,WalletTokenTransfersTool,WebsiteTrustKeyringAgent,ZERO_ADDRESS,buildRangePresets,buildUniswapPoolUrl,clampTick,configureSupportedChains,createAiAgent,createDefaultSubagents,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletActionAppTools,createWalletAgent,ethCallAt,ethCallByChain,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,normalizePriceRangeToPool,priceToTick,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});